TExcelTAD
Home › Shaders & Graphics Programming › Mini Project: Animated Raymarched Scene

Mini Project: Animated Raymarched Scene

Time to put the course together in one shader: a small animated 3D scene, rendered entirely in a fragment shader. A ball bounces on a checkered floor, a golden torus spins, a row of stone pillars recedes into the haze, and the camera orbits (or follows your mouse). It uses almost everything from the lighting and effects lessons:

Feature Lessons
Sphere tracing, SDF primitives, repetition, look-at camera Raymarching SDF Scenes
Normals from the SDF gradient Normal Estimation
Lambert, hemisphere sky light, gamma Diffuse Lighting
Blinn-Phong highlights, tinted metal reflections Specular, PBR
Soft shadows and ambient occlusion Soft Shadows and AO
Distance fog, sky and sun disk Fog
Tone mapping and vignette Color Grading
Mouse orbit Mouse Interaction

We build it in five steps. Each step is a complete shader you can run, and two deliberate mistakes along the way show you how to read the compiler's complaints.

Step 1: the scene and materials

A raymarched scene needs to know not only how far the nearest surface is but which surface it is, so it can be colored differently. The standard trick: map returns a vec2, with the distance in x and a material id in y. Combining two objects keeps the whole vec2 of the nearer one:

glsl
vec2 opU(vec2 a, vec2 b) { return a.x < b.x ? a : b; }   // union that keeps the material id

Step 1 builds the four objects, the orbiting camera and the march, and colors each pixel by its material id, with no lighting yet. Flat colors are an excellent debugging view: if an object is missing or the wrong color here, no amount of lighting will fix it.

glsl · try it yourself
// Material ids: 1 floor, 2 ball, 3 torus, 4 pillars.
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; }
mat2 rot(float a) { float c = cos(a), s = sin(a); return mat2(c, s, -s, c); }
vec2 opU(vec2 a, vec2 b) { return a.x < b.x ? a : b; }

vec2 map(vec3 p) {
    vec2 res = vec2(p.y, 1.0);                                        // floor
    float h = abs(sin(iTime * 2.5));                                  // bounce: 0 at the floor, 1 at the top
    res = opU(res, vec2(length(p - vec3(-0.8, 0.55 + 1.6 * h, 0.0)) - 0.55, 2.0));
    vec3 q = p - vec3(1.6, 1.2, 0.6);
    q.yz *= rot(iTime);
    q.xy *= rot(iTime * 0.7);
    res = opU(res, vec2(sdTorus(q, vec2(0.65, 0.22)), 3.0));
    vec3 r = p - vec3(0.0, 0.0, 4.5);
    r.x = mod(r.x + 1.75, 3.5) - 1.75;                                // pillars every 3.5 units
    res = opU(res, vec2(sdBox(r - vec3(0.0, 1.6, 0.0), vec3(0.3, 1.6, 0.3)) - 0.05, 4.0));
    return res;
}

vec2 raymarch(vec3 ro, vec3 rd) {
    float t = 0.0;
    for (int i = 0; i < 160; i++) {
        vec2 h = map(ro + rd * t);
        if (h.x < 0.0005 * t + 0.0005) return vec2(t, h.y);           // epsilon grows with distance
        t += h.x;
        if (t > 60.0) break;
    }
    return vec2(t, -1.0);                                              // miss
}

mat3 camera(vec3 eye, vec3 target) {
    vec3 f = normalize(target - eye);
    vec3 r = normalize(cross(vec3(0.0, 1.0, 0.0), f));
    return mat3(r, cross(f, r), f);
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
    float a = 0.25 * iTime;
    vec3 target = vec3(0.0, 1.0, 0.0);
    vec3 ro = target + vec3(7.0 * sin(a), 1.8, -7.0 * cos(a));
    vec3 rd = camera(ro, target) * normalize(vec3(uv, 1.8));

    vec2 hit = raymarch(ro, rd);
    vec3 color = vec3(0.5, 0.7, 1.0);                                  // sky
    if (hit.y == 1.0) color = vec3(0.5);
    if (hit.y == 2.0) color = vec3(0.9, 0.15, 0.1);
    if (hit.y == 3.0) color = vec3(1.0, 0.75, 0.3);
    if (hit.y == 4.0) color = vec3(0.8, 0.78, 0.72);
    fragColor = vec4(color, 1.0);
}

