Light and Pixels
How do millions of samples of light become a picture, and how many samples are enough?
The part opens with the series' own box rendered at 1, 4, 16 and 256 paths per pixel, its error falling close to 1/sqrt(N), and with the two ways to make a picture: a rasterized triangle and a ray-traced image. The first half builds the rasterizer. Homogeneous coordinates make translation linear, perspective is similar triangles and one division, and the depth it stores is affine in 1/d, so a 24-bit buffer that resolves 0.06 at distance 1000 with the near plane at 1 resolves only 5.9 with it at 0.01. Edge functions, barycentric coordinates, interpolation of 1/w, the z-buffer, shading and mipmaps follow, each measured against a ray-cast reference. The part then turns from triangles to light: rays meet spheres and triangles, a bounding volume hierarchy cuts 100,000 tests per ray to 2.5, and radiometry leads to Kajiya's rendering equation, whose Neumann series is summed bounce by bounce on screen. A path tracer solves it by Monte Carlo with cosine-weighted sampling, Russian roulette and next-event estimation, and a denoiser makes 16 paths look better than 256. It ends with Bezier curves, subdivision surfaces and fonts, and at the frontier with real-time ray tracing and neural rendering.
What you need. Vectors, matrices and the dot and cross products; integrals over an angle for the second half.
- Mathematics, ideas and history
- homogeneous coordinates, projection, rasterization, sampling and mipmaps, ray tracing, BVHs, the rendering equation, path tracing, Béziers
- What we build or compute
- a rasterizer and a path tracer
What you will be able to do
Degree
- Compose translations and rotations as 4 x 4 matrices and predict the effect of their order.
- Derive the perspective projection from similar triangles and say why the division cannot be part of the matrix.
- Evaluate a cubic Bezier curve by de Casteljau's construction and split it in two.
Graduate
- Derive perspective-correct interpolation and show that u/w and 1/w are affine on the screen.
- State the rendering equation, expand it as a Neumann series and identify each term with paths of a given number of bounces.
- Prove that Russian roulette leaves the estimator unbiased, and compute the variance it adds.
Research
- Explain what a denoiser trades for its lower error, and why a guarantee for it is an open problem.
- Describe neural radiance fields and Gaussian splatting as this part's rendering run in reverse, and what is lost.
Industry
- Choose near and far planes and a depth format so that two surfaces a given gap apart do not z-fight.
- Build a bounding volume hierarchy with the surface-area heuristic and count box and triangle tests per ray.
- Compare sampling strategies by efficiency, 1 / (error squared x time), at equal sample counts.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 22 min · Graduate 51 min · Research 53 min · Industry 31 min.
- 0A picture is samples of lightDegree2 min
- 1Transforms and rotationsDegree4 min
- 2Perspective projectionDegree4 min
- 3Rasterization and the z-bufferDegree4 min
- 4ShadingDegree3 min
- 5Textures and samplingGraduate4 min
- 6The GPU pipelineIndustry3 min
- 7Ray tracingGraduate4 min
- 8Acceleration structuresIndustry4 min
- 9Radiometry and BRDFsGraduate4 min
- 10The rendering equationGraduate4 min
- 11Path tracingGraduate5 min
- 12Our path tracer, and denoisingIndustry3 min
- 13Curves, surfaces and fontsDegree3 min
- 14Frontier: real time, and neural renderingResearch2 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
A picture is samples of lightDegree2 min
This picture was made by the program we build in this part. With one path of light per pixel it is mostly noise. Each pixel's colour is a random estimate of how much light reaches it, bounced around a box with a red wall, a green wall, a mirror ball and a light in the ceiling. With four paths the shapes appear; with sixteen the colours; with two hundred and fifty-six it is nearly clean, and the soft shadows and the red light spilling onto the white ball are not painted on: they come out of the physics. The error falls like one over the square root of the number of paths, the Monte Carlo rate of Part 20, so four times the work halves the noise.
There are two ways to turn a scene into pixels, and this part builds both. Rasterization takes each triangle, projects its corners onto the screen with linear algebra and one division, and fills in the pixels it covers, here blending three colours across one triangle. Games and user interfaces work this way, sixty or more times a second. Ray tracing works backwards: from the eye, through each pixel, into the scene, bouncing off mirrors and through glass. This small image took 41,563 rays. Ivan Sutherland's Sketchpad drew lines on a screen in 1963. Turner Whitted traced recursive rays in 1980. The mathematics between them is the subject of this part.
1Transforms and rotationsDegree4 min
A scene is made of points, and a renderer's first job is to move them: each object into the world, and the world in front of the camera. A matrix moves every point at once. Its columns say where the two axis arrows land, and because the map is linear, everything else follows. Rotations, scalings and shears all work this way, and one after another is a single matrix, their product. But a linear map never moves the origin, so the simplest motion of all, sliding sideways, is not a matrix of this size.
The fix is to add one coordinate. A general motion is a matrix times the point, plus a constant. Give every point an extra coordinate, w, equal to one, and put the constant in a new last column: the matrix multiplies that one and adds the translation for us. Here is the picture one dimension down. Points live on the line where w is one. A shear of the plane keeps the origin fixed, as linear maps must, yet slides the line along itself: a translation. These are August Möbius's homogeneous coordinates of 1827. Directions get w equal to zero, so they turn but never move.
Now a chain of motions multiplies into one matrix. But matrix products do not commute, and they act from right to left. On the left, the unit square is rotated a quarter turn, then moved two units right. On the right, the same two matrices in the other order: moved first, then swung around the origin. The corners, computed by our transform module, land in different places. A renderer multiplies three such matrices: the model matrix places an object in the world, the view matrix puts the world in front of the camera, and the projection matrix, next chapter, prepares perspective.
Rotations in three dimensions are usually described by three angles: yaw, pitch and roll. Watch the roll axis as the pitch rises. At ninety degrees it lies along the yaw axis: yaw and roll now spin about the same line, and one way of turning is gone. This is gimbal lock. Our transform module measures it: the singular values of the map from angle rates to spin are one, and the square roots of one plus and one minus the sine of the pitch. At eighty-nine degrees the smallest is about one hundredth; at ninety, zero, and the rank falls to two.
The cure is older than computers. In 1843 William Rowan Hamilton found numbers with three imaginary units whose squares are all minus one. A turn by theta about an axis is the unit quaternion of cosine and sine of half the angle. To rotate a vector, multiply by q on one side and its conjugate on the other. Euler angles are compact but singular. A matrix has nine numbers, which Part 4's rounding slowly pushes away from a rotation. A quaternion has four, never locks, and is repaired by dividing by its length.
2Perspective projectionDegree4 min
Why do far things look small? Leon Battista Alberti wrote down the painter's answer in 1435, and it is similar triangles. Put the eye at the origin and a screen at distance n. A point at height y and distance d is seen along this line, which crosses the screen at height y prime. The small triangle and the large one have the same angles, so y prime over n equals y over d. Multiply through: y prime is n y over d. Twice as far, half as tall. Every coordinate is divided by depth, and division is not linear, so no matrix can do it alone.
The fourth coordinate rescues us. The projection matrix scales x and y by the focal factor, and its last row copies the distance into w. Nothing has been divided yet: these are clip coordinates. The hardware then divides by w, once per vertex, and that one division is all of perspective. The third row must keep depth for the depth buffer. After the division it is minus A plus B over d. Ask that the near plane land at minus one and the far plane at plus one, and solve. Stored depth is affine in one over the distance, not in the distance, and that will cost us precision.
Here is what the matrix and the division do to space. This is the frustum, the truncated pyramid the camera sees between the near and far planes, with three equally spaced slices. Apply the map a little at a time. The far face shrinks and the near face grows, until the frustum is a cube from minus one to one in every coordinate. Straight lines stay straight all the way. But look at the slices: equally spaced in the world, they crowd towards the far face. Triangles are clipped before the division, while everything is still linear, and the cube is finally stretched onto the pixels.
How much does that crowding matter? Plot stored depth against distance, for a near plane at a tenth of a unit and a far plane at a thousand. Half of the whole range is used up before twice the near distance, and ninety percent before distance one. Depth buffers store integers. Picture one with only four bits: its sixteen values sit at sixteen over sixteen minus k. Half of them lie before distance two. And a single step covers the whole back half of the scene, from eight to sixteen.
When two surfaces are closer than that gap, their depths round to the same integer, and drawing order decides which one shows. Our module draws two planes a hundredth of a unit apart at distance fifty. With a sixteen-bit buffer and the near plane at a hundredth, ninety-nine percent of the pixels show the wrong plane. Twenty-four bits cut it to about a third. Moving the near plane out to one helps less on its own, to about seventy percent; with both, every pixel is right. Modern engines also store depth reversed, in floating point, so that the dense floats near zero of Part 4 land on the distant geometry that needs them.
3Rasterization and the z-bufferDegree4 min
Which pixels does a triangle cover? For an edge from a to b, take the cross product of the edge with the vector to a point p: twice the signed area of the triangle a, b, p, Part 22's orientation test, telling which side of the edge p is on. Test every pixel centre against the three edges in turn. A centre on the wrong side of any edge is out; the rest are in, and a tie-breaking rule gives a centre exactly on a shared edge to one triangle only. Each edge function is affine, so one pixel to the right adds a constant, and hardware tests whole blocks at once. About half the bounding box was inside.
Once a pixel is inside, we need its colour, its depth, its texture position: values given only at the three corners. A point p splits the triangle into three smaller ones. The share of the area opposite each corner is that corner's weight, lambda, and the three weights add to one. Move p around and watch: near a corner, that corner's weight approaches one. These are barycentric coordinates, from August Möbius in 1827 again, and they come free from the edge functions we already computed. Any value at the corners is blended with the same weights. Give the corners pure red, green and blue, and our rasterizer paints the weights themselves.
There is a catch, and it is perspective. Equal steps across the screen are not equal steps across a floor that recedes from the eye. The point halfway between two vertices on the screen is much nearer than the point halfway along the floor. So blending a texture coordinate by screen fractions is wrong. What is right? On a flat triangle, one over the depth is an affine function of screen position: divide the plane's equation by depth to see it. So is any attribute divided by depth. So interpolate u over w and one over w, both linearly, and divide one by the other at every pixel. That division is perspective-correct interpolation.
Here is the difference, from our own rasterizer. A checkered floor made of two triangles, with texture coordinates interpolated affinely: the squares bend along the diagonal where the triangles meet, and almost half of the floor's pixels get the wrong colour. With one over w, every pixel is right. And against a ray cast of the true floor, the texture coordinates agree to rounding error. The original PlayStation, in 1994, skipped this division, and its textures famously wobbled.
Now visibility: which of two overlapping triangles do we see? These two pass through each other, so each is in front over part of the overlap. The painter's algorithm sorts whole triangles from back to front. The blue one is farther on average, so it is painted first and covered everywhere: four hundred and seventy-two pixels wrong. No order of whole triangles can be right. Ed Catmull's answer, in 1974, was a depth for every pixel: a fragment is written only if it is nearer than what is there. The result is right in any drawing order, for one number per pixel, a price steep in 1974 and trivial today.
4ShadingDegree3 min
Now that we know which triangle a pixel sees, how bright should it be? Start with a beam of light falling straight onto a matte surface. Tilt the light. The same beam now spreads over a longer stretch of surface, one over the cosine of the angle as long, so each bit of surface receives less, in proportion to the cosine. Johann Heinrich Lambert wrote this down in 1760. The power per unit area is the power over the area, and the area grows as one over the cosine. So brightness goes as the cosine, which is the dot product of the unit normal with the unit vector towards the light. A matte surface scatters that light equally in all directions, so it looks the same from anywhere: here is our sphere with diffuse light alone.
Shiny surfaces add a highlight, and in 1975 Bui Tuong Phong, at Utah, gave the model still taught first. Reflect the light direction in the normal. Its projection onto the normal is N dot L times N; go there twice and step back by L, and you have the mirror direction R. The highlight is brightest when the eye looks straight down R, and falls off as the cosine between R and the view direction, raised to a power s. A larger power makes a tighter lobe and a smaller, sharper highlight, a shinier material. Add an ambient constant for light from everywhere else, the diffuse term and the highlight, and this is our rasterizer's sphere, with the power at thirty-two.
In 1977 Jim Blinn proposed a cheaper highlight. Instead of reflecting the light, take the vector halfway between the light and the eye, H, and measure how close the normal is to it. When the normal is exactly H, the eye sits in the mirror direction. The two highlights are not the same width with the same power. Near the peak, Phong's cosine to the power s behaves like a Gaussian in the angle alpha. The angle to H is about half of alpha, so Blinn's power must be four times larger to match. With a distant light and viewer, H is the same at every pixel, which made this the fixed-function lighting of OpenGL and Direct3D.
One last trap, back in chapter one's matrices. Normals are directions, so they are not translated. But squash a circle into an ellipse and move its normals with the same matrix, and they tilt: they are no longer perpendicular to the surface, and the lighting is wrong. Why? A normal is defined by being perpendicular to every tangent. Slip the identity, M inverse times M, between them. The tangents move by M, so to keep the product zero, normals must move by the inverse transpose. For rotations the two are the same matrix, which is why the mistake hides until an object is stretched, and why engines hand their shaders a separate normal matrix.
5Textures and samplingGraduate4 min
A texture is a picture glued onto a surface, Ed Catmull's idea of 1974. Looking it up is sampling, and sampling has a trap. A wave of nine cycles, sampled ten times. Join the samples and they trace a wave of one cycle, going the wrong way: an alias. A frequency f, sampled at a rate f s, is indistinguishable from f minus any multiple of f s. To be safe, take more than two samples per cycle, Nyquist's rule from Part 36. Our rasterizer looks up one texel at each pixel's centre. Near the horizon each pixel spans many squares, far beyond the Nyquist limit, and the samples draw curves that are not there: moiré.
Two cures: filter the texture before sampling, or take more samples. Here is the floor four ways, from our renderer. Point sampling: the moiré. The reference: two hundred and fifty-six jittered samples per pixel, averaged. Against it, point sampling is off by about a fifth of full brightness. A trilinear mipmap reads eight texels per pixel and cuts that error by a factor of three. Sixteen samples per pixel do slightly better, at twice the reads, and the far rows still shimmer. The cheap winner is the prefiltered texture.
In 1983 Lance Williams proposed filtering the texture in advance, at every scale. Level zero is the texture. Each next level averages two by two blocks of the one before: half the width, half the height. By level five each texel covers a light and a dark square equally, and the pattern has become its average grey. Williams called it a mip map, from multum in parvo, many things in a small place. The cost? Each level has a quarter of the texels of the one before. The extra memory is a geometric series, one third. Our sixteen thousand texels become twenty-two thousand.
Which level should a pixel read? The one whose texels match the pixel's footprint. Step one pixel right, or one down, and measure how far the texture coordinates move, in texels; call the larger rho. If a step crosses four texels, then two levels down a texel is four times wider: the level is the logarithm, base two, of rho. Lambda is rarely whole, so trilinear filtering reads the two nearest levels, four texels each, and blends them: the eight reads. Here is the level our renderer chose at each pixel: zero near the camera, rising to seven, the single grey texel, at the horizon. On real hardware the derivatives come from neighbouring pixels, as the next chapter shows.
Mipmaps fix the inside of a triangle, but edges alias too, into staircases. The brute-force cure is supersampling: sixteen samples per pixel, each shaded, then averaged, for sixteen times the cost. Multisample antialiasing, MSAA, sees that a staircase is a coverage problem. It tests coverage and depth at four points per pixel, but runs the shader once per pixel per triangle and copies the colour to the covered samples. Averaging the samples softens the edge. Inside a triangle all four samples agree, so textures still need mipmaps. On our floor, sixteen samples beat the mipmap only slightly, for sixteen times the work. Good sampling is cheaper than more sampling.
6The GPU pipelineIndustry3 min
Everything so far is what a graphics processor does in hardware, organised as a pipeline. Vertices are fetched from memory and handed to a small program, the vertex shader, which applies the matrices of chapters one and two and outputs each vertex in clip coordinates. Fixed hardware clips, divides by w and maps to the screen, then rasterizes with chapter three's edge functions, producing fragments: candidate pixels carrying interpolated values. A second program, the fragment shader, computes each fragment's colour: chapters four and five. Finally the depth test and blending write the framebuffer. The green stages are programs you write; the orange ones are silicon. OpenGL, Direct3D, Vulkan, Metal and WebGPU all expose this same shape.
Here are the two programs, in the style of OpenGL's shading language. The vertex shader runs once per vertex. It multiplies the position by one combined model, view and projection matrix, and moves the normal by the normal matrix, chapter four's inverse transpose. Whatever it outputs, here the normal and the texture coordinates, the rasterizer interpolates across the triangle, perspective-correctly, with chapter three's one over w. The fragment shader runs once per fragment: renormalize the normal and take Lambert's cosine, then multiply by a texture lookup. That one call is chapter five's trilinear filter, in dedicated hardware. Neither program can see any other vertex or fragment, and that independence is what lets a GPU run millions of them at once.
How many runs is that? A screen of nineteen twenty by ten eighty has about two million pixels, and each needs its own fragment shader run, sixty times a second. Because every run is independent, the GPU packs fragments, in blocks of two by two called quads, into groups that share one instruction stream: on NVIDIA hardware a warp of thirty-two lanes, the SIMT model of Part 10 and of AI, Built part seventeen. The price is branching. If some fragments of a warp take one side of an if and the rest take the other, the warp runs both sides, one after the other, with part of its lanes switched off each time. A shader that branches pixel by pixel can run at half speed, or worse.
Last, where the depth test sits. Chapter three's two crossing triangles produce six thousand five hundred and seventy-six fragments. If every fragment is shaded first and depth-tested afterwards, every one of them pays for a fragment shader. GPUs test depth before shading whenever the shader cannot change the outcome. In our run, six hundred and ninety-three fragments fail the test, and are never shaded. But only five thousand four hundred and twelve pixels are visible: four hundred and seventy-one fragments passed, were shaded, and were painted over by a nearer one drawn later. So engines draw opaque objects front to back, or lay down depth in a first pass, and then shade each visible pixel exactly once.
7Ray tracingGraduate4 min
Rasterization starts from the triangles; ray tracing starts from the eye. For every pixel, shoot a ray through the pixel's centre: a point o plus t times a direction d. Intersect it with every object and keep the nearest hit with t positive: that is what the pixel sees. Arthur Appel did this in 1968, for hidden surfaces and shadows. It is the z-buffer turned around: instead of each triangle asking which pixels it covers, each pixel asks which object it meets first. Our tracer sends nineteen thousand two hundred such rays for a small image, then, following Turner Whitted, keeps going.
The simplest object is a sphere. A point on the ray is on the sphere when its distance from the centre is the radius. Expand the squared length as a dot product, and it is a quadratic in t. Name the coefficients A, B and C, and the roots follow. The discriminant decides everything. Slide the ray: positive, two hits, in and out; zero, the ray grazes the sphere; negative, it misses. The smaller positive root is the hit we see. And from Part 4: the textbook formula can subtract nearly equal numbers, so our code computes one root safely and the other from their product.
Most scenes are triangles. In 1997 Tomas Möller and Ben Trumbore published the test most ray tracers still use. A point of the triangle is a blend of its corners with barycentric weights, chapter three's again; the ray hits it when the two points agree. Measure everything from the first corner, along the two edges. That is a three by three linear system for t, u and v. Solve it by Cramer's rule: each determinant is a triple product, and they share two cross products, p and q. It is a hit when u and v are non-negative, sum to at most one, and t is positive; and u and v come out free, ready for texturing.
Turner Whitted's paper of 1980 asked what happens after the first hit. At a matte surface, cast a shadow ray towards the light; if something is in the way, the point is in shadow. At a mirror, trace the reflected ray by the same procedure. Here it finds the red ball, at a point the mirror itself hides from the light. At glass, trace two: a reflected ray, and a refracted one that bends into the ball and out again. Each pixel grows a tree. Our tracer counts them: nineteen thousand two hundred primary rays, thirteen and a half thousand shadow rays, over four thousand each reflected and refracted: about two per pixel.
Glass bends light. Snell's law: the index of refraction times the sine of the angle is the same on both sides. A ray tracer wants it in vectors: the bent direction is a blend of the incoming direction and the normal, no angles needed. Going from glass into air, the square root can fail. Tilt the ray inside the glass: beyond about forty-two degrees there is no refracted ray, and all the light reflects. In a ball this never happens: the radii to entry and exit make an isosceles triangle, so a ray leaves at the angle it entered. Our tracer counted zero.
8Acceleration structuresIndustry4 min
A ray tracer spends nearly all its time on one question: which triangle does this ray hit first? The obvious answer tests every triangle and keeps the nearest. Forty triangles, forty tests, for one hit. Our Whitted image used forty-one and a half thousand rays. Against a mesh of a hundred thousand triangles, the largest we test below, that is over four billion intersection tests for a tiny picture. And almost all of them are wasted: each ray keeps one answer. The cure, from Steven Rubin and Turner Whitted in 1980, is the same as for a library: put things in boxes, and boxes in bigger boxes. A ray that misses a box can skip everything inside it.
Here is the idea built on our forty triangles. Put one box around everything: the root. Sort the triangles along the box's wider side and split them at the median, boxing each half. Repeat inside each half, and again, until a box holds at most three triangles. Each box is a node of a binary tree, the leaves hold the triangles. The boxes of two children may overlap. A bounding volume hierarchy divides the objects, not space, so every triangle lives in exactly one leaf, and a box can be refitted cheaply when its triangles move. Halving at every level, the depth grows like the logarithm of the number of triangles.
Now trace a ray through the tree. Testing a box is cheap: Kay and Kajiya's slab test. For each axis, find where the ray enters and leaves the slab between the box's two planes. The ray is inside the box between the latest entry and the earliest exit, so it hits the box when that interval is not empty. Start at the root. At each box it enters, visit the nearer child first; skip a box it misses, or one that begins beyond the best hit found so far. In the leaves it reaches, test the triangles. This ray needed a handful of boxes and a few triangles instead of all forty, and found the same nearest hit.
The median split ignores where the triangles are. Here, nine are bunched at the left and three spread to the right. Where should the box be cut? Price a split by its expected cost: one box test, plus each child's triangles, weighted by the chance that a ray entering the parent enters that child. For random rays that chance is the child's surface area over the parent's, a classical result of integral geometry. With both unit costs one, as in our builder, this is the surface area heuristic of MacDonald and Booth, 1990. Sweep a candidate plane across, as Part 22 swept lines, and evaluate the cost at each position. The median cuts through the cluster and leaves a wide box of six. The cheapest plane puts the whole cluster in one compact box, the three stragglers in another. And if no split beats testing every triangle, make a leaf.
9Radiometry and BRDFsGraduate4 min
First, directions. An angle in the plane is an arc length divided by the radius, in radians. A solid angle is the same idea one dimension up: the area a shape covers on a sphere, divided by the radius squared, in steradians. On the unit sphere a small patch of latitude and longitude has area sine theta d theta d phi. Integrate it over a cap of half-angle alpha: two pi times one minus cos alpha. Open the cap to ninety degrees and it covers every direction above a surface: two pi steradians, half the sphere's four pi.
Now the quantities. Radiant flux, capital phi, is energy per second, in watts. Irradiance is flux arriving per unit area: how brightly a surface is lit. Radiance divides once more: flux per unit area across the beam, per unit solid angle. The cosine is there because a patch seen at a slant presents only cos theta of its area. Radiance is what a camera pixel measures: a small area looking along a narrow cone. Gathered over the hemisphere with the cosine, radiance gives back irradiance: Lambert's law of chapter four.
How a material reflects is a function of two directions. The BRDF, the bidirectional reflectance distribution function named by Fred Nicodemus and colleagues in 1977, is the radiance going out in one direction per unit of irradiance arriving from another. Add up every incoming direction, and we have the reflection equation. A matte surface scatters equally everywhere, so its BRDF is a constant, rho over pi. Why pi? The cosine integrated over the hemisphere is two pi times one half: pi. So under uniform light of radiance one, a matte surface returns exactly its albedo. A glossy surface instead gathers its light into a lobe around the mirror direction.
Glossy surfaces are rough at a scale far below a pixel. In 1982 Robert Cook and Kenneth Torrance modelled them as tiny mirrors, microfacets, tilted at random. A facet sends light from one direction to the other only if its normal is the half vector between them. So the BRDF is D, the density of facets facing the half vector; times G, the fraction not hidden or shadowed by their neighbours; times F, the Fresnel reflectance of chapter seven; over four cosines from the change of variables. The GGX distribution, brought to graphics by Bruce Walter and colleagues in 2007, has one parameter, the roughness alpha. Turn it up and the facets spread: the highlight widens and dims.
Every physical BRDF obeys two rules, and our instruments check both. Reciprocity: swapping the two directions gives the same value. On ten thousand random pairs our four models agree to rounding. Energy conservation: lit equally from every direction, in a white furnace, a surface must return at most one. Lambert returns exactly one. Normalized Phong returns one head-on, and less at grazing angles, where its lobe dips below the horizon. The usual Blinn-Phong normalization is only approximate: at exponent ten it creates energy, one point nought seven five. GGX keeps nearly everything when smooth, but at roughness one it loses more than two thirds head-on, because the model leaves out light that bounces between facets more than once.
10The rendering equationGraduate4 min
Chapter nine's reflection equation needs the light arriving at a point. Take a point on the back wall. Light arrives from every direction in front of it. But each arrival is light leaving some other surface: the ceiling, the lamp, the two balls, or nothing at all through the open front. And what leaves that surface depends in turn on everything arriving there. Write it down. The light leaving a point is what it emits, plus what it reflects. The light arriving from a direction is the light leaving the first surface a ray meets that way, the job of chapters seven and eight. Substitute, and the unknown radiance appears on both sides. This is the rendering equation, published by James Kajiya in 1986: a balance of energy at every point and in every direction.
Name the integral as an operator. T takes a field of radiance and returns the light reflected once: cast a ray, look up the radiance there, weight it by the BRDF and the cosine, and integrate. The equation becomes L equals L e plus T L. Move T L across, and invert. Then expand as a geometric series, exactly as one over one minus x is one plus x plus x squared. This Neumann series converges when T shrinks every field, and chapter nine's furnace guarantees it: each reflection keeps at most its albedo. In a closed room with walls of albedo nought point seven three, our white walls, each bounce keeps seventy-three per cent, and the bounces add up to three point seven times the light emitted.
Each term of the series has a picture. L e alone is light that goes from the lamp straight into the eye. T L e is light that reflected once on its way to us: off the floor, or off the mirror ball. This is direct lighting. T squared L e is light that bounced twice, from the back wall onto the floor and then to the eye. Each term is an integral over every path with that many reflections, and the picture is the sum over all lengths. Eric Veach's thesis of 1997 wrote the whole equation as a single integral over paths, which is the form the next chapter samples.
Our path tracer records each path's light by the number of reflections it took, so we can watch the series add up, term by term, in our own scene. Bounce zero: only the lamp. Add bounce one, direct lighting. The floor and walls are lit, the balls cast shadows, and the mirror shows the walls; but the ceiling is black, because no light reaches it directly. Add bounce two. The ceiling appears, the shadows soften, and red and green light spills onto the white surfaces. Three, four, five and beyond: each adds less, and the picture settles into the converged image. Nothing here was painted on. Soft shadows and colour bleeding are simply the later terms of the series.
11Path tracingGraduate5 min
The rendering equation is an integral inside an integral, with no end, and Monte Carlo handles that. To estimate an integral, draw directions from any density p, and average the integrand divided by p: Part twenty's method. It is unbiased: under p, the expected value of g over p is exactly the integral. Now take a single sample at each bounce. From the eye the ray meets the back wall; choose one direction at random; it meets the ceiling; again, the matte ball; again, and it reaches the lamp. That is a path. A running weight, the throughput, is multiplied at each bounce by f cos theta over p, and the light the path finds, times its throughput, is one estimate of the pixel. This is path tracing, Kajiya's own algorithm.
Which density should we sample? Any works, but the noise depends on the choice. The integrand contains a cosine, so sample more often where the cosine is large, near the normal. Malley's method does this without any trigonometry. Pick points uniformly on a disk, then lift each one straight up onto the hemisphere above it. They crowd towards the top. The disk is the hemisphere seen from above, and a patch of directions d omega appears on it with area cos theta d omega. So the lifted directions have density cos theta over pi. For a matte surface, f cos theta over p is then just the albedo. Every bounce multiplies the throughput by the same number, and the cosine adds no noise at all.
When should a path stop? Cutting every path at a fixed length drops the later terms of the series: a bias. A path's throughput shrinks at each bounce, so its later terms matter less and less. Russian roulette, brought to graphics by James Arvo and David Kirk in 1990, stops paths at random instead: keep the path with probability q, and if it survives, divide its weight by q. The proof is one line. The expected contribution is q times X over q, plus one minus q times zero: X. The price is some extra variance, growing as q falls. Our tracer plays from the third bounce, with q equal to the throughput, capped at nought point nine five: dim paths usually die, and survivors return to full weight.
Our light is small, a sixteenth of the ceiling. A path that leaves the floor in a random direction rarely hits it: here, none of nine. The paths that do find it are rare and bright: that is noise. Next-event estimation aims at the light directly. At every matte vertex, pick a point on the lamp and send a shadow ray towards it. Converting area on the light to solid angle at the point gives two cosines over the distance squared. If the shadow ray is clear, add the direct light. Then, so nothing is counted twice, light that a later bounce reaches by chance is ignored, except after a mirror, which a shadow ray cannot aim through.
Light sampling is not always best. With a small light and a broad lobe it is ideal: every sample lands where the integrand lives. But with a large light and a narrow, shiny lobe, most light samples land where the BRDF is nearly zero, and sampling the BRDF is far better. Eric Veach and Leonidas Guibas showed in 1995 how to use both: draw samples from each strategy, and weight every sample. If the weights sum to one in every direction, the combination is unbiased, whatever they are. The balance heuristic weights a sample by its own strategy's density over the sum of all of them, so each region is handled mostly by the strategy that samples it best, and Veach proved it is never much worse than the best single strategy.
12Our path tracer, and denoisingIndustry3 min
Here is one corner of our render, enlarged: the white ball, the blue ball and the green wall. One path per pixel is speckle. Each step multiplies the paths by four, and the time with them, from under three hundredths of a second to over six seconds. Each path is an independent random estimate, and the pixel is their average. The variance of an average of N independent terms is sigma squared over N, so the error falls as one over the square root of N: four times the work halves the noise.
Now the whole image, against a reference of two thousand and forty-eight paths per pixel. On logarithmic axes the error falls on a line. Its slope is minus nought point four six, close to Monte Carlo's minus one half. The last point sits a little high, because the reference is noisy too. Time grows with the paths, so each halving of the error costs four times the time. The rate is fixed; the rest of this chapter attacks the constant, sigma.
The other way to fight noise is to borrow from the neighbours, with the edge-avoiding à-trous filter of Holger Dammertz and colleagues, from 2010. A pass blends each pixel with twenty-five neighbours under a small, smooth kernel. Each pass spreads the taps twice as far apart, with holes between them: à trous. Three passes, seventy-five taps in all, reach across a square twenty-nine pixels wide. To keep edges, each tap is also weighted by how alike the two pixels are, in colour, normal, albedo and position. And only the light is blurred: divide by the albedo, filter, and multiply it back, so the walls' colours stay sharp.
Here is the filter on sixteen paths per pixel. Around the balls the speckle is gone, while the edges and soft shadows survive: the error on the surfaces is four times smaller. On the ceiling, lit only indirectly, the noise turns into blotches, error at low frequencies that no filter can tell from real light. Over all pixels the error falls much less, because the noise on the light's own edge is left alone. The filter costs a third of a second, less than the render. But it is biased: it trades noise for blur.
13Curves, surfaces and fontsDegree3 min
Smooth shapes need curves, and the standard one was found twice, at two car makers: by Paul de Casteljau at Citroën in 1959, and by Pierre Bézier at Renault, who published it in the 1960s. Start with four control points. Pick a fraction t. Go that fraction along each leg of the polygon, and join the new points. Repeat until one point is left: that is the curve at t. Sweep t from nought to one, and the point draws the whole curve. At one half, our instrument gives the point two, one point six. The construction gives more. Frozen at one half, the first points of each level are the control points of the curve's left half, and the last points those of its right half. Split until every piece is nearly straight, then draw lines: that is how a renderer draws a curve.
What polynomial is the construction computing? One level is a linear interpolation between two points. Two levels nest them, a lerp of lerps. Multiply out, and the quadratic weights are one minus t squared, two t times one minus t, and t squared. Three levels give the cubic, and its four weights are the Bernstein polynomials. They are never negative and always sum to one. So the curve stays inside the convex hull of its control points; it starts and ends on the end points, tangent to the first and last legs; and moving the four points by a matrix moves the curve, so chapter one's transforms act on control points alone.
And curves are in front of you now. Every letter in this series is an outline made of Bézier curves. Here is the word Light, as Manim draws it from TeX's fonts. The dots are the anchor points where curves meet, and the squares are the control handles; a straight stroke is simply a curve whose handles lie on the line. This word is one hundred and ten cubic curves, and the heading above it is five hundred and thirty-six. PostScript, and the fonts TeX uses, store cubic curves; TrueType stores quadratics. To draw a letter, a rasterizer fills the outline by its winding number, and averages the coverage within each pixel: chapter five's anti-aliasing, so that curves look smooth on a grid of samples.
14Frontier: real time, and neural renderingResearch2 min
Can a path tracer run at sixty frames a second? A film frame can take hours. A game has sixteen milliseconds. The gap is closed first by taking very few samples: here our own image at sixteen paths a pixel, still noisy. Then a denoiser, the edge-aware filter of chapter twelve, smooths the noise guided by each pixel's normal and colour, and its error drops from 0.077 to 0.019, below that of two hundred and fifty-six paths. Real-time renderers add three more ideas: hardware since 2018 that walks bounding volume hierarchies in silicon; algorithms such as ReSTIR, from 2020, that reuse good light samples across neighbouring pixels and frames; and neural networks trained to denoise and upscale.
The newest idea turns rendering around. In 2020 Ben Mildenhall and colleagues trained a small network that maps a point and a viewing direction to a colour and a density, and rendered it by integrating along each ray, fitted to a few dozen photographs of a real scene. In 2023 Bernhard Kerbl and colleagues replaced the network with millions of small three-dimensional Gaussians, projected and blended by a rasterizer, which runs in real time. What is lost is the physics: there are no explicit materials or lights, so these scenes are hard to edit or relight. Both run this part backwards: given pictures, find the scene, the inverse problem of AI, Built part twenty-two.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. Transforms as matrices, with quaternions to rotate smoothly; perspective as linear algebra plus one division, and the depth buffer that division distorts. A rasterizer with edge functions and perspective-correct interpolation, shading, and textures sampled without aliasing. A ray tracer, accelerated by bounding volume hierarchies to a logarithm per ray. Radiometry and the rendering equation, solved by a path tracer whose noise falls as one over the square root of the samples, made practical by importance sampling and denoising. And the Bézier curves that draw every letter on screen. One idea runs through it: a picture is an integral, and every technique is a way of estimating it.
Where this comes back. Part 52 treats integration and linear solvers with the care rounding demands. Part 54 proves programs correct, graphics drivers among them. Part 57 asks when learning from images can generalize. Part 60 builds hardware for one job, and the GPU is the first and most successful example. And Part 61 returns to this part's open problems as research.
In practice. Game engines rasterize, and add ray-traced shadows and reflections where hardware allows. Graphics programming interfaces such as Vulkan, Metal and WebGPU expose shaders and command buffers. Film is rendered by production path tracers with denoisers, on render farms. Fonts, vector graphics and compositors draw every interface you use. And when a renderer is wrong, look at one sample per pixel: the noise tells you where the light is lost.
Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: give our path tracer a second light and sample both, then measure the noise. The last, marked with a star, is a research problem: an estimator for caustics whose variance is provably close to the best possible.
Next time, Part 52: computing with real numbers. With rounding in every operation, which answers can we trust? The answer separates how hard a problem is from how good an algorithm is, and leads to the algorithms that power all of scientific computing.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 52 treats integration and linear solvers with the care rounding demands. Part 57 asks when learning from images can generalize, and Part 60 builds hardware for one job, of which the GPU is the first example. Part 61 returns to this part's open problems as research.
Key results
The part's results in one place, for revision.
Try it
Lab 51 · Samples of light: noise, roulette and the white furnace
Estimate the light falling on a surface from a bright-overhead sky with the series' uniform and cosine-weighted samplers and fit how the error falls with the sample count, end paths in a room of albedo 0.73 by Russian roulette and by a hard cut-off, and check which shading models conserve energy.
python -m videos.cs.labs 51
needs numpy, scipy, matplotlib · download lab51.py ·
source on GitHubuniform sampling: relative error at 16, 256, 4096 samples 0.251, 0.0606, 0.0157 fitted slope -0.50 (theory -0.50)
cosine sampling: relative error at 16, 256, 4096 samples 0.111, 0.0273, 0.0069 fitted slope -0.50 (theory -0.50)
variance, uniform over cosine-weighted 4.9 times
room of albedo 0.73: exact 1/(1 - 0.73) 3.704
roulette, survive with q = 0.73 3.705 ± 0.007 2.70 rays a path
roulette, survive with q = 0.90 3.709 ± 0.003 9.03 rays a path
cut off after 5 bounces 3.143 (biased low) 5 rays a path
white furnace, seen head-on lambert 1.000 phong 1.000 blinn_phong 1.075 ggx 0.307
turning between two orientations slerp 139.2 degrees in equal steps of 3.48; Euler angles 237.2, unevenly
Every estimator's error falls on a line of slope -1/2 and good sampling only lowers the line; roulette shortens paths without bias where a cut-off darkens the picture; and a shading model can create or lose energy without anyone noticing until it is put in a furnace.
The code (124 lines; it asserts its own result)
"""Lab 51: watch Monte Carlo noise fall as 1/sqrt(N), test Russian roulette for bias, and put four BRDFs in a white furnace."""
from videos.coursekit import labs # noqa: I001 (must stay first: it lets explainer.cs import without manim)
import numpy as np
from explainer.cs.graphics import brdf, curves, transform
TITLE = "Samples of light: noise, roulette and the white furnace"
GOAL = ("Estimate the light falling on a surface from a bright-overhead sky with the series' uniform and "
"cosine-weighted samplers and fit how the error falls with the sample count, end paths in a room of albedo "
"0.73 by Russian roulette and by a hard cut-off, and check which shading models conserve energy.")
TASKS = [
"Change the sky from 1 + 3 cos^4 to a constant 1. What happens to the cosine-weighted estimator's error, and why is f cos / p then the same for every sample?",
"Play roulette with survival probability 0.5 instead of 0.73. The mean is still right in theory: compute the second moment of the throughput, (rho^2 / q)^k, and explain what you see.",
"Call transform.resolvable(1000, near, 1000) for near = 0.01, 0.1 and 1. How large a gap can a 24-bit depth buffer resolve at distance 1000, and what does moving the near plane buy?",
]
RHO = 0.73
EXACT = 2 * np.pi # the integral of (1 + 3 cos^4) cos over the hemisphere
def sky(w):
return 1 + 3 * w[..., 2] ** 4
def estimates(sampler, n, trials, rng):
w, pdf = sampler(rng.random((trials, n)), rng.random((trials, n)))
return (sky(w) * w[..., 2] / pdf).mean(axis=1)
def room(q, paths, rng, cut=None):
"""Light reaching the eye in a closed room of albedo RHO whose walls all emit 1: 1 + rho + rho^2 + ...
Roulette survives each bounce with probability q and divides by q; a cut-off simply stops after `cut` bounces."""
total, beta, alive, rays = np.ones(paths), np.ones(paths), np.ones(paths, bool), 0
for bounce in range(1, 400):
if cut is not None:
if bounce > cut:
break
beta = beta * RHO
else:
alive &= rng.random(paths) < q
beta = np.where(alive, beta * RHO / q, 0.0)
if not alive.any():
break
rays += int(alive.sum())
total += np.where(alive, beta, 0.0)
return total.mean(), total.std() / np.sqrt(paths), rays / paths
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. the error of a Monte Carlo estimate falls as 1 / sqrt(N); importance sampling lowers the whole line
ns, trials = (16, 64, 256, 1024, 4096), 400
rms = {}
for name, sampler in (("uniform", brdf.sample_uniform_hemisphere), ("cosine", brdf.sample_cosine_hemisphere)):
rms[name] = [float(np.sqrt(np.mean((estimates(sampler, n, trials, rng) - EXACT) ** 2))) / EXACT for n in ns]
slope = float(np.polyfit(np.log(ns), np.log(rms[name]), 1)[0])
assert abs(slope + 0.5) < 0.08, "the error falls as N^(-1/2)"
lab.row(f"{name} sampling: relative error at 16, 256, 4096 samples",
f"{rms[name][0]:.3f}, {rms[name][2]:.4f}, {rms[name][4]:.4f} fitted slope {slope:.2f} (theory -0.50)")
gain = (rms["uniform"][2] / rms["cosine"][2]) ** 2
assert gain > 1.5, "sampling in proportion to the cosine lowers the variance"
lab.row("variance, uniform over cosine-weighted", f"{gain:.1f} times")
# 2. Russian roulette is unbiased; cutting paths off is not
exact = 1 / (1 - RHO)
m_r, se_r, rays_r = room(RHO, 200_000, rng)
m_9, se_9, rays_9 = room(0.9, 200_000, rng)
m_c, _, rays_c = room(None, 1, rng, cut=5)
assert abs(m_r - exact) < 4 * se_r and abs(m_9 - exact) < 4 * se_9, "roulette keeps the mean"
assert abs(m_c - (1 - RHO ** 6) / (1 - RHO)) < 1e-9 and m_c < exact - 0.5, "a cut-off loses the later bounces"
lab.row("room of albedo 0.73: exact 1/(1 - 0.73)", f"{exact:.3f}")
lab.row("roulette, survive with q = 0.73", f"{m_r:.3f} ± {se_r:.3f} {rays_r:.2f} rays a path")
lab.row("roulette, survive with q = 0.90", f"{m_9:.3f} ± {se_9:.3f} {rays_9:.2f} rays a path")
lab.row("cut off after 5 bounces", f"{m_c:.3f} (biased low) {rays_c:.0f} rays a path")
# 3. the white furnace: light returned by a surface lit equally from everywhere
head_on = brdf.direction(0.0)
furnace = {}
for model, param in (("lambert", 1.0), ("phong", 10), ("blinn_phong", 10), ("ggx", 1.0)):
quad = brdf.albedo_quadrature(model, param, head_on, theta_panels=64, n_phi=256)
mc, se = brdf.albedo_mc(model, param, head_on, samples=100_000, seed=seed)
assert abs(mc - quad) < 4 * se + 2e-3, model
furnace[model] = quad
assert abs(furnace["lambert"] - 1) < 1e-3 and abs(furnace["phong"] - 1) < 5e-3
assert furnace["blinn_phong"] > 1.05 and furnace["ggx"] < 0.4, "one model creates energy, one loses it"
lab.row("white furnace, seen head-on", " ".join(f"{k} {v:.3f}" for k, v in furnace.items()))
# 4. two exact checks: de Casteljau against Bernstein's polynomials, slerp's constant step
pts = np.array([(0, 0), (1, 2), (3, 2.2), (4, 0.2)], float)
t = float(rng.uniform(0.05, 0.95))
bern = (1 - t) ** 3 * pts[0] + 3 * t * (1 - t) ** 2 * pts[1] + 3 * t * t * (1 - t) * pts[2] + t ** 3 * pts[3]
assert np.allclose(curves.de_casteljau(pts, t)["point"], bern, atol=1e-12)
sl = transform.slerp_vs_euler()
steps = sl["slerp"]["per_step_deg"]
assert max(steps) - min(steps) < 1e-6 and abs(sl["slerp"]["total_deg"] - sl["geodesic_deg"]) < 1e-6
assert sl["euler"]["total_deg"] > sl["geodesic_deg"] + 50
lab.row("turning between two orientations", f"slerp {sl['slerp']['total_deg']:.1f} degrees in equal steps of "
f"{steps[0]:.2f}; Euler angles {sl['euler']['total_deg']:.1f}, unevenly")
lab.note = ("Every estimator's error falls on a line of slope -1/2 and good sampling only lowers the line; "
"roulette shortens paths without bias where a cut-off darkens the picture; and a shading model can "
"create or lose energy without anyone noticing until it is put in a furnace.")
fig, ax = labs.figure(2, size=(11, 4.3))
ax[0].loglog(ns, rms["uniform"], "o-", color=labs.ORANGE, label="uniform over the hemisphere")
ax[0].loglog(ns, rms["cosine"], "o-", color=labs.BLUE, label="cosine-weighted")
ax[0].loglog(ns, rms["uniform"][0] * np.sqrt(ns[0] / np.array(ns)), color=labs.MUTED, ls="--", label="1 / sqrt(N)")
ax[0].set(title="Error of the estimated irradiance", xlabel="samples N", ylabel="relative RMS error, 400 trials")
ax[0].legend()
angles = np.array([0, 15, 30, 45, 60, 70, 80, 85])
for (model, param, label), color in zip((("lambert", 1.0, "Lambert"), ("phong", 10, "Phong, n = 10 (normalized)"),
("blinn_phong", 10, "Blinn-Phong, n = 10"), ("ggx", 1.0, "GGX, alpha = 1")),
(labs.GREEN, labs.BLUE, labs.RED, labs.PURPLE)):
ax[1].plot(angles, [brdf.albedo_quadrature(model, param, brdf.direction(float(a)), theta_panels=48, n_phi=192)
for a in angles], "o-", color=color, label=label)
ax[1].axhline(1, color=labs.MUTED, ls="--", lw=1)
ax[1].set(title="White furnace: share of the light returned", xlabel="viewing angle from the normal (degrees)",
ylabel="directional albedo", ylim=(0, 1.3))
ax[1].legend(fontsize=8, loc="lower left")
lab.fig = fig
return lab
Now change it
- Change the sky from 1 + 3 cos^4 to a constant 1. What happens to the cosine-weighted estimator's error, and why is f cos / p then the same for every sample?
- Play roulette with survival probability 0.5 instead of 0.73. The mean is still right in theory: compute the second moment of the throughput, (rho^2 / q)^k, and explain what you see.
- Call transform.resolvable(1000, near, 1000) for near = 0.01, 0.1 and 1. How large a gap can a 24-bit depth buffer resolve at distance 1000, and what does moving the near plane buy?
Problems, with solutions
Try each problem before opening its solution.
-
Perspective. Derive the perspective matrix that maps the frustum to the cube [−1, 1]³, and show depth is affine in 1/z.
Solution
In eye space the camera is at the origin looking down −z, so a point in front is at distance d = −z. By similar triangles a point at height y lands on a screen at distance n at height n y/d. Scale the screen so the top of the field of view, y = d tan(fov/2), lands at 1: y_ndc = c y/d with c = cot(fov/2), and likewise x_ndc = (c/a) x/d for aspect ratio a. Both are linear in the point divided by d = −z, so the fourth row is (0, 0, −1, 0), which puts w = d, and the first two rows are (c/a, 0, 0, 0) and (0, c, 0, 0). Depth may not depend on x or y, so the third row is (0, 0, A, B), and after the division z_ndc = (A z + B)/(−z) = −A + B/d. Asking for d = n ↦ −1 and d = f ↦ +1 gives −A + B/n = −1 and −A + B/f = 1; subtracting, B(1/n − 1/f) = −2, so B = 2fn/(n − f), and then A = 1 + B/n = (f + n)/(n − f). Hence z_ndc = (f + n)/(f − n) − (2fn/(f − n)) · (1/d): affine in 1/d = −1/z, not in z. The side faces x = ±a d tan(fov/2) and y = ±d tan(fov/2) go to ±1, so the frustum becomes the cube. For ours (60°, 4:3, n = 1, f = 4): c = √3 = 1.732, c/a = 1.299, A = −5/3, B = −8/3, and d = 1, 1.75, 2.5, 3.25, 4 land at z_ndc = −1, 0.14, 0.60, 0.85, 1. The price: dz_ndc/dd = 2fn/((f − n) d²), so one step 1/(2^b − 1) of window depth (z_ndc + 1)/2 spans Δ ≈ d²(f − n)/(f n (2^b − 1)): 5.96 at d = 1000 for n = 0.01, f = 1000 and b = 24 (bisection on the exact mapping: 5.93), and 0.060 for n = 1.
-
Why 1/w. Show that interpolating u/w and 1/w linearly in screen space gives perspective-correct u.
Solution
A triangle lies in a plane m · P = k of eye space (k ≠ 0, or the eye is in the plane and the triangle is seen edge on). Screen position (x_s, y_s) is an affine function of (x/w, y/w), with w = −z, so every point of the plane is P = w r(x_s, y_s), where r = (x/w, y/w, −1) is affine in screen position. Substituting, w (m · r) = k, so 1/w = (m · r)/k is affine in (x_s, y_s). An attribute that is affine over the triangle in 3D, u = g · P + h, gives u/w = g · r + h · (1/w), again affine in screen position. Linear interpolation with screen-space barycentrics λᵢ reproduces affine functions exactly, so u/w = Σ λᵢ uᵢ/wᵢ and 1/w = Σ λᵢ/wᵢ, and u = (Σ λᵢ uᵢ/wᵢ)/(Σ λᵢ/wᵢ); equivalently the true barycentrics are bᵢ = (λᵢ/wᵢ)/Σⱼ (λⱼ/wⱼ). Interpolating u directly is wrong whenever the wᵢ differ, since u is a ratio of two affine functions, not one. Example: an edge from depth 2 to depth 12 with u from 0 to 8, like our floor. At the screen midpoint affine interpolation gives u = 4; the correct value is (½ · 0/2 + ½ · 8/12)/(½ · 1/2 + ½ · 1/12) = 1.14, at depth 3.43, and the floor's own midpoint (depth 7, u = 4) appears 86% of the way across. On our two-triangle floor affine interpolation colours 48.5% of the 3,934 pixels wrongly, interpolation with 1/w none, matching the ray cast to 1.8 × 10⁻¹⁴.
-
Möller–Trumbore. Derive the ray–triangle test with Cramer's rule.
Solution
A point of the triangle is (1 − u − v) v₀ + u v₁ + v v₂ with u, v ≥ 0 and u + v ≤ 1. Setting it equal to the ray o + t d and writing e₁ = v₁ − v₀, e₂ = v₂ − v₀, s = o − v₀ gives −t d + u e₁ + v e₂ = s, the linear system [−d e₁ e₂](t, u, v)ᵀ = s. With det[a b c] = a · (b × c), the determinant is (−d) · (e₁ × e₂) = e₁ · (d × e₂) = e₁ · p, where p = d × e₂; if it is near zero the ray is parallel to the plane. Cramer's rule replaces one column by s: u = det[−d s e₂]/det = −d · (s × e₂)/det = s · p/det; with q = s × e₁, v = det[−d e₁ s]/det = d · (s × e₁)/det = d · q/det, and t = det[s e₁ e₂]/det = s · (e₁ × e₂)/det = e₂ · q/det. It is a hit when u ≥ 0, v ≥ 0, u + v ≤ 1 and t > t_min: two cross products, four dot products and one reciprocal, with early exits after u and after v, and u, v left over as interpolation weights. Check: v₀ = (0, 0, 0), v₁ = (1, 0, 0), v₂ = (0, 1, 0), o = (0.2, 0.3, 1), d = (0, 0, −1) give p = (1, 0, 0), det = 1, u = 0.2, q = (0, 1, −0.3), v = 0.3 and t = 1, as
ray.moller_trumborereturns. -
Russian roulette. Prove that Russian roulette leaves the path tracer unbiased, and compute its effect on variance.
Solution
At a vertex, let X ≥ 0 be the light the rest of the path would contribute, and let the path continue with probability q ∈ (0, 1], chosen from the path so far, by a coin independent of everything else; the survivor's contribution is divided by q, so X′ = X/q with probability q and 0 otherwise. Given the path so far and X, E[X′] = q · X/q + (1 − q) · 0 = X, and by the tower property E[X′] = E[X]. Roulette is applied at every vertex from the third bounce on; by induction from the last vertex back, each vertex's estimate keeps its expectation, so every term T^k L_e of the series keeps its expected value (both versions are capped at 32 reflections, so they estimate the same sum). For the variance, E[X′² | X] = q X²/q² = X²/q, so Var[X′] = E[X²/q] − E[X]² = Var[X] + E[(1/q − 1) X²]. For a whole sample F = H + T, with H gathered before the coin and T after, F′ = H + I T/q with E[I] = q, and Var[F′] = Var[F] + E[(1 − q) T²/q]: the added variance is largest when q is small and T large, which is why q is the throughput β: a survivor's weight β/q returns to 1, and paths are killed mostly where their tail is dim. With β = 0.73³, q = 0.389 and 1/q − 1 = 1.57 at that vertex. Capping q at 0.95 means at most 0.95/0.05 = 19 further bounces are expected even in a white furnace. What matters is efficiency, the inverse of variance times time: in our check the means agree (0.2463 ± 0.0009 against 0.2474 ± 0.0007, z = −0.95), the per-pixel RMS z-score is 1.04, and roulette cuts the rays per path from 6.96 to 3.16 (55% fewer) and the time from 1.99 s to 1.06 s.
-
Build. Add next-event estimation for a second light to our path tracer, and measure the noise at 16 spp.
Solution
Solution notes. In
path.py, givecornell_scenea second emitter rectangle (for instance another 0.25 × 0.25 square, on the back wall or elsewhere on the ceiling) and replace the scene's singlelightindex by a list of indices, packed by_packas an integer array with each light's area and power (area times the luminance of its radiance). In_kernel, at each diffuse vertex choose light j with probability Pⱼ (½ each, or proportional to power), sample a point uniformly on it as now, and divide its contribution, f L_e cos θ cos θ′ A/d² V, by Pⱼ; or loop over both lights with one shadow ray each and no division. The rule that stops light being counted twice must cover every sampled light:obj != lightbecomes a test of anis_lightflag, still counting emission at depth 0 and after a mirror; the one-sided testcl > 0uses each light's own axis andrsign. Getting either rule wrong for one light makes it too bright or drops its direct light, and the tests catch both: the bounce-1 image is linear in the emitters, so with both lights it must equal the sum of the bounce-1 images with each light alone to within noise (per-pixel z-scores near 1, as in the roulette check); and a two-light version offurnace_scenemust still return L = emit/(1 − ρ) at every bounce. To measure, render a 2048-spp reference of the new scene, then 16-spp images with (a) NEE for the old light only, the new one found by chance, (b) a uniform choice of light, (c) a choice by power, (d) both lights at every vertex, and comparermseon the surfaces, time and the efficiency 1/(error² × time) assampling_comparisondoes. Expect (a) to be far noisier wherever the new light dominates, (c) to beat (b) when the lights differ in power, and (d) to have the lowest error per path at the cost of two shadow rays. -
★ Research. Caustic paths with provably near-optimal variance.
Discussion. Open. A specular–diffuse–specular path, such as light focused by glass onto a floor and seen in a mirror, is hard for every local way of building paths: a light path hits the floor, but its connection to the eye must pass through the mirror in exactly the reflected direction; an eye path reaches the floor through the mirror, but its connection to the light must pass through the glass in exactly the refracted direction. Neither can be sampled by a shadow ray, so unbiased methods find these paths only by chance, and with a point light and a pinhole camera, as Veach's thesis observes, some cannot be sampled at all. Our own box shows the easier case: light reflected by the mirror ball onto the floor (a caustic) reaches the eye only when a cosine-sampled bounce from the floor happens to strike the mirror and then the small light. Existing methods trade one property for another: photon mapping and its progressive and vertex-merging forms are consistent but biased; Metropolis light transport and manifold exploration are unbiased but come with no useful variance bound; specular manifold sampling has an unbiased form whose cost depends on the scene. The problem asks for an estimator together with a theorem: define the class of estimators allowed (unbiased, at most a fixed number of ray casts per sample), the best variance any of them can reach on a family of scenes, and an algorithm within a constant factor of it. A good partial answer would settle a restricted family, such as a single smooth convex refractor over a diffuse plane, seen through one planar mirror, with a matching lower bound; or prove that an existing method's variance is bounded relative to the integrand on such a family.
Notes and sources
Glossary
- homogeneous coordinates, w, clip coordinates, NDC, viewport — points with an extra coordinate so that translation and perspective are matrices; the space before the division; the cube [−1, 1]³ after it; the map to pixels.
- model, view and projection matrices, frustum, near and far planes, clipping — object to world, world to eye, eye to clip; the truncated pyramid the camera sees; cutting triangles to it before the division.
- depth buffer (z-buffer), window depth, z-fighting, reversed depth — a depth per pixel; depth stored in [0, 1]; two surfaces that round to the same depth; near at 1 and far at 0 in floating point.
- Euler angles, gimbal lock, quaternion, slerp — three angles about fixed axes; the lost degree of freedom when two axes align; four numbers for a rotation; interpolation along the great circle.
- rasterization, edge function, top-left rule, fragment — finding the pixels a triangle covers; the signed area test; the tie-break for centres on an edge; a candidate pixel with its interpolated values.
- barycentric coordinates, perspective-correct interpolation — a point's weights on a triangle's corners; interpolating a/w and 1/w, then dividing.
- painter's algorithm — drawing whole triangles from back to front.
- Lambert's cosine law, Phong and Blinn–Phong models, Gouraud and Phong shading, normal matrix — diffuse brightness; highlights about the mirror and the halfway vector; lighting at vertices or per pixel; the inverse transpose for normals.
- aliasing, moiré, texel, mipmap, level of detail, trilinear and anisotropic filtering — high frequencies read as low ones; a texture's pixel; the prefiltered pyramid; λ = log₂ ρ; blending two levels; several probes along a long footprint.
- supersampling, MSAA — several shaded samples per pixel; several coverage samples, one shader run.
- vertex shader, fragment shader, SIMT, warp, quad, helper lane, early depth test — the programmable stages; one instruction stream for many lanes; 32 lanes; a 2 × 2 block for derivatives; a lane run only to be subtracted; testing depth before shading.
- ray casting, Whitted ray tracing, shadow ray, Snell's law, total internal reflection, Fresnel, Schlick's approximation — the nearest hit along a ray; recursive reflection and refraction; a ray towards the light; bending at an interface; no refracted ray; the reflected fraction and its fifth-power fit.
- BVH, slab test, surface area heuristic — boxes in boxes over the objects; a ray against a box; choosing splits by expected cost.
- solid angle, steradian, flux, irradiance, radiance — area on the unit sphere; its unit; watts; watts per area; watts per area across the beam per steradian.
- BRDF, albedo, reciprocity, white furnace, microfacet, GGX — radiance out per irradiance in; the fraction reflected; symmetry in the two directions; the test that a surface returns at most what it receives; tiny mirrors; their distribution of normals.
- rendering equation, Neumann series, direct and indirect light, colour bleeding, radiosity — energy balance at every point and direction; the solution as a sum over bounces; one bounce and more; colour carried from surface to surface; the matte-only finite-element method.
- path tracing, throughput, importance sampling, cosine-weighted sampling, Russian roulette — one sampled direction per bounce; a path's running weight; sampling where the integrand is large; Malley's method; ending paths at random without bias.
- next-event estimation, multiple importance sampling, balance and power heuristics — a shadow ray to a point on the light; combining strategies with weights that sum to one; two such weightings.
- spp, efficiency, denoising, à-trous filter, g-buffer, demodulation — samples per pixel; 1/(error² × time); trading noise for bias; a sparse filter in passes; per-pixel normal, albedo and position; filtering light divided by albedo.
- Bézier curve, de Casteljau's construction, Bernstein polynomials, B-spline, NURBS — a polynomial curve from control points; repeated linear interpolation; its weights; smooth piecewise curves with local control; their rational form with uneven knots.
- Catmull–Clark subdivision, limit surface, winding number — refining a mesh towards a smooth surface; where refinement converges; how many times an outline goes round a point.
- caustic, specular–diffuse–specular path — light focused by mirrors or glass; a path no shadow ray can sample.
- neural radiance field, Gaussian splatting, ReSTIR — a network giving colour and density along rays; millions of rasterized Gaussians; reusing light samples across pixels and frames.
Sources
- M. Pharr, W. Jakob and G. Humphreys, Physically Based Rendering: From Theory to Implementation (4th ed., 2023); S. Marschner and P. Shirley, Fundamentals of Computer Graphics; T. Akenine-Möller, E. Haines, N. Hoffman, A. Pesce, M. Iwanicki and S. Hillaire, Real-Time Rendering (4th ed., 2018); J. F. Hughes, A. van Dam, M. McGuire, D. F. Sklar, J. D. Foley, S. K. Feiner and K. Akeley, Computer Graphics: Principles and Practice (3rd ed., 2013); G. Farin, Curves and Surfaces for CAGD: A Practical Guide (5th ed., 2002).
- I. E. Sutherland, "Sketchpad: a man-machine graphical communication system", AFIPS Spring Joint Computer Conference 1963; A. R. Smith, "A pixel is not a little square", Microsoft Technical Memo 6 (1995).
- K. Shoemake, "Animating rotation with quaternion curves", SIGGRAPH 1985.
- I. E. Sutherland and G. W. Hodgman, "Reentrant polygon clipping", Comm. ACM 1974; E. Catmull, A Subdivision Algorithm for Computer Display of Curved Surfaces, PhD thesis, University of Utah (1974); J. Pineda, "A parallel algorithm for polygon rasterization", SIGGRAPH 1988.
- H. Gouraud, "Continuous shading of curved surfaces", IEEE Trans. Computers 1971; B. T. Phong, "Illumination for computer generated pictures", Comm. ACM 1975; J. F. Blinn, "Models of light reflection for computer synthesized pictures", SIGGRAPH 1977.
- L. Williams, "Pyramidal parametrics", SIGGRAPH 1983.
- A. Appel, "Some techniques for shading machine renderings of solids", AFIPS Spring Joint Computer Conference 1968; T. Whitted, "An improved illumination model for shaded display", Comm. ACM 1980; T. Möller and B. Trumbore, "Fast, minimum storage ray-triangle intersection", Journal of Graphics Tools 1997; C. Schlick, "An inexpensive BRDF model for physically-based rendering", Computer Graphics Forum (Eurographics) 1994.
- S. M. Rubin and T. Whitted, "A 3-dimensional representation for fast rendering of complex scenes", SIGGRAPH 1980; T. L. Kay and J. T. Kajiya, "Ray tracing complex scenes", SIGGRAPH 1986; J. D. MacDonald and K. S. Booth, "Heuristics for ray tracing using space subdivision", The Visual Computer 1990.
- F. E. Nicodemus, J. C. Richmond, J. J. Hsia, I. W. Ginsberg and T. Limperis, Geometrical Considerations and Nomenclature for Reflectance, NBS Monograph 160 (1977); R. L. Cook and K. E. Torrance, "A reflectance model for computer graphics", ACM TOG 1982; B. Walter, S. R. Marschner, H. Li and K. E. Torrance, "Microfacet models for refraction through rough surfaces", EGSR 2007.
- J. T. Kajiya, "The rendering equation", SIGGRAPH 1986; C. M. Goral, K. E. Torrance, D. P. Greenberg and B. Battaile, "Modeling the interaction of light between diffuse surfaces", SIGGRAPH 1984; E. Veach, Robust Monte Carlo Methods for Light Transport Simulation, PhD thesis, Stanford University (1997); E. Veach and L. J. Guibas, "Optimally combining sampling techniques for Monte Carlo rendering", SIGGRAPH 1995; J. Arvo and D. Kirk, "Particle transport and image synthesis", SIGGRAPH 1990.
- H. Dammertz, D. Sewtz, J. Hanika and H. P. A. Lensch, "Edge-avoiding À-Trous wavelet transform for fast global illumination filtering", High Performance Graphics 2010.
- M. G. Cox, "The numerical evaluation of B-splines", J. Inst. Maths Applics 1972; C. de Boor, "On calculating with B-splines", J. Approximation Theory 1972; E. Catmull and J. Clark, "Recursively generated B-spline surfaces on arbitrary topological meshes", Computer-Aided Design 1978; M. Halstead, M. Kass and T. DeRose, "Efficient, fair interpolation using Catmull–Clark surfaces", SIGGRAPH 1993; T. DeRose, M. Kass and T. Truong, "Subdivision surfaces in character animation", SIGGRAPH 1998.
- B. Bitterli, C. Wyman, M. Pharr, P. Shirley, A. Lefohn and W. Jarosz, "Spatiotemporal reservoir resampling for real-time ray tracing with dynamic direct lighting", SIGGRAPH 2020; B. Mildenhall, P. P. Srinivasan, M. Tancik, J. T. Barron, R. Ramamoorthi and R. Ng, "NeRF: representing scenes as neural radiance fields for view synthesis", ECCV 2020; B. Kerbl, G. Kopanas, T. Leimkühler and G. Drettakis, "3D Gaussian splatting for real-time radiance field rendering", SIGGRAPH 2023.
- For the research problem: H. W. Jensen, "Global illumination using photon maps", Eurographics Workshop on Rendering 1996; T. Hachisuka, S. Ogaki and H. W. Jensen, "Progressive photon mapping", SIGGRAPH Asia 2008; I. Georgiev, J. Křivánek, T. Davidovič and P. Slusallek, "Light transport simulation with vertex connection and merging", SIGGRAPH Asia 2012; E. Veach and L. J. Guibas, "Metropolis light transport", SIGGRAPH 1997; W. Jakob and S. Marschner, "Manifold exploration", SIGGRAPH 2012; T. Zeltner, I. Georgiev and W. Jakob, "Specular manifold sampling for rendering high-frequency caustics and glints", SIGGRAPH 2020.
About this partfrom its README
Part 51 of a sixty-one-part course in computer science (see the series plan and the syllabus), the first part of Act X, Horizons and Trust. A picture is millions of samples of light. Projecting triangles onto a screen is linear algebra plus one division, getting the samples right is Nyquist again, and the physics of light comes down to one integral equation, which Monte Carlo solves one bounced path at a time. We build both ways of making a picture, a rasterizer and a ray tracer, and end with a path tracer that renders the series' own box, its noise falling as 1/√N.
The instruments are in explainer/cs/graphics/ (tested in tests/test_cs51_raster.py and
tests/test_cs51_light.py):
transform.py: 4 × 4 homogeneous matrices (translation, scaling, rotations, composition applied right to left) and the rotate-then-translate demo; OpenGL's perspective matrix (gluPerspective's) and the frustum folded into the NDC cube; window depth, the smallest depth gap a b-bit buffer resolves (by bisection, checked against the closed form) and z-fighting between two close planes; Euler angles (yaw, pitch, roll about Z, Y, X) and the singular values of the map from angle rates to spin; quaternions with the Hamilton product, and Shoemake's slerp against linear Euler interpolation.raster.py: edge functions (Part 22's orientation test) on vertices snapped to 1/256 pixel, the top-left fill rule, barycentrics, Sutherland–Hodgman clipping against the near plane in homogeneous space, perspective-correct interpolation of a/w and 1/w, a z-buffer (cleared to 1, test GL_LESS) and fragment counters; the demos built on it: a triangle coloured by its barycentrics, a checkered floor three ways (affine, with 1/w, ray cast), Lambert, Phong and Blinn–Phong on a sphere of 360 triangles with Gouraud against Phong shading and the exact sphere, a mip pyramid with nearest, bilinear and trilinear sampling (λ = log₂ ρ) against 16× supersampling and a 256-sample reference, and the z-buffer against the painter's algorithm.ray.py: ray–sphere (the quadratic, solved without cancellation) and Möller–Trumbore intersection; random terrain meshes; BVHs built by median split and by binned SAH, traversed nearest child first, against brute force; a Whitted ray tracer (a checkerboard floor, mirror, glass and diffuse spheres, one point light with hard shadows) with Snell refraction, Fresnel–Schlick weights and total internal reflection, traced breadth first with ray counts by kind.brdf.py: Lambert, normalized Phong ((n + 2)/2π) and Blinn–Phong ((n + 8)/8π, an approximation), Cook–Torrance with the GGX distribution, Smith masking and Fresnel–Schlick; samplers and their pdfs (uniform and cosine hemisphere, GGX half vectors, a Phong lobe, a cone); white-furnace albedos by quadrature and by Monte Carlo; reciprocity on 10,000 random pairs of directions; light, BRDF and multiple importance sampling (balance and power heuristics) for one glossy point under a spherical light.path.py: the series' scene, a Cornell-like box open at the front (white walls of albedo 0.73, a red and a green wall, a 0.25 × 0.25 light in the ceiling, a mirror ball, a white ball and a small blue ball), and a path tracer compiled with numba: cosine or uniform sampling, next-event estimation, Russian roulette from the third bounce, and each path's light filed by its number of reflections, so the image splits into the terms of the Neumann series; a 2048-spp reference, convergence, four sampling strategies, the roulette check, an edge-avoiding à-trous denoiser on a g-buffer (normal, albedo and position of the first non-mirror hit), and sRGB output through a Reinhard curve.curves.py: de Casteljau's construction and the Bernstein form, subdivision of a cubic, B-splines by the Cox–de Boor recursion and their continuity at the knots, and Catmull–Clark subdivision of a cube with the limit positions of Halstead, Kass and DeRose.
Chapter notes
- Hook. A picture is samples of light. Our path tracer's 128 × 128 box at 1, 4, 16 and 256 paths per pixel, with error on the surfaces 0.283, 0.129, 0.076 and 0.021: it falls like N^−0.46, close to the 1/√N of Part 20's Monte Carlo. Two ways to make a picture: a rasterized triangle blending three colours, and a 160 × 120 Whitted ray-traced image that took 41,563 rays; Sketchpad (1963) and Whitted (1980); the plan.
- 1. Transforms and rotations. A matrix moves every point at once (its columns are where the axis arrows land), but never the origin; homogeneous coordinates (Möbius 1827) make translation linear, a shear one dimension up, with points at w = 1 and directions at w = 0. Order matters: rotating the unit square 90° and then translating it by 2 puts its corners at (2, 0), (2, 1), (1, 1), (1, 0), the other order at (0, 2), (0, 3), (−1, 3), (−1, 2); a renderer chains P V M x. Gimbal lock measured: the singular values of the map from angle rates to spin are 1, √(1 + sin p) and √(1 − sin p), so 1.307, 1 and 0.541 at a pitch of 45°, a smallest of 0.012 at 89°, and 0 with rank 2 at 90°. Quaternions (Hamilton 1843) against Euler angles and matrices; slerp (Shoemake 1985) from (yaw, pitch, roll) = (0, 0, 0) to (150, 80, −100) degrees in 40 steps turns a constant 3.48° a step, 139.2° in all, exactly the single rotation between the ends, against 237.2°, unevenly, for Euler angles moved in straight lines.
- 2. Perspective projection. Similar triangles (Alberti 1435): y′ = n y/d, twice as far, half as tall; division is not linear, so the matrix copies the distance into w and the hardware divides once per vertex. The third row, from near ↦ −1 and far ↦ +1: z_ndc = (f + n)/(f − n) − 2fn/((f − n) d), affine in 1/d. Ours (60°, 4:3, near 1, far 4) has entries 1.299, 1.732, −1.667, −2.667 and −1; the frustum folds into the cube [−1, 1]³, straight lines stay straight, and three equally spaced slices (d = 1.75, 2.5, 3.25) crowd towards the far face at z_ndc = 0.14, 0.60, 0.85; clipping comes first, while everything is linear. Where depth goes, for near 0.1 and far 1000: half the stored range is used by distance 0.20 and 90% by 1.00; a 4-bit buffer whose last step spans the back half, 8 to 16. The smallest gap a 24-bit buffer resolves, by bisection and the closed form Δ ≈ d²(f − n)/(f n (2^b − 1)): at distance 1000 it is 5.9 with the near plane at 0.01, 0.60 at 0.1 and 0.060 at 1. Z-fighting, two planes 0.01 apart at distance 50 over 19,200 pixels: 99.4% drawn wrong with near 0.01 and 16 bits, 31.9% with 24 bits, 71.9% with near 1 and 16 bits, 0.0% with near 1 and 24 bits; reversed floating-point depth.
- 3. Rasterization and the z-buffer. Edge functions (Part 22's orientation test; Pineda 1988) and the top-left rule: at 160 × 120, 9,804 pixels of the triangle's bounding box tested and 4,748 inside. Barycentric coordinates, free from the edge functions, painted as red, green and blue. Why interpolate 1/w: equal steps on the screen are growing steps on a receding floor, while u/w and 1/w are affine in screen position. A checkered floor of two triangles (3,934 pixels): affine interpolation colours 48.5% of them wrongly, interpolation with 1/w none, and its texture coordinates agree with a ray cast to 1.8 × 10⁻¹⁴; the original PlayStation's wobbling textures. The z-buffer (Catmull 1974) on two triangles that pass through each other: of 1,164 overlap pixels the orange one is in front in 693 and the blue one in 471; the painter's order gets 472 pixels wrong, the z-buffer 1 (a coverage tie on an outer edge), with 5,883 fragments passing the depth test and 693 failing. Our rasterizer end to end: clip coordinates, near-plane clipping, the division, the viewport, edge functions, the depth test, the a/w and 1/w blend.
- 4. Shading. Lambert's cosine law (1760) from irradiance, E = E⊥ (N · L); Phong's highlight about the mirror direction (1975), R = 2(N · L)N − L, with power s = 32; Blinn's halfway vector (1977) and why s′ = 4s gives the same width, since cos^s α ≈ e^(−sα²/2) and H is α/2 from N; Gouraud (1971) against Phong shading on a sphere of 360 triangles, where the highlight is a star or a disc: the largest per-pixel difference is 0.34 of full brightness, and against the exact, ray-cast sphere the error is 0.040 for Gouraud and 0.0079 for Phong, 5 times smaller. Normals move by the inverse transpose, n′ = M^−⊤ n.
- 5. Textures and sampling. Moiré is aliasing: 9 cycles sampled 10 times read as 1 cycle, |f − k f_s|, and Nyquist (Part 36) asks for more than two samples per cycle. One floor, four samplers, against 256 jittered samples per pixel over 19,200 pixels: point sampling's error is 0.199, the trilinear mipmap's (8 texel reads) 0.065, 3.1 times smaller, and 16 samples per pixel reach 0.053. Mipmaps (Williams 1983): levels from 128 × 128 down to 1 × 1, grey from level 5, 16,384 texels becoming 21,845 (33.33% more, the geometric series' third). The level λ = log₂ ρ from the pixel's footprint, 0 at the bottom of the frame and 7 at the horizon; anisotropic filtering with N = ⌈ρmax/ρmin⌉ probes; supersampling against MSAA (16 shaded samples against 4 coverage samples and one shader run).
- 6. The GPU pipeline. Vertex fetch, vertex shader, clip and divide, rasterize, fragment shader, depth and blend, the two shaders written by the programmer; a vertex and a fragment shader in the style of GLSL (illustrative). SIMT: about 2 million pixels at 60 frames a second, fragments in 2 × 2 quads packed into warps of 32 lanes, a branch that splits a warp running both sides. Derivatives by subtraction within a quad: chapter 3's 4,748 pixels touch 1,236 quads, so 196 helper lanes, 4% extra. Early depth testing on chapter 3's crossing triangles: of 6,576 fragments 693 fail and are never shaded, and 471 of the 5,883 shaded are painted over, leaving 5,412 visible pixels.
- 7. Ray tracing. One ray through every pixel (Appel 1968), 19,200 primary rays in our Whitted tracer; ray meets sphere as a quadratic whose discriminant decides two hits, a graze or a miss, computed without cancellation (Part 4); Möller–Trumbore (1997) by Cramer's rule; Whitted's ray tree in a 2D slice (shadow rays, reflection, refraction) and our counts: 19,200 primary, 13,650 shadow, 4,397 reflection and 4,316 refraction rays, 41,563 in all, 2.16 per pixel. Snell's law in vectors and total internal reflection beyond 41.8°, which a ray inside a ball never reaches (0 counted); exact Fresnel against Schlick's fit (1994), R₀ = 0.04 for glass, and the rim of our glass ball as a mirror.
- 8. Acceleration structures. Brute force: 41,563 rays against 100,000 triangles is about 4.2 × 10⁹ tests. A BVH over 40 illustrative triangles by median splits (31 nodes, 16 leaves of at most 3, 4 levels below the root); the traversal with Kay and Kajiya's slabs, nearer child first: one ray tests 17 boxes (11 entered, 6 skipped) and 8 of the 40 triangles, and finds the same hit. The surface area heuristic (MacDonald and Booth 1990): on 12 boxes, 9 bunched and 3 spread out, the median split costs 8.6, the cheapest plane 6.9, no split 12. Our 3D BVH on terrains of 100 to 100,000 triangles: 6.8 to 10.3 triangle tests per ray with median splits, 2.1 to 2.9 with the SAH; at 100,000 triangles, 2.5 tests and 39 boxes per ray against 100,000 tests, each tenfold increase adding 9 to 10 box visits, the SAH tree deeper (19 levels against 15) yet cheaper to walk, and the same nearest hit as brute force on 100% of the rays checked.
- 9. Radiometry and BRDFs. Solid angle, Ω = 2π(1 − cos α) for a cap, 2π for the hemisphere; flux, irradiance and radiance, which is constant along a ray; the BRDF (Nicodemus et al. 1977) and the reflection equation; Lambert's ρ/π, and why π; microfacets, Cook–Torrance (1982) and GGX (Walter et al. 2007). Reciprocity on 10,000 random pairs: Lambert, Phong and Blinn–Phong exact, GGX to 6 × 10⁻¹⁵. The white furnace: Lambert returns 1 at every angle, normalized Phong at n = 10 returns 1 head-on and 0.23 at 80°, Blinn–Phong at n = 10 returns 1.075 head-on (Monte Carlo 1.070 ± 0.003), creating energy, and GGX at α = 1 returns 0.307 head-on, losing 69% (0.988 at α = 0.1).
- 10. The rendering equation. Light arriving is light leaving somewhere else: Kajiya's equation (1986); the operator T and the Neumann series L = L_e + T L_e + T² L_e + ⋯, which converges because each reflection keeps at most its albedo (in a closed room of walls of albedo 0.73 the bounces add up to 1/(1 − 0.73) = 3.70 times the light emitted); each term is a set of paths (Veach 1997). Our path tracer's bounce images, 0 to 7 and up at 2048 paths per pixel, summed on screen: direct light leaves the ceiling black, bounce 2 lights it and brings the colour bleeding. The mean radiance of the bounce images, 0.128, 0.067, 0.026, 0.012, …, each term from bounce 1 on 0.38 to 0.53 times the one before; the eight add up exactly to the reference's mean, 0.2466; 43% of the light reaching the eye from surfaces took two or more bounces; radiosity (Goral et al. 1984).
- 11. Path tracing. The Monte Carlo estimator and the throughput β; one path in a side view of our box (back wall, ceiling, the matte ball, the lamp). Cosine-weighted sampling by Malley's method, p = cos θ/π, so that f cos θ/p is just the albedo. Russian roulette (Arvo and Kirk 1990): E[X′] = q · X/q = X, at the price Var[X′] = Var[X] + (1/q − 1)E[X²]; our tracer plays from the third bounce with q the throughput, capped at 0.95 (q = 0.73³ = 0.39 for a path among walls of 0.73). Next-event estimation: the light is a sixteenth of the ceiling, and none of 9 random bounces from the floor found it in the side view, so a shadow ray aims at a point on it, dω = cos θ′ dA/d², and light reached by chance is then ignored except after a mirror. Multiple importance sampling (Veach and Guibas 1995), in one dimension: unbiased for any weights that sum to one, and the balance heuristic.
- 12. Our path tracer, and denoising. The noise up close at 1 to 256 paths per pixel (0.026 s to 6.37 s), the variance σ²/N; on log axes the fitted slopes are −0.46 on surfaces and over all pixels, the last point lifted by the reference's own noise (about 0.283/√2048 = 0.0063, against 0.0206). Four strategies at 16 spp, efficiency 1/(error² × time) relative to the first: cosine sampling with NEE 1.00 (error 0.075), uniform with NEE 0.70, cosine without NEE 0.11, uniform without NEE 0.070; NEE is worth 9.0 times, the cosine 1.42 times with NEE and 1.59 without. Roulette tested on 12 renders each way (64 × 64, 16 spp): mean 0.2463 ± 0.0009 against 0.2474 ± 0.0007 (z = −0.95), a per-pixel RMS z-score of 1.04, and 3.16 rays per path against 6.96, 55% fewer, in 1.06 s against 1.99 s. MIS measured on one glossy point (normalized Phong with n = 10, 100, 1000: lobe widths 18.1°, 5.7°, 1.8°) under a round light of angular radius 1.0°, 5.7° and 19.5°, 32 samples, 4,000 trials a cell: worst relative errors 0.93 for light sampling, 4.64 for BRDF sampling, 0.095 for the balance heuristic and 0.084 for the power heuristic. The edge-avoiding à-trous filter (Dammertz et al. 2010): a B3 kernel, three passes with taps 1, 2 and 4 pixels apart, weights by colour, normal, albedo and position, and demodulation by the albedo; at 16 spp the surface error falls from 0.077 to 0.019, 4.0 times smaller, all pixels from 0.127 to 0.105, the indirectly lit ceiling turns blotchy, and the filter takes 0.34 s against a 0.43 s render.
- 13. Curves, surfaces and fonts. De Casteljau (Citroën, 1959) and Bézier (Renault): the cubic with control points (0, 0), (1, 2), (3, 2.2), (4, 0.2) passes through (2, 1.6) at t = ½, and the construction splits it in two; the Bernstein polynomials, the convex hull, and transforms acting on control points alone. A uniform cubic B-spline (Cox and de Boor 1972) of seven points and four pieces: across the knots the position jumps by 10⁻¹⁵ to 10⁻¹⁴, the slope by 10⁻¹³ to 10⁻¹², the curvature by 10⁻¹¹ to 10⁻¹⁰, while the third derivative jumps by 9.85, 5.66 and 8.94: C²; local control; NURBS. Catmull–Clark (1978) on a cube: 6, 24, 96, 384 and 1,536 faces with V − E + F = 2 throughout, a corner's distance from the centre 1.7321, 0.9623, 0.8821, 0.8687, 0.8665 against the limit 0.8660 (Halstead et al. 1993); Geri's Game (1997). The word "Light" as Manim draws it from TeX's fonts: 110 cubic curves, and 536 in the heading above it; PostScript and Type 1 fonts store cubics, TrueType quadratics; letters filled by winding number with coverage averaged in each pixel.
- 14. Frontier: real time, and neural rendering. A few samples, then clean up: our 16-path image (error 0.077) denoised to 0.019, below 256 paths' 0.021; ray-tracing hardware since 2018, ReSTIR (Bitterli et al. 2020) and learned denoisers and upscalers; neural radiance fields (Mildenhall et al. 2020) and 3D Gaussian splatting (Kerbl et al. 2023), this part's rendering run in reverse (AI, Built 22), and what is lost. Four open problems (caustics, denoisers with guarantees, inverse rendering, perceptual error) and the ★ research problem.
- Outro. Recap, payoffs, practice, problems, next part.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Sketchpad (Sutherland 1963) to framebuffers; "a pixel is not a little square" (Smith 1995).
- Transforms: homogeneous coordinates make translation linear; composition order; Euler angles and gimbal lock, quaternions and slerp (3D).
- Perspective projection derived from similar triangles; the frustum squashed into the cube; NDC; the depth nonlinearity and z-fighting.
- Rasterization: edge functions (Part 22's orientation test); barycentrics; perspective-correct interpolation (why 1/w); the z-buffer (Catmull 1974). Our rasterizer.
- Shading: Lambert's cosine law; Phong and Blinn–Phong; Gouraud against Phong.
- Textures and sampling: moiré as aliasing (Nyquist, callback to Part 36); mipmaps (Williams 1983); trilinear and anisotropic filtering; supersampling and MSAA.
- The GPU pipeline: vertex and fragment shaders (callback to AI, Built 17).
- Ray tracing (Whitted 1980): ray–sphere and Möller–Trumbore intersection derived; shadows; Snell and Fresnel–Schlick.
- Acceleration: BVHs with the surface-area heuristic (callback to Part 22); O(log n) per ray.
- Radiometry: solid angle, radiance, irradiance; BRDFs (reciprocity, energy conservation); microfacets (Cook–Torrance, GGX).
- The rendering equation (Kajiya 1986) as energy balance; its Neumann series as paths of light, summed bounce by bounce on screen.
- Path tracing: the estimator; cosine-weighted importance sampling; Russian roulette (unbiased, proved); next-event estimation; multiple importance sampling (Veach 1997).
- Our path tracer renders the series' scene; variance against samples; denoising.
- Radiosity and photon mapping; real time (RTX, ReSTIR); neural rendering (callback to AI, Built 22).
- Curves: Bézier and de Casteljau; B-splines; Catmull–Clark subdivision (Geri's Game); fonts as Béziers, including the text on this screen. Outro.
Computed: rasterizer and path-tracer images at increasing sample counts; variance curves; importance-sampling gains; BVH traversal counts; mipmap comparisons; slerp against Euler paths. Visuals: the frustum folding into the cube; barycentric color blends; rays bouncing in our scene; the bounce-by- bounce Neumann sum; de Casteljau's construction. In practice: game engines (Unreal, Unity), GPU pipelines (Vulkan, Metal, WebGPU), film rendering, UI rendering. Reading: Pharr, Jakob & Humphreys, Physically Based Rendering (4th ed.); Marschner & Shirley, Fundamentals of Computer Graphics; Akenine-Möller et al., Real-Time Rendering; Hughes et al., Computer Graphics: Principles and Practice; Farin, Curves and Surfaces for CAGD; Kajiya 1986; Veach 1997; Whitted 1980; Cook & Torrance 1982; Catmull 1974; Sutherland 1963.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
透视。 推导把视锥体映到立方体 [−1, 1]³ 的透视矩阵,并证明深度是 1/z 的仿射函数。
解答
在眼空间中,相机在原点,朝 −z 方向看,所以前方一点的距离是 d = −z。由相似三角形,高度为 y 的点落在距离 n 的屏幕上, 高度为 n y/d。把屏幕缩放,使视野的上边缘 y = d tan(fov/2) 落在 1:y_ndc = c y/d,其中 c = cot(fov/2);同理,宽高比为 a 时 x_ndc = (c/a) x/d。两者都是点的线性函数除以 d = −z,所以第四行取 (0, 0, −1, 0),使 w = d,前两行取 (c/a, 0, 0, 0) 和 (0, c, 0, 0)。深度不能依赖 x 和 y,所以第三行是 (0, 0, A, B),除法之后 z_ndc = (A z + B)/(−z) = −A + B/d。要求 d = n ↦ −1、 d = f ↦ +1,得 −A + B/n = −1 和 −A + B/f = 1;相减得 B(1/n − 1/f) = −2,所以 B = 2fn/(n − f),再得 A = 1 + B/n = (f + n)/(n − f)。于是 z_ndc = (f + n)/(f − n) − (2fn/(f − n)) · (1/d):是 1/d = −1/z 的仿射函数,而不是 z 的。侧面 x = ±a d tan(fov/2) 和 y = ±d tan(fov/2) 都映到 ±1,所以视锥体变成立方体。对我们的参数(60°,4:3,n = 1,f = 4): c = √3 = 1.732,c/a = 1.299,A = −5/3,B = −8/3,d = 1、1.75、2.5、3.25、4 分别落在 z_ndc = −1、0.14、0.60、0.85、1。代价是: dz_ndc/dd = 2fn/((f − n) d²),所以窗口深度 (z_ndc + 1)/2 的一个台阶 1/(2^b − 1) 跨越 Δ ≈ d²(f − n)/(f n (2^b − 1)):n = 0.01、 f = 1000、b = 24 时在 d = 1000 处为 5.96(在精确映射上二分得 5.93),n = 1 时为 0.060。
-
为什么是 1/w。 证明在屏幕空间中线性插值 u/w 和 1/w,得到的是透视正确的 u。
解答
三角形位于眼空间的一个平面 m · P = k 上(k ≠ 0;否则眼睛在平面内,三角形只是一条线)。屏幕位置 (x_s, y_s) 是 (x/w, y/w) 的仿射函数,其中 w = −z,所以平面上每一点都是 P = w r(x_s, y_s),r = (x/w, y/w, −1) 是屏幕位置的仿射函数。代入得 w (m · r) = k,所以 1/w = (m · r)/k 是 (x_s, y_s) 的仿射函数。在三维中沿三角形仿射变化的属性 u = g · P + h,给出 u/w = g · r + h · (1/w),同样是屏幕位置的仿射函数。用屏幕空间的重心坐标 λᵢ 做线性插值能精确地重现仿射函数,所以 u/w = Σ λᵢ uᵢ/wᵢ,1/w = Σ λᵢ/wᵢ,u = (Σ λᵢ uᵢ/wᵢ)/(Σ λᵢ/wᵢ);等价地,真正的重心坐标是 bᵢ = (λᵢ/wᵢ)/Σⱼ (λⱼ/wⱼ)。只要各 wᵢ 不相等,直接插值 u 就是错的,因为 u 是两个仿射函数之比,而不是一个仿射函数。例子:一条边从深度 2 到深度 12,u 从 0 到 8,就像 我们的地板。在屏幕上的中点,仿射插值给出 u = 4;正确的值是 (½ · 0/2 + ½ · 8/12)/(½ · 1/2 + ½ · 1/12) = 1.14,深度为 3.43;而地板 自己的中点(深度 7,u = 4)出现在屏幕上 86% 的位置。在我们由两个三角形组成的地板上,仿射插值把 3,934 个像素中的 48.5% 涂错, 用 1/w 插值一个也不错,与光线投射的结果相差 1.8 × 10⁻¹⁴。
-
Möller–Trumbore。 用克拉默法则推导光线与三角形的求交测试。
解答
三角形上的点是 (1 − u − v) v₀ + u v₁ + v v₂,u, v ≥ 0,u + v ≤ 1。令它等于光线 o + t d,记 e₁ = v₁ − v₀、e₂ = v₂ − v₀、 s = o − v₀,得 −t d + u e₁ + v e₂ = s,即线性方程组 [−d e₁ e₂](t, u, v)ᵀ = s。用 det[a b c] = a · (b × c),行列式为 (−d) · (e₁ × e₂) = e₁ · (d × e₂) = e₁ · p,其中 p = d × e₂;它接近零时,光线与平面平行。克拉默法则把一列换成 s: u = det[−d s e₂]/det = −d · (s × e₂)/det = s · p/det;记 q = s × e₁,v = det[−d e₁ s]/det = d · (s × e₁)/det = d · q/det, t = det[s e₁ e₂]/det = s · (e₁ × e₂)/det = e₂ · q/det。u ≥ 0、v ≥ 0、u + v ≤ 1 且 t > t_min 时相交:两次叉积、四次点积、一次求倒数, 算出 u 和 v 后都可以提前退出,剩下的 u、v 正好用作插值权重。验算:v₀ = (0, 0, 0)、v₁ = (1, 0, 0)、v₂ = (0, 1, 0)、 o = (0.2, 0.3, 1)、d = (0, 0, −1),得 p = (1, 0, 0),det = 1,u = 0.2,q = (0, 1, −0.3),v = 0.3,t = 1,与
ray.moller_trumbore的结果一致。 -
俄罗斯轮盘赌。 证明俄罗斯轮盘赌使路径追踪保持无偏,并计算它对方差的影响。
解答
在某个顶点,设 X ≥ 0 是路径其余部分会贡献的光,路径以概率 q ∈ (0, 1] 继续;q 由到此为止的路径决定,抛的硬币与其他一切 独立;幸存者的贡献除以 q,所以 X′ 以概率 q 等于 X/q,否则为 0。给定到此为止的路径和 X,E[X′] = q · X/q + (1 − q) · 0 = X,由 全期望公式得 E[X′] = E[X]。从第三次反弹起每个顶点都做轮盘赌;从最后一个顶点往回归纳,每个顶点的估计都保持期望,所以级数的每一项 T^k L_e 都保持期望值(两个版本都封顶在 32 次反射,所以估计的是同一个和)。方差:E[X′² | X] = q X²/q² = X²/q,所以 Var[X′] = E[X²/q] − E[X]² = Var[X] + E[(1/q − 1) X²]。对整个样本 F = H + T,H 是硬币之前收集的光,T 是之后的,F′ = H + I T/q, E[I] = q,于是 Var[F′] = Var[F] + E[(1 − q) T²/q]:q 小而 T 大时增加的方差最大,这就是 q 取路径权重(吞吐量)β 的原因:幸存者的 权重 β/q 回到 1,被终止的路径大多是尾部本来就暗的。β = 0.73³ 时,该顶点 q = 0.389,1/q − 1 = 1.57。把 q 封顶在 0.95,意味着即使 在白炉里,预期的后续反弹也至多 0.95/0.05 = 19 次。真正要看的是效率,即方差乘时间的倒数:在我们的检验中,均值一致 (0.2463 ± 0.0009 对 0.2474 ± 0.0007,z = −0.95),逐像素 z 分数的均方根是 1.04,而轮盘赌把每条路径的光线数从 6.96 降到 3.16 (少 55%),时间从 1.99 秒降到 1.06 秒。
-
动手。 给我们的路径追踪器加上对第二个光源的下一事件估计,并在每像素 16 个样本时测量噪声。
解答
解答要点。 在
path.py中,给cornell_scene加第二个发光矩形(比如另一个 0.25 × 0.25 的正方形,放在后墙上或天花板的别处), 把场景里唯一的light下标换成一个下标列表,由_pack打包成整数数组,并附上每个光源的面积和功率(面积乘以其辐射亮度 换算成的亮度)。在_kernel中,在每个漫反射顶点以概率 Pⱼ 选光源 j(各 ½,或按功率成比例),像现在一样在它上面均匀取一点,把贡献 f L_e cos θ cos θ′ A/d² V 除以 Pⱼ;或者对两个光源各发一条阴影射线,不做除法。防止光被计两次的规则必须覆盖每个被采样的光源:obj != light改为检查一个is_light标志,深度 0 和镜面反射之后仍然计入发光;单面发光的测试cl > 0要用每个光源自己的轴和rsign。任何一个光源的这两条规则写错,它就会过亮,或者丢掉直接光,而测试能抓住这两种错误:第一次反弹的图像对发光体是线性的, 所以两个光源时,它必须在噪声范围内等于各光源单独时第一次反弹图像之和(逐像素 z 分数接近 1,像轮盘赌检验那样);双光源版本的furnace_scene在每次反弹都仍须给出 L = emit/(1 − ρ)。测量时,先为新场景渲染一张 2048 spp 的参考图,再渲染 16 spp 的图像: (a) 只对原来的光源做 NEE,新光源靠碰运气找到;(b) 均匀地选光源;(c) 按功率选;(d) 每个顶点两个光源都采样;然后像sampling_comparison那样比较表面上的rmse、时间和效率 1/(误差² × 时间)。预计 (a) 在新光源占主导的地方噪声大得多;两个光源 功率不同时 (c) 胜过 (b);(d) 每条路径的误差最低,代价是两条阴影射线。 -
★ 研究。 方差可证明接近最优的焦散路径估计。
讨论。 尚未解决。镜面–漫反射–镜面路径,例如被玻璃聚焦到地板上、又在镜子里被看到的光,对每一种局部构造路径的方法都很难:从光源 出发的路径能打到地板,但它与眼睛的连接必须恰好沿反射方向穿过镜子;从眼睛出发的路径能经镜子到达地板,但它与光源的连接必须恰好沿 折射方向穿过玻璃。两者都不能用一条阴影射线采到,所以无偏方法只能碰运气找到这些路径;Veach 的博士论文指出,点光源加针孔相机时, 有些这样的路径根本无法被采样。我们自己的盒子里就有较容易的情形:镜面球反射到地板上的光(一种焦散),只有当地板上按余弦采样的一次 反弹恰好打中镜子、再打中那个小光源时,才能到达眼睛。现有方法各有取舍:光子映射及其渐进式和顶点合并的变体是一致的,但有偏; Metropolis 光传输和流形探索是无偏的,但没有有用的方差界;镜面流形采样有一种无偏的形式,代价却依赖于场景。这道题要的是估计器加一个定理: 规定允许的估计器类(无偏、每个样本至多固定次数的光线投射),任何估计器在一族场景上能达到的最好方差,以及一个在它常数倍之内的算法。 好的部分答案可以解决一个受限的场景族,比如一个光滑的凸折射体放在漫反射平面上方、透过一面平面镜观看,并给出相匹配的下界;或者在 这样的场景族上,证明某个现有方法的方差相对于被积函数有界。
Build the film
python -m videos.cs.cs51.compute # the part's numbers, into .cache/cs51
python tools/build.py cs51 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs51 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs51. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs51.compute
python -m unittest tests.test_cs51_raster tests.test_cs51_light
python tools/build.py cs51