Ilmu Komputer · Buku 5 · Sarjana Tahun 3

University Computer Science — Year 3

Buku ini belum tersedia dalam Bahasa Indonesia. Edisi: English.

University Computer Science — Year 3 · Sarjana Tahun 3

31Computer 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, 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 ABCABC is λAA+λBB+λCC\lambda_A A + \lambda_B B + \lambda_C C with λA+λB+λC=1\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 (±1,±1,±1)(\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×240320 \times 240 pixels. Turning is a linear map, a 3×33 \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)(x, y, z) of space are (x,y,z,1)(x, y, z, 1), and those of a direction (x,y,z)(x, y, z) are (x,y,z,0)(x, y, z, 0). More generally, (x,y,z,w)(x, y, z, w) with w≠0w \neq 0 stands for the point (x/w,y/w,z/w)(x/w, y/w, z/w): all non-zero multiples of a 4-vector stand for the same point.

In homogeneous coordinates the translation by (tx,ty,tz)(t_x, t_y, t_z) and the rotation by an angle aa about the yy axis are

T=(100tx010ty001tz0001),Ry(a)=(cos⁡a0sin⁡a00100−sin⁡a0cos⁡a00001).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}.

TT adds ww times (tx,ty,tz)(t_x, t_y, t_z): it moves a point, whose ww is 1, and leaves a direction, whose ww is 0, as it was, which is right, since a direction has no position to move. A scaling by the factors (sx,sy,sz)(s_x, s_y, s_z) is the diagonal matrix of entries sx,sy,sz,1s_x, s_y, s_z, 1. A product of such matrices applies the right-hand factor first: TRy(a)T R_y(a) turns a point, then moves it, and the order matters, since Ry(a)TR_y(a) T moves it first and then turns it about the origin, with the translation turned too (Exercise 31.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 zz axis, with yy 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.
The chain that takes a corner of the cube to a pixel. The three matrices multiply into one, PVMPVM; the division by ww and the viewport are applied to each point after it.

The chain is the same for every vertex of every object; only MM changes from object to object, and VV 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 yy and distance d=−zd = -z in front of the camera is seen in the direction of slope y/dy/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.
A side view of the camera. A point at height yy and distance dd is seen where its line of sight crosses the plane d=1d = 1, at height y/dy/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=−zd = -z in front of the camera to the screen position (x/d,y/d)(x/d, y/d), scaled so that the edges of the field of view map to ±1\pm1. The view frustum is the truncated pyramid of points that the camera shows: inside the field of view, between a near plane d=nd = n and a far plane d=fd = f. The projection matrix leaves the division undone: it puts dd into the fourth coordinate ww, and the perspective division divides by it, giving the normalised device coordinates (NDC), each in [−1,1][-1, 1] inside the frustum.

With the vertical field of view θ\theta, the aspect ratio α\alpha (width over height) and c=1/tan⁡(θ/2)c = 1/\tan(\theta/2), the projection matrix is

P=(c/α0000c0000f+nn−f2fnn−f00−10).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 xx and yy directly, so that parallel lines stay parallel and far objects keep their size; its last row is (0,0,0,1)(0, 0, 0, 1). The perspective matrix’s last row puts w=−z=dw = -z = d. Its first two rows scale xx and yy so that, after the division, the top of the field of view, where y/d=tan⁡(θ/2)y/d = \tan(\theta/2), lands at 11. Its third row gives the depth ((f+n)/(f−n))−(2fn/(f−n))/d\bigl((f+n)/(f-n)\bigr) - \bigl(2fn/(f-n)\bigr)/d after the division: −1-1 on the near plane, +1+1 on the far plane, and growing with dd in between, which is all a depth test needs. The listing writes it in C, with m[i][j]m[i][j] the entry of row ii and column jj.

// 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, 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∘20^\circ about xx, then by 30∘30^\circ about yy, then pushed 6 units in front of the camera; the camera has a field of view of 60∘60^\circ, the aspect ratio 4/34/3, and the planes n=1n = 1 and f=20f = 20. The viewport, the last step, maps xNDC∈[−1,1]x_{\mathrm{NDC}} \in [-1, 1] to [0,320][0, 320] and yNDCy_{\mathrm{NDC}} to [240,0][240, 0], since rows of pixels are counted from the top.

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 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 ww between 4.39 and 7.61: their distances from the camera. The nearest corner, (−1,1,1)(-1, 1, 1), has the smallest depth, 0.626.

The first corner checks by hand: its ww is its distance, 6.610, and its depth is (21−40/6.610)/19=0.787(21 - 40/6.610)/19 = 0.787. The four corners with z=1z = 1 in the cube’s own coordinates have ww 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 aa to bb is

Eab(p)=(bx−ax)(py−ay)−(by−ay)(px−ax),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)(a, b, p); it is zero on the line abab 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 yy pointing down the screen and a triangle (a,b,c)(a, b, c) listed clockwise, the three edge functions EabE_{ab}, EbcE_{bc} and EcaE_{ca} are all positive inside the triangle, and their sum at any point is Eab(c)E_{ab}(c), twice the area: divided by it, they are the barycentric coordinates of the point. Juan Pineda described rasterisation by edge functions 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)(i, j) is (16i+8,16j+8)(16i + 8, 16j + 8), and an edge function 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.

