Introduction

So far this series has drawn flat shapes. Distance functions work just as well in 3D: a sphere is length(p) − r, with p a three-number (x, y, z) point measured from the centre and r the radius, and every trick from SDF part 2 works unchanged. But how do you draw a 3D distance function on a 2D screen? With ray marching, the technique behind many astonishing Shadertoy scenes. This post covers:

  • The idea: fire a ray from each pixel and find where it meets the surface
  • Sphere tracing: using the distance to take big, safe steps
  • Getting normals, lighting and shadows from the same function
  • The costs and uses of the technique

It builds on Rays and Intersections.

Marching Along a Ray

For each pixel, imagine a ray from the camera out through that pixel. We want the first point where it touches the scene: where the distance function is zero. A single sphere has a formula for that, but a scene of blended, repeated, twisted shapes doesn’t. So instead, we march: step along the ray until we arrive.

How big should each step be? Too small and it takes forever; too big and we might jump through a thin object. Here distance functions shine: at any point, they give the distance to the nearest surface in any direction. Nothing is within that distance, so we can safely jump exactly that far along the ray, then measure and jump again. Near a surface the steps get tiny; once the distance is almost zero, we’ve arrived. This is sphere tracing (the safe areas are circles in 2D, spheres in 3D).

Drag the ray’s start and aim point below. Each orange circle is the distance measured at that step; the ray jumps to its edge.

Sphere tracing in 2D: each step jumps as far as the distance allows

The marching loop for this ray, with the current numbers filled in:

In the code, ro (ray origin) is where the ray starts and rd (ray direction) the way it points, as a unit vector. A point t units along the ray is ro + rd * t, as in Rays and Intersections. scene is the distance to all the shapes together: the min of their distances, as in SDF part 2. The d values show the steps shrinking as the ray closes in.

Things to notice:

  • In open space the ray takes huge steps; near a surface the circles shrink until they’re tiny.
  • Aim the ray to skim just past a shape. The steps become tiny as it passes close by, and it may run out of steps, which is why real ray marchers always set a maximum number of steps and distance.
  • Set Maximum steps to 1, 2, 3… to watch it step by step.

A Real 3D Scene

The demo below draws a whole 3D scene this way, in one fragment shader: a checkered floor, a turning rounded box and a bobbing ball, smoothly blended. There isn’t a single triangle (apart from the one covering the screen to run the shader). Drag to look around.

A ray-marched 3D scene: no triangles, just one distance function

The whole scene is one function giving the distance to the nearest thing: the min of the floor and the smooth union of the box and ball. Everything else comes from it:

  • The surface point: march each pixel’s ray until the distance is tiny.
  • The normal (Basic Lighting): the direction in which the distance grows fastest, found by measuring the distance a tiny step either side of the point along x, y and z.
  • Lighting: the usual N · L with that normal (the dot product).
  • Shadows: march a second ray from the surface towards the light. If it hits something, the point is in shadow; if it only passes close to something, the point is partly shadowed, giving beautiful soft shadows almost for free.
The scene's distance function and normal, as the shader writes them

Slightly simplified from the demo’s shader (which also animates the box and ball):

float scene(vec3 p) {
    float ground = p.y + 1.0;                                  // height above a floor at y = −1
    float box    = sdBox(p - boxCentre, vec3(0.55)) - 0.08;    // a cube, rounded by 0.08
    float ball   = sdSphere(p - ballCentre, 0.5);              // a ball of radius 0.5
    return min(ground, smoothUnion(box, ball, k));             // floor, plus box and ball melted together
}

Here p is a 3D point (x, y, z). The floor is flat at a height of −1, so the distance to it is the point’s height above it, p.y + 1. boxCentre and ballCentre are where the shapes are, and k is the blend slider. sdBox and sdSphere are the 3D versions of SDF part 1’s box and circle, and smoothUnion is the smooth union from SDF part 2.

The normal compares the distance a tiny step e (0.001 units) either side of the point, along each axis:

vec3 normal = normalize(vec3(
    scene(p + vec3(e, 0, 0)) - scene(p - vec3(e, 0, 0)),   // how fast distance grows along x
    scene(p + vec3(0, e, 0)) - scene(p - vec3(0, e, 0)),   // along y
    scene(p + vec3(0, 0, e)) - scene(p - vec3(0, 0, e))    // along z
));

Distance grows fastest straight away from the surface, so together these differences point straight out of it: the normal.

How the soft shadow is worked out

The shadow ray marches from the surface towards the light like the main ray. At each step it knows d, how close the nearest shape is, and t, how far it has travelled. If d reaches (almost) 0, the ray has hit something: full shadow. Otherwise the demo keeps the smallest value of:

k × d ÷ t

seen along the way, and uses it (limited to 0 to 1) as the amount of light. A ray passing close to an object (small d) gets a small value: partly shadowed. Dividing by t makes a near miss far from the surface darken less than one close by, so the shadow is sharp where an object meets the ground and blurrier further away, like real soft shadows. The number k sets the softness; this demo uses 10, and bigger values give harder shadows. (This is Inigo Quilez’s technique, linked below.)

Choose Number of steps per pixel. Most pixels take only a few steps, but rays that skim past the shapes’ edges or graze the distant floor take many more, just as in 2D.

Under the hood

Ray marching is a stern test of a graphics card. Every pixel runs a loop, and neighbouring pixels can need very different numbers of steps, so groups that run in lockstep (How GPUs Run Shaders) wait for their slowest member. The scene function runs dozens of times per pixel (more for normals and shadows), so complex scenes get expensive quickly; this demo renders at slightly reduced resolution for that reason. Games use ray marching selectively: for clouds, fog and smoke, for soft shadows and reflections against simplified distance fields of the scene, and for water and terrain, while the main scene is still drawn with triangles.

Questions You Might Have

Is ray marching the same as ray tracing?

They’re cousins: both fire rays through pixels. Ray tracing usually means finding exactly where a ray hits triangles, helped by special data structures and hardware. Ray marching steps along the ray using a distance function, so it needs no triangles at all.

Summary

  • Ray marching finds where each pixel’s ray meets a surface by stepping along it.
  • Sphere tracing steps by the distance function’s value: always safe, and big in open space.
  • One distance function gives the surface, the normal (how the distance changes), lighting and soft shadows.
  • It’s elegant but costly per pixel; games use it for clouds, fog, shadows and special effects.

That completes the signed distance fields series: from a circle to a whole 3D world, built from distances.

Further Reading