Drawing

Shadows of spot and point lights

A spot light and a point light sit at one point and shine outward. Their shadow maps are drawn by a perspective camera at the light: one camera along the cone for a spot light, six cameras in a cube for a point light. This page explains the cone, the cube map and how a direction picks its face, why the cube's cameras are mirrored, and why the bias must grow with distance. It builds on Shadow mapping. The last part shows how RASM does it.

In short

  • Rays leave the light from one point, so the light's camera is a perspective camera at the light, not an orthographic box.
  • A spot light has a cone: full light inside the inner angle, a smooth fade to 0 at the outer angle. Its shadow is one square map along the cone's axis, with a field of view of 2 × the outer angle.
  • A point light shines everywhere. Its shadow is a cube map: 6 faces, each a 90° view. A direction belongs to the face of its biggest axis, and the depth to compare is the distance along that axis.
  • The cube faces' cameras are mirrored, so the face passes swap back-face and front-face culling.
  • In a perspective map a texel gets bigger with distance, so the bias grows with distance too.

1The problem: rays from one point

The sun is far away, so its rays are parallel and an orthographic box fits them. A lamp is close. Its rays fan out from one point, so the camera that draws its shadow map must fan out the same way.

light rays the shadow map's camera in shadow
Sun: parallel rays orthographic box texels: the same size near and far Spot or point light: rays from one point near plane perspective texels: bigger far from the light
The test is the same as for the sun (Shadow mapping, section 4): move the point into the light's clip space, divide by w, read the map, compare. Only the camera changes. With a perspective camera, w is the depth from the light, not 1.

Directional (sun)

Orthographic boxes along the light, often several cascades.

1 to 4 maps

one map

Spot

One perspective map along the cone's axis (sections 2 and 3).

1 map

6 faces, 90° each

Point

A cube map: six perspective maps of 90°, one per face (sections 4 to 6).

6 maps in one cube

2The spot light's cone

A spot light shines inside a cone around its direction. Two angles, measured from the axis, shape it: inside the inner angle the light is full; between inner and outer it fades; outside the outer angle there is no light.

outer inner full light fade fade no light no light The light, by angle from the axis 1 0 inner 18° outer 30° angle → cone cone²
The dashed curve is the cone factor. The light is multiplied by its square (the thick curve), which starts and ends the fade more softly. The factor uses the cosine of the angle, so the shader needs no acos.

The rule is the one of the glTF lights extension (KHR_lights_punctual). Two numbers per light, worked out once on the CPU, turn the cosine into the cone factor:

cone = saturate(cos θ · scale + offset)

scale = 1 / max(cos(inner) − cos(outer), 0.001)

offset = −cos(outer) · scale

light = color · intensity · cone² / distance²

cos θ
dot(light direction, −l): the cosine of the angle between the axis and the ray to the point
saturate
clamp to 0..1: 1 at cos(inner), 0 at cos(outer)
0.001
keeps the division finite when inner and outer are equal: the fade becomes a hard edge
distance²
the usual inverse-square falloff of a light at a point, often with a smooth window that ends at the light's range

3The spot light's shadow map

A spot light needs only one map. Its camera sits at the light and looks along the axis. The field of view is 2 × the outer angle, so the cone just fits. The map is square, so the cone is the circle inside the square.

near field of view = 2 × outer one perspective map along the axis outside the map: no shadow test seen from the light full light fade map the cone is the circle inside the square map corners: in the map, but no light
The corners hold about a fifth of the texels and get no light, so they are wasted. That is the price of a square texture for a round cone. A point outside the map has no shadow information; with a field of view of 2 × outer, every such point is outside the cone and gets no light anyway.

Try the cone and its map. The light is at the top and shines down. Drag the point P, and change the two angles.

the cone: full, then fading the map's width at P's depth
Move P from the axis to the cone's edge and watch cone² fall. Then open the outer angle wide: the map's width at P grows quickly, and so does one texel. Set inner above outer to see the fade disappear.

