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
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Agent Note: Point and Spot Light Shadow Maps in render3d

Status: implemented

## Problem

Issue #255 (part of #251) requires real-time shadow maps for local 3D lights—perspective 2D shadows for spot lights and omnidirectional shadows for point lights—whose rendered shadows match analytic and golden references across every NSGo GPU backend (Metal, Direct3D 11, OpenGL 3.3, WebGPU, WebGL 2, OpenGL ES 3.0, and the software GPU renderer).

Implementing local shadows directly on top of NSGo v0.3.0's `gpu.Device` exposes four cross-backend constraints that callers should not have to rediscover:

1. **No layered depth attachments**: `gpu.DepthStencilAttachment` targets a 2D `*gpu.Texture` without an `ArrayLayer` selector, so rendering six cube faces directly into a `DimCube` depth texture is not expressible through the portable render-pass API.
2. **Uniform control flow and software VM limits**: WebGPU restricts `textureSampleCompare` to uniform control flow (rejecting calls inside `if` bounds checks), and NSGo v0.3.0's software GPU VM does not implement `exp`, `exp2`, or `log2`.
3. **Multi-caster uniform aliasing inside one pass**: Calling `Device.WriteBuffer` repeatedly to offset 0 of a single caster uniform buffer inside one `RenderPass` overwrites earlier casters' model matrices before `Submit` executes the pass.
4. **Device-loss restoration**: As recorded in [3D GPU Textures and Samplers](2026-11-24-render3d-textures-and-samplers.md), caching a `*gpu.Device` pointer on a retained resource wrapper becomes stale after `TriggerGPUDeviceLost` + `RestoreGPUDevice`.

## Decision

`packages/game/render3d/local_shadows.go` implements `SpotShadowMap` and `PointShadowMap` as dedicated, self-contained files (`local_shadows.go`, `local_shadows_test.go`, and golden PNGs under `testdata/golden/local_shadow_*.png`) to avoid symbol or file collisions with parallel directional/CSM/spotlight work:

- **Shadows for the `LightRig`'s own lights**: the maps take main's `SpotLight` and `PointLight` (`Update(dev, light)`), not a parallel light type. The far plane is the light's `Range`, or the config's `Far` when `Range` is 0 (unbounded inverse-square falloff); the config carries `Near`. The WGSL only computes visibility (`sample_spot_shadow`, `sample_point_shadow`); lighting stays in `LightWGSL`, whose new `shade_pbr_visibility` scales directional light 0, point light 0 and spot light 0 by a visibility each (`shade_pbr_shadowed` delegates to it). `LitPBRSpotShadowWGSL` / `LitPBRPointShadowWGSL` are `LitPBRWGSL` with the matching map bound, so the per-draw model and normal matrices and the material come from `PBRDrawUniform`, and `ShadePointVisibility` is the CPU reference.
- **Bind group 3**: `LocalShadowGroup` is `ShadowGroup` (3), the slot the directional shadow, fog, IBL and skinning share after camera (0), lights (1) and per-draw data (2). `SpotShadowWGSLForGroup` / `PointShadowWGSLForGroup` move the bindings, so a custom shader can bind a spot and a point shadow at once (tested at groups 3 and 2).
- **3×2 2D `FormatDepth32Float` atlas for point lights (`PointShadowMap`)**: All six 90° cube faces (`gpu.CubeFacePosX`..`gpu.CubeFaceNegZ`) are packed into a single `(3 * FaceResolution) × (2 * FaceResolution)` depth-only `gpu.RenderTarget`. `BeginFacePass(dev, target, face)` clears the entire atlas on `face == 0` (`LoadClear`), preserves previous tiles on `face` 1..5 (`LoadLoad`), and locks both `SetViewport` and `SetScissor` to that face's tile so geometry cannot bleed into neighboring faces.
- **Analytic perspective depth without a depth fragment shader**: Both spot and point shadow passes use a vertex-only depth pipeline (`vs_local_shadow_depth`) writing standard `[0, 1]` perspective depth. In `PointShadowWGSL`, `sample_point_shadow` selects the dominant cube face from `worldPos + worldNormal * normalBias - lightPos`, projects `(xView, yView, axisDist)` directly into tile-local UV, computes the exact NDC depth `(far/(far-near)) * (1 - near/axisDist)` without uploading six `mat4x4`s to the fragment shader, and clamps every tap inside `[0.51/faceRes, 1 - 0.51/faceRes]` so linear comparison and 3×3 PCF taps never sample across tile boundaries.
- **Portable WGSL and `textureSampleCompareLevel`**: `SpotShadowWGSL` and `PointShadowWGSL` avoid `exp`/`exp2`/`log2` and call `textureSampleCompareLevel` so bounds checks and filter branches remain valid under WebGPU's strict uniformity analysis as well as WebGL 2, GLES 3.0, and the software renderer.
- **256-byte dynamic-offset caster uniform slots**: the spot map allocates `MaxCasters` 256-byte slots and the point map `6 * MaxCasters`, one range per face, bound with `HasDynamicOffset: true`. `DrawCaster(pass, mesh, model)` writes `(lightViewProj, model)` to the next slot and returns false when the pass (or face) is full or `Update` has not run yet, as `DirectionalShadowMap.DrawCaster` does. `BeginFacePass` resets only its own face's slots, so refreshing a subset of faces, in any order, never exhausts the buffer. `MaxCasters` is capped at `MaxLocalShadowCasters` (4096) and the caster buffer is checked against the device's `MaxBufferSize`, both reported as `ErrInvalidLocalShadow`.
- **Same pass API as `DirectionalShadowMap`**: `BeginShadowPass(dev, target)` and `BeginFacePass(dev, target, face)` take the live `*gpu.Device` and a `ShadowPassTarget` (`*gpu.Encoder` or `*gpu.Frame`), so `Retained: true` maps survive device loss and restore.
- **Pure-Go CPU reference evaluators**: `EvaluateSpotShadow`, `PointShadowSelectFace` and `EvaluatePointShadow` mirror the WGSL math (including nearest vs linear depth comparison and clamped 3×3 PCF); with `ShadePointVisibility` they reproduce the GPU pixels in `local_shadows_test.go`.

