TExcelTAD

Shadows

Shadows anchor objects to the ground and tell the player where things are: a jumping character without a shadow seems to float, and it is hard to judge where it will land. Three.js uses shadow maps: each shadow-casting light renders the scene's depth from its own point of view into a texture, and lit materials compare against that texture to decide whether a pixel is in shadow. That means one extra render of the scene per shadow-casting light (six for a point light), so shadows are one of the biggest costs in a scene.

Four switches

Shadows are off by default and need to be enabled in four places:

js
renderer.shadowMap.enabled = true;     // 1. the renderer
sun.castShadow = true;                 // 2. the light
player.castShadow = true;              // 3. objects that throw shadows
ground.receiveShadow = true;           // 4. objects that show them

An object can do both (castShadow and receiveShadow), for example a wall that shades the floor and receives the shadow of a tree. For a loaded model, set the flags on every mesh with model.traverse((o) => { if (o.isMesh) o.castShadow = o.receiveShadow = true; }).

The shadow camera

A directional light's shadow is rendered by an orthographic camera stored in light.shadow.camera, by default a 10 × 10 box (left −5 … right 5, bottom −5 … top 5). Anything outside that box casts no shadow, and the shadow map's pixels (light.shadow.mapSize, 512 × 512 by default) are spread over it. This gives the central trade-off:

  • Box too small: shadows are cut off at its edges.
  • Box too big: each shadow-map pixel covers a large area, so shadows are blocky.

This model shows how many world centimetres one shadow-map texel covers for a few combinations:

js · try it yourself
// Size of one shadow-map texel on the ground for a directional light's shadow box.
for (const boxSize of [10, 40, 200]) {
  const cells = [512, 1024, 2048].map((mapSize) => {
    const cm = (boxSize / mapSize) * 100;
    return `${mapSize}: ${cm.toFixed(1).padStart(5)} cm`;
  });
  console.log(`box ${String(boxSize).padStart(3)} m  ->  ${cells.join('   ')}`);
}
box  10 m  ->  512:   2.0 cm   1024:   1.0 cm   2048:   0.5 cm
box  40 m  ->  512:   7.8 cm   1024:   3.9 cm   2048:   2.0 cm
box 200 m  ->  512:  39.1 cm   1024:  19.5 cm   2048:   9.8 cm

A 200 m box with a 2048 map still gives 10 cm texels, too coarse for a character's shadow. So games keep the box small and move it with the player: put the light and its target at a fixed offset from the player every frame, and the box travels along. Large engines go further with cascaded shadow maps (several boxes of increasing size); Three.js has a CSM addon for that.

Seeing and tuning the shadow

Use a CameraHelper on light.shadow.camera to see the box. In this scene the yellow lines are the shadow camera; the sun and its box follow the hopping character, so its shadow stays sharp anywhere on the large floor. The buttons change the map size and the bias:

html · try it yourself
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block }
#ui { position: fixed; left: 8px; top: 8px; display: flex; gap: 4px; flex-wrap: wrap }
button { font: 12px system-ui, sans-serif }</style>
<div id="ui"><button id="size">mapSize 1024</button><button id="bias">bias: tuned</button><button id="helper">helper: on</button></div>
<script type="module">
import * as THREE from 'three';

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;              // PCFShadowMap is the default type
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#9fc4e8');
const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 200);
addEventListener('resize', () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(innerWidth, innerHeight);
});

scene.add(new THREE.HemisphereLight('#dbe9ff', '#5a4a3a', 1.2));
const sun = new THREE.DirectionalLight('#fff5e0', 2.5);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
const box = 6;                                  // a 12 x 12 m shadow box around the player
Object.assign(sun.shadow.camera, { left: -box, right: box, top: box, bottom: -box, near: 1, far: 40 });
sun.shadow.bias = -0.0005;                      // fights "shadow acne" on surfaces facing the light
sun.shadow.normalBias = 0.02;                   // pushes the lookup along the normal (curved surfaces)
sun.shadow.radius = 3;                          // softens PCF shadow edges
scene.add(sun, sun.target);
const helper = new THREE.CameraHelper(sun.shadow.camera);
scene.add(helper);

const ground = new THREE.Mesh(new THREE.PlaneGeometry(80, 80), new THREE.MeshStandardMaterial({ color: '#7fae6a' }));
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
const pillarMat = new THREE.MeshStandardMaterial({ color: '#c9bca8' });
for (let i = 0; i < 16; i++) {
  const p = new THREE.Mesh(new THREE.CylinderGeometry(0.3, 0.3, 2 + (i % 3), 16), pillarMat);
  const a = (i / 16) * Math.PI * 2;
  p.position.set(Math.cos(a) * 9, (2 + (i % 3)) / 2, Math.sin(a) * 9);
  p.castShadow = p.receiveShadow = true;
  scene.add(p);
}
const hero = new THREE.Mesh(new THREE.CapsuleGeometry(0.35, 0.7, 4, 16), new THREE.MeshStandardMaterial({ color: '#ff7043' }));
hero.castShadow = true;
scene.add(hero);