// 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 and the two tests: the naive one draws every centre with E≥0E \geq 0 for the three edges; the top-left rule 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 yy 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)(3.2, 2.5), (28.7,9.1)(28.7, 9.1) and (9.4,21.8)(9.4, 21.8), on a grid of 32×2432 \times 24 pixels, as text. The corners are rounded to sixteenths of a pixel first, to (3.1875,2.5)(3.1875, 2.5), (28.6875,9.125)(28.6875, 9.125) and (9.375,21.8125)(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×69 \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 draws each of the 9×6=549 \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.
The top-left rule on a triangle drawn with yy 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: aa is, bb and cc 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 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 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, 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 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).

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. 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.
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 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). It does not replace the depth buffer, 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 n\mathbf n, lit from the unit direction L\mathbf L and seen from the unit direction V\mathbf V, the diffuse term is proportional to max⁡(0,n⋅L)\max(0, \mathbf n \cdot \mathbf L), the cosine of the angle of incidence, and the specular term to max⁡(0,r⋅V)s\max(0, \mathbf r \cdot \mathbf V)^s, where r=2(n⋅L)n−L\mathbf r = 2(\mathbf n \cdot \mathbf L)\mathbf n - \mathbf L is the mirror image of L\mathbf L about the normal and the shininess ss narrows the highlight as it grows. Bui Tuong Phong published this reflection model in 1975.

// 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-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,n⋅L)\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×88 \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 approaches as it interpolates the vertex normals of a fine enough mesh. The brightest point should be where r=V\mathbf r = \mathbf V, that is where the normal is the unit vector halfway between L\mathbf L and V\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.
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: 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∈[0,1]v \in [0, 1] to the power 1/2.21/2.2, a gamma encoding, and rounds 255 v1/2.2255\,v^{1/2.2} to a byte.

31.5 Ray tracing

Rasterisation starts from the triangles and asks which pixels they cover. Ray tracing 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+tdo + t\mathbf d, with origin oo, unit direction d\mathbf d and t>0t > 0. It meets the sphere of centre cc and radius rr where ∣o+td−c∣2=r2|o + t\mathbf d - c|^2 = r^2; with v=o−c\mathbf v = o - c and b=v⋅db = \mathbf v \cdot \mathbf d, that is the quadratic t2+2bt+∣v∣2−r2=0t^2 + 2bt + |\mathbf v|^2 - r^2 = 0, whose roots are t=−b±b2−∣v∣2+r2t = -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=y0y = y_0 at t=(y0−oy)/dyt = (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.
A primary ray from the eye oo meets a sphere at t1t_1 and t2t_2; the nearer, t1t_1, is seen. The point t=−bt = -b is the foot of the perpendicular from the centre. From the hit, a shadow ray goes to the light; the normal n\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 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 uses.

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 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 through the centre of each pixel of a 320×240320 \times 240 image, from a camera at the origin with the same field of view of 60∘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 per pixel, and one shadow ray for each primary ray that meets something: 76,800−31,630=45,17076{,}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.
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.

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 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 pays per triangle, ray tracing 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)T(2, 0, 0) applied to the point (1,1,1)(1, 1, 1) and to the direction (1,1,1)(1, 1, 1), in homogeneous coordinates, and Ry(π/2)R_y(\pi/2) applied to the point (1,0,0)(1, 0, 0). Which way does Ry(π/2)R_y(\pi/2) turn the xx axis, seen from above?