## Alternatives considered

### Render point shadows into a `DimCube` depth texture with `texture_depth_cube`

A native cubemap depth texture lets hardware select faces and filter seamlessly across cube edges in a single `textureSampleCompare` call. It was rejected because NSGo v0.3.0's `gpu.DepthStencilAttachment` has no `ArrayLayer` field to attach individual cube faces, and cubemap depth attachments plus seamless cubemap PCF have backend-specific caveats on WebGL 2 and OpenGL ES 3.0. Packing the six faces into a `3×2` `FormatDepth32Float` 2D render target with per-tile scissor and UV clamping works identically across all six NSGo backends and the software GPU renderer.

### Write linear distance via `@builtin(frag_depth)` in a fragment shader for point shadows

Writing `length(worldPos - lightPos) / range` to `@builtin(frag_depth)` simplifies depth bias to a uniform world-space offset across all distances. It was rejected because writing `frag_depth` disables hardware early-Z optimization on every backend and requires fragment-shader execution during shadow passes, whereas analytic perspective NDC depth `(far/(far-near)) * (1 - near/axisDist)` matches the vertex-only hardware depth buffer exactly while keeping world-space `NormalBias` for grazing-angle acne suppression.

### Keep a separate light model (`SpotShadowLight`, `PointShadowLight`) with its own lighting helpers

The first version shipped its own light structs and `evaluate_*_lighting` WGSL. It was rejected in review: it disagreed with the `LightRig` (no 1/π in the diffuse term, a different near-field clamp, `Range` required where the rig allows 0), its ready-made pipelines had no per-draw model matrix and a constant albedo, and it hard-coded `@group(1)`, which collides with `LightGroup`. Deriving the shadow from the rig's lights and multiplying visibility into the existing PBR loop keeps one lighting model.

### Use one static caster uniform buffer overwritten per `DrawCaster`

A single 128-byte uniform buffer avoids sizing a `MaxCasters * 256` slot buffer. It was rejected because `Device.WriteBuffer` executes before the submitted command buffer runs, so drawing two or more casters in the same shadow pass (or across six faces in one command encoder) would silently overwrite earlier casters' transforms with the last caster's matrix.

## Consequences

- **Benefits**:
- Perspective spot-light and omnidirectional 6-face point-light shadows work identically on full GPU profiles and `nsgotest.NoGPUCompute` (WebGL 2 / OpenGL ES 3.0), with zero-allocation uniform encoding (`SpotShadowUniform.Encode`, `PointShadowUniform.Encode`), multi-caster dynamic offsets, `Retained` device-loss restoration, and exact `ByteSize()` budget reporting.
- Verified by `local_shadows_test.go` against the pure-Go references (`EvaluateSpotShadow`, `EvaluatePointShadow`, `ShadePointVisibility`) and golden reference PNGs (`local_shadow_spot.png`, `local_shadow_point.png`).
- **Costs**:
- `PointShadowMap`'s `3×2` atlas clamps PCF taps inside each tile boundary rather than filtering across cube-face seams, which can leave a subtle 1-texel softness discontinuity right along a cube diagonal edge; increasing `FaceResolution` minimizes it.
- Only the first spot light and the first point light of a rig can be shadowed by the ready-made pipelines, and both cannot be bound there at once because they share group 3; a custom shader binds both through the `ForGroup` variants.
- Face 0 clears the whole point atlas, so a partial refresh must either include face 0 with every other face or skip it.
- `DrawCaster` refuses draws past `MaxCasters` (default 256 per spot pass or per point face) and reports it by returning false rather than resizing GPU buffers mid-pass.
3 changes: 3 additions & 0 deletions changelog.d/render3d-local-shadows-255.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Added

