Shaders From Zero · Episode 19

Lighting & Normals

Lighting & Normals is Episode 19 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 19 · Shaders From Zero · Season 3

Until this episode our spheres were flat oranges. Round-edged silhouettes, yes — depth-tinted, sure — but completely lacking the thing that makes 3D look 3D: shading. A sphere lit from one side should be bright on that side and dark on the other. Ours has been uniformly orange. That ends now.

Lighting requires normals — for every surface point, a unit vector pointing away from the surface, telling us which way the surface faces. With a mesh, vertex normals come baked into the geometry buffer and the GPU interpolates them across triangles. Raymarchers have no triangles, no buffers, no baked normals. What we have is the SDF — and the SDF is enough. The normal at a point is the direction the SDF grows fastest. Approximate that gradient with a few extra SDF samples and you have your normal. Then standard Lambert shading works, and the sphere becomes a sphere.

0 fps
SDF gradient · Lambert
Same as Ep 17 final — depth color, no real lighting.

Normals from the SDF gradient

The normal at a point on a surface is the direction the SDF grows fastest. In math terms: the gradient of the SDF, normalized. In code: sample the SDF at a few offset points around p, take a weighted sum of the offset directions, and normalize. The classic four-tap version (cheap, accurate enough for most scenes):

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

Read it slowly. k.xyy is vec3(1, -1, -1), k.yyx is vec3(-1, -1, 1), k.yxy is vec3(-1, 1, -1), k.xxx is vec3(1, 1, 1). Four offset directions — the four vertices of a tetrahedron centered on p. Each sample contributes its own offset direction, scaled by the SDF value at that offset point. The sum is the gradient direction in disguise; normalize makes it a unit vector.

Cost: four extra SDF evaluations per hit pixel. That sounds expensive, but you're already doing 30-60 SDF evaluations per ray in the march itself. Four more on hit is a rounding error.

Lambert diffuse

Once you have a normal N and a light direction L, the classic diffuse term is one line:

vec3 L = normalize(uLightDir);
float diff = max(dot(N, L), 0.0);

The dot product is 1.0 when the surface faces directly at the light (full brightness), 0.0 at 90 degrees (terminator — the boundary between lit and unlit), and negative on the far side. The max(..., 0.0) clamps that negative region to zero — surfaces facing away get no diffuse contribution at all, which is physically what happens.

That's Lambertian reflectance. It's been the foundation of computer graphics lighting since the 1970s and it's still the first thing every real-time shader computes. Forget all the PBR-this and ACES-that for a moment — Lambert is where the 3D illusion starts.

Adding ambient

Pure Lambert has a problem: the shadow side is black. Pure black. In the real world, the shadow side of an object still receives light bouncing off nearby surfaces — the sky, the ground, the wall behind it. Ignore that and your render looks broken, like a cutout.

The cheapest fix in graphics: ambient light. A flat scalar added to the diffuse term, simulating omnidirectional bounce light:

float ambient = 0.15;
vec3 col = uBaseColor * (ambient + diff);

Set ambient too low (0.0) and shadows are voids. Too high (0.5) and the scene looks flat — there's no contrast left. 0.1 to 0.2 is usually right. We'll use 0.15 in Stage 4.

Key + fill lighting

Real-world lighting setups don't use one light. Even the bluntest cinematic scene has at least two — a key light that defines the form and a fill light that lifts the shadow side without erasing it. Add a backlight and you have three-point lighting, the basis of every studio portrait ever shot.

For our raymarcher, two directional lights are enough to look great:

vec3 keyL  = normalize(vec3(0.5, 0.8, 0.3));     // key from upper right
vec3 fillL = normalize(vec3(-0.7, 0.4, -0.5));   // fill from lower left
vec3 keyCol  = vec3(1.0, 0.9, 0.7);              // warm
vec3 fillCol = vec3(0.4, 0.5, 0.7);              // cool
float keyDiff  = max(dot(N, keyL),  0.0);
float fillDiff = max(dot(N, fillL), 0.0);
vec3 col = uBaseColor * (0.1 + keyDiff * keyCol + fillDiff * fillCol * 0.4);

The lights point from roughly opposite directions. The key is warm and at full strength; the fill is cool, weaker (* 0.4), and on the opposite side so it lifts the shadow without competing with the key. The warm/cool split is the cheapest cinematography trick there is — the eye reads it as "lit from outside" even on a featureless sphere.

That's basically every studio portrait, every Pixar key shot, every video-game promo render, in twelve lines of GLSL.

Common pitfalls

  • Forgot to normalize(N) after the gradient. The four samples don't naturally produce a unit vector — they produce something proportional to the gradient. Without normalization the dot product has wrong magnitudes and the diffuse term scales weirdly across the surface.
  • h too small (e.g. 0.00001). Floating-point precision starts breaking down. The four sample SDF values are almost identical, the subtraction produces noise, and your normals get jittery. A noisy normal under Lambert looks like sandpaper.
  • h too large (e.g. 0.01). You're sampling the SDF too far from p, so the gradient is computed over a wide neighborhood and high-frequency surface detail gets averaged out. The sphere still looks fine but a bumpy SDF will look smooth.
  • Light direction not normalized. dot(N, L) assumes L is a unit vector. If you forget normalize, the diffuse term scales by length(L) and the whole scene gets brighter or darker for no apparent reason.
  • Forgot ambient. The shadow side is pure black, which reads as a hole punched in the scene rather than an unlit region. Even 0.05 ambient fixes it.
  • Used dot(N, L) not max(dot(N, L), 0.0). Surfaces facing away from the light get a NEGATIVE diffuse contribution. Subtract that from the base color and you get either negative components (clamped to zero eventually, but going through black on the way) or weird inverted shading that looks like X-ray vision.

Exercises

  1. Make the key light orbit the scene by tying it to uTime: vec3 keyL = normalize(vec3(cos(uTime), 0.7, sin(uTime)));. Watch the terminator slide across the sphere.
  2. Switch the four-tap normal to a six-tap central difference: sample p ± h along each axis separately, subtract pairs, normalize. Slightly more accurate, twice the SDF evaluations. Compare side by side.
  3. Color the normals directly: col = N * 0.5 + 0.5;. This is the "matcap debug" look — the same trick Blender's Solid view uses. Useful for visually checking your normals are correct before adding lighting on top.

What's next

Episode 20 — Shadows. Hard shadow rays are a straight extension of what we just built — march a second ray from the surface point toward the light and see if anything blocks it. Then Iñigo Quílez's soft-shadow trick turns those hard, jagged edges into beautiful penumbras using nothing but the closest-approach distance along the shadow ray.