Raymarching SDF Scenes
A rasterizer starts from triangles and asks "which pixels does this cover?". A raymarcher starts from the pixel and asks "what does the ray through this pixel hit?". For each pixel it shoots a ray from the camera and walks along it until it reaches a surface. With signed distance functions (SDFs) describing the scene, that walk is fast and the whole 3D world fits in one fragment shader. It is how most Shadertoy scenes are made, and it is the playground we use for the rest of the lighting lessons.
You met 2D SDFs in Shapes with SDFs. In 3D the idea is the same: sdf(p) returns the distance from point p to the nearest surface, negative inside.
| Shape | SDF |
|---|---|
sphere of radius r at the origin |
length(p) - r |
ground plane y = 0 |
p.y |
box with half-size b |
length(max(abs(p) - b, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) with q = abs(p) - b |
torus (radii R, r) |
length(vec2(length(p.xz) - R, p.y)) - r |
Sphere tracing
The trick that makes SDF raymarching fast: if the scene says the nearest surface is d away, you can step exactly d along the ray without passing through anything. Near open space the steps are large, near surfaces they shrink, and when d drops below a small epsilon you have a hit. Here is the loop in JavaScript, marching one ray toward a sphere of radius 1 sitting 5 units in front of the camera:
const sdSphere = (p, c, r) => Math.hypot(p[0] - c[0], p[1] - c[1], p[2] - c[2]) - r;
const scene = (p) => sdSphere(p, [0, 0, 5], 1);
function march(ro, rd) {
let t = 0;
for (let i = 0; i < 64; i++) {
const p = ro.map((o, k) => o + rd[k] * t);
const d = scene(p);
console.log(`step ${i}: t = ${t.toFixed(4)}, distance = ${d.toFixed(4)}`);
if (d < 0.001) return t;
t += d;
if (t > 20) break;
}
return -1;
}
const len = Math.hypot(0.15, 0, 1);
const t = march([0, 0, 0], [0.15 / len, 0, 1 / len]); // a ray slightly to the right
console.log(`hit at t = ${t.toFixed(4)}`);step 0: t = 0.0000, distance = 4.0000
step 1: t = 4.0000, distance = 0.2011
step 2: t = 4.2011, distance = 0.0503
step 3: t = 4.2513, distance = 0.0153
step 4: t = 4.2666, distance = 0.0049
step 5: t = 4.2716, distance = 0.0016
step 6: t = 4.2732, distance = 0.0005
hit at t = 4.2732
Seven steps to find the surface, and the steps shrink as the ray skims past the sphere's side. Rays that graze an edge take many more, which is why the loop has an iteration limit and a maximum distance.
A first raymarched scene
The shader below sets up a camera, builds a ray for each pixel, marches it, and shades by distance: near is bright, far is dark, misses are sky blue. The scene is a sphere resting on a ground plane, combined with min (the union of two SDFs).
float map(vec3 p) {
float sphere = length(p - vec3(0.0, 1.0, 0.0)) - 1.0;
float ground = p.y;
return min(sphere, ground); // union
}
float raymarch(vec3 ro, vec3 rd) {
float t = 0.0;
for (int i = 0; i < 100; i++) {
float d = map(ro + rd * t);
if (d < 0.001) return t; // hit
t += d;
if (t > 40.0) break; // escaped
}
return -1.0;
}
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
// Pixel -> centered coordinates, y from -1 to 1, x scaled by the aspect ratio.
vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
vec3 ro = vec3(0.0, 1.5, -4.0); // ray origin: the camera
vec3 rd = normalize(vec3(uv, 1.5)); // ray direction: 1.5 = focal length
float t = raymarch(ro, rd);
vec3 color = vec3(0.55, 0.7, 0.9); // sky
if (t > 0.0) color = vec3(1.0 - t / 40.0); // depth as brightness: 0 at the far limit
fragColor = vec4(color, 1.0);
}Three lines carry the camera model:
uvmaps the pixel to-1..1vertically, keeping squares square.vec3(uv, 1.5)is a point on an imaginary screen 1.5 units in front of the camera. A bigger number is a longer lens (narrower field of view).normalize(...)turns it into a direction. The marcher needs unit directions, becausetis measured in world units.
A look-at camera
A fixed camera looking down +Z is limiting. A look-at basis builds the camera's right, up and forward axes from an eye position and a target, exactly like lookAt in Math for Games. Here it orbits the scene with iTime, and the SDF list grows: a box, a torus and a smooth union between two spheres.
float sdBox(vec3 p, vec3 b) {
vec3 q = abs(p) - b;
return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0);
}
float sdTorus(vec3 p, vec2 t) {
return length(vec2(length(p.xz) - t.x, p.y)) - t.y;
}
float smin(float a, float b, float k) { // smooth union
float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0);
return mix(b, a, h) - k * h * (1.0 - h);
}
float map(vec3 p) {
float d = p.y; // ground
d = min(d, sdBox(p - vec3(-2.2, 0.6, 0.0), vec3(0.6)));
d = min(d, sdTorus(p - vec3(2.2, 0.35, 0.0), vec2(0.7, 0.25)));
float blobA = length(p - vec3(-0.35, 1.0, 0.0)) - 0.7;
float blobB = length(p - vec3(0.45, 1.2 + 0.3 * sin(iTime * 2.0), 0.0)) - 0.5;
return min(d, smin(blobA, blobB, 0.4));
}
mat3 lookAt(vec3 eye, vec3 target) {
vec3 f = normalize(target - eye); // forward
vec3 r = normalize(cross(vec3(0.0, 1.0, 0.0), f)); // right
vec3 u = cross(f, r); // up
return mat3(r, u, f); // columns: camera axes in world space
}
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
float a = 0.4 * iTime;
vec3 ro = vec3(6.0 * sin(a), 2.5, -6.0 * cos(a));
vec3 rd = lookAt(ro, vec3(0.0, 0.7, 0.0)) * normalize(vec3(uv, 1.8));
float t = 0.0;
bool hit = false;
for (int i = 0; i < 128; i++) {
float d = map(ro + rd * t);
if (d < 0.001) { hit = true; break; }
t += d;
if (t > 40.0) break;
}
vec3 color = vec3(0.55, 0.7, 0.9) - 0.3 * rd.y; // sky gradient
if (hit) color = vec3(exp(-0.12 * t)); // depth fog in grey
fragColor = vec4(color, 1.0);
}The cross(vec3(0, 1, 0), f) order matters: with forward along +Z, it gives right = +X, matching our first camera. Swap the arguments and the image mirrors.
SDF operators
Because shapes are just functions, you combine them with arithmetic. These are the ones you will use most:
| Operation | Code | Effect |
|---|---|---|
| union | min(a, b) |
both shapes |
| intersection | max(a, b) |
only the overlap |
| subtraction | max(a, -b) |
a with b carved out |
| smooth union | smin(a, b, k) |
blobs that melt together over a distance k |
| translate | sdf(p - offset) |
move the shape by moving the point the other way |
| rotate | sdf(inverse(R) * p) |
rotate the point by the inverse rotation |
| repeat | p.xz = mod(p.xz + 0.5 * s, s) - 0.5 * s |
infinite copies every s units, for free |
| round | sdf(p) - r |
inflate and round the corners |
Repetition is the most surprising: one mod gives an endless field of objects for the cost of one. This shader repeats a sphere on the ground plane:
float map(vec3 p) {
vec3 q = p;
q.xz = mod(q.xz + 1.5, 3.0) - 1.5; // one cell is 3 x 3 units
float spheres = length(q - vec3(0.0, 0.6 + 0.3 * sin(iTime + p.x), 0.0)) - 0.6;
return min(p.y, spheres);
}
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
vec3 ro = vec3(0.0, 2.0, iTime * 2.0); // fly forward
vec3 rd = normalize(vec3(uv.x, uv.y - 0.3, 1.5));
float t = 0.0;
for (int i = 0; i < 150; i++) {
float d = map(ro + rd * t);
if (d < 0.001 || t > 60.0) break;
t += d;
}
vec3 color = mix(vec3(0.9, 0.6, 0.4), vec3(0.2, 0.25, 0.4), exp(-0.06 * t));
fragColor = vec4(color, 1.0);
}Tip:
sin(iTime + p.x)uses the unrepeatedp, so each copy bobs with its own phase. Usingqinstead would make them all move in lockstep.
The rules that keep SDFs correct
- The step must never overshoot. An SDF that overestimates distance makes the marcher pass through thin objects. Operations that stretch space (non-uniform scale, twisting, adding a large displacement) break that guarantee: multiply the distance by a safety factor such as
0.5, or stepd * 0.7in the loop. - Scale uniformly:
sdf(p / s) * skeeps distances correct. - Budget iterations. Each step evaluates the whole
map. 100 steps × 10 objects × 2 million pixels is a lot of math; real-time scenes keepmapcheap and stop early.
Test yourself
In sphere tracing, how far does each step move along the ray?
- A fixed 0.01 units
- The distance returned by the scene SDF at the current point
- Half the remaining distance to the far plane
- One pixel
Which operation combines two SDF shapes into their union?
- max(a, b)
- min(a, b)
- a * b
- max(a, -b)
Why can a twisted or non-uniformly scaled SDF make objects disappear in places?
- Distances are overestimated, so steps overshoot surfaces
- GLSL cannot twist
- The loop runs fewer iterations
- Normals become zero