- `game/render3d`: shadows for the first spot light and the first point light of a `LightRig` (#255). `SpotShadowMap` renders a perspective depth map and `PointShadowMap` packs the six cube faces into one 3x2 depth atlas, both updated from the rig's `SpotLight` / `PointLight`, with hard or 3x3 PCF filtering, depth and normal bias, several casters per pass, and `Retained` device-loss recovery. `LitPBRSpotShadowWGSL` / `LitPBRPointShadowWGSL` (`NewLitPBRSpotShadowPipeline`, `NewLitPBRPointShadowPipeline`, or `LitPBRPipelineOptions.SpotShadowLayout` / `PointShadowLayout`) draw lit PBR meshes with the shadow at bind group 3; `SpotShadowWGSL` / `PointShadowWGSL` and their `ForGroup` variants add the shadows to custom shaders, `shade_pbr_visibility` in `LightWGSL` and `ShadePointVisibility` scale the shadowed lights, and `EvaluateSpotShadow` / `EvaluatePointShadow` are the CPU references.
50 changes: 48 additions & 2 deletions docs/en/render3d.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# render3d

`game/render3d` provides mesh buffers, textures and samplers, metallic-roughness PBR materials, directional shadow maps, camera uniforms, offscreen render-to-texture cameras and multi-viewport split-screen rendering, distance and height fog, and an HDR render target with a tone-mapping pass for the NSGo GPU view alongside the GPU-agnostic, zero-steady-state-allocation CPU 3D render pipeline and developer tools: frustum culling, opaque/transparent draw sorting, automatic instancing, LOD selection with hysteresis, camera-facing billboards and 3D ribbon trails, 3D debug wireframes and transform gizmos, frame profiling, and mobile/desktop GPU budgets.
`game/render3d` provides mesh buffers, textures and samplers, metallic-roughness PBR materials, directional, spot and point light shadow maps, camera uniforms, offscreen render-to-texture cameras and multi-viewport split-screen rendering, distance and height fog, and an HDR render target with a tone-mapping pass for the NSGo GPU view alongside the GPU-agnostic, zero-steady-state-allocation CPU 3D render pipeline and developer tools: frustum culling, opaque/transparent draw sorting, automatic instancing, LOD selection with hysteresis, camera-facing billboards and 3D ribbon trails, 3D debug wireframes and transform gizmos, frame profiling, and mobile/desktop GPU budgets.

```go
import "github.com/nsgo-dev/game/packages/game/render3d"
Expand Down Expand Up @@ -378,7 +378,7 @@ Three pipelines draw a `GPUSkinnedMesh`, each binding the palette at its own gro
| Pipeline | Shader | Palette group | Not combinable with |
| --- | --- | --- | --- |
| `NewSkinnedMeshPipeline` (unlit, colored by normal) | `SkinnedMeshWGSL` | `SkinGroup` (1) | |
| `NewLitPBRPipelineWithOptions` with `LitPBRPipelineOptions.SkinLayout` (scene lights) | `LitPBRSkinnedWGSL` | `LitPBRSkinGroup` (3) | `FogLayout`, `IBLLayout`, `ShadowLayout` |
| `NewLitPBRPipelineWithOptions` with `LitPBRPipelineOptions.SkinLayout` (scene lights) | `LitPBRSkinnedWGSL` | `LitPBRSkinGroup` (3) | `FogLayout`, `IBLLayout`, `ShadowLayout`, `SpotShadowLayout`, `PointShadowLayout` |
| `NewMaterialPipeline` with `MaterialPipelineOptions.SkinLayout` (glTF material with textures) | `MaterialSkinnedWGSL` | `MaterialSkinGroup` (2) | `FogLayout` |

`SkinWGSL` declares the uniform block at group 1 and the portable `skin_position` / `skin_normal` vertex helpers matching CPU `SkinVertex`, for custom shaders that bind nothing else at group 1.
Expand Down Expand Up @@ -1092,3 +1092,49 @@ _ = renderer.Draw(pass, camBuf, lmMesh, worldMat, mat)
- **Atlas transform**: `LightmapRef.UVScale` / `UVOffset` are the authoritative atlas transform; `LightmapRef.Texture` carries no scale or offset, so do not also apply it with `TransformTexCoords`. See [Baked lightmaps](3d-models-blender.md#baked-lightmaps) for where the values come from.
- **Texture streaming**: `BeginFrame` drops cached bind groups of lightmap and albedo textures that have been closed, so streaming levels or hot-reloading lightmaps does not grow the cache.
- **Scope**: `LightmapRenderer` is a standalone path, albedo times (baked irradiance plus one Lambertian light). It has no metallic-roughness, normal, occlusion or emissive maps and does not read a `LightRig`. Feeding lightmaps into the PBR material path as its indirect term is tracked in [#752](https://github.com/nsgo-dev/game/issues/752).

## Point and spot light shadows (`SpotShadowMap`, `PointShadowMap`)

`SpotShadowMap` and `PointShadowMap` shadow the first spot light (`rig.Spot[0]`) and the first point light (`rig.Point[0]`) of a `LightRig`. They render depth-only `FormatDepth32Float` maps from the rig's own `SpotLight` and `PointLight`, and the lit PBR pipelines multiply that light's contribution by the shadow, so a shadowed light is shaded exactly like the same light in `LitPBRWGSL` (Cook-Torrance GGX, energy-conserving Lambert, `PointLightAttenuation`, glTF cone falloff). Everything runs on every NSGo backend, the WebGL 2 / OpenGL ES 3.0 profile (`nsgotest.NoGPUCompute`) and the software renderer included:

```go
spot, err := render3d.NewSpotShadowMap(cx, dev, render3d.DefaultSpotShadowConfig())
litPipe, err := render3d.NewLitPBRSpotShadowPipeline(cx, dev, camBuf.Layout(), lightBuf.Layout(), drawBufs[0].Layout(), spot.Layout(), gpu.FormatDepth24Plus)

// Each frame in OnFrame:
_ = spot.Update(dev, rig.Spot[0]) // the light the shadow attenuates
if sp := spot.BeginShadowPass(dev, frame); sp != nil {
spot.DrawCaster(sp, pillarMesh, pillarModel) // false when the pass is full
sp.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.LocalShadowGroup, spot.BindGroup())
for i, mesh := range meshes {
mp.SetBindGroup(render3d.PBRDrawGroup, drawBufs[i].BindGroup()) // per-draw model matrix and material
mesh.Draw(mp)
}
mp.End()
```

For a point light, update from `rig.Point[0]`, draw with `NewLitPBRPointShadowPipeline`, and render the cube faces:

```go
_ = point.Update(dev, rig.Point[0])
for face := range gpu.CubeFace(render3d.PointShadowFaceCount) {
if fp := point.BeginFacePass(dev, frame, face); fp != nil {
point.DrawCaster(fp, blockerMesh, blockerModel)
fp.End()
}
}
```

- **Spot projection**: a square `[0, 1]`-depth perspective from the light's `Position` along its `Direction` with a field of view of `2 * OuterConeAngle` (`SpotShadowViewProj`). The far plane is the light's `Range`, or `SpotShadowConfig.Far` (default `DefaultLocalShadowFar`, 50) for a light with `Range` 0; `Near` defaults to 0.1. A cone wider than `MaxSpotShadowConeAngle` (just under 90°) cannot be projected and `Update` returns `ErrInvalidLocalShadow`.
- **Point atlas**: the six 90° cube faces are packed into one `(3 * FaceResolution) × (2 * FaceResolution)` 2D depth atlas, because NSGo cannot attach a single face of a depth cube map. `sample_point_shadow` picks the dominant face, computes the perspective depth `(far/(far-near)) * (1 - near/axisDist)` directly, and clamps every tap inside its tile so 3×3 PCF never bleeds into a neighboring face. `BeginFacePass` with face 0 clears the whole atlas and faces 1..5 keep what is there, so a partial refresh either includes face 0 with every other face or skips it.
- **Casters**: `DrawCaster` writes each caster's `(lightViewProj, model)` into its own 256-byte dynamic-offset slot, so many casters draw in one pass. `MaxCasters` (default 256, at most `MaxLocalShadowCasters`) applies per spot pass and per point face; each face has its own slots, so faces can be refreshed in any order. `DrawCaster` returns false when the pass or face is full or `Update` has not run yet.
- **Filtering and bias**: `LocalShadowFilterHard` (one nearest comparison tap) or `LocalShadowFilterPCF3x3` (nine linear taps), with a constant `DepthBias` and a world-space `NormalBias`.
- **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).
Loading
Loading