Solution

Solution of Exercise 31.1.

T(2,0,0)(1,1,1,1)=(3,1,1,1)T(2, 0, 0)(1, 1, 1, 1) = (3, 1, 1, 1): the point moves by 2 along xx. T(2,0,0)(1,1,1,0)=(1,1,1,0)T(2, 0, 0)(1, 1, 1, 0) = (1, 1, 1, 0): the last column is multiplied by w=0w = 0, and the direction is unchanged. Ry(π/2)(1,0,0,1)=(cos⁡π2,0,−sin⁡π2,1)=(0,0,−1,1)R_y(\pi/2)(1, 0, 0, 1) = (\cos\frac\pi2, 0, -\sin\frac\pi2, 1) = (0, 0, -1, 1): the xx axis turns to the −z-z axis, which, seen from above with yy 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)(0, 1, -2) and (0,2,−4)(0, 2, -4) of camera coordinates, and the row of pixels on which they land. Why must they land on the same pixel?

Solution

Solution of Exercise 31.2.

With θ=60∘\theta = 60^\circ, c=1/tan⁡30∘=3c = 1/\tan 30^\circ = \sqrt3. Both points have y/d=1/2y/d = 1/2, so yNDC=3/2≈0.866y_{\mathrm{NDC}} = \sqrt3/2 \approx 0.866 for both, and the viewport puts them on the row (1−0.866)/2×240=16.1(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/191/19 for the first and (21−10)/19=11/19(21 - 10)/19 = 11/19 for the second. A test checks both NDC heights.

Exercise 31.3 ★

Take a=(0,0)a = (0, 0), b=(8,0)b = (8, 0) and c=(0,8)c = (0, 8) on a screen whose yy points down. Is (a,b,c)(a, b, c) clockwise? Compute EabE_{ab}, EbcE_{bc} and EcaE_{ca} at p=(2,3)p = (2, 3), their sum, and the barycentric coordinates of pp. Show that the sum of the three edge functions is the same at every point.

Solution

Solution of Exercise 31.3.

Eab(c)=(8−0)(8−0)−(0−0)(0−0)=64>0E_{ab}(c) = (8 - 0)(8 - 0) - (0 - 0)(0 - 0) = 64 > 0: clockwise on a screen whose yy points down. At p=(2,3)p = (2, 3): Eab=8⋅3−0=24E_{ab} = 8 \cdot 3 - 0 = 24, Ebc=(0−8)(3−0)−(8−0)(2−8)=−24+48=24E_{bc} = (0 - 8)(3 - 0) - (8 - 0)(2 - 8) = -24 + 48 = 24, Eca=(0−0)(3−8)−(0−8)(2−0)=16E_{ca} = (0 - 0)(3 - 8) - (0 - 8)(2 - 0) = 16. The sum is 64=Eab(c)64 = E_{ab}(c). Each edge function, divided by 64, is the barycentric coordinate of the vertex opposite its edge: λc=24/64\lambda_c = 24/64, λa=24/64\lambda_a = 24/64, λb=16/64\lambda_b = 16/64, and indeed 38a+14b+38c=(2,3)\frac38 a + \frac14 b + \frac38 c = (2, 3). Each EE is affine in pp; in the sum, the coefficient of pxp_x is −(by−ay)−(cy−by)−(ay−cy)=0-(b_y - a_y) - (c_y - b_y) - (a_y - c_y) = 0, and that of pyp_y is 0 the same way, so the sum is a constant, its value at p=cp = c, where two of the terms vanish: Eab(c)E_{ab}(c). A test checks the four values.

Exercise 31.4 ★

Rasterise by hand, with the top-left rule, the triangle (1,1)(1, 1), (7,2)(7, 2), (2,6)(2, 6) on a grid of 8×78 \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

Solution of Exercise 31.4.

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

........ .###.... .#####.. .####... ..##.... ..#..... ........

15 pixels for an area of 14.5. The centre (1.5,3.5)(1.5, 3.5) of pixel (1,3)(1, 3) is on the edge from c=(2,6)c = (2, 6) to a=(1,1)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 Ry(a) T(0,0,−6)R_y(a)\,T(0, 0, -6) instead of T(0,0,−6) Ry(a)T(0, 0, -6)\,R_y(a). Where is its centre for a=0,π/4,π/2,πa = 0, \pi/4, \pi/2, \pi? Describe what the viewer sees, and write the rule for the order of the factors.

Solution

Solution of Exercise 31.5.

Ry(a) T(0,0,−6)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)(0, 0, -6) becomes (−6sin⁡a,0,−6cos⁡a)(-6\sin a, 0, -6\cos a): (0,0,−6)(0, 0, -6) at a=0a = 0, (−4.24,0,−4.24)(-4.24, 0, -4.24) at π/4\pi/4, (−6,0,0)(-6, 0, 0) at π/2\pi/2, level with the camera, and (0,0,6)(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) Ry(a)T(0, 0, -6)\,R_y(a) the centre stays at (0,0,−6)(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=TRM = T R. exercises/ex5_drift.c prints both centres for five angles, and a test checks the one at π/4\pi/4.

Exercise 31.6 ★★

Add back-face culling 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, and not two?

Solution

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 is negative. A face turned towards the camera is seen from outside, counterclockwise, which on a screen whose yy points down gives E<0E < 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 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=1n = 1 and f=20f = 20, compute the NDC depth at the distances d=1,2,10,20d = 1, 2, 10, 20. What part of the depth range [−1,1][-1, 1] is left to the far half of the frustum, 10≤d≤2010 \leq d \leq 20? A depth buffer 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

Solution of Exercise 31.7.

With n=1n = 1 and f=20f = 20 the NDC depth is (21−40/d)/19(21 - 40/d)/19: −1-1 at d=1d = 1, 1/19≈0.0531/19 \approx 0.053 at d=2d = 2, 17/19≈0.89517/19 \approx 0.895 at d=10d = 10 and 11 at d=20d = 20. The far half of the frustum keeps only 1−17/19=2/191 - 17/19 = 2/19 of the range of length 2, that is 1/19≈5.3 %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/(19d2)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=15d = 15 moves the depth 100 times less than at d=1.5d = 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 nn for nn small against ff: 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)(240, 80), L\mathbf L is the unit vector of (−1,1,1)(-1, 1, 1), V=(0,0,1)\mathbf V = (0, 0, 1). Why is the highlight where n\mathbf n is halfway between L\mathbf L and V\mathbf V? Why does the Gouraud half miss it?

