Practical Computer Graphics
Practical Computer Graphics
Semester-5
Practical on :
Computer Graphics
BCA-501/M1T
Submitted By
Student Name :- - - - - - - - - - - - - -
Enrollment No. :- - - - - - - - - - - - - -
radian = math.radians(angle)
x_offset = a * math.cos(radian)
y_offset = b * math.sin(radian)
pen.goto(x + x_offset, y + y_offset)
# Drawing shapes
draw_line(-100, 0, 100, 0) # Line
draw_circle(0, 0, 50) # Circle
draw_arc(200, 0, 50, 0, 180) # Arc
draw_ellipse(-200, 0, 80, 40) # Ellipse
draw_rectangle(-50, -150, 100, 50) # Rectangle
# Finish
pen.hideturtle()
screen.mainloop()
Explanation:
1. Line: Uses two points to draw a straight line.
2. Circle: Drawn using the circle method of the turtle module.
3. Arc: Partial circle using the circle method with an extent angle.
4. Ellipse: Approximates the ellipse using parametric equations and a loop.
5. Rectangle: Drawn with four sides using the forward and left methods.
Run the program in a Python environment to see the graphics drawn on the screen.
rad = np.radians(angle)
rotation_matrix = np.array([
[np.cos(rad), -np.sin(rad), 0],
[np.sin(rad), np.cos(rad), 0],
[0, 0, 1]
])
points_homogeneous = np.hstack((points, np.ones((points.shape[0], 1))))
transformed_points = points_homogeneous @ rotation_matrix.T
return transformed_points[:, :2]
[0.5, 1]
])
# Perform transformations
transformed_points = composite_transform(original_points, tx, ty, angle, sx, sy)
Explanation:
1. Translation:
o Moves the shape by (tx, ty) using a translation matrix: T=[10tx01ty001]T = \begin{bmatrix} 1
& 0 & tx \\ 0 & 1 & ty \\ 0 & 0 & 1 \end{bmatrix}T=100010txty1
2. Rotation:
o Rotates the shape by an angle (in degrees) using a rotation matrix:
R=[cos(θ)−sin(θ)0sin(θ)cos(θ)0001]R = \begin{bmatrix} \cos(\theta) & -\sin(\theta) &
0 \\ \sin(\theta) & \cos(\theta) & 0 \\ 0 & 0 & 1 \end{bmatrix}R=cos(θ)sin(θ)0−sin(θ)cos(θ)0
001
3. Scaling:
o Scales the shape by factors (sx, sy) using a scaling matrix: S=[sx000sy0001]S =
\begin{bmatrix} sx & 0 & 0 \\ 0 & sy & 0 \\ 0 & 0 & 1 \end{bmatrix}S=sx000sy0001
4. Composite Transformation:
o Combines Translation → Rotation → Scaling in sequence.
Output:
• A matplotlib plot displaying:
o The original shape (blue).
o The transformed shape (red).
You can modify the shape and transformation parameters (tx, ty, angle, sx, sy) to see different results.
3. Write a program to draw a Circle using midpoint implementation Method.
Here is a Python program to draw a circle using the Midpoint Circle Algorithm. This algorithm efficiently
calculates the points of a circle in a rasterized grid, making it ideal for graphical implementations.
plot_circle_points(x_center, y_center, x, y)
while x < y:
x += 1
if d < 0:
d += 2 * x + 1
else:
y -= 1
d += 2 * (x - y) + 1
plot_circle_points(x_center, y_center, x, y)
Explanation:
1. Midpoint Circle Algorithm:
o The circle is drawn using its symmetry; only one-eighth of the circle is computed, and other
points are mirrored.
o The decision parameter ddd determines whether the next pixel will be directly horizontal or
diagonal.
2. Plot Points:
o Eight points symmetric around the circle's center are calculated and plotted for each step.
3. Decision Parameter Update:
o Initial d=1−rd = 1 - rd=1−r.
o If d<0d < 0d<0, the next pixel is directly horizontal (d=d+2x+1d = d + 2x + 1d=d+2x+1).
o Otherwise, the next pixel is diagonal (d=d+2(x−y)+1d = d + 2(x - y) + 1d=d+2(x−y)+1).
Output:
• The program uses Matplotlib to display a rasterized circle on a grid.
• You can adjust the x_center, y_center, and radius variables to modify the circle's properties.
Parameters:
control_points (list of tuples): Control points [(x1, y1), (x2, y2), ...].
n_points (int): Number of points on the curve to compute.
Returns:
np.array: Points on the Bezier curve.
"""
def de_casteljau(points, t):
"""Recursive implementation of De Casteljau's algorithm."""
if len(points) == 1:
return points[0]
new_points = [
(1 - t) * np.array(points[i]) + t * np.array(points[i + 1])
for i in range(len(points) - 1)
]
return de_casteljau(new_points, t)
Explanation:
1. Control Points:
o The Bezier curve is defined by a series of control points (x1,y1),(x2,y2),…,(xn,yn)(x_1, y_1),
(x_2, y_2), \ldots, (x_n, y_n)(x1,y1),(x2,y2),…,(xn,yn).
o In the example, [(0,0),(2,4),(4,2),(6,0)][(0, 0), (2, 4), (4, 2), (6, 0)][(0,0),(2,4),(4,2),(6,0)] are
used.
2. De Casteljau's Algorithm:
o Recursively computes intermediate points based on the parameter t∈[0,1]t \in [0, 1]t∈[0,1].
o The recursion stops when only one point remains, which lies on the curve.
3. Bezier Curve Points:
o The algorithm computes nnn points along the curve, where nnn is defined by n_points.
4. Plot:
o The control polygon (dashed lines connecting control points) is drawn for reference.
o The Bezier curve is drawn as a smooth blue curve.
Output:
• A smooth Bezier curve is plotted along with its control polygon and control points.
• You can modify the control points in the control_points list to change the shape of the curve.
•
Parameters:
point (tuple): The point (x, y) to rotate.
center (tuple): The center of rotation (cx, cy).
angle (float): The angle in degrees to rotate.
Returns:
tuple: The rotated point (x', y').
"""
rad = np.radians(angle) # Convert angle to radians
cos_theta, sin_theta = np.cos(rad), np.sin(rad)
Parameters:
vertices (list of tuples): List of four vertices [(x1, y1), (x2, y2), ...].
angle (float): The angle in degrees to rotate.
Returns:
list of tuples: The rotated vertices.
"""
# Calculate the midpoint of the rectangle
center = np.mean(vertices, axis=0)
# Original rectangle
# Rotated rectangle
rotated_vertices_np = np.array(rotated_vertices + [rotated_vertices[0]]) # Close the rectangle
plt.plot(rotated_vertices_np[:, 0], rotated_vertices_np[:, 1], 'r--', label="Rotated Rectangle")
# Midpoint
center = np.mean(rectangle_vertices, axis=0)
plt.plot(center[0], center[1], 'go', label="Midpoint")
# Configure plot
plt.title(f"Rectangle Rotation (Angle = {angle}°)")
plt.xlabel("X")
plt.ylabel("Y")
plt.legend()
plt.grid(True)
plt.axis('equal')
plt.show()
Explanation:
1. Rotation Matrix:
o The rotation formula for a point (x,y)(x, y)(x,y) about a center (cx,cy)(cx, cy)(cx,cy) is:
x′=(x−cx)⋅cos(θ)−(y−cy)⋅sin(θ)+cxx' = (x - cx) \cdot \cos(\theta) - (y - cy) \cdot \sin(\theta)
+ cxx′=(x−cx)⋅cos(θ)−(y−cy)⋅sin(θ)+cx y′=(x−cx)⋅sin(θ)+(y−cy)⋅cos(θ)+cyy' = (x - cx) \cdot
\sin(\theta) + (y - cy) \cdot \cos(\theta) + cyy′=(x−cx)⋅sin(θ)+(y−cy)⋅cos(θ)+cy
2. Steps:
o Calculate the midpoint (center of the rectangle).
o Rotate each vertex around the midpoint using the rotation matrix.
3. Vertices Representation:
o Rectangles are represented as a list of four points: [(x1, y1), (x2, y2), ...].
4. Visualization:
Output:
• A plot showing the original rectangle and its rotated version.
• You can modify the rectangle vertices and rotation angle to test with different inputs
The Liang-Barsky algorithm is an efficient method for line clipping against a rectangular clipping window.
Below is a Python implementation of the Liang-Barsky method to clip a line against a rectangular clipping
window.
Parameters:
x_min, y_min: Bottom-left corner of the clipping window.
x_max, y_max: Top-right corner of the clipping window.
x1, y1, x2, y2: Endpoints of the line.
Returns:
(x1', y1', x2', y2'): The clipped line endpoints if visible, otherwise None.
"""
dx = x2 - x1
dy = y2 - y1
for i in range(4):
if p[i] == 0: # Parallel line
if q[i] < 0:
return None # Line is outside the clipping window
else:
t = q[i] / p[i]
if p[i] < 0: # Entering segment
u1 = max(u1, t)
else: # Exiting segment
u2 = min(u2, t)
if u1 > u2:
return None # Line is completely outside
# Perform clipping
clipped_line = liang_barsky(x_min, y_min, x_max, y_max, x1, y1, x2, y2)
plt.legend()
plt.grid(True)
plt.axis('equal')
plt.show()
Explanation:
1. Parameters:
o The clipping rectangle is defined by (x_min, y_min) and (x_max, y_max).
o The line is defined by its endpoints (x1, y1) and (x2, y2).
2. Algorithm:
o The algorithm calculates parametric values (u1 and u2) that determine the portions of the
line inside the clipping window.
o If u1 > u2, the line is completely outside the clipping window.
3. Edge Cases:
o If the line is parallel to a clipping boundary and outside, it is rejected.
o If the line lies entirely within the clipping window, it is returned unchanged.
4. Visualization:
o The clipping window is plotted as a rectangle.
o The original line is plotted as a dashed blue line.
o The clipped line is plotted as a solid red line.
Output:
• A graphical representation of the original line, the clipping window, and the clipped line (if it is
partially or fully inside the window).
•
Parameters:
points (np.array): A 3D array of shape (n, 3), where each row is (x, y, z).
d (float): The distance of the viewer (projection plane) from the origin.
Returns:
np.array: A 2D array of shape (n, 2) containing the projected points.
"""
projected_points = []
for x, y, z in points:
if z != 0: # Avoid division by zero
xp = (d * x) / z
yp = (d * y) / z
projected_points.append((xp, yp))
else:
projected_points.append((np.inf, np.inf)) # Undefined points
return np.array(projected_points)
(4, 5), (5, 6), (6, 7), (7, 4), # Back face
(0, 4), (1, 5), (2, 6), (3, 7) # Connecting edges
]
# Configure plot
plt.title("3D to 2D Perspective Projection")
plt.xlabel("X (projected)")
plt.ylabel("Y (projected)")
plt.axhline(0, color='black', linewidth=0.5)
plt.axvline(0, color='black', linewidth=0.5)
plt.grid(True)
plt.legend()
plt.axis('equal')
plt.show()
Explanation:
1. Perspective Projection Formula:
o For a 3D point (x,y,z)(x, y, z)(x,y,z), the projection onto a 2D plane at distance ddd from the
origin is given by: x′=d⋅xz,y′=d⋅yzx' = \frac{d \cdot x}{z}, \quad y' = \frac{d \cdot y}{z}x′=zd⋅x
,y′=zd⋅y
o zzz represents the depth of the point in the scene.
2. 3D Object:
o A cube is used as an example, represented by its 8 vertices.
3. Edges:
o The edges of the cube are defined to connect its vertices for visualization.
4. Projection Plane:
o The plane is at a distance ddd from the origin. Larger ddd values reduce the perspective
effect, making the projection closer to orthographic.
5. Visualization:
o The program uses matplotlib to plot the 2D projection of the cube.
o Red points represent the projected vertices, and blue lines connect them to visualize the
cube structure.
Output:
• A 2D plot showing the perspective projection of the cube.
• You can adjust the d value, cube dimensions, or add other 3D shapes to see different perspective
effects.
•
Here is a Python program to implement Parallel Projection in 3D. In parallel projection, the lines projecting
from the object to the viewing plane are parallel, preserving the relative proportions of the object.
Parameters:
points (np.array): A 3D array of shape (n, 3), where each row is (x, y, z).
projection_plane (str): The plane onto which to project ('xy', 'xz', or 'yz').
Returns:
np.array: A 2D array of shape (n, 2) containing the projected points.
"""
if projection_plane == 'xy':
return points[:, :2] # Keep x, y; discard z
elif projection_plane == 'xz':
return points[:, [0, 2]] # Keep x, z; discard y
elif projection_plane == 'yz':
return points[:, [1, 2]] # Keep y, z; discard x
else:
raise ValueError("Invalid projection plane. Choose 'xy', 'xz', or 'yz'.")
Explanation:
1. Parallel Projection:
o Projects a 3D point (x,y,z)(x, y, z)(x,y,z) onto a specified 2D plane by dropping one coordinate:
▪ For XY plane: Retain x,yx, yx,y and discard zzz.
▪ For XZ plane: Retain x,zx, zx,z and discard yyy.
▪ For YZ plane: Retain y,zy, zy,z and discard xxx.
2. 3D Object:
o The program uses a cube represented by its 8 vertices.
3. Edges:
o The cube's edges are defined to connect its vertices, making the structure visible.
4. Projection Planes:
o The user can choose the projection plane ('xy', 'xz', or 'yz') to view the projection from
different perspectives.
5. Visualization:
o The program uses matplotlib to plot the projected 2D view of the cube.
o Red points represent the projected vertices, and blue lines connect them to visualize the
structure.
Output:
• A 2D plot of the 3D cube projected onto the specified plane.
• You can modify the projection_plane variable to switch between XY, XZ, and YZ projections.
•
Here’s a Python program to implement a Digital Clock using the tkinter library. The program continuously
updates the current time and displays it in a graphical window.
def update_time():
"""Update the time displayed on the clock."""
current_time = strftime('%H:%M:%S %p') # Format: Hour:Minute:Second AM/PM
label.config(text=current_time)
label.after(1000, update_time) # Update every second
Explanation:
1. strftime:
o The strftime('%H:%M:%S %p') function formats the current time:
▪ %H for 24-hour format hours.
▪ %M for minutes.
▪ %S for seconds.
▪ %p for AM/PM.
2. label.after(1000, update_time):
o Calls the update_time function every 1000 milliseconds (1 second) to refresh the clock.
3. GUI with tkinter:
o The main window (window) displays the time using a Label widget.
o The label's font, background (bg), and foreground (fg) colors are set for a digital clock
appearance.
4. Customizations:
o Change font, bg, and fg to modify the clock’s appearance.
o Adjust geometry("400x200") for window size.
Output:
• A graphical window with a digital clock showing the current time in the format HH:MM:SS AM/PM.
• The time updates in real-time every second.
•
10. Write a Program to draw animation using increasing circles filled with different colors and patterns
Here’s a Python program that creates an animation of increasing circles filled with different colors and
patterns. This is achieved using the matplotlib library's animation feature.
circles = []
def update(frame):
"""Update function for animation frames."""
global circles
# Clear existing circles
for circle in circles:
circle.remove()
Explanation:
1. Figure Setup:
o A matplotlib figure and axes are created with equal aspect ratio to ensure circles appear
correctly.
2. Animation:
o The FuncAnimation class from matplotlib.animation is used to animate the circle growth.
o update function recalculates and redraws circles for each frame.
3. Circle Attributes:
o Radius increases over time using (frame + i * 10) % 50 + 5.
o Colors and patterns alternate from predefined lists using modulo indexing.
4. Hatching Patterns:
o Patterns like /, |, +, etc., add a visual effect to the circle fills.
5. Customizations:
o Adjust the colors and patterns list for variety.
o Change interval (in milliseconds) to control animation speed.
o Modify the frames range for animation duration.
Output:
• Animated circles expand from the center, filled with alternating colors and patterns.
• The radii reset after reaching a maximum value, creating a looping effect.