Raymarching 4: modelling, materials and motion
glint · Examples · Tutorials · Gallery
The craft: mirror symmetry, polar repetition, extrusion and revolution, shells, elongation, morphing, easing, squash and stretch, colours that melt with the shapes, three-point lighting, highlights, metal and roughness, toon shading and ink outlines, bounding volumes, smooth edges and motion blur over frames.
A free interactive course of 20 steps in glint, a live shader editor in the browser: each step changes a running shader, and ticks itself when you've done its task.
1. Model half, get both: mirror symmetry
Faces, cars, robots, most things built are symmetrical. Measuring a point as if it were on the other side, q.x = abs(q.x), means whatever is modelled on the +x side also appears on the −x side, for free: one ear and one eye written, two of each drawn.
Here the head has one ear and one eye on the right (+x) and a nose in the middle. The ear and eye are measured from q, a copy of p. The nose uses p itself, so it isn't doubled.
It works per axis (abs(q.z) front and back) and in any direction you turn space first. The Advanced course's fractals are this, done again and again.
Your turn: Give it two ears and two eyes: after vec3 q = p; add q.x = abs(q.x);
2. Round a circle: polar repetition
Teeth on a gear, petals, spokes, chairs round a table: copies round a circle. Cut the circle into N equal slices, k = 6.2832 / N radians each, and measure every point as if it were in slice 0.
atan(q.z, q.x) is the point's angle round the middle. mod(a + k * 0.5, k) - k * 0.5 is its angle within its own slice, centred on 0. Turning q back to that angle at the same distance puts every slice on top of slice 0, so one tooth (at +x) is measured in all of them.
With N = 1 there's one slice, the whole circle, and one tooth.
Your turn: Make it a gear: const float N = 12.0;
3. From 2D to 3D: extrusion
Everything from the 2D courses can become 3D. A 2D distance used on p.xy alone ignores z, so the shape goes on for ever along z: a star-shaped beam, as you see when it turns.
extrude gives it a thickness: it combines the 2D distance with how far z is outside ±h, the same way sdBox combines its sides (inside, the larger; outside, the length of what's outside). A cookie cutter for distance functions.
Your turn: Cut it to 0.25 thick: return extrude(star(p.xy, 1.0, 0.45), p.z, 0.25);
4. Spun round: revolution
Vases, bottles, chess pieces, wheels: anything made on a lathe is a 2D outline spun round an axis. In 2D the outline is drawn in (distance from the middle, height).
q = p.xy uses x as the distance from the middle, which isn't: it's two wavy walls going on for ever in z. The real distance from the vertical axis is length(p.xz). Use that and the outline is spun all the way round.
Your turn: Spin the outline: vec2 q = vec2(length(p.xz), p.y);
5. Hollow it out: shells
abs(d) turns any solid into an infinitely thin skin: inside and outside both measure as outside. Subtract a thickness, abs(d) - 0.05, and it's a shell 0.1 thick. Do it twice and you get a shell inside a shell, like an onion.
This ball has a smaller ball inside, but it's solid, so the cut-away front only shows a flat face. Hollow it and you'll see the core.
Your turn: Hollow it: after the first line add d = abs(d) - 0.05;
6. Stretch without squashing: elongation
Scaling a shape squashes its round parts. Elongating keeps them: q = p - clamp(p, -h, h) measures every point within h of the middle as if it were at the middle, so the shape is cut in half and pulled apart, with a straight piece in between.
A sphere becomes a capsule, a box a longer box with the same rounded edges, and this ring becomes a chain link.
Your turn: Pull it into a link: const vec3 STRETCH = vec3(0.5, 0.0, 0.0);
7. One shape into another: morphing
Mixing two distances, mix(ball, box, m), gives a shape in between: 0 the ball, 1 the box, 0.5 halfway, a softened box. Animate m and one turns into the other.
It isn't an exact distance in between, but close enough for the march (it never overestimates by much). It works for any two shapes, even very different ones, and for whole scenes.
Your turn: Animate it: float m = 0.5 + 0.5 * sin(time);
8. Easing: motion that feels right
The ball slides from side to side at a steady speed and turns round instantly at each end. Nothing real moves like that: it looks mechanical.
Easing reshapes the 0 to 1 of the motion. smoothstep(0.0, 1.0, x) starts slowly, speeds up through the middle and slows to a stop: the ball now seems to have weight. Other curves give other characters: x * x accelerates away, 1.0 - (1.0 - x) * (1.0 - x) brakes in, and overshooting ones spring.
Watch it move rather than a still frame: that's where easing shows.
Your turn: Ease it: float e = smoothstep(0.0, 1.0, x);
9. Squash and stretch
Animators' oldest trick: a ball that flattens as it lands looks soft and alive; one that stays round looks like a bearing. The squash s scales the ball down vertically and up sideways by its square root, so it keeps its volume.
Scaling space changes distances, so the distance is multiplied back by the smallest scale (* s) to keep it safe to march.
h is the height above the floor. Squash it only close to the ground: 1 up in the air, flatter as h nears 0.
Your turn: Squash it on landing: float s = 1.0 - 0.45 * smoothstep(0.35, 0.0, h);
10. Colours that melt together
Two blobs smoothly joined, one blue, one orange. The colour is picked by which blob is nearer, so the join has a hard line where the shape has none.
sminC returns the blend as well as the distance: its .y is how much of the first shape is in the mix, 1 on the blue blob, 0 on the orange, in between across the join. Mixing the colours by it makes the colour melt exactly where the shapes do. The same trick blends any material property: roughness, glow, texture.
Your turn: Blend the colours: vec3 paint = mix(ORANGE, BLUE, m.y);
11. Three-point lighting
Photographers light a subject with three lights. The key does most of the work, from above and to one side, casting the shadows. The fill, dimmer and from the other side, keeps the shadows from going black. The rim, from behind, draws a bright edge round the outline that lifts it off the background.
Key and fill are here. A real rim light behind would need its own direction; the cheap version used everywhere brightens surfaces we see edge-on: 1.0 - dot(n, -rd) is 0 facing us and 1 side-on, and the power keeps it to a thin edge.
Your turn: Add the rim: after the col = albedo * … line, add if (!isFloor) col += vec3(0.5, 0.75, 1.0) * rim * 0.8;
12. Highlights
Shiny things show a bright spot where the light reflects towards you: the specular highlight. Blinn-Phong is the classic recipe. hv, the direction halfway between the light and the eye, lines up with the normal exactly where the light would bounce into your eye.
pow(dot(n, hv), 64.0) is 1 there and drops away; the power is the shininess. 8 is a broad soft sheen (rubber), 64 plastic, 512 a tiny sharp glint (glass, wet things). It's white whatever the surface colour: that's what makes plastic look like plastic.
Your turn: Add a highlight: float spec = pow(max(dot(n, hv), 0.0), 64.0);
13. Metal or plastic
Five balls in a row (a limited repetition), all the same gold colour, all plastic. What makes metal look like metal isn't its colour.
Every surface reflects its surroundings more at grazing angles (Fresnel). Plastic reflects only 4% head-on, and that reflection is white: under it you see the coloured paint (diffuse). Metal has no paint underneath: it's all reflection, and the reflection itself is coloured. F0, the head-on reflection, goes from 4% grey to the metal's own colour, and the diffuse fades out.
id is which ball: −2 to 2. (id + 2.0) / 4.0 goes 0, 0.25, 0.5, 0.75, 1 along the row (in-between values are for blends, like dusty metal).
Your turn: Plastic to metal along the row: float metal = (id + 2.0) / 4.0;
14. Rough or polished
All five are metal now, all polished: each shows the studio's softbox as a sharp bright patch. Roughness is how scratched the surface is at a tiny scale: each spot reflects a slightly different direction, so the reflection blurs and the highlight spreads and dims.
Here env(direction, rough) stands in for that: the rougher, the wider and fainter the softbox. Real renderers average many directions, or blurred copies of the surroundings (the Skies and reflections course's mipmaps).
Metal and roughness are the two numbers behind almost every material in modern games and films.
Your turn: Polished to brushed along the row: float rough = (id + 2.0) / 4.0;
15. Toon shading
Cartoons don't shade smoothly: a lit colour, a shadow colour, maybe one in between. Rounding the light to a few levels does it: floor(dif * 3.0 + 0.5) / 3.0 turns 0..1 into 0, 1/3, 2/3 or 1.
It's applied after the shadow, so cast shadows become flat shapes too. More bands is softer; 2 is the bold comic look.
Your turn: Flatten the light into bands: after the dif line, add dif = floor(dif * 3.0 + 0.5) / 3.0;
16. Ink outlines
The last piece of the cartoon look: a black line round the outline. A marching ray already knows how close it came to the object: minObj keeps the smallest distance on the way. A ray that missed the object but came within a hair of it is just outside the outline.
So: where the ray didn't hit the object (sky, or the floor), darken by how close it came. smoothstep(0.03, 0.015, minObj) is 1 within 0.015 and fades by 0.03. The line has the same width in world units, so nearer things get thicker lines, like a real pen drawing.
Your turn: Draw the ink: float outline = smoothstep(0.03, 0.015, minObj);
17. Skip the work: bounding volumes
Sixteen blobs melted together: every call of map works out all sixteen distances, however far the point is from them. Most of the march (the sky, the floor, the empty space round it) is far from everything, and pays the full price for nothing.
A bounding volume is a cheap shape round the whole expensive one. Far outside it, its distance is a safe answer: it's never more than the real one, since the blobs are inside. Only near it is the real work done.
SHOW_COST is on: brighter is more work per pixel (each map call counted, the blob loop as 16). Then turn it off; the picture is the same.
Your turn: Skip the blobs when far away: after the bound line add if (bound > 0.3) return bound;
18. Smooth edges over time
One ray per pixel gives jagged edges and shimmering thin details: the gear's teeth and the checked floor far away. Raymarching, step by step did several rays per pixel at once, multiplying the cost.
When the picture keeps still, the rays can be spread over frames instead. Each frame every pixel's ray goes through a slightly different spot within the pixel (jitter), and the result is blended into the last frame's (feedback, this pass's own last picture). Over a few frames the average is a smooth edge, at the cost of one ray per frame.
w is this frame's share. With 1 it's all new frame, no smoothing. 1.0 / float(frame + 1) is an exact average of every frame so far; keeping at least 0.05 lets edits show within a second.
Your turn: Average over frames: float w = max(1.0 / float(frame + 1), 0.05);
19. Motion blur
A camera's shutter is open for a moment, not an instant, so fast things smear along their path. Without it, fast motion looks choppy, strobing: this gear spins fast enough that the teeth jump.
Same idea as the last step, spread over time instead of space: each pixel, each frame, picks a random moment within the shutter, T = time + (random - 0.5) * SHUTTER, and the scene is drawn at that moment. Blended over frames (here a fixed 25% of each), the moments average into a smear: the faster something moves, the longer.
SHUTTER is in seconds: 0 is a frozen instant. At 60 frames a second a film camera's is about 1/120.
Your turn: Open the shutter: const float SHUTTER = 0.03;
20. Pull it apart: clockwork
A clockwork: two brass gears meshing (polar repetition), two posts modelled once (symmetry), metal with Fresnel reflections of the studio, soft shadows. Read through it.
But look at the teeth: every one is cut in half down the middle, and they don't sit where the gaps of the other gear are. Something in how gear repeats its tooth is off.
Hint: the angle within a slice should run from −half a slice to +half, so the tooth (at angle 0) sits in the middle of its slice. What range does mod(…, k) give?
Your turn: Fix the teeth.
Other courses: Basics · Medium · Advanced · Maths for shaders · Raymarching, step by step · Matrices, from scratch · Sound you can see · Noise from scratch · Colour and light · Passes and feedback · Skies and reflections · Vertex shaders, step by step · Raymarching 2: glow, fog and light · Raymarching 3: worlds · Fractals, step by step · Vertex shaders 2: lines, particles and moving meshes · Fractals 2: further in · Vertex shaders 3: living geometry · Post-processing · Surfaces: from vertex to fragment · Blur and glow