diff --git a/.agents/notes/implemented/feature/2026-11-24-render3d-csm.md b/.agents/notes/implemented/feature/2026-11-24-render3d-csm.md new file mode 100644 index 00000000..924b7f36 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-24-render3d-csm.md @@ -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. diff --git a/changelog.d/render3d-csm-257.md b/changelog.d/render3d-csm-257.md new file mode 100644 index 00000000..cc101f72 --- /dev/null +++ b/changelog.d/render3d-csm-257.md @@ -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). diff --git a/docs/en/render3d.md b/docs/en/render3d.md index 3d93b6fd..e0abbbae 100644 --- a/docs/en/render3d.md +++ b/docs/en/render3d.md @@ -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: diff --git a/docs/zh/render3d.md b/docs/zh/render3d.md index bb620ad3..bca93dd3 100644 --- a/docs/zh/render3d.md +++ b/docs/zh/render3d.md @@ -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`),并将最终结果写入交换链或指定的目标纹理: diff --git a/packages/game/render3d/csm.go b/packages/game/render3d/csm.go new file mode 100644 index 00000000..dd91e0ab --- /dev/null +++ b/packages/game/render3d/csm.go @@ -0,0 +1,1661 @@ +package render3d + +import ( + "encoding/binary" + "errors" + "fmt" + "math" + + "github.com/nsgo-dev/game/packages/game/math3d" + "github.com/nsgo-dev/game/packages/game/scene3d" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/gpu" +) + +const ( + // MaxCascades is the maximum number of shadow cascades supported by [CascadedShadowMap], [CSMFrame], and [CSMWGSL]. + MaxCascades = 4 + + // CSMGroup is the bind group index [CSMWGSL] and [LitPBRCSMWGSL] use for the cascaded shadow map (uniform buffer at binding 0, depth atlas at binding 1, comparison sampler at binding 2). It is [ShadowGroup] (3), after [CameraGroup], [LightGroup] and [PBRDrawGroup], so a lit PBR pipeline takes the cascaded shadow map instead of the single directional shadow map, fog, IBL or skinning. Custom shaders that need group 3 for something else place the bindings elsewhere with [CSMWGSLForGroup]. + CSMGroup = ShadowGroup + + // CSMUniformSize is the byte size of the CSMUniforms block encoded by [CSMFrame.EncodeUniforms] and declared by [CSMWGSL]: four mat4x4 matrices (256 bytes) plus ten vec4 vectors (160 bytes). + CSMUniformSize = 4*64 + 10*16 + + // DefaultCSMCascadeCount is the default number of cascades used when [CSMConfig.CascadeCount] is zero. + DefaultCSMCascadeCount = 4 + + // DefaultCSMResolution is the default per-cascade shadow-map resolution in texels used when [CSMConfig.Resolution] is zero. + DefaultCSMResolution = 1024 + + // DefaultCSMSplitLambda is the practical split blend factor returned by [DefaultCSMConfig], blending 75% logarithmic and 25% uniform splits. + DefaultCSMSplitLambda float32 = 0.75 + + // DefaultCSMDepthBias is the constant receiver depth bias returned by [DefaultCSMConfig]. + DefaultCSMDepthBias float32 = 0.0015 + + // DefaultCSMNormalBias is the world-space normal offset bias (for cascade 0, scaled proportionally to texel size for farther cascades) returned by [DefaultCSMConfig]. + DefaultCSMNormalBias float32 = 0.02 + + // DefaultCSMCascadeBlendRange is the fractional cascade transition zone ([0, 0.5] of each cascade's depth span) returned by [DefaultCSMConfig]. + DefaultCSMCascadeBlendRange float32 = 0.1 + + // DefaultCSMCasterPadding is the distance in world units pulled back toward the light source when fitting cascade orthographic near planes, so off-frustum casters behind the camera still cast shadows into view. + DefaultCSMCasterPadding float32 = 25.0 + + // DefaultCSMMaxCasters is the default per-frame dynamic caster transform capacity allocated by [NewCascadedShadowMap] when [CSMConfig.MaxCasters] is 0. + DefaultCSMMaxCasters = 256 +) + +// ErrInvalidCSM is wrapped by every validation or invalid-argument error returned by the cascaded shadow map API. +var ErrInvalidCSM = errors.New("render3d: invalid cascaded shadow map") + +// CSMConfig configures [FitCascades] and [NewCascadedShadowMap]. +// +// Use [DefaultCSMConfig] for balanced outdoor defaults (4 cascades, 1024x1024 per cascade, lambda 0.75, texel snapping enabled, 3x3 PCF, 10% cascade blend). Zero values for CascadeCount, Resolution, and MaxCasters fall back to [DefaultCSMCascadeCount], [DefaultCSMResolution], and [DefaultCSMMaxCasters]. +type CSMConfig struct { + // Label names GPU resources in capture tools. + Label string + // CascadeCount is the number of cascades in [1, MaxCascades]. Zero defaults to 4. + CascadeCount int + // Resolution is the width and height in texels of each cascade tile in the 2D depth atlas. Zero defaults to 1024. + Resolution int + // SplitLambda blends uniform (0.0) and logarithmic (1.0) cascade split distances using the practical split scheme. Must lie in [0, 1]. + SplitLambda float32 + // MaxShadowDistance caps the farthest view-space depth covered by shadows. When zero, the camera's far clip plane is used. + MaxShadowDistance float32 + // DepthBias subtracts a small constant (modulated by surface slope) from receiver light-space depth to prevent shadow acne. Must be >= 0. + DepthBias float32 + // NormalBias offsets receiver world positions along their surface normal (scaled by each cascade's texel size relative to cascade 0) before projecting into light space. Must be >= 0. + NormalBias float32 + // CascadeBlendRange is the fraction in [0, 0.5] of each cascade's depth interval used to smoothly cross-fade into the next cascade (and fade out shadows smoothly approaching MaxShadowDistance). Zero disables blending. + CascadeBlendRange float32 + // TexelSnap fits each cascade with a rotation-invariant bounding sphere and snaps its light-space projection origin to whole shadow-map texel increments, eliminating shadow-edge swimming as the camera moves. + TexelSnap bool + // Filter selects hard 1-tap shadows ([ShadowFilterHard]) or 3x3 PCF ([ShadowFilterPCF3x3]). + Filter ShadowFilter + // CasterPadding extends each cascade's orthographic near plane backward along -lightDir by this many world units so tall or off-frustum casters behind the camera still cast shadows into view. Must be >= 0. + CasterPadding float32 + // DebugCascades tints lit surfaces by active cascade (0=red, 1=green, 2=blue, 3=yellow) in [LitPBRCSMWGSL] for inspecting cascade boundaries; [CSMFrame.DebugTint] is its CPU reference. + DebugCascades bool + // MaxCasters is the number of distinct non-identity caster model matrices [CascadedShadowMap.DrawCaster] can hold between two [CascadedShadowMap.Update] calls. A model drawn into several cascades takes one slot. Zero defaults to [DefaultCSMMaxCasters] (256). + MaxCasters int + // Retained opts every GPU buffer, depth atlas, sampler, and pipeline owned by [CascadedShadowMap] into automatic recreation across GPU device loss. + Retained bool +} + +// DefaultCSMConfig returns balanced defaults for cascaded directional shadows. +func DefaultCSMConfig() CSMConfig { + return CSMConfig{ + CascadeCount: DefaultCSMCascadeCount, + Resolution: DefaultCSMResolution, + SplitLambda: DefaultCSMSplitLambda, + DepthBias: DefaultCSMDepthBias, + NormalBias: DefaultCSMNormalBias, + CascadeBlendRange: DefaultCSMCascadeBlendRange, + TexelSnap: true, + Filter: ShadowFilterPCF3x3, + CasterPadding: DefaultCSMCasterPadding, + MaxCasters: DefaultCSMMaxCasters, + } +} + +// Validate checks every field of c and returns an error wrapping [ErrInvalidCSM] if any value is out of range or non-finite. +func (c CSMConfig) Validate() error { + if c.CascadeCount < 0 || c.CascadeCount > MaxCascades { + return fmt.Errorf("%w: CascadeCount %d must be in [0, %d]", ErrInvalidCSM, c.CascadeCount, MaxCascades) + } + if c.Resolution < 0 { + return fmt.Errorf("%w: Resolution %d must be non-negative", ErrInvalidCSM, c.Resolution) + } + if !finite(c.SplitLambda) || c.SplitLambda < 0 || c.SplitLambda > 1 { + return fmt.Errorf("%w: SplitLambda %v must be in [0, 1]", ErrInvalidCSM, c.SplitLambda) + } + if !finite(c.MaxShadowDistance) || c.MaxShadowDistance < 0 { + return fmt.Errorf("%w: MaxShadowDistance %v must be finite and >= 0", ErrInvalidCSM, c.MaxShadowDistance) + } + if !finite(c.DepthBias) || c.DepthBias < 0 { + return fmt.Errorf("%w: DepthBias %v must be finite and >= 0", ErrInvalidCSM, c.DepthBias) + } + if !finite(c.NormalBias) || c.NormalBias < 0 { + return fmt.Errorf("%w: NormalBias %v must be finite and >= 0", ErrInvalidCSM, c.NormalBias) + } + if !finite(c.CascadeBlendRange) || c.CascadeBlendRange < 0 || c.CascadeBlendRange > 0.5 { + return fmt.Errorf("%w: CascadeBlendRange %v must be in [0, 0.5]", ErrInvalidCSM, c.CascadeBlendRange) + } + if !validShadowFilter(c.Filter) { + return fmt.Errorf("%w: unknown filter mode %d", ErrInvalidCSM, c.Filter) + } + if !finite(c.CasterPadding) || c.CasterPadding < 0 { + return fmt.Errorf("%w: CasterPadding %v must be finite and >= 0", ErrInvalidCSM, c.CasterPadding) + } + if c.MaxCasters < 0 { + return fmt.Errorf("%w: MaxCasters %d must be non-negative", ErrInvalidCSM, c.MaxCasters) + } + return nil +} + +func (c CSMConfig) normalize() CSMConfig { + out := c + if out.CascadeCount <= 0 { + out.CascadeCount = DefaultCSMCascadeCount + } + if out.CascadeCount > MaxCascades { + out.CascadeCount = MaxCascades + } + if out.Resolution <= 0 { + out.Resolution = DefaultCSMResolution + } + if !finite(out.SplitLambda) { + out.SplitLambda = DefaultCSMSplitLambda + } else { + out.SplitLambda = math3d.Clamp(out.SplitLambda, 0, 1) + } + if !finite(out.MaxShadowDistance) || out.MaxShadowDistance < 0 { + out.MaxShadowDistance = 0 + } + if !finite(out.DepthBias) || out.DepthBias < 0 { + out.DepthBias = 0 + } + if !finite(out.NormalBias) || out.NormalBias < 0 { + out.NormalBias = 0 + } + if !finite(out.CascadeBlendRange) { + out.CascadeBlendRange = 0 + } else { + out.CascadeBlendRange = math3d.Clamp(out.CascadeBlendRange, 0, 0.5) + } + if !finite(out.CasterPadding) || out.CasterPadding < 0 { + out.CasterPadding = 0 + } + if out.MaxCasters <= 0 { + out.MaxCasters = DefaultCSMMaxCasters + } + return out +} + +func csmAtlasGrid(count int) (cols, rows int) { + switch { + case count <= 1: + return 1, 1 + case count == 2: + return 2, 1 + default: + return 2, 2 + } +} + +// AtlasSize returns the pixel dimensions (width, height) of the 2D depth atlas that packs c's cascades: 1x1 for 1 cascade, 2x1 for 2 cascades, and 2x2 for 3 or 4 cascades. +func (c CSMConfig) AtlasSize() (width, height uint32) { + n := c.normalize() + cols, rows := csmAtlasGrid(n.CascadeCount) + return uint32(n.Resolution * cols), uint32(n.Resolution * rows) +} + +// ComputeCSMSplits computes count+1 view-space split depths [d_0, ..., d_count] spanning [near, far] using the practical split scheme (Zhang et al., 2006): +// +// d_i = lambda * near * (far/near)^(i/count) + (1 - lambda) * (near + (far - near) * i / count) +// +// lambda=0 produces uniform splits; lambda=1 produces logarithmic splits. Returns nil when count <= 0, near <= 0, far <= near, or either bound is non-finite. Non-finite lambda falls back to [DefaultCSMSplitLambda]; out-of-range finite lambda is clamped to [0, 1]. +func ComputeCSMSplits(near, far float32, count int, lambda float32) []float32 { + if count <= 0 || !finite(near) || !finite(far) || near <= 0 || far <= near { + return nil + } + if !finite(lambda) { + lambda = DefaultCSMSplitLambda + } else { + lambda = math3d.Clamp(lambda, 0, 1) + } + splits := make([]float32, count+1) + computeCSMSplitsInto(splits, near, far, count, lambda) + return splits +} + +func computeCSMSplitsInto(dst []float32, near, far float32, count int, lambda float32) { + dst[0] = near + dst[count] = far + if count == 1 { + return + } + n64 := float64(near) + f64 := float64(far) + ratio := f64 / n64 + span := f64 - n64 + lam := float64(lambda) + invCount := 1.0 / float64(count) + for i := 1; i < count; i++ { + p := float64(i) * invCount + logSplit := n64 * math.Pow(ratio, p) + uniSplit := n64 + span*p + dst[i] = float32(lam*logSplit + (1.0-lam)*uniSplit) + } +} + +// CSMCascade holds the fitted light-space projection, depth bounds, atlas tile placement, and bounding sphere of a single shadow cascade. +type CSMCascade struct { + // Near and Far are positive view-space distances covered by this cascade. + Near float32 + Far float32 + // LightView transforms world space into light view space (origin at world 0). + LightView math3d.Mat4 + // LightProj is the orthographic projection mapping light view space into [0, 1] NDC depth. + LightProj math3d.Mat4 + // LightViewProj is LightProj * LightView. + LightViewProj math3d.Mat4 + // AtlasRect is the normalized UV sub-rectangle (u0, v0, uScale, vScale) of this cascade's tile inside the 2D depth atlas. + AtlasRect math3d.Vec4 + // Viewport is [x, y, width, height] in atlas pixels for SetViewport/SetScissor. + Viewport [4]float32 + // TexelSize is the world-space width of one shadow-map texel. + TexelSize float32 + // Center and Radius describe the cascade sub-frustum's bounding sphere in world space. + Center math3d.Vec3 + Radius float32 +} + +// CSMFrame holds the complete per-frame cascade solution computed by [FitCascades] or [FitCascadesFromCamera], ready to upload to a [CascadedShadowMap] via [CascadedShadowMap.Update] or evaluate on the CPU with [EvaluateCSMShadow] and [CSMFrame.DebugTint]. +type CSMFrame struct { + CascadeCount int + Cascades [MaxCascades]CSMCascade + Splits [MaxCascades + 1]float32 + LightDir math3d.Vec3 + MaxShadowDistance float32 + AtlasWidth uint32 + AtlasHeight uint32 + Config CSMConfig +} + +// FitCascades fits directional shadow cascades to the camera frustum defined by camView, camProj (using [0, 1] NDC depth as produced by [math3d.Perspective] and [math3d.Ortho]), and positive view-space clip distances [near, far]. +// +// lightDir is the world-space direction light rays travel (from the directional light toward the scene, e.g. {0.3, -1, -0.4}). It is normalized internally; a zero or non-finite vector falls back to (0, -1, 0). +// +// When cfg.TexelSnap is true, each cascade uses a rotation-invariant bounding sphere quantized to 1/16 world unit and snaps its light-space projection origin to whole shadow-map texel steps, preventing shadow-edge swimming under camera motion. FitCascades performs zero heap allocations. +func FitCascades(camView, camProj math3d.Mat4, near, far float32, lightDir math3d.Vec3, cfg CSMConfig) CSMFrame { + nCfg := cfg.normalize() + count := nCfg.CascadeCount + atlasW, atlasH := nCfg.AtlasSize() + cols, rows := csmAtlasGrid(count) + + // rayNear and rayFar are the view-space distances of camProj's own near and far planes, which parameterise the frustum corner rays below. They can differ from near and far, which only bound the range shadows cover: an orthographic projection may put its near plane at or behind the camera (Near <= 0), while shadows start at a positive depth. + rayNear, rayFar, rayOK := projectionDepthRange(camProj) + if !finite(near) || near <= 0 { + near = 0.1 + } + if !finite(far) || far <= near { + far = near + 100 + } + if !rayOK { + rayNear, rayFar = near, far + } + shadowFar := far + if nCfg.MaxShadowDistance > 0 && nCfg.MaxShadowDistance < shadowFar { + shadowFar = nCfg.MaxShadowDistance + } + if shadowFar <= near { + shadowFar = near + 1 + } + + if !finite3(lightDir) || lightDir.LenSq() < 1e-12 { + lightDir = math3d.Vec3{Y: -1} + } else { + lightDir = lightDir.Norm() + } + + frame := CSMFrame{ + CascadeCount: count, + LightDir: lightDir, + MaxShadowDistance: shadowFar, + AtlasWidth: atlasW, + AtlasHeight: atlasH, + Config: nCfg, + } + computeCSMSplitsInto(frame.Splits[:count+1], near, shadowFar, count, nCfg.SplitLambda) + + // Unproject the 8 corners of the full camera frustum (NDC z=0 near, z=1 far). For any perspective or orthographic frustum, every ray from a near corner to its matching far corner varies linearly with view-space distance d. + invVP, ok := camProj.Mul(camView).Inverse() + if !ok { + invVP = math3d.Mat4Identity() + } + ndcXY := [4][2]float32{ + {-1, -1}, + {1, -1}, + {1, 1}, + {-1, 1}, + } + var fullNear, fullFar [4]math3d.Vec3 + for k := range 4 { + fullNear[k] = invVP.TransformPoint(math3d.Vec3{X: ndcXY[k][0], Y: ndcXY[k][1], Z: 0}) + fullFar[k] = invVP.TransformPoint(math3d.Vec3{X: ndcXY[k][0], Y: ndcXY[k][1], Z: 1}) + } + + // Build a world-anchored light view basis depending only on lightDir so the texel grid remains stable across camera translations and rotations. + lightUp := math3d.Vec3Up() + if absf32(lightDir.Y) > 0.99 { + lightUp = math3d.Vec3{Z: 1} + } + lightBasis := math3d.LookAt(math3d.Vec3Zero(), lightDir, lightUp) + + fullSpan := rayFar - rayNear + resF := float32(nCfg.Resolution) + invCols := float32(1.0) / float32(cols) + invRows := float32(1.0) / float32(rows) + + var corners [8]math3d.Vec3 + for i := range count { + cNear := frame.Splits[i] + cFar := frame.Splits[i+1] + t0 := (cNear - rayNear) / fullSpan + t1 := (cFar - rayNear) / fullSpan + + var center math3d.Vec3 + for k := range 4 { + corners[k] = fullNear[k].Lerp(fullFar[k], t0) + corners[4+k] = fullNear[k].Lerp(fullFar[k], t1) + center = center.Add(corners[k]).Add(corners[4+k]) + } + center = center.Scale(1.0 / 8.0) + + var maxDistSq float32 + for k := range 8 { + dSq := corners[k].Sub(center).LenSq() + if dSq > maxDistSq { + maxDistSq = dSq + } + } + radius := float32(math.Sqrt(float64(maxDistSq))) + if radius < 1e-3 { + radius = 1e-3 + } + + var left, right, bottom, top, minZ, maxZ, texelSize float32 + if nCfg.TexelSnap { + // Reserve 0.5 texel margin so snapping centerLS by up to +/-0.5 texel still strictly encloses every sub-frustum corner, then quantize the half-extent to 1/16 world unit so float rounding never jitters texelSize. + padded := radius + if nCfg.Resolution > 1 { + padded = radius * resF / (resF - 1.0) + } + halfExtent := float32(math.Ceil(float64(padded)*16.0) / 16.0) + texelSize = (2.0 * halfExtent) / resF + + centerLS := lightBasis.TransformPoint(center) + snapX := float32(math.Floor(float64(centerLS.X)/float64(texelSize)+0.5)) * texelSize + snapY := float32(math.Floor(float64(centerLS.Y)/float64(texelSize)+0.5)) * texelSize + snapZ := float32(math.Floor(float64(centerLS.Z)/float64(texelSize)+0.5)) * texelSize + + left = snapX - halfExtent + right = snapX + halfExtent + bottom = snapY - halfExtent + top = snapY + halfExtent + maxZ = snapZ + halfExtent + nCfg.CasterPadding + minZ = snapZ - halfExtent + } else { + minX, maxX := float32(math.Inf(1)), float32(math.Inf(-1)) + minY, maxY := float32(math.Inf(1)), float32(math.Inf(-1)) + minZ, maxZ = float32(math.Inf(1)), float32(math.Inf(-1)) + for k := range 8 { + p := lightBasis.TransformPoint(corners[k]) + if p.X < minX { + minX = p.X + } + if p.X > maxX { + maxX = p.X + } + if p.Y < minY { + minY = p.Y + } + if p.Y > maxY { + maxY = p.Y + } + if p.Z < minZ { + minZ = p.Z + } + if p.Z > maxZ { + maxZ = p.Z + } + } + if maxX-minX < 1e-3 { + mid := 0.5 * (minX + maxX) + minX, maxX = mid-0.5e-3, mid+0.5e-3 + } + if maxY-minY < 1e-3 { + mid := 0.5 * (minY + maxY) + minY, maxY = mid-0.5e-3, mid+0.5e-3 + } + if maxZ-minZ < 1e-3 { + mid := 0.5 * (minZ + maxZ) + minZ, maxZ = mid-0.5e-3, mid+0.5e-3 + } + left, right = minX, maxX + bottom, top = minY, maxY + maxZ += nCfg.CasterPadding + texelSize = max(right-left, top-bottom) / resF + } + + // In right-handed light view space, points closer to the light have larger +Z (since LookAt maps +lightDir to -Z). OrthoZO expects positive-forward near and far distances (-z_view), so near = -maxZ and far = -minZ maps z_view = maxZ (closest to light) -> NDC z = 0 and z_view = minZ -> NDC z = 1. + lightProj := math3d.Ortho(left, right, bottom, top, -maxZ, -minZ) + lightVP := lightProj.Mul(lightBasis) + + col := i % cols + row := i / cols + tileRect := math3d.Vec4{ + X: float32(col) * invCols, + Y: float32(row) * invRows, + Z: invCols, + W: invRows, + } + vp := [4]float32{ + float32(col * nCfg.Resolution), + float32(row * nCfg.Resolution), + resF, + resF, + } + + frame.Cascades[i] = CSMCascade{ + Near: cNear, + Far: cFar, + LightView: lightBasis, + LightProj: lightProj, + LightViewProj: lightVP, + AtlasRect: tileRect, + Viewport: vp, + TexelSize: texelSize, + Center: center, + Radius: radius, + } + } + + return frame +} + +// FitCascadesFromCamera fits cascades to a [scene3d.Camera] with the same near and far planes its [scene3d.Camera.ProjMatrix] uses (the defaults [scene3d.Projection.Matrix] fills in for zero or out-of-range fields included). Shadows cover view depths from max(near, 0.1) to the far plane or [CSMConfig.MaxShadowDistance], so an orthographic camera whose near plane is at or behind it (Near <= 0) is shadowed from 0.1 on. When cam is nil, a default perspective camera at the origin looking down -Z is used. lightDir is the world-space direction light rays travel; with [LitPBRCSMWGSL] pass the Direction of the [LightRig]'s first directional light, the one the cascades shadow. +func FitCascadesFromCamera(cam *scene3d.Camera, lightDir math3d.Vec3, cfg CSMConfig) CSMFrame { + if cam == nil { + cam = scene3d.NewPerspectiveCamera(math3d.Vec3Zero(), math3d.DegToRad(60), 1, 0.1, 100) + } + near, far := cameraDepthRange(cam.Projection) + return FitCascades(cam.ViewMatrix(), cam.ProjMatrix(), near, far, lightDir, cfg) +} + +// cameraDepthRange returns the near and far planes [scene3d.Projection.Matrix] uses for p. +func cameraDepthRange(p scene3d.Projection) (near, far float32) { + near, far = p.Near, p.Far + if p.Kind == scene3d.ProjectionOrthographic { + if near == 0 && far == 0 { + return 0.1, 1000 + } + } else if near <= 0 { + near = 0.1 + } + if far <= near { + far = near + 1000 + } + return near, far +} + +// projectionDepthRange returns the positive-forward view-space distances of proj's near (NDC z = 0) and far (NDC z = 1) planes along the view axis, and false when proj is singular or the planes are not finite and ordered. +func projectionDepthRange(proj math3d.Mat4) (near, far float32, ok bool) { + inv, ok := proj.Inverse() + if !ok { + return 0, 0, false + } + n := inv.TransformPoint(math3d.Vec3{}) + f := inv.TransformPoint(math3d.Vec3{Z: 1}) + near, far = -n.Z, -f.Z + if !finite(near) || !finite(far) || far <= near { + return 0, 0, false + } + return near, far, true +} + +// SelectCascade returns the primary cascade index for a positive camera view-space depth, along with the next cascade index (or -1 if none / fading out past the final cascade) and blend factor in [0, 1]. +// +// When viewDepth <= 0 or viewDepth >= f.MaxShadowDistance (or f.CascadeCount <= 0), SelectCascade returns (-1, -1, 0). +func (f *CSMFrame) SelectCascade(viewDepth float32) (index int, nextIndex int, blend float32) { + if f == nil || f.CascadeCount <= 0 || viewDepth <= 0 || viewDepth >= f.MaxShadowDistance { + return -1, -1, 0 + } + count := min(f.CascadeCount, MaxCascades) + idx := count - 1 + for i := range count { + if viewDepth <= f.Cascades[i].Far { + idx = i + break + } + } + blendFrac := f.Config.CascadeBlendRange + if blendFrac <= 0 { + return idx, -1, 0 + } + cNear := f.Cascades[idx].Near + cFar := f.Cascades[idx].Far + span := max(cFar-cNear, float32(1e-4)) + blendDist := span * blendFrac + blendStart := cFar - blendDist + if viewDepth <= blendStart { + return idx, -1, 0 + } + t := math3d.Clamp((viewDepth-blendStart)/max(blendDist, float32(1e-4)), 0, 1) + if idx+1 < count { + return idx, idx + 1, t + } + // Last cascade smoothly fades out toward 1.0 (unshadowed) at MaxShadowDistance. + return idx, -1, t +} + +// EncodeUniforms writes f into dst as the little-endian [CSMUniformSize]-byte uniform block matching [CSMWGSL]'s CSMUniforms struct and returns dst[:CSMUniformSize]. It panics if len(dst) < [CSMUniformSize]. It makes zero heap allocations. +func (f *CSMFrame) EncodeUniforms(dst []byte) []byte { + if len(dst) < CSMUniformSize { + panic("render3d: CSMFrame.EncodeUniforms: dst shorter than CSMUniformSize") + } + dst = dst[:CSMUniformSize] + off := 0 + put := func(v float32) { + binary.LittleEndian.PutUint32(dst[off:], math.Float32bits(v)) + off += 4 + } + putMat4 := func(m *math3d.Mat4) { + for _, v := range m { + put(v) + } + } + putVec4 := func(v math3d.Vec4) { + put(v.X) + put(v.Y) + put(v.Z) + put(v.W) + } + + count := min(max(f.CascadeCount, 1), MaxCascades) + baseTexel := f.Cascades[0].TexelSize + if baseTexel < 1e-4 { + baseTexel = 1e-4 + } + + // 4 x light_vp (256 bytes) + for i := range MaxCascades { + src := min(i, count-1) + putMat4(&f.Cascades[src].LightViewProj) + } + // 4 x atlas_rect (64 bytes) + for i := range MaxCascades { + src := min(i, count-1) + putVec4(f.Cascades[src].AtlasRect) + } + // splits (far depths, 16 bytes) + for i := range MaxCascades { + src := min(i, count-1) + put(f.Cascades[src].Far) + } + // split_near (near depths, 16 bytes) + for i := range MaxCascades { + src := min(i, count-1) + put(f.Cascades[src].Near) + } + // light_dir (xyz = unit travel dir, w = max_shadow_distance, 16 bytes) + put(f.LightDir.X) + put(f.LightDir.Y) + put(f.LightDir.Z) + put(f.MaxShadowDistance) + // bias_params (x = depth_bias, y = normal_bias, z = blend_range, w = cascade_count, 16 bytes) + put(f.Config.DepthBias) + put(f.Config.NormalBias) + put(f.Config.CascadeBlendRange) + put(float32(count)) + // atlas_params (x = 1/atlasW, y = 1/atlasH, z = filter_mode, w = debug_mode, 16 bytes) + invW := float32(0) + invH := float32(0) + if f.AtlasWidth > 0 { + invW = 1.0 / float32(f.AtlasWidth) + } + if f.AtlasHeight > 0 { + invH = 1.0 / float32(f.AtlasHeight) + } + filterF := float32(0) + if f.Config.Filter == ShadowFilterPCF3x3 { + filterF = 1 + } + debugF := float32(0) + if f.Config.DebugCascades { + debugF = 1 + } + put(invW) + put(invH) + put(filterF) + put(debugF) + // cascade_scales (relative texel size per cascade for normal bias scaling, 16 bytes) + for i := range MaxCascades { + src := min(i, count-1) + scale := f.Cascades[src].TexelSize / baseTexel + if scale < 1 { + scale = 1 + } + put(scale) + } + return dst +} + +// CSMDepthWGSL is the depth-only vertex shader used by [CascadedShadowMap] to rasterize shadow casters into a cascade tile of the 2D depth atlas. +// +// Bind groups: +// - @group(0) @binding(0): CSMCascadeUniform (light_view_proj: mat4x4) +// - @group(1) @binding(0): CSMModelUniform (world: mat4x4) +// +// Vertex buffer 0 matches [MeshVertexLayout]. +const CSMDepthWGSL = `struct CSMCascadeUniform { + light_view_proj: mat4x4, +} + +struct CSMModelUniform { + world: mat4x4, +} + +@group(0) @binding(0) var csm_cascade: CSMCascadeUniform; +@group(1) @binding(0) var csm_model: CSMModelUniform; + +struct CSMDepthIn { + @location(0) pos: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, +} + +@vertex +fn vs_csm_depth(in: CSMDepthIn) -> @builtin(position) vec4 { + let world_pos = csm_model.world * vec4(in.pos, 1.0); + return csm_cascade.light_view_proj * world_pos; +} +` + +// csmStructWGSL declares the CSMUniforms block shared by [CSMWGSL] and [CSMWGSLForGroup]. +const csmStructWGSL = `struct CSMUniforms { + light_vp0: mat4x4, + light_vp1: mat4x4, + light_vp2: mat4x4, + light_vp3: mat4x4, + atlas_rect0: vec4, + atlas_rect1: vec4, + atlas_rect2: vec4, + atlas_rect3: vec4, + splits: vec4, + split_near: vec4, + light_dir: vec4, + bias_params: vec4, + atlas_params: vec4, + cascade_scales: vec4, +} +` + +// csmSampleFnWGSL holds the cascade selection and sampling helpers shared by [CSMWGSL] and [CSMWGSLForGroup]. +const csmSampleFnWGSL = ` +fn csm_sample_cascade(idx: i32, world_pos: vec3, world_normal: vec3, ndotl: f32) -> f32 { + var light_vp: mat4x4; + var rect: vec4; + var nscale: f32; + if (idx == 0) { + light_vp = csm.light_vp0; + rect = csm.atlas_rect0; + nscale = csm.cascade_scales.x; + } else if (idx == 1) { + light_vp = csm.light_vp1; + rect = csm.atlas_rect1; + nscale = csm.cascade_scales.y; + } else if (idx == 2) { + light_vp = csm.light_vp2; + rect = csm.atlas_rect2; + nscale = csm.cascade_scales.z; + } else { + light_vp = csm.light_vp3; + rect = csm.atlas_rect3; + nscale = csm.cascade_scales.w; + } + + let biased_pos = world_pos + world_normal * (csm.bias_params.y * nscale); + let clip = light_vp * vec4(biased_pos, 1.0); + let ndc = clip.xyz / clip.w; + let local_uv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); + + if (local_uv.x < 0.0 || local_uv.x > 1.0 || local_uv.y < 0.0 || local_uv.y > 1.0 || ndc.z < 0.0 || ndc.z > 1.0) { + return 1.0; + } + + let bias = csm.bias_params.x * (2.0 - ndotl); + let cmp_depth = clamp(ndc.z - bias, 0.0, 1.0); + + let texel = csm.atlas_params.xy; + let uv_min = rect.xy + texel * 0.501; + let uv_max = rect.xy + rect.zw - texel * 0.501; + let base_uv = rect.xy + local_uv * rect.zw; + + if (csm.atlas_params.z < 0.5) { + let suv = clamp(base_uv, uv_min, uv_max); + return textureSampleCompareLevel(csm_shadow_map, csm_shadow_sampler, suv, cmp_depth); + } + + var sum: f32 = 0.0; + for (var dy: i32 = -1; dy <= 1; dy = dy + 1) { + for (var dx: i32 = -1; dx <= 1; dx = dx + 1) { + let off = vec2(f32(dx) * texel.x, f32(dy) * texel.y); + let suv = clamp(base_uv + off, uv_min, uv_max); + sum = sum + textureSampleCompareLevel(csm_shadow_map, csm_shadow_sampler, suv, cmp_depth); + } + } + return sum * (1.0 / 9.0); +} + +fn csm_select_cascade(view_depth: f32) -> i32 { + let count = i32(csm.bias_params.w + 0.5); + if (view_depth <= csm.splits.x || count <= 1) { + return 0; + } + if (view_depth <= csm.splits.y || count == 2) { + return 1; + } + if (view_depth <= csm.splits.z || count == 3) { + return 2; + } + return 3; +} + +fn csm_shadow_factor(world_pos: vec3, world_normal: vec3, view_depth: f32) -> f32 { + let max_dist = csm.light_dir.w; + if (view_depth <= 0.0 || view_depth >= max_dist) { + return 1.0; + } + let count = i32(csm.bias_params.w + 0.5); + let ndotl = clamp(dot(world_normal, -csm.light_dir.xyz), 0.0, 1.0); + let idx = csm_select_cascade(view_depth); + + var c_near: f32 = csm.split_near.w; + var c_far: f32 = csm.splits.w; + if (idx == 0) { + c_near = csm.split_near.x; + c_far = csm.splits.x; + } else if (idx == 1) { + c_near = csm.split_near.y; + c_far = csm.splits.y; + } else if (idx == 2) { + c_near = csm.split_near.z; + c_far = csm.splits.z; + } + + var vis = csm_sample_cascade(idx, world_pos, world_normal, ndotl); + let blend_frac = csm.bias_params.z; + if (blend_frac > 0.0) { + let span = max(c_far - c_near, 0.0001); + let blend_dist = span * blend_frac; + let blend_start = c_far - blend_dist; + if (view_depth > blend_start) { + let t = clamp((view_depth - blend_start) / max(blend_dist, 0.0001), 0.0, 1.0); + if (idx + 1 < count) { + let next_vis = csm_sample_cascade(idx + 1, world_pos, world_normal, ndotl); + vis = mix(vis, next_vis, t); + } else { + vis = mix(vis, 1.0, t); + } + } + } + return vis; +} + +fn csm_cascade_tint(idx: i32) -> vec3 { + if (idx == 0) { + return vec3(1.0, 0.35, 0.35); + } + if (idx == 1) { + return vec3(0.35, 1.0, 0.35); + } + if (idx == 2) { + return vec3(0.35, 0.55, 1.0); + } + return vec3(1.0, 0.9, 0.35); +} + +fn csm_view_depth(world_pos: vec3) -> f32 { + return -(camera.view * vec4(world_pos, 1.0)).z; +} + +fn sample_csm_shadow(world_pos: vec3, world_normal: vec3) -> f32 { + var n = vec3(0.0, 1.0, 0.0); + let n_len = length(world_normal); + if (n_len > 0.000001) { + n = world_normal / n_len; + } + return csm_shadow_factor(world_pos, n, csm_view_depth(world_pos)); +} + +fn csm_debug_tint(world_pos: vec3) -> vec3 { + let view_depth = csm_view_depth(world_pos); + if (csm.atlas_params.w < 0.5 || view_depth <= 0.0 || view_depth >= csm.light_dir.w) { + return vec3(1.0, 1.0, 1.0); + } + return mix(vec3(1.0, 1.0, 1.0), csm_cascade_tint(csm_select_cascade(view_depth)), 0.55); +} +` + +// CSMWGSL declares the cascaded shadow map uniform block, 2D depth atlas and comparison sampler at [CSMGroup] (@group(3)), and portable helpers for sampling them with optional 3x3 PCF, smooth inter-cascade blending, a fade toward [CSMConfig.MaxShadowDistance] and optional debug cascade tinting. It equals CSMWGSLForGroup(CSMGroup). +// +// The helpers read the camera's view matrix, so prepend [CameraWGSL] first. sample_csm_shadow(world_pos, world_normal) returns the visibility in [0, 1] of the light the cascades were fitted to, like sample_directional_shadow in [ShadowWGSL]: pass it as the shadow_vis of shade_pbr_shadowed in [LightWGSL] to shadow the [LightRig]'s first directional light. csm_shadow_factor(world_pos, unit_normal, view_depth) takes the view depth directly, and csm_debug_tint(world_pos) returns the per-cascade color multiplier [CSMConfig.DebugCascades] enables (white when it is off). [LitPBRCSMWGSL] is the ready-made PBR shader built on it. +// +// It uses only algebraic WGSL operations and textureSampleCompareLevel (no exp, exp2, log2 or texture_depth_2d_array), so it runs identically on Metal, Direct3D 11, OpenGL 3.3, WebGPU, WebGL 2, OpenGL ES 3.0 and the software GPU renderer. +const CSMWGSL = csmStructWGSL + ` +@group(3) @binding(0) var csm: CSMUniforms; +@group(3) @binding(1) var csm_shadow_map: texture_depth_2d; +@group(3) @binding(2) var csm_shadow_sampler: sampler_comparison; +` + csmSampleFnWGSL + +// CSMWGSLForGroup returns [CSMWGSL] with its bindings placed at @group(group) instead of [CSMGroup], for custom shaders whose group 3 already holds something else. +func CSMWGSLForGroup(group uint32) string { + return fmt.Sprintf(`%s +@group(%[2]d) @binding(0) var csm: CSMUniforms; +@group(%[2]d) @binding(1) var csm_shadow_map: texture_depth_2d; +@group(%[2]d) @binding(2) var csm_shadow_sampler: sampler_comparison; +%[3]s`, csmStructWGSL, group, csmSampleFnWGSL) +} + +// LitPBRCSMWGSL is [LitPBRWGSL] with cascaded directional shadows: the same vertex stage, bind groups [CameraGroup], [LightGroup] and [PBRDrawGroup], and lighting, plus [CSMWGSL] at [CSMGroup]. The fragment stage multiplies the first directional light of the [LightRig] (lights.directional[0]) by sample_csm_shadow and the lit color by csm_debug_tint before encoding to sRGB; every other light, the ambient term and emission are unshadowed. [ShadePointShadowed] with [EvaluateCSMShadow] as the visibility, times [CSMFrame.DebugTint], is its CPU reference. Fit the cascades with that light's Direction. Use [NewLitPBRCSMPipeline] or [LitPBRPipelineOptions].CSMLayout to create a pipeline from it. +const LitPBRCSMWGSL = litPBRPreludeWGSL + CSMWGSL + litPBRCSMFragmentHeadWGSL + ` return vec4(linear_to_srgb(lit), pbr_draw.base_color.a); +} +` + +// litPBRCSMLinearWGSL is [LitPBRCSMWGSL] writing the lit linear color without sRGB encoding, compiled by [NewLitPBRPipelineWithOptions] when [LitPBRPipelineOptions].LinearOutput and CSMLayout are set. +const litPBRCSMLinearWGSL = litPBRPreludeWGSL + CSMWGSL + litPBRCSMFragmentHeadWGSL + ` return vec4(lit, pbr_draw.base_color.a); +} +` + +// litPBRCSMFragmentHeadWGSL opens fs_main for the cascaded-shadow lit PBR shaders and computes the lit linear color lit with directional light 0 attenuated by the cascades. +const litPBRCSMFragmentHeadWGSL = ` +@fragment +fn fs_main(in: PBRVertexOut) -> @location(0) vec4 { + let view_dir = normalize(camera.eye.xyz - in.world_pos * camera.eye.w); + let shadow_vis = sample_csm_shadow(in.world_pos, in.world_normal); + let lit = (shade_pbr_shadowed( + in.world_pos, + in.world_normal, + view_dir, + pbr_draw.base_color.rgb, + pbr_draw.pbr_params.x, + pbr_draw.pbr_params.y, + shadow_vis, + ) + pbr_draw.emissive.rgb) * csm_debug_tint(in.world_pos); +` + +// NewLitPBRCSMPipeline compiles [LitPBRCSMWGSL] and creates a pipeline configured like [NewLitPBRPipeline] with csmLayout ([CascadedShadowMap.Layout]) added at [CSMGroup]. +func NewLitPBRCSMPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, csmLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error) { + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + if csmLayout == nil { + return nil, gpu.Error{Code: gpu.ErrInvalidDescriptor, Message: "render3d: NewLitPBRCSMPipeline requires a cascaded shadow map bind group layout"} + } + return NewLitPBRPipelineWithOptions(cx, dev, camLayout, lightLayout, drawLayout, LitPBRPipelineOptions{CSMLayout: csmLayout, DepthFormat: depthFormat}) +} + +// CSMDepthAtlas holds a CPU copy of a 2D float32 shadow depth atlas (row-major, top-left origin, depth values in [0, 1]) for pure-Go reference evaluation via [EvaluateCSMShadow]. +type CSMDepthAtlas struct { + Width int + Height int + Depth []float32 +} + +func (a CSMDepthAtlas) sampleCompare(u, v, cmpDepth float32, linear bool) float32 { + if a.Width <= 0 || a.Height <= 0 || len(a.Depth) < a.Width*a.Height { + return 1.0 + } + u = math3d.Clamp(u, 0, 1) + v = math3d.Clamp(v, 0, 1) + w, h := a.Width, a.Height + cmpTexel := func(x, y int) float32 { + x = min(max(x, 0), w-1) + y = min(max(y, 0), h-1) + if cmpDepth <= a.Depth[y*w+x] { + return 1.0 + } + return 0.0 + } + if linear { + fx := u*float32(w) - 0.5 + fy := v*float32(h) - 0.5 + x0 := int(math.Floor(float64(fx))) + y0 := int(math.Floor(float64(fy))) + tx := fx - float32(x0) + ty := fy - float32(y0) + c00 := cmpTexel(x0, y0) + c10 := cmpTexel(x0+1, y0) + c01 := cmpTexel(x0, y0+1) + c11 := cmpTexel(x0+1, y0+1) + top := c00*(1-tx) + c10*tx + bot := c01*(1-tx) + c11*tx + return top*(1-ty) + bot*ty + } + ix := int(math.Floor(float64(u * float32(w)))) + iy := int(math.Floor(float64(v * float32(h)))) + return cmpTexel(ix, iy) +} + +func evaluateCSMCascade(frame *CSMFrame, atlas CSMDepthAtlas, idx int, worldPos, worldNormal math3d.Vec3, ndotl float32) float32 { + c := &frame.Cascades[idx] + baseTexel := frame.Cascades[0].TexelSize + if baseTexel < 1e-4 { + baseTexel = 1e-4 + } + nscale := c.TexelSize / baseTexel + if nscale < 1 { + nscale = 1 + } + + biasedPos := worldPos.Add(worldNormal.Scale(frame.Config.NormalBias * nscale)) + clip := c.LightViewProj.MulVec4(biasedPos.Vec4(1)) + if clip.W == 0 { + return 1.0 + } + invW := 1.0 / clip.W + ndcX := clip.X * invW + ndcY := clip.Y * invW + ndcZ := clip.Z * invW + localU := ndcX*0.5 + 0.5 + localV := 0.5 - ndcY*0.5 + + if localU < 0 || localU > 1 || localV < 0 || localV > 1 || ndcZ < 0 || ndcZ > 1 { + return 1.0 + } + + bias := frame.Config.DepthBias * (2.0 - ndotl) + cmpDepth := math3d.Clamp(ndcZ-bias, 0, 1) + + texelU := float32(1.0) / float32(max(int(frame.AtlasWidth), 1)) + texelV := float32(1.0) / float32(max(int(frame.AtlasHeight), 1)) + rect := c.AtlasRect + uvMinU := rect.X + texelU*0.501 + uvMinV := rect.Y + texelV*0.501 + uvMaxU := rect.X + rect.Z - texelU*0.501 + uvMaxV := rect.Y + rect.W - texelV*0.501 + baseU := rect.X + localU*rect.Z + baseV := rect.Y + localV*rect.W + + if frame.Config.Filter == ShadowFilterHard { + su := math3d.Clamp(baseU, uvMinU, uvMaxU) + sv := math3d.Clamp(baseV, uvMinV, uvMaxV) + return atlas.sampleCompare(su, sv, cmpDepth, false) + } + + var sum float32 + for dy := -1; dy <= 1; dy++ { + for dx := -1; dx <= 1; dx++ { + su := math3d.Clamp(baseU+float32(dx)*texelU, uvMinU, uvMaxU) + sv := math3d.Clamp(baseV+float32(dy)*texelV, uvMinV, uvMaxV) + sum += atlas.sampleCompare(su, sv, cmpDepth, true) + } + } + return sum * (1.0 / 9.0) +} + +// EvaluateCSMShadow is the pure-Go CPU reference matching csm_shadow_factor in [CSMWGSL]. It returns the shadow visibility factor in [0, 1] (0 = fully in shadow, 1 = fully lit) for a world-space surface point, unit world normal, and positive camera view-space depth. +func EvaluateCSMShadow(frame CSMFrame, atlas CSMDepthAtlas, worldPos, worldNormal math3d.Vec3, viewDepth float32) float32 { + if frame.CascadeCount <= 0 || viewDepth <= 0 || viewDepth >= frame.MaxShadowDistance { + return 1.0 + } + if worldNormal.LenSq() > 1e-12 { + worldNormal = worldNormal.Norm() + } + ndotl := math3d.Clamp(worldNormal.Dot(frame.LightDir.Neg()), 0, 1) + idx, nextIdx, blend := frame.SelectCascade(viewDepth) + if idx < 0 { + return 1.0 + } + vis := evaluateCSMCascade(&frame, atlas, idx, worldPos, worldNormal, ndotl) + if blend > 0 { + if nextIdx >= 0 { + nextVis := evaluateCSMCascade(&frame, atlas, nextIdx, worldPos, worldNormal, ndotl) + vis = math3d.Lerp(vis, nextVis, blend) + } else { + vis = math3d.Lerp(vis, 1.0, blend) + } + } + return vis +} + +// DebugTint returns the color multiplier csm_debug_tint in [CSMWGSL] applies at a positive camera view depth: white (1, 1, 1) when [CSMConfig.DebugCascades] is off or viewDepth is outside the shadowed range, otherwise the active cascade's tint (0 red, 1 green, 2 blue, 3 yellow) mixed 55% into white. +func (f *CSMFrame) DebugTint(viewDepth float32) math3d.Vec3 { + white := math3d.Vec3{X: 1, Y: 1, Z: 1} + if f == nil || !f.Config.DebugCascades || viewDepth <= 0 || viewDepth >= f.MaxShadowDistance { + return white + } + idx, _, _ := f.SelectCascade(viewDepth) + if idx < 0 { + return white + } + t := csmCascadeTint(idx) + return math3d.Vec3{X: math3d.Lerp(1, t[0], 0.55), Y: math3d.Lerp(1, t[1], 0.55), Z: math3d.Lerp(1, t[2], 0.55)} +} + +func csmCascadeTint(idx int) [3]float32 { + switch idx { + case 0: + return [3]float32{1.0, 0.35, 0.35} + case 1: + return [3]float32{0.35, 1.0, 0.35} + case 2: + return [3]float32{0.35, 0.55, 1.0} + default: + return [3]float32{1.0, 0.9, 0.35} + } +} + +// RenderPassStarter is satisfied by both [*gpu.Encoder] and [*gpu.Frame], allowing [CascadedShadowMap.BeginCascadePass] to record depth passes both on a standalone [gpu.SoftwareRenderer] encoder and inside [gpu.ViewProps.OnFrame]. +type RenderPassStarter interface { + BeginRenderPass(desc gpu.RenderPassDesc) *gpu.RenderPass +} + +// CascadedShadowMap owns the portable 2D [gpu.FormatDepth32Float] depth atlas, comparison sampler, uniform buffers, bind groups, and depth-only caster pipeline for directional cascaded shadow maps on an NSGo [gpu.Device]. +// +// Typical per-frame usage: +// +// frame := render3d.FitCascadesFromCamera(cam, rig.Directional[0].Direction, csm.Config()) +// _ = csm.Update(dev, frame) +// for i := range csm.CascadeCount() { +// if pass := csm.BeginCascadePass(enc, i); pass != nil { +// csm.DrawCaster(pass, mesh, modelMat) +// pass.End() +// } +// } +// // Then in the main lit pass, with a pipeline from NewLitPBRCSMPipeline: +// mainPass.SetBindGroup(render3d.CSMGroup, csm.BindGroup()) +type CascadedShadowMap struct { + dev *gpu.Device + cfg CSMConfig + + rt *gpu.RenderTarget + sampler *gpu.Sampler + + uniformBuf *gpu.Buffer + layout *gpu.BindGroupLayout + group *gpu.BindGroup + + cascadeLayout *gpu.BindGroupLayout + cascadeBufs [MaxCascades]*gpu.Buffer + cascadeGroups [MaxCascades]*gpu.BindGroup + + casterLayout *gpu.BindGroupLayout + casterBuf *gpu.Buffer + casterGroup *gpu.BindGroup + casterStride uint64 + maxCasters int + casterSlot int + casterSlots map[math3d.Mat4]uint32 + + depthPipe *gpu.Pipeline + + frame CSMFrame + atlasCleared bool + + uniformScratch [CSMUniformSize]byte + matScratch [64]byte +} + +// NewCascadedShadowMap validates cfg and allocates the 2D depth atlas, comparison sampler, uniform buffers, bind groups, and depth-only caster pipeline on dev, scoped to cx. +// +// Invalid configuration returns an error wrapping [ErrInvalidCSM] before any GPU resource is created. A nil or lost device returns [gpu.ErrDeviceLost]. +func NewCascadedShadowMap(cx *core.Scope, dev *gpu.Device, cfg CSMConfig) (*CascadedShadowMap, error) { + if err := cfg.Validate(); err != nil { + return nil, err + } + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + nCfg := cfg.normalize() + atlasW, atlasH := nCfg.AtlasSize() + if lim := dev.Limits().MaxTextureDimension2D; lim > 0 && (atlasW > lim || atlasH > lim) { + return nil, fmt.Errorf("%w: atlas size %dx%d exceeds device MaxTextureDimension2D %d", ErrInvalidCSM, atlasW, atlasH, lim) + } + + label := nCfg.Label + if label == "" { + label = "render3d.csm" + } + + c := &CascadedShadowMap{ + dev: dev, + cfg: nCfg, + maxCasters: nCfg.MaxCasters, + casterSlot: 1, + casterSlots: make(map[math3d.Mat4]uint32), + } + cleanup := func() { + _ = c.Close() + } + + var err error + c.rt, err = dev.CreateRenderTarget(cx, gpu.RenderTargetDesc{ + Label: label + " depth atlas", + Width: atlasW, + Height: atlasH, + DepthFormat: gpu.FormatDepth32Float, + Retained: nCfg.Retained, + }) + if err != nil { + cleanup() + return nil, err + } + + filter := gpu.FilterNearest + if nCfg.Filter == ShadowFilterPCF3x3 { + filter = gpu.FilterLinear + } + c.sampler, err = dev.CreateSampler(cx, gpu.SamplerDesc{ + Label: label + " compare sampler", + MinFilter: filter, + MagFilter: filter, + AddressU: gpu.AddressClampToEdge, + AddressV: gpu.AddressClampToEdge, + AddressW: gpu.AddressClampToEdge, + Compare: gpu.CompareLessEqual, + Retained: nCfg.Retained, + }) + if err != nil { + cleanup() + return nil, err + } + + c.uniformBuf, err = dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + " uniforms", + Size: CSMUniformSize, + Usage: gpu.UsageUniform | gpu.UsageCopyDst, + Retained: nCfg.Retained, + }) + if err != nil { + cleanup() + return nil, err + } + + c.layout, err = dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{ + Label: label + " layout", + Entries: []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageVertex | gpu.StageFragment, Type: gpu.BindingUniform}, + {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 2, Visibility: gpu.StageFragment, Type: gpu.BindingComparisonSampler}, + }, + }) + if err != nil { + cleanup() + return nil, err + } + + c.group, err = dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{ + Label: label + " group", + Layout: c.layout, + Entries: []gpu.BindGroupEntry{ + {Binding: 0, Buffer: c.uniformBuf, Size: CSMUniformSize}, + {Binding: 1, Texture: c.rt.Depth}, + {Binding: 2, Sampler: c.sampler}, + }, + }) + if err != nil { + cleanup() + return nil, err + } + + c.cascadeLayout, err = dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{ + Label: label + " cascade layout", + Entries: []gpu.BindGroupLayoutEntry{{ + Binding: 0, + Visibility: gpu.StageVertex, + Type: gpu.BindingUniform, + }}, + }) + if err != nil { + cleanup() + return nil, err + } + + identBytes := make([]byte, 64) + encodeMat4Into(identBytes, math3d.Mat4Identity()) + for i := range nCfg.CascadeCount { + c.cascadeBufs[i], err = dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: fmt.Sprintf("%s cascade %d", label, i), + Usage: gpu.UsageUniform | gpu.UsageCopyDst, + Data: identBytes, + Retained: nCfg.Retained, + }) + if err != nil { + cleanup() + return nil, err + } + c.cascadeGroups[i], err = dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{ + Label: fmt.Sprintf("%s cascade %d group", label, i), + Layout: c.cascadeLayout, + Entries: []gpu.BindGroupEntry{{Binding: 0, Buffer: c.cascadeBufs[i], Size: 64}}, + }) + if err != nil { + cleanup() + return nil, err + } + } + + align := uint64(dev.Limits().MinUniformBufferAlignment) + if align < 64 { + align = 256 + } + c.casterStride = ((64 + align - 1) / align) * align + casterBytes := make([]byte, c.casterStride*uint64(c.maxCasters)) + // Slot 0 is permanently Identity so world-space casters need zero writes. + encodeMat4Into(casterBytes[:64], math3d.Mat4Identity()) + + c.casterBuf, err = dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + " caster models", + Usage: gpu.UsageUniform | gpu.UsageCopyDst, + Data: casterBytes, + Retained: nCfg.Retained, + }) + if err != nil { + cleanup() + return nil, err + } + + c.casterLayout, err = dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{ + Label: label + " caster model layout", + Entries: []gpu.BindGroupLayoutEntry{{ + Binding: 0, + Visibility: gpu.StageVertex, + Type: gpu.BindingUniform, + HasDynamicOffset: true, + }}, + }) + if err != nil { + cleanup() + return nil, err + } + + c.casterGroup, err = dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{ + Label: label + " caster model group", + Layout: c.casterLayout, + Entries: []gpu.BindGroupEntry{{Binding: 0, Buffer: c.casterBuf, Size: 64}}, + }) + if err != nil { + cleanup() + return nil, err + } + + depthMod, err := gpu.CompileWGSL(CSMDepthWGSL) + if err != nil { + cleanup() + return nil, err + } + c.depthPipe, err = dev.CreatePipeline(cx, gpu.PipelineDesc{ + Label: label + " depth pipeline", + Layouts: []*gpu.BindGroupLayout{c.cascadeLayout, c.casterLayout}, + Vertex: gpu.ShaderStage{Module: depthMod, EntryPoint: "vs_csm_depth"}, + VertexBuffers: []gpu.VertexBufferLayout{MeshVertexLayout()}, + Primitive: gpu.PrimitiveState{ + Topology: gpu.TopologyTriangleList, + FrontFace: gpu.FrontCCW, + CullMode: gpu.CullNone, + }, + DepthStencil: &gpu.DepthStencilState{ + Format: gpu.FormatDepth32Float, + DepthWrite: true, + DepthCompare: gpu.CompareLess, + }, + Retained: nCfg.Retained, + }) + if err != nil { + cleanup() + return nil, err + } + + // Populate a valid initial frame so the uniform buffer starts well-defined. + c.frame = FitCascades(math3d.Mat4Identity(), math3d.Perspective(math3d.DegToRad(60), 1, 0.1, 100), 0.1, 100, math3d.Vec3{Y: -1}, nCfg) + dev.WriteBuffer(c.uniformBuf, 0, c.frame.EncodeUniforms(c.uniformScratch[:])) + return c, nil +} + +// Update uploads frame's cascade matrices, split distances, atlas rects and shading parameters onto dev with zero heap allocations, and frees every caster slot [CascadedShadowMap.DrawCaster] took since the last Update. Call it once per frame before [CascadedShadowMap.BeginCascadePass]. +// +// frame must be fitted with c's cascade count, resolution and filter ([CascadedShadowMap.Config]), because its atlas tiles, viewports, texel size and filter mode index c's atlas and sampler; any other frame returns an error wrapping [ErrInvalidCSM] and leaves c unchanged. The other [CSMConfig] fields (splits, biases, blend range, padding, debug tint) may change from frame to frame. +func (c *CascadedShadowMap) Update(dev *gpu.Device, frame CSMFrame) error { + if c == nil || !c.Valid() { + return fmt.Errorf("%w: cascaded shadow map is not valid", ErrInvalidCSM) + } + if dev == nil { + return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + if frame.CascadeCount != c.cfg.CascadeCount || frame.Config.CascadeCount != c.cfg.CascadeCount { + return fmt.Errorf("%w: frame cascade count %d does not match the atlas cascade count %d", ErrInvalidCSM, frame.CascadeCount, c.cfg.CascadeCount) + } + if frame.Config.Resolution != c.cfg.Resolution || frame.AtlasWidth != c.rt.Width || frame.AtlasHeight != c.rt.Height { + return fmt.Errorf("%w: frame resolution %d (atlas %dx%d) does not match the atlas resolution %d (%dx%d)", ErrInvalidCSM, frame.Config.Resolution, frame.AtlasWidth, frame.AtlasHeight, c.cfg.Resolution, c.rt.Width, c.rt.Height) + } + if frame.Config.Filter != c.cfg.Filter { + return fmt.Errorf("%w: frame filter %v does not match the atlas sampler's filter %v", ErrInvalidCSM, frame.Config.Filter, c.cfg.Filter) + } + c.dev = dev + c.frame = frame + c.casterSlot = 1 + clear(c.casterSlots) + c.atlasCleared = false + + dev.WriteBuffer(c.uniformBuf, 0, c.frame.EncodeUniforms(c.uniformScratch[:])) + for i := range frame.CascadeCount { + encodeMat4Into(c.matScratch[:], frame.Cascades[i].LightViewProj) + dev.WriteBuffer(c.cascadeBufs[i], 0, c.matScratch[:]) + } + return nil +} + +// BeginCascadePass starts a depth-only render pass targeting cascadeIdx's tile in the 2D depth atlas, sets the tile viewport and scissor rectangle, binds the depth-only caster pipeline, and binds cascadeIdx's light view-projection at group 0. +// +// The first cascade pass after [CascadedShadowMap.Update], whichever cascade it is, clears the whole depth atlas to 1.0 (a clear is not limited by the scissor); every later pass keeps the tiles already drawn with [gpu.LoadLoad]. Render every cascade after each Update, in any order. Returns nil when c, enc, or cascadeIdx is invalid. +func (c *CascadedShadowMap) BeginCascadePass(enc RenderPassStarter, cascadeIdx int) *gpu.RenderPass { + if c == nil || enc == nil || !c.Valid() || cascadeIdx < 0 || cascadeIdx >= c.frame.CascadeCount { + return nil + } + loadOp := gpu.LoadLoad + if !c.atlasCleared { + loadOp = gpu.LoadClear + c.atlasCleared = true + } + pass := enc.BeginRenderPass(gpu.RenderPassDesc{ + Label: fmt.Sprintf("csm cascade %d", cascadeIdx), + DepthStencil: &gpu.DepthStencilAttachment{ + Texture: c.rt.Depth, + DepthLoadOp: loadOp, + DepthStoreOp: gpu.StoreStore, + ClearDepth: 1.0, + }, + }) + vp := c.frame.Cascades[cascadeIdx].Viewport + pass.SetViewport(vp[0], vp[1], vp[2], vp[3], 0, 1) + pass.SetScissor(int32(vp[0]), int32(vp[1]), int32(vp[2]), int32(vp[3])) + pass.SetPipeline(c.depthPipe) + pass.SetBindGroup(0, c.cascadeGroups[cascadeIdx]) + return pass +} + +// DrawCaster renders mesh as a shadow caster inside a pass opened by [CascadedShadowMap.BeginCascadePass], transforming its vertices by model, and reports whether it drew. +// +// A zero or identity model uses a pre-filled identity slot. Every other model takes one slot of the caster transform buffer the first time it is drawn after [CascadedShadowMap.Update]; drawing the same model again, for example into the next cascade, reuses that slot, so [CSMConfig.MaxCasters] counts distinct models per frame, not draws. Once every slot is taken, DrawCaster draws nothing and returns false rather than overwrite a transform an earlier draw of the same command buffer still reads; raise MaxCasters, or bind caller-owned transforms with [CascadedShadowMap.DrawCasterGroup]. +func (c *CascadedShadowMap) DrawCaster(pass *gpu.RenderPass, mesh *GPUMesh, model math3d.Mat4) bool { + if c == nil || pass == nil || !c.Valid() || !mesh.Valid() { + return false + } + var dynOffset uint32 + if model != (math3d.Mat4{}) && model != math3d.Mat4Identity() { + off, ok := c.casterSlots[model] + if !ok { + if c.casterSlot >= c.maxCasters || c.dev == nil { + return false + } + encodeMat4Into(c.matScratch[:], model) + byteOff := uint64(c.casterSlot) * c.casterStride + c.dev.WriteBuffer(c.casterBuf, byteOff, c.matScratch[:]) + off = uint32(byteOff) + c.casterSlot++ + if finiteMat4(model) { + c.casterSlots[model] = off + } + } + dynOffset = off + } + pass.SetBindGroup(1, c.casterGroup, dynOffset) + mesh.Draw(pass) + return true +} + +// DrawCasterGroup renders mesh inside a pass opened by [CascadedShadowMap.BeginCascadePass] using a caller-owned model bind group matching [CascadedShadowMap.CasterModelLayout] at group 1. +func (c *CascadedShadowMap) DrawCasterGroup(pass *gpu.RenderPass, mesh *GPUMesh, modelGroup *gpu.BindGroup, dynamicOffsets ...uint32) { + if c == nil || pass == nil || !c.Valid() || !mesh.Valid() || modelGroup == nil || !modelGroup.Valid() { + return + } + pass.SetBindGroup(1, modelGroup, dynamicOffsets...) + mesh.Draw(pass) +} + +// Config returns the normalized [CSMConfig] used to create c. +func (c *CascadedShadowMap) Config() CSMConfig { + if c == nil { + return CSMConfig{} + } + return c.cfg +} + +// Frame returns the most recently uploaded [CSMFrame]. +func (c *CascadedShadowMap) Frame() CSMFrame { + if c == nil { + return CSMFrame{} + } + return c.frame +} + +// CascadeCount returns the number of cascades of the frame last passed to [CascadedShadowMap.Update], which [CascadedShadowMap.BeginCascadePass] accepts; it always equals [CSMConfig.CascadeCount] of [CascadedShadowMap.Config]. +func (c *CascadedShadowMap) CascadeCount() int { + if c == nil { + return 0 + } + return c.frame.CascadeCount +} + +// AtlasWidth returns the depth atlas width in texels. +func (c *CascadedShadowMap) AtlasWidth() uint32 { + if c == nil || c.rt == nil { + return 0 + } + return c.rt.Width +} + +// AtlasHeight returns the depth atlas height in texels. +func (c *CascadedShadowMap) AtlasHeight() uint32 { + if c == nil || c.rt == nil { + return 0 + } + return c.rt.Height +} + +// DepthTexture returns the underlying 2D [gpu.FormatDepth32Float] atlas texture. +func (c *CascadedShadowMap) DepthTexture() *gpu.Texture { + if c == nil || c.rt == nil { + return nil + } + return c.rt.Depth +} + +// Sampler returns the comparison sampler bound with the depth atlas. +func (c *CascadedShadowMap) Sampler() *gpu.Sampler { + if c == nil { + return nil + } + return c.sampler +} + +// UniformBuffer returns the [CSMUniformSize]-byte uniform buffer. +func (c *CascadedShadowMap) UniformBuffer() *gpu.Buffer { + if c == nil { + return nil + } + return c.uniformBuf +} + +// Layout returns the bind group layout a lit pipeline places at [CSMGroup]. +func (c *CascadedShadowMap) Layout() *gpu.BindGroupLayout { + if c == nil { + return nil + } + return c.layout +} + +// BindGroup returns the bind group a lit render pass sets at [CSMGroup]. +func (c *CascadedShadowMap) BindGroup() *gpu.BindGroup { + if c == nil { + return nil + } + return c.group +} + +// DepthPipeline returns the depth-only caster pipeline used by [BeginCascadePass]. +func (c *CascadedShadowMap) DepthPipeline() *gpu.Pipeline { + if c == nil { + return nil + } + return c.depthPipe +} + +// CascadeBindGroup returns the group-0 bind group holding cascade idx's light_view_proj uniform buffer, or nil if idx is out of range. +func (c *CascadedShadowMap) CascadeBindGroup(idx int) *gpu.BindGroup { + if c == nil || idx < 0 || idx >= c.cfg.CascadeCount { + return nil + } + return c.cascadeGroups[idx] +} + +// CasterModelLayout returns the group-1 bind group layout expected by [CascadedShadowMap.DepthPipeline] and [CascadedShadowMap.DrawCasterGroup]. +func (c *CascadedShadowMap) CasterModelLayout() *gpu.BindGroupLayout { + if c == nil { + return nil + } + return c.casterLayout +} + +// ByteSize returns the GPU memory held by c's depth atlas and uniform buffers, for [RenderStats] and [Budget] accounting. +func (c *CascadedShadowMap) ByteSize() uint64 { + if c == nil { + return 0 + } + var total uint64 + if c.rt != nil { + total += gpu.FormatDepth32Float.ByteSize(c.rt.Width, c.rt.Height) + } + if c.uniformBuf != nil { + total += c.uniformBuf.Size() + } + if c.casterBuf != nil { + total += c.casterBuf.Size() + } + for i := range c.cfg.CascadeCount { + if c.cascadeBufs[i] != nil { + total += c.cascadeBufs[i].Size() + } + } + return total +} + +// Valid reports whether every GPU resource owned by c is open and belongs to a live device. +func (c *CascadedShadowMap) Valid() bool { + if c == nil || c.rt == nil || !c.rt.Valid() || + c.sampler == nil || !c.sampler.Valid() || + c.uniformBuf == nil || !c.uniformBuf.Valid() || + c.layout == nil || !c.layout.Valid() || + c.group == nil || !c.group.Valid() || + c.cascadeLayout == nil || !c.cascadeLayout.Valid() || + c.casterLayout == nil || !c.casterLayout.Valid() || + c.casterBuf == nil || !c.casterBuf.Valid() || + c.casterGroup == nil || !c.casterGroup.Valid() || + c.depthPipe == nil || !c.depthPipe.Valid() { + return false + } + for i := range c.cfg.CascadeCount { + if c.cascadeBufs[i] == nil || !c.cascadeBufs[i].Valid() || + c.cascadeGroups[i] == nil || !c.cascadeGroups[i].Valid() { + return false + } + } + return true +} + +// Close releases every GPU resource owned by c now rather than waiting for its owning scope. It is safe to call on a nil receiver or more than once. +func (c *CascadedShadowMap) Close() error { + if c == nil { + return nil + } + var errs []error + closeIf := func(cl interface{ Close() error }) { + if cl == nil { + return + } + if err := cl.Close(); err != nil { + errs = append(errs, err) + } + } + closeIf(c.depthPipe) + closeIf(c.casterGroup) + closeIf(c.casterLayout) + closeIf(c.casterBuf) + for i := range c.cascadeGroups { + closeIf(c.cascadeGroups[i]) + closeIf(c.cascadeBufs[i]) + } + closeIf(c.cascadeLayout) + closeIf(c.group) + closeIf(c.layout) + closeIf(c.uniformBuf) + closeIf(c.sampler) + closeIf(c.rt) + return errors.Join(errs...) +} + +// ReadCSMDepthAtlasAsync asynchronously reads back c's [gpu.FormatDepth32Float] shadow atlas into a CPU [CSMDepthAtlas] and invokes fn on the engine goroutine (matching [gpu.Device.ReadTexture]). +func ReadCSMDepthAtlasAsync(dev *gpu.Device, csm *CascadedShadowMap, fn func(CSMDepthAtlas, error)) { + if fn == nil { + return + } + if dev == nil { + fn(CSMDepthAtlas{}, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"}) + return + } + if csm == nil || !csm.Valid() { + fn(CSMDepthAtlas{}, fmt.Errorf("%w: cascaded shadow map is not valid", ErrInvalidCSM)) + return + } + w := csm.AtlasWidth() + h := csm.AtlasHeight() + wantBytes := int(w) * int(h) * 4 + dev.ReadTexture(csm.DepthTexture(), gpu.TextureRegion{Width: w, Height: h}, func(data []byte, err error) { + if err != nil { + fn(CSMDepthAtlas{}, err) + return + } + if len(data) < wantBytes { + fn(CSMDepthAtlas{}, fmt.Errorf("%w: depth readback returned %d bytes, want %d", ErrInvalidCSM, len(data), wantBytes)) + return + } + depths := make([]float32, int(w)*int(h)) + for i := range depths { + depths[i] = math.Float32frombits(binary.LittleEndian.Uint32(data[i*4:])) + } + fn(CSMDepthAtlas{ + Width: int(w), + Height: int(h), + Depth: depths, + }, nil) + }) +} + +// ReadCSMDepthAtlas reads back c's [gpu.FormatDepth32Float] shadow atlas synchronously (for [gpu.SoftwareRenderer] tests where [gpu.Device.ReadTexture] completes immediately). Inside a [gpu.View], use [ReadCSMDepthAtlasAsync]. +func ReadCSMDepthAtlas(dev *gpu.Device, csm *CascadedShadowMap) (CSMDepthAtlas, error) { + var ( + atlas CSMDepthAtlas + gotErr error + called bool + ) + ReadCSMDepthAtlasAsync(dev, csm, func(a CSMDepthAtlas, err error) { + atlas = a + gotErr = err + called = true + }) + if !called { + return CSMDepthAtlas{}, fmt.Errorf("%w: depth readback is asynchronous on this device; use ReadCSMDepthAtlasAsync", ErrInvalidCSM) + } + return atlas, gotErr +} + +func encodeMat4Into(dst []byte, m math3d.Mat4) { + for i, v := range m { + binary.LittleEndian.PutUint32(dst[i*4:], math.Float32bits(v)) + } +} + +// finiteMat4 reports whether every element of m is finite, so it can serve as a map key that compares equal to itself. +func finiteMat4(m math3d.Mat4) bool { + for _, v := range m { + if !finite(v) { + return false + } + } + return true +} diff --git a/packages/game/render3d/csm_test.go b/packages/game/render3d/csm_test.go new file mode 100644 index 00000000..b5b378b6 --- /dev/null +++ b/packages/game/render3d/csm_test.go @@ -0,0 +1,1439 @@ +package render3d_test + +import ( + "encoding/binary" + "errors" + "image" + "math" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/gametest" + "github.com/nsgo-dev/game/packages/game/math3d" + "github.com/nsgo-dev/game/packages/game/render3d" + "github.com/nsgo-dev/game/packages/game/scene3d" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/gpu" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +const ( + csmTestWidth = 160 + csmTestHeight = 120 +) + +func csmTestBoxMesh(minPt, maxPt math3d.Vec3) render3d.Mesh { + type face struct { + n math3d.Vec3 + a, b, c, d math3d.Vec3 + } + lo, hi := minPt, maxPt + faces := []face{ + // +Y top + {math3d.Vec3{Y: 1}, + math3d.Vec3{X: lo.X, Y: hi.Y, Z: hi.Z}, + math3d.Vec3{X: hi.X, Y: hi.Y, Z: hi.Z}, + math3d.Vec3{X: hi.X, Y: hi.Y, Z: lo.Z}, + math3d.Vec3{X: lo.X, Y: hi.Y, Z: lo.Z}}, + // -Y bottom + {math3d.Vec3{Y: -1}, + math3d.Vec3{X: lo.X, Y: lo.Y, Z: lo.Z}, + math3d.Vec3{X: hi.X, Y: lo.Y, Z: lo.Z}, + math3d.Vec3{X: hi.X, Y: lo.Y, Z: hi.Z}, + math3d.Vec3{X: lo.X, Y: lo.Y, Z: hi.Z}}, + // +X right + {math3d.Vec3{X: 1}, + math3d.Vec3{X: hi.X, Y: lo.Y, Z: hi.Z}, + math3d.Vec3{X: hi.X, Y: lo.Y, Z: lo.Z}, + math3d.Vec3{X: hi.X, Y: hi.Y, Z: lo.Z}, + math3d.Vec3{X: hi.X, Y: hi.Y, Z: hi.Z}}, + // -X left + {math3d.Vec3{X: -1}, + math3d.Vec3{X: lo.X, Y: lo.Y, Z: lo.Z}, + math3d.Vec3{X: lo.X, Y: lo.Y, Z: hi.Z}, + math3d.Vec3{X: lo.X, Y: hi.Y, Z: hi.Z}, + math3d.Vec3{X: lo.X, Y: hi.Y, Z: lo.Z}}, + // +Z front + {math3d.Vec3{Z: 1}, + math3d.Vec3{X: lo.X, Y: lo.Y, Z: hi.Z}, + math3d.Vec3{X: hi.X, Y: lo.Y, Z: hi.Z}, + math3d.Vec3{X: hi.X, Y: hi.Y, Z: hi.Z}, + math3d.Vec3{X: lo.X, Y: hi.Y, Z: hi.Z}}, + // -Z back + {math3d.Vec3{Z: -1}, + math3d.Vec3{X: hi.X, Y: lo.Y, Z: lo.Z}, + math3d.Vec3{X: lo.X, Y: lo.Y, Z: lo.Z}, + math3d.Vec3{X: lo.X, Y: hi.Y, Z: lo.Z}, + math3d.Vec3{X: hi.X, Y: hi.Y, Z: lo.Z}}, + } + var m render3d.Mesh + for _, f := range faces { + base := uint32(len(m.Positions)) + m.Positions = append(m.Positions, f.a, f.b, f.c, f.d) + m.Normals = append(m.Normals, f.n, f.n, f.n, f.n) + m.UVs = append(m.UVs, + math3d.Vec2{X: 0, Y: 0}, + math3d.Vec2{X: 1, Y: 0}, + math3d.Vec2{X: 1, Y: 1}, + math3d.Vec2{X: 0, Y: 1}, + ) + m.Indices = append(m.Indices, base, base+1, base+2, base, base+2, base+3) + } + return m +} + +func csmTestGroundMesh(minX, maxX, minZ, maxZ float32) render3d.Mesh { + up := math3d.Vec3Up() + return render3d.Mesh{ + Positions: []math3d.Vec3{ + {X: minX, Y: 0, Z: maxZ}, + {X: maxX, Y: 0, Z: maxZ}, + {X: maxX, Y: 0, Z: minZ}, + {X: minX, Y: 0, Z: minZ}, + }, + Normals: []math3d.Vec3{up, up, up, up}, + UVs: []math3d.Vec2{ + {X: 0, Y: 0}, + {X: 1, Y: 0}, + {X: 1, Y: 1}, + {X: 0, Y: 1}, + }, + Indices: []uint32{0, 1, 2, 0, 2, 3}, + } +} + +func csmTestMergeMeshes(meshes ...render3d.Mesh) render3d.Mesh { + var out render3d.Mesh + for _, m := range meshes { + base := uint32(len(out.Positions)) + out.Positions = append(out.Positions, m.Positions...) + out.Normals = append(out.Normals, m.Normals...) + out.UVs = append(out.UVs, m.UVs...) + for _, idx := range m.Indices { + out.Indices = append(out.Indices, base+idx) + } + } + return out +} + +type csmTestPillar struct { + centerX float32 + centerZ float32 + halfW float32 + height float32 +} + +type csmTestSceneSpec struct { + cam *scene3d.Camera + lightDir math3d.Vec3 + ground render3d.Mesh + pillars []csmTestPillar + rig render3d.LightRig + groundMat render3d.PBRMaterial + pillarMat render3d.PBRMaterial +} + +func csmTestLargeScene() csmTestSceneSpec { + cam := scene3d.NewPerspectiveCamera( + math3d.Vec3{X: 0, Y: 3.2, Z: 3.5}, + math3d.DegToRad(58), + float32(csmTestWidth)/float32(csmTestHeight), + 1.0, + 60.0, + ) + cam.LookAt(math3d.Vec3{X: 0, Y: 0.3, Z: -15}, math3d.Vec3Up()) + + // Oblique sun shining downward and toward (+X, -Y, -Z) so shadows stretch cleanly to the right and slightly away from the camera on the ground plane. + lightDir := math3d.Vec3{X: 0.55, Y: -0.85, Z: -0.20}.Norm() + + pillars := []csmTestPillar{ + // Near pillar strictly inside cascade 0 (viewDepth ~ 5.1m) + {centerX: -1.4, centerZ: -1.2, halfW: 0.32, height: 2.0}, + // Cascade 1 pillar (viewDepth ~ 9.5m) + {centerX: 1.5, centerZ: -5.5, halfW: 0.45, height: 2.8}, + // Cascade 2 pillars (viewDepth ~ 17..21m) + {centerX: -4.0, centerZ: -13.5, halfW: 0.75, height: 4.4}, + {centerX: 3.2, centerZ: -17.5, halfW: 0.85, height: 5.0}, + // Cascade 3 far pillars (viewDepth ~ 36..41m) + {centerX: -6.8, centerZ: -32.0, halfW: 1.3, height: 7.5}, + {centerX: 5.4, centerZ: -37.0, halfW: 1.4, height: 8.0}, + } + + return csmTestSceneSpec{ + cam: cam, + lightDir: lightDir, + ground: csmTestGroundMesh(-20, 20, -56, 2.0), + pillars: pillars, + rig: csmTestRig(lightDir), + groundMat: render3d.PBRMaterial{BaseColor: math3d.Vec3{X: 0.82, Y: 0.82, Z: 0.78}, Roughness: 0.9}, + pillarMat: render3d.PBRMaterial{BaseColor: math3d.Vec3{X: 0.76, Y: 0.42, Z: 0.28}, Roughness: 0.7}, + } +} + +// csmTestRig returns a LightRig whose first directional light, the one the cascades shadow, shines along lightDir, plus an unshadowed fill light and an ambient term. +func csmTestRig(lightDir math3d.Vec3) render3d.LightRig { + return render3d.LightRig{ + Ambient: render3d.AmbientLight{Color: math3d.Vec3{X: 0.18, Y: 0.20, Z: 0.24}, Intensity: 1}, + Directional: []render3d.DirectionalLight{ + {Direction: lightDir, Color: math3d.Vec3{X: 1.0, Y: 0.96, Z: 0.88}, Intensity: 2.2}, + {Direction: math3d.Vec3{X: -0.4, Y: -1, Z: 0.6}, Color: math3d.Vec3{X: 0.6, Y: 0.65, Z: 0.75}, Intensity: 0.4}, + }, + } +} + +func (s csmTestSceneSpec) pillarMesh() render3d.Mesh { + boxes := make([]render3d.Mesh, len(s.pillars)) + for i, p := range s.pillars { + boxes[i] = csmTestBoxMesh( + math3d.Vec3{X: p.centerX - p.halfW, Y: 0, Z: p.centerZ - p.halfW}, + math3d.Vec3{X: p.centerX + p.halfW, Y: p.height, Z: p.centerZ + p.halfW}, + ) + } + return csmTestMergeMeshes(boxes...) +} + +func csmTestAssertGolden(t *testing.T, name string, got *image.RGBA) { + t.Helper() + path := gametest.GoldenPath("", name) + if gametest.ShouldUpdateGolden() { + if err := gametest.WritePNG(path, got); err != nil { + t.Fatal(err) + } + return + } + want, err := gametest.ReadPNG(path) + if err != nil { + t.Fatalf("read golden %s: %v (UPDATE_GOLDEN=1 writes it)", path, err) + } + if !want.Bounds().Eq(got.Bounds()) { + t.Fatalf("%s: size %v, golden %v", name, got.Bounds(), want.Bounds()) + } + const channelTolerance = 3 + far := 0 + b := got.Bounds() + for y := b.Min.Y; y < b.Max.Y; y++ { + for x := b.Min.X; x < b.Max.X; x++ { + g := got.RGBAAt(x, y) + wr, wg, wb, wa := want.At(x, y).RGBA() + w := [4]int{int(wr >> 8), int(wg >> 8), int(wb >> 8), int(wa >> 8)} + for i, c := range [4]int{int(g.R), int(g.G), int(g.B), int(g.A)} { + if d := c - w[i]; d > channelTolerance || d < -channelTolerance { + far++ + break + } + } + } + } + if limit := b.Dx() * b.Dy() / 200; far > limit { + dir := t.TempDir() + diff, _ := gametest.DiffImage(got, want) + _ = gametest.WritePNG(dir+"/"+name+".got.png", got) + _ = gametest.WritePNG(dir+"/"+name+".diff.png", diff) + t.Fatalf("%s: %d pixels differ from golden (limit %d); got and diff written to %s", name, far, limit, dir) + } +} + +// csmTestLit holds the camera, light and per-draw buffers and the LitPBRCSMWGSL pipeline that draw a scene shadowed by a CascadedShadowMap. +type csmTestLit struct { + camBuf *render3d.CameraBuffer + lightBuf *render3d.GPULightBuffer + pipe *gpu.Pipeline + draws []*render3d.PBRDrawBuffer +} + +func csmTestNewLit(t *testing.T, cx *core.Scope, dev *gpu.Device, csm *render3d.CascadedShadowMap, rig render3d.LightRig, draws []render3d.PBRDrawUniform, retained bool) csmTestLit { + t.Helper() + var l csmTestLit + var err error + l.camBuf, err = render3d.NewCameraBuffer(cx, dev) + if err != nil { + t.Fatalf("NewCameraBuffer: %v", err) + } + l.lightBuf, err = render3d.NewLightBuffer(cx, dev, rig, render3d.LightBufferOptions{Label: "csm-lights", Retained: retained}) + if err != nil { + t.Fatalf("NewLightBuffer: %v", err) + } + var layout *gpu.BindGroupLayout + for i, u := range draws { + db, err := render3d.NewPBRDrawBuffer(cx, dev, layout, u, retained) + if err != nil { + t.Fatalf("NewPBRDrawBuffer[%d]: %v", i, err) + } + if layout == nil { + layout = db.Layout() + } + l.draws = append(l.draws, db) + } + l.pipe, err = render3d.NewLitPBRCSMPipeline(cx, dev, l.camBuf.Layout(), l.lightBuf.Layout(), layout, csm.Layout(), gpu.FormatDepth24Plus) + if err != nil { + t.Fatalf("NewLitPBRCSMPipeline: %v", err) + } + if cx == nil { + t.Cleanup(func() { + _ = l.pipe.Close() + for _, d := range l.draws { + _ = d.Close() + } + _ = l.lightBuf.Close() + _ = l.camBuf.Close() + }) + } + return l +} + +// draw records the main lit pass: meshes[i] is drawn with the i-th per-draw buffer. +func (l csmTestLit) draw(pass *gpu.RenderPass, csm *render3d.CascadedShadowMap, meshes ...*render3d.GPUMesh) { + pass.SetPipeline(l.pipe) + pass.SetBindGroup(render3d.CameraGroup, l.camBuf.BindGroup()) + pass.SetBindGroup(render3d.LightGroup, l.lightBuf.BindGroup()) + pass.SetBindGroup(render3d.CSMGroup, csm.BindGroup()) + for i, m := range meshes { + pass.SetBindGroup(render3d.PBRDrawGroup, l.draws[i].BindGroup()) + m.Draw(pass) + } +} + +// csmTestMainPass begins the main color + depth pass of a test frame. +func csmTestMainPass(enc render3d.RenderPassStarter, clear core.Color) *gpu.RenderPass { + return enc.BeginRenderPass(gpu.RenderPassDesc{ + Label: "csm-main", + ColorAttachments: []gpu.ColorAttachment{{ + LoadOp: gpu.LoadClear, + StoreOp: gpu.StoreStore, + ClearColor: clear, + }}, + DepthStencil: &gpu.DepthStencilAttachment{ + DepthLoadOp: gpu.LoadClear, + DepthStoreOp: gpu.StoreDiscard, + ClearDepth: 1.0, + }, + }) +} + +// csmTestExpected returns the sRGB 8-bit color LitPBRCSMWGSL draws for an up-facing ground point wp at view depth viewDepth, from the CPU references EvaluateCSMShadow, ShadePointShadowed, CSMFrame.DebugTint and LinearToSRGB. +func csmTestExpected(frame render3d.CSMFrame, atlas render3d.CSMDepthAtlas, cam *scene3d.Camera, rig render3d.LightRig, mat render3d.PBRMaterial, wp math3d.Vec3, viewDepth float32) ([3]int, float32) { + vis := render3d.EvaluateCSMShadow(frame, atlas, wp, math3d.Vec3Up(), viewDepth) + e := cam.Eye() + eye := math3d.Vec3{X: e.X, Y: e.Y, Z: e.Z} + lin := render3d.ShadePointShadowed(wp, math3d.Vec3Up(), eye.Sub(wp), mat, rig, vis) + tint := frame.DebugTint(viewDepth) + lin = math3d.Vec3{X: lin.X * tint.X, Y: lin.Y * tint.Y, Z: lin.Z * tint.Z} + c := render3d.LinearToSRGB(lin) + return [3]int{int(math.Round(float64(c.X) * 255)), int(math.Round(float64(c.Y) * 255)), int(math.Round(float64(c.Z) * 255))}, vis +} + +func TestCSMSplitsPracticalScheme(t *testing.T) { + const near, far = float32(0.5), float32(100.0) + + // lambda = 0: exact uniform splits. + uni := render3d.ComputeCSMSplits(near, far, 4, 0) + if len(uni) != 5 { + t.Fatalf("uniform split len = %d, want 5", len(uni)) + } + for i := range 5 { + want := near + (far-near)*float32(i)/4.0 + if math.Abs(float64(uni[i]-want)) > 1e-4 { + t.Errorf("uniform[%d] = %v, want %v", i, uni[i], want) + } + } + + // lambda = 1: exact logarithmic splits. + logS := render3d.ComputeCSMSplits(near, far, 4, 1) + if len(logS) != 5 { + t.Fatalf("log split len = %d, want 5", len(logS)) + } + for i := range 5 { + want := float32(float64(near) * math.Pow(float64(far)/float64(near), float64(i)/4.0)) + if math.Abs(float64(logS[i]-want)) > 1e-4 { + t.Errorf("log[%d] = %v, want %v", i, logS[i], want) + } + } + + // lambda = 0.75: strictly monotonic, endpoints exact, strictly between log and uniform. + prac := render3d.ComputeCSMSplits(near, far, 4, 0.75) + if len(prac) != 5 { + t.Fatalf("practical split len = %d, want 5", len(prac)) + } + if prac[0] != near || prac[4] != far { + t.Errorf("endpoints = [%v, %v], want [%v, %v]", prac[0], prac[4], near, far) + } + for i := 1; i < 4; i++ { + if prac[i] <= prac[i-1] || prac[i] >= prac[i+1] { + t.Errorf("practical splits not strictly monotonic at %d: %v", i, prac) + } + if !(prac[i] > logS[i] && prac[i] < uni[i]) { + t.Errorf("practical[%d] = %v, want strictly between log=%v and uniform=%v", i, prac[i], logS[i], uni[i]) + } + } + + // Single cascade returns [near, far]. + one := render3d.ComputeCSMSplits(0.1, 50, 1, 0.75) + if len(one) != 2 || one[0] != 0.1 || one[1] != 50 { + t.Fatalf("1-cascade splits = %v, want [0.1 50]", one) + } + + // Clamped / NaN lambda and invalid inputs. + clampedLo := render3d.ComputeCSMSplits(near, far, 4, -5) + clampedHi := render3d.ComputeCSMSplits(near, far, 4, 5) + nanLam := render3d.ComputeCSMSplits(near, far, 4, float32(math.NaN())) + for i := range 5 { + if clampedLo[i] != uni[i] { + t.Errorf("clampedLo[%d]=%v != uni=%v", i, clampedLo[i], uni[i]) + } + if clampedHi[i] != logS[i] { + t.Errorf("clampedHi[%d]=%v != log=%v", i, clampedHi[i], logS[i]) + } + if nanLam[i] != prac[i] { + t.Errorf("nanLam[%d]=%v != default(0.75)=%v", i, nanLam[i], prac[i]) + } + } + + for _, bad := range []struct { + near, far float32 + count int + }{ + {0, 10, 4}, + {-1, 10, 4}, + {10, 10, 4}, + {20, 10, 4}, + {0.1, 10, 0}, + {float32(math.NaN()), 10, 4}, + {0.1, float32(math.Inf(1)), 4}, + } { + if got := render3d.ComputeCSMSplits(bad.near, bad.far, bad.count, 0.75); got != nil { + t.Errorf("ComputeCSMSplits(%v, %v, %d) = %v, want nil", bad.near, bad.far, bad.count, got) + } + } +} + +func TestCSMTexelSnappingStability(t *testing.T) { + cfgSnap := render3d.DefaultCSMConfig() + cfgSnap.Resolution = 256 + cfgSnap.TexelSnap = true + + cfgNoSnap := cfgSnap + cfgNoSnap.TexelSnap = false + + lightDir := math3d.Vec3{X: 0.4, Y: -1.0, Z: -0.3}.Norm() + proj := math3d.Perspective(math3d.DegToRad(55), 16.0/9.0, 0.5, 80.0) + + baseEye := math3d.Vec3{X: 3.17, Y: 4.23, Z: 8.41} + baseView := math3d.LookAt(baseEye, baseEye.Add(math3d.Vec3{Z: -10}), math3d.Vec3Up()) + baseFrame := render3d.FitCascades(baseView, proj, 0.5, 80.0, lightDir, cfgSnap) + + // 1. Sub-texel camera translations inside a texel cell produce bit-for-bit identical cascade matrices (zero jitter). + for c := range baseFrame.CascadeCount { + // Pick an offset smaller than 0.05 texel along the light's axes. + tiny := baseFrame.Cascades[c].TexelSize * 0.02 + if tiny > 0.001 { + tiny = 0.001 + } + movedEye := baseEye.Add(math3d.Vec3{X: tiny, Y: tiny * 0.5, Z: -tiny * 0.7}) + movedView := math3d.LookAt(movedEye, movedEye.Add(math3d.Vec3{Z: -10}), math3d.Vec3Up()) + movedFrame := render3d.FitCascades(movedView, proj, 0.5, 80.0, lightDir, cfgSnap) + + // Even if a tiny move happens to straddle a rounding boundary for one axis, projecting any static world point must shift by an EXACT integer number of texels. + staticPt := math3d.Vec3{X: 1.5, Y: 0.5, Z: -5.0} + p0 := baseFrame.Cascades[c].LightViewProj.TransformPoint(staticPt) + p1 := movedFrame.Cascades[c].LightViewProj.TransformPoint(staticPt) + duTex := (p1.X - p0.X) * 0.5 * float32(cfgSnap.Resolution) + dvTex := (p1.Y - p0.Y) * 0.5 * float32(cfgSnap.Resolution) + if fracX := math.Abs(float64(duTex) - math.Round(float64(duTex))); fracX > 1e-3 { + t.Errorf("cascade %d sub-texel move shifted U by fractional texel %v (frac=%v)", c, duTex, fracX) + } + if fracY := math.Abs(float64(dvTex) - math.Round(float64(dvTex))); fracY > 1e-3 { + t.Errorf("cascade %d sub-texel move shifted V by fractional texel %v (frac=%v)", c, dvTex, fracY) + } + } + + // 2. Arbitrary multi-meter camera translations ALWAYS shift every static world point by an exact integer number of shadow-map texels when TexelSnap=true, whereas TexelSnap=false produces fractional texel swimming. + staticPt := math3d.Vec3{X: 2.0, Y: 0.0, Z: -12.0} + offsets := []math3d.Vec3{ + {X: 0.13, Y: 0.07, Z: -0.29}, + {X: 1.37, Y: -0.41, Z: -2.83}, + {X: -4.19, Y: 1.11, Z: 3.77}, + } + noSnapFrame0 := render3d.FitCascades(baseView, proj, 0.5, 80.0, lightDir, cfgNoSnap) + sawNoSnapSwim := false + for _, off := range offsets { + eye := baseEye.Add(off) + view := math3d.LookAt(eye, eye.Add(math3d.Vec3{Z: -10}), math3d.Vec3Up()) + fSnap := render3d.FitCascades(view, proj, 0.5, 80.0, lightDir, cfgSnap) + fNoSnap := render3d.FitCascades(view, proj, 0.5, 80.0, lightDir, cfgNoSnap) + + for c := range fSnap.CascadeCount { + if fSnap.Cascades[c].TexelSize != baseFrame.Cascades[c].TexelSize { + t.Errorf("cascade %d TexelSize changed on translation: %v -> %v", c, baseFrame.Cascades[c].TexelSize, fSnap.Cascades[c].TexelSize) + } + p0 := baseFrame.Cascades[c].LightViewProj.TransformPoint(staticPt) + p1 := fSnap.Cascades[c].LightViewProj.TransformPoint(staticPt) + duTex := (p1.X - p0.X) * 0.5 * float32(cfgSnap.Resolution) + dvTex := (p1.Y - p0.Y) * 0.5 * float32(cfgSnap.Resolution) + if fracX := math.Abs(float64(duTex) - math.Round(float64(duTex))); fracX > 2e-3 { + t.Errorf("cascade %d offset %v: snapped U shifted by fractional texel %v (frac=%v)", c, off, duTex, fracX) + } + if fracY := math.Abs(float64(dvTex) - math.Round(float64(dvTex))); fracY > 2e-3 { + t.Errorf("cascade %d offset %v: snapped V shifted by fractional texel %v (frac=%v)", c, off, dvTex, fracY) + } + + q0 := noSnapFrame0.Cascades[c].LightViewProj.TransformPoint(staticPt) + q1 := fNoSnap.Cascades[c].LightViewProj.TransformPoint(staticPt) + nuTex := (q1.X - q0.X) * 0.5 * float32(cfgNoSnap.Resolution) + if math.Abs(float64(nuTex)-math.Round(float64(nuTex))) > 0.05 { + sawNoSnapSwim = true + } + } + } + if !sawNoSnapSwim { + t.Error("expected TexelSnap=false to show fractional texel shift on camera translation") + } + + // 3. Camera rotation invariance: TexelSize must stay constant as the camera yaws/pitches. + for _, yawDeg := range []float32{15, 45, 90, 143} { + rot := math3d.QuatFromEuler(math3d.DegToRad(-12), math3d.DegToRad(yawDeg), 0) + fwd := rot.RotateVec3(math3d.Vec3Forward()) + view := math3d.LookAt(baseEye, baseEye.Add(fwd), math3d.Vec3Up()) + fRot := render3d.FitCascades(view, proj, 0.5, 80.0, lightDir, cfgSnap) + for c := range fRot.CascadeCount { + if fRot.Cascades[c].TexelSize != baseFrame.Cascades[c].TexelSize { + t.Errorf("yaw %v cascade %d TexelSize changed: %v -> %v", yawDeg, c, baseFrame.Cascades[c].TexelSize, fRot.Cascades[c].TexelSize) + } + } + } +} + +func TestCSMCascadeSelectionBlendAndCasterPadding(t *testing.T) { + cfg := render3d.DefaultCSMConfig() + cfg.CascadeCount = 4 + cfg.Resolution = 128 + cfg.MaxShadowDistance = 40 + cfg.CascadeBlendRange = 0.2 + cfg.CasterPadding = 30 + + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{Y: 2, Z: 0}, math3d.DegToRad(60), 1, 0.5, 100) + frame := render3d.FitCascadesFromCamera(cam, math3d.Vec3{Y: -1}, cfg) + + if frame.MaxShadowDistance != 40 { + t.Fatalf("MaxShadowDistance = %v, want 40", frame.MaxShadowDistance) + } + if idx, next, blend := frame.SelectCascade(0); idx != -1 || next != -1 || blend != 0 { + t.Errorf("SelectCascade(0) = (%d,%d,%v), want (-1,-1,0)", idx, next, blend) + } + if idx, next, blend := frame.SelectCascade(40); idx != -1 || next != -1 || blend != 0 { + t.Errorf("SelectCascade(40) = (%d,%d,%v), want (-1,-1,0)", idx, next, blend) + } + + // Interior of each cascade selects that cascade with blend = 0. + for i := range 4 { + mid := frame.Cascades[i].Near + 0.5*(frame.Cascades[i].Far-frame.Cascades[i].Near) + idx, next, blend := frame.SelectCascade(mid) + if idx != i || next != -1 || blend != 0 { + t.Errorf("cascade %d mid (%v): SelectCascade = (%d,%d,%v), want (%d,-1,0)", i, mid, idx, next, blend, i) + } + } + + // Inside the last 20% of cascade 0 -> blends smoothly into cascade 1. + c0Span := frame.Cascades[0].Far - frame.Cascades[0].Near + halfwayBlendDepth := frame.Cascades[0].Far - 0.1*c0Span + idx, next, blend := frame.SelectCascade(halfwayBlendDepth) + if idx != 0 || next != 1 || math.Abs(float64(blend-0.5)) > 1e-3 { + t.Errorf("cascade 0 blend midpoint = (%d,%d,%v), want (0,1,0.5)", idx, next, blend) + } + + // Approaching MaxShadowDistance in cascade 3 -> fades out (next = -1, blend ~ 0.5). + c3Span := frame.Cascades[3].Far - frame.Cascades[3].Near + fadeDepth := frame.Cascades[3].Far - 0.1*c3Span + idx, next, blend = frame.SelectCascade(fadeDepth) + if idx != 3 || next != -1 || math.Abs(float64(blend-0.5)) > 1e-3 { + t.Errorf("cascade 3 far fade = (%d,%d,%v), want (3,-1,0.5)", idx, next, blend) + } + + // Verify CasterPadding captures a tall caster 20 units above the frustum along -lightDir (+Y). + offFrustumCaster := math3d.Vec3{X: 0, Y: 20, Z: -2} + ndc := frame.Cascades[0].LightViewProj.TransformPoint(offFrustumCaster) + if ndc.Z < 0 || ndc.Z > 1 { + t.Errorf("off-frustum caster at Y=20 projected outside light depth [0,1]: ndc.Z = %v", ndc.Z) + } + + // Verify CPU EvaluateCSMShadow blends smoothly across cascade 0 -> 1 when tile 0 is shadowed (0.0) and tile 1 is lit (1.0). + atlasW, atlasH := int(frame.AtlasWidth), int(frame.AtlasHeight) + depth := make([]float32, atlasW*atlasH) + for y := range atlasH { + for x := range atlasW { + if x < atlasW/2 && y < atlasH/2 { + depth[y*atlasW+x] = 0.0 // tile 0: fully occluding + } else { + depth[y*atlasW+x] = 1.0 // tiles 1..3: fully lit + } + } + } + atlas := render3d.CSMDepthAtlas{Width: atlasW, Height: atlasH, Depth: depth} + worldPt := math3d.Vec3{X: 0, Y: 2, Z: -halfwayBlendDepth} + visBlend := render3d.EvaluateCSMShadow(frame, atlas, worldPt, math3d.Vec3Up(), halfwayBlendDepth) + if math.Abs(float64(visBlend-0.5)) > 0.02 { + t.Errorf("EvaluateCSMShadow at blend midpoint = %v, want ~0.5", visBlend) + } + + // Beyond MaxShadowDistance, EvaluateCSMShadow returns 1.0 (unshadowed). + if visFar := render3d.EvaluateCSMShadow(frame, atlas, worldPt, math3d.Vec3Up(), 45); visFar != 1.0 { + t.Errorf("EvaluateCSMShadow beyond MaxShadowDistance = %v, want 1.0", visFar) + } +} + +func TestCSMConfigValidationLayoutAndZeroAlloc(t *testing.T) { + nan := float32(math.NaN()) + inf := float32(math.Inf(1)) + + tests := []struct { + name string + cfg render3d.CSMConfig + ok bool + }{ + {"zero value", render3d.CSMConfig{}, true}, + {"default", render3d.DefaultCSMConfig(), true}, + {"1 cascade", render3d.CSMConfig{CascadeCount: 1, Resolution: 64}, true}, + {"cascade count too high", render3d.CSMConfig{CascadeCount: render3d.MaxCascades + 1}, false}, + {"negative cascade count", render3d.CSMConfig{CascadeCount: -1}, false}, + {"negative resolution", render3d.CSMConfig{Resolution: -64}, false}, + {"lambda < 0", render3d.CSMConfig{SplitLambda: -0.1}, false}, + {"lambda > 1", render3d.CSMConfig{SplitLambda: 1.1}, false}, + {"lambda NaN", render3d.CSMConfig{SplitLambda: nan}, false}, + {"negative max dist", render3d.CSMConfig{MaxShadowDistance: -1}, false}, + {"inf max dist", render3d.CSMConfig{MaxShadowDistance: inf}, false}, + {"negative depth bias", render3d.CSMConfig{DepthBias: -0.001}, false}, + {"negative normal bias", render3d.CSMConfig{NormalBias: -0.01}, false}, + {"blend > 0.5", render3d.CSMConfig{CascadeBlendRange: 0.6}, false}, + {"blend < 0", render3d.CSMConfig{CascadeBlendRange: -0.05}, false}, + {"unknown filter", render3d.CSMConfig{Filter: render3d.ShadowFilter(99)}, false}, + {"negative caster padding", render3d.CSMConfig{CasterPadding: -5}, false}, + {"negative max casters", render3d.CSMConfig{MaxCasters: -1}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.cfg.Validate() + if tt.ok && err != nil { + t.Fatalf("Validate = %v, want nil", err) + } + if !tt.ok && !errors.Is(err, render3d.ErrInvalidCSM) { + t.Fatalf("Validate = %v, want ErrInvalidCSM", err) + } + }) + } + + // Atlas dimensions per cascade count. + for _, tc := range []struct { + count int + w, h uint32 + }{ + {1, 128, 128}, + {2, 256, 128}, + {3, 256, 256}, + {4, 256, 256}, + } { + w, h := (render3d.CSMConfig{CascadeCount: tc.count, Resolution: 128}).AtlasSize() + if w != tc.w || h != tc.h { + t.Errorf("AtlasSize(count=%d, res=128) = %dx%d, want %dx%d", tc.count, w, h, tc.w, tc.h) + } + } + + // Nil device error. + if _, err := render3d.NewCascadedShadowMap(nil, nil, render3d.DefaultCSMConfig()); !errors.Is(err, gpu.ErrDeviceLost) { + t.Fatalf("NewCascadedShadowMap(nil dev) = %v, want ErrDeviceLost", err) + } + if _, err := render3d.NewLitPBRCSMPipeline(nil, nil, nil, nil, nil, nil, gpu.FormatUndefined); !errors.Is(err, gpu.ErrDeviceLost) { + t.Fatalf("NewLitPBRCSMPipeline(nil dev) = %v, want ErrDeviceLost", err) + } + if render3d.CSMGroup != render3d.ShadowGroup { + t.Fatalf("CSMGroup = %d, want ShadowGroup %d", render3d.CSMGroup, render3d.ShadowGroup) + } + + // Uniform encoding byte layout & 0-alloc verification. + sr := gpu.NewSoftwareRenderer(16, 16, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + dev := sr.Device() + + // Exceeding MaxTextureDimension2D fails cleanly with ErrInvalidCSM. + hugeCfg := render3d.DefaultCSMConfig() + hugeCfg.Resolution = int(dev.Limits().MaxTextureDimension2D) + 1 + if _, err := render3d.NewCascadedShadowMap(nil, dev, hugeCfg); !errors.Is(err, render3d.ErrInvalidCSM) { + t.Fatalf("NewCascadedShadowMap(oversized) = %v, want ErrInvalidCSM", err) + } + + cfg := render3d.DefaultCSMConfig() + cfg.Resolution = 64 + csm, err := render3d.NewCascadedShadowMap(nil, dev, cfg) + if err != nil { + t.Fatalf("NewCascadedShadowMap: %v", err) + } + t.Cleanup(func() { _ = csm.Close() }) + + camView := math3d.LookAt(math3d.Vec3{Y: 5, Z: 5}, math3d.Vec3{Z: -10}, math3d.Vec3Up()) + camProj := math3d.Perspective(math3d.DegToRad(50), 1.33, 0.5, 60) + lightDir := math3d.Vec3{X: 0.4, Y: -1, Z: -0.2}.Norm() + frame := render3d.FitCascades(camView, camProj, 0.5, 60, lightDir, cfg) + + var buf [render3d.CSMUniformSize + 8]byte + encoded := frame.EncodeUniforms(buf[:]) + if len(encoded) != render3d.CSMUniformSize || render3d.CSMUniformSize != 416 { + t.Fatalf("encoded len = %d, CSMUniformSize = %d, want 416", len(encoded), render3d.CSMUniformSize) + } + readF := func(idx int) float32 { + return math.Float32frombits(binary.LittleEndian.Uint32(encoded[idx*4:])) + } + // Check cascade 0 matrix and splits offset (4*16 + 4*4 = 80 floats = byte 320). + for i := range 16 { + if readF(i) != frame.Cascades[0].LightViewProj[i] { + t.Fatalf("light_vp0[%d] = %v, want %v", i, readF(i), frame.Cascades[0].LightViewProj[i]) + } + } + for i := range 4 { + if readF(80+i) != frame.Cascades[i].Far { + t.Fatalf("splits[%d] = %v, want %v", i, readF(80+i), frame.Cascades[i].Far) + } + } + + if allocs := testing.AllocsPerRun(100, func() { + f := render3d.FitCascades(camView, camProj, 0.5, 60, lightDir, cfg) + f.EncodeUniforms(buf[:]) + }); allocs != 0 { + t.Errorf("FitCascades + EncodeUniforms allocated %v times, want 0", allocs) + } + + // A short slice must panic in EncodeUniforms. + func() { + defer func() { + if recover() == nil { + t.Error("EncodeUniforms on short dst did not panic") + } + }() + frame.EncodeUniforms(make([]byte, 0, render3d.CSMUniformSize)) + }() + + // The lit PBR pipeline compiles with the CSM layout and refuses a second group-3 layout. + if _, err := render3d.NewLitPBRCSMPipeline(nil, dev, csm.Layout(), csm.Layout(), csm.Layout(), nil, gpu.FormatUndefined); !errors.Is(err, gpu.ErrInvalidDescriptor) { + t.Errorf("NewLitPBRCSMPipeline(nil csm layout) = %v, want ErrInvalidDescriptor", err) + } + if _, err := render3d.NewLitPBRPipelineWithOptions(nil, dev, csm.Layout(), csm.Layout(), csm.Layout(), render3d.LitPBRPipelineOptions{CSMLayout: csm.Layout(), ShadowLayout: csm.Layout()}); !errors.Is(err, gpu.ErrInvalidDescriptor) { + t.Errorf("CSMLayout with ShadowLayout = %v, want ErrInvalidDescriptor", err) + } + for _, src := range []string{render3d.LitPBRCSMWGSL, render3d.CameraWGSL + render3d.CSMWGSLForGroup(1) + ` +@fragment +fn fs_main(@location(0) world_pos: vec3) -> @location(0) vec4 { + return vec4(csm_debug_tint(world_pos) * sample_csm_shadow(world_pos, vec3(0.0, 1.0, 0.0)), 1.0); +} +`} { + if _, err := gpu.CompileWGSL(src); err != nil { + t.Errorf("CompileWGSL: %v", err) + } + } + + // Update refuses a frame fitted for another atlas: its tiles, viewports, texel size or filter would not match the atlas and sampler. + if err := csm.Update(dev, frame); err != nil { + t.Fatalf("Update(matching frame) = %v", err) + } + badFrame := frame + badFrame.CascadeCount = 0 + if err := csm.Update(dev, badFrame); !errors.Is(err, render3d.ErrInvalidCSM) { + t.Errorf("Update(0 cascades) = %v, want ErrInvalidCSM", err) + } + mismatched := map[string]func(*render3d.CSMConfig){ + "fewer cascades": func(c *render3d.CSMConfig) { c.CascadeCount = 2 }, + "larger resolution": func(c *render3d.CSMConfig) { c.Resolution = 128 }, + "other filter": func(c *render3d.CSMConfig) { c.Filter = render3d.ShadowFilterHard }, + } + for name, mutate := range mismatched { + other := cfg + mutate(&other) + f := render3d.FitCascades(camView, camProj, 0.5, 60, lightDir, other) + if err := csm.Update(dev, f); !errors.Is(err, render3d.ErrInvalidCSM) { + t.Errorf("Update(%s) = %v, want ErrInvalidCSM", name, err) + } + if got := csm.CascadeCount(); got != cfg.CascadeCount { + t.Errorf("after Update(%s): CascadeCount() = %d, want %d", name, got, cfg.CascadeCount) + } + if got := csm.Frame(); got != frame { + t.Errorf("Update(%s) replaced the uploaded frame", name) + } + } + for i := range csm.CascadeCount() { + pass := csm.BeginCascadePass(dev.BeginEncoder(), i) + if pass == nil { + t.Fatalf("BeginCascadePass(%d) = nil for i < CascadeCount()", i) + } + pass.End() + } + if err := csm.Update(nil, frame); !errors.Is(err, gpu.ErrDeviceLost) { + t.Errorf("Update(nil dev) = %v, want ErrDeviceLost", err) + } + if csm.ByteSize() == 0 { + t.Error("ByteSize() = 0, want > 0") + } +} + +func TestCSMLargeSceneReferenceRender(t *testing.T) { + scene := csmTestLargeScene() + pillarCPU := scene.pillarMesh() + + cfg := render3d.DefaultCSMConfig() + cfg.CascadeCount = 4 + cfg.Resolution = 128 + cfg.SplitLambda = 0.75 + cfg.MaxShadowDistance = 56.0 + cfg.DepthBias = 0.0025 + cfg.NormalBias = 0.03 + cfg.CascadeBlendRange = 0.1 + cfg.TexelSnap = true + cfg.Filter = render3d.ShadowFilterPCF3x3 + cfg.CasterPadding = 25.0 + + // Compare near cascade texel density vs single-map equivalent at same resolution. + csmFrame := render3d.FitCascadesFromCamera(scene.cam, scene.lightDir, cfg) + singleCfg := cfg + singleCfg.CascadeCount = 1 + singleFrame := render3d.FitCascadesFromCamera(scene.cam, scene.lightDir, singleCfg) + densityGain := singleFrame.Cascades[0].TexelSize / csmFrame.Cascades[0].TexelSize + if densityGain < 3.0 { + t.Fatalf("near cascade texel density gain = %.2fx (csm=%v, single=%v), want >= 3.0x", + densityGain, csmFrame.Cascades[0].TexelSize, singleFrame.Cascades[0].TexelSize) + } + + profiles := []struct { + name string + opts []nsgotest.Option + }{ + {"full", nil}, + {"webgl2-gles3", []nsgotest.Option{nsgotest.NoGPUCompute()}}, + } + + for _, p := range profiles { + t.Run(p.name, func(t *testing.T) { + var ( + dev *gpu.Device + lit csmTestLit + csm *render3d.CascadedShadowMap + groundMesh *render3d.GPUMesh + pillarMesh *render3d.GPUMesh + activeCfg = cfg + lastFrame render3d.CSMFrame + depthAtlas render3d.CSMDepthAtlas + ) + + opts := append([]nsgotest.Option{nsgotest.Size(csmTestWidth, csmTestHeight), nsgotest.ManualFrames()}, p.opts...) + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return gpu.View(cx, gpu.ViewProps{ + TestID: "csm-viewport", + Style: core.Style{Width: core.Pt(csmTestWidth), Height: core.Pt(csmTestHeight)}, + DepthFormat: gpu.FormatDepth24Plus, + OnReady: func(d *gpu.Device) { + dev = d + var err error + csm, err = render3d.NewCascadedShadowMap(cx, dev, cfg) + if err != nil { + t.Fatalf("NewCascadedShadowMap: %v", err) + } + lit = csmTestNewLit(t, cx, dev, csm, scene.rig, []render3d.PBRDrawUniform{ + render3d.NewPBRDrawUniform(math3d.Mat4Identity(), scene.groundMat), + render3d.NewPBRDrawUniform(math3d.Mat4Identity(), scene.pillarMat), + }, false) + groundMesh, err = render3d.UploadMesh(cx, dev, scene.ground, render3d.MeshUpload{Label: "csm-ground"}) + if err != nil { + t.Fatalf("UploadMesh ground: %v", err) + } + pillarMesh, err = render3d.UploadMesh(cx, dev, pillarCPU, render3d.MeshUpload{Label: "csm-pillars"}) + if err != nil { + t.Fatalf("UploadMesh pillars: %v", err) + } + }, + OnFrame: func(frame *gpu.Frame) { + lastFrame = render3d.FitCascadesFromCamera(scene.cam, scene.rig.Directional[0].Direction, activeCfg) + if err := csm.Update(dev, lastFrame); err != nil { + t.Fatalf("csm.Update: %v", err) + } + for i := range csm.CascadeCount() { + sp := csm.BeginCascadePass(frame, i) + csm.DrawCaster(sp, pillarMesh, math3d.Mat4Identity()) + sp.End() + } + + lit.camBuf.WriteCamera(scene.cam) + pass := csmTestMainPass(frame, core.RGB(0x5278a8)) + lit.draw(pass, csm, groundMesh, pillarMesh) + pass.End() + frame.Submit() + }, + }) + }, opts...) + + app.Advance(16 * time.Millisecond) + img, err := app.GPUReadPixels("id:csm-viewport") + if err != nil { + t.Fatalf("GPUReadPixels: %v", err) + } + got := csmTestCloneRGBA(img) + csmTestAssertGolden(t, "csm_large_scene", got) + + // Read back the GPU depth atlas asynchronously on the engine goroutine and verify CPU reference parity. + var readDone bool + app.Post(func() { + render3d.ReadCSMDepthAtlasAsync(dev, csm, func(a render3d.CSMDepthAtlas, rerr error) { + if rerr != nil { + t.Errorf("ReadCSMDepthAtlasAsync: %v", rerr) + return + } + depthAtlas = a + readDone = true + }) + }) + app.Settle() + app.Advance(16 * time.Millisecond) + app.Settle() + if !readDone { + t.Fatal("ReadCSMDepthAtlasAsync callback did not complete") + } + + // Sample world points on the ground plane near both a near pillar (cascade 0) and a far pillar (cascade 3): each pillar casts its shadow along (+lightDir.X / -lightDir.Y, +lightDir.Z / -lightDir.Y) on Y = 0. + dxPerH := scene.lightDir.X / (-scene.lightDir.Y) + dzPerH := scene.lightDir.Z / (-scene.lightDir.Y) + + type probe struct { + name string + world math3d.Vec3 + wantShadow bool + wantCasc int + } + nearP := scene.pillars[0] + c1P := scene.pillars[1] + midP := scene.pillars[2] + farP := scene.pillars[4] + probes := []probe{ + { + name: "near pillar shadow (cascade 0)", + world: math3d.Vec3{X: nearP.centerX + dxPerH*0.8, Y: 0, Z: nearP.centerZ + dzPerH*0.8}, + wantShadow: true, + wantCasc: 0, + }, + { + name: "near sunlit ground (cascade 0)", + world: math3d.Vec3{X: nearP.centerX + 2.0, Y: 0, Z: nearP.centerZ}, + wantShadow: false, + wantCasc: 0, + }, + { + name: "cascade 1 pillar shadow", + world: math3d.Vec3{X: c1P.centerX + dxPerH*1.3, Y: 0, Z: c1P.centerZ + dzPerH*1.3}, + wantShadow: true, + wantCasc: 1, + }, + { + name: "mid pillar shadow (cascade 2)", + world: math3d.Vec3{X: midP.centerX + dxPerH*2.0, Y: 0, Z: midP.centerZ + dzPerH*2.0}, + wantShadow: true, + wantCasc: 2, + }, + { + name: "far pillar shadow (cascade 3)", + world: math3d.Vec3{X: farP.centerX + dxPerH*3.2, Y: 0, Z: farP.centerZ + dzPerH*3.2}, + wantShadow: true, + wantCasc: 3, + }, + { + name: "far sunlit ground (cascade 3)", + world: math3d.Vec3{X: 1.5, Y: 0, Z: farP.centerZ}, + wantShadow: false, + wantCasc: 3, + }, + } + + camView := scene.cam.ViewMatrix() + for _, pr := range probes { + scr, _, visible := scene.cam.WorldToScreen(pr.world, csmTestWidth, csmTestHeight) + if !visible { + t.Fatalf("probe %q at %v is not visible in viewport", pr.name, pr.world) + } + px, py := int(scr.X), int(scr.Y) + // Intersect the exact GPU pixel-center ray with Y = 0 so CPU EvaluateCSM samples the exact world point rasterized at pixel (px, py). + ray := scene.cam.ScreenRay(float32(px)+0.5, float32(py)+0.5, csmTestWidth, csmTestHeight) + tHit := -ray.Origin.Y / ray.Dir.Y + exactWorld := ray.Origin.Add(ray.Dir.Scale(tHit)) + + viewDepth := -camView.TransformPoint(exactWorld).Z + gotCasc, _, _ := lastFrame.SelectCascade(viewDepth) + if pr.wantCasc >= 0 && gotCasc != pr.wantCasc { + t.Errorf("probe %q (viewDepth=%.2f): cascade = %d, want %d", pr.name, viewDepth, gotCasc, pr.wantCasc) + } + + // Compare the CPU reference shadow factor and shaded color with the GPU pixel. + want, cpuShadow := csmTestExpected(lastFrame, depthAtlas, scene.cam, scene.rig, scene.groundMat, exactWorld, viewDepth) + if pr.wantShadow && cpuShadow > 0.35 { + t.Errorf("probe %q: CPU shadow factor = %.3f, want <= 0.35 (in shadow)", pr.name, cpuShadow) + } + if !pr.wantShadow && cpuShadow < 0.85 { + t.Errorf("probe %q: CPU shadow factor = %.3f, want >= 0.85 (lit)", pr.name, cpuShadow) + } + + gpuPix := got.RGBAAt(px, py) + const tol = 4 + if csmTestAbsInt(int(gpuPix.R)-want[0]) > tol || csmTestAbsInt(int(gpuPix.G)-want[1]) > tol || csmTestAbsInt(int(gpuPix.B)-want[2]) > tol { + t.Errorf("probe %q at (%d,%d): GPU RGB=(%d,%d,%d), CPU reference=%v (shadow=%.2f)", pr.name, px, py, gpuPix.R, gpuPix.G, gpuPix.B, want, cpuShadow) + } + } + + // Verify debug cascade tint mode visibly distinguishes cascade 0 (red-tinted) vs cascade 3 (yellow-tinted). + if p.name == "full" { + app.Post(func() { + activeCfg.DebugCascades = true + }) + app.Settle() + app.Advance(16 * time.Millisecond) + dbgImg, err := app.GPUReadPixels("id:csm-viewport") + if err != nil { + t.Fatalf("GPUReadPixels debug: %v", err) + } + nearScr, _, _ := scene.cam.WorldToScreen(probes[1].world, csmTestWidth, csmTestHeight) + farScr, _, _ := scene.cam.WorldToScreen(probes[5].world, csmTestWidth, csmTestHeight) + nearC := dbgImg.RGBAAt(int(nearScr.X), int(nearScr.Y)) + farC := dbgImg.RGBAAt(int(farScr.X), int(farScr.Y)) + if nearC.R <= nearC.G+20 { + t.Errorf("debug cascade 0 pixel %+v expected strong red tint", nearC) + } + if farC.R <= farC.B+20 || farC.G <= farC.B+20 { + t.Errorf("debug cascade 3 pixel %+v expected yellow tint (R,G > B)", farC) + } + if !lastFrame.Config.DebugCascades { + t.Fatal("debug frame was not fitted with DebugCascades") + } + for _, pr := range []probe{probes[1], probes[5]} { + scr, _, _ := scene.cam.WorldToScreen(pr.world, csmTestWidth, csmTestHeight) + px, py := int(scr.X), int(scr.Y) + ray := scene.cam.ScreenRay(float32(px)+0.5, float32(py)+0.5, csmTestWidth, csmTestHeight) + wp := ray.Origin.Add(ray.Dir.Scale(-ray.Origin.Y / ray.Dir.Y)) + want, _ := csmTestExpected(lastFrame, depthAtlas, scene.cam, scene.rig, scene.groundMat, wp, -camView.TransformPoint(wp).Z) + c := dbgImg.RGBAAt(px, py) + if csmTestAbsInt(int(c.R)-want[0]) > 4 || csmTestAbsInt(int(c.G)-want[1]) > 4 || csmTestAbsInt(int(c.B)-want[2]) > 4 { + t.Errorf("debug probe %q at (%d,%d): GPU RGB=(%d,%d,%d), CPU reference with DebugTint=%v", pr.name, px, py, c.R, c.G, c.B, want) + } + } + } + }) + } +} + +// csmTestSmallScene renders a box placed by a non-identity model matrix over a ground plane into a 2-cascade map, drawing the casters into the cascades in the given order. +type csmTestSmallScene struct { + cam *scene3d.Camera + rig render3d.LightRig + groundMat render3d.PBRMaterial + casterModel math3d.Mat4 +} + +func newCSMTestSmallScene() csmTestSmallScene { + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 6.0, Z: 2.5}, math3d.DegToRad(50), 1, 0.5, 30) + cam.LookAt(math3d.Vec3{X: 0, Y: 0, Z: -4.5}, math3d.Vec3Up()) + return csmTestSmallScene{ + cam: cam, + // A white sun and gray ambient keep the gray ground neutral, so penumbra pixels are easy to tell from the red caster. + rig: render3d.LightRig{ + Ambient: render3d.AmbientLight{Color: math3d.Vec3{X: 0.15, Y: 0.15, Z: 0.15}, Intensity: 1}, + Directional: []render3d.DirectionalLight{{Direction: math3d.Vec3{X: 0.55, Y: -0.85, Z: 0.0}, Color: math3d.Vec3{X: 1, Y: 1, Z: 1}, Intensity: 2.5}}, + }, + groundMat: render3d.PBRMaterial{BaseColor: math3d.Vec3{X: 0.85, Y: 0.85, Z: 0.85}, Roughness: 1}, + casterModel: math3d.Translate(math3d.Vec3{X: -0.8, Y: 0, Z: -4.0}), + } +} + +func (sc csmTestSmallScene) render(t *testing.T, filter render3d.ShadowFilter, order []int) (*image.RGBA, render3d.CSMFrame, render3d.CSMDepthAtlas) { + t.Helper() + sr := gpu.NewSoftwareRenderer(96, 96, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + dev := sr.Device() + + cfg := render3d.DefaultCSMConfig() + cfg.CascadeCount = 2 + cfg.Resolution = 128 + cfg.MaxShadowDistance = 30 + cfg.DepthBias = 0.002 + cfg.NormalBias = 0.01 + cfg.Filter = filter + cfg.CascadeBlendRange = 0 + + csm, err := render3d.NewCascadedShadowMap(nil, dev, cfg) + if err != nil { + t.Fatalf("NewCascadedShadowMap: %v", err) + } + t.Cleanup(func() { _ = csm.Close() }) + casterMat := render3d.PBRMaterial{BaseColor: math3d.Vec3{X: 0.8, Y: 0.3, Z: 0.2}, Roughness: 1} + lit := csmTestNewLit(t, nil, dev, csm, sc.rig, []render3d.PBRDrawUniform{ + render3d.NewPBRDrawUniform(math3d.Mat4Identity(), sc.groundMat), + render3d.NewPBRDrawUniform(sc.casterModel, casterMat), + }, false) + + groundMesh, err := render3d.UploadMesh(nil, dev, csmTestGroundMesh(-8, 8, -14, 4), render3d.MeshUpload{}) + if err != nil { + t.Fatalf("UploadMesh ground: %v", err) + } + t.Cleanup(func() { _ = groundMesh.Close() }) + // A box at the origin, placed in the scene only by its model matrix. + box, err := render3d.UploadMesh(nil, dev, csmTestBoxMesh(math3d.Vec3{X: -0.75, Y: 0, Z: -0.75}, math3d.Vec3{X: 0.75, Y: 2.4, Z: 0.75}), render3d.MeshUpload{}) + if err != nil { + t.Fatalf("UploadMesh box: %v", err) + } + t.Cleanup(func() { _ = box.Close() }) + + frame := render3d.FitCascadesFromCamera(sc.cam, sc.rig.Directional[0].Direction, cfg) + if err := csm.Update(dev, frame); err != nil { + t.Fatalf("csm.Update: %v", err) + } + enc := dev.BeginEncoder() + for _, i := range order { + sp := csm.BeginCascadePass(enc, i) + if !csm.DrawCaster(sp, box, sc.casterModel) { + t.Fatalf("DrawCaster into cascade %d returned false", i) + } + sp.End() + } + lit.camBuf.WriteCamera(sc.cam) + mp := csmTestMainPass(enc, core.RGB(0x101820)) + lit.draw(mp, csm, groundMesh, box) + mp.End() + dev.Submit(enc.Finish()) + if sr.LastError() != nil { + t.Fatalf("SoftwareRenderer: %v", sr.LastError()) + } + atlas, err := render3d.ReadCSMDepthAtlas(dev, csm) + if err != nil { + t.Fatalf("ReadCSMDepthAtlas: %v", err) + } + return csmTestCloneRGBA(sr.Image()), frame, atlas +} + +func TestCSMHardVsPCFAndNonIdentityCasterTransform(t *testing.T) { + // Under ShadowFilterHard every ground pixel is either fully shadowed or fully lit; ShadowFilterPCF3x3 adds a penumbra along the shadow edge. The box is placed only by its model matrix, so a shadow at all shows DrawCaster applied it. + sc := newCSMTestSmallScene() + camView := sc.cam.ViewMatrix() + e := sc.cam.Eye() + eye := math3d.Vec3{X: e.X, Y: e.Y, Z: e.Z} + + classify := func(img *image.RGBA, frame render3d.CSMFrame, atlas render3d.CSMDepthAtlas) (shadowed, penumbra, lit, mismatched int) { + b := img.Bounds() + for y := b.Min.Y; y < b.Max.Y; y++ { + for x := b.Min.X; x < b.Max.X; x++ { + c := img.RGBAAt(x, y) + // Ground pixels are neutral gray; the caster is red and the clear color is blue-black. + if csmTestAbsInt(int(c.R)-int(c.G)) > 2 || csmTestAbsInt(int(c.R)-int(c.B)) > 2 || c.R < 25 { + continue + } + ray := sc.cam.ScreenRay(float32(x)+0.5, float32(y)+0.5, 96, 96) + if ray.Dir.Y >= 0 { + continue + } + wp := ray.Origin.Add(ray.Dir.Scale(-ray.Origin.Y / ray.Dir.Y)) + dark := render3d.LinearToSRGB(render3d.ShadePointShadowed(wp, math3d.Vec3Up(), eye.Sub(wp), sc.groundMat, sc.rig, 0)).X * 255 + bright := render3d.LinearToSRGB(render3d.ShadePointShadowed(wp, math3d.Vec3Up(), eye.Sub(wp), sc.groundMat, sc.rig, 1)).X * 255 + f := (float32(c.R) - dark) / (bright - dark) + switch { + case f < 0.1: + shadowed++ + case f > 0.9: + lit++ + default: + penumbra++ + } + want, _ := csmTestExpected(frame, atlas, sc.cam, sc.rig, sc.groundMat, wp, -camView.TransformPoint(wp).Z) + if csmTestAbsInt(int(c.R)-want[0]) > 4 { + mismatched++ + } + } + } + return shadowed, penumbra, lit, mismatched + } + + hardImg, hardFrame, hardAtlas := sc.render(t, render3d.ShadowFilterHard, []int{0, 1}) + pcfImg, pcfFrame, pcfAtlas := sc.render(t, render3d.ShadowFilterPCF3x3, []int{0, 1}) + hShad, hPen, hLit, hBad := classify(hardImg, hardFrame, hardAtlas) + pShad, pPen, pLit, pBad := classify(pcfImg, pcfFrame, pcfAtlas) + if hShad < 50 || hLit < 200 { + t.Fatalf("hard shadow render missing shadow/lit ground: shadowed=%d lit=%d", hShad, hLit) + } + if pShad < 20 || pLit < 200 { + t.Fatalf("PCF shadow render missing shadow/lit ground: shadowed=%d lit=%d", pShad, pLit) + } + if hPen != 0 { + t.Errorf("ShadowFilterHard produced %d penumbra pixels, want 0", hPen) + } + if pPen < 20 { + t.Errorf("ShadowFilterPCF3x3 produced only %d penumbra pixels, want >= 20", pPen) + } + // A pixel right on a shadow edge can land on the other side of a depth comparison on the CPU, so allow a handful. + if hBad > 4 || pBad > 4 { + t.Errorf("ground pixels off the CPU reference by more than 4: hard %d, PCF %d", hBad, pBad) + } + + // The first pass after Update clears the atlas whichever cascade it draws, so drawing cascade 1 before cascade 0 gives the same atlas and image. + revImg, _, revAtlas := sc.render(t, render3d.ShadowFilterPCF3x3, []int{1, 0}) + if d := csmTestDiffPixels(pcfImg, revImg); d != 0 { + t.Errorf("rendering cascades in reverse order changed %d pixels", d) + } + for i := range pcfAtlas.Depth { + if pcfAtlas.Depth[i] != revAtlas.Depth[i] { + t.Fatalf("rendering cascades in reverse order changed atlas texel %d: %v, want %v", i, revAtlas.Depth[i], pcfAtlas.Depth[i]) + } + } +} + +func TestCSMDrawCasterSlots(t *testing.T) { + sr := gpu.NewSoftwareRenderer(16, 16, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + dev := sr.Device() + cfg := render3d.DefaultCSMConfig() + cfg.Resolution = 32 + cfg.MaxCasters = 4 // slot 0 is the identity, so three distinct models fit + csm, err := render3d.NewCascadedShadowMap(nil, dev, cfg) + if err != nil { + t.Fatalf("NewCascadedShadowMap: %v", err) + } + t.Cleanup(func() { _ = csm.Close() }) + mesh, err := render3d.UploadMesh(nil, dev, csmTestBoxMesh(math3d.Vec3{X: -0.5, Y: 0, Z: -0.5}, math3d.Vec3{X: 0.5, Y: 1, Z: 0.5}), render3d.MeshUpload{}) + if err != nil { + t.Fatalf("UploadMesh: %v", err) + } + t.Cleanup(func() { _ = mesh.Close() }) + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{Y: 4, Z: 4}, math3d.DegToRad(60), 1, 0.5, 40) + cam.LookAt(math3d.Vec3{}, math3d.Vec3Up()) + frame := render3d.FitCascadesFromCamera(cam, math3d.Vec3{X: 0.3, Y: -1, Z: -0.2}, csm.Config()) + + models := []math3d.Mat4{ + math3d.Translate(math3d.Vec3{X: 1}), + math3d.Translate(math3d.Vec3{X: 2}), + math3d.Translate(math3d.Vec3{X: 3}), + } + extra := math3d.Translate(math3d.Vec3{X: 4}) + for round := range 2 { + if err := csm.Update(dev, frame); err != nil { + t.Fatalf("Update: %v", err) + } + enc := dev.BeginEncoder() + // Each of the three models is drawn into all four cascades: twelve draws, three slots. + for i := range csm.CascadeCount() { + pass := csm.BeginCascadePass(enc, i) + for _, m := range models { + if !csm.DrawCaster(pass, mesh, m) { + t.Fatalf("round %d cascade %d: DrawCaster(%v) = false with a slot per model", round, i, m[12]) + } + } + if !csm.DrawCaster(pass, mesh, math3d.Mat4Identity()) { + t.Fatalf("round %d cascade %d: DrawCaster(identity) = false", round, i) + } + if csm.DrawCaster(pass, mesh, extra) { + t.Fatalf("round %d cascade %d: DrawCaster(fourth model) = true past MaxCasters", round, i) + } + pass.End() + } + dev.Submit(enc.Finish()) + if sr.LastError() != nil { + t.Fatalf("SoftwareRenderer: %v", sr.LastError()) + } + } + if csm.DrawCaster(nil, mesh, extra) { + t.Error("DrawCaster(nil pass) = true") + } +} + +func TestCSMOrthographicCamera(t *testing.T) { + cfg := render3d.DefaultCSMConfig() + cfg.CascadeCount = 2 + cfg.Resolution = 64 + lightDir := math3d.Vec3{X: 0.3, Y: -1, Z: -0.2} + eye := math3d.Vec3{Y: 10, Z: 10} + target := math3d.Vec3{} + + // An orthographic camera whose near plane is behind it: cascades start at 0.1 and still cover the stretch of the view frustum they claim. + cam := scene3d.NewOrthographicCamera(eye, 20, 1, -10, 50) + cam.LookAt(target, math3d.Vec3Up()) + frame := render3d.FitCascadesFromCamera(cam, lightDir, cfg) + if frame.Splits[0] != 0.1 || frame.Splits[2] != 50 { + t.Fatalf("splits = %v, want them to span [0.1, 50]", frame.Splits[:3]) + } + view := cam.ViewMatrix() + inv, ok := view.Inverse() + if !ok { + t.Fatal("camera view matrix is singular") + } + for i := range frame.CascadeCount { + c := frame.Cascades[i] + for _, d := range []float32{c.Near, c.Far} { + for _, xy := range [][2]float32{{-10, -10}, {10, -10}, {10, 10}, {-10, 10}} { + // The view-space corner of the camera's box at depth d, in world space, must project inside the cascade. + wp := inv.TransformPoint(math3d.Vec3{X: xy[0], Y: xy[1], Z: -d}) + ndc := c.LightViewProj.TransformPoint(wp) + const eps = 1e-3 + if ndc.X < -1-eps || ndc.X > 1+eps || ndc.Y < -1-eps || ndc.Y > 1+eps || ndc.Z < -eps || ndc.Z > 1+eps { + t.Errorf("cascade %d: frustum corner %v at depth %v projects to %v, outside the cascade", i, xy, d, ndc) + } + } + } + } + + // Near and Far both zero take the 0.1 and 1000 defaults ProjMatrix uses. + def := scene3d.NewOrthographicCamera(eye, 20, 1, 0, 0) + def.LookAt(target, math3d.Vec3Up()) + if f := render3d.FitCascadesFromCamera(def, lightDir, cfg); f.Splits[0] != 0.1 || f.Splits[2] != 1000 { + t.Errorf("default orthographic splits = %v, want them to span [0.1, 1000]", f.Splits[:3]) + } +} + +func TestCSMRetainedDeviceLossAndClose(t *testing.T) { + scene := csmTestLargeScene() + pillarCPU := scene.pillarMesh() + + cfg := render3d.DefaultCSMConfig() + cfg.CascadeCount = 2 + cfg.Resolution = 64 + cfg.MaxShadowDistance = 30 + cfg.Filter = render3d.ShadowFilterHard + cfg.Retained = true + + const size = 64 + var ( + dev *gpu.Device + lit csmTestLit + csm *render3d.CascadedShadowMap + groundMesh *render3d.GPUMesh + pillarMesh *render3d.GPUMesh + ) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return gpu.View(cx, gpu.ViewProps{ + TestID: "csm-retained", + Style: core.Style{Width: core.Pt(size), Height: core.Pt(size)}, + DepthFormat: gpu.FormatDepth24Plus, + OnReady: func(d *gpu.Device) { + dev = d + var err error + if csm == nil { + csm, err = render3d.NewCascadedShadowMap(cx, dev, cfg) + if err != nil { + t.Fatalf("NewCascadedShadowMap: %v", err) + } + } + lit = csmTestNewLit(t, cx, dev, csm, scene.rig, []render3d.PBRDrawUniform{ + render3d.NewPBRDrawUniform(math3d.Mat4Identity(), scene.groundMat), + render3d.NewPBRDrawUniform(math3d.Mat4Identity(), scene.pillarMat), + }, true) + if groundMesh == nil { + groundMesh, err = render3d.UploadMesh(cx, dev, scene.ground, render3d.MeshUpload{Label: "g", Retained: true}) + if err != nil { + t.Fatalf("UploadMesh ground: %v", err) + } + pillarMesh, err = render3d.UploadMesh(cx, dev, pillarCPU, render3d.MeshUpload{Label: "p", Retained: true}) + if err != nil { + t.Fatalf("UploadMesh pillars: %v", err) + } + } + }, + OnFrame: func(frame *gpu.Frame) { + f := render3d.FitCascadesFromCamera(scene.cam, scene.lightDir, cfg) + if err := csm.Update(dev, f); err != nil { + t.Fatalf("csm.Update: %v", err) + } + for i := range csm.CascadeCount() { + sp := csm.BeginCascadePass(frame, i) + csm.DrawCaster(sp, pillarMesh, math3d.Mat4Identity()) + sp.End() + } + lit.camBuf.WriteCamera(scene.cam) + pass := csmTestMainPass(frame, core.RGB(0x5278a8)) + lit.draw(pass, csm, groundMesh, pillarMesh) + pass.End() + frame.Submit() + }, + }) + }, nsgotest.Size(size, size), nsgotest.ManualFrames()) + + app.Advance(16 * time.Millisecond) + before, err := app.GPUReadPixels("id:csm-retained") + if err != nil { + t.Fatalf("GPUReadPixels before loss: %v", err) + } + beforeCopy := csmTestCloneRGBA(before) + firstCSM := csm + if !firstCSM.Valid() { + t.Fatal("csm not valid before device loss") + } + + app.TriggerGPUDeviceLost("id:csm-retained", nsgotest.GPULostContextLost, "context lost") + if firstCSM.Valid() { + t.Fatal("csm still valid while device is lost") + } + + app.RestoreGPUDevice("id:csm-retained") + if csm != firstCSM || !firstCSM.Valid() { + t.Fatalf("retained csm not restored: same=%v valid=%v", csm == firstCSM, firstCSM.Valid()) + } + + app.Advance(16 * time.Millisecond) + after, err := app.GPUReadPixels("id:csm-retained") + if err != nil { + t.Fatalf("GPUReadPixels after restore: %v", err) + } + if diff := csmTestDiffPixels(beforeCopy, after); diff != 0 { + t.Errorf("frame after device restore differed by %d pixels, want 0", diff) + } + + // Test Close idempotency and nil receiver safety. + sr := gpu.NewSoftwareRenderer(8, 8, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + closeable, err := render3d.NewCascadedShadowMap(nil, sr.Device(), render3d.CSMConfig{CascadeCount: 2, Resolution: 32}) + if err != nil { + t.Fatalf("NewCascadedShadowMap: %v", err) + } + if err := closeable.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + if closeable.Valid() { + t.Fatal("csm still valid after Close") + } + if err := closeable.Close(); err != nil { + t.Fatalf("second Close: %v", err) + } + if closeable.BeginCascadePass(sr.Device().BeginEncoder(), 0) != nil { + t.Error("BeginCascadePass on closed csm returned non-nil") + } + + var nilCSM *render3d.CascadedShadowMap + if nilCSM.Valid() || nilCSM.CascadeCount() != 0 || nilCSM.AtlasWidth() != 0 || nilCSM.AtlasHeight() != 0 || + nilCSM.DepthTexture() != nil || nilCSM.Sampler() != nil || nilCSM.UniformBuffer() != nil || + nilCSM.Layout() != nil || nilCSM.BindGroup() != nil || nilCSM.DepthPipeline() != nil || + nilCSM.CascadeBindGroup(0) != nil || nilCSM.CasterModelLayout() != nil || nilCSM.ByteSize() != 0 || + nilCSM.Close() != nil { + t.Error("nil CascadedShadowMap accessors violated zero-value safety") + } +} + +func csmTestAbsInt(v int) int { + if v < 0 { + return -v + } + return v +} + +func csmTestCloneRGBA(src *image.RGBA) *image.RGBA { + dst := image.NewRGBA(src.Bounds()) + copy(dst.Pix, src.Pix) + return dst +} + +func csmTestDiffPixels(a, b *image.RGBA) int { + n := 0 + bounds := a.Bounds() + for y := bounds.Min.Y; y < bounds.Max.Y; y++ { + for x := bounds.Min.X; x < bounds.Max.X; x++ { + pa, pb := a.RGBAAt(x, y), b.RGBAAt(x, y) + if csmTestAbsInt(int(pa.R)-int(pb.R)) > 2 || + csmTestAbsInt(int(pa.G)-int(pb.G)) > 2 || + csmTestAbsInt(int(pa.B)-int(pb.B)) > 2 { + n++ + } + } + } + return n +} diff --git a/packages/game/render3d/light.go b/packages/game/render3d/light.go index 1ce04b44..ec343fc8 100644 --- a/packages/game/render3d/light.go +++ b/packages/game/render3d/light.go @@ -957,11 +957,13 @@ type LitPBRPipelineOptions struct { SpotShadowLayout *gpu.BindGroupLayout // PointShadowLayout, when set, compiles [LitPBRPointShadowWGSL] with this layout ([PointShadowMap.Layout]) at [LocalShadowGroup], as [NewLitPBRPointShadowPipeline] does, so the first point light of the [LightRig] is attenuated by the point shadow atlas. It uses bind group 3 like the directional shadow, fog, IBL and skinning, so it cannot be combined with any of them. PointShadowLayout *gpu.BindGroupLayout + // CSMLayout, when set, compiles [LitPBRCSMWGSL] with this layout ([CascadedShadowMap.Layout]) at [CSMGroup], as [NewLitPBRCSMPipeline] does, so the first directional light of the [LightRig] is attenuated by the cascaded shadow map. It uses bind group 3 like the single directional shadow, spot and point shadows, fog, IBL and skinning, so it cannot be combined with any of them. + CSMLayout *gpu.BindGroupLayout // LinearOutput skips the final linear-to-sRGB encoding and its clamp to [0, 1] and writes the lit linear radiance ([ShadePoint], plus [EvaluateIBL] or [Fog.Apply] when enabled), for drawing into an [HDRTarget] that a [ToneMapPass] then resolves to the display. LinearOutput bool } -// NewLitPBRPipelineWithOptions creates a lit PBR pipeline like [NewLitPBRPipeline], [NewLitPBRFogPipeline], [NewLitPBRIBLPipeline], [NewLitPBRShadowPipeline], [NewLitPBRSpotShadowPipeline] or [NewLitPBRPointShadowPipeline], with a configurable color format, with [LitPBRPipelineOptions].LinearOutput linear HDR output for an [HDRTarget], and with [LitPBRPipelineOptions].SkinLayout GPU skinning. +// NewLitPBRPipelineWithOptions creates a lit PBR pipeline like [NewLitPBRPipeline], [NewLitPBRFogPipeline], [NewLitPBRIBLPipeline], [NewLitPBRShadowPipeline], [NewLitPBRSpotShadowPipeline], [NewLitPBRPointShadowPipeline] or [NewLitPBRCSMPipeline], with a configurable color format, with [LitPBRPipelineOptions].LinearOutput linear HDR output for an [HDRTarget], and with [LitPBRPipelineOptions].SkinLayout GPU skinning. func NewLitPBRPipelineWithOptions(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout *gpu.BindGroupLayout, opts LitPBRPipelineOptions) (*gpu.Pipeline, error) { if dev == nil { return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} @@ -986,6 +988,13 @@ func NewLitPBRPipelineWithOptions(cx *core.Scope, dev *gpu.Device, camLayout, li return nil, gpu.Error{Code: gpu.ErrInvalidDescriptor, Message: "render3d: spot and point shadows use bind group 3 like the directional shadow, fog, IBL and skinning; set at most one of them"} } } + if opts.CSMLayout != nil { + for _, l := range [...]*gpu.BindGroupLayout{opts.FogLayout, opts.IBLLayout, opts.SkinLayout, opts.ShadowLayout, opts.SpotShadowLayout, opts.PointShadowLayout} { + if l != nil { + return nil, gpu.Error{Code: gpu.ErrInvalidDescriptor, Message: "render3d: the cascaded shadow map uses bind group 3 like the directional, spot and point shadows, fog, IBL and skinning; set CSMLayout without any of them"} + } + } + } label, src, linearSrc := "render3d.lit_pbr", LitPBRWGSL, litPBRLinearWGSL vertexLayout := MeshVertexLayout() layouts := make([]*gpu.BindGroupLayout, PBRDrawGroup+1, FogGroup+1) @@ -1012,6 +1021,9 @@ func NewLitPBRPipelineWithOptions(cx *core.Scope, dev *gpu.Device, camLayout, li case opts.PointShadowLayout != nil: label, src, linearSrc = "render3d.lit_pbr_point_shadow", LitPBRPointShadowWGSL, litPBRPointShadowLinearWGSL layouts = append(layouts, opts.PointShadowLayout) + case opts.CSMLayout != nil: + label, src, linearSrc = "render3d.lit_pbr_csm", LitPBRCSMWGSL, litPBRCSMLinearWGSL + layouts = append(layouts, opts.CSMLayout) } layouts[CameraGroup] = camLayout layouts[LightGroup] = lightLayout diff --git a/packages/game/render3d/testdata/golden/csm_large_scene.png b/packages/game/render3d/testdata/golden/csm_large_scene.png new file mode 100644 index 00000000..920e5b7a Binary files /dev/null and b/packages/game/render3d/testdata/golden/csm_large_scene.png differ