Solution

Solution of Exercise 31.8.

Facts used: r=2(n⋅L)n−L\mathbf r = 2(\mathbf n \cdot \mathbf L)\mathbf n - \mathbf L, the specular term is largest when r=V\mathbf r = \mathbf V. If r=V\mathbf r = \mathbf V then L+V=2(n⋅L)n\mathbf L + \mathbf V = 2(\mathbf n \cdot \mathbf L)\mathbf n, so n\mathbf n is the unit vector h\mathbf h of L+V\mathbf L + \mathbf V: the normal must bisect the light and the view. Here L=(−1,1,1)/3\mathbf L = (-1, 1, 1)/\sqrt3, L+V=(−0.577,0.577,1.577)\mathbf L + \mathbf V = (-0.577, 0.577, 1.577) of length 1.776, and h=(−0.3251,0.3251,0.8881)\mathbf h = (-0.3251, 0.3251, 0.8881). On a sphere of radius 70 centred at (240,80)(240, 80) the point of normal h\mathbf h is at x=240−70×0.3251=217.25x = 240 - 70 \times 0.3251 = 217.25 and y=80−22.75=57.25y = 80 - 22.75 = 57.25, with yy downwards; a pixel’s centre is its index plus 12\frac12, so the pixel is (216.75,56.75)(216.75, 56.75), which the program prints rounded as (216.7,56.7)(216.7, 56.7), and its brightest pixel is (217,57)(217, 57). The Gouraud half computes the light only at its vertices, at multiples of 22.5∘22.5^\circ of longitude and latitude, while h\mathbf h is at about −20∘-20^\circ of longitude and 19∘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 h\mathbf h and the pixel.

