The projection matrix has left each vertex in clip space, with four coordinates \((x, y, z, w)\). Between that abstract point and a lit pixel on the screen there are still four decisions to make: which part of each triangle falls inside the field of view (clipping), which pixel coordinates correspond to each vertex (viewport), which pixels the triangle covers (rasterization) and, when several triangles compete for the same pixel, which of them is seen (visibility). In this lesson we settle all four. Along the way, the barycentric coordinates that in Module 3 only served to say "inside or outside" will become the tool for spreading any piece of data over the interior of a triangle, and the depth that the projection preserved so carefully will finally be put to use.
The code assumes that the functions from the previous lessons (to_homogeneous, from_homogeneous, project_point, perspective_matrix, follow_camera, octahedron_mesh, transform_mesh...) and the scene data are already defined: ship, lamp, ship_world, hull_model, initial_view, view and projection (FOV 60°, aspect 16/9, planes at 1 and 100 m).
The remaining stages
| Stage | Input | Output | Question it answers |
|---|---|---|---|
| Clipping | Triangles in clip space | Triangles inside the view volume | Which part can be seen? |
| Perspective divide | \((x, y, z, w)\) | NDC | (we already know it) |
| Viewport | NDC | Screen coordinates | Which pixel does each vertex fall on? |
| Backface culling | Triangle on screen | Drawn or not | Is it facing away from us? |
| Rasterization | Triangle on screen | Covered pixels, with interpolated attributes | Which pixels does it occupy? |
| Depth test | Candidate pixel | Pixel written or discarded | Is there something in front? |
Each section builds one of these pieces separately. Assembling them into a complete renderer will be the task of the lesson "Computer Graphics", in Module 6.
Clipping in homogeneous coordinates
The condition
A point in NDC is visible if its three coordinates lie between \(-1\) and \(1\). Since NDC is obtained by dividing by \(w\), the condition \(-1 \le x/w \le 1\) is equivalent, when \(w > 0\), to \(-w \le x \le w\). The view volume in clip space is therefore:
\[ -w \le x \le w \qquad -w \le y \le w \qquad -w \le z \le w \]
These are the same six inequalities from which we extracted the frustum planes in the previous lesson. There, whole objects were tested in order to cull them; here they are applied exactly, vertex by vertex.
Why before dividing
It would be tempting to divide first and clip afterward against the cube, but there are two reasons not to:
- Points with \(w = 0\). They lie on the plane that passes through the eye, perpendicular to the line of sight. The division is a division by zero.
- Points with \(w < 0\). They are behind the camera. On dividing by a negative number, \(x\) and \(y\) change sign: the point appears mirrored, in front of the camera, in a place where it does not belong.
Let us see it with the follow camera, located behind the ship. The lighthouse beam goes from the lamp, \((0, 12, 0)\), to the point on the hull where it hits, \(\left(\tfrac{26}{3}, \tfrac{10}{3}, \tfrac{13}{3}\right)\). The lamp is behind the camera's back.
import numpy as np
np.set_printoptions(suppress=True) # no scientific notation when printing arrays
def inside_clip_volume(c):
"""True if the homogeneous point c = (x, y, z, w) satisfies -w <= x, y, z <= w."""
x, y, z, w = c
return bool(-w <= x <= w and -w <= y <= w and -w <= z <= w)
follow = follow_camera(ship_world, [0.0, 2.0, -8.0], [0.0, 0.0, 4.0])
vp = projection @ follow
hit = np.array([26.0, 10.0, 13.0]) / 3.0
c_lamp = vp @ to_homogeneous(lamp)
c_hit = vp @ to_homogeneous(hit)
print(np.round(c_lamp, 3) + 0.0, inside_clip_volume(c_lamp))
print(np.round(c_hit, 3), inside_clip_volume(c_hit))
print(np.round(c_lamp[:3] / c_lamp[3], 3) + 0.0) # what you must NOT doThe lamp has \(w = -3.124\): it is 3.12 m behind the camera. If we simply divide, we get \(y_{\text{ndc}} = -3.6\): the lamp, which is above the camera, would appear below the image, and the line of the beam would be drawn toward the wrong side. The hit point, with \(w = 7.7\), is inside.
What is done with each triangle
| Situation | Action |
|---|---|
| All three vertices inside | Accepted whole |
| All three vertices outside the same plane | Discarded whole |
| Remaining cases | It is clipped: the polygon that remains inside is computed |
Clipping a triangle against one plane produces a polygon with three or four sides; against all six, with up to nine, which is then triangulated again. The general procedure (the Sutherland–Hodgman algorithm) goes through the planes one by one and applies to each edge the operation we see next. In practice, the truly mandatory plane is the near one, because of the problems with \(w \le 0\); whatever sticks out at the sides can be left for rasterization to remove, since it never paints outside the screen.
Clipping an edge against the near plane
The near plane is \(z = -w\), that is, \(w + z = 0\). The quantity
\[ d = w + z \]
plays the role of "signed distance" in clip space: positive on the visible side and negative on the other. If the endpoints of an edge, \(\mathbf{c}_0\) and \(\mathbf{c}_1\), have \(d_0\) and \(d_1\) of opposite signs, the edge crosses the plane. Since \(d\) varies linearly along the edge \(\mathbf{c}(t) = \mathbf{c}_0 + t,(\mathbf{c}_1 - \mathbf{c}_0)\), the crossing is where \(d_0 + t,(d_1 - d_0) = 0\):
\[ t = \frac{d_0}{d_0 - d_1} \]
It is the line-plane intersection from "Equations of Planes and Lines", carried over to four dimensions. The same \(t\) is also used to interpolate the attributes of the new vertex (color, normal...).
def clip_edge_near(c0, c1):
"""Point (in clip space) where the edge c0-c1 crosses the near plane, w + z = 0, and its t."""
d0, d1 = c0[3] + c0[2], c1[3] + c1[2] # > 0: visible side
t = d0 / (d0 - d1)
return c0 + t * (c1 - c0), t
crossing, t = clip_edge_near(c_lamp, c_hit)
print(round(c_lamp[3] + c_lamp[2], 3), round(c_hit[3] + c_hit[2], 3), round(t, 4))
print(np.round(crossing, 3), np.round(lamp + t * (hit - lamp), 3))The beam crosses the near plane 38% of the way along, at the world point \((3.3, 8.7, 1.65)\). The new vertex has \(w = 1\) (it is at a depth of 1 m, that of the near plane) and \(z = -w\). The visible stretch of the beam goes from that point to the hit point. Its \(y = 6.8\) still exceeds \(w\): it still sticks out above the image, but that no longer causes any numerical problem.
The viewport transformation
After the division, NDC coordinates run from \(-1\) to \(1\). The viewport transformation takes them to the window's rectangle of pixels, width × height. There are two details of convention:
- The Y axis is flipped. In NDC, \(y\) grows upward; in almost all image systems, row 0 is the top one and rows grow downward.
- Pixels are cells, not points. The pixel in column \(i\) and row \(j\) occupies the square \([i, i+1] \times [j, j+1]\), and its center is at \((i + 0.5,\ j + 0.5)\).
The transformation is, once again, a translation plus a scaling per axis: add 1 to go from \([-1, 1]\) to \([0, 2]\) and multiply by half the size.
\[ x_p = (x_{\text{ndc}} + 1),\frac{\text{width}}{2} \qquad y_p = (1 - y_{\text{ndc}}),\frac{\text{height}}{2} \qquad z_p = \frac{z_{\text{ndc}} + 1}{2} \]
Depth is taken to the interval \([0, 1]\): 0 at the near plane and 1 at the far plane. As a matrix:
\[ M_{\text{viewport}} = \begin{pmatrix} \tfrac{\text{width}}{2} & 0 & 0 & \tfrac{\text{width}}{2} \\ 0 & -\tfrac{\text{height}}{2} & 0 & \tfrac{\text{height}}{2} \\ 0 & 0 & \tfrac{1}{2} & \tfrac{1}{2} \\ 0 & 0 & 0 & 1 \end{pmatrix} \]
The negative sign in the second row is the flip of the Y axis.
Example. With the initial view, the ship was at NDC \((0.5567, -0.2474, 0.8759)\). In a 1280 × 720 window:
\[ x_p = 1.5567 \cdot 640 = 996.3 \qquad y_p = 1.2474 \cdot 360 = 449.1 \qquad z_p = \frac{1.8759}{2} = 0.938 \]
The center of the ship falls on the pixel in column 996 and row 449: to the right of and somewhat below the center of the image, \((640, 360)\).
def ndc_to_screen(ndc, width, height):
"""From NDC to the screen: x, y in pixels (origin at the top left) and z in [0, 1]."""
x, y, z = ndc
return np.array([(x + 1.0) * 0.5 * width, (1.0 - y) * 0.5 * height, (z + 1.0) * 0.5])
def viewport_matrix(width, height):
"""4x4 matrix equivalent to ndc_to_screen."""
return np.array([[width / 2.0, 0.0, 0.0, width / 2.0],
[0.0, -height / 2.0, 0.0, height / 2.0],
[0.0, 0.0, 0.5, 0.5],
[0.0, 0.0, 0.0, 1.0]])
ndc = project_point(projection @ initial_view, ship)
print(np.round(ndc_to_screen(ndc, 1280, 720), 2))
print(ndc_to_screen([-1.0, 1.0, -1.0], 1280, 720), ndc_to_screen([1.0, -1.0, 1.0], 1280, 720))
full = viewport_matrix(1280, 720) @ projection @ initial_view
print(np.round(from_homogeneous(full @ to_homogeneous(ship)), 2))The NDC corner \((-1, 1)\)—top left—goes to pixel \((0, 0)\), and \((1, -1)\) goes to \((1280, 720)\). The last line shows that the viewport matrix can be chained with the others: a single matrix goes from the world to the screen, with the division by \(w\) at the end (the viewport is affine and does not alter \(w\)).
Backface culling
In "Representing 3D Objects" we established that the front face of a triangle is the one from which its vertices are seen running counterclockwise. Now that we have the vertices on screen we can check which winding each triangle shows. If it appears clockwise, we are seeing it from behind and, in a closed object, it will be hidden: there is no need to rasterize it.
The winding of a 2D triangle is given by the sign of its signed area, which is a 2×2 determinant like those of Module 1:
\[ 2,\text{Area} = (x_1 - x_0)(y_2 - y_0) - (y_1 - y_0)(x_2 - x_0) \]
With mathematical axes (Y up), the area is positive if the path is counterclockwise. But on screen the Y axis points down, and that flip is a reflection that changes the sign of every area. The rule in pixel coordinates therefore comes out the other way around:
| Signed area (Y down) | Winding that is seen | Face |
|---|---|---|
| Negative | Counterclockwise | Front: it is drawn |
| Positive | Clockwise | Back: it is culled |
| Zero | The three vertices collinear | Edge-on: it covers no pixel |
This criterion is equivalent to the geometric one we would use in 3D: a face is a front face if its normal points toward the camera, \(\hat{\mathbf{n}} \cdot (\mathbf{e} - \mathbf{p}) > 0\), with \(\mathbf{p}\) a point of the face and \(\mathbf{e}\) the eye. The on-screen version is cheaper and automatically takes perspective into account.
The code is in the next section, because the formula for the area is, precisely, the edge function.
The edge function
The edge function of an oriented edge \(A \to B\) evaluated at a point \(P\) is:
\[ E_{AB}(P) = (B_x - A_x)(P_y - A_y) - (B_y - A_y)(P_x - A_x) \]
It is the \(z\) component of the cross product \((B - A) \times (P - A)\), or twice the signed area of the triangle \(ABP\). It has three readings, all of them useful:
- Its sign says which side of the line \(AB\) the point \(P\) is on; it equals 0 on the line.
- Its value is proportional to the distance from \(P\) to the line.
- It is linear in \(P\): on advancing one pixel horizontally it changes by a fixed amount, \(-(B_y - A_y)\); vertically, by \(B_x - A_x\). A real rasterizer takes advantage of this to evaluate it with a single addition per pixel.
def edge_function(a, b, p):
"""Twice the signed area of the triangle a, b, p (uses only x and y)."""
return (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])
def is_back_face(p0, p1, p2):
"""True if the triangle, in screen coordinates (Y down), does not show its front face."""
return edge_function(p0, p1, p2) >= 0.0
hull = transform_mesh(hull_model, octahedron_mesh())
mvp = projection @ view # the camera looks at the ship
screen = np.array([ndc_to_screen(project_point(mvp, v), 1280, 720)
for v in hull["vertices"]])
print(np.round(screen, 2))
for k, face in enumerate(hull["faces"]):
p0, p1, p2 = screen[face]
print(k, face, round(edge_function(p0, p1, p2), 1) + 0.0, is_back_face(p0, p1, p2))[[655.32 344.91 0.96] [614.87 384.75 0.93] [640. 321.62 0.95] [640. 397.8 0.95] [717.33 361.19 0.95] [564.98 358.85 0.95]] 0 [0 2 4] 1194.3 True 1 [4 2 1] -5875.8 False 2 [1 2 5] -3800.3 False 3 [5 2 0] 2317.2 True 4 [4 3 0] 3528.9 True 5 [1 3 4] -1929.2 False 6 [5 3 1] 0.0 True 7 [0 3 5] 4564.8 True
Here the hull's vertices are taken to the world and from there to the screen (view already starts from the world). The ship occupies about 150 × 76 pixels around the center, \((640, 360)\). Of its eight faces, only three are front faces, and all three have vertex 1 as a corner, the left wing, which is the one pointing toward the camera. Four are back faces. And face 6 gives zero area: by a coincidence of the scene, the camera is exactly in the plane of that face and sees it edge-on, as a line. That is why is_back_face uses >=: a triangle with no area does not need to be drawn either.
Culling has removed five out of eight triangles with one subtraction and two products each. In any closed mesh, it saves on average half of the rasterization work.
Rasterizing a triangle
Rasterizing means deciding which pixels a triangle covers. The standard criterion is: a pixel belongs to the triangle if its center falls inside.
The inside/outside test
A point is inside a triangle if it lies on the same side of its three edges, traversed in order. It is the idea we used in 3D in "Intersections: Rays, Spheres, Triangles and Boxes", now in 2D and with edge functions:
\[ E_{12}(P),\quad E_{20}(P),\quad E_{01}(P) \qquad \text{all three with the same sign as the total area } E_{01}(P_2) \]
The bounding box
There is no need to test every pixel on the screen: only those in the triangle's on-screen bounding box (its 2D AABB), clipped to the limits of the image. For face 1 of the hull, whose vertices have \(x\) between 614.9 and 717.3 and \(y\) between 321.6 and 384.8, that is about 104 × 64 candidate pixels instead of the 921,600 of the screen.
The pixels on the boundary
When the center of a pixel falls exactly on an edge shared by two triangles, which one does it belong to? If it is assigned to both, it is painted twice (a problem with transparency); if to neither, a hole is left. Graphics cards apply the top-left rule: the pixel belongs to the triangle for which that edge is a left edge or a horizontal top edge. That way each pixel of a mesh is painted exactly once. Our teaching rasterizer settles for accepting the points on the boundary (\(\ge 0\)).
Barycentric coordinates for interpolating attributes
The three values of the inside/outside test are not thrown away. Divided by the total area they give three numbers that add up to 1:
\[ \alpha = \frac{E_{12}(P)}{E_{01}(P_2)} \qquad \beta = \frac{E_{20}(P)}{E_{01}(P_2)} \qquad \gamma = \frac{E_{01}(P)}{E_{01}(P_2)} \]
They are the barycentric coordinates of \(P\) with respect to the triangle on screen: \(P = \alpha P_0 + \beta P_1 + \gamma P_2\). Each weight corresponds to the vertex opposite its edge, and measures what fraction of the total area is taken up by the subtriangle that \(P\) forms with it. Because we divide by the area, the weights come out positive inside the triangle whatever its winding.
In Module 3 we only looked at their signs. Now we use them for what they do best: interpolating. Any attribute \(q\) known at the three vertices is extended to the interior with the same blend:
\[ q(P) = \alpha,q_0 + \beta,q_1 + \gamma,q_2 \]
- At a vertex, its weight is 1 and the others are 0: we recover that vertex's value.
- Along an edge, the weight of the opposite vertex is 0: the interpolation is the
lerpbetween two endpoints from Module 1. - At the centroid, the three weights are \(1/3\): the average.
This is how the color, the normal, the texture coordinates and the depth of each pixel are obtained from the data of three vertices.
def interpolate_attribute(weights, values):
"""Barycentric blend of an attribute known at the three vertices."""
alpha, beta, gamma = weights
v0, v1, v2 = (np.asarray(v, dtype=float) for v in values)
return alpha * v0 + beta * v1 + gamma * v2Perspective-correct interpolation
The formula above has a catch. The barycentric coordinates were computed on screen, after the projection, and perspective does not preserve proportions: the midpoint of a segment on screen is not the midpoint of the segment in 3D.
Example. A straight 8 m walkway recedes from the camera: it starts at a depth of 2 m and ends at 10 m. We assign it an attribute \(u\) that equals 0 at the start and 1 at the end (it could be a texture coordinate). What is the value of \(u\) at the pixel that is halfway along in the image? Linear interpolation says 0.5, that is, the point 6 m away. But the far half of the walkway looks much smaller than the near half, so the midpoint of the image has to be considerably closer to the start.
The key is knowing which quantities do vary linearly on screen. The projection divides by \(w\), and it turns out that for any attribute \(q\) that varies linearly over the triangle in 3D:
- \(q / w\) varies linearly on screen;
- so does \(1 / w\) (it is the particular case \(q = 1\)).
Hence the recipe: we interpolate \(q/w\) and \(1/w\) with the screen barycentric coordinates, and divide one by the other.
\[ q(P) = \frac{\alpha,\dfrac{q_0}{w_0} + \beta,\dfrac{q_1}{w_1} + \gamma,\dfrac{q_2}{w_2}}{\alpha,\dfrac{1}{w_0} + \beta,\dfrac{1}{w_1} + \gamma,\dfrac{1}{w_2}} \]
Here \(w_i\) is the clip-space \(w\) coordinate of each vertex: its depth, which the perspective matrix saved for this moment.
On the walkway, with weights \((0.5, 0.5)\), \(w_0 = 2\) and \(w_1 = 10\):
\[ u = \frac{0.5 \cdot \tfrac{0}{2} + 0.5 \cdot \tfrac{1}{10}}{0.5 \cdot \tfrac{1}{2} + 0.5 \cdot \tfrac{1}{10}} = \frac{0.05}{0.30} = \frac{1}{6} \approx 0.167 \]
The center of the walkway's image corresponds to the point only \(8/6 = 1.33\) m from its start (at a depth of 3.33 m), not to the one 4 m along.
def interpolate_with_perspective(weights, values, w):
"""Perspective-correct interpolation: screen weights and clip-space w of each vertex."""
corrected = np.asarray(weights, dtype=float) / np.asarray(w, dtype=float)
corrected = corrected / corrected.sum()
return interpolate_attribute(corrected, values)
print(interpolate_attribute((0.5, 0.5, 0.0), [0.0, 1.0, 0.0]),
round(float(interpolate_with_perspective((0.5, 0.5, 0.0), [0.0, 1.0, 0.0], [2.0, 10.0, 1.0])), 4))
# Check in 3D: the walkway goes from (0, -1, -2) to (0, -1, -10) in view space
start, end = np.array([0.0, -1.0, -2.0]), np.array([0.0, -1.0, -10.0])
screen_midpoint = (project_point(projection, start) + project_point(projection, end)) / 2.0
print(np.round(screen_midpoint, 4) + 0.0)
print(np.round(project_point(projection, start + (end - start) / 6.0), 4) + 0.0)
print(np.round(project_point(projection, start + (end - start) / 2.0), 4) + 0.0)The function divides each weight by the \(w\) of its vertex and normalizes again so that they add up to 1: it is the formula above written as a set of "corrected" weights. The check confirms the calculation: the point that projects onto the center of the walkway is the one with \(u = 1/6\); the one with \(u = 1/2\) falls considerably higher up in the image.
Two consequences:
- The attributes that describe the surface (color, normals, texture coordinates) must be interpolated with correction. The error of not doing so is very visible with textures; we will see it with a checkerboard in "Texture Coordinates and Mapping".
- The NDC or screen depth \(z\) is the lucky exception: it already has the form "something divided by \(w\)", so it is interpolated linearly on screen, without correction. It is one of the reasons why the perspective matrix was designed the way it was.
When the three vertices are at the same depth (a triangle seen face-on, or any orthographic projection), the two interpolations coincide.
The visibility problem: the painter's algorithm
When two triangles cover the same pixel, the nearer one must be seen. The first solution that occurs to anyone is that of an oil painter: paint what is far away first and what is near on top. The painter's algorithm sorts the triangles from farthest to nearest and draws them in that order.
It is simple, but it has serious flaws:
- Triangles that pass through each other. If two triangles intersect, each one is in front over part of its area: no order is correct.
- Cyclic overlaps. Three triangles can cover one another in a circle (A over B, B over C and C over A), like the flaps of a cardboard box.
- Ambiguous depth. A triangle does not have "a" depth. Sorting by the centroid fails with large or elongated triangles.
- Cost. All the triangles have to be re-sorted every time the camera moves.
The z-buffer
The z-buffer (or depth buffer) solves visibility without sorting anything, pixel by pixel. Alongside the image, a second array of the same size is kept that stores, for each pixel, the depth of the nearest thing painted so far.
- The z-buffer is initialized to the maximum value (1.0, the far plane).
- For each pixel of each triangle, its depth \(z\) is interpolated.
- If \(z\) is less than the stored value, the pixel is closer than what was there: its color is written and the z-buffer is updated.
- Otherwise, it is discarded: there is something in front.
| Painter's algorithm | Z-buffer | |
|---|---|---|
| Unit of decision | The whole triangle | Each pixel |
| Needs sorting | Yes, every frame | No: any order gives the same result |
| Intersecting triangles | Fails | Correct |
| Extra memory | None | One number per pixel |
| Limitation | The cases above | Finite precision; does not solve transparency |
The painter's algorithm survives in one case: semi-transparent objects, which must be blended with what lies behind them and are drawn at the end, sorted from far to near.
With all the pieces, the rasterizer fits in one function. The shader parameter is a function that receives the pixel's barycentric coordinates and returns what has to be written in it: a character, a color... It leaves open the decision of what to paint, which will be the subject of the last two lessons of the module.
def rasterize_triangle(p0, p1, p2, canvas, z_buffer, shader):
"""Paints on `canvas` the pixels of the triangle that pass the depth test.
p0, p1, p2: vertices on screen (x, y in pixels; z = depth).
shader(alpha, beta, gamma): returns the value that is written in the pixel.
Returns the number of pixels written.
"""
height, width = z_buffer.shape
area = edge_function(p0, p1, p2)
if area == 0.0:
return 0 # degenerate triangle
x_min = max(int(np.floor(min(p0[0], p1[0], p2[0]))), 0)
x_max = min(int(np.ceil(max(p0[0], p1[0], p2[0]))), width - 1)
y_min = max(int(np.floor(min(p0[1], p1[1], p2[1]))), 0)
y_max = min(int(np.ceil(max(p0[1], p1[1], p2[1]))), height - 1)
written = 0
for j in range(y_min, y_max + 1):
for i in range(x_min, x_max + 1):
center = (i + 0.5, j + 0.5)
alpha = edge_function(p1, p2, center) / area
beta = edge_function(p2, p0, center) / area
gamma = edge_function(p0, p1, center) / area
if alpha < 0.0 or beta < 0.0 or gamma < 0.0:
continue # the pixel center lies outside
z = alpha * p0[2] + beta * p1[2] + gamma * p2[2]
if z < z_buffer[j, i]: # closer than what is already painted
z_buffer[j, i] = z
canvas[j, i] = shader(alpha, beta, gamma)
written += 1
return writtenThe four max/min calls at the beginning compute the bounding box and clip it to the image: that is what allows us not to have clipped the triangle against the sides of the frustum.
A mini-rasterizer in ASCII
Let us try it with a "screen" of 40 × 16 characters. Two triangular solar panels of the lighthouse cross each other in an X: panel A (#) has its left edge close to the camera (\(z_{\text{ndc}} = 0.2\)) and its right tip far away (0.8); panel B (o), the other way around. We give the vertices directly in NDC.
WIDTH, HEIGHT = 40, 16
def new_canvas():
return np.full((HEIGHT, WIDTH), "."), np.full((HEIGHT, WIDTH), 1.0)
def show(canvas):
print("\n".join("".join(row) for row in canvas))
panel_a = [ndc_to_screen(p, WIDTH, HEIGHT)
for p in ([-0.9, -0.8, 0.2], [0.9, 0.0, 0.8], [-0.9, 0.8, 0.2])]
panel_b = [ndc_to_screen(p, WIDTH, HEIGHT)
for p in ([0.9, -0.8, 0.2], [0.9, 0.8, 0.2], [-0.9, 0.0, 0.8])]
print(is_back_face(*panel_a), is_back_face(*panel_b))
canvas, z_buffer = new_canvas()
print(rasterize_triangle(*panel_a, canvas, z_buffer, lambda a, b, g: "#"),
rasterize_triangle(*panel_b, canvas, z_buffer, lambda a, b, g: "o"))
show(canvas)
print(np.round(z_buffer[8, ::5], 2))False False 230 172 ........................................ ........................................ ..#####..........................ooooo.. ..###########..............ooooooooooo.. ..################....oooooooooooooooo.. ..##################oooooooooooooooooo.. ..##################oooooooooooooooooo.. ..##################oooooooooooooooooo.. ..##################oooooooooooooooooo.. ..##################oooooooooooooooooo.. ..##################oooooooooooooooooo.. ..################....oooooooooooooooo.. ..###########..............ooooooooooo.. ..#####..........................ooooo.. ........................................ ........................................ [1. 0.63 0.67 0.71 0.75 0.7 0.66 0.62]
Both panels are front-facing. A is painted whole (230 pixels); then B only manages to write 172: in the left half of the overlap, A had already left smaller depths. The result is the correct one: the panels intersect along the central column, and each one is seen in the half where it is in front. The last line shows one row of the z-buffer: the depth grows from the left edge to the center (panel A receding) and decreases again toward the right (panel B approaching). The initial 1.0 is untouched background.
Let us compare with the painter's algorithm, which we simulate by clearing the z-buffer between one triangle and the next so that the second one covers everything:
canvas, z_buffer = new_canvas()
rasterize_triangle(*panel_a, canvas, z_buffer, lambda a, b, g: "#")
z_buffer[:] = 1.0 # no memory of depth
rasterize_triangle(*panel_b, canvas, z_buffer, lambda a, b, g: "o")
show(canvas[5:11])
# With a z-buffer, the drawing order does not matter
canvas_ab, z_ab = new_canvas()
rasterize_triangle(*panel_a, canvas_ab, z_ab, lambda a, b, g: "#")
rasterize_triangle(*panel_b, canvas_ab, z_ab, lambda a, b, g: "o")
canvas_ba, z_ba = new_canvas()
rasterize_triangle(*panel_b, canvas_ba, z_ba, lambda a, b, g: "o")
rasterize_triangle(*panel_a, canvas_ba, z_ba, lambda a, b, g: "#")
print(np.array_equal(canvas_ab, canvas_ba))..##############oooooooooooooooooooooo.. ..########oooooooooooooooooooooooooooo.. ..###ooooooooooooooooooooooooooooooooo.. ..###ooooooooooooooooooooooooooooooooo.. ..########oooooooooooooooooooooooooooo.. ..##############oooooooooooooooooooooo.. True
Panel B invades the left-hand area, where it is actually behind. Painting them in the opposite order would not fix it either: the error would move to the right. This is the case of triangles that pass through each other, which the painter cannot solve. With a z-buffer, on the other hand, the two orders produce exactly the same image (True).
Finally, let us use the shader to interpolate an attribute. We give the vertices of panel A a brightness of 0, 1 and 0.3 and translate it into a ramp of characters:
ramp = ":-=+*#%@"
brightness = (0.0, 1.0, 0.3)
canvas, z_buffer = new_canvas()
rasterize_triangle(*panel_a, canvas, z_buffer,
lambda a, b, g: ramp[int(round(7 * (a * brightness[0] + b * brightness[1] + g * brightness[2])))])
show(canvas[2:14])..===++................................. ..====++++++*........................... ..=====++++++*****...................... ..======++++++******####................ ..-======++++++******######%%%.......... ..--======++++++******######%%%%%%@..... ..---======++++++******######%%%%%%..... ..----======++++++******######.......... ..-----======++++++*****................ ..------======++++...................... ..:------====........................... ..::---.................................
The brightness increases smoothly from the bottom left corner (:) toward the right tip (@), in straight bands: the lines of equal value of an interpolated attribute are always parallel straight lines. This gradient is the basis of the smooth shading we will study in "Lighting and Shading".
Z-fighting
The z-buffer has a weak point: it stores depth with a finite number of bits. If two surfaces are so close together that their depths are rounded to the same value, or to values that alternate from one pixel to the next, the engine cannot decide which one goes in front and the image shows a flicker of sawtooth stripes: z-fighting.
This is where we pay the bill for the nonlinearity we studied in "Projections and Views". Two panels 60 m from the camera, 2 cm apart:
for near in (1.0, 0.01):
p = perspective_matrix(np.radians(60.0), 16.0 / 9.0, near, 100.0)
za = (project_point(p, [0.0, 0.0, -60.0])[2] + 1.0) / 2.0
zb = (project_point(p, [0.0, 0.0, -60.02])[2] + 1.0) / 2.0
print(near, int(za * (2 ** 24 - 1)), int(zb * (2 ** 24 - 1)),
int(za * (2 ** 16 - 1)), int(zb * (2 ** 16 - 1)))Each pair is the integer values that would be stored for the two panels, with 24 and with 16 bits.
- With the near plane at 1 m and 24 bits, they are 94 steps apart: no problem.
- With the near plane at 1 cm, only one step: any rounding error in the interpolation mixes them up.
- With 16 bits and the plane at 1 cm, they receive the same value: guaranteed z-fighting.
Remedies, in order of preference:
- Push the near plane as far away as possible and do not exaggerate the far one.
- Do not model overlapping coplanar surfaces (a poster stuck on a wall): separate them or use a small depth offset (depth bias).
- Use higher-precision buffers, or the reversed z technique with floating-point numbers, which distributes the precision much better.
Common Mistakes and Tips
- Dividing by \(w\) before clipping against the near plane. Vertices with \(w \le 0\) produce divisions by zero or mirrored geometry. First clip, then divide.
- Forgetting the flip of the Y axis. Without it, the image comes out upside down. And with it, the front-face criterion changes sign: do not mix the NDC convention with the screen one.
- Sampling at the corner of the pixel instead of the center. The triangle appears shifted by half a pixel and leaves gaps or overlaps with its neighbors. The center is \((i + 0.5,\ j + 0.5)\).
- Initializing the z-buffer to 0. Nothing is less than 0: no pixel would be painted. It is initialized to the farthest value, 1.0, and this has to be done every frame.
- Applying backface culling to open or single-layer meshes (a sail, a leaf, a panel). They disappear when seen from behind. For those objects it is turned off.
- Interpolating texture coordinates or colors linearly on screen. In perspective this is wrong: \(q/w\) and \(1/w\) have to be interpolated.
- Using the wrong \(w\). Perspective correction uses the clip-space \(w\) of each vertex (before dividing), not a 1.
- Tip. To debug a rasterizer, do what we have done here: a tiny screen and characters. Sign errors, half-pixel errors and depth errors are visible to the naked eye.
Exercises
Exercise 1. In an 800 × 600 window:
a) Which screen coordinates does the NDC point \((0.5, -0.25, 0)\) go to? b) Invert the transformation: which NDC coordinates \((x, y)\) correspond to the center of the pixel in column 200 and row 150?
Exercise 2. A triangle has, on screen, the vertices \(P_0 = (2, 1)\), \(P_1 = (10, 3)\) and \(P_2 = (4, 9)\), with depths 0.2, 0.6 and 0.4.
a) Compute its signed area. Is it a front face or a back face? b) Compute the barycentric coordinates of the center of pixel \((5, 4)\) and decide whether it is inside. If it is, interpolate its depth. c) Do the same with pixel \((9, 7)\).
Exercise 3. a) With the initial view, a cable joins the satellite located at \((0, 5, 26)\), behind the camera, to the ship, \((8, 3, 6)\). Use clip_edge_near to find the world point where the cable starts to be visible and check that it is on the near plane. b) Add to the ASCII scene of the two panels a third triangle, with NDC vertices \((-0.5, -0.9, 0)\), \((0.5, -0.9, 0)\) and \((0, 0.4, 0.9)\), with the character +. How many pixels does it manage to write? Interpret the image.
Solutions
Solution 1.
a) \(x_p = (0.5 + 1) \cdot 400 = 600\); \(y_p = (1 + 0.25) \cdot 300 = 375\); \(z_p = 0.5\).
b) The center of the pixel is \((200.5, 150.5)\). Solving: \(x_{\text{ndc}} = \dfrac{2 \cdot 200.5}{800} - 1 = -0.4988\); \(y_{\text{ndc}} = 1 - \dfrac{2 \cdot 150.5}{600} = 0.4983\). It is in the upper left quadrant, as befits a pixel with a small row and column.
Solution 2.
a) \(E_{01}(P_2) = (10 - 2)(9 - 1) - (3 - 1)(4 - 2) = 64 - 4 = 60\). It is positive and, with the Y axis pointing down, that means a clockwise path: it is a back face. (The barycentric coordinates can be computed all the same.)
b) Center \((5.5, 4.5)\):
- \(E_{12} = (4 - 10)(4.5 - 3) - (9 - 3)(5.5 - 10) = -9 + 27 = 18\)
- \(E_{20} = (2 - 4)(4.5 - 9) - (1 - 9)(5.5 - 4) = 9 + 12 = 21\)
- \(E_{01} = (10 - 2)(4.5 - 1) - (3 - 1)(5.5 - 2) = 28 - 7 = 21\)
They add up to 60 ✓. Weights: \(\alpha = 0.30\), \(\beta = 0.35\), \(\gamma = 0.35\). All positive: inside. Depth: \(0.30 \cdot 0.2 + 0.35 \cdot 0.6 + 0.35 \cdot 0.4 = 0.06 + 0.21 + 0.14 = 0.41\).
c) Center \((9.5, 7.5)\): \(E_{12} = (-6)(4.5) - (6)(-0.5) = -27 + 3 = -24\); \(E_{20} = (-2)(-1.5) - (-8)(5.5) = 3 + 44 = 47\); \(E_{01} = 8 \cdot 6.5 - 2 \cdot 7.5 = 52 - 15 = 37\). They add up to 60 ✓. \(\alpha = -0.4\): outside; the pixel has crossed the edge \(P_1 P_2\), the one opposite \(P_0\).
Solution 3.
print(ndc_to_screen([0.5, -0.25, 0.0], 800, 600))
t0, t1, t2 = (2.0, 1.0, 0.2), (10.0, 3.0, 0.6), (4.0, 9.0, 0.4)
area = edge_function(t0, t1, t2)
for center in ((5.5, 4.5), (9.5, 7.5)):
weights = np.array([edge_function(t1, t2, center), edge_function(t2, t0, center),
edge_function(t0, t1, center)]) / area
print(area, np.round(weights, 4), round(float(weights @ [0.2, 0.6, 0.4]), 4))
satellite = np.array([0.0, 5.0, 26.0])
initial_vp = projection @ initial_view
crossing, t = clip_edge_near(initial_vp @ to_homogeneous(satellite), initial_vp @ to_homogeneous(ship))
print(round(t, 4), np.round(satellite + t * (ship - satellite), 4), np.round(crossing, 4))
canvas, z_buffer = new_canvas()
rasterize_triangle(*panel_a, canvas, z_buffer, lambda a, b, g: "#")
rasterize_triangle(*panel_b, canvas, z_buffer, lambda a, b, g: "o")
panel_c = [ndc_to_screen(p, WIDTH, HEIGHT) for p in ([-0.5, -0.9, 0.0], [0.5, -0.9, 0.0], [0.0, 0.4, 0.9])]
print(rasterize_triangle(*panel_c, canvas, z_buffer, lambda a, b, g: "+"))
show(canvas[8:15])[600. 375. 0.5] 60.0 [0.3 0.35 0.35] 0.41 60.0 [-0.4 0.7833 0.6167] 0.6367 0.35 [ 2.8 4.3 19. ] [ 2.728 -1.2124 -1. 1. ] 70 ..##################oooooooooooooooooo.. ..##################oooooooooooooooooo.. ..#############++++++++++ooooooooooooo.. ..############++++++++++++oooooooooooo.. ..###########++++++++++++++ooooooooooo.. ..#####.....++++++++++++++++.....ooooo.. ...........++++++++++++++++++...........
a) The cable starts to be seen 35% of the way along, at \((2.8, 4.3, 19)\): its \(z = 19\) is exactly the near plane of the camera, located at \(z = 20\). In clip space, the point has \(w = 1\) and \(z = -w\).
b) The third triangle writes 70 pixels. Its base is very close to the camera (\(z_{\text{ndc}} = 0\)) and that is why it covers the two panels in the lower part; its tip recedes to 0.9 and, above a certain height, it ends up behind the panels and can no longer be seen. The z-buffer has resolved a triangle that passes through two others without sorting anything.
Conclusion
Between clip space and the screen there are four steps. Clipping removes, in homogeneous coordinates and before dividing, whatever lies outside \(-w \le x, y, z \le w\), and it is essential against the near plane. The viewport transformation converts NDC into pixels, flipping the Y axis. The sign of the on-screen area gives away the back faces, which are culled. Rasterization goes through the triangle's bounding box and decides with three edge functions whether the center of each pixel falls inside; those same functions, divided by the area, are the barycentric coordinates with which any attribute is interpolated, correcting the perspective by means of \(1/w\). And the z-buffer solves visibility pixel by pixel, where the painter's algorithm fails, at the price of a finite precision that has to be managed. mini3d gains inside_clip_volume, clip_edge_near, ndc_to_screen, viewport_matrix, edge_function, is_back_face, interpolate_attribute, interpolate_with_perspective and rasterize_triangle.
We now know where to paint each triangle; we have left open what to paint. Before dealing with color, we go back to shape for a moment. All our meshes have come from simple formulas or from hand-written lists, and their faces are flat; but the hull of a ship or the dome of a lighthouse are curved surfaces. In the next lesson, "Surface Modeling", we will study how those surfaces are described mathematically—explicit, parametric, implicit, Bézier and NURBS—how their exact normals are obtained and how they are converted into the triangle meshes we have just learned to draw.