const offset = new THREE.Vector3(-6, 12, 5);    // sun direction relative to the player
const btn = (id, fn) => { document.getElementById(id).onclick = (e) => fn(e.target); };
btn('size', (b) => {
  const s = sun.shadow.mapSize.x === 1024 ? 256 : 1024;
  sun.shadow.mapSize.set(s, s);
  sun.shadow.map?.dispose();                    // the shadow map is recreated at the new size
  sun.shadow.map = null;
  b.textContent = `mapSize ${s}`;
});
btn('bias', (b) => {
  const tuned = sun.shadow.normalBias !== 0;
  sun.shadow.bias = tuned ? 0 : -0.0005;
  sun.shadow.normalBias = tuned ? 0 : 0.02;
  b.textContent = `bias: ${tuned ? 'zero (acne!)' : 'tuned'}`;
});
btn('helper', (b) => { helper.visible = !helper.visible; b.textContent = `helper: ${helper.visible ? 'on' : 'off'}`; });

const timer = new THREE.Timer();
renderer.setAnimationLoop((t) => {
  timer.update(t);
  const time = Math.max(0, timer.getElapsed());
  hero.position.set(Math.cos(time * 0.4) * 6, 0.7 + Math.abs(Math.sin(time * 3)) * 1.2, Math.sin(time * 0.4) * 6);
  // Keep the shadow box centred on the hero: move the light and its target together.
  sun.target.position.copy(hero.position).setY(0);
  sun.position.copy(sun.target.position).add(offset);
  helper.update();
  camera.position.set(hero.position.x * 0.6 + 8, 9, hero.position.z * 0.6 + 12);
  camera.lookAt(hero.position.x * 0.6, 0, hero.position.z * 0.6);
  renderer.render(scene, camera);
});
</script>

Try bias: zero: the lit surfaces fill with stripes and dots, called shadow acne. Depth values from the shadow map and from the surface itself are nearly equal, so rounding makes the surface shadow itself. A small negative bias or a positive normalBias fixes it; too much makes shadows detach from their casters (peter-panning). Tune both by eye for your scene's scale. mapSize 256 shows what too few texels look like.

Shadow map types

renderer.shadowMap.type Look Cost
THREE.BasicShadowMap hard, aliased edges cheapest
THREE.PCFShadowMap (default) filtered edges; shadow.radius widens the softening moderate
THREE.VSMShadowMap soft, blurred (radius, blurSamples); can show light bleeding; all receivers also cast moderate–high

THREE.PCFSoftShadowMap is deprecated in r186: the WebGL renderer prints a warning and uses PCFShadowMap instead. Older tutorials use it everywhere; replace it with the default and set shadow.radius.

Shadows that don't move

If the light and the shadow casters are static (a level's buildings under a fixed sun), there is no need to re-render the shadow map every frame:

js
renderer.shadowMap.autoUpdate = false;
renderer.shadowMap.needsUpdate = true;   // render the shadow maps once (set again after changes)

That only works when nothing that casts a shadow moves. A common compromise: bake static shadows into the level's textures or a lightMap in Blender, and let only the characters cast real-time shadows on a small, player-centred box.

Shadows on mobile

  • Use one shadow-casting light (the sun). Avoid shadow-casting point lights: each renders the scene six times.
  • Keep mapSize at 1024 or lower and the box tight.
  • Let only important objects cast shadows: characters, large props. Grass, debris and particles should not.
  • For characters on flat ground, a blob shadow (a dark, soft-edged circle texture on a plane under the feet, with depthWrite: false) costs almost nothing and reads well.

Test yourself

Shadows appear only near the world origin and are cut off further away. What should you adjust?

  1. renderer.shadowMap.type
  2. The shadow camera's box (left/right/top/bottom) or move it with the player
  3. shadow.bias
  4. castShadow on the ground

Lit surfaces show stripes and speckles of self-shadowing. What is this, and what fixes it?

  1. Z-fighting; increase camera.near
  2. Shadow acne; adjust shadow.bias / shadow.normalBias
  3. Aliasing; enable antialias
  4. Peter-panning; reduce the map size

Why are shadow-casting point lights particularly expensive?

  1. They use VSM
  2. They render the scene into six shadow maps, one per cube face
  3. They can't use PCF
  4. They disable frustum culling