Exercise 31.9 ★★

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

Solution

Solution of Exercise 31.9.

Facts used: ∣d∣=1|\mathbf d| = 1. ∣o+td−c∣2=∣v+td∣2=t2+2t v⋅d+∣v∣2|o + t\mathbf d - c|^2 = |\mathbf v + t\mathbf d|^2 = t^2 + 2t\,\mathbf v \cdot \mathbf d + |\mathbf v|^2, with v=o−c\mathbf v = o - c; equal to r2r^2, this is t2+2bt+(∣v∣2−r2)=0t^2 + 2bt + (|\mathbf v|^2 - r^2) = 0. For the first ray, v=(0,0,5)\mathbf v = (0, 0, 5), b=−5b = -5, ∣v∣2−r2=24|\mathbf v|^2 - r^2 = 24, and t=5±25−24=4t = 5 \pm \sqrt{25 - 24} = 4 or 6: the ray enters at t=4t = 4, the front of the sphere, and leaves at 6. From the centre, v=0\mathbf v = 0, b=0b = 0, and t=±1t = \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-z axis passes at the distance 5sin⁡α5\sin\alpha from the centre; it stops meeting the sphere when that distance exceeds the radius, at sin⁡α=1/5\sin\alpha = 1/5, α≈11.54∘\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 pqpq, on opposite sides of it. Prove that a pixel centre lying on pqpq strictly between pp and qq is drawn by exactly one of them under the top-left rule.

Solution

Solution of Exercise 31.10.

Facts used: Eba=−EabE_{ba} = -E_{ab}; a triangle (a,b,c)(a, b, c) is clockwise when Eab(c)>0E_{ab}(c) > 0; top_left(a,b)(a, b) holds when ay=bya_y = b_y and bx>axb_x > a_x, or when by<ayb_y < a_y.

Let the triangles be (p,q,r)(p, q, r) and (q,p,s)(q, p, s) with rr and ss on opposite sides of the line pqpq, Epq(r)>0>Epq(s)E_{pq}(r) > 0 > E_{pq}(s). The first is clockwise as written. For the second, Eqp(s)=−Epq(s)>0E_{qp}(s) = -E_{pq}(s) > 0, so it is clockwise as (q,p,s)(q, p, s): the two triangles run along the shared edge in opposite directions. Let xx be a centre on pqpq strictly between pp and qq. Then Epq(x)=Eqp(x)=0E_{pq}(x) = E_{qp}(x) = 0. The two other edges of the first triangle meet the line pqpq only at pp and at qq, so their edge functions are not zero at xx; since xx is on the closed triangle, they are positive. The same holds for the second triangle. So the first triangle draws xx exactly when top_left(p,q)(p, q), and the second exactly when top_left(q,p)(q, p). If py≠qyp_y \neq q_y, exactly one of qy<pyq_y < p_y and py<qyp_y < q_y holds, and the horizontal clause is false for both. If py=qyp_y = q_y, the clause by<ayb_y < a_y is false for both, and exactly one of qx>pxq_x > p_x and px>qxp_x > q_x holds, since p≠qp \neq q. In every case exactly one of the two tests is true, and xx 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)(x, y), so that interpolating the corners’ depths with screen-space barycentric coordinates is exact. Show that the distance dd is not affine in (x,y)(x, y), but 1/d1/d is. What does this mean for a texture or a colour interpolated across a triangle seen at a slant?

