Introduction#
Part 9 worked out which pixels each triangle covers. Each covered pixel becomes a fragment, which now needs a colour: the job of the fragment shader (a pixel shader in Direct3D), where most of the visual magic in games happens. This post covers:
- Interpolation: how the corners’ values are blended across the triangle
- What a fragment shader receives and produces, with a live editor to play in
- Perspective-correct interpolation: the subtle fix that keeps textures from warping
Blending Across a Triangle#
A vertex shader only runs at the three corners, but a triangle can cover thousands of pixels. Every value it outputs (a varying, as part 7 called them), such as a colour or a texture coordinate, must be filled in for each pixel in between. The rasteriser does this by interpolating: blending the three corner values by how close the pixel is to each corner.
The amounts of each corner are called barycentric weights (from barycentre, a centre of balance). They’re part 9’s edge function values divided by the triangle’s area: a pixel on a corner gets 100% of that corner, a pixel on the opposite edge gets 0% of it, and the three always add up to exactly 1.
Move the pink point around the triangle below, and drag its corners: each corner’s line thickens as its weight grows.
Blending three corner colours with barycentric weights
Every varying is blended this way: colours, texture coordinates, normals and positions. To stop blending, for example for an ID number, GLSL lets you mark a varying flat: every pixel then gets one corner’s value.
The Fragment Shader#
Then the fragment shader runs, once per fragment. It receives:
- The interpolated varyings for this fragment
- The same kind of uniforms as the vertex shader (time, colours, light positions, textures)
- Built-in values such as
gl_FragCoord, the fragment’s position on screen in pixels
It produces a colour (and optionally a depth, how far away it is: see part 11), or it can discard the fragment so nothing is written, which is how cut-out shapes like leaves and fences are often made. Each run knows nothing of the pixels around it (apart from the ddx and ddy trick).
Here’s a fragment shader drawing one rectangle that covers the whole picture, so it runs once for every pixel. Pick a preset, then edit the code: the picture updates as you type.
Edit the fragment shader and watch every pixel change
The presets use a few GLSL functions beyond those in part 7. vUV is this pixel’s position, from (0, 0) at the bottom left to (1, 1) at the top right, and uTime is the time in seconds.
floor(x)rounds down to a whole number, andfract(x)keeps only the part after the decimal point, sofract(x * 10.0)counts from 0 to 1 ten times as x goes from 0 to 1: handy for repeats.mod(a, 2.0)is the remainder after dividing by 2: 0 for even numbers, 1 for odd ones.step(edge, x)is 0 when x is belowedgeand 1 above it, a hard switch.smoothstepchanges smoothly over a short range instead.mix(a, b, t)blends fromatobastgoes from 0 to 1 (see Interpolation).atan(y, x)gives a direction’s angle, for circular patterns.a ? b : cmeans “ifais true, useb, otherwise usec”.
Some things to try:
- In Gradient from coordinates, change
vUV.xto1.0 - vUV.x, or the0.0to0.5 + 0.5 * sin(uTime), and watch it change over time. - In A circle, change
0.3to resize it. The edge is hard and jagged, because each pixel is either in or out; the fwidth post shows how to smooth it. - Sunset uses no images at all, just maths on
vUV, like many game effects.
The fragment shader is usually the most expensive part of drawing: it runs for every covered pixel (several times where objects overlap), so its cost grows with resolution. A 4K screen has over 8 million pixels, so at 60 frames per second a full-screen effect runs it about half a billion times a second.
Perspective-Correct Interpolation#
There’s a catch with blending in screen space. A road’s white lines are evenly spaced on the ground but bunch up on screen in the distance: equal steps on screen are not equal steps across the surface. Blending texture coordinates evenly on screen would stretch distant textures and squeeze near ones.
So graphics cards do perspective-correct interpolation, using each corner’s w (its depth, from part 5). Instead of blending each value directly, they blend the value divided by w, and 1 Ă· w, then divide one by the other for each pixel. The result is exactly what blending evenly across the real 3D surface would give.
The demo below shows a checkerboard floor of just two triangles. Switch to Affine (blended evenly across the screen) to turn the correction off: the shader undoes it with the same trick in reverse.
A floor of two triangles, with and without perspective correction
Without the correction, the checkerboard bends along the diagonal where the triangles meet, and distant squares are far too big; lowering the camera makes it worse. The original PlayStation lacked this correction, so textures in its games warp as the camera moves (they split surfaces into many small triangles to hide it).
Fragment shaders always run in 2Ă—2 groups of pixels, so neighbouring pixels can be compared, which smooth texture reading needs (see the ddx and ddy posts). On many modern graphics cards, interpolation isn’t a fixed-function step: the rasteriser hands each group its barycentric weights, and the shader blends with a few multiply-add instructions at its start. So passing lots of varyings has a real cost.
Questions You Might Have#
Can a fragment shader move its pixel somewhere else?
No. Each copy works on one fixed position and decides its colour (it can also discard the fragment, or change its depth). Where things go on screen is the vertex shader’s job.
Summary#
- Values output by the vertex shader are interpolated across each triangle using barycentric weights, which always add up to 1.
- The fragment shader runs once per fragment and outputs its colour (or discards it).
- It’s usually the most expensive stage, because it runs for every covered pixel.
- Perspective-correct interpolation uses each corner’s depth so that textures don’t warp.
Next, part 11 solves a problem we’ve been ignoring: when two triangles cover the same pixel, which one wins?
Further Reading#
- Patricio Gonzalez Vivo and Jen Lowe, The Book of Shaders: a gentle, beautiful introduction to fragment shaders, with live editors.
- Inigo Quilez and Pol Jeremias, Shadertoy: thousands of fragment shaders to read and remix, from simple to astonishing.
- Scratchapixel, Perspective Correct Interpolation: the maths behind the correction, step by step.