Advanced
glint · Examples · Tutorials · Gallery
3D and beyond: raymarching, lighting, shadows, cameras, fractals, vertex shaders, GPU simulation and HLSL.
A free interactive course of 10 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. Raymarching
To draw 3D, each pixel asks: looking out from the camera through this pixel, what do I see? So each pixel makes a ray, a starting point and a direction. ro (ray origin) is the camera, 4 units back. rd (ray direction) is vec3(uv, 1.5): forward along z, tilted sideways and up by this pixel's position; normalize makes it length 1.
Points along the ray are ro + rd * t, where t is how far along it we are. We want the first t where the ray touches a surface.
map(p) is a 3D distance field, like the 2D ones: how far p is from the nearest surface. Here it's a sphere of radius 1 at the origin, length(p) - 1.0.
The key idea: if the nearest surface is d away, the ray can move d forward without passing through anything. So the loop measures, steps that far, measures again. Each step lands closer; when d is tiny (below 0.001) it's a hit, and if t goes past 20 the ray missed. That's raymarching (also called sphere tracing). The Raymarching course takes it apart line by line, with diagrams.
The colour is only how far the ray went: t near 3 (the front of the sphere) is white, further is darker, a miss is black. Lighting comes next.
To move the sphere, move the point you measure from, as in 2D: length(p - c) - 1.0 is a sphere centred at c.
Your turn: Move the sphere up: subtract a vec3 before measuring, e.g. length(p - vec3(0.0, 0.5, 0.0)) - 1.0.
2. Normals and light
To light a surface we need its normal: the direction it faces, pointing straight out. A distance field makes that easy, because the distance grows fastest straight away from the surface. calcNormal measures map a tiny step (0.001) either side of the point along x, then y, then z; the three differences make a vector pointing out of the surface, and normalize makes it length 1. (e.xyy is just vec3(0.001, 0, 0), and so on.)
A matte surface is brightest where it faces the light and darkens as it turns away. dot(n, l) measures exactly that: 1 when the normal points at the light, 0 when edge-on, negative when facing away. max(…, 0.0) stops the far side going below black.
l is the direction towards the light (not from it). vec3(-0.6, 0.8, -0.4) is left (-x), up (+y) and towards the camera (-z, since the camera sits at z = -4). The 0.1 + adds a little ambient light so the dark side isn't pure black.
pow(col, vec3(0.4545)) is gamma correction. Screens darken mid-tones, so lighting worked out in plain numbers looks harsh without it (0.4545 is 1/2.2).
Try: a second light with its own colour, col += vec3(0.2, 0.3, 0.6) * max(dot(n, normalize(vec3(0.8, -0.2, -0.5))), 0.0);.
Your turn: Move the light: change the light direction vector l (e.g. to come from the right).
3. Modelling in 3D
Everything from the Medium course works in 3D: min joins shapes, max cuts, smin melts. Here map is the min of a sphere and a floor. p.y + 1.0 is the distance to the flat plane y = -1 (a point is p.y + 1 above it).
Repetition works like the grid of cells in 2D. mod(q.xz, 3.0) wraps x and z into 0 to 3, so space repeats every 3 units in both; subtracting 1.5 puts each copy in the middle of its cell. Only x and z are wrapped, so spheres repeat across the floor but not upwards. The floor keeps using the original p.
One sphere's code now draws endless copies at no extra cost: the ray only ever measures the one in the cell it's in. The fog (mix towards the sky by 1.0 - exp(-0.002 * t * t)) fades distant copies out so the horizon isn't a shimmering mess.
The spacing has to be bigger than the object (3 is more than the sphere's width of 2), or copies get sliced off at the cell walls.
Try: bob each sphere with sin(time + floor(p.x / 3.0)) added to q.y, or swap the sphere for a smin with a box.
Your turn: Repeat the sphere along x and z: before measuring, vec3 q = p; q.xz = mod(q.xz, 3.0) - 1.5; then use q for the sphere.
4. A proper camera
So far the camera looked straight along z. A look-at camera can be anywhere and point at anything. From where it is (ro) and what it looks at (ta), it builds three directions:
fw = normalize(ta - ro) forward
rt = normalize(cross(fw, up)) right
up = cross(rt, fw) camera's upForward points from the camera to the target. Right is level and sideways: the cross product of two directions points at right angles to both, so crossing forward with the world's up (0, 1, 0) gives it. Crossing right with forward then gives the camera's own up, tilted with it.
Each pixel's ray is uv.x steps right, uv.y steps up and a fixed amount forward. That forward amount is the lens: more forward brings the pixels' rays closer together, so the view narrows and things look bigger (a telephoto lens); less is a wide angle, with more distortion.
The camera circles the box: ro goes round a circle of radius 3.5 as yaw changes with time and the mouse. Hide the code (Ctrl+.) and drag across the output to orbit and raise it. 0.5 + 0.5 * n colours each face by its normal, which makes the angles easy to read.
Try: move the target, ta = vec3(0.0, 0.5 * sin(time), 0.0), to nod the camera.
Your turn: Zoom in: raise the forward weight (the 1.5 in the rd line) to 2.5 or more.
5. Soft shadows and occlusion
A point is in shadow if something sits between it and the light. So from the surface point, march a second ray towards the light: softShadow(p + n * 0.01, l) (it starts a hair off the surface so it doesn't hit the surface it's on). If it hits anything, direct light doesn't reach the point.
That alone gives hard, sharp-edged shadows. Real shadows are soft at the edges because lights have size. The trick: while marching, note how close the shadow ray came to hitting something compared with how far it had gone, h / t. A ray that only just scraped past was nearly blocked, so the point is partly shadowed. res keeps the smallest k * h / t seen: 1 is fully lit, 0 fully shadowed.
k sets how close a near miss has to be to count. Big k (16) only counts very close misses: sharp edges, like a small bright light. Small k (2 to 4) counts wide misses: soft, blurry edges, like a big overcast sky.
Ambient occlusion (ao) darkens places that are hemmed in, such as the ground under the ball. It samples the distance a few short steps out along the normal. Out in the open the distance grows as fast as the steps, so h - map(…) stays near 0; near other surfaces it grows more slowly, o adds up, and the point darkens. It only affects the ambient light (the 0.2 * part).
Try: turn the ambient part up to 0.5 to see the occlusion clearly, or move the light lower for longer shadows.
Your turn: Make the shadows softer: lower k in softShadow (the 16.0) to 4.0 or less.
6. Materials and fog
To colour objects differently, the scene has to say which one is nearest, not only how far. mapId returns a vec2: x is the distance, y an id (0 is the ground, 1 the torus). ground.x < torus.x ? ground : torus does what min does, but keeps the winner's id with it.
The march loop remembers the id of the last thing it measured (id = h.y), which is what the ray hit. albedo (the surface's own colour) is then chosen by id: id > 0.5 means the torus (comparing with 0.5 is safer than testing a float for exactly 1.0). The ground is a checkerboard: mod(floor(p.x) + floor(p.z), 2.0) alternates 0 and 1 from square to square.
Fog: mix(col, sky, 1.0 - exp(-0.01 * t * t)). Near the camera (small t) the exp is close to 1, so there's no fog; far away it drops to 0, so it's all sky. It hides the hard horizon and makes depth easy to read.
sdTorus is a ring of radius 0.8 around the y axis, 0.25 thick. The rotation on q.yz tumbles it around x as time goes on.
Try: a third object with id 2.0 and its own colour, or thicker fog (0.03).
Your turn: Give the torus a different colour: change the colour used for material 1 (the vec3(0.9, 0.3, 0.2)).
7. Folding space: fractals
p = abs(p) mirrors space in all three axes: the point (-1, 2, -3) is measured as (1, 2, 3), so whatever is in the positive corner appears in all eight corners. Subtracting an offset then moves the mirror planes apart, so the copies separate. Fold again and again and the copies multiply: 8, 64, 512…
Each time round the loop: fold (abs), shift (- vec3(1.0, 1.0, 1.0)), scale up (p *= 2.0, so each round's copies are half the size of the last) and turn a little (the mat2 on p.xy), so it isn't all right angles. After 5 rounds, measuring one box gives thousands of tiny ones.
Scaling p up by 2 each round makes the distances too big by the same amount, so the total scale s is tracked and the distance is divided by it at the end. Without that, rays would overshoot and the fractal would be full of holes.
The offset is where the fun is: it decides where the copies go, and small changes make very different shapes. The turn matters too (0.8, 0.6 is about 37°).
Try: offsets between 0.5 and 1.5 in each axis, or a different angle: mat2(cos(0.3), -sin(0.3), sin(0.3), cos(0.3)).
Your turn: Change the fold offset (the vec3(1.0, 1.0, 1.0) subtracted in the loop) and watch the fractal change.
8. Vertex shaders
Until now every step drew a rectangle over the whole screen and did the work per pixel, in the fragment shader. The vertex shader is the other half of the pipeline: it runs once per point of a mesh, and its job is to say where that point goes on screen (gl_Position).
This pass has no mesh (Pass settings › Geometry is Vertices only). It asks for 30,000 points and the vertex shader invents each one's position from its number, gl_VertexID (0, 1, 2 … 29,999). t turns that number into a position along a curve, 0 to 6.28.
The curve is a Lissajous knot: x, y and z are each a sine or cosine of t at a different frequency (3, 2 and 5). Different whole numbers make different knots. The time * 0.3 in x makes it slowly change shape.
mvp is the camera (model-view-projection matrix, from Pass settings › Camera): it turns a 3D point into a place on screen, with perspective. gl_PointSize is the point's size in pixels. v_color is handed on to the fragment shader (the Fragment tab), which colours each point. The pass adds overlapping points together (Blend: add), so crossings glow.
Try: * (0.9 + 0.1 * sin(time + t * 20.0)) on p to make it pulse along its length.
Your turn: Change the knot: edit the frequencies in the sin/cos calls (e.g. the 3.0 or 2.0) in the vertex shader.
9. Simulation on the GPU
Feedback can remember numbers, not only pictures. Each pixel of pass 0 (Waves) stores the height of a water surface at that spot: red is the height now, green the height a frame ago. Every frame the pass reads them and writes the next heights. What you see is pass 1 (Light) shading that height map.
texelFetch(feedback, p, 0) reads exactly one stored pixel, with no blending. The four lines after it read the neighbours left, right, up and down; clamp keeps them from reading off the edge.
The wave equation, in words: water speeds up towards the average of its neighbours.
2.0 * s.r - s.g keep moving
0.25 * (n - 4.0 * s.r) pull to neighbours
* 0.95 lose energyKeep moving: now + (now - a frame ago), carrying on at the speed it had. Pull to neighbours: n is the sum of the four, so n - 4.0 * s.r is how far this point is below their average. Lose energy: without it ripples would bounce around forever. Then vec4(next, s.r, …) stores the new height in red and this frame's height in green, which is “a frame ago” next time. A drop sets the height to 1.0 in a small circle: at the mouse while you click (hide the code with Ctrl+. first), or at random spots a few times a second. frame < 2 clears everything at the start.
At 0.95 ripples die out quickly; closer to 1.0 they cross the whole screen. The Light pass works out the surface's slope from neighbouring heights (like the normals in step 2) and lights it, so the ripples look like glass.
Your turn: Let ripples travel further: raise the damping (the 0.95) closer to 1.0, e.g. 0.99.
10. HLSL, the other language
HLSL is the shader language of Direct3D, Unity, Unreal and many VJ tools. The ideas are all the same as GLSL's; mostly the spelling differs:
GLSL HLSL
vec2, vec3, vec4 float2, float3, float4
mat3 float3x3
mix(a, b, t) lerp(a, b, t)
fract(x) frac(x)
clamp(x, 0., 1.) saturate(x)
M * v mul(M, v)
texture(s, uv) tex.Sample(samp, uv)Uniforms are just global variables (float time;). The entry function returns the colour instead of setting fragColor, and semantics label what things are: pos : SV_Position is the pixel's position (like gl_FragCoord), and : SV_Target after the function means its result is the colour.
This pass is HLSL (Pass settings › Language), but two GLSL spellings were left in, so it doesn't compile: the error bar at the bottom points at them. glint translates HLSL to GLSL behind the scenes to run it.
Your turn: Fix it: change vec3 to float3 and mix to lerp.
Other courses: Basics · Medium · 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 · Raymarching 4: modelling, materials and motion · 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