Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions .agents/notes/implemented/feature/2026-11-24-render3d-csm.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Agent Note: Cascaded Shadow Maps in render3d

Status: implemented

## Problem

A single directional shadow map (`DirectionalShadowMap`) stretched across a large view frustum cannot keep shadows sharp near the camera and still reach the horizon: near objects alias unless the map is impractically large, and moving the camera makes shadow edges swim. `game/render3d` must also run identically on every NSGo backend, WebGL 2 and OpenGL ES 3.0 (`nsgotest.NoGPUCompute`) and the software renderer included, without `texture_depth_2d_array`, compute shaders or transcendental WGSL ops.

## Decision

`packages/game/render3d/csm.go` adds directional cascaded shadow maps that shadow the same light the rest of the lit PBR path shades, `LightRig.Directional[0]`:

- **Splits and fitting**: `ComputeCSMSplits` uses the practical split scheme (`SplitLambda`, default 0.75). `FitCascades` cuts each cascade's slice of the camera frustum along the projection's own near and far planes (read from the projection matrix), so orthographic cameras whose near plane is at or behind them fit correctly; shadows start at view depth `max(near, 0.1)`. `FitCascadesFromCamera` uses the near and far planes `scene3d.Projection.Matrix` uses. With `TexelSnap` each cascade is sized from a bounding sphere quantized to 1/16 world unit and snapped to whole texels in a world-anchored light basis.
- **One 2D depth atlas**: cascades are tiles of one `FormatDepth32Float` render target (1x1, 2x1 or 2x2). `Update` refuses frames fitted with another cascade count, resolution or filter than the atlas, because tiles, texel sizes and the sampler's filter come from that config. The first `BeginCascadePass` after `Update` clears the whole atlas, whichever cascade it draws.
- **Casters**: `DrawCaster` gives each distinct model matrix one dynamic-offset slot per frame and reuses it across cascades, so `MaxCasters` counts distinct models, not draws; it returns false when the slots run out instead of silently dropping the shadow.
- **Integration with lit PBR**: `CSMGroup` is `ShadowGroup` (3). `CSMWGSL` (or `CSMWGSLForGroup`) declares `sample_csm_shadow(world_pos, world_normal)`, which reads the view depth from `CameraWGSL` and is passed as `shade_pbr_shadowed`'s visibility. `LitPBRCSMWGSL` / `NewLitPBRCSMPipeline` / `LitPBRPipelineOptions.CSMLayout` mirror the single directional shadow's pipeline, and filtering reuses `ShadowFilter`. `EvaluateCSMShadow` plus `ShadePointShadowed` (and `CSMFrame.DebugTint`) are the CPU reference.

## Alternatives considered

### A separate CSM lit shader and bind group layout

The first version shipped its own Lambert shader (`CSMLitWGSL`) at groups 1 and 2 with its own material type. It was dropped once `LightRig` and the lit PBR pipelines landed: groups 1 and 2 belong to `LightGroup` and `PBRDrawGroup`, and a second lit path would shade the scene differently from every other shadow kind.

### `texture_depth_2d_array` instead of an atlas

An array gives each cascade its own `[0, 1]` UVs, but NSGo's portable render targets are 2D depth attachments. A 2x2 atlas with per-tile viewports, scissors and tile-clamped taps works on every backend with one render target and one bind group.

### Tight light-space AABB fitting by default

A tight AABB maximizes texel density for a static camera but changes world units per texel as the camera turns, so shadows shimmer. It remains available with `TexelSnap: false`.

## Consequences

- Shadows stay sharp near the camera (the large-scene test checks at least 3x the texel density of one map at the same resolution) and blend smoothly between cascades.
- Bind group 3 is shared with the single directional, spot and point shadows, fog, IBL and skinning, so a lit PBR pipeline takes one of them; custom shaders move the bindings with `CSMWGSLForGroup`.
- Three or four cascades double the atlas size per side (`Resolution: 1024` allocates 2048x2048); `NewCascadedShadowMap` checks `MaxTextureDimension2D` and returns `ErrInvalidCSM` when it is exceeded.

## Verification

