22. SDF Ray Marching
Rendering smooth, infinite-detail shapes by marching rays through distance fields
In traditional 3D rendering, scenes are built from triangles — millions of them, each one tested against every pixel. Ray marching takes a radically different approach: shapes are defined by mathematical functions, and we find surfaces by carefully stepping along rays until we get close enough. No vertices. No meshes. No polygon budgets.
The technique was formalized by John Hart in his 1996 paper on sphere tracing, but it had been quietly powering the demoscene for years before that. Today, platforms like Shadertoy host thousands of breathtaking scenes — entire worlds described by a single function, often in under 300 lines of code.
Signed Distance Functions
A signed distance function (SDF) takes a point in space and returns the distance from that point to the nearest surface. The sign tells you which side you're on:
- Positive — outside the shape
- Negative — inside the shape
- Zero — exactly on the surface
The simplest SDF is a sphere centered at the origin with radius :
At any point , the distance to the sphere's surface is the distance from to the origin, minus the radius. If you're standing 5 units from the origin and the sphere has radius 3, you're 2 units from the surface.
In pseudocode:
function sdSphere(p, radius):
return length(p) - radius
More Primitives
Box — An axis-aligned box with half-extents :
function sdBox(p, b):
d = abs(p) - b
return length(max(d, 0)) + min(max(d.x, d.y, d.z), 0)
The first term handles the exterior distance. The second term handles points inside the box, where all components of d are negative.
Torus — A torus with major radius (ring) and minor radius (tube):
function sdTorus(p, R, r):
q = length(p.xz) - R
return length(vec2(q, p.y)) - r
Plane — An infinite ground plane at :
function sdPlane(p):
return p.y
Every point's distance to the plane is just its y-coordinate.
Why "signed"?
The sign is crucial. A regular distance function would be zero at the surface and positive everywhere else — you couldn't tell inside from outside. The sign lets us perform Boolean operations on shapes (union, intersection, subtraction) with simple min and max operations.
Sphere Tracing
Now we need to render these distance fields. The algorithm is called sphere tracing (or ray marching):
- Start at the camera position
- Cast a ray through the pixel into the scene
- Evaluate the SDF at the current position — this gives the distance to the nearest surface
- Step forward along the ray by exactly that distance
- Repeat until the distance is smaller than some tiny (we hit something) or we've marched too far (we missed everything)
The key insight is that the SDF tells us the maximum safe step size. If the nearest surface is 2.5 units away, we can safely move 2.5 units forward without passing through anything — because nothing is closer.
function rayMarch(origin, direction):
t = 0
for i in 0..MAX_STEPS:
p = origin + t * direction
d = sceneSDF(p)
if d < EPSILON:
return t // hit!
t += d
if t > MAX_DIST:
return -1 // miss
return -1 // ran out of steps
Each step traces a "sphere" of safe space around the current point — hence the name. Near surfaces, the steps shrink automatically. In open space, they grow. This adaptive stepping is what makes the algorithm efficient.
Step-by-Step Walkthrough
Imagine a ray heading toward a sphere:
- Step 1 — SDF says nearest surface is 4.2 units away. Advance 4.2 units.
- Step 2 — Now the SDF returns 1.8. We're getting closer. Advance 1.8.
- Step 3 — SDF returns 0.3. Almost there.
- Step 4 — SDF returns 0.02. Under epsilon. Hit.
In empty scenes, the ray takes huge leaps and terminates quickly. Near complex geometry, it takes many small steps, concentrating computation where it matters.
Combining Shapes — CSG Operations
One of the most powerful features of SDFs is how easily shapes combine. Constructive Solid Geometry (CSG) reduces to simple arithmetic on distance values:
Union — the nearest surface of either shape:
function opUnion(d1, d2):
return min(d1, d2)
Intersection — only where both shapes overlap:
function opIntersection(d1, d2):
return max(d1, d2)
Subtraction — carve one shape out of another:
function opSubtraction(d1, d2):
return max(d1, -d2)
Negating an SDF flips inside and outside. max(d1, -d2) keeps points that are inside shape 1 and outside shape 2.
Smooth Union
Hard boolean operations create sharp edges. A smooth minimum blends shapes together, producing organic, melted-looking transitions:
In practice, a polynomial approximation is cheaper and works just as well:
function smin(a, b, k):
h = clamp(0.5 + 0.5 * (b - a) / k, 0, 1)
return mix(b, a, h) - k * h * (1 - h)
The parameter controls the blend radius. Larger values produce wider, smoother transitions.
CSG is just min and max
Boolean operations on meshes are notoriously difficult — you need to clip polygons, handle degenerate cases, and retopologize the result. With SDFs, union is min, intersection is max, and subtraction is max(a, -b). This simplicity is one of the main reasons SDFs are so popular in procedural modeling.
Domain Operations
SDFs describe shapes implicitly, which means we can manipulate the input coordinates to warp and repeat geometry in ways that would be impossibly expensive with meshes.
Infinite Repetition
Take the modulo of the coordinates before evaluating the SDF, and a single shape becomes an infinite grid:
function opRepeat(p, spacing):
q = mod(p + 0.5 * spacing, spacing) - 0.5 * spacing
return sceneSDF(q)
One sphere becomes an infinite lattice. One box becomes an infinite cityscape. The SDF is evaluated once, but the visual result repeats forever in every direction.
Domain Twist
Rotate the XZ plane by an amount proportional to Y, and any shape gets twisted like taffy:
function opTwist(p, amount):
angle = amount * p.y
c = cos(angle)
s = sin(angle)
q = vec3(c * p.x - s * p.z, p.y, s * p.x + c * p.z)
return sceneSDF(q)
Displacement
Add noise or a sine function to the SDF output to create bumpy, organic surfaces:
function opDisplace(p):
d = sceneSDF(p)
displacement = sin(10 * p.x) * sin(10 * p.y) * sin(10 * p.z)
return d + displacement * 0.1
These operations compose freely. You can twist a repeated shape that's been smoothly unioned with a displaced torus — and the entire scene is still just one function returning one number.
Normals and Lighting
To shade a surface, we need its normal — the direction the surface faces at the hit point. With meshes, normals come from vertex data. With SDFs, we estimate them by sampling the gradient of the distance field:
This is the central differences approximation of the gradient. Six SDF evaluations give us the surface normal at any point.
function estimateNormal(p):
e = 0.001
return normalize(vec3(
sdf(p + vec3(e,0,0)) - sdf(p - vec3(e,0,0)),
sdf(p + vec3(0,e,0)) - sdf(p - vec3(0,e,0)),
sdf(p + vec3(0,0,e)) - sdf(p - vec3(0,0,e))
))
With normals in hand, we apply standard Phong lighting:
ambient = 0.1
diffuse = max(dot(normal, lightDir), 0)
specular = pow(max(dot(reflect(-lightDir, normal), viewDir), 0), shininess)
color = material * (ambient + diffuse) + specular
The directional light, the view direction, and the normal — that's all you need for convincing shading.
SDF Ray Marcher
Ambient Occlusion via SDF
Traditional ambient occlusion requires sampling dozens of random directions and tracing rays. With an SDF, we can approximate it cheaply by marching along the normal:
function ambientOcclusion(p, normal):
ao = 0
scale = 1.0
for i in 1..5:
dist = i * 0.1
sampled = sdf(p + normal * dist)
ao += scale * (dist - sampled)
scale *= 0.5
return clamp(1.0 - ao, 0, 1)
At each step, we compare the actual SDF value to the expected distance along the normal. If the SDF is less than the distance (meaning there's geometry nearby), the point is partially occluded. The scale factor weights nearby samples more heavily than distant ones.
This technique produces convincing contact shadows and crevice darkening with just 5 SDF evaluations — no random sampling, no noise.
Soft Shadows
Hard shadows (fully lit or fully dark) look unrealistic. With SDFs, soft shadows are nearly free. As we march a ray from the surface toward the light, we track how close the ray passes to any surface:
function softShadow(origin, lightDir, minT, maxT, k):
result = 1.0
t = minT
for i in 0..64:
d = sdf(origin + lightDir * t)
if d < 0.001:
return 0.0 // fully in shadow
result = min(result, k * d / t)
t += d
if t > maxT:
break
return clamp(result, 0, 1)
The ratio measures how close the ray came to a surface relative to how far it's traveled. A close pass early on means a harder shadow. A near miss far away barely dims the light. The parameter controls shadow softness — higher values produce sharper shadows.
This produces penumbra that varies naturally with the distance between occluder and surface, matching real-world shadow behavior.
The Demoscene Connection
SDF ray marching is the foundation of the demoscene — the subculture of programmers who create audiovisual productions (demos) in absurdly small file sizes. A 4KB demo is 4096 bytes total, including the code, the music, and the visuals.
How do you fit an entire 3D world in 4KB? You can't store mesh data — a single cube takes more than that. But you can describe a scene as a mathematical function:
function scene(p):
ground = p.y
pillars = sdBox(opRepeat(p, vec3(4,0,4)), vec3(0.3, 2, 0.3))
dome = sdSphere(p - vec3(0, 3, 0), 2.0)
return smin(opUnion(ground, pillars), dome, 0.5)
A few lines of SDF code — infinite pillars on a ground plane, blended into a dome. The entire scene is procedural: no textures, no models, no assets. Combine this with procedural camera paths and synthesized audio, and you have a complete demo in a handful of kilobytes.
Famous demos like Elevated (4KB, 2009) and Leviathan (4KB, 2012) used SDF ray marching to render entire mountain landscapes and alien worlds. The technique turned file size constraints from a limitation into an art form.
Conclusion
Signed distance functions represent a fundamentally different way of thinking about geometry. Instead of defining surfaces explicitly — as collections of points, edges, and faces — SDFs define surfaces implicitly as the zero set of a continuous mathematical field. Every point in space knows how far it is from the nearest surface, and that single number is enough to render, combine, warp, and shade shapes in ways that would be extraordinarily complex with traditional meshes.
The math is approachable. The algorithms are short. And the results — smooth blends, infinite repetition, organic warping, cheap shadows and ambient occlusion — are genuinely beautiful. Whether you're building a Shadertoy experiment or trying to understand how a 4KB demo renders an entire world, SDF ray marching is one of the most elegant techniques in computer graphics.