TExcelTAD
Home › Shaders & Graphics Programming › Soft Shadows and Ambient Occlusion

Soft Shadows and Ambient Occlusion

Lambert and Blinn-Phong ask only "which way does this surface face?". They never ask "is something in the way?". Without that, a sphere floats above the ground with no shadow under it, and corners look as bright as open floor. Rasterizers answer the question with shadow maps (render the scene from the light, compare depths). Raymarchers can answer it directly: march a second ray from the surface toward the light. If it hits something, the point is in shadow.

Hard shadows

glsl
float hardShadow(vec3 ro, vec3 rd, float maxT) {
    float t = 0.02;                          // start a little off the surface
    for (int i = 0; i < 64; i++) {
        float d = map(ro + rd * t);
        if (d < 0.001) return 0.0;           // blocked
        t += d;
        if (t > maxT) break;
    }
    return 1.0;                              // reached the light
}

Two details matter:

  • Start offset (t = 0.02, or p + n * 0.01). The shadow ray starts on the surface, where map is about zero, so without an offset every point shadows itself. This "shadow acne" exists with shadow maps too, where it is fixed with a depth bias.
  • maxT: for a point light, stop at the light's distance. Objects behind the light must not cast shadows.

Soft shadows for free

Real lights have a size, so shadows have soft edges (a penumbra). Sphere tracing gives a beautiful approximation at no extra cost, a technique popularized by Inigo Quilez: while marching toward the light, track how close the ray came to any surface, relative to how far along it was. A ray that barely grazes an object is "almost blocked" and gets a partial shadow:

glsl
float softShadow(vec3 ro, vec3 rd, float maxT, float k) {
    float res = 1.0;
    float t = 0.02;
    for (int i = 0; i < 64; i++) {
        float d = map(ro + rd * t);
        if (d < 0.001) return 0.0;
        res = min(res, k * d / t);           // near miss, early along the ray = darker
        t += d;
        if (t > maxT) break;
    }
    return clamp(res, 0.0, 1.0);
}

k controls the softness: around 2 is very soft, 32 is almost hard. Because d / t is an angle-like ratio, the penumbra widens with distance from the occluder, just like a real one.

Compare them: the left half of this frame uses the hard shadow, the right half the soft one with k = 6. The sphere bobs, so you can watch the penumbra grow as it rises.

glsl · try it yourself
float map(vec3 p) {
    float sphere = length(p - vec3(0.0, 1.0 + 0.6 * sin(iTime), 0.0)) - 0.7;
    return min(sphere, p.y);
}

float shadow(vec3 ro, vec3 rd, float k, bool soft) {
    float res = 1.0;
    float t = 0.02;
    for (int i = 0; i < 64; i++) {
        float d = map(ro + rd * t);
        if (d < 0.001) return 0.0;
        if (soft) res = min(res, k * d / t);
        t += d;
        if (t > 20.0) break;
    }
    return clamp(res, 0.0, 1.0);
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
    vec3 ro = vec3(0.0, 2.2, -5.0);
    vec3 rd = normalize(vec3(uv, 1.5) + vec3(0.0, -0.3, 0.0));
    vec3 l = normalize(vec3(0.0, 1.0, 0.6));                // shadow falls straight back, across the divider

    vec3 color = vec3(0.3, 0.45, 0.7);
    float t = 0.0;
    for (int i = 0; i < 100; i++) {
        vec3 p = ro + rd * t;
        float d = map(p);
        if (d < 0.001) {
            bool soft = fragCoord.x > 0.5 * iResolution.x;
            if (p.y > 0.01) {
                color = vec3(0.8, 0.3, 0.2);                // the sphere: flat color, no shadow test
            } else {
                float s = shadow(p + vec3(0.0, 0.01, 0.0), l, 6.0, soft);
                color = vec3(0.8) * (0.25 + 0.75 * s);
            }
            break;
        }
        t += d;
        if (t > 30.0) break;
    }
    fragColor = vec4(pow(color, vec3(1.0 / 2.2)), 1.0);
}

(Only the ground receives shadows here, so the shadow ray can start a fixed 0.01 above it instead of along a computed normal.)

Ambient occlusion

The hemisphere light from the Lambert lesson lights creases and corners as brightly as open surfaces. In reality, less sky reaches a point inside a corner. Ambient occlusion (AO) estimates how open a point is. An SDF makes a cheap estimate: take a few samples along the normal. On an open surface the distance at height h is h; near other geometry it is less. The difference is the occlusion.