- `packages/game/render3d/csm_test.go` covers split bounds, texel-snapping stability, cascade selection and blending, validation, zero-allocation fitting and encoding, `Update` refusing mismatched frames, caster slot reuse and overflow, an orthographic camera with a negative near plane, cascade passes drawn in reverse order, hard vs 3x3 PCF, `Retained` device loss and `Close`.
- `TestCSMLargeSceneReferenceRender` renders six pillars across four cascades through `LitPBRCSMWGSL` on the full and `NoGPUCompute` profiles, compares with `testdata/golden/csm_large_scene.png`, and checks GPU pixels (debug tint included) against `ShadePointShadowed` with `EvaluateCSMShadow` within 4/255.
3 changes: 3 additions & 0 deletions changelog.d/render3d-csm-257.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Added

- `game/render3d`: cascaded shadow maps for the first directional light of a `LightRig` (`CascadedShadowMap`, `CSMConfig`, `ComputeCSMSplits`, `FitCascades`, `FitCascadesFromCamera`, `CSMWGSL`, `CSMWGSLForGroup`, `LitPBRCSMWGSL`, `NewLitPBRCSMPipeline`, `LitPBRPipelineOptions.CSMLayout`, and the CPU reference `EvaluateCSMShadow`), packing up to four texel-snapped cascades into one 2D depth atlas at bind group 3 with hard or 3x3 PCF filtering, cascade blending, a far fade and `Retained` device-loss support (#257).
43 changes: 43 additions & 0 deletions docs/en/render3d.md
Original file line number Diff line number Diff line change
Expand Up @@ -1141,6 +1141,49 @@ for face := range gpu.CubeFace(render3d.PointShadowFaceCount) {
- **Bind group 3**: `LocalShadowGroup` is `ShadowGroup` (3), the group the directional shadow, fog, IBL and skinning also use, so a lit PBR pipeline takes one of them (`LitPBRPipelineOptions.SpotShadowLayout` or `PointShadowLayout`). A custom shader that needs both, or group 3 for something else, places the bindings with `SpotShadowWGSLForGroup` / `PointShadowWGSLForGroup` and scales its lights with `shade_pbr_visibility(…, directional0_vis, point0_vis, spot0_vis)` from `LightWGSL`.
- **Device loss and CPU references**: with `Retained: true` the depth target, sampler, buffers, bind groups and depth pipeline come back after a device loss. `EvaluateSpotShadow`, `EvaluatePointShadow` and `PointShadowSelectFace` mirror the WGSL, and `ShadePointVisibility` with a `LightVisibility` reproduces the lit pixel; the tests compare them with the GPU and with the golden renders `render3d/testdata/golden/local_shadow_spot.png` and `local_shadow_point.png` (`UPDATE_GOLDEN=1` rewrites them).

## Cascaded shadow maps (`CascadedShadowMap`, `CSMConfig`)

`CascadedShadowMap` shadows the first directional light of a `LightRig` (`rig.Directional[0]`) with up to four cascades (`MaxCascades`), so shadows stay sharp near the camera and still reach the horizon. It is the large-scene alternative to `DirectionalShadowMap`: the lit PBR pipelines shade the rig exactly like `LitPBRWGSL` and multiply that one light by the cascaded shadow, leaving the other lights, ambient and emission unshadowed. Everything runs on every NSGo backend, the WebGL 2 / OpenGL ES 3.0 profile (`nsgotest.NoGPUCompute`) and the software renderer included:

```go
cfg := render3d.DefaultCSMConfig() // 4 cascades, 1024 texels each, 3x3 PCF, texel snapping
cfg.MaxShadowDistance = 80
cfg.Retained = true
csm, err := render3d.NewCascadedShadowMap(cx, dev, cfg)
litPipe, err := render3d.NewLitPBRCSMPipeline(cx, dev, camBuf.Layout(), lightBuf.Layout(), drawBufs[0].Layout(), csm.Layout(), gpu.FormatDepth24Plus)

// Each frame in OnFrame(frame *gpu.Frame):
shadowFrame := render3d.FitCascadesFromCamera(cam, rig.Directional[0].Direction, csm.Config()) // the light the cascades shadow
_ = csm.Update(dev, shadowFrame)
for i := range csm.CascadeCount() {
if pass := csm.BeginCascadePass(frame, i); pass != nil {
for j, mesh := range casterMeshes {
csm.DrawCaster(pass, mesh, casterModels[j]) // false once MaxCasters distinct models are taken
}
pass.End()
}
}

mp := frame.BeginRenderPass(gpu.RenderPassDesc{ /* color + depth */ })
mp.SetPipeline(litPipe)
mp.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup())
mp.SetBindGroup(render3d.LightGroup, lightBuf.BindGroup())
mp.SetBindGroup(render3d.CSMGroup, csm.BindGroup())
for i, mesh := range meshes {
mp.SetBindGroup(render3d.PBRDrawGroup, drawBufs[i].BindGroup())
mesh.Draw(mp)
}
mp.End()
```

- **Splits (`ComputeCSMSplits`)**: `[near, min(far, MaxShadowDistance)]` is divided with the practical split scheme, blending logarithmic and uniform splits by `SplitLambda` (default 0.75).
- **Fitting (`FitCascades`, `FitCascadesFromCamera`)**: each cascade's slice of the camera frustum is cut along the projection's own near and far planes, so perspective and orthographic cameras both work. `FitCascadesFromCamera` uses the near and far planes `Camera.ProjMatrix` uses; shadows start at view depth 0.1 when an orthographic camera's near plane is at or behind it. With `TexelSnap` (the default) each cascade is sized from a bounding sphere and snapped to whole texels, so shadow edges do not shimmer as the camera moves or turns. `CasterPadding` pulls each cascade's near plane toward the light so casters outside the view still cast into it. Fitting and `CSMFrame.EncodeUniforms` allocate nothing.
- **One 2D depth atlas**: the cascades are tiles of one `FormatDepth32Float` texture (1x1 for one cascade, 2x1 for two, 2x2 for three or four), so no depth texture arrays are needed. `Update` refuses, with `ErrInvalidCSM`, a frame fitted with another cascade count, resolution or filter than the atlas, because its tiles, texel size and filter would not match the atlas and its sampler. The first `BeginCascadePass` after `Update`, whichever cascade it draws, clears the whole atlas; render every cascade after each `Update`, in any order.
- **Casters**: `DrawCaster` writes each distinct model matrix into its own 256-byte dynamic-offset slot once per frame and reuses it in the other cascades, so `MaxCasters` (default 256) counts distinct models between two `Update` calls, not draws. When the slots run out it draws nothing and returns false. `DrawCasterGroup` draws with caller-owned transforms instead.
- **Filtering and blending**: `ShadowFilterHard` (one nearest comparison tap) or `ShadowFilterPCF3x3` (nine linear taps clamped inside the cascade's tile), the same `ShadowFilter` the single directional shadow map uses. `CascadeBlendRange` cross-fades into the next cascade over that fraction of each cascade and fades the last one out toward `MaxShadowDistance`; `DebugCascades` tints surfaces by cascade (red, green, blue, yellow).
- **Bind group 3**: `CSMGroup` is `ShadowGroup` (3), so a lit PBR pipeline takes the cascaded shadow map instead of the directional, spot or point shadow, fog, IBL or skinning (`LitPBRPipelineOptions.CSMLayout`). Custom shaders prepend `CameraWGSL` and `CSMWGSL` (or `CSMWGSLForGroup(n)` when group 3 holds something else) and pass `sample_csm_shadow(world_pos, world_normal)` to `shade_pbr_shadowed` from `LightWGSL`.
- **Device loss and CPU references**: with `Retained: true` the atlas, sampler, buffers, bind groups and depth pipeline come back after a device loss. `EvaluateCSMShadow` mirrors the WGSL over an atlas read back with `ReadCSMDepthAtlas` / `ReadCSMDepthAtlasAsync`, and `ShadePointShadowed` with that visibility, times `CSMFrame.DebugTint`, reproduces the lit pixel; the tests compare them with the GPU on both profiles and with the golden render `render3d/testdata/golden/csm_large_scene.png` (`UPDATE_GOLDEN=1` rewrites it).

## 3D post-processing (`PostStack3D`, `BloomPass`, `SSAOPass`, `DepthOfFieldPass`)

`PostStack3D` composes screen-space ambient occlusion (`SSAOPass`), depth-aware disc bokeh Depth of Field (`DepthOfFieldPass`), and HDR Bloom (`BloomPass`) over an offscreen 3D color+depth `gpu.RenderTarget` (`FormatRGBA16Float` + `FormatDepth32Float` by default) and writes the final image to the swapchain or a chosen destination texture:
Expand Down
43 changes: 43 additions & 0 deletions docs/zh/render3d.md
Original file line number Diff line number Diff line change
Expand Up @@ -1141,6 +1141,49 @@ for face := range gpu.CubeFace(render3d.PointShadowFaceCount) {
- **第 3 绑定组**:`LocalShadowGroup` 即 `ShadowGroup`(3),方向光阴影、雾、IBL 与蒙皮也使用该组,因此一条带光照的 PBR 管线只能选用其中之一(`LitPBRPipelineOptions.SpotShadowLayout` 或 `PointShadowLayout`)。需要同时使用两种阴影、或第 3 组另有用途的自定义着色器,可用 `SpotShadowWGSLForGroup` / `PointShadowWGSLForGroup` 放置绑定,并用 `LightWGSL` 中的 `shade_pbr_visibility(…, directional0_vis, point0_vis, spot0_vis)` 缩放各光源。
- **设备丢失与 CPU 参考实现**:设置 `Retained: true` 后,深度目标、采样器、缓冲、绑定组与深度管线会在设备丢失后恢复。`EvaluateSpotShadow`、`EvaluatePointShadow` 与 `PointShadowSelectFace` 与 WGSL 一一对应,`ShadePointVisibility` 配合 `LightVisibility` 可复现带光照的像素;测试将它们与 GPU 结果以及参考渲染图 `render3d/testdata/golden/local_shadow_spot.png` 和 `local_shadow_point.png`(`UPDATE_GOLDEN=1` 可重写)进行比较。

## 级联阴影贴图(`CascadedShadowMap`、`CSMConfig`)

`CascadedShadowMap` 用最多四级级联(`MaxCascades`)为 `LightRig` 的第一盏方向光(`rig.Directional[0]`)投射阴影,使阴影在相机附近保持清晰,同时覆盖到地平线。它是 `DirectionalShadowMap` 面向大场景的替代方案:受光 PBR 管线与 `LitPBRWGSL` 完全一样地着色整个光照组,只把这一盏灯乘以级联阴影,其他光源、环境光与自发光不受阴影影响。全部功能在每个 NSGo 后端上运行,包括 WebGL 2 / OpenGL ES 3.0 配置(`nsgotest.NoGPUCompute`)与软件渲染器:

```go
cfg := render3d.DefaultCSMConfig() // 4 级级联、每级 1024 texel、3x3 PCF、texel 对齐
cfg.MaxShadowDistance = 80
cfg.Retained = true
csm, err := render3d.NewCascadedShadowMap(cx, dev, cfg)
litPipe, err := render3d.NewLitPBRCSMPipeline(cx, dev, camBuf.Layout(), lightBuf.Layout(), drawBufs[0].Layout(), csm.Layout(), gpu.FormatDepth24Plus)

// 每帧在 OnFrame(frame *gpu.Frame) 中:
shadowFrame := render3d.FitCascadesFromCamera(cam, rig.Directional[0].Direction, csm.Config()) // 级联所遮挡的那盏灯
_ = csm.Update(dev, shadowFrame)
for i := range csm.CascadeCount() {
if pass := csm.BeginCascadePass(frame, i); pass != nil {
for j, mesh := range casterMeshes {
csm.DrawCaster(pass, mesh, casterModels[j]) // 占满 MaxCasters 个不同模型矩阵后返回 false
}
pass.End()
}
}

mp := frame.BeginRenderPass(gpu.RenderPassDesc{ /* 颜色 + 深度 */ })
mp.SetPipeline(litPipe)
mp.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup())
mp.SetBindGroup(render3d.LightGroup, lightBuf.BindGroup())
mp.SetBindGroup(render3d.CSMGroup, csm.BindGroup())
for i, mesh := range meshes {
mp.SetBindGroup(render3d.PBRDrawGroup, drawBufs[i].BindGroup())
mesh.Draw(mp)
}
mp.End()
```

- **分割(`ComputeCSMSplits`)**:用实用分割方案划分 `[near, min(far, MaxShadowDistance)]`,以 `SplitLambda`(默认 0.75)混合对数分割与均匀分割。
- **拟合(`FitCascades`、`FitCascadesFromCamera`)**:每级级联在相机视锥中所占的一段按投影自身的近、远平面截取,因此透视与正交相机都适用。`FitCascadesFromCamera` 使用 `Camera.ProjMatrix` 所用的近、远平面;正交相机的近平面位于相机处或其后方时,阴影从视深 0.1 开始。开启 `TexelSnap`(默认)时,每级级联按包围球确定大小并对齐到整 texel,相机移动或转动时阴影边缘不会闪烁。`CasterPadding` 把每级级联的近平面向光源方向拉远,使视野外的投射体仍能把阴影投进视野。拟合与 `CSMFrame.EncodeUniforms` 都不分配内存。
- **单张 2D 深度图集**:各级级联是同一张 `FormatDepth32Float` 纹理中的图块(1 级为 1x1、2 级为 2x1、3 或 4 级为 2x2),因此不需要深度纹理数组。如果某帧拟合时使用的级联数、分辨率或滤波方式与图集不同,`Update` 会以 `ErrInvalidCSM` 拒绝它,因为其图块、texel 大小与滤波方式无法与图集及其采样器对应。`Update` 之后的第一次 `BeginCascadePass` 无论绘制哪一级都会清空整张图集;每次 `Update` 之后请渲染全部级联,顺序不限。
- **投射体**:`DrawCaster` 每帧把每个不同的模型矩阵写入各自的 256 字节动态偏移槽位,并在其他级联中复用,因此 `MaxCasters`(默认 256)统计的是两次 `Update` 之间不同模型矩阵的数量,而不是绘制次数。槽位用尽时它不绘制并返回 false。`DrawCasterGroup` 则使用调用方自有的变换。
- **滤波与混合**:`ShadowFilterHard`(一次最近点比较采样)或 `ShadowFilterPCF3x3`(九次线性采样,限制在该级图块内),与单张方向光阴影贴图使用同一个 `ShadowFilter`。`CascadeBlendRange` 在每级级联的这一比例范围内向下一级交叉淡入,并让最后一级朝 `MaxShadowDistance` 淡出;`DebugCascades` 按级联给表面着色(红、绿、蓝、黄)。
- **绑定组 3**:`CSMGroup` 就是 `ShadowGroup`(3),因此受光 PBR 管线只能在级联阴影贴图与方向光、聚光灯或点光源阴影、雾、IBL、蒙皮中取其一(`LitPBRPipelineOptions.CSMLayout`)。自定义着色器在前面拼接 `CameraWGSL` 与 `CSMWGSL`(绑定组 3 已有他用时用 `CSMWGSLForGroup(n)`),并把 `sample_csm_shadow(world_pos, world_normal)` 传给 `LightWGSL` 中的 `shade_pbr_shadowed`。
- **设备丢失与 CPU 参考实现**:设置 `Retained: true` 时,图集、采样器、缓冲区、绑定组与深度管线会在设备丢失后恢复。`EvaluateCSMShadow` 在通过 `ReadCSMDepthAtlas` / `ReadCSMDepthAtlasAsync` 读回的图集上复现 WGSL,`ShadePointShadowed` 以该可见度计算、再乘以 `CSMFrame.DebugTint`,即可复现受光像素;测试在两种配置下把它们与 GPU 结果以及黄金渲染图 `render3d/testdata/golden/csm_large_scene.png` 比较(`UPDATE_GOLDEN=1` 会重写它)。

## 3D 后处理(`PostStack3D`、`BloomPass`、`SSAOPass`、`DepthOfFieldPass`)

`PostStack3D` 通过离屏 3D 颜色+深度 `gpu.RenderTarget`(默认为 `FormatRGBA16Float` + `FormatDepth32Float`)组合屏幕空间环境光遮蔽(`SSAOPass`)、深度感知圆盘散景景深(`DepthOfFieldPass`)和 HDR 泛光(`BloomPass`),并将最终结果写入交换链或指定的目标纹理:
Expand Down
Loading
Loading