Notes on step 1:

  • The hit epsilon grows with distance (0.0005 * t + 0.0005). A fixed tiny epsilon wastes iterations on far-away surfaces that cover less than a pixel; a growing one stops as soon as the error is invisible.
  • Comparing floats with == for the material id is safe here, because the ids are small whole numbers copied around, never computed.
  • q.yz *= rot(iTime) rotates the point (and so the torus) in the y-z plane. vec2 *= mat2 multiplies the row vector by the matrix, which rotates the opposite way to mat * vec: either is fine for spinning.

Step 2: a refactoring mistake

Changing map from float to vec2 is a typical refactor, and it is easy to miss a caller. Suppose the normal function still treats map as returning a float:

glsl · try it yourself
vec2 map(vec3 p) {
    return vec2(length(p) - 1.0, 2.0);
}

vec3 calcNormal(vec3 p) {
    const vec2 e = vec2(0.001, 0.0);
    float d = map(p);
    return normalize(vec3(map(p + e.xyy).x - d, map(p + e.yxy).x - d, map(p + e.yyx).x - d));
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
    vec3 n = calcNormal(vec3(uv, -0.5));
    fragColor = vec4(n * 0.5 + 0.5, 1.0);
}
Shader compile error:
ERROR: line 7: '=' : dimension mismatch
ERROR: line 7: '=' : cannot convert from 'highp 2-component vector of float' to 'highp float'

How to read it:

  1. line 7: the line in your code. Go there first. Both errors point at the same line and the same token, so they describe one problem.
  2. '=': the token where the compiler gave up, here the assignment.
  3. The messages: dimension mismatch says the two sides have different sizes; the second line says which: the right side is a vec2 ('highp 2-component vector of float' is the compiler's long name for vec2) and the left side is a float. GLSL never converts between them silently.

The fix is float d = map(p).x;. Notice the other calls on line 8 already use .x; a partial refactor is the classic source of this error. The lesson generalizes: when the compiler mentions 2-component vector, 3-component vector or 4x4 matrix, translate it back to vec2, vec3 and mat4 and look for the missing swizzle or constructor.

Step 3: lighting

Now the light: normals by the tetrahedron technique (taking .x everywhere!), a warm sun with Lambert diffuse and Blinn-Phong specular, and a hemisphere sky light. Each material gets an albedo plus a specular strength and shininess. The floor gets a checker pattern, and the torus is treated as a metal: almost no diffuse, and a specular highlight tinted by its own color.

glsl · try it yourself
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; }
mat2 rot(float a) { float c = cos(a), s = sin(a); return mat2(c, s, -s, c); }
vec2 opU(vec2 a, vec2 b) { return a.x < b.x ? a : b; }

vec2 map(vec3 p) {
    vec2 res = vec2(p.y, 1.0);
    float h = abs(sin(iTime * 2.5));
    res = opU(res, vec2(length(p - vec3(-0.8, 0.55 + 1.6 * h, 0.0)) - 0.55, 2.0));
    vec3 q = p - vec3(1.6, 1.2, 0.6);
    q.yz *= rot(iTime);
    q.xy *= rot(iTime * 0.7);
    res = opU(res, vec2(sdTorus(q, vec2(0.65, 0.22)), 3.0));
    vec3 r = p - vec3(0.0, 0.0, 4.5);
    r.x = mod(r.x + 1.75, 3.5) - 1.75;
    res = opU(res, vec2(sdBox(r - vec3(0.0, 1.6, 0.0), vec3(0.3, 1.6, 0.3)) - 0.05, 4.0));
    return res;
}

vec2 raymarch(vec3 ro, vec3 rd) {
    float t = 0.0;
    for (int i = 0; i < 160; i++) {
        vec2 h = map(ro + rd * t);
        if (h.x < 0.0005 * t + 0.0005) return vec2(t, h.y);
        t += h.x;
        if (t > 60.0) break;
    }
    return vec2(t, -1.0);
}

vec3 calcNormal(vec3 p) {
    const vec2 k = vec2(1.0, -1.0);
    const float e = 0.0005;
    return normalize(k.xyy * map(p + k.xyy * e).x + k.yyx * map(p + k.yyx * e).x +
                     k.yxy * map(p + k.yxy * e).x + k.xxx * map(p + k.xxx * e).x);
}

mat3 camera(vec3 eye, vec3 target) {
    vec3 f = normalize(target - eye);
    vec3 r = normalize(cross(vec3(0.0, 1.0, 0.0), f));
    return mat3(r, cross(f, r), f);
}