Solution

Solution of Exercise 31.11.

Facts used: perspective projection gives x=kxxc/dx = k_x x_c/d and y=kyyc/dy = k_y y_c/d with d=−zcd = -z_c; the NDC depth is A−B/dA - B/d with constants AA, BB.

A flat triangle lies in a plane αxc+βyc+γzc=δ\alpha x_c + \beta y_c + \gamma z_c = \delta of camera coordinates; if the plane does not pass through the eye, δ≠0\delta \neq 0. Dividing by dd and writing xc/d=x/kxx_c/d = x/k_x, yc/d=y/kyy_c/d = y/k_y, zc/d=−1z_c/d = -1 gives

αkx x+βky y−γ=δd,\frac{\alpha}{k_x}\,x + \frac{\beta}{k_y}\,y - \gamma = \frac{\delta}{d},

so 1/d1/d is an affine function of the screen position (x,y)(x, y) over the triangle. The NDC depth A−B/dA - B/d is then affine in (x,y)(x, y) too, and an affine function is reproduced exactly by barycentric interpolation of its values at the corners: the depth buffer of zbuffer.c, which interpolates in screen space, computes the exact depth. The distance d=δ/(affine)d = \delta/(\text{affine}) is not affine unless the affine function is constant, that is unless the triangle faces the camera squarely (α=β=0\alpha = \beta = 0). A colour or a texture coordinate given at the corners varies linearly in camera space, so like dd it is not affine on the screen: interpolated there it bends a slanted checkerboard. The fix is to interpolate u/du/d and 1/d1/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 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

Solution of Exercise 31.12.

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

limitprimaryreflectedshadowtotal
076,800045,170121,970
176,80012,42150,881140,102
276,80013,33351,343141,476
376,80013,47851,422141,700
476,80013,49851,435141,733

At limit 1 every primary ray that ends on a sphere is reflected once: 3,686+2,661+6,074=12,4213{,}686 + 2{,}661 + 6{,}074 = 12{,}421, the floor being no mirror. Of these reflected rays, 50,881−45,170=5,71150{,}881 - 45{,}170 = 5{,}711 meet a surface and send a shadow ray; 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.34<1 %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.
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 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×4864 \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−1A = I + B/2 - 1, where II counts the integer points strictly inside it and BB 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×48=3,07264 \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×69 \times 6 square, whose corners are pixel centres.

Part II — Lattice triangles.

  1. Check Pick’s formula on the first triangle of the table.
  2. Why is the naive count always I+BI + B? Check it on the fourth row.
  3. The second triangle has an area of 28.5 and the top-left rule draws only 20 pixels. Where are its 23 boundary points, and which of them does the rule keep?
  4. For a lattice triangle, show that the top-left count lies between II and I+BI + B, and that it can be above or below the area.
  5. 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?
  6. Why does no single triangle’s count tell whether a rule is right?

Part III — Meshes.

  1. How are the meshes made, and why are a third of the inner vertices put on pixel centres?
  2. Why does the top-left rule draw exactly 3,072 pixels for every mesh?
  3. For the first mesh, the naive rule draws 3,159 pixels, with 66 drawn more than once. Why is 3,159−3,072=873{,}159 - 3{,}072 = 87 larger than 66?
  4. Why does the naive rule never leave a pixel undrawn?
  5. A rule that drew only centres with all three E>0E > 0: what would it leave in a mesh, and how would it show?
  6. Why does a pixel drawn twice matter for a half-transparent surface, even though the depth buffer hides it for an opaque one?

