Shaders From Zero · Episode 21
Reflections
Reflections is Episode 21 of Shaders From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Once you have a working raymarcher with lighting and shadows, the next visual leap is reflections. Real surfaces reflect their environment. In a raymarcher, "the environment" is whatever else the SDF describes — so reflections are essentially "do another raymarch from the surface, in the reflected direction."
That's the whole episode in one sentence. The rest is plumbing: refactor the march loop so we can call it twice, blend the second result into the first, and optionally repeat for multi-bounce or jitter the normal for rough surfaces. This is the single most cinematic-looking thing you can add to a raymarcher.
Factoring out the marcher
So far each stage has had its own raymarch loop pasted into main.
For reflections we need to call the marcher twice (or more) per
pixel — once for the camera ray, once for the bounce ray. Copy-pasting the loop
is unacceptable. Refactor it into a function:
bool march(vec3 ro, vec3 rd, out float t, out vec3 hitP) {
t = 0.0;
for (int i = 0; i < 100; i++) {
hitP = ro + rd * t;
float d = sceneSDF(hitP);
if (d < 0.001) return true;
if (t > 50.0) break;
t += d;
}
return false;
}
Same loop you've written four times by now. The out parameters
return both the travel distance and the hit point so the caller doesn't have to
recompute ro + rd * t. Now main becomes
march(ro, rd, t, hitP) and the bounce ray gets its own call with
different arguments. One source of truth.
The bounce
GLSL has a built-in reflect(I, N). Given the incoming ray
direction I and the surface normal N, it returns the
reflected direction — the mirror angle, with the component along N
flipped. Use it:
vec3 R = reflect(rd, N);
vec3 ro2 = hitP + N * 0.01; // step off the surface
float t2;
vec3 hitP2;
bool hit2 = march(ro2, R, t2, hitP2);
vec3 reflColor = hit2 ? shadeAtPoint(hitP2) : sky(R);
The N * 0.01 offset is the same trick we used for the shadow ray
in Episode 20. Without it, the bounce ray spawns on the surface itself —
sceneSDF(hitP) is approximately zero, so the loop reports a hit on
iteration one. Self-intersection. Always nudge off the surface along the normal
before any secondary ray.
Blending with the base color
Pure mirror: replace the base color with the reflection. That's a chrome ball. Most real materials aren't chrome. They reflect their environment more at glancing angles and less head-on — the classic Fresnel effect, the same trick we used for the hologram rim in Episode 09 and the glass in Episode 12.
float fresnel = pow(1.0 - max(dot(-rd, N), 0.0), 5.0);
vec3 col = mix(diffuseColor, reflColor, fresnel * 0.85 + 0.05);
dot(-rd, N) is the cosine of the angle between the view direction
and the surface normal. Zero at the silhouette (grazing), one straight on. The
1.0 - ... flips that so the value is large at the rim. The
pow(..., 5.0) is Schlick's approximation — a cheap match for the
real Fresnel curve. The * 0.85 + 0.05 clamps the mix range so the
surface always has a tiny bit of reflection (the 0.05 baseline) and
never goes fully mirror (capped at 0.9). Tune to taste.
Multi-bounce reflections
Real-world: a reflection of a reflection of a reflection. Mirror facing a
mirror. GLSL has no function recursion — you can't call
march from inside itself. The fix is to unroll the bounce loop
manually:
vec3 reflColor = sky(R);
if (march(ro2, R, t2, hitP2)) {
vec3 N2 = calcNormal(hitP2);
vec3 baseColor2 = shade(hitP2, N2);
vec3 R2 = reflect(R, N2);
vec3 ro3 = hitP2 + N2 * 0.01;
float t3; vec3 hitP3;
vec3 second = march(ro3, R2, t3, hitP3) ? shade(hitP3, calcNormal(hitP3)) : sky(R2);
reflColor = mix(baseColor2, second, 0.4);
}
Each bounce adds another march call — roughly doubles the
pixel cost. Two bounces is plenty for a stylized look. Four bounces is invisible
improvement on top of the cost. Real path tracers do hundreds, but they're not
running in a fragment shader at 60fps.
Roughness via normal jitter
Perfect mirror reflections look fake on anything that isn't actual chrome or water. Real surfaces have micro-scale bumps that scatter the reflected rays into a cone instead of a single direction. The cheap approximation: jitter the normal with hash noise before computing the reflection.
float h1 = hash(gl_FragCoord.xy);
float h2 = hash(gl_FragCoord.xy + 11.0);
float h3 = hash(gl_FragCoord.xy + 22.0);
vec3 jitter = (vec3(h1, h2, h3) - 0.5) * uRoughness;
vec3 Nj = normalize(N + jitter);
vec3 R = reflect(rd, Nj);
One jittered sample per pixel gives a noisy reflection — a frozen frame looks
like static. Under animation, the noise pattern shifts every frame and your eye
averages it into something that reads as roughness. For sharper, non-noisy
roughness, sample multiple jittered rays and average the results — but each extra
sample is another march call. The single-jitter trick is the budget
version.
Common pitfalls
- Self-intersection on the bounce ray. Forgot the
N * 0.01offset. The bounce ray immediately re-hits the surface it just left, returns black or a weird color. Always nudge off the surface. - Recursion not unrolled. GLSL doesn't allow function recursion — the shader fails to compile with an obscure linker error. Write a loop, or copy-paste the bounce block N times.
- Reflection budget too high. 4+ bounces is invisible improvement and doubles cost per bounce. Two is plenty.
- Roughness jitter without temporal accumulation. A single frame looks like static rather than rough surface. The illusion only works under animation, where successive frames average out.
- Full mirror on a diffuse-looking material. A clay-red sphere that perfectly reflects looks like chrome plastic, not clay. Always use Fresnel-weighted mix unless you specifically want chrome.
- Sky function returns black. When the bounce ray misses, it samples the sky — and if the sky is solid black, your reflection looks like a smudge. Give it at least a gradient.
Exercises
- Add a small metallic sphere next to the main one. Both reflective. The big sphere reflects the small one, the small one reflects the big one.
- Make the floor reflective with low fresnel and lots of roughness. Wet asphalt look. (Use a material ID to distinguish floor from sphere — peek ahead at Episode 22.)
- Add a colorful sky using the IQ palette
(
0.5 + 0.5*cos(6.28*(t + vec3(0,0.33,0.67)))). The reflection will pick up the sky colors and look vivid even with no other geometry.
What's next
Episode 22 — Materials. Per-SDF material IDs, so different parts of the scene can have different colors, reflectivity, and shading behavior. The current "everything is one material" assumption ends.