const vec3 SUN_DIR = vec3(0.57, 0.62, -0.54);           // already unit length
const vec3 SUN_COLOR = vec3(1.0, 0.9, 0.75) * 1.6;
const vec3 SKY_COLOR = vec3(0.45, 0.6, 0.9);

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
    float a = 0.25 * iTime;
    vec3 target = vec3(0.0, 1.0, 0.0);
    vec3 ro = target + vec3(7.0 * sin(a), 1.8, -7.0 * cos(a));
    vec3 rd = camera(ro, target) * normalize(vec3(uv, 1.8));

    vec2 hit = raymarch(ro, rd);
    vec3 color = SKY_COLOR;
    if (hit.y > 0.0) {
        vec3 p = ro + rd * hit.x;
        vec3 n = calcNormal(p);
        vec3 v = -rd;
        vec3 h = normalize(SUN_DIR + v);

        vec3 albedo = vec3(0.5);
        float specStrength = 0.1, shininess = 16.0;
        bool metal = false;
        if (hit.y == 1.0) albedo = mix(vec3(0.25), vec3(0.6), mod(floor(p.x) + floor(p.z), 2.0));
        if (hit.y == 2.0) { albedo = vec3(0.8, 0.08, 0.05); specStrength = 0.6; shininess = 96.0; }
        if (hit.y == 3.0) { albedo = vec3(1.0, 0.72, 0.3); specStrength = 1.0; shininess = 128.0; metal = true; }
        if (hit.y == 4.0) albedo = vec3(0.7, 0.66, 0.6);

        float diff = max(dot(n, SUN_DIR), 0.0);
        float spec = pow(max(dot(n, h), 0.0), shininess) * specStrength * step(0.0, diff);
        vec3 specColor = metal ? albedo : vec3(1.0);          // metals tint their reflections
        vec3 diffuseAlbedo = metal ? albedo * 0.1 : albedo;   // and have almost no diffuse
        vec3 hemi = mix(vec3(0.12, 0.1, 0.08), SKY_COLOR * 0.5, 0.5 + 0.5 * n.y);

        color = diffuseAlbedo * (SUN_COLOR * diff + hemi) + specColor * SUN_COLOR * spec;
        if (metal) color += albedo * SKY_COLOR * 0.35 * (0.5 + 0.5 * reflect(rd, n).y);  // fake sky reflection
    }
    fragColor = vec4(pow(color, vec3(1.0 / 2.2)), 1.0);
}

The torus's "fake sky reflection" adds the sky color in the direction the surface mirrors, using only the reflected ray's y: a one-line stand-in for the image-based lighting a real engine would sample from an environment map.

Step 4: the gamma mistake

The scene is lit but still looks like a 3D model viewer: flat sky, infinite visibility, hard-clipped highlights. The finishing pass adds tone mapping and gamma. A very common slip when writing it:

glsl · try it yourself
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec3 color = vec3(fragCoord.x / iResolution.x) * 2.0;    // an HDR ramp from 0 to 2
    color = color / (1.0 + color);                            // Reinhard tone mapping
    color = pow(color, 1.0 / 2.2);
    fragColor = vec4(color, 1.0);
}
Shader compile error:
ERROR: line 4: 'pow' : no matching overloaded function found
ERROR: line 4: '=' : dimension mismatch
ERROR: line 4: 'assign' : cannot convert from 'const mediump float' to 'highp 3-component vector of float'

Three errors, one mistake. Read from the top: no matching overloaded function found is the cause. Because the call failed, the compiler gave the bad pow(...) expression a placeholder type (a float), and the next two errors complain that a float can't be assigned to the vec3 called color. Fix the first error and the others vanish; chasing the last one would lead you astray.

no matching overloaded function found means "a function with this name exists, but not for these argument types". GLSL's pow takes two arguments of the same type: pow(float, float), pow(vec3, vec3) and so on. There is no pow(vec3, float). Write pow(color, vec3(1.0 / 2.2)). The same error appears for mix(vec3, vec3, int) (use 1.0, not 1), max(vec2, int), or texture called with a vec3 coordinate on a sampler2D. When you see it, check each argument's type against the function's signatures, which are listed in the GLSL ES 3.00 specification (section 8, "Built-in Functions").

Note the division in line 3 is fine: color / (1.0 + color) mixes a vec3 and a float with operators, which GLSL allows; only the built-in functions insist on matching types.

Step 5: atmosphere, shadows and the final image

The final step adds everything that makes it feel like a place:

  • soft shadows from the sun and ambient occlusion on the sky light;
  • a sky with a horizon gradient and a sun disk, used both for misses and for the metal's reflection;
  • distance fog that blends toward the horizon color, which also hides the endless pillars;
  • ACES-style tone mapping (Krzysztof Narkowicz's curve fit), then gamma;
  • a gentle vignette;
  • mouse orbit: drag horizontally to rotate the camera, vertically to raise it.
glsl · try it yourself
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; }
mat2 rot(float a) { float c = cos(a), s = sin(a); return mat2(c, s, -s, c); }
vec2 opU(vec2 a, vec2 b) { return a.x < b.x ? a : b; }

