Shaders From Zero · Episode 23

Volumetrics & Fog

Volumetrics & Fog is Episode 23 of Shaders From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 23 · Shaders From Zero · Season 3

Until now, the ray marched until it hit a surface, then we shaded that one point. The whole season has assumed the interesting thing happens AT the surface — the SDF, the normal, the material, the BRDF. The empty space between camera and surface was just travel time.

Volumetric effects — fog, clouds, god rays — break that assumption. There is no surface. The effect happens in the empty space the ray is currently traversing. The fix is conceptually simple: instead of shading one point at the hit, sample density along the ray and accumulate. The implementation gets expensive fast, but the first version is five lines.

0 fps
Volumetric raymarching
Surface lighting only. No atmosphere.

Distance fog — the cheapest version

The simplest volumetric effect, and the one you will use in 90% of real scenes: every surface fades into the background as a function of how far away it is. No raymarching of the medium, no per-pixel cost beyond a single exp.

float fogAmount = 1.0 - exp(-t * uFogDensity);
col = mix(col, fogColor, fogAmount);

t is the hit distance from the surface march. exp(-t * density) is the Beer-Lambert law — the fraction of light that survives traveling distance t through a medium of constant density. It's physically motivated and looks great. uFogDensity = 0.05 is a reasonable starting point; 0.2 is heavy fog; 0.01 is a hazy day.

Notice this costs nothing per pixel beyond the surface shading you already did. t falls out of the surface march for free.

Height-based fog

Constant-density fog is boring — real atmosphere is thicker near the ground and thins out as you go up. Two exponentials, still cheap:

float h = hitP.y;
float fogDensity = exp(-h * 0.4);            // thicker low, thinner high
float fogAmount  = 1.0 - exp(-t * fogDensity * 0.1);
col = mix(col, fogColor, fogAmount);

The first exp attenuates density with altitude. The second is Beer-Lambert along the ray, using that altitude-modulated density. It's not physically rigorous — a proper integral would walk the ray and accumulate height-varying density at each point — but it sells the "morning mist over a field" look for one extra exp per pixel.

If you need rigor, raymarch it. Most of the time you don't.

Volumetric clouds — raymarching through density

Now the proper approach. At each step along the ray, sample a 3D density field and accumulate. The medium is no longer a function of distance — it's a function of position in space, which means you have to actually visit each point.

float density(vec3 p) {
  // 3D FBM from Ep 05 — placeholder, swap in your own
  return fbm3(p * 0.5 + uTime * 0.05) - 0.3;   // bias to mostly empty
}

vec4 marchVolume(vec3 ro, vec3 rd, float tMax) {
  float t = 0.0;
  vec4 accum = vec4(0.0);              // rgb = light, a = total opacity
  for (int i = 0; i < 32; i++) {
    if (t > tMax) break;
    vec3 p = ro + rd * t;
    float d = max(density(p), 0.0);
    if (d > 0.001) {
      vec3 lit = vec3(1.0) * d;        // simplification — white per unit density
      accum.rgb += (1.0 - accum.a) * lit * 0.15;
      accum.a   += (1.0 - accum.a) * d   * 0.15;
    }
    t += 0.2;                          // fixed step size for density
  }
  return accum;
}

Two things to understand here.

Fixed step size. The surface raymarch used sphere tracing: the SDF told us the maximum safe step. For a density field there is no SDF — every point in space has some density value, and we have to sample at a regular cadence. Pick a step size that's fine enough to capture the detail of your noise but coarse enough to stay fast. 0.2 with 32 samples covers 6.4 units of depth, which matches the scene scale here.

Front-to-back compositing. Each step's contribution is weighted by (1.0 - accum.a) — the transmittance left from prior steps. Once accum.a reaches 1, every later step contributes 0, which is correct: a fully opaque cloud in front blocks everything behind it. Forget this multiplier and your fog will keep brightening past white, which looks like a bug because it is one.

Cost: 32 extra samples per pixel, on top of the surface march. That's the same as raymarching a small scene twice. Volumetrics are expensive — there is no free lunch here, only optimization.

God rays (volumetric light shafts)

Imagine a beam of light passing through a particle-rich medium — dust, smoke, fog. The light scatters off the particles toward the eye, and you see the beam itself, not just what it illuminates. Crepuscular rays, sunlight through tree canopy, that cone of dust in an old attic.

The detail-correct version raymarches the volume AND samples shadow rays at each step to ask "is this point in shadow?". If it's lit, add the light's contribution; if not, skip. Expensive — you're now nesting one raymarch inside another.

for (int i = 0; i < 32; i++) {
  vec3 p = ro + rd * t;
  // shadow ray from p toward light — if NOT in shadow, p receives light
  float visibility = shadowMarch(p, lightDir);
  accum += visibility * lightColor * 0.05;
  t += 0.3;
}

The stylized version skips the shadow ray entirely and just samples noise that's aligned with the light direction, multiplied by the light color. It's not physically right, but it reads as "shafts of light through atmosphere" in one tenth the cost. We use the stylized version below.

Common pitfalls

  • Fixed step size too large. You'll see banding — visible slabs in the fog where each sample lands. Either reduce step size or jitter the start position per pixel to dither out the artifact.
  • Fixed step too small. 60× slower with no visible improvement. The detail in the noise already smooths between samples.
  • Forgot to clamp density to 0. Negative density makes alpha decrease, which is physically nonsense and breaks front-to-back compositing. Always max(d, 0.0).
  • Forgot the (1.0 - alpha) weight. Fog past opacity 1 keeps contributing color, your scene goes white, you blame the noise function. The bug is the missing multiplier.
  • God rays without light visibility modulation. If every point in the volume gets the same brightness, it's not a "shaft" — it's a uniform glow. The shaft comes from the spatial variation in how much light reaches each point.

Exercises

  1. Vary fog color by altitude: mix(groundFog, skyFog, smoothstep(0.0, 4.0, hitP.y)). Warm brown near the ground, cool blue toward the sky.
  2. Animate the density field with uTime in the noise input. Slow drift looks like clouds; fast motion looks like fire.
  3. Combine height fog (cheap) with volume noise (expensive) — the height fog handles bulk atmosphere, the noise adds local cloud structure. Cheapest route to a believable sky.

What's next

Episode 24 — the season finale. A complete scene that composes every technique from this season: SDF library, normals, soft shadows, AO, materials, volumetrics. One fragment shader, one full scene.