6. Rasterization

How triangles become pixels — scanline traversal, barycentric interpolation, and the depth buffer

After the MVP pipeline projects every vertex to screen coordinates, we have a list of 2D triangles. Rasterization is the process of figuring out which pixels each triangle covers and what color they should be.

This is the heart of real-time rendering — the step that turns geometry into an image. GPUs do it billions of times per second, but the algorithm itself is surprisingly simple.

The Problem

Given a triangle defined by three screen-space vertices, determine:

  1. Which pixels fall inside the triangle
  2. For each pixel, interpolate attributes (color, texture coordinates, depth) from the vertices
  3. Use the depth buffer to handle overlapping triangles

Step 1: Bounding Box

The simplest optimization — don't test every pixel on screen. Compute the axis-aligned bounding box of the triangle's three vertices and only test pixels inside that box.

x_min = floor(min(v0.x, v1.x, v2.x))
x_max = ceil(max(v0.x, v1.x, v2.x))
y_min = floor(min(v0.y, v1.y, v2.y))
y_max = ceil(max(v0.y, v1.y, v2.y))

Clamp to the screen bounds and you have your search area.

Step 2: Inside/Outside Test

For each pixel in the bounding box, we need to determine if it's inside the triangle. The most elegant method uses edge functions.

Edge Functions

An edge function computes which side of an edge a point lies on. For an edge from vertex A to vertex B, the edge function at point P is:

E_AB(P) = (B.x - A.x)(P.y - A.y) - (B.y - A.y)(P.x - A.x)

This is just the Z component of the cross product (B - A) x (P - A). If the triangle's vertices are in counter-clockwise order:

  • E > 0 → P is inside (to the left of the edge)
  • E = 0 → P is exactly on the edge
  • E < 0 → P is outside (to the right)

A point is inside the triangle if and only if all three edge functions are non-negative:

E01(P) >= 0  AND  E12(P) >= 0  AND  E20(P) >= 0
Interactive

Edge function rasterizer

Hover over pixels to see edge function values. Drag vertices to reshape.

Step 3: Barycentric Coordinates

The edge functions don't just tell us inside/outside — they give us barycentric coordinates for free. Normalize the three edge function values by the total area of the triangle:

lambda0 = E12(P) / E12(V0)
lambda1 = E20(P) / E20(V1)
lambda2 = E01(P) / E01(V2)

These three values (which sum to 1) tell us how much each vertex "contributes" to the point. They're the weights for interpolating any per-vertex attribute:

attr(P) = lambda0 * attr0 + lambda1 * attr1 + lambda2 * attr2

This is how we interpolate colors, texture coordinates, normals, and depth across the face of a triangle.

Barycentric Interpolation

Barycentric coordinates are the universal interpolation tool in rasterization. Every attribute — color, depth, UV, normal — is interpolated this way.

Interactive

Barycentric color interpolation

Hover inside the triangle to see barycentric weights. Drag vertices to reshape.

Step 4: The Depth Buffer (Z-Buffer)

When triangles overlap, we need to determine which one is in front. The Z-buffer is a 2D array the same size as the screen, storing the depth of the closest fragment at each pixel.

The algorithm is simple:

for each pixel (x, y) inside the triangle:
    z = interpolate depth using barycentric coordinates
    if z < depth_buffer[x][y]:
        depth_buffer[x][y] = z
        color_buffer[x][y] = interpolated color

Triangles can be drawn in any order — the depth buffer ensures the correct result regardless. This is why it was such a breakthrough when Catmull invented it in 1974.

Depth Precision

Remember from the projection article that depth is stored as 1/z, not linearly. This means:

  • Near objects get lots of depth precision
  • Far objects get very little
  • Two distant surfaces might map to the same depth value → Z-fighting

Practical fixes: keep the near plane as far as possible, use a reversed depth buffer (maps near=1, far=0 for better float precision), or use a logarithmic depth buffer.

Interactive

Z-buffer demo

Draw order: Red triangle (closer) → Blue triangle (farther)

The Scanline Algorithm

The bounding-box approach works but wastes time testing many pixels outside the triangle. The classic scanline algorithm is smarter — it processes the triangle one horizontal row at a time, computing the exact start and end x-coordinate for each row.

How It Works

  1. Sort the three vertices by Y coordinate
  2. For each scanline (row of pixels) between the top and bottom vertex:
    • Compute where the scanline intersects the left and right edges
    • Fill all pixels between those two intersections

This was the dominant algorithm in software renderers before GPUs, and it's still used in some CPU-based renderers and font rasterizers.

Perspective-Correct Interpolation

There's a subtle trap: linearly interpolating attributes in screen space produces incorrect results after perspective projection. Texture coordinates interpolated linearly in 2D will warp and swim.

The fix is perspective-correct interpolation. Instead of interpolating attr directly, interpolate attr/w and 1/w separately, then divide:

            lambda0 * (a0/w0) + lambda1 * (a1/w1) + lambda2 * (a2/w2)
attr(P) =  ─────────────────────────────────────────────────────────────
            lambda0 * (1/w0)  + lambda1 * (1/w1)  + lambda2 * (1/w2)

This accounts for the nonlinear relationship between screen position and world-space depth. Every GPU does this automatically, but if you're writing a software renderer, you need to handle it yourself.

Fill Rules

What happens when a pixel lies exactly on an edge shared by two triangles? If both triangles claim the pixel, it gets drawn twice (overdraw, blending errors). If neither claims it, there's a gap.

The top-left fill rule (used by Direct3D and OpenGL) solves this: a pixel on an edge is included only if the edge is a "top edge" (exactly horizontal, above the triangle) or a "left edge" (going upward). This guarantees every pixel along a shared edge belongs to exactly one triangle.

Clipping

Triangles that extend beyond the screen — or behind the camera — need to be clipped. This typically happens in clip space (before the perspective divide) against the six planes of the view frustum.

A triangle that partially extends outside a clipping plane is split into smaller triangles that fit entirely within. The Sutherland-Hodgman algorithm handles this efficiently.

Putting It All Together

Here's the complete rasterization pipeline for one triangle:

1. Project vertices to screen space (MVP + perspective divide + viewport)
2. Compute bounding box
3. For each pixel in the bounding box:
   a. Compute edge functions / barycentric coordinates
   b. If inside (all three >= 0):
      - Interpolate depth (perspective-correct)
      - Depth test against Z-buffer
      - If passes: interpolate attributes, write color + depth

Modern GPUs parallelize this massively — thousands of pixels tested simultaneously. But the fundamental algorithm is exactly what we've described.

What's Next

We can now turn triangles into colored pixels. But flat-colored triangles look terrible — they need lighting and shading to look three-dimensional.