Part IV — Exactly once.

  1. Prove that a centre on a shared edge, strictly between its ends, is drawn by exactly one of the two triangles (Exercise 31.10 may be quoted).
  2. Show that a centre strictly inside one triangle of a mesh is drawn by that triangle alone.
  3. 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?
  4. Explain the rule in one dimension: a segment of pixels split at points, each piece drawing the half-open interval [x0,x1)[x_0, x_1).
  5. Why must the rule depend only on the edge, and not on which triangle is drawn first?
  6. 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

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 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 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)(1, 1) to centre (10,7)(10, 7), a step of (9,6)=3×(3,2)(9, 6) = 3 \times (3, 2): it passes through the centres of pixels (1,1)(1, 1), (4,3)(4, 3), (7,5)(7, 5) and (10,7)(10, 7), and through no other. The naive test draws a centre with E=0E = 0 in both triangles.

4. The column i=10i = 10 and the row j=7j = 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)p = (1, 1), q=(10,1)q = (10, 1), r=(10,7)r = (10, 7), s=(1,7)s = (1, 7) in pixel centres and yy down, both triangles (p,q,r)(p, q, r) and (p,r,s)(p, r, s) are clockwise, with E=54E = 54. In the first, p→qp \to q runs right, horizontal: top; q→rq \to r runs down: neither; r→pr \to p runs up: left. In the second, p→rp \to r runs down: neither; r→sr \to s runs left, horizontal: neither; s→ps \to p runs up: left. So the diagonal belongs to triangle 1, as the grid shows at (4,3)(4, 3) and (7,5)(7, 5); the top row and the left column are drawn, the bottom row and the right column are not.

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

7. 26+4/2−1=2726 + 4/2 - 1 = 27, the area.

8. The naive test draws the centres of the closed triangle: the II inside and the BB on the boundary. Fourth row: 74+24=9874 + 24 = 98.

9. The triangle (12,10)(12, 10), (22,13)(22, 13), (3,13)(3, 13) is clockwise. Its bottom edge, from (22,13)(22, 13) to (3,13)(3, 13), carries 20 centres, its two ends included; its edge from (3,13)(3, 13) to (12,10)(12, 10), a step of 3×(3,−1)3 \times (3, -1), carries 2 more strictly between its ends; the corner (12,10)(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)(3, 13) up to (12,10)(12, 10) is a left edge, and its 2 inner centres are kept. The corner (12,10)(12, 10) is also on the edge to (22,13)(22, 13), which runs down, and is refused. So 18+2=2018 + 2 = 20. A test checks the split.

10. The top-left rule draws every centre strictly inside, all with E>0E > 0, and some of those on the boundary, so its count is between II and I+BI + B. The area I+B/2−1I + 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=3B = 3 gives A=I+1/2A = 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 II or I+1I + 1, here 40, half a pixel from the area.

12. A single triangle may legitimately draw anything between II and I+BI + 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)×(3+s)(4 + s) \times (3 + s) cells for the seed ss, 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]×[0,48][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 8787 extra draws are 6666 pixels drawn twice or more, plus 2121 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: the two triangles run along the edge in opposite directions, and top_left is true for exactly one direction. The other two edge functions of each triangle are positive there.

20. A centre strictly inside a triangle TT has its three edge functions positive, and TT draws it. Another triangle T′T' of the mesh cannot contain it even in its closure: a small disc around the centre lies inside TT, and if the centre were in the closed T′T', the disc would contain inner points of T′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 (ε,ε2)(\varepsilon, \varepsilon^2), for a small enough ε>0\varepsilon > 0, is strictly inside. On an edge with E=0E = 0, the move changes EE by (bx−ax)ε2−(by−ay)ε(b_x - a_x)\varepsilon^2 - (b_y - a_y)\varepsilon; if by≠ayb_y \neq a_y, the first-order term decides, and it is positive when by<ayb_y < a_y, a left edge; if by=ayb_y = a_y, it is positive when bx>axb_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 x0<x1<x2x_0 < x_1 < x_2: the piece [x0,x1)[x_0, x_1) takes its left end and not its right one, and the next piece [x1,x2)[x_1, x_2) takes x1x_1. Every point belongs to exactly one piece. The top-left rule 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 II and I+BI + 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,0723{,}072 pixels of the image under the top-left rule, 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.

Istilah yang didefinisikan dalam bab ini

Lihat semua 1050 istilah di glosarium