4The point light's cube map

A point light shines in all directions. No single perspective camera sees everything: a field of view must stay well below 180°. Six cameras of 90° do it, one along each axis: +X, −X, +Y, −Y, +Z, −Z. Their images are the six faces of a cube map, one texture with six square layers.

+Ylayer 2s: +x · t: +z −Xlayer 1s: +z · t: −y +Zlayer 4s: +x · t: −y +Xlayer 0s: −z · t: −y −Zlayer 5s: −x · t: −y −Ylayer 3s: +x · t: −z Every face, as a texture s t (0, 0) (1, 1) s grows right, t grows down "s: −z" means: s grows toward −z. The marked edge: +Z's right side is +X's left side. In this cross, every edge between two drawn faces joins with no jump.
The layers follow the GPU's order: +X, −X, +Y, −Y, +Z, −Z are layers 0 to 5. Which way s and t run on each face is fixed by the API, not chosen by the engine (next table).

The GPU reads a cube map with a direction r, not with texture coordinates. Vulkan's cube map face table says which face and which texel a direction falls on. ma is the biggest of r's three parts, the major axis:

Biggest partFaceLayersctcma
|rx|, rx > 0+X0−rz−ryrx
|rx|, rx < 0−X1+rz−ryrx
|ry|, ry > 0+Y2+rx+rzry
|ry|, ry < 0−Y3+rx−rzry
|rz|, rz > 0+Z4+rx−ryrz
|rz|, rz < 0−Z5−rx−ryrz
s = (sc / |ma| + 1) / 2     0 at the left edge, 1 at the right edge
t = (tc / |ma| + 1) / 2     0 at the top row, 1 at the bottom row

5Reading the cube: face and depth

To test a point P, take the vector from the light, d = P − light. Its biggest part picks the face. The 90° faces meet at the cube's diagonals, so the face is the one whose axis is nearest to d.

P depth 3 |d| = 3.33 +X −X −Z +Z x z Look up P = light + (3, 0.4, −1.4) |d.x| = 3 · |d.y| = 0.4 · |d.z| = 1.4 biggest: x, and d.x > 0 → face +X depth along +X = |d.x| = 3 not the length |d| = 3.33 s = (−d.z / 3 + 1) / 2 = 0.733 t = (−d.y / 3 + 1) / 2 = 0.433 The top view hides d.y = 0.4: it points out of the page. +Y and −Y sit above and below the light.
Each face's projection maps view depth, the distance along the face's axis, to the stored depth. So the value to compare is |d.x| on the +X face, not the length of d.
P |d| = 3.13 stored: 3 wall

Compare the distance |d|

3.13 > 3: P seems behind the wall itself and shadows itself. The error grows toward the face's edges, up to √3 at the corners.

P depth along the axis: 3 stored: 3 wall

Compare the depth along the axis

3 = 3: P is the first surface, so it is lit, like every other point of the wall.

Another way: store the distance

Some engines write the distance |d| into the faces from a fragment shader, and compare |d| when reading. That works too. The two sides must only agree. Storing the depth the hardware writes needs no fragment shader in the shadow pass.

Try it. The picture is the slice through the light at its height, seen from above. Drag P, and move it up or down with the height slider: when |d.y| is the biggest, P falls on the +Y or −Y face.

the face that holds P, and its depth the light the face's image
Drag P across a diagonal: the face changes where two parts of d are equal. Put P near a face's corner and compare the depth with |d|. Then make the map smaller and move P away from the light: the texel at P grows.

6Drawing a face: a mirrored camera

To draw a face so that the lookup above finds each depth, the face's camera must put texel (s, t) where the table expects it. So the camera looks along the face's axis F, its image's right is S (where s grows), and its image's up is −T (t grows down). That camera is not a normal one:

