---
title: "Computer Graphics: From Triangles to Pixels"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 31
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/31-computer-graphics-from-triangles-to-pixels
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 31 — Computer Graphics: From Triangles to Pixels

A picture on a screen is a grid of pixels, and a three-dimensional scene is a list of triangles in space. Computer graphics turns the second into the first. Each triangle is moved into place, seen through a camera, projected onto the screen and broken into the pixels it covers; where two triangles cover the same pixel, the nearer one wins; each pixel then receives a colour from the light that falls on the surface. The chapter writes every step in a few dozen lines of C, with no graphics library, and writes its images to files: a cube’s corners through the whole chain of matrices, a rasteriser in exact integers whose fill rule draws every pixel of a mesh exactly once, a [depth buffer](#def-b3-computer-graphics-visibility), two kinds of shading, and a small scene traced ray by ray.

**You already know.**

Vectors, the dot and cross products, matrices and their products, and the composition of linear maps come from the mathematics volumes, as do barycentres and barycentric coordinates: a point of a triangle $ABC$ is $\lambda_A A + \lambda_B B + \lambda_C C$ with $\lambda_A + \lambda_B + \lambda_C = 1$, and the coordinates are ratios of signed areas. An image is a grid of pixels, each with a red, a green and a blue intensity (grade 10 volume). Floating-point numbers round, and two computations of the same value can differ in their last bits (grade 10 volume). Structures, fixed-size arrays and integers in C come from the Year 1 and Year 2 volumes.

## 31.1 Coordinates and transformations

A cube of side 2 centred at the origin has the eight corners $(\pm1, \pm1, \pm1)$. To show it, the program must turn it, place it in front of a camera, and find where each corner lands on a screen of $320 \times 240$ pixels. Turning is a linear map, a $3 \times 3$ matrix; placing is a translation, which is not linear, since it moves the origin. One more coordinate makes both of them matrices.

**Definition 31.1 (Homogeneous coordinates).**

The *homogeneous coordinates* of a point $(x, y, z)$ of space are $(x, y, z, 1)$, and those of a direction $(x, y, z)$ are $(x, y, z, 0)$. More generally, $(x, y, z, w)$ with $w \neq 0$ stands for the point $(x/w, y/w, z/w)$: all non-zero multiples of a 4-vector stand for the same point.

In [homogeneous coordinates](#def-b3-computer-graphics-homogeneous) the translation by $(t_x, t_y, t_z)$ and the rotation by an angle $a$ about the $y$ axis are

$$
T = \begin{pmatrix} 1 & 0 & 0 & t_x \\ 0 & 1 & 0 & t_y \\ 0 & 0 & 1 & t_z \\ 0 & 0 & 0 & 1 \end{pmatrix},
\qquad
R_y(a) = \begin{pmatrix} \cos a & 0 & \sin a & 0 \\ 0 & 1 & 0 & 0 \\ -\sin a & 0 & \cos a & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix}.
$$

$T$ adds $w$ times $(t_x, t_y, t_z)$: it moves a point, whose $w$ is 1, and leaves a direction, whose $w$ is 0, as it was, which is right, since a direction has no position to move. A scaling by the factors $(s_x, s_y, s_z)$ is the diagonal matrix of entries $s_x, s_y, s_z, 1$. A product of such matrices applies the right-hand factor first: $T R_y(a)$ turns a point, then moves it, and the order matters, since $R_y(a) T$ moves it first and then turns it about the origin, with the translation turned too (Exercise [31.5](#exo-b3-computer-graphics-5)).

**Definition 31.2 (Model transform, view transform, projection matrix).**

The *model transform* of an object is the matrix that takes the coordinates in which the object was modelled to the coordinates of the scene. The *view transform* takes scene coordinates to camera coordinates, in which the camera sits at the origin and looks down the negative $z$ axis, with $y$ up. The *projection matrix* takes camera coordinates to clip coordinates, a 4-vector whose division by its last coordinate gives the position on the screen and a depth.

![The chain that takes a corner of the cube to a pixel. The three matrices multiply into one, PVM; the division by w and the viewport are applied to each point after it.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-computer-graphics/fig-6830c5a65e11.svg)

*The chain that takes a corner of the cube to a pixel. The three matrices multiply into one, $PVM$; the division by $w$ and the viewport are applied to each point after it.*

The chain is the same for every vertex of every object; only $M$ changes from object to object, and $V$ when the camera moves. Interactive computer graphics goes back to Sketchpad, the drawing program that Ivan Sutherland wrote in 1963.

### Perspective

In camera coordinates, a point at height $y$ and distance $d = -z$ in front of the camera is seen in the direction of slope $y/d$: twice as far, it must be twice as high to be seen in the same direction. This division by the distance is perspective.

![A side view of the camera. A point at height y and distance d is seen where its line of sight crosses the plane d = 1, at height y/d, by similar triangles. The dashed lines bound the field of view, of angle ; with the near and far planes they bound the volume the camera shows.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-computer-graphics/fig-c6431c491cee.svg)

*A side view of the camera. A point at height $y$ and distance $d$ is seen where its line of sight crosses the plane $d = 1$, at height $y/d$, by similar triangles. The dashed lines bound the field of view, of angle $\theta$; with the near and far planes they bound the volume the camera shows.*

**Definition 31.3 (Perspective projection, view frustum, perspective division).**

A *perspective projection* maps a point of camera coordinates at distance $d = -z$ in front of the camera to the screen position $(x/d, y/d)$, scaled so that the edges of the field of view map to $\pm1$. The *view frustum* is the truncated pyramid of points that the camera shows: inside the field of view, between a near plane $d = n$ and a far plane $d = f$. The [projection matrix](#def-b3-computer-graphics-transforms) leaves the division undone: it puts $d$ into the fourth coordinate $w$, and the *perspective division* divides by it, giving the normalised device coordinates (NDC), each in $[-1, 1]$ inside the frustum.

With the vertical field of view $\theta$, the aspect ratio $\alpha$ (width over height) and $c = 1/\tan(\theta/2)$, the [projection matrix](#def-b3-computer-graphics-transforms) is

$$
P = \begin{pmatrix} c/\alpha & 0 & 0 & 0 \\ 0 & c & 0 & 0 \\ 0 & 0 & \dfrac{f + n}{n - f} & \dfrac{2fn}{n - f} \\ 0 & 0 & -1 & 0 \end{pmatrix}.
$$

An orthographic projection, for technical drawings, skips the division: it scales $x$ and $y$ directly, so that parallel lines stay parallel and far objects keep their size; its last row is $(0, 0, 0, 1)$. The perspective matrix’s last row puts $w = -z = d$. Its first two rows scale $x$ and $y$ so that, after the division, the top of the field of view, where $y/d = \tan(\theta/2)$, lands at $1$. Its third row gives the depth $\bigl((f+n)/(f-n)\bigr) - \bigl(2fn/(f-n)\bigr)/d$ after the division: $-1$ on the near plane, $+1$ on the far plane, and growing with $d$ in between, which is all a depth test needs. The listing writes it in C, with $m[i][j]$ the entry of row $i$ and column $j$.

```cpp
// Perspective projection: camera at the origin looking down -z, vertical field of view
// fovy, z = -near and z = -far mapped to depths -1 and +1 after division by w = -z.
static inline mat4 perspective(double fovy, double aspect, double near, double far) {
    double f = 1.0 / tan(fovy / 2);
    mat4 r = {{{0}}};
    r.m[0][0] = f / aspect;
    r.m[1][1] = f;
    r.m[2][2] = (far + near) / (near - far);
    r.m[2][3] = 2 * far * near / (near - far);
    r.m[3][2] = -1;
    return r;
}
```

***Listing 31.1.** The [projection matrix](#def-b3-computer-graphics-transforms), as in the formula above. The other functions of `vec.h`, all a few lines long, are the vector operations, the product of matrices and the translation and rotation matrices. code/bachelor-3/31-computer-graphics/listings/vec.h*

The program below sends the eight corners through the whole chain. The cube is turned by $20^\circ$ about $x$, then by $30^\circ$ about $y$, then pushed 6 units in front of the camera; the camera has a field of view of $60^\circ$, the aspect ratio $4/3$, and the planes $n = 1$ and $f = 20$. The viewport, the last step, maps $x_{\mathrm{NDC}} \in [-1, 1]$ to $[0, 320]$ and $y_{\mathrm{NDC}}$ to $[240, 0]$, since rows of pixels are counted from the top.

```c
int main(void) {
    mat4 model = matmul(translate(0, 0, -6), matmul(rotate_y(PI / 6), rotate_x(PI / 9)));
    mat4 view = identity();  // the camera stays at the origin, looking down -z
    mat4 proj = perspective(PI / 3, 4.0 / 3.0, 1, 20);
    mat4 mvp = matmul(proj, matmul(view, model));
    printf("corner        clip (x, y, z, w)               NDC (x, y, z)        pixel\n");
    for (int i = 0; i < 8; i++) {
        vec4 p = {i & 1 ? 1 : -1, i & 2 ? 1 : -1, i & 4 ? 1 : -1, 1};
        vec4 c = apply(mvp, p);
        double nx = c.x / c.w, ny = c.y / c.w, nz = c.z / c.w;  // perspective division
        double px = (nx + 1) / 2 * 320, py = (1 - ny) / 2 * 240;  // viewport: y down
        printf("(%2.0f,%2.0f,%2.0f)  (%6.3f,%6.3f,%6.3f,%6.3f)  (%6.3f,%6.3f,%6.3f)  (%5.1f,%5.1f)\n",
               p.x, p.y, p.z, c.x, c.y, c.z, c.w, nx, ny, nz, px, py);
    }
    return 0;
}
```

***Listing 31.2.** The eight corners through the model, view and projection matrices, the [perspective division](#def-b3-computer-graphics-projection) and the viewport. The view matrix is the identity: the camera stays where camera coordinates put it. code/bachelor-3/31-computer-graphics/listings/transform.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o transform transform.c -lm && ./transform
corner        clip (x, y, z, w)               NDC (x, y, z)        pixel
(-1,-1,-1)  (-1.957,-1.035, 5.201, 6.610)  (-0.296,-0.157, 0.787)  (112.6,138.8)
( 1,-1,-1)  ( 0.293,-1.035, 6.306, 7.610)  ( 0.038,-0.136, 0.829)  (166.1,136.3)
(-1, 1,-1)  (-1.513, 2.220, 4.546, 6.018)  (-0.251, 0.369, 0.755)  (119.8, 75.7)
( 1, 1,-1)  ( 0.737, 2.220, 5.651, 7.018)  ( 0.105, 0.316, 0.805)  (176.8, 82.0)
(-1,-1, 1)  (-0.737,-2.220, 3.402, 4.982)  (-0.148,-0.446, 0.683)  (136.3,173.5)
( 1,-1, 1)  ( 1.513,-2.220, 4.507, 5.982)  ( 0.253,-0.371, 0.753)  (200.5,164.5)
(-1, 1, 1)  (-0.293, 1.035, 2.747, 4.390)  (-0.067, 0.236, 0.626)  (149.3, 91.7)
( 1, 1, 1)  ( 1.957, 1.035, 3.852, 5.390)  ( 0.363, 0.192, 0.715)  (218.1, 97.0)
```

***Output 31.1.** The corners, with $w$ between 4.39 and 7.61: their distances from the camera. The nearest corner, $(-1, 1, 1)$, has the smallest depth, 0.626.*

The first corner checks by hand: its $w$ is its distance, 6.610, and its depth is $(21 - 40/6.610)/19 = 0.787$. The four corners with $z = 1$ in the cube’s own coordinates have $w$ from 4.39 to 5.98, against 6.02 to 7.61 for the other four, and their pixels spread over 82 columns, against 64 for the far face: perspective makes the near face look bigger.

## 31.2 Rasterisation

Once its three corners are pixels, a triangle must be broken into the pixels it covers. The test for one pixel uses three signed areas.

**Definition 31.4 (Rasterisation, edge function, top-left rule).**

*Rasterisation* is the computation of the set of pixels that a shape covers; a pixel is covered by a triangle when its centre is inside the triangle. The *edge function* of the directed edge from $a$ to $b$ is

$$
E_{ab}(p) = (b_x - a_x)(p_y - a_y) - (b_y - a_y)(p_x - a_x),
$$

twice the signed area of the triangle $(a, b, p)$; it is zero on the line $ab$ and has opposite signs on its two sides. The *top-left rule* decides the centres that lie exactly on an edge: such a centre is drawn only if the edge is a top edge, horizontal with the triangle below it, or a left edge, with the triangle to its right.

With $y$ pointing down the screen and a triangle $(a, b, c)$ listed clockwise, the three [edge functions](#def-b3-computer-graphics-raster) $E_{ab}$, $E_{bc}$ and $E_{ca}$ are all positive inside the triangle, and their sum at any point is $E_{ab}(c)$, twice the area: divided by it, they are the barycentric coordinates of the point. Juan Pineda described [rasterisation](#def-b3-computer-graphics-raster) by [edge functions](#def-b3-computer-graphics-raster) in 1988, as a test that every pixel can run at the same time; the older line-drawing algorithm of Bresenham, from 1965, was written for a digital plotter.

The rasteriser below works in exact integers: coordinates are counted in sixteenths of a pixel, so that the centre of pixel $(i, j)$ is $(16i + 8, 16j + 8)$, and an [edge function](#def-b3-computer-graphics-raster) is a product of integers, exactly zero when a centre is on an edge. With floating-point numbers, the same centre could fall on one side of an edge for one triangle and on the other side for its neighbour.

```cpp
// Twice the signed area of (a, b, p): positive when p is to the right of a -> b on a
// screen whose y points down, that is inside a triangle listed clockwise.
static inline long edge(pt a, pt b, pt p) {
    return (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
}

// For a clockwise triangle: a top edge is horizontal with the inside below it (it runs
// to the right); a left edge runs up the screen.
static inline bool top_left(pt a, pt b) {
    return (a.y == b.y && b.x > a.x) || b.y < a.y;
}

// Is p drawn as part of the triangle (a, b, c), already put in clockwise order?
// rule 1: the top-left rule; rule 0: the naive test, every point with w >= 0.
static inline bool inside(pt a, pt b, pt c, pt p, int rule) {
    long w[3] = {edge(a, b, p), edge(b, c, p), edge(c, a, p)};
    pt from[3] = {a, b, c}, to[3] = {b, c, a};
    for (int k = 0; k < 3; k++) {
        if (w[k] < 0) return false;
        if (w[k] == 0 && rule == 1 && !top_left(from[k], to[k])) return false;
    }
    return true;
}
```

***Listing 31.3.** The [edge function](#def-b3-computer-graphics-raster) and the two tests: the naive one draws every centre with $E \geq 0$ for the three edges; the [top-left rule](#def-b3-computer-graphics-raster) refuses a centre on an edge that is neither top nor left. code/bachelor-3/31-computer-graphics/listings/raster.h*

The programs of this chapter test every pixel of the image, which keeps them short; a rasteriser tests only the pixels of the triangle’s bounding box, the smallest rectangle of pixels around its three corners. For a clockwise triangle on a screen whose $y$ points down, an edge running up the screen has the inside on its right, which is the triangle’s left edge; a horizontal edge running to the right has the inside below it, which is its top edge. That is all `top_left` tests. `raster.c` draws one triangle, of corners $(3.2, 2.5)$, $(28.7, 9.1)$ and $(9.4, 21.8)$, on a grid of $32 \times 24$ pixels, as text. The corners are rounded to sixteenths of a pixel first, to $(3.1875, 2.5)$, $(28.6875, 9.125)$ and $(9.375, 21.8125)$, and the area it prints is that of the rounded triangle, 225.74 against 225.615 for the corners as given.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o raster raster.c -lm && ./raster
................................
................................
................................
....###.........................
....#######.....................
....###########.................
....###############.............
.....#################..........
.....#####################......
.....#######################....
......#####################.....
......###################.......
......##################........
.......###############..........
.......##############...........
.......############.............
........#########...............
........########................
........######..................
.........####...................
.........##.....................
.........#......................
................................
................................
226 pixels drawn, triangle area 225.74 pixels
```

***Output 31.2.** One triangle rasterised: a pixel is drawn, `#`, when its centre is inside. The count of pixels is close to the area, without being equal to it.*

The edge between two triangles of a mesh is where the rule matters. `shared_edge.c` splits a $9 \times 6$ square, whose corners are pixel centres, along its diagonal, and marks each pixel with the triangle that drew it: 1, 2, or X for both.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o shared_edge shared_edge.c -lm && ./shared_edge
naive test, w >= 0:
............
.X111111111.
.2211111111.
.222X111111.
.2222211111.
.222222X111.
.2222222211.
.222222222X.
............
drawn twice: 4, square pixels missed: 0
top-left rule:
............
.111111111..
.221111111..
.222111111..
.222221111..
.222222111..
.222222221..
............
............
drawn twice: 0, square pixels missed: 0
```

***Output 31.3.** The naive test draws the four centres on the diagonal twice, and also the right column and the bottom row, which belong to the next squares of a mesh. The [top-left rule](#def-b3-computer-graphics-raster) draws each of the $9 \times 6 = 54$ pixels of the square exactly once.*

![The top-left rule on a triangle drawn with y up for reading. Dots are pixel centres. Of the centres on the triangle’s edges, those on the top and left edges are drawn, filled, and those on the right edge are not, hollow: the neighbour across that edge draws them. A corner is drawn only if both its edges are top or left: a is, b and c are not.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-computer-graphics/fig-0f4b96fec4a3.svg)

*The [top-left rule](#def-b3-computer-graphics-raster) on a triangle drawn with $y$ up for reading. Dots are pixel centres. Of the centres on the triangle’s edges, those on the top and left edges are drawn, filled, and those on the right edge are not, hollow: the neighbour across that edge draws them. A corner is drawn only if both its edges are top or left: $a$ is, $b$ and $c$ are not.*

The rule draws each centre on a shared edge once because the two triangles run along it in opposite directions: an edge that runs up the screen for one runs down for the other, so it is a left edge for exactly one of them; a horizontal edge has the inside below it for exactly one of them. Exercise [31.10](#exo-b3-computer-graphics-10) proves it, and the weekend problem counts the pixels of whole meshes.

## 31.3 Visibility

Where two triangles cover the same pixel, the pixel shows the nearer one. Sorting the triangles from far to near and drawing them in that order, the painter’s way, fails when two triangles cross: each is in front of the other in part of the image. The [depth buffer](#def-b3-computer-graphics-visibility) decides pixel by pixel.

**Definition 31.5 (Depth buffer, back-face culling).**

A *depth buffer*, or z-buffer, holds one depth per pixel, initialised to the far plane; a triangle’s pixel is drawn only if its depth at that pixel is smaller than the one stored, which it then replaces. *Back-face culling* drops, before [rasterisation](#def-b3-computer-graphics-raster), every triangle of a closed surface that faces away from the camera; with the triangles of every surface listed in the same order seen from outside, it is the triangles whose screen order is reversed.

The z-buffer was first described in 1974 by Wolfgang Straßer, in his doctoral thesis, and the same year by Edwin Catmull, to whom it is most often attributed. The depth of a pixel inside a triangle is interpolated from the depths of its corners with the pixel’s barycentric coordinates, the [edge functions](#def-b3-computer-graphics-raster) divided by twice the area. In NDC the depth is an affine function of the screen position over a flat triangle, so the interpolation is exact (Exercise [31.11](#exo-b3-computer-graphics-11)).

```c
static void draw(int id, vertex v[3], const double colour[3]) {
    vertex u[3] = {v[0], v[1], v[2]};
    pt a = fixed(u[0].x, u[0].y), b = fixed(u[1].x, u[1].y), c = fixed(u[2].x, u[2].y);
    if (edge(a, b, c) < 0) {  // clockwise order; each depth stays with its vertex
        pt t = b;
        b = c, c = t;
        vertex s = u[1];
        u[1] = u[2], u[2] = s;
    }
    double area = (double)edge(a, b, c);
    for (int j = 0; j < H; j++)
        for (int i = 0; i < W; i++) {
            pt p = centre(i, j);
            if (!inside(a, b, c, p, 1)) continue;
            double l0 = edge(b, c, p) / area, l1 = edge(c, a, p) / area, l2 = 1 - l0 - l1;
            double z = l0 * u[0].z + l1 * u[1].z + l2 * u[2].z;  // barycentric depth
            covers[j][i] |= id;
            if (z < depth[j][i]) {  // nearer than what is there: draw it
                depth[j][i] = z, front[j][i] = id;
                for (int k = 0; k < 3; k++) image[j][i][k] = colour[k] * (1.1 - z);
            }
        }
}
```

***Listing 31.4.** Drawing one triangle into the [depth buffer](#def-b3-computer-graphics-visibility). The corners are put in clockwise order with their depths; each covered pixel gets its interpolated depth, and is drawn if it is nearer than what is there. code/bachelor-3/31-computer-graphics/listings/zbuffer.c*

`zbuffer.c` draws two triangles that cross: a red one whose depth goes from 0.2 on its left to 0.8 on the right, and a blue one going the other way.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o zbuffer zbuffer.c -lm && ./zbuffer
pixels covered by red only 2784, blue only 2236, both 3486, neither 10694
where both cover a pixel: red in front at 1830, blue at 1656
```

***Output 31.4.** Of the 3,486 pixels covered by both triangles, the red one is in front at 1,830 and the blue one at 1,656: neither triangle is in front of the other.*

![The image that zbuffer.c writes: the two triangles cross along the line where their depths are equal, and each is darker where it is farther. No order of drawing the two whole triangles would give this picture.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-computer-graphics/img-c99e4ac4cb63.jpg)

*The image that `zbuffer.c` writes: the two triangles cross along the line where their depths are equal, and each is darker where it is farther. No order of drawing the two whole triangles would give this picture.*

[Back-face culling](#def-b3-computer-graphics-visibility) halves the work for a closed object: a cube shows at most three faces, and its other three are hidden by the first ones, so they need not be rasterised at all (Exercise [31.6](#exo-b3-computer-graphics-6)). It does not replace the [depth buffer](#def-b3-computer-graphics-visibility), which must still order the faces that remain, and the faces of other objects.

## 31.4 Shading

The colour of a pixel depends on the light that leaves the surface towards the eye. Three terms give a usable picture: a constant ambient term for light coming from everywhere; a diffuse term for a matt surface, which scatters light equally in all directions; and a specular term for a shiny one, which sends it mainly in the mirror direction. For a surface of unit normal $\mathbf n$, lit from the unit direction $\mathbf L$ and seen from the unit direction $\mathbf V$, the diffuse term is proportional to $\max(0, \mathbf n \cdot \mathbf L)$, the cosine of the angle of incidence, and the specular term to $\max(0, \mathbf r \cdot \mathbf V)^s$, where $\mathbf r = 2(\mathbf n \cdot \mathbf L)\mathbf n - \mathbf L$ is the mirror image of $\mathbf L$ about the normal and the shininess $s$ narrows the highlight as it grows. Bui Tuong Phong published this reflection model in 1975.

```c
// The light leaving a point of normal n towards the viewer at +z: ambient, diffuse
// (Lambert: proportional to the cosine n.L) and specular (Phong: the reflected light
// direction r against the view direction, raised to a shininess).
static vec3 light(vec3 n) {
    vec3 l = unit(v3(-1, 1, 1)), view = v3(0, 0, 1), base = v3(0.9, 0.55, 0.2);
    double diffuse = dot(n, l) > 0 ? dot(n, l) : 0;
    vec3 r = sub(mul(n, 2 * dot(n, l)), l);
    double specular = diffuse > 0 && dot(r, view) > 0 ? pow(dot(r, view), 40) : 0;
    return add(mul(base, 0.08 + 0.75 * diffuse), mul(v3(1, 1, 1), 0.6 * specular));
}
```

***Listing 31.5.** The light leaving a point of normal `n`: an ambient term 0.08, a diffuse term of weight 0.75, and a white specular term of weight 0.6 with the shininess 40. The light comes from the upper left, the viewer looks down $-z$. code/bachelor-3/31-computer-graphics/listings/shade.c*

**Definition 31.6 (Lambertian shading, Gouraud shading, Phong shading).**

*Lambertian shading* colours a point in proportion to $\max(0, \mathbf n \cdot \mathbf L)$, as a matt surface that scatters light equally in every direction. *Gouraud shading* computes the light at the vertices of each triangle, with the vertex normals, and interpolates the colours across the triangle. *Phong shading* interpolates the normals instead, renormalises them, and computes the light at every pixel.

Henri Gouraud published his interpolation in 1971. `shade.c` lights the front half of a sphere both ways. On the left, the half-sphere is a mesh of $8 \times 8$ cells of two triangles each, lit at its vertices and interpolated; on the right, each pixel takes the sphere’s exact normal, which is what [Phong shading](#def-b3-computer-graphics-shading) approaches as it interpolates the vertex normals of a fine enough mesh. The brightest point should be where $\mathbf r = \mathbf V$, that is where the normal is the unit vector halfway between $\mathbf L$ and $\mathbf V$.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o shade shade.c -lm && ./shade
Gouraud:   brightest pixel ( 55,  53), green 0.806
per pixel: brightest pixel (217,  57), green 1.008
highlight expected where n = (L + V)/|L + V|: pixel (216.7, 56.7)
```

***Output 31.5.** The brightest pixel of each half, by its green intensity. Per pixel, the highlight is where the formula puts it, and reaches 1.008 before clipping to 1; the interpolated mesh peaks at 0.806 elsewhere.*

![The two halves of shade.c. On the left, the highlight falls between vertices and is smeared over a few triangles, whose edges show in the shading; on the right, it is a small bright spot.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-computer-graphics/img-68538a169314.jpg)

*The two halves of `shade.c`. On the left, the highlight falls between vertices and is smeared over a few triangles, whose edges show in the shading; on the right, it is a small bright spot.*

The left half shows the weakness of [Gouraud shading](#def-b3-computer-graphics-shading): a highlight narrower than a triangle is lost if no vertex sees it, and drawn too wide if one does. The cost is the reason it was used: the light is computed once per vertex instead of once per pixel.

**In practice.**

The images of this chapter are written by the C programs themselves, as binary PPM files: the two characters `P6`, the width, the height and the maximum value 255 in ASCII decimal, then three bytes per pixel, row by row. A Python script of under 60 lines then writes each one as a PNG file, which is what the book prints: the 8-byte signature, then chunks, each with its length, its four-letter type, its data and a CRC computed over the type and the data, from the header chunk `IHDR` to the end chunk `IEND`, with the pixels compressed by `zlib` in between. A test decodes every PNG back and compares it with the PPM, pixel for pixel. Before storing, `ppm.h` raises each intensity $v \in [0, 1]$ to the power $1/2.2$, a gamma encoding, and rounds $255\,v^{1/2.2}$ to a byte.

## 31.5 Ray tracing

[Rasterisation](#def-b3-computer-graphics-raster) starts from the triangles and asks which pixels they cover. [Ray tracing](#def-b3-computer-graphics-rays) starts from the pixels and asks what each one sees.

**Definition 31.7 (Ray tracing, primary ray, shadow ray).**

*Ray tracing* computes the colour of each pixel by following rays of light backwards, from the eye into the scene. The *primary ray* of a pixel starts at the eye and passes through the pixel; its colour is that of the nearest surface it meets. A *shadow ray* starts at a point of a surface and goes towards a light: if it meets a surface before the light, the point is in shadow.

A ray is $o + t\mathbf d$, with origin $o$, unit direction $\mathbf d$ and $t > 0$. It meets the sphere of centre $c$ and radius $r$ where $|o + t\mathbf d - c|^2 = r^2$; with $\mathbf v = o - c$ and $b = \mathbf v \cdot \mathbf d$, that is the quadratic $t^2 + 2bt + |\mathbf v|^2 - r^2 = 0$, whose roots are $t = -b \pm \sqrt{b^2 - |\mathbf v|^2 + r^2}$. A negative discriminant means a miss; otherwise the smaller positive root is the visible hit. A ray meets the floor plane $y = y_0$ at $t = (y_0 - o_y)/d_y$.

![A primary ray from the eye o meets a sphere at t_1 and t_2; the nearer, t_1, is seen. The point t = -b is the foot of the perpendicular from the centre. From the hit, a shadow ray goes to the light; the normal n points from the centre through the hit.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-computer-graphics/fig-ba2b4124d9a6.svg)

*A [primary ray](#def-b3-computer-graphics-rays) from the eye $o$ meets a sphere at $t_1$ and $t_2$; the nearer, $t_1$, is seen. The point $t = -b$ is the foot of the perpendicular from the centre. From the hit, a [shadow ray](#def-b3-computer-graphics-rays) goes to the light; the normal $\mathbf n$ points from the centre through the hit.*

The scene of `rt.h` has three spheres over a checkered floor and one point light. `trace` finds the nearest hit, sends a [shadow ray](#def-b3-computer-graphics-rays) from just off the surface, and lights the point by Lambert’s term if the light is not blocked; its last lines trace a reflected ray when a depth budget remains, which Exercise [31.12](#exo-b3-computer-graphics-12) uses.

```cpp
static vec3 trace(vec3 o, vec3 d, int depth, counts *n) {
    int what;
    double t = nearest(o, d, &what);
    n->ends[what + 1]++;
    if (t < 0) return v3(0.75, 0.85, 1.0);  // the sky
    vec3 p = add(o, mul(d, t)), normal, colour;
    double mirror;
    if (what == 3) {
        normal = v3(0, 1, 0), mirror = 0;
        int check = ((long)floor(p.x) + (long)floor(p.z)) & 1;
        colour = check ? v3(0.85, 0.85, 0.85) : v3(0.35, 0.35, 0.35);
    } else {
        normal = unit(sub(p, scene[what].centre));
        colour = scene[what].colour, mirror = scene[what].mirror;
    }
    vec3 to_light = sub(LIGHT, p);
    double dist = sqrt(dot(to_light, to_light));
    vec3 l = mul(to_light, 1 / dist);
    vec3 start = add(p, mul(normal, 1e-6));  // just off the surface
    int blocker;
    n->shadow++;
    double tb = nearest(start, l, &blocker);
    int lit = !(tb > 0 && tb < dist && blocker != 3);
    double diffuse = lit && dot(normal, l) > 0 ? dot(normal, l) : 0;
    vec3 c = mul(colour, 0.1 + 0.9 * diffuse);
    if (depth > 0 && mirror > 0) {
        n->reflected++;
        vec3 r = sub(d, mul(normal, 2 * dot(d, normal)));
        c = add(mul(c, 1 - mirror), mul(trace(start, r, depth - 1, n), mirror));
    }
    return c;
}
```

***Listing 31.6.** Tracing one ray: the nearest hit, its normal and colour, a [shadow ray](#def-b3-computer-graphics-rays) to the light, then, for a mirror and a depth left, the reflected ray, traced the same way. `hit_sphere` solves the quadratic above. code/bachelor-3/31-computer-graphics/listings/rt.h*

`raytrace.c` sends one [primary ray](#def-b3-computer-graphics-rays) through the centre of each pixel of a $320 \times 240$ image, from a camera at the origin with the same field of view of $60^\circ$ as before, and with no reflection.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o raytrace raytrace.c -lm && ./raytrace
primary rays 76800, shadow rays 45170, reflected rays 0
rays ending: sky 31630, red 3686, green 2661, blue 6074, floor 32749
```

***Output 31.6.** One [primary ray](#def-b3-computer-graphics-rays) per pixel, and one [shadow ray](#def-b3-computer-graphics-rays) for each [primary ray](#def-b3-computer-graphics-rays) that meets something: $76{,}800 - 31{,}630 = 45{,}170$.*

![The image that raytrace.c writes. Shadows on the floor and on the spheres come from the shadow rays; the light is to the upper left.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-computer-graphics/img-c25f95a4736e.jpg)

*The image that `raytrace.c` writes. Shadows on the floor and on the spheres come from the [shadow rays](#def-b3-computer-graphics-rays); the light is to the upper left.*

Turner Whitted showed in 1980 how to trace recursive rays for mirror reflection and refraction, which is what the last lines of `trace` do for reflection. The cost of [ray tracing](#def-b3-computer-graphics-rays) is in the search for the nearest hit: each ray here tests three spheres and a plane, but a scene of many thousands of triangles keeps them in a tree of bounding boxes, so that a ray tests only the few triangles near its path. [Rasterisation](#def-b3-computer-graphics-raster) pays per triangle, [ray tracing](#def-b3-computer-graphics-rays) per pixel and per ray; shadows and reflections, which a rasteriser must fake, come to a ray tracer from the same function called once more.

## 31.6 Exercises

**Exercise 31.1 ★.**

Compute $T(2, 0, 0)$ applied to the point $(1, 1, 1)$ and to the direction $(1, 1, 1)$, in [homogeneous coordinates](#def-b3-computer-graphics-homogeneous), and $R_y(\pi/2)$ applied to the point $(1, 0, 0)$. Which way does $R_y(\pi/2)$ turn the $x$ axis, seen from above?

**Solution of Exercise 31.1.**

$T(2, 0, 0)(1, 1, 1, 1) = (3, 1, 1, 1)$: the point moves by 2 along $x$. $T(2, 0, 0)(1, 1, 1, 0) = (1, 1, 1, 0)$: the last column is multiplied by $w = 0$, and the direction is unchanged. $R_y(\pi/2)(1, 0, 0, 1) = (\cos\frac\pi2, 0, -\sin\frac\pi2, 1) = (0, 0, -1, 1)$: the $x$ axis turns to the $-z$ axis, which, seen from above with $y$ towards the viewer, is a quarter turn counterclockwise. A test checks the three products.

**Exercise 31.2 ★.**

With the camera of `transform.c`, find the NDC height of the points $(0, 1, -2)$ and $(0, 2, -4)$ of camera coordinates, and the row of pixels on which they land. Why must they land on the same pixel?

**Solution of Exercise 31.2.**

With $\theta = 60^\circ$, $c = 1/\tan 30^\circ = \sqrt3$. Both points have $y/d = 1/2$, so $y_{\mathrm{NDC}} = \sqrt3/2 \approx 0.866$ for both, and the viewport puts them on the row $(1 - 0.866)/2 \times 240 = 16.1$, inside row 16. They lie on the same line of sight from the camera, the second twice as far and twice as high: the camera cannot tell them apart, only the depth can, and it is $1/19$ for the first and $(21 - 10)/19 = 11/19$ for the second. A test checks both NDC heights.

**Exercise 31.3 ★.**

Take $a = (0, 0)$, $b = (8, 0)$ and $c = (0, 8)$ on a screen whose $y$ points down. Is $(a, b, c)$ clockwise? Compute $E_{ab}$, $E_{bc}$ and $E_{ca}$ at $p = (2, 3)$, their sum, and the barycentric coordinates of $p$. Show that the sum of the three [edge functions](#def-b3-computer-graphics-raster) is the same at every point.

**Solution of Exercise 31.3.**

$E_{ab}(c) = (8 - 0)(8 - 0) - (0 - 0)(0 - 0) = 64 > 0$: clockwise on a screen whose $y$ points down. At $p = (2, 3)$: $E_{ab} = 8 \cdot 3 - 0 = 24$, $E_{bc} = (0 - 8)(3 - 0) - (8 - 0)(2 - 8) = -24 + 48 = 24$, $E_{ca} = (0 - 0)(3 - 8) - (0 - 8)(2 - 0) = 16$. The sum is $64 = E_{ab}(c)$. Each [edge function](#def-b3-computer-graphics-raster), divided by 64, is the barycentric coordinate of the vertex opposite its edge: $\lambda_c = 24/64$, $\lambda_a = 24/64$, $\lambda_b = 16/64$, and indeed $\frac38 a + \frac14 b + \frac38 c = (2, 3)$. Each $E$ is affine in $p$; in the sum, the coefficient of $p_x$ is $-(b_y - a_y) - (c_y - b_y) - (a_y - c_y) = 0$, and that of $p_y$ is 0 the same way, so the sum is a constant, its value at $p = c$, where two of the terms vanish: $E_{ab}(c)$. A test checks the four values.

**Exercise 31.4 ★.**

Rasterise by hand, with the [top-left rule](#def-b3-computer-graphics-raster), the triangle $(1, 1)$, $(7, 2)$, $(2, 6)$ on a grid of $8 \times 7$ pixels. How many pixels are drawn, against which area? One pixel centre lies exactly on an edge: which, and is it drawn?

**Solution of Exercise 31.4.**

$E_{ab}(c) = 6 \cdot 5 - 1 \cdot 1 = 29$: the triangle is clockwise, with area 14.5. Testing the 56 centres $(i + \frac12, j + \frac12)$ gives

`........` `.###....` `.#####..` `.####...` `..##....` `..#.....` `........`

15 pixels for an area of 14.5. The centre $(1.5, 3.5)$ of pixel $(1, 3)$ is on the edge from $c = (2, 6)$ to $a = (1, 1)$, at its middle. That edge runs up the screen, so it is a left edge, and the centre is drawn. A test checks the count, the area and the decision.

**Exercise 31.5 ★★.**

A spinning cube is drawn with the model matrix $R_y(a)\,T(0, 0, -6)$ instead of $T(0, 0, -6)\,R_y(a)$. Where is its centre for $a = 0, \pi/4, \pi/2, \pi$? Describe what the viewer sees, and write the rule for the order of the factors.

**Solution of Exercise 31.5.**

$R_y(a)\,T(0, 0, -6)$ moves the cube 6 units away first, then turns it about the camera’s vertical axis. Its centre $(0, 0, -6)$ becomes $(-6\sin a, 0, -6\cos a)$: $(0, 0, -6)$ at $a = 0$, $(-4.24, 0, -4.24)$ at $\pi/4$, $(-6, 0, 0)$ at $\pi/2$, level with the camera, and $(0, 0, 6)$ at $\pi$, behind it. The viewer sees the cube swing off to the left and disappear, coming back a turn later. With $T(0, 0, -6)\,R_y(a)$ the centre stays at $(0, 0, -6)$ and the cube spins in place. The rule: the factor written last acts first, so an object is turned about its own centre, then placed, $M = T R$. `exercises/ex5_drift.c` prints both centres for five angles, and a test checks the one at $\pi/4$.

**Exercise 31.6 ★★.**

Add [back-face culling](#def-b3-computer-graphics-visibility) to the cube of `transform.c`: list its 12 triangles counterclockwise seen from outside, project them, and keep those whose screen order shows their front. How many are kept? Why is culling enough to draw one convex object correctly with no [depth buffer](#def-b3-computer-graphics-visibility), and not two?

**Solution of Exercise 31.6.**

`exercises/ex6_cull.c` lists the six faces by their corners, splits each into two triangles, and keeps a triangle when its projected [edge function](#def-b3-computer-graphics-raster) is negative. A face turned towards the camera is seen from outside, counterclockwise, which on a screen whose $y$ points down gives $E < 0$; a back face is seen from inside, clockwise. Of the 12 triangles, 6 are kept: three faces. A test checks, for 24 orientations of the cube, that the kept triangles are exactly those of the faces whose outward normal points towards the camera. For one convex object culling is enough: a line of sight from the eye enters a convex body once, through one front face, so the front faces never cover each other and can be drawn in any order. With two objects, a front face of the nearer one can hide a front face of the other, and the order matters again: the [depth buffer](#def-b3-computer-graphics-visibility) is still needed. It is also needed for one object that is not convex, such as a torus, whose front faces can hide each other.

**Exercise 31.7 ★★.**

With $n = 1$ and $f = 20$, compute the NDC depth at the distances $d = 1, 2, 10, 20$. What part of the depth range $[-1, 1]$ is left to the far half of the frustum, $10 \leq d \leq 20$? A [depth buffer](#def-b3-computer-graphics-visibility) stores the depth with a fixed number of bits: where does it tell near surfaces apart best, and how does moving the near plane closer change it?

**Solution of Exercise 31.7.**

With $n = 1$ and $f = 20$ the NDC depth is $(21 - 40/d)/19$: $-1$ at $d = 1$, $1/19 \approx 0.053$ at $d = 2$, $17/19 \approx 0.895$ at $d = 10$ and $1$ at $d = 20$. The far half of the frustum keeps only $1 - 17/19 = 2/19$ of the range of length 2, that is $1/19 \approx 5.3\,\%$, while the distances from 1 to 2 use more than half of it. The depth changes at the rate $40/(19 d^2)$, so a buffer with a fixed number of levels separates surfaces finely near the camera and coarsely far away: one unit of distance at $d = 15$ moves the depth 100 times less than at $d = 1.5$, and two surfaces close together far away can round to the same stored depth and flicker in front of each other. The rate is proportional to $n$ for $n$ small against $f$: bringing the near plane from 1 to 0.1 divides the precision near the far plane by about ten. The near plane should be as far as the scene allows. A test checks the four depths.

**Exercise 31.8 ★★.**

Find by hand the pixel where the highlight of the right half of `shade.c` should be: the sphere has radius 70 pixels and centre $(240, 80)$, $\mathbf L$ is the unit vector of $(-1, 1, 1)$, $\mathbf V = (0, 0, 1)$. Why is the highlight where $\mathbf n$ is halfway between $\mathbf L$ and $\mathbf V$? Why does the Gouraud half miss it?

**Solution of Exercise 31.8.**

Facts used: $\mathbf r = 2(\mathbf n \cdot \mathbf L)\mathbf n - \mathbf L$, the specular term is largest when $\mathbf r = \mathbf V$. If $\mathbf r = \mathbf V$ then $\mathbf L + \mathbf V = 2(\mathbf n \cdot \mathbf L)\mathbf n$, so $\mathbf n$ is the unit vector $\mathbf h$ of $\mathbf L + \mathbf V$: the normal must bisect the light and the view. Here $\mathbf L = (-1, 1, 1)/\sqrt3$, $\mathbf L + \mathbf V = (-0.577, 0.577, 1.577)$ of length 1.776, and $\mathbf h = (-0.3251, 0.3251, 0.8881)$. On a sphere of radius 70 centred at $(240, 80)$ the point of normal $\mathbf h$ is at $x = 240 - 70 \times 0.3251 = 217.25$ and $y = 80 - 22.75 = 57.25$, with $y$ downwards; a pixel’s centre is its index plus $\frac12$, so the pixel is $(216.75, 56.75)$, which the program prints rounded as $(216.7, 56.7)$, and its brightest pixel is $(217, 57)$. The Gouraud half computes the light only at its vertices, at multiples of $22.5^\circ$ of longitude and latitude, while $\mathbf h$ is at about $-20^\circ$ of longitude and $19^\circ$ of latitude: no vertex is at the highlight, and with the shininess 40 the specular term falls fast away from it, so the interpolated colours stay lower, 0.806 at best, and the peak is spread along the triangles’ edges. A test checks $\mathbf h$ and the pixel.

**Exercise 31.9 ★★.**

Derive the quadratic of the ray–sphere test. Compute $t$ for the ray from $(0, 0, 0)$ along $(0, 0, -1)$ against the sphere of centre $(0, 0, -5)$ and radius 1, and for a ray from that sphere’s centre along $(1, 0, 0)$. At which angle from the $-z$ axis do rays from the origin stop meeting the sphere?

**Solution of Exercise 31.9.**

Facts used: $|\mathbf d| = 1$. $|o + t\mathbf d - c|^2 = |\mathbf v + t\mathbf d|^2 = t^2 + 2t\,\mathbf v \cdot \mathbf d + |\mathbf v|^2$, with $\mathbf v = o - c$; equal to $r^2$, this is $t^2 + 2bt + (|\mathbf v|^2 - r^2) = 0$. For the first ray, $\mathbf v = (0, 0, 5)$, $b = -5$, $|\mathbf v|^2 - r^2 = 24$, and $t = 5 \pm \sqrt{25 - 24} = 4$ or 6: the ray enters at $t = 4$, the front of the sphere, and leaves at 6. From the centre, $\mathbf v = 0$, $b = 0$, and $t = \pm1$: the only positive root, 1, is where the ray leaves the sphere, which is why `hit_sphere` tries the larger root when the smaller is not positive. A ray from the origin at the angle $\alpha$ from the $-z$ axis passes at the distance $5\sin\alpha$ from the centre; it stops meeting the sphere when that distance exceeds the radius, at $\sin\alpha = 1/5$, $\alpha \approx 11.54^\circ$. A test checks the two roots and that rays just inside and just outside that angle hit and miss.

**Exercise 31.10 ★★★.**

Two clockwise triangles share the edge $pq$, on opposite sides of it. Prove that a pixel centre lying on $pq$ strictly between $p$ and $q$ is drawn by exactly one of them under the [top-left rule](#def-b3-computer-graphics-raster).

**Solution of Exercise 31.10.**

Facts used: $E_{ba} = -E_{ab}$; a triangle $(a, b, c)$ is clockwise when $E_{ab}(c) > 0$; `top_left`$(a, b)$ holds when $a_y = b_y$ and $b_x > a_x$, or when $b_y < a_y$.

Let the triangles be $(p, q, r)$ and $(q, p, s)$ with $r$ and $s$ on opposite sides of the line $pq$, $E_{pq}(r) > 0 > E_{pq}(s)$. The first is clockwise as written. For the second, $E_{qp}(s) = -E_{pq}(s) > 0$, so it is clockwise as $(q, p, s)$: the two triangles run along the shared edge in opposite directions. Let $x$ be a centre on $pq$ strictly between $p$ and $q$. Then $E_{pq}(x) = E_{qp}(x) = 0$. The two other edges of the first triangle meet the line $pq$ only at $p$ and at $q$, so their [edge functions](#def-b3-computer-graphics-raster) are not zero at $x$; since $x$ is on the closed triangle, they are positive. The same holds for the second triangle. So the first triangle draws $x$ exactly when `top_left`$(p, q)$, and the second exactly when `top_left`$(q, p)$. If $p_y \neq q_y$, exactly one of $q_y < p_y$ and $p_y < q_y$ holds, and the horizontal clause is false for both. If $p_y = q_y$, the clause $b_y < a_y$ is false for both, and exactly one of $q_x > p_x$ and $p_x > q_x$ holds, since $p \neq q$. In every case exactly one of the two tests is true, and $x$ is drawn exactly once. ∎

**Exercise 31.11 ★★★.**

Show that the NDC depth of the points of a flat triangle is an affine function of their NDC position $(x, y)$, so that interpolating the corners’ depths with screen-space barycentric coordinates is exact. Show that the distance $d$ is not affine in $(x, y)$, but $1/d$ is. What does this mean for a texture or a colour interpolated across a triangle seen at a slant?

**Solution of Exercise 31.11.**

Facts used: [perspective projection](#def-b3-computer-graphics-projection) gives $x = k_x x_c/d$ and $y = k_y y_c/d$ with $d = -z_c$; the NDC depth is $A - B/d$ with constants $A$, $B$.

A flat triangle lies in a plane $\alpha x_c + \beta y_c + \gamma z_c = \delta$ of camera coordinates; if the plane does not pass through the eye, $\delta \neq 0$. Dividing by $d$ and writing $x_c/d = x/k_x$, $y_c/d = y/k_y$, $z_c/d = -1$ gives

$$
\frac{\alpha}{k_x}\,x + \frac{\beta}{k_y}\,y - \gamma = \frac{\delta}{d},
$$

so $1/d$ is an affine function of the screen position $(x, y)$ over the triangle. The NDC depth $A - B/d$ is then affine in $(x, y)$ too, and an affine function is reproduced exactly by barycentric interpolation of its values at the corners: the [depth buffer](#def-b3-computer-graphics-visibility) of `zbuffer.c`, which interpolates in screen space, computes the exact depth. The distance $d = \delta/(\text{affine})$ is not affine unless the affine function is constant, that is unless the triangle faces the camera squarely ($\alpha = \beta = 0$). A colour or a texture coordinate given at the corners varies linearly in camera space, so like $d$ it is not affine on the screen: interpolated there it bends a slanted checkerboard. The fix is to interpolate $u/d$ and $1/d$, both affine on the screen, and divide one by the other at each pixel, which is called perspective-correct interpolation. In `shade.c` the mesh is projected straight, without perspective, so its interpolation is exact.

**Exercise 31.12 ★★★.**

Make the three spheres of `rt.h` partial mirrors and trace the image with a depth limit of 0 to 4. Count the primary, reflected and [shadow rays](#def-b3-computer-graphics-rays) for each limit. Explain the number of reflected rays at limit 1, why the counts stop growing quickly, and why a limit is needed at all.

**Solution of Exercise 31.12.**

`exercises/ex12_reflect.c` traces the scene with each depth limit, and a test checks every count:

| limit | primary | reflected | shadow | total |
| --- | --- | --- | --- | --- |
| 0 | 76,800 | 0 | 45,170 | 121,970 |
| 1 | 76,800 | 12,421 | 50,881 | 140,102 |
| 2 | 76,800 | 13,333 | 51,343 | 141,476 |
| 3 | 76,800 | 13,478 | 51,422 | 141,700 |
| 4 | 76,800 | 13,498 | 51,435 | 141,733 |

At limit 1 every [primary ray](#def-b3-computer-graphics-rays) that ends on a sphere is reflected once: $3{,}686 + 2{,}661 + 6{,}074 = 12{,}421$, the floor being no mirror. Of these reflected rays, $50{,}881 - 45{,}170 = 5{,}711$ meet a surface and send a [shadow ray](#def-b3-computer-graphics-rays); the other 6,710 go to the sky. Each further level adds only the rays that meet a sphere again: 912, then 145, then 20. Three spheres apart from each other face each other over small solid angles, so a reflected ray rarely meets another one. Each bounce also weighs its colour by the mirror factor 0.3, so the fourth level changes a pixel by at most $0.3^4 < 1\,\%$. A limit is needed because nothing else stops the recursion: two mirrors facing each other send a ray along the line through their centres back and forth for ever.

![The scene traced with the depth limit 3: each sphere shows its neighbours and the floor.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-computer-graphics/img-9f6117586e7e.jpg)

*The scene traced with the depth limit 3: each sphere shows its neighbours and the floor.*

## 31.7 Weekend problem

**Problem 31.1.**

Weekend problem — How many pixels does a triangle cover?

A triangle of area 225.74 pixels, once its corners are rounded to sixteenths, covered 226 pixels. The problem asks how close the count of pixels is to the area, when it is exact, and why the [top-left rule](#def-b3-computer-graphics-raster) makes it exact for a whole mesh. `mesh.c` draws six random triangles whose corners are pixel centres, so that Pick’s theorem applies, then five meshes that cover an image of $64 \times 48$ pixels, each with both rules. Pick’s theorem, from 1899, says that a polygon whose corners have integer coordinates has the area $A = I + B/2 - 1$, where $I$ counts the integer points strictly inside it and $B$ those on its boundary.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o mesh mesh.c -lm && ./mesh
lattice triangle             area  interior  boundary  Pick  naive  top-left
(23, 8) (17, 9) (11, 1)   27.0        26         4  27.0     30        27
(12,10) (22,13) ( 3,13)   28.5        18        23  28.5     41        20
( 8, 2) (10,15) ( 3, 9)   39.5        39         3  39.5     42        40
(23, 6) (18,16) ( 1,16)   85.0        74        24  85.0     98        75
( 0,11) (17, 8) (16,15)   58.0        56         6  58.0     62        60
(13,16) (11,17) (19, 8)    5.0         4         4   5.0      8         4
mesh  cells  triangles  rule      drawn  overlap  never
   1     20         40  top-left   3072        0      0
   1     20         40  w >= 0     3159       66      0
   2     30         60  top-left   3072        0      0
   2     30         60  w >= 0     3139       44      0
   3     42         84  top-left   3072        0      0
   3     42         84  w >= 0     3139       32      0
   4     56        112  top-left   3072        0      0
   4     56        112  w >= 0     3173       56      0
   5     72        144  top-left   3072        0      0
   5     72        144  w >= 0     3270      112      0
```

***Output 31.7.** Above, six lattice triangles: their area, their centres strictly inside and on the boundary, Pick’s formula, and the pixels each rule draws. Below, five meshes of 40 to 144 triangles over $64 \times 48 = 3{,}072$ pixels, with the number of draws (a pixel drawn twice counts twice), the pixels drawn more than once, and those never drawn.*

**Part I — One triangle, one square.**

1. Why does the count of drawn pixels of `raster.c` differ from the area, and by how much can it differ for a triangle of that size?
2. Why does the rasteriser count in sixteenths of a pixel with integers? What could go wrong with floating-point coordinates on a shared edge?
3. In the naive grid of `shared_edge.c` , which four pixels are drawn twice, and why exactly those?
4. Which pixels does the naive test draw outside the square’s 54, and which neighbouring square of a mesh would draw them too?
5. Name each edge of the two triangles of the square as top, left, or neither, and check the top-left grid against it.
6. Check Pick’s theorem on the $9 \times 6$ square, whose corners are pixel centres.

**Part II — Lattice triangles.**

7. Check Pick’s formula on the first triangle of the table.
8. Why is the naive count always $I + B$ ? Check it on the fourth row.
9. The second triangle has an area of 28.5 and the [top-left rule](#def-b3-computer-graphics-raster) draws only 20 pixels. Where are its 23 boundary points, and which of them does the rule keep?
10. For a lattice triangle, show that the top-left count lies between $I$ and $I + B$ , and that it can be above or below the area.
11. The third triangle has no boundary points but its corners. What does Pick’s theorem give for it, and why is its top-left count then within one pixel of the area?
12. Why does no single triangle’s count tell whether a rule is right?

**Part III — Meshes.**

13. How are the meshes made, and why are a third of the inner vertices put on pixel centres?
14. Why does the [top-left rule](#def-b3-computer-graphics-raster) draw exactly 3,072 pixels for every mesh?
15. For the first mesh, the naive rule draws 3,159 pixels, with 66 drawn more than once. Why is $3{,}159 - 3{,}072 = 87$ larger than 66?
16. Why does the naive rule never leave a pixel undrawn?
17. A rule that drew only centres with all three $E > 0$ : what would it leave in a mesh, and how would it show?
18. Why does a pixel drawn twice matter for a half-transparent surface, even though the [depth buffer](#def-b3-computer-graphics-visibility) hides it for an opaque one?

**Part IV — Exactly once.**

19. Prove that a centre on a shared edge, strictly between its ends, is drawn by exactly one of the two triangles (Exercise [31.10](#exo-b3-computer-graphics-10) may be quoted).
20. Show that a centre strictly inside one triangle of a mesh is drawn by that triangle alone.
21. The proof leaves out centres exactly on a vertex. What does the table say about them, given that the meshes put many vertices on centres?
22. Explain the rule in one dimension: a segment of pixels split at points, each piece drawing the half-open interval $[x_0, x_1)$ .
23. Why must the rule depend only on the edge, and not on which triangle is drawn first?
24. Sum up: how many pixels does a single triangle cover compared with its area, and how many does a mesh covering the image draw under each rule?

**Solution of Problem 31.1.**

**1.** A pixel is drawn when its centre is in the triangle; the centres form a grid with one point per unit of area, so the count is the area plus an error from the pixels that the boundary cuts, each wrong by less than one pixel. For this triangle, whose perimeter is about 70 pixels, the error can reach the order of the perimeter in the worst case, but errors of opposite signs along the boundary cancel, and here the count, 226, is within 0.26 of the area.

**2.** So that every [edge function](#def-b3-computer-graphics-raster) is computed exactly: a centre is then exactly on an edge, or exactly on one side. With floating-point numbers, the two triangles of a shared edge compute the [edge function](#def-b3-computer-graphics-raster) with their vertices in another order, and rounding can put a centre on the edge inside both, or inside neither, which leaves a doubled pixel or a hole.

**3.** The diagonal runs from centre $(1, 1)$ to centre $(10, 7)$, a step of $(9, 6) = 3 \times (3, 2)$: it passes through the centres of pixels $(1, 1)$, $(4, 3)$, $(7, 5)$ and $(10, 7)$, and through no other. The naive test draws a centre with $E = 0$ in both triangles.

**4.** The column $i = 10$ and the row $j = 7$: 7 plus 9, 16 pixels, since the naive test draws the square’s right and bottom edges, which go through centres. In a mesh of such squares, the square to the right draws the column again on its left edge, and the square below draws the row on its top edge.

**5.** With $p = (1, 1)$, $q = (10, 1)$, $r = (10, 7)$, $s = (1, 7)$ in pixel centres and $y$ down, both triangles $(p, q, r)$ and $(p, r, s)$ are clockwise, with $E = 54$. In the first, $p \to q$ runs right, horizontal: top; $q \to r$ runs down: neither; $r \to p$ runs up: left. In the second, $p \to r$ runs down: neither; $r \to s$ runs left, horizontal: neither; $s \to p$ runs up: left. So the diagonal belongs to triangle 1, as the grid shows at $(4, 3)$ and $(7, 5)$; the top row and the left column are drawn, the bottom row and the right column are not.

**6.** $I = 8 \times 5 = 40$ centres strictly inside, $B = 2(9 + 6) = 30$ on the boundary, and $I + B/2 - 1 = 40 + 15 - 1 = 54 = 9 \times 6$. A test checks it.

**7.** $26 + 4/2 - 1 = 27$, the area.

**8.** The naive test draws the centres of the closed triangle: the $I$ inside and the $B$ on the boundary. Fourth row: $74 + 24 = 98$.

**9.** The triangle $(12, 10)$, $(22, 13)$, $(3, 13)$ is clockwise. Its bottom edge, from $(22, 13)$ to $(3, 13)$, carries 20 centres, its two ends included; its edge from $(3, 13)$ to $(12, 10)$, a step of $3 \times (3, -1)$, carries 2 more strictly between its ends; the corner $(12, 10)$ is the 23rd. The bottom edge runs left: it is not a top edge, and its 20 centres are refused. The edge from $(3, 13)$ up to $(12, 10)$ is a left edge, and its 2 inner centres are kept. The corner $(12, 10)$ is also on the edge to $(22, 13)$, which runs down, and is refused. So $18 + 2 = 20$. A test checks the split.

**10.** The [top-left rule](#def-b3-computer-graphics-raster) draws every centre strictly inside, all with $E > 0$, and some of those on the boundary, so its count is between $I$ and $I + B$. The area $I + B/2 - 1$ is between them as well, and the count can fall on either side: the third and fifth rows are above, 40 against 39.5 and 60 against 58; the second, fourth and sixth are below.

**11.** $B = 3$ gives $A = I + 1/2$: 39.5. A corner is drawn only if both edges through it are top or left, and at most one corner of a triangle is, the one where its two top-left edges meet; so the count is $I$ or $I + 1$, here 40, half a pixel from the area.

**12.** A single triangle may legitimately draw anything between $I$ and $I + B$; what makes a rule right is a property of a mesh: every pixel of the covered region drawn exactly once. Only the count over a mesh, compared with the region, tests that.

**13.** A grid of $(4 + s) \times (3 + s)$ cells for the seed $s$, whose outer vertices lie on the image’s border; each inner vertex is either moved by up to 2.5 pixels in each direction or, one time in three, put exactly on a pixel centre; each cell is cut along one of its two diagonals at random. The vertices on centres make many edges pass exactly through centres, and some centres be vertices, the cases where a rule can fail: random vertices alone would almost never put a centre on an edge.

**14.** The triangles cover the rectangle $[0, 64] \times [0, 48]$ without overlapping, and no centre lies on the outer border, which runs along pixel boundaries. By Questions 19 to 21, each of the 3,072 centres is drawn by exactly one triangle.

**15.** A centre on a shared edge is drawn twice, but a centre on a vertex is drawn by every triangle that has that vertex as a corner, often four to six. The $87$ extra draws are $66$ pixels drawn twice or more, plus $21$ more draws on pixels drawn three times or more.

**16.** The closed triangles cover the whole rectangle, and the naive test draws every centre of its closed triangle: each centre is in at least one.

**17.** Such a rule draws no centre on an edge: every centre on a shared edge or a vertex would be drawn by nobody, leaving lines of background pixels along the edges that pass through centres, cracks in the surface.

**18.** With blending, the colour of a half-transparent surface is mixed with what is behind it once per draw. A pixel drawn twice is mixed twice, and shows as a darker or more opaque seam along the edges. An opaque surface drawn twice at the same depth gives the same colour twice, and the error does not show.

**19.** This is Exercise [31.10](#exo-b3-computer-graphics-10): the two triangles run along the edge in opposite directions, and `top_left` is true for exactly one direction. The other two [edge functions](#def-b3-computer-graphics-raster) of each triangle are positive there.

**20.** A centre strictly inside a triangle $T$ has its three [edge functions](#def-b3-computer-graphics-raster) positive, and $T$ draws it. Another triangle $T'$ of the mesh cannot contain it even in its closure: a small disc around the centre lies inside $T$, and if the centre were in the closed $T'$, the disc would contain inner points of $T'$, so the two triangles would overlap.

**21.** The table shows no pixel drawn twice and none missed in five meshes where a third of the inner vertices are centres: the rule works at vertices too. A proof: the test of `inside` is the same as asking whether the point moved by $(\varepsilon, \varepsilon^2)$, for a small enough $\varepsilon > 0$, is strictly inside. On an edge with $E = 0$, the move changes $E$ by $(b_x - a_x)\varepsilon^2 - (b_y - a_y)\varepsilon$; if $b_y \neq a_y$, the first-order term decides, and it is positive when $b_y < a_y$, a left edge; if $b_y = a_y$, it is positive when $b_x > a_x$, a top edge. The moved point lies on none of the finitely many edges, so it is strictly inside exactly one triangle, the one that draws the centre.

**22.** On a line, cut the pixels at the points $x_0 < x_1 < x_2$: the piece $[x_0, x_1)$ takes its left end and not its right one, and the next piece $[x_1, x_2)$ takes $x_1$. Every point belongs to exactly one piece. The [top-left rule](#def-b3-computer-graphics-raster) is the same choice in the plane: each triangle owns its top and left boundary, and leaves its bottom and right boundary to its neighbours.

**23.** So that the result does not depend on the order of drawing: each pixel is decided by its own centre and the triangle’s edges only, so the triangles can be drawn in any order, and the pixels tested all at once, as Pineda’s parallel test does.

**24.** One triangle covers its centres strictly inside and part of its boundary: between $I$ and $I + B$, close to the area but off by up to the boundary’s share, 20 against 28.5 in the worst row. A mesh that covers the image draws exactly the $3{,}072$ pixels of the image under the [top-left rule](#def-b3-computer-graphics-raster), with no overlap and no gap, in all five meshes; the naive rule never leaves a gap but makes from 3,139 to 3,270 draws, with 32 to 112 pixels drawn more than once.