glsl
float ambientOcclusion(vec3 p, vec3 n) {
    float occ = 0.0;
    float weight = 1.0;
    for (int i = 1; i <= 5; i++) {
        float h = 0.03 + 0.12 * float(i);
        float d = map(p + n * h);
        occ += (h - d) * weight;             // how much closer than expected
        weight *= 0.75;                      // nearer samples count more
    }
    return clamp(1.0 - 1.5 * occ, 0.0, 1.0);
}

Engines compute AO in screen space (SSAO, HBAO, GTAO) from the depth buffer, or bake it into lightmaps and textures. The idea is the same: dim indirect light where geometry crowds in. AO multiplies only the ambient term, never direct sunlight, which has its own shadows.

All together

The scene below has a sphere, a box and a torus on the ground, a sun that circles, soft shadows, AO on the sky light, and gamma correction. Every three seconds the frame switches to the AO term alone; watch it darken the contact points and the inside of the torus.

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 map(vec3 p) {
    float d = p.y;
    d = min(d, length(p - vec3(-1.6, 0.8, 0.5)) - 0.8);
    d = min(d, sdBox(p - vec3(0.6, 0.5, 1.2), vec3(0.5)));
    vec3 q = p - vec3(1.4, 0.3, -0.6);
    d = min(d, length(vec2(length(q.xz) - 0.6, q.y)) - 0.3);
    return d;
}

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

float softShadow(vec3 ro, vec3 rd, float maxT, float k) {
    float res = 1.0;
    float t = 0.02;
    for (int i = 0; i < 64; i++) {
        float d = map(ro + rd * t);
        if (d < 0.001) return 0.0;
        res = min(res, k * d / t);
        t += d;
        if (t > maxT) 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.03 + 0.12 * float(i);
        occ += (h - map(p + n * h)) * w;
        w *= 0.75;
    }
    return clamp(1.0 - 1.5 * occ, 0.0, 1.0);
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
    vec3 ro = vec3(0.0, 2.6, -5.5);
    vec3 fw = normalize(vec3(0.0, 0.5, 0.0) - ro);
    vec3 rt = normalize(cross(vec3(0.0, 1.0, 0.0), fw));
    vec3 rd = mat3(rt, cross(fw, rt), fw) * normalize(vec3(uv, 1.7));

    vec3 sky = vec3(0.35, 0.55, 0.9);
    vec3 color = sky - 0.3 * rd.y;
    float aoOnly = -1.0;

    float t = 0.0;
    for (int i = 0; i < 128; i++) {
        vec3 p = ro + rd * t;
        float d = map(p);
        if (d < 0.001) {
            vec3 n = calcNormal(p);
            vec3 l = normalize(vec3(cos(iTime * 0.5), 0.8, sin(iTime * 0.5)));
            float diff = max(dot(n, l), 0.0);
            float sha = diff > 0.0 ? softShadow(p + n * 0.01, l, 20.0, 8.0) : 0.0;
            float ao = ambientOcclusion(p, n);
            vec3 albedo = p.y < 0.01 ? vec3(0.55) : vec3(0.8, 0.45, 0.25);

            vec3 sun = vec3(1.0, 0.9, 0.75) * 1.5 * diff * sha;
            vec3 skyLight = sky * 0.45 * (0.5 + 0.5 * n.y) * ao;
            color = albedo * (sun + skyLight);
            aoOnly = ao;
            break;
        }
        t += d;
        if (t > 40.0) break;
    }

    if (mod(iTime, 6.0) > 3.0 && aoOnly >= 0.0) color = vec3(aoOnly * aoOnly);  // show the AO term alone
    fragColor = vec4(pow(color, vec3(1.0 / 2.2)), 1.0);
}

Cost

Shadows multiply work: every lit pixel marches a second ray, and AO adds 5 more map calls. In this scene the shadow march costs about as much as the camera march. Common savings:

  • skip the shadow ray when N·L <= 0 (the point faces away anyway), as the code does;
  • use fewer iterations and a larger minimum step for shadows than for the camera ray;
  • for several lights, cast shadows only from the most important one.

Test yourself

Why does the shadow ray start at p + n * 0.01 instead of exactly at p?

  1. To make shadows softer
  2. At p the SDF is about zero, so the ray would immediately 'hit' its own surface
  3. To save iterations
  4. Because the light is above the surface

In res = min(res, k * d / t), what makes the shadow darker?

  1. A large distance d far along the ray
  2. A small distance d (a near miss) early along the ray (small t)
  3. A large k
  4. The light color

Which lighting term should ambient occlusion multiply?

  1. The direct sunlight
  2. The specular highlight only
  3. The ambient/indirect (sky) light
  4. The final color including emission