A normal camera right up back (toward you) right × up = back det = +1 A cube face's camera S (s grows) −T (t grows down) F (away) S × (−T) = F det = −1 mirrored
A view matrix's rows are the camera's right, up and back axes. For a normal camera, right × up = back, so the determinant is +1. For a face, the rows are S, −T, −F, and S × (−T) = +F: the determinant is −1. The cube map table is left-handed, so every face's camera is.
+X face:  F = (1, 0, 0)   S = (0, 0, −1)   T = (0, −1, 0)
rows:     S = (0, 0, −1)   −T = (0, 1, 0)   −F = (−1, 0, 0)
det = (S × −T) · (−F) = (1, 0, 0) · (−1, 0, 0) = −1

A mirror reverses the winding of every triangle on screen (Face culling, section 5). Through a face's camera, the triangles that face the light turn clockwise and look like back faces. The fix is cheap: in a face's pass, swap the cull mode.

culled stored plane: culled

Cull back faces, as usual

The side toward the light is culled. The map holds the far side of closed objects, and open meshes (a plane, a leaf) cast no shadow.

stored plane: stored

Swap the cull mode

Cull the faces the GPU calls front: through the mirror, they are the real back faces. The faces toward the light are drawn, as in every other view.

Find the mirror from the matrix

Do not keep a list of mirrored views by hand. A view is mirrored when the determinant of its 3×3 part is negative. Test that once per view, and swap the culling when it is.

7The bias grows with distance

The fixes for shadow acne (Shadow mapping, section 5) are best measured in texels. In an orthographic map, a texel has the same size everywhere. In a perspective map it does not: the texels' rays fan out, so one texel covers more of the world the farther it is from the light.

Perspective: texels grow near: small texel, small offset far: big texel, bigger offset Orthographic: one texel size the same offset near and far
The short thick lines are the offsets: about one texel. A fixed offset that is right near the light is too small far away (acne), and one that is right far away is too big near the light (peter-panning).

So compute the texel's size at the point being shaded:

texel ≈ 2 · depth · tan(fov / 2) / size

cube face (fov = 90°, tan 45° = 1): texel = 2 · depth / size

from the matrix: texel = 2 · w / (|row 0 of M| · size)

depth
the point's distance from the light along the map's axis
fov
the map's field of view; size its width in texels
M
the light's view-projection matrix. The length of its first row is the projection's x scale: 1 / tan(fov / 2) for a square perspective map, 2 / box width for an orthographic one
w
the point's clip-space w: 1 in an orthographic map, the depth from the light in a perspective one. So the last line is right for both kinds

Then the lookup point leaves the surface by about one texel, in two directions:

p' = p + n · texel · (1 + 2 · (1 − n·l)) + l · texel

n · texel · …
along the normal: 1 texel where the surface faces the light, up to 3 where the light grazes it
l · texel
toward the light: 1 texel

Both terms use the texel at p, so a far point moves more than a near one. For a cube, depth is the biggest part of d, the depth on the point's face.

8Soft edges across faces

PCF (Shadow mapping, section 6) reads a block of texels around the lookup. Near a face's edge, part of that block is on the next face. A cube map handles this by itself when it is read with directions: GPUs sample cube maps seamlessly, so a filter at a face's edge reads the neighbour face's texels. Those texels hold the depth along the neighbour's axis, so each part of the filter compares with the point's depth along the axis of the face it reads. Near the edge the two depths are almost equal, but not quite, and comparing with the wrong one gives a thin line of light or acne along the cube's edges.

clamped: copies of the edge column

Each face as a 2D image

The block stops at the face's edge. The result jumps there: a seam along every cube edge.

face +Z face +X

Read through the cube

Turn each gather's texel corner back into a direction and sample the cube: the block crosses the edge with no seam.

9Cost: renders per light

Each map is one more render of the scene's depth. A point light is the most expensive light to shadow.

4

Sun, 4 cascades

One orthographic render per cascade.

4 renders

1

Spot light

One perspective render along the cone.

1 render

6

Point light

One 90° render per face.

6 renders

Six renders do not mean six times the triangles. Each face is culled with its own 90° frustum, so an object is drawn only by the faces that see it: most objects fall in one or two faces. What does add up six times is the fixed cost of a view: its culling pass, its draw calls and its barriers.

