Drawing
Shadow mapping
A point is in shadow when something stands between it and the light. Shadow mapping answers that question with two passes: first draw the scene's depth as the light sees it, then, for each pixel the camera sees, compare its depth from the light with that stored depth. This page explains the idea, the math, the artifacts and their fixes. The last part shows how RASM does it.
In short
- Pass 1 draws the scene from the light into a depth-only texture, the shadow map. Each texel keeps the depth of the surface nearest the light.
- Pass 2 draws from the camera. For each pixel, it moves the surface point into the light's view and compares: farther than the stored depth means something is in front of it, so it is in shadow.
- A directional light (the sun) uses an orthographic light camera; a spot light a perspective one; a point light six of them (a cube).
- The map has a finite number of texels, so a surface can shadow itself: shadow acne. A small depth bias and a normal offset fix it.
- One comparison per pixel gives hard, jagged edges. PCF averages several comparisons for a soft edge.
1The question: can the light see this point?
Lighting math uses the direction to the light and the surface normal. That lights every point that faces the light, even one behind a wall. A shadow is a different question: is the path from the point to the light free?
2The idea: depth from the light
Draw the scene from the light and keep only depth. Each texel of that image, the shadow map, now holds the distance to the first surface the light hits in that direction. A point farther away than that number has something in front of it.
So shadow mapping is two passes over the same scene:
3The light's camera
The shadow pass needs a view and a projection, like any camera. The kind of light decides them.
Directional (sun)
Parallel rays from far away. An orthographic camera looking along the light. Its box must hold every object that can cast a shadow into the view.
1 map, or several cascades (section 7)
Spot
Rays from one point, inside a cone. A perspective camera at the light, with a field of view equal to the cone's angle.
1 map
Point
Rays from one point, in all directions. Six perspective cameras of 90° each, one per face of a cube around the light.
6 maps (a cube map)
For the orthographic camera, the size of the box is a design choice. The map has a fixed number of texels, and the box stretches them over the ground:
Too large
Each texel covers a lot of ground. Shadows are blocky and blurry.
Too small
Sharp shadows, but an object outside the box is not in the map, so it casts none.
Fitted
Just large enough for every caster and every receiver that the view can see.
The light camera's near plane must sit behind every caster. A caster between the light and the near plane is clipped away, and its shadow vanishes.
4The test, step by step
The light camera's projection times its view is one matrix, S. In pass 2, a fragment at world position p takes this path:
- pworld position of the fragment
- S · pinto the light's clip space
- ÷ wto NDC (w = 1 for orthographic)
- uv, dwhere to read the map; depth as the light sees it
- storedread the map at uv
- compared against stored
c = S · (p, 1) light clip space
ndc = c.xyz / c.w divide (w = 1 for orthographic)
uv = (ndc.x · 0.5 + 0.5, texture coordinates,
0.5 − ndc.y · 0.5) v = 0 at the top
d = ndc.z the fragment's depth as the light sees it
stored = shadowMap(uv) the nearest depth along that texel's ray
lit = d is not behind stored
standard depth: d ≤ stored reversed-Z: d ≥ stored
| Detail | What to know |
|---|---|
| The uv line | It assumes a Y-up clip space and textures with row 0 at the top. Other conventions flip v differently; the shadow pass and the lookup just have to agree. |
| Reversed-Z | With near = 1 and far = 0 (Projection and reversed-Z depth), a nearer surface has the larger depth, so the comparison flips. |
| Outside the map | A point with uv outside 0..1, or d outside the depth range, has no information. It is usually treated as lit. |
5Shadow acne, and the fixes
The map stores one depth per texel: the depth at the texel's center. A surface tilted toward the light changes depth inside one texel. Half of the surface under each texel is then "behind" the stored value and shadows itself, in stripes. That is shadow acne.
Try it. The picture below runs the real test for every point of the ground, against a small shadow map. Start with no bias, then raise it slowly.
Four fixes, often combined:
Constant depth bias
Compare against the stored depth moved by a small fixed amount toward the fragment.
Too much: peter-panning (below)
Slope-scaled bias
A bias that grows with the surface's slope as the light sees it. The rasterizer can add it while drawing the map.
Too much: the same, on steep surfaces only
Normal offset
Look up the map from a point pushed off the surface along its normal: about one texel, more where the light grazes.
Too much: shadows shift sideways; thin objects leak light
Draw back faces only
The shadow pass culls front faces, so the map holds the far side of closed objects, away from the lit surface.
Fails for: open meshes and thin walls
Bias is a balance. Too little leaves acne; too much moves the shadow away from the object that casts it:
Too little: acne
Stripes on surfaces that should be lit.
Right
No stripes, and the shadow starts at the object's foot.
Too much: peter-panning
The shadow detaches, and the object seems to float.
Both offsets are best set in texels, not in fixed world units. Then they stay right when the map's size or the light camera's box changes.
6Soft edges: percentage-closer filtering
One comparison gives 0 or 1, so each shadow-map texel becomes a hard square on screen, and the shadow's edge is a staircase. Blurring the depths does not help: the average of two depths is a depth no surface has. Percentage-closer filtering (PCF) blurs the results instead: compare against several texels around the point, and average the 0s and 1s.
One comparison
Each pixel is 0 or 1. The edge is a staircase of map texels.
PCF: average of several
A pixel near the edge gets a value between 0 and 1: the share of its neighbours that are lit.
How the average is built decides how smooth the edge is. A common kernel reads a 4x4 block and weights it so that it acts as a 3x3 filter that slides with the point:
A wider kernel gives a softer edge at more reads per pixel. Real penumbrae grow with the distance between the caster and the receiver; techniques like PCSS (percentage-closer soft shadows) estimate that distance first and widen the kernel to match.
7Resolution, coverage and cascades
A shadow-map texel covers box width / map size world units. Near the camera, one texel can cover many screen pixels: blocky shadows (perspective aliasing). Far away, many texels fall into one pixel and are wasted. Cascades fix this with several maps of the same size over boxes of different sizes.
| Variant | Idea | When |
|---|---|---|
| One map, fixed box | The box covers a known area (a level, a room, a small scene). | Small, bounded scenes; the simplest. |
| Box fitted to the view | Every frame, fit the box around the part of the camera's frustum that can receive shadows. Snap it to whole texels so edges do not crawl as the camera moves. | Medium scenes. |
| Cascaded shadow maps (CSM) | Split the camera's frustum by distance into 3 or 4 slices, each with its own map. The shader picks the cascade by the fragment's depth. | Large outdoor scenes; the standard for a sun. |
| Virtual shadow maps | One huge sparse map; only the pages that pixels need are drawn. | High-end engines. |
8Worked example
A sun shadow over a 28 × 28 unit area: an orthographic box from −14 to 14, near 0.1, far 60, and a 2048 × 2048 map.
9Pitfalls
- Stripes or moiré on lit surfaces
- Shadow acne: no bias, or a bias smaller than half a texel's depth change.
- Objects float; shadows start away from their feet
- Too much bias (peter-panning).
- A shadow is missing near the light
- The caster is in front of the light camera's near plane, or outside its box.
- Everything is in shadow, or nothing is
- The comparison has the wrong direction (reversed-Z flips it), or v is flipped between the passes.
- Shadow edges crawl when the camera moves
- A box fitted to the view but not snapped to whole texels.
- Blocky shadows close to the camera
- One map stretched over too large an area: shrink the box, raise the resolution, or use cascades.
- Reading the map gives garbage or validation errors
- The depth texture was not moved from attachment to sampled between the passes, or was not created sampleable.
10In RASM
RASM shadows a directional light with cascaded shadow maps: up to four maps, each fitted every frame to a slice of the camera's view. Spot and point lights have shadows too (Spot and point light shadows), and a shaded view reads up to MAX_VIEW_SHADOWS (4). This section shows a directional light's. addShadowPasses adds a depth-only scene view per cascade, and addScenePasses adds the shaded view that reads them. All are ordinary render graph passes, so the graph orders them and adds every barrier. examples/06_shadows shows it, followed by a post pass, with no barrier in the example. Without a graph of your own, list the shadows in the View: View::shadows and View::shadowCount make Renderer::render(views, count) add the same passes for each view, from its own camera (Multiple views).
Cascade and the cascade's number, so the GPU timers and the graph dump tell the views apart. A cascade's view picks each caster's LOD from the shaded view's camera and size, so a surface is shadowed by the same triangles it is drawn with (LOD selection).Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Lights | directional, spot, point | Each light can have a shadow: a view reads up to MAX_VIEW_SHADOWS (4), each named by its ShadowDesc::light. prepareSceneView puts each shadowed light's first map in gfx::Light::shadowMap. A directional light has cascades (this page and Cascaded shadow maps); a spot light one perspective map and a point light a cube (Spot and point light shadows). The ambient term is not shadowed. |
| Light camera | derived from the light, often fitted to the view | Derived: no light camera exists. fitShadowCascade builds each cascade's orthographic box along the light, around a slice of the camera's view, snapped to whole texels, every frame (Cascaded shadow maps). |
| Shadow map | a depth texture | One depth-only render target per cascade, made by addShadowPasses: ShadowDesc::size squared, D32_SFLOAT and no colorFormats. Its depth is always SAMPLED_DEPTH_ATTACHMENT and in the bindless set (NEAREST_CLAMP), even without occlusion culling. |
| Shadow pass | depth only | A scene view per cascade: the same culling, and the draws with depthPipeline (shaders/passes/shadow.slang: the vertex pulling of rasm.slang, through getVertex and getWorldMatrix, so animated, skinned and morphed meshes cast the shadow of their pose this frame, and an empty fragMain); cut-out and see-through draws use depthMaskPipeline (vertMask, fragMask), which keeps the cutoff or uses hashed alpha (transparency). |
| Depth convention | standard or reversed-Z | Reversed-Z: cleared to 0, compare GREATER_OR_EQUAL, so lit means depth ≥ stored. |
| Acne fixes | constant, slope-scaled, normal offset | The lookup moves 1 to 3 texels along the normal (more where the light grazes) and 1 texel toward the light, in the map's texels at that point (offsetLookup). No rasterizer depth bias; the shadow pass culls like the main pass. |
| Filtering | PCF, comparison samplers, PCSS | 3x3 PCF with bilinear weights over 4x4 texels, read as four 2x2 Gathers, in the shader; no comparison sampler. |
| Caster detail | the same mesh in both passes | Meshes have LODs. A cascade's view takes them from the camera and size of the view that reads it (lodPixelsPerUnit, lodDepthPlane), so all views draw a mesh at the same LOD. |
| Coverage | fixed, fitted, cascades | Cascades: 1 to MAX_SHADOW_CASCADES (4), out to ShadowDesc::distance from the camera. |
| Synchronization | a barrier between the passes | The render graph's: the scene passes declare readDepth on every cascade, so they run after the cascade passes and the graph records the layout changes. |
Where it lives in code
| What | Where |
|---|---|
| The API | ShadowDesc, SceneShadow, MAX_SHADOW_CASCADES, MAX_VIEW_SHADOWS in include/rasm/scene.h; Renderer::addShadowPasses, Renderer::addScenePasses in src/renderer/gpuScene.cpp |
| Splits and boxes | getShadowSplits, fitShadowCascade in src/renderer/shadowCascades.cpp; getShadowMaps in src/renderer/gpuScene.cpp |
| Depth-only views, the cascades' matrices | Renderer::prepareSceneView, Renderer::drawSceneView in src/renderer/gpuScene.cpp; SceneView in src/renderer/gpuScene.h |
| GPU fields | shadowMaps (gfx::ShadowMap: matrix, texture, split), the shadowed lights' shadowedLights (gfx::ShadowedLight: light, firstMap, mapCount), and the LOD camera's lodPixelsPerUnit, lodDepthPlane in SceneData: src/renderer/uberMaterialTypes.h and shaders/lib/core.slang |
| The shadow pass shader | shaders/passes/shadow.slang |
| The lookup and PCF | sampleShadow, sampleShadowMap, offsetLookup, getPcfWeights in shaders/lib/shadow.slang; called from shadePBR in shaders/lib/pbr.slang |
| Applying it | shadePBR in shaders/lib/pbr.slang: the shadowed lights' loop, which reads a shadow only where its light reaches the surface |
| Depth-only targets | checkRenderTargetDesc and the depth texture's usage in src/rhi/renderContext.cpp; VulkanCommandBuffer::beginRendering (render area from the depth); canReadDepth in src/renderer/renderGraph.cpp |
| An example | examples/06_shadows/main.cpp |
sampleShadowfinds a light's maps only through itsgfx::ShadowedLight(firstMap,mapCount);shadePBRmultiplies only that light by it. A shadowed light is left out of the global and clustered loops, so it is shaded once.- The offsets take the texel size from the point's clip w, which is 1 in a cascade's orthographic box and the depth from the light in a perspective map, so one formula serves both.
- The cascades' views and the shaded view must fit the cascades with the same inputs (camera, the shaded view's aspect ratio, light,
SceneShadow), or the maps are read with other matrices than they were drawn with.addScenePassesonly takes a shadow thataddShadowPassesmade for the same scene and camera in the same graph, read by one view of that camera. - The test direction follows reversed-Z. Changing the depth convention changes it too (Projection and reversed-Z depth).
- The scene passes must declare
readDepthon every cascade, or they get no barrier and read one while it is still an attachment. - Each
gfx::ShadowMap::textureholds the bindless index of this frame slot's depth texture of the map:prepareSceneViewlooks them up every frame.
Further reading
- Lance Williams, "Casting curved shadows on curved surfaces", SIGGRAPH 1978: the original shadow map.
- William Reeves, David Salesin, Robert Cook, "Rendering antialiased shadows with depth maps", SIGGRAPH 1987: percentage-closer filtering.
- Microsoft, "Common Techniques to Improve Shadow Depth Maps" and "Cascaded Shadow Maps" (Windows DirectX documentation).
- Daniel Holbert, "Saying goodbye to shadow acne" (GDC 2011 poster): normal offset shadows.
- Elmar Eisemann and others, Real-Time Shadows (2011).