We closed Module 5 with a sentence left hanging: every stage of an object's journey to the screen had been built and tested separately, as a loose piece of mini3d, and what remained was to fit them together. This lesson does exactly that. We take the model, view and projection matrices, the clipping, the viewport, the rasterizer with its z-buffer and the lighting model, and chain them into a single function, render, which receives the scene of "Stellar Lighthouse" and returns an image. Afterwards we will reach the same image by the opposite road, casting rays from the camera, and we will see how all this work is shared out in a real graphics card. No new mathematics appears: the goal is to see how all the mathematics of the course works together, and in what order.
The code assumes that all the functions from the previous lessons have been imported (from mini3d import *). The scene data used are defined in the first block.
The graphics pipeline from end to end
A graphics pipeline is a chain of stages in which each one transforms the output of the one before. A geometric description of the scene goes in and an array of colors comes out. It is usually divided into four large blocks:
flowchart LR
A["Application<br/>scene, camera,<br/>per-object culling"] --> B["Geometry<br/>vertex shader,<br/>clipping, viewport"]
B --> C["Rasterization<br/>coverage and<br/>interpolation"]
C --> D["Fragments<br/>lighting, textures,<br/>depth test"]
D --> E["Image"]
- Application. The program decides what has to be drawn: it updates the world matrix of each object, places the camera and culls whatever is certain not to be seen.
- Geometry. It works per vertex: it takes each vertex to clip space, clips the triangles and converts them to screen coordinates.
- Rasterization. It works per triangle: it finds out which pixels the triangle covers and interpolates the attributes of its vertices.
- Fragments. It works per covered pixel: it computes the color and decides, using the depth, whether it stays in the image. A fragment is a "candidate pixel": the interpolated data of a triangle at the position of a pixel. Several fragments may compete for the same pixel; the nearest one wins.
Each stage rests on a specific part of the course:
| Stage | What it does | Mathematics | Lesson where it was built | mini3d function |
|---|---|---|---|---|
| Application | World matrix of each object | Composition \(T,R,S\), hierarchies | "Composition of Transformations" | model_matrix, compose |
| Application | Culling objects outside the camera | Signed distance to six planes | "Projections and Views" | frustum_planes, sphere_in_frustum |
| Geometry | World → view | Inverse of a rigid matrix | "Coordinate Spaces and the View Matrix" | look_at_matrix |
| Geometry | View → clip | Homogeneous coordinates, perspective | "Projections and Views" | perspective_matrix |
| Geometry | Normals to the world | Inverse transpose | "Lighting and Shading" | normal_matrix |
| Geometry | Clipping | Linear interpolation in 4D | "From Clip Space to the Screen: Viewport, Rasterization and Z-buffer" | clip_edge_near |
| Geometry | Division by \(w\) and viewport | Scaling and translation | "From Clip Space to the Screen: Viewport, Rasterization and Z-buffer" | ndc_to_screen |
| Rasterization | Back faces, coverage | 2×2 determinant (signed area) | "From Clip Space to the Screen: Viewport, Rasterization and Z-buffer" | is_back_face, edge_function |
| Rasterization | Interpolating attributes | Barycentric coordinates corrected with \(1/w\) | "From Clip Space to the Screen: Viewport, Rasterization and Z-buffer" | interpolate_with_perspective |
| Fragments | Color | Dot products \(\hat{\mathbf{N}} \cdot \hat{\mathbf{L}}\), \(\hat{\mathbf{N}} \cdot \hat{\mathbf{H}}\) | "Lighting and Shading" | shade_point |
| Fragments | Visibility | Depth comparison | "From Clip Space to the Screen: Viewport, Rasterization and Z-buffer" | rasterize_triangle (z-buffer) |
Read from top to bottom, the table is the table of contents of Modules 2 to 5.
The input data: scene and camera
Before programming the pipeline we fix the format of what goes into it. We will use dictionaries, as in the rest of mini3d:
- An object is
{"mesh", "model", "material"}: a mesh in local space, its model matrix and a material like those of "Lighting and Shading". The mesh may carry the optional keys"colors"(one color per vertex) and"normals"(one normal per vertex, in local space). - A scene is
{"objects": [...], "lights": [...], "ambient": color}. - A camera is
{"view", "projection"}: the two 4×4 matrices.
import numpy as np
from mini3d import *
np.set_printoptions(suppress=True)
ship = np.array([8.0, 3.0, 6.0])
lamp = np.array([0.0, 12.0, 0.0])
ship_orientation = np.array([[0.6, 0.0, 0.8], [0.0, 1.0, 0.0], [-0.8, 0.0, 0.6]])
hull_model = model_matrix(ship, ship_orientation, (4.0, 1.0, 2.0))
hull = octahedron_mesh() # vertices: +X, -X, +Y, -Y, +Z, -Z
hull["colors"] = np.array([[0.9, 0.2, 0.2], [0.2, 0.9, 0.2], [0.8, 0.8, 0.8],
[0.3, 0.3, 0.3], [1.0, 1.0, 1.0], [1.0, 0.6, 0.0]])
exterior_camera = {"view": look_at_matrix([24.0, 10.0, 2.0], [3.0, 4.0, 3.0]),
"projection": perspective_matrix(np.radians(45.0), 16.0 / 9.0, 1.0, 100.0)}The vertex colors are those of the hull we fixed in Module 5 (red right wing, green left wing, white nose, orange tail...). The camera is new: an exterior camera located at \((24, 10, 2)\), to the east of the scene, looking toward \((3, 4, 3)\) with a 45° field of view. From there the ship, the lighthouse and the two asteroids can all be seen at once.
Geometry stage: the vertex shader
The vertex shader is the function that runs once per vertex. Its duty is to deliver the position of the vertex in clip space; it also prepares the attributes that the fragment stage will need interpolated. In our case:
\[ \mathbf{p}{\text{world}} = M,\mathbf{p}{\text{local}} \qquad \mathbf{c} = P,V,\mathbf{p}{\text{world}} \qquad \mathbf{n}{\text{world}} = \operatorname{normalize}!\left(\left(M^{-1}\right)^{T} \mathbf{n}_{\text{local}}\right) \]
We keep the world position because we will light in that space (remember that lighting cannot be done after the projection, which distorts angles). The matrix \(P,V\) is the same for every object and is computed only once per frame.
def vertex_shader(mesh, model, vp):
"""Per-vertex stage. Returns world positions (n x 3), clip positions
(n x 4) and world normals (n x 3, or None if the mesh has no normals)."""
world = transform_points(model, mesh["vertices"])
homogeneous = np.hstack([world, np.ones((len(world), 1))])
clip = homogeneous @ vp.T # all the vertices at once
normals = None
if "normals" in mesh:
normals = mesh["normals"] @ normal_matrix(model).T
normals = normals / np.linalg.norm(normals, axis=1, keepdims=True)
return world, clip, normals
vp = exterior_camera["projection"] @ exterior_camera["view"]
world, clip, normals = vertex_shader(hull, hull_model, vp)
print(np.round(world, 2))
print(np.round(clip, 3))[[10.4 3. 2.8] [ 5.6 3. 9.2] [ 8. 4. 6. ] [ 8. 2. 6. ] [ 9.6 3. 7.2] [ 6.4 3. 4.8]] [[-0.207 -7.225 13.304 15.021] [-8.578 -3.847 18.306 19.924] [-4.392 -3.214 15.525 17.198] [-4.392 -7.857 16.085 17.747] [-6.123 -6.557 14.293 15.99 ] [-2.661 -4.515 17.317 18.954]]
The first matrix holds the six vertices of the hull in the world, the same as always. The second, their clip coordinates. The fourth column, \(w\), is the depth of each vertex relative to the camera: between 15 and 20 m. Two implementation details:
homogeneous @ vp.Tmultiplies all the vertices by the matrix in a single operation: since the points are stored as rows, we multiply by the transpose (it is the same thingtransform_pointsdoes). We will come back to this when we talk about performance.- The hull carries no vertex normals: its faces are flat and, as we saw, the correct shading for it is flat shading. The normal of each face will be computed later from its three vertices.
Clipping and culling
Between the vertex shader and rasterization, everything that cannot appear in the image is eliminated. There are three filters, from coarsest to finest:
| Filter | Unit | Criterion | What it saves |
|---|---|---|---|
| Frustum culling | Whole object | Its bounding sphere lies outside one plane of the frustum | The whole pipeline for that object |
| Trivial rejection and clipping | Triangle | All three vertices outside the same plane; or it crosses the near plane | Rasterizing the invisible; avoids \(w \le 0\) |
| Backface culling | Triangle | Signed area on screen \(\ge 0\) | In closed meshes, half the triangles |
The first belongs to the application stage and we already have it (sphere_in_frustum); we will use it in the final project. The third is is_back_face. The second remains to be completed: in "From Clip Space to the Screen: Viewport, Rasterization and Z-buffer" we clipped an edge against the near plane; now we have to clip a triangle and, with it, all the attributes of its vertices.
The idea that simplifies everything is to treat each vertex as a bundle: a row with its four clip coordinates followed by the attributes (world position, normal, color). Since all those quantities vary linearly along an edge in clip space, the new vertex that appears where the edge crosses the plane is obtained by interpolating the whole row with the same \(t = d_0 / (d_0 - d_1)\), where \(d = w + z\).
def outside_volume(c):
"""True if the three vertices (rows x, y, z, w...) lie outside the same clipping plane."""
w = c[:, 3]
return any(np.all(c[:, k] > w) or np.all(c[:, k] < -w) for k in range(3))
def clip_triangle_near(vertices):
"""Clips a triangle against the near plane (w + z = 0).
vertices: 3 x k matrix; the first 4 columns are the clip (x, y, z, w) and the rest,
attributes that are interpolated the same way. Returns a list of 0, 1 or 2 triangles."""
d = vertices[:, 3] + vertices[:, 2] # > 0: visible side
polygon = []
for i in range(3):
k = (i + 1) % 3 # edge i -> k
if d[i] > 0.0:
polygon.append(vertices[i])
if (d[i] > 0.0) != (d[k] > 0.0): # the edge crosses the plane
t = d[i] / (d[i] - d[k])
polygon.append(vertices[i] + t * (vertices[k] - vertices[i]))
return [np.array([polygon[0], polygon[k], polygon[k + 1]])
for k in range(1, len(polygon) - 1)]
test = np.array([[0.0, 0.0, -3.0, 1.0, 1.0], # x, y, z, w and one attribute
[2.0, 0.0, 1.0, 3.0, 0.0],
[0.0, 2.0, 1.0, 3.0, 0.0]])
print(outside_volume(test), len(clip_triangle_near(test)))
print(np.round(clip_triangle_near(test)[0], 3))This is the Sutherland–Hodgman algorithm reduced to a single plane: we walk around the triangle edge by edge, keep the visible vertices and add a new vertex at each crossing. The test triangle has one vertex behind the near plane (\(d = 1 - 3 = -2\)) and two in front (\(d = 4\)): cutting off the tip leaves a quadrilateral, which is returned as two triangles. In the first one we see the new vertex: \(t = -2/(-2 - 4) = 1/3\), with \(z = -w\) (it is on the near plane) and the interpolated attribute, \(1 + \tfrac{1}{3}(0 - 1) = 0.667\). The traversal preserves the winding, so backface culling still works afterwards.
We do not clip against the other five planes: the trivial rejection of outside_volume is enough, because rasterize_triangle already limits its bounding box to the image.
Rasterization and the fragment shader: the render function
The second half remains. For each triangle that survives:
- Perspective divide and viewport:
ndc_to_screenapplied to \((x, y, z)/w\). - Backface culling with the signed area.
- Rasterization with
rasterize_triangle, which goes through the covered pixels, applies the z-buffer test and calls a shader with the pixel's barycentric coordinates. - Fragment shader: the function that runs once per fragment. It interpolates the attributes with perspective correction—this is where the clip-space \(w\) of each vertex is used—and evaluates the Blinn-Phong lighting with
shade_point.
The interpolated vertex color plays the role of the material's diffuse color at that point. If the mesh has no colors, every vertex receives the material's diffuse color. And the interpolated normal is normalized again: that is Phong shading; in meshes without vertex normals the three normals of the bundle are the face normal and the result is flat shading.
def render(scene, camera, width, height):
"""Software renderer. Returns the RGB image (height x width x 3), the z-buffer
and a dictionary with the count of what was processed at each stage."""
view, projection = camera["view"], camera["projection"]
vp = projection @ view
eye = camera_position(view)
image = np.zeros((height, width, 3)) # black background
z_buffer = np.full((height, width), 1.0) # everything at the far plane
counts = {"vertices": 0, "triangles": 0, "outside": 0, "back_facing": 0,
"rasterized": 0, "fragments": 0}
for obj in scene["objects"]:
mesh, model, material = obj["mesh"], obj["model"], obj["material"]
world, clip, normals = vertex_shader(mesh, model, vp)
colors = mesh.get("colors", np.tile(material["diffuse"], (len(world), 1)))
counts["vertices"] += len(world)
for face in mesh["faces"]:
counts["triangles"] += 1
if outside_volume(clip[face]):
counts["outside"] += 1
continue
if normals is None: # flat shading: the face normal
face_normals_3 = np.tile(triangle_normal(*world[face]), (3, 1))
else:
face_normals_3 = normals[face]
bundle = np.hstack([clip[face], world[face], face_normals_3, colors[face]])
for triangle in clip_triangle_near(bundle):
w = triangle[:, 3]
p0, p1, p2 = (ndc_to_screen(v[:3] / v[3], width, height) for v in triangle)
if is_back_face(p0, p1, p2):
counts["back_facing"] += 1
continue
def fragment_shader(alpha, beta, gamma, attributes=triangle[:, 4:], w=w):
a = interpolate_with_perspective((alpha, beta, gamma), attributes, w)
point, normal, color = a[0:3], normalize(a[3:6]), a[6:9]
return shade_point(point, normal, eye, dict(material, diffuse=color),
scene["lights"], scene["ambient"])
counts["rasterized"] += 1
counts["fragments"] += rasterize_triangle(p0, p1, p2, image, z_buffer,
fragment_shader)
return image, z_buffer, countsIt is forty lines, and almost all of them are calls to functions that already existed. It is worth reading it from top to bottom and recognizing each piece:
- The outer loop goes through objects;
vertex_shaderprocesses all their vertices. - The middle loop goes through triangles: trivial rejection, a bundle of 13 numbers per vertex (4 for clip + 3 for position + 3 for normal + 3 for color), clipping, viewport and backface culling.
- The pixel loop is inside
rasterize_triangle, which only calls the fragment shader for the pixels that pass the depth test.dict(material, diffuse=color)is a copy of the material with the diffuse color replaced. - The default values
attributes=...andw=wof the inner function freeze the data of the current triangle at the moment it is defined.
The "Stellar Lighthouse" scene, finally as an image
We assemble the scene with five objects: the lighthouse asteroid (a sphere of radius 10 centered at \((0, -10, 0)\)), the rogue asteroid (radius 5, center \((2, 8, 5)\)), the dome of the lamp (radius 1.5), the tower (a 2 × 12 × 2 m prism, made with a scaled cube_mesh) and the hull of the ship. The three spheres share a single unit mesh, placed with a different model matrix each; on a unit sphere the normal of each vertex coincides with its position.
def unit_sphere(parallels, meridians):
"""Sphere of radius 1 with exact (radial) vertex normals."""
mesh = sphere_mesh(1.0, parallels, meridians)
mesh["normals"] = mesh["vertices"].copy()
return mesh
hull_material = {"diffuse": (0.6, 0.65, 0.7), "specular": (0.9, 0.9, 0.9), "shininess": 32.0}
rock = {"diffuse": (0.55, 0.5, 0.45), "specular": (0.1, 0.1, 0.1), "shininess": 8.0}
glass = {"diffuse": (0.2, 0.3, 0.5), "specular": (1.0, 1.0, 1.0), "shininess": 64.0}
lighthouse_light = {"type": "spot", "position": lamp, "color": (2.0, 1.9, 1.6),
"attenuation": (1.0, 0.05, 0.005), "axis": direction_to(lamp, ship),
"angles": (np.radians(6.0), np.radians(10.0))}
star_light = {"type": "directional", "direction": np.array([0.36, 0.8, 0.48]),
"color": (0.3, 0.3, 0.35)}
spheres = [{"center": np.array([0.0, -10.0, 0.0]), "radius": 10.0, "material": rock},
{"center": np.array([2.0, 8.0, 5.0]), "radius": 5.0, "material": rock},
{"center": lamp, "radius": 1.5, "material": glass, "no_shadow": True}]
sphere_objects = [{"mesh": unit_sphere(12, 24), "material": s["material"],
"model": model_matrix(s["center"], np.eye(3), [s["radius"]] * 3)}
for s in spheres]
tower = {"mesh": cube_mesh(), "material": rock,
"model": model_matrix([0.0, 6.0, 0.0], np.eye(3), (1.0, 6.0, 1.0))}
ship_object = {"mesh": hull, "model": hull_model, "material": hull_material}
scene = {"objects": sphere_objects + [tower, ship_object],
"lights": [lighthouse_light, star_light], "ambient": (0.05, 0.05, 0.08)}The spheres list keeps the analytic description (center and radius) of the three spheres; we will reuse it in the ray tracer. The dome's "no_shadow" key is also for then.
To see the result in a terminal we turn each pixel into a character according to its brightness. The perceived brightness of a color is its luminance, a weighted average of the three channels (the eye is far more sensitive to green than to blue), which is nothing more than a dot product with a vector of weights. Before choosing the character we apply the gamma correction we discussed in "Lighting and Shading", so that the midtones do not come out too dark.
def luminance(image):
"""Perceived brightness of each pixel: dot product of the color with (0.2126, 0.7152, 0.0722)."""
return np.asarray(image) @ np.array([0.2126, 0.7152, 0.0722])
def to_ascii(image, gamma=2.2, ramp=" .:-=+*#%@"):
"""Converts an RGB image into text: one character per pixel, according to its brightness.
ramp: characters ordered from least to most brightness."""
levels = (luminance(image) ** (1.0 / gamma) * len(ramp)).astype(int)
levels = np.minimum(levels, len(ramp) - 1)
return "\n".join("".join(ramp[k] for k in row) for row in levels)
WIDTH, HEIGHT = 72, 20
image, z_buffer, counts = render(scene, exterior_camera, WIDTH, HEIGHT)
print(counts)
print(to_ascii(image)){'vertices': 812, 'triangles': 1604, 'outside': 425, 'back_facing': 681, 'rasterized': 498, 'fragments': 489}
=========---- --:::.
============------::....
============------::.---
===========-------:::.---
========--------::::...--
--------------:::::....--
-----------::::::......--
------:::::::........---
:::::::::..........----
............... ----
......... ----
----
+*******## -==-----
*##****+++-==============---
:+++===============-----
=====================------
=======================------:
========================-------:
=========================-------::
=========================--------::The canvas is 72 × 20 characters and not 72 × 40 because a terminal character is roughly twice as tall as it is wide: this way the image keeps the 16:9 proportion of the projection.
There is the complete scene. At the top left, the rogue asteroid, with the smooth gradient of Phong shading: lighter where its normal faces the star and dark on its underside. To its right, the lighthouse tower, crowned by the dome, rises from the large asteroid that fills the lower part. And to the left of the tower, the ship: its flat faces can be told apart by the abrupt jumps in brightness, and it is the brightest thing in the image because the lighthouse lamp is pointing at it.
The count is an X-ray of the pipeline: of 1604 triangles, 425 were rejected for being outside the view volume, 681 for being back faces, and only 498 reached the rasterizer. Between them they wrote 489 fragments into an image of 1440 pixels.
If you want the image in color, the PPM format is the simplest one there is: a text header followed by the RGB bytes. Most image viewers can open it.
def save_ppm(image, path, gamma=2.2):
"""Saves an RGB image (values in [0, 1]) to a binary PPM file."""
data = (np.clip(image, 0.0, 1.0) ** (1.0 / gamma) * 255.0 + 0.5).astype(np.uint8)
height, width, _ = data.shape
with open(path, "wb") as file:
file.write(f"P6 {width} {height} 255\n".encode("ascii"))
file.write(data.tobytes())
large, _, large_counts = render(scene, exterior_camera, 160, 90)
save_ppm(large, "stellar_lighthouse.ppm")
print(large_counts["rasterized"], large_counts["fragments"])At 160 × 90 pixels the same 498 triangles are rasterized, but the fragments go from 489 to 4875, ten times as many: the cost of the first half of the pipeline depends on the geometry; that of the second, on the resolution.
The opposite road: ray tracing
The image above has a flaw that cannot be seen with the naked eye but that we have known about since "Lighting and Shading": the lighthouse beam that lights the hull so brightly should not arrive, because the rogue asteroid is in the way. The rasterizer processes each triangle knowing nothing about the others; the only global information it handles is the z-buffer, and only from the camera's point of view.
There is another way of producing the image, which reverses the order of the loops:
- Rasterization: for each triangle, which pixels does it cover?
- Ray tracing: for each pixel, which object is seen through it?
Ray tracing answers with the intersection tests of Module 3. For each pixel a primary ray is cast from the eye; the object with the smallest positive \(t\) is the visible one (that minimum plays the role of the z-buffer), and the same lighting is evaluated at the hit point. The advantage is that, from that point, more rays can be cast: toward each light, to find out whether it is blocked (shadow rays); in the direction of reflect, for reflections...
The ray of a pixel
We have to undo the chain of transformations: from the pixel to NDC, and from NDC to a direction. First we invert the viewport for the center of the pixel in column \(i\) and row \(j\):
\[ x_{\text{ndc}} = \frac{2,(i + 0.5)}{\text{width}} - 1 \qquad y_{\text{ndc}} = 1 - \frac{2,(j + 0.5)}{\text{height}} \]
The perspective matrix computed \(x_{\text{ndc}} = P_{00},x_v / (-z_v)\), with \(P_{00} = 1 / (\text{aspect} \cdot \tan(\text{fov}/2))\), and the analogous expression for \(y\) with \(P_{11}\). Therefore, the view-space point that lies at depth 1 (\(z_v = -1\)) and projects onto that pixel is \(\left(x_{\text{ndc}}/P_{00},\ y_{\text{ndc}}/P_{11},\ -1\right)\). Seen as a vector from the eye—the origin of view space—it is the direction of the ray. All that is left is to take it to the world with the transpose of the rotation of the view matrix, which, being orthogonal, is its inverse.
def primary_ray(camera, column, row, width, height):
"""Ray (origin, unit direction) in the world that passes through the center of a pixel."""
view, projection = camera["view"], camera["projection"]
x_ndc = (column + 0.5) / width * 2.0 - 1.0
y_ndc = 1.0 - (row + 0.5) / height * 2.0
in_view = np.array([x_ndc / projection[0, 0], y_ndc / projection[1, 1], -1.0])
return camera_position(view), normalize(view[:3, :3].T @ in_view)
origin, direction = primary_ray(exterior_camera, 28, 13, WIDTH, HEIGHT)
print(origin, np.round(direction, 4))
point = origin + 20.0 * direction
print(np.round(ndc_to_screen(project_point(vp, point), WIDTH, HEIGHT)[:2], 3))The check closes the circle: an arbitrary point of the ray (the one 20 m along it), projected with the forward pipeline, lands exactly on the center of the pixel we started from, \((28.5, 13.5)\).
The tracer
def in_shadow(point, light, spheres):
"""True if some sphere lies between the point and the light."""
if light["type"] == "directional":
toward_light, reach = np.asarray(light["direction"], dtype=float), np.inf
else:
toward_light = direction_to(point, light["position"])
reach = distance(point, light["position"])
for sphere in spheres:
if sphere.get("no_shadow"):
continue
t = ray_sphere(point, toward_light, sphere["center"], sphere["radius"])
if t is not None and t < reach:
return True
return False
def trace_ray(origin, direction, spheres, lights, ambient, shadows=True):
"""Color that reaches the origin from the given direction."""
t_min, visible = np.inf, None
for sphere in spheres: # the closest hit
t = ray_sphere(origin, direction, sphere["center"], sphere["radius"])
if t is not None and t < t_min:
t_min, visible = t, sphere
if visible is None:
return np.zeros(3) # background
point = origin + t_min * direction
normal = (point - visible["center"]) / visible["radius"]
if shadows:
start = point + 1e-4 * normal # avoids self-intersection
lights = [light for light in lights if not in_shadow(start, light, spheres)]
return shade_point(point, normal, origin, visible["material"], lights, ambient)
def trace_scene(spheres, lights, ambient, camera, width, height, shadows=True):
"""RGB image of a scene of spheres by ray tracing."""
image = np.zeros((height, width, 3))
for row in range(height):
for column in range(width):
origin, direction = primary_ray(camera, column, row, width, height)
image[row, column] = trace_ray(origin, direction, spheres, lights, ambient, shadows)
return imageThe normal of a sphere at a point is the normalized radius: there is no mesh and no interpolation. The dome carries the "no_shadow" flag because the lamp is inside it: if it counted as an obstacle, it would block its own light (real glass would let it through). A light "in shadow" is simply removed from the list before calling shade_point.
The same result by both roads
We compare the two methods with the same camera and the same lights on the three spheres: rasterized as meshes of 528 triangles each, and traced as exact spheres, first without shadows.
sphere_scene = dict(scene, objects=sphere_objects)
raster, _, _ = render(sphere_scene, exterior_camera, WIDTH, HEIGHT)
rays = trace_scene(spheres, scene["lights"], scene["ambient"], exterior_camera,
WIDTH, HEIGHT, shadows=False)
raster_covers, rays_cover = luminance(raster) > 0.0, luminance(rays) > 0.0
difference = np.abs(luminance(raster) - luminance(rays))[raster_covers & rays_cover]
print(raster_covers.sum(), rays_cover.sum(), (raster_covers != rays_cover).sum())
print(round(float(difference.mean()), 4), round(float(difference.max()), 4))The mesh covers 427 pixels and the exact sphere, 431: the 4 that differ are on the outline, where the polygon mesh lies slightly inside the sphere. In the pixels they share, the average difference in brightness is 7 ten-thousandths. Two algorithms that do not share a single line of their main loop produce the same image, because they solve the same geometric problem: projecting along straight lines that pass through the eye.
Now we switch on the shadow rays:
with_shadows = trace_scene(spheres, scene["lights"], scene["ambient"], exterior_camera,
WIDTH, HEIGHT)
print(to_ascii(with_shadows))
print(int((np.abs(luminance(with_shadows) - luminance(rays)) > 1e-6).sum())) ==========---- --:::.
============------::....
============------:::..
===========-------::::
========--------::::...
--------------:::::....
-----------::::::......
------:::::::........
:::::::::..........
...............
.........
........
=.................
===................----
=====================------
=======================------:
=========================-------:
=========================-------::
==========================--------:.
41At the top of the large asteroid, right where the tower stands in the complete scene, a dark patch of 41 pixels appears: the cast shadow of the rogue asteroid, which blocks the light of the star. Those points keep only the ambient light. With the rasterizer, getting this shadow requires a separate technique (shadow maps); with the tracer, ten lines and one function from Module 3 were enough.
Rasterization versus ray tracing
| Rasterization | Ray tracing | |
|---|---|---|
| Outer loop | Triangles | Pixels (rays) |
| Question | Which pixels does this triangle cover? | Which object does this pixel see? |
| Projection | Perspective matrix and division by \(w\) | Implicit: the rays start at the eye |
| Visibility | Z-buffer | The smallest \(t\) of the intersections |
| Core mathematics | 4×4 matrices, barycentric coordinates on screen | Ray-object intersections |
| Geometry supported | Triangles | Any shape with an intersection test (exact spheres, SDFs...) |
| Shadows, reflections, refraction | Added techniques, approximate | Natural: more rays |
| Cost | Proportional to the triangles plus the fragments | Rays × objects, unless an acceleration structure is used |
| Typical use | Real time | Film, global illumination; and specific effects in real time |
The "rays × objects" cost is tamed with the broad phase from "Intersections: Rays, Spheres, Triangles and Boxes": the objects are grouped into a bounding volume hierarchy (BVH) and each ray only tests the boxes it passes through. Today's engines combine the two methods: they rasterize what is seen directly and trace rays for shadows and reflections.
The same pipeline on a GPU
A graphics card implements this same pipeline in hardware. The clipping, the division by \(w\), the viewport, the rasterization, the perspective-correct interpolation and the z-buffer are fixed stages: they work the way we have programmed them, without anyone having to write them. What the programmer supplies are two small programs, the shaders, which correspond to our two functions:
In mini3d |
On the GPU | Runs | Receives | Delivers |
|---|---|---|---|---|
vertex_shader |
Vertex shader | Once per vertex | Vertex attributes and matrices (uniform) |
Clip position and attributes to be interpolated |
clip_triangle_near, ndc_to_screen, rasterize_triangle |
Fixed stages | — | — | Fragments with interpolated attributes |
fragment_shader |
Fragment shader | Once per fragment | Interpolated attributes, lights and material | Color |
In GLSL, the shader language of OpenGL, what we have implemented would be written like this (simplified to the directional light):
// --- Vertex shader ---
uniform mat4 model, viewProjection;
uniform mat3 normalMatrix; // inverse transpose of the model
in vec3 position, normal, color; // vertex attributes (local space)
out vec3 worldPoint, worldNormal, vertexColor;
void main() {
vec4 world = model * vec4(position, 1.0); // w = 1: it is a point
worldPoint = world.xyz;
worldNormal = normalMatrix * normal;
vertexColor = color;
gl_Position = viewProjection * world; // clip space
}
// --- Fragment shader ---
uniform vec3 eye, towardLight, lightColor, ambient, specular;
uniform float shininess;
in vec3 worldPoint, worldNormal, vertexColor; // already interpolated
out vec4 finalColor;
void main() {
vec3 n = normalize(worldNormal); // renormalize after interpolating
vec3 v = normalize(eye - worldPoint);
vec3 h = normalize(towardLight + v); // Blinn-Phong halfway vector
float diffuse = max(dot(n, towardLight), 0.0);
float spec = diffuse > 0.0 ? pow(max(dot(n, h), 0.0), shininess) : 0.0;
vec3 c = ambient * vertexColor + lightColor * (vertexColor * diffuse + specular * spec);
finalColor = vec4(clamp(c, 0.0, 1.0), 1.0);
}You do not need to know GLSL to read it: mat4, vec3, dot and normalize are the matrices, the vectors, the dot product and the normalization of the course, and * between a matrix and a vector is our @. Each line has its equivalent in vertex_shader or in shade_point. The out variables of the first shader reappear as in in the second one already interpolated by the fixed rasterization stage. Engines such as Unity, Unreal or Godot generate shaders of this kind from their materials; underneath, the operations are always the same.
Performance: what each stage costs and why we vectorize
With the count from render we can estimate the work of each stage in our 72 × 20 image:
| Stage | Times it runs | Work per run | Grows with |
|---|---|---|---|
| Vertex shader | 812 vertices | Two matrix-vector products | The complexity of the meshes |
| Rejection, clipping, back faces | 1604 triangles | Comparisons and a 2×2 determinant | The complexity of the meshes |
| Coverage | Pixels of the bounding boxes of 498 triangles | Three edge functions | Triangles and resolution |
| Fragment shader | 489 fragments | Interpolating 9 attributes; for each light, two normalizations, two dot products and one power | The resolution and the number of lights |
| Ray tracing (for comparison) | 1440 rays × 3 spheres | One quadratic equation per test | Resolution × objects |
At 1920 × 1080, the fragments would go from a few hundred to close to a million, sixty times per second. Two practical consequences:
- The fragment shader dominates the cost. That is why it matters so much not to run it in vain: cull back faces, and draw what is near first so that the z-buffer rejects early whatever lies behind.
- The cheap rejections go first. Each filter removes work from all the later stages.
The other key is that every stage performs the same operation on many independent pieces of data: vertex 3 does not need vertex 7, nor does a fragment need its neighbor. That allows them to be processed in parallel, which is exactly what a GPU does with its thousands of cores. In NumPy, the equivalent is to vectorize: replacing a Python loop with an operation on whole arrays, as we did with homogeneous @ vp.T. Another example: the coverage of a sphere for all the pixels at once, with the discriminant of ray_sphere computed on an array of directions.
def vectorized_coverage(camera, center, radius, width, height):
"""Mask (height x width) of the pixels whose primary ray hits the sphere."""
view, projection = camera["view"], camera["projection"]
columns, rows = np.meshgrid(np.arange(width), np.arange(height))
x_ndc = (columns + 0.5) / width * 2.0 - 1.0
y_ndc = 1.0 - (rows + 0.5) / height * 2.0
in_view = np.stack([x_ndc / projection[0, 0], y_ndc / projection[1, 1],
-np.ones_like(x_ndc)], axis=-1)
directions = in_view @ view[:3, :3] # rows times R = (R^T d) for each pixel
directions /= np.linalg.norm(directions, axis=-1, keepdims=True)
m = np.asarray(center) - camera_position(view)
b = directions @ m # one dot product per pixel
return (b * b - (m @ m - radius * radius) >= 0.0) & (b > 0.0)
fast = vectorized_coverage(exterior_camera, spheres[1]["center"], 5.0, WIDTH, HEIGHT)
slow = np.array([[ray_sphere(*primary_ray(exterior_camera, i, j, WIDTH, HEIGHT),
spheres[1]["center"], 5.0) is not None
for i in range(WIDTH)] for j in range(HEIGHT)])
print(int(fast.sum()), np.array_equal(fast, slow))The two versions mark the same 208 pixels of the rogue asteroid. The vectorized one has not a single loop: directions @ m computes the 1440 dot products at once, and at real resolutions it is hundreds of times faster than the version with two nested loops. The formulas are identical; the only change is that each variable is a whole array instead of a number. Our render is deliberately slow and readable: its value is that each line corresponds to an idea from the course.
Common Mistakes and Tips
- Multiplying the matrices in another order. The chain is \(P,V,M\), and it is applied from right to left: first model, then view, then projection.
- Lighting with data from different spaces. Point, normal, eye and lights must be in the same space (here, the world). Never in clip space.
- Transforming the normals with the model matrix. The spheres of the scene have uniform scaling and it would not be noticed, but the hull has scale \((4, 1, 2)\): with the wrong matrix, its lighting would be incorrect. Always
normal_matrix. - Dividing by \(w\) before clipping, or not clipping against the near plane. As soon as the camera gets close to an object, mirrored triangles will appear.
- Interpolating the attributes without perspective correction. With colors it is barely noticeable; with world positions and textures, it is.
- Not renormalizing the interpolated normal in the fragment shader.
- Forgetting to clear the z-buffer every frame, or initializing it to 0.
- In the tracer, casting the shadow ray from the exact point. Rounding errors sometimes place it inside the surface, which then blocks itself and produces a dark speckle ("shadow acne"). The origin has to be moved a small distance along the normal.
- Tip. When the image comes out black, check the pipeline stage by stage, with a single vertex, as in Exercise 1: is its \(w\) positive? Are its NDC between −1 and 1? Which pixel does it land on? Is its triangle front-facing? The per-stage count from
rendertells you at which one the geometry is lost.
Exercises
Exercise 1. Follow the hull's "top" vertex, \((8, 4, 6)\), through the pipeline by hand with the exterior camera. Its clip coordinates are \((-4.392, -3.214, 15.525, 17.198)\).
a) Is it inside the view volume? At what depth is it relative to the camera? b) Compute its NDC coordinates and the pixel of the 72 × 20 canvas on which it lands. c) Check with the image's z-buffer that something has been drawn at that depth in that pixel.
Exercise 2. The escort drone flies alongside the ship, at \((10, 3, 6)\). Add it to the scene as a cube with 1 m sides, with diffuse color \((0.9, 0.8, 0.2)\), and render again.
a) How many more vertices and triangles does the pipeline process? How many of the drone's triangles reach the rasterizer? b) How many pixels of the image change? Does the order in which the drone is added to the list of objects matter?
Exercise 3. The star's light arrives from the direction \((0.36, 0.8, 0.48)\). The rogue asteroid is the sphere with center \((2, 8, 5)\) and radius 5.
a) Work out by hand, with the discriminant of the ray-sphere intersection, whether the base of the lighthouse, \((0, 0, 0)\), is in the shadow of the rogue asteroid.
b) Do the same with the point \((6, -2, 0)\) of the lighthouse asteroid.
c) Check it with in_shadow.
Solutions
Solution 1.
a) We have to check \(-w \le x, y, z \le w\) with \(w = 17.198\): \(-4.392\), \(-3.214\) and \(15.525\) are all three between \(-17.198\) and \(17.198\). It is inside. The depth is \(w = 17.2\) m.
b) Dividing by \(w\): \(\text{NDC} = (-0.2554, -0.1869, 0.9027)\). Viewport:
\[ x_p = (1 - 0.2554) \cdot 36 = 26.81 \qquad y_p = (1 + 0.1869) \cdot 10 = 11.87 \qquad z_p = \frac{1.9027}{2} = 0.9514 \]
It lands on the pixel in column 26 and row 11.
c) See the code further down. At pixel \((26, 11)\) the z-buffer still holds the background (1.0), and at the one below it, \((26, 12)\), it stores 0.950. This is not an error: the top is the highest point of the hull and it projects to \(y_p = 11.87\), whereas the center of the pixel in row 11 is at \(y = 11.5\), above it. The rasterizer only paints the pixels whose center lies inside the triangle, so the first one covered is the one in row 12, at a depth practically equal to that of the vertex (0.9514).
Solution 2. The cube has 8 vertices and 12 triangles. The z-buffer means that the drawing order does not alter the image.
Solution 3.
a) With origin at \((0, 0, 0)\) and unit direction \(\hat{\mathbf{d}} = (0.36, 0.8, 0.48)\): \(\mathbf{m} = (2, 8, 5)\), \(b = \mathbf{m} \cdot \hat{\mathbf{d}} = 0.72 + 6.4 + 2.4 = 9.52\), \(c = \lVert \mathbf{m} \rVert^2 - r^2 = 93 - 25 = 68\). Discriminant: \(b^2 - c = 90.63 - 68 = 22.63 > 0\), and \(b > 0\): the ray hits the asteroid at \(t = 9.52 - \sqrt{22.63} = 4.76\) m. The base of the lighthouse is in shadow.
b) \(\mathbf{m} = (2, 8, 5) - (6, -2, 0) = (-4, 10, 5)\); \(b = -1.44 + 8 + 2.4 = 8.96\); \(c = 141 - 25 = 116\). Discriminant: \(80.28 - 116 < 0\). The ray does not hit the sphere: the point receives the star's light.
c) and checks for the previous exercises:
top = clip[2]
print(outside_volume(clip[[2, 2, 2]]), np.round(top[:3] / top[3], 4),
np.round(ndc_to_screen(top[:3] / top[3], WIDTH, HEIGHT), 4))
print(np.round(z_buffer[11:13, 26], 4))
drone = {"mesh": cube_mesh(), "material": dict(rock, diffuse=(0.9, 0.8, 0.2)),
"model": model_matrix([10.0, 3.0, 6.0], np.eye(3), (0.5, 0.5, 0.5))}
with_drone, _, drone_counts = render(dict(scene, objects=scene["objects"] + [drone]),
exterior_camera, WIDTH, HEIGHT)
drone_first, _, _ = render(dict(scene, objects=[drone] + scene["objects"]),
exterior_camera, WIDTH, HEIGHT)
print({k: drone_counts[k] - counts[k] for k in counts})
print(int(np.any(with_drone != image, axis=2).sum()), np.allclose(with_drone, drone_first))
for q in ([0.0, 0.0, 0.0], [6.0, -2.0, 0.0]):
q = np.array(q)
normal = (q - spheres[0]["center"]) / 10.0
t = ray_sphere(q, star_light["direction"], spheres[1]["center"], 5.0)
print(None if t is None else round(t, 3), in_shadow(q + 1e-4 * normal, star_light, spheres))False [-0.2554 -0.1869 0.9027] [26.8056 11.8691 0.9514]
[1. 0.9499]
{'vertices': 8, 'triangles': 12, 'outside': 0, 'back_facing': 6, 'rasterized': 6, 'fragments': 8}
8 True
4.763 True
None FalseThe drone adds 8 vertices and 12 triangles; 6 are back faces and the other 6 are rasterized (the three faces of the cube that face the camera). Only 8 pixels change—16 m from the camera, a 1 m cube takes up very little on such a small canvas—and the two images, with the drone drawn last or first, are identical.
Conclusion
A graphics pipeline is the ordered composition of almost everything we have studied: the model, view and projection matrices take each vertex to clip space; the clipping in homogeneous coordinates, the division by \(w\) and the viewport turn it into pixels; the edge functions decide the coverage and the barycentric coordinates, corrected with \(1/w\), distribute the attributes; the z-buffer solves visibility and the dot products of Blinn-Phong supply the color. Ray tracing reaches the same image by the opposite road, with the intersections of Module 3, and gets shadows naturally. On a GPU, the programmer writes only the vertex and fragment shaders; the rest are fixed stages that you now know how to rebuild. mini3d gains vertex_shader, outside_volume, clip_triangle_near, render, unit_sphere, luminance, to_ascii, save_ppm, primary_ray, in_shadow, trace_ray, trace_scene and vectorized_coverage.
We have an image, but it is a photograph: nothing moves. In the lessons that follow, the scene comes to life in two different ways. The first is to let the laws of mechanics decide the motion: in the next lesson, "Physics Simulation", we will give the ship mass and velocity, apply forces to it—the gravity of the asteroid, the thrust of its thrusters—and compute step by step its trajectory, its collisions and its rotations.