Way to make it cheaperIdea
One pass for all facesCull once against all six frusta and draw into the six layers in one pass (layered rendering or multiview).
Smaller maps for far lightsA light that covers few pixels on screen needs fewer texels.
Update less oftenWhen nothing near a light moves, last frame's cube is still right.
Skip facesA light on a wall or a ceiling has faces that see only the wall.

10Worked example

A point light with a 1024 × 1024 cube, and a point P at d = (3, 0.4, −1.4) from it:

+Xthe face, layer 0|d.x| = 3 is the biggest
3the depth to compare|d.x|, not |d| = 3.33
(750, 443)the texel: s = 0.733, t = 0.433s · 1024, t · 1024
0.0059world units per texel at P2 · 3 / 1024

So the normal offset moves the lookup by 0.006 units where the surface faces the light, and up to 0.018 where the light grazes it.

A spot light with an inner angle of 14°, an outer angle of 22° and a 2048 × 2048 map, and a point 18° off the axis, 10 units along it:

23.2, −21.5scale and offset1 / (cos 14° − cos 22°)
0.31of the light reaches the pointcone = 0.55, squared
44°the map's field of view2 × 22°
0.0039world units per texel at the point2 · 10 · tan 22° / 2048

With an outer angle of 80°, the same texel is 14 times bigger: tan 80° / tan 22° = 14.

11Pitfalls

Acne that grows toward the cube's edges and corners
The lookup compares the distance |d| against a depth stored along the face's axis. |d| is up to √3 times larger at a corner. Compare the depth along the face's axis, or store distances.
A point light's shadows vanish, or objects shadow themselves
The faces' mirrored cameras were not handled: back-face culling removes the faces toward the light. Swap the cull mode when the view's determinant is negative.
Shadows are mirrored, or sit on the wrong side of the light
A face's camera does not match the cube map table, so a face is drawn turned or flipped. Build each camera from the table's S and T, and test every face against the table.
An object very close to the light casts no shadow
It is nearer than the near plane, so it is clipped away. Make the near plane small; reversed-Z keeps the depth precise down to it.
A very wide spot light has blurry, blocky shadows
A field of view near 180° spreads the map's texels thin: tan(fov / 2) grows without end. Limit the field of view, and accept that light outside the map is not shadowed; or use a cube for a very wide cone.
Acne far from the light, peter-panning near it
The offsets are fixed in world units. In a perspective map, compute them from the texel size at the point.
Seams along the cube's edges
The PCF reads each face as a 2D image. Read the cube with directions, so the GPU filters across faces.

12In RASM

RASM shadows spot and point lights with the same two calls as the sun. Renderer::addShadowPasses takes a ShadowDesc for any light and returns a SceneShadow; Renderer::addScenePasses takes up to MAX_VIEW_SHADOWS (4) of them, each of a different light. For a spot or point light, ShadowDesc::distance is the far plane, measured from the light, and the near plane is that distance / 200. Each map is drawn by a depth-only scene view, so it is culled on the GPU like any view, in ordinary render graph passes. examples/07_lights shows it: a weak moon with cascades, a spot lamp and a point lantern, with a spinning cube whose shadow moves. A View lists the same ShadowDescs in View::shadows; each view draws a spot map or a cube from its own camera, since the maps take that camera's LODs, so a cube costs six scene views per view that lists it (examples/22_c_api gives its main view the point light's cube).

const rasm::LightHandle lamp = engine.createLight(rasm::LightType::SPOT, glm::vec3(1.0f, 0.95f, 0.8f), lampPosition, lampDirection, 900.0f, 40.0f, glm::radians(14.0f), glm::radians(22.0f));
const rasm::LightHandle lantern = engine.createLight(rasm::LightType::POINT, glm::vec3(1.0f, 0.6f, 0.3f), lanternPosition, glm::vec3(0.0f), 25.0f, 14.0f);