vec2 map(vec3 p) {
    vec2 res = vec2(p.y, 1.0);
    float h = abs(sin(iTime * 2.5));
    res = opU(res, vec2(length(p - vec3(-0.8, 0.55 + 1.6 * h, 0.0)) - 0.55, 2.0));
    vec3 q = p - vec3(1.6, 1.2, 0.6);
    q.yz *= rot(iTime);
    q.xy *= rot(iTime * 0.7);
    res = opU(res, vec2(sdTorus(q, vec2(0.65, 0.22)), 3.0));
    vec3 r = p - vec3(0.0, 0.0, 4.5);
    r.x = mod(r.x + 1.75, 3.5) - 1.75;
    res = opU(res, vec2(sdBox(r - vec3(0.0, 1.6, 0.0), vec3(0.3, 1.6, 0.3)) - 0.05, 4.0));
    return res;
}

vec2 raymarch(vec3 ro, vec3 rd) {
    float t = 0.0;
    for (int i = 0; i < 160; i++) {
        vec2 h = map(ro + rd * t);
        if (h.x < 0.0005 * t + 0.0005) return vec2(t, h.y);
        t += h.x;
        if (t > 60.0) break;
    }
    return vec2(t, -1.0);
}

vec3 calcNormal(vec3 p) {
    const vec2 k = vec2(1.0, -1.0);
    const float e = 0.0005;
    return normalize(k.xyy * map(p + k.xyy * e).x + k.yyx * map(p + k.yyx * e).x +
                     k.yxy * map(p + k.yxy * e).x + k.xxx * map(p + k.xxx * e).x);
}

float softShadow(vec3 ro, vec3 rd, float k) {
    float res = 1.0, t = 0.02;
    for (int i = 0; i < 48; i++) {
        float d = map(ro + rd * t).x;
        if (d < 0.0005) return 0.0;
        res = min(res, k * d / t);
        t += clamp(d, 0.02, 0.5);                         // bounded steps: fewer iterations, no tunneling
        if (t > 12.0) break;
    }
    return clamp(res, 0.0, 1.0);
}

float ambientOcclusion(vec3 p, vec3 n) {
    float occ = 0.0, w = 1.0;
    for (int i = 1; i <= 5; i++) {
        float h = 0.02 + 0.1 * float(i);
        occ += (h - map(p + n * h).x) * w;
        w *= 0.7;
    }
    return clamp(1.0 - 1.8 * occ, 0.0, 1.0);
}

mat3 camera(vec3 eye, vec3 target) {
    vec3 f = normalize(target - eye);
    vec3 r = normalize(cross(vec3(0.0, 1.0, 0.0), f));
    return mat3(r, cross(f, r), f);
}

const vec3 SUN_DIR = vec3(0.57, 0.62, -0.54);
const vec3 SUN_COLOR = vec3(1.0, 0.9, 0.75) * 2.2;

vec3 sky(vec3 rd) {
    vec3 col = mix(vec3(0.55, 0.65, 0.8), vec3(0.15, 0.35, 0.8), clamp(rd.y * 2.5, 0.0, 1.0));
    float s = max(dot(rd, SUN_DIR), 0.0);
    col += SUN_COLOR * (pow(s, 600.0) * 4.0 + pow(s, 12.0) * 0.08);   // disk + glow
    return col;
}

vec3 acesFilm(vec3 x) {
    return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0);
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;

    float yaw = 0.25 * iTime, height = 1.8;
    if (iMouse.z > 0.0) {                                  // a button is held: follow the mouse
        vec2 m = iMouse.xy / iResolution.xy;
        yaw = (m.x - 0.5) * 6.2832;
        height = 0.4 + 4.0 * m.y;
    }
    vec3 target = vec3(0.0, 1.0, 0.0);
    vec3 ro = target + vec3(7.0 * sin(yaw), height, -7.0 * cos(yaw));
    vec3 rd = camera(ro, target) * normalize(vec3(uv, 1.8));

    vec2 hit = raymarch(ro, rd);
    vec3 color = sky(rd);
    if (hit.y > 0.0) {
        vec3 p = ro + rd * hit.x;
        vec3 n = calcNormal(p);
        vec3 v = -rd;
        vec3 h = normalize(SUN_DIR + v);

        vec3 albedo = vec3(0.5);
        float specStrength = 0.1, shininess = 16.0;
        bool metal = false;
        if (hit.y == 1.0) albedo = mix(vec3(0.25), vec3(0.6), mod(floor(p.x) + floor(p.z), 2.0));
        if (hit.y == 2.0) { albedo = vec3(0.8, 0.08, 0.05); specStrength = 0.6; shininess = 96.0; }
        if (hit.y == 3.0) { albedo = vec3(1.0, 0.72, 0.3); specStrength = 1.0; shininess = 128.0; metal = true; }
        if (hit.y == 4.0) albedo = vec3(0.7, 0.66, 0.6);

        float diff = max(dot(n, SUN_DIR), 0.0);
        float sha = diff > 0.0 ? softShadow(p + n * 0.002, SUN_DIR, 10.0) : 0.0;
        float ao = ambientOcclusion(p, n);
        float spec = pow(max(dot(n, h), 0.0), shininess) * specStrength * sha;

        vec3 specColor = metal ? albedo : vec3(1.0);
        vec3 diffuseAlbedo = metal ? albedo * 0.1 : albedo;
        vec3 skyLight = mix(vec3(0.12, 0.1, 0.08), vec3(0.3, 0.45, 0.7), 0.5 + 0.5 * n.y) * ao;

        color = diffuseAlbedo * (SUN_COLOR * diff * sha + skyLight) + specColor * SUN_COLOR * spec;
        if (metal) color += albedo * sky(reflect(rd, n)) * 0.4 * ao;

        float fog = 1.0 - exp(-0.0015 * hit.x * hit.x);
        color = mix(color, sky(rd), fog);
    }

    color = acesFilm(color * 0.65);                        // exposure, then HDR -> 0..1
    color = pow(color, vec3(1.0 / 2.2));                   // linear -> display
    vec2 q = fragCoord / iResolution.xy;
    color *= 0.5 + 0.5 * pow(16.0 * q.x * q.y * (1.0 - q.x) * (1.0 - q.y), 0.2);  // vignette
    fragColor = vec4(color, 1.0);
}

What changed from step 3, and why:

Change Why
Sun intensity raised to 2.2, then acesFilm lighting is computed in HDR (values above 1 are allowed); tone mapping compresses it into 0..1 smoothly instead of clipping highlights to flat white
sha multiplies the sun's diffuse and specular a point in shadow gets no highlight from that light
ao multiplies only the sky light AO models blocked indirect light
sky(reflect(rd, n)) for the metal the torus mirrors the same sky the camera sees, sun disk included
fog 1 - exp(-0.0015 t²) squared-exponential fog keeps the foreground clear and swallows the far pillars, hiding their repetition and the far-distance aliasing
shadow steps clamped to 0.02..0.5 a minimum step stops the loop from crawling along surfaces; a maximum step avoids skipping thin objects

Make it yours

Ideas to extend the project, roughly in order of difficulty:

  1. Make the ball squash when it touches the floor: scale p.y up and p.xz down near h = 0, and multiply the distance by the smallest scale factor to keep the SDF safe.
  2. Give the floor reflections: for material 1, march a second ray along reflect(rd, n) and mix in its color with a Fresnel weight from Rim Light and Fresnel.
  3. Replace Blinn-Phong with the Cook-Torrance BRDF from PBR, and give each material a roughness and metallic value instead of shininess.
  4. Add a dissolve to the torus with the noise threshold from Dissolve. (Hint: in a raymarcher, "discarding" means continuing to march through the dissolved region; offset the SDF by the noise instead.)
  5. Port it to WebGPU by translating the GLSL to WGSL, or into Godot as a canvas_item shader (Godot Shading Language).

Tip: When an extension breaks the image, go back to step 1's trick: output flat material colors, or n * 0.5 + 0.5, or vec3(hit.x / 20.0). Seeing the raw data almost always shows which stage is wrong. Debugging Shaders collects more of these views.

Test yourself

Why does map return a vec2 in this project?

  1. To return two distances for soft shadows
  2. The y component carries a material id for the nearest surface
  3. GLSL functions cannot return float
  4. For 2D rendering

What does ERROR: line 4: 'pow' : no matching overloaded function found mean?

  1. pow does not exist in GLSL ES
  2. No version of pow accepts these argument types
  3. Line 4 is missing a semicolon
  4. The exponent is negative

Why is tone mapping applied before gamma correction?

  1. Gamma must always be first
  2. Tone mapping maps HDR linear light into 0..1; gamma then encodes that linear result for the display
  3. They are interchangeable
  4. Tone mapping only works on sRGB values