const rasm::SceneShadow shadows[] = {
    engine.addShadowPasses(graph, scene, camera, rasm::ShadowDesc{.light = lamp, .size = 2048, .distance = 40.0f}),
    engine.addShadowPasses(graph, scene, camera, rasm::ShadowDesc{.light = lantern, .size = 1024, .distance = 14.0f}),
};
engine.addScenePasses(graph, scene, camera, sceneTarget, shadows, 2);

The cone angles are in radians. The outer angle's default is SPOT_OUTER_CONE_ANGLE (π/4, glTF's default), and Renderer::createLight rejects a spot light unless 0 ≤ inner < outer ≤ π/2.

the application graph passes textures shader steps
application · once, when building the graph createLight(SPOT, ..., inner, outer) createLight(POINT, ...) addShadowPasses(graph, scene, camera, {light, size, distance}) addScenePasses(graph, scene, camera, target, shadows, count) GPU · every frame, in graph order Spot i Cull 1, Spot i 1, … one view along the cone fov 2 × outer, at most 160° shadow_spot_<i> one 2D depth texture size × size Cube i Face 0 Cull, Cube i Face 0, … Face 5 six mirrored views frustum culling only shadow_cube_<i> 6 layers: one cube view, one 2D view per face later faces keep the others readDepth Cull, Scene (rasm.slang) SceneData::shadowMaps: matrix, texture, split shadowedLights: the light's row, firstMap, mapCount; the light table: spotScale, spotOffset a cube's matrix: the projection only shadePBR → sampleShadow, per shadowed light that reaches the pixel (shadow.slang) sampleShadow: by light type spot: sampleShadowMap matrix → uv, depth point: sampleShadowCube getCubeFace, depth on its axis offsetLookup, 4 gathers, getPcfWeights shadows[i] → shadePBR: light × cone² × shadow
The spot light's view uses occlusion culling when it is on (passes Spot 2 Cull 1, Spot 2 1, Spot 2 Hi-Z, Spot 2 Cull 2, Spot 2 2 for light 2: the passes, like the targets, name the light, so two spot or point lights can be told apart). A cube face's passes are Cube 3 Face 0 Cull and Cube 3 Face 0, up to face 5. The cube's faces are only frustum culled, because the Hi-Z build reads a 2D depth. The render graph clears each face in its first pass. The barrier of a cube covers all six layers, so only the cube's first pass of the frame may drop its old contents (AttachmentOps::firstWrite); the later face passes keep the faces already drawn.

Where RASM follows this page, and where it differs

PartThis pageRASM
ConeglTF's inner and outer angles, cone²The same. setSpotCone computes spotScale and spotOffset on the CPU every frame; shadePBR multiplies the light by cone², after the inverse square and the range window.
Spot mapone perspective map, fov 2 × outerOne depth-only render target shadow_spot_<light index>, ShadowDesc::size squared. getSpotShadowView (a world-space glm::dmat4, from the light's double position; each view moves it into its render space) and getSpotShadowProjection build its matrices; the field of view is clamped to at most 160° (MAX_SPOT_HALF_ANGLE), so light more than 80° off the axis is not shadowed.
Near planesmall, behind every casterdistance / 200 (NEAR_PART), with reversed-Z, like every RASM projection.
Cube6 faces in the API's orderOne cube render target shadow_cube_<light index>, made with RenderTargetDesc::cube. Its depth texture has TextureDesc::cube: CUBE_FACES (6) layers, a cube view for sampling and one 2D view per face for drawing. Each face's pass draws one face with PassBuilder::write(target, face).
Face camerasfrom the cube map tablegetCubeFaceView builds rows S, −T, −F from the tables CUBE_FORWARD, CUBE_S, CUBE_T; getCubeFaceProjection is the shared 90° projection. tests/localShadowsTests.cpp checks every face against Vulkan's table.
Mirrored facesswap the cull modeSceneView::mirrored is set when the view's 3×3 determinant is negative, and Renderer::drawSceneView swaps CullMode::BACK and CullMode::FRONT.
Depth comparedalong the face's axisThe depth the hardware writes. sampleShadowCube turns the depth on the face's axis into clip depth with the face projection, which is the map's matrix for a point light.
Biasabout one texel, from the texel size at the pointoffsetLookup: along the normal 1 to 3 texels, and 1 texel toward the light. sampleShadowMap takes the texel from 2 · w / (|row 0| · size), right for cascades and spot maps; sampleShadowCube from 2 · depth / size.
FilteringPCF through the cube, seamless3x3 PCF with bilinear weights as four 2x2 Gathers (getPcfWeights). For the cube, each gather's corner becomes a direction into gCubeTextures, a SamplerCube array on the same binding as gTextures, and each gather compares with the depth along the axis of the face it reads (getCubeFace of the corner, getCubeDepth).
Cost1 render per spot, 6 per point lightOne scene view per map: a sun with 4 cascades, a spot light, a point light and the shaded view take 12 of the MAX_SCENE_VIEWS (32). Drawing all faces in one view is D20 in docs/code_review.md.

Where it lives in code

WhatWhere
The APIRenderer::createLight in src/scene/light.cpp; SPOT_OUTER_CONE_ANGLE in include/rasm/light.h; ShadowDesc, SceneShadow, MAX_VIEW_SHADOWS, MAX_SCENE_VIEWS in include/rasm/scene.h; Renderer::addShadowPasses, Renderer::addScenePasses in src/renderer/gpuScene.cpp
The maps' matricesgetSpotShadowView, getSpotShadowProjection, getCubeFaceView, getCubeFaceProjection in src/renderer/localShadows.cpp; getShadowMaps in src/renderer/gpuScene.cpp
The views, mirrored cullingRenderer::createSceneView, Renderer::prepareSceneView, Renderer::drawSceneView in src/renderer/gpuScene.cpp; SceneView in src/renderer/gpuScene.h
Cube targets and texturesCUBE_FACES, TextureDesc, RenderTargetDesc, AttachmentOps in include/rasm/render/resource.h; the image and its views in src/rhi/vulkan/vulkanDevice.cpp
Drawing one face, keeping the othersPassBuilder::write in include/rasm/render/renderGraph.h; RenderGraph::assignAttachmentOps in src/renderer/renderGraph.cpp
GPU fieldsgfx::ShadowMap, gfx::Light, SceneData::shadowMaps in src/renderer/uberMaterialTypes.h and shaders/lib/core.slang
The lookupsampleShadow, sampleShadowMap, sampleShadowCube, offsetLookup, getPcfWeights in shaders/lib/shadow.slang; getCubeFace and the cube tables in shaders/lib/cubeMap.slang, which the environment bake shares; gCubeTextures and fragMain in shaders/passes/rasm.slang
The cone, applying the shadowshadePBR and PBRInfo::shadows in shaders/lib/pbr.slang
Teststests/localShadowsTests.cpp
An exampleexamples/07_lights/main.cpp
Keep these true
  • CUBE_FORWARD, CUBE_S and CUBE_T exist twice, in src/renderer/localShadows.cpp and shaders/lib/cubeMap.slang. They must stay equal and match Vulkan's cube map face table; tests/localShadowsTests.cpp checks the C++ side.
  • A mirrored view must swap its culling. SceneView::mirrored comes from the view matrix, so a new kind of view gets it for free; a pipeline that sets its own cull mode does not.
  • A cube render target is depth-only and square, with a fixed size. addScenePasses does not take one as its color target.
  • Only the cube's first pass of the frame may drop its contents (AttachmentOps::firstWrite). One barrier covers the whole cube, so the later face passes must keep the faces drawn before them.
  • A point light's gfx::ShadowMap holds only the faces' projection. The shader builds the face's view from the light's position, so it must use the same tables as getCubeFaceView.
  • Every index into gTextures and gCubeTextures comes from the scene data and is the same for every pixel of the draw.

Further reading