From de21ff85fb1b52f72bc3e996b1aef5175effcc9a Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Tue, 24 Nov 2026 19:28:42 +0900 Subject: [PATCH 1/2] feat(render3d): add clustered forward shading for many local lights --- .../2026-11-24-render3d-clustered-forward.md | 41 + changelog.d/render3d-clustered-forward-382.md | 3 + docs/en/render3d.md | 35 + docs/zh/render3d.md | 35 + packages/game/render3d/clustered.go | 1691 +++++++++++++++++ packages/game/render3d/clustered_test.go | 908 +++++++++ 6 files changed, 2713 insertions(+) create mode 100644 .agents/notes/implemented/feature/2026-11-24-render3d-clustered-forward.md create mode 100644 changelog.d/render3d-clustered-forward-382.md create mode 100644 packages/game/render3d/clustered.go create mode 100644 packages/game/render3d/clustered_test.go diff --git a/.agents/notes/implemented/feature/2026-11-24-render3d-clustered-forward.md b/.agents/notes/implemented/feature/2026-11-24-render3d-clustered-forward.md new file mode 100644 index 00000000..c72f6906 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-24-render3d-clustered-forward.md @@ -0,0 +1,41 @@ +# Agent Note: Clustered Forward Lighting in render3d + +Status: implemented + +## Problem + +`render3d` needs to render scenes with hundreds of local point and spot lights (256+ lights within a 60 fps desktop frame budget) without switching away from forward rendering or breaking mobile and browser targets (WebGL 2 / OpenGL ES 3.0) that lack compute shaders and storage buffers (`Features.Compute == false`, `Features.StorageBuffers == false`, simulated in tests via `nsgotest.NoGPUCompute`). + +Three NSGo-specific constraints shape the design: +- NSGo v0.3.0's software GPU VM (used by headless `nsgotest` and `gpu.NewSoftwareRenderer`) omits `shaderir.Log2`, `shaderir.Exp`, and `shaderir.Exp2`, so the textbook `floor(log2(z / near) * scale)` depth-slice formula in WGSL would fail in software GPU tests. +- WebGL 2 and OpenGL ES 3.0 disallow `UsageStorage` buffers and `BindingStorageRead` bind-group entries; any light system targeting all NSGo backends must automatically drop to a pure uniform-buffer path when `DeviceSupportsClusteredLighting(dev)` is false. +- Retained GPU resources survive device loss and restore by retargeting buffers to the restored device; holding a stale `*gpu.Device` inside the light system breaks updates after `RestoreGPUDevice`. + +## Decision + +`packages/game/render3d/clustered.go` implements a dual-path clustered forward lighting system (`ClusterGrid`, `ClusteredLightSystem`, `ClusterLight`, `ClusterConfig`) alongside pure-Go analytic evaluators (`EvaluateLightAttenuation`, `EvaluateDirectLights`, `EvaluateClusteredLights`): + +- **Zero-allocation CPU frustum clustering (`ClusterGrid`)**: Partitions view space into `TilesX × TilesY × SlicesZ` (default `16 × 9 × 24 = 3,456` clusters) using logarithmic depth splits `z_i = near * (far/near)^(i/SlicesZ)` for perspective projections (and linear splits for orthographic). Cluster view-space AABBs are cached by `(proj, near, far)` and reused across camera translation/rotation. `AssignLights` culls off-frustum lights, computes conservative screen-tile and Z-slice bounds (clamping near-plane-straddling lights to the full tile span so there are zero false negatives), runs exact sphere-vs-AABB plus Bart Wronski tight bounding-sphere + cone-vs-AABB rejection for `ClusterLightSpot`, and packs contiguous `ClusterOffsetCount` + `LightIndices` slices with 0 heap allocations in steady state. +- **Portable binary-search depth slicing in WGSL**: `ClusteredBindingsWGSL` passes up to `MaxClusterSlicesZ + 1` (65) slice boundaries in a fixed 17 × `vec4` uniform array (`ClusterParams.slice_depths`) and computes `slice_z` with a fixed 6-step binary search (`cluster_find_slice`) over `view_z = -(camera.view * vec4(world_pos, 1.0)).z`. This avoids `log2`/`exp`, avoids dynamic vector indexing, and works identically across Metal, Direct3D 11, OpenGL 3.3, WebGPU, and NSGo's software GPU VM. +- **Automatic capability-gated fallback (`ClusteredLightSystem`)**: `NewClusteredLightSystem` inspects `DeviceSupportsClusteredLighting(dev)` (requiring `Features.StorageBuffers`, `Features.Compute`, and `MaxStorageBufferBindingSize >= 64 KiB`, unless `ForceFallback` is set). On capable devices it binds 1 uniform buffer (`ClusterParams`, 320 bytes) + 3 read-only storage buffers (`cluster_lights`, `cluster_cells`, `cluster_indices`) at `@group(1)` (`ClusteredLightGroup = 1`), all 16-byte aligned (`vec4` / `vec4`). On WebGL 2 / OpenGL ES 3.0 / `nsgotest.NoGPUCompute` devices it allocates a single 1,056-byte uniform buffer (`FallbackLightUniform`) holding up to `FallbackMaxLights` (default/max `16`) lights prioritized per frame by `SelectFallbackLights`. +- **Shared WGSL evaluation signature**: Both `ClusteredBindingsWGSL` and `ClusteredFallbackBindingsWGSL` expose `evaluate_clustered_lights(world_pos, normal, frag_pos) -> vec3` with glTF `KHR_lights_punctual` smooth range and spotlight attenuation, so both the built-in shaders (`ClusteredLitWGSL`, `ClusteredFallbackWGSL`) and user material shaders share one fragment body across desktop and mobile paths. +- **Explicit `*gpu.Device` on `Update`/`UpdateCamera`**: Matching `GPUTexture` and `GPUMorphMesh`, `ClusteredLightSystem` never caches a `*gpu.Device` pointer, allowing `ClusterConfig.Retained` buffers to recover and resume updating cleanly across GPU device loss and restore. + +## Alternatives considered + +### Compute-shader light assignment on the GPU + +Assigning lights to clusters in a WGSL compute pass avoids uploading per-frame cell and index buffers from the CPU. However, NSGo's software GPU device runs compute workgroups sequentially on the CPU (making 3,456 × 256 invocations far slower in headless tests), requires atomic append counters in WGSL (`atomicAdd`) across all native backends, and still needs a CPU path for capability-limited targets. CPU `ClusterGrid.AssignLights` handles 256 point lights in well under 1 ms with 0 heap allocations, keeps buffer sizes deterministic (~884 KiB max index buffer), and lets headless tests and servers share the exact same culling logic. + +### `log2(view_z / near)` slice indexing in WGSL + +Computing `u32(log2(view_z / near) * inv_log_ratio)` saves 272 bytes in `ClusterParams`. It was rejected because NSGo v0.3.0's software GPU VM does not implement `shaderir.Log2`, which would break headless GPU parity tests, and because a uniform split-depth table also supports orthographic linear slicing and custom depth distributions with zero shader changes. + +### Packing clustered light lists into a 2D RGBA32UI texture for WebGL 2 + +Emulating storage buffers via `textureLoad` on floating-point/integer textures could allow clustering on WebGL 2 without storage buffers, at the cost of requiring `Features.ExtendedFormats` (`FormatRGBA32Float` / integer texture formats) and much higher fragment-shader texture-fetch pressure on mobile tile GPUs. A prioritized 16-light uniform-buffer fallback (`SelectFallbackLights`) uses only core WebGL 2 / GLES 3.0 uniform buffers and stays comfortably within mobile fragment budgets. + +## Consequences + +- **Benefits**: Desktop GPU targets render 256+ local point and spot lights with zero steady-state CPU allocations, exact CPU-vs-GPU pixel parity (verified by `TestClustered256PointLightsParityAndBudget` and `TestClusteredMixedPointAndSpotLightsGPU`), and automatic seamless fallback on `nsgotest.NoGPUCompute` (WebGL 2 / GLES 3.0) with `Retained` device-loss recovery. Keeping all code in standalone `clustered.go` / `clustered_test.go` avoids merge conflicts with parallel `render3d` work. +- **Costs**: Cluster assignment runs on the CPU and uploads `cells` and `indices` buffers each frame via `Device.WriteBuffer` (scaling linearly with active cluster assignments, capped by `MaxLightsPerCluster` and `MaxStorageBufferBindingSize`). Depth slice count is capped at `MaxClusterSlicesZ = 64` to fit the fixed 17 × `vec4` uniform split table, and `FallbackMaxLights` is capped at `16` to stay compact inside WebGL 2 / GLES 3.0 uniform buffers. diff --git a/changelog.d/render3d-clustered-forward-382.md b/changelog.d/render3d-clustered-forward-382.md new file mode 100644 index 00000000..99d3ea97 --- /dev/null +++ b/changelog.d/render3d-clustered-forward-382.md @@ -0,0 +1,3 @@ +### Added + +- `game/render3d`: clustered forward shading (`ClusterGrid`, `ClusteredLightSystem`, `ClusterLight`, `ClusterConfig`, `SelectFallbackLights`, `ClusteredLitWGSL`, `ClusteredFallbackWGSL`) supporting hundreds of point and spot lights on desktop storage-buffer devices with automatic prioritized uniform-buffer fallback on WebGL 2 / OpenGL ES 3.0 targets without compute or storage buffers (#382). diff --git a/docs/en/render3d.md b/docs/en/render3d.md index 5ffff73f..130f21a3 100644 --- a/docs/en/render3d.md +++ b/docs/en/render3d.md @@ -1177,3 +1177,38 @@ _ = stack.SetCamera(cam) - **Depth of Field (`DepthOfFieldConfig`, `DepthOfFieldPass`)**: linearizes perspective or orthographic `[0, 1]` depth to compute a signed Circle of Confusion around `FocusDistance` ± `FocusRange`, then gathers an 18-tap two-ring disc bokeh blur that prevents blurred background pixels from bleeding across sharp in-focus silhouettes. - **Bloom (`BloomConfig`, `BloomPass`)**: extracts bright LDR or HDR (`> 1.0`) pixels with a quadratic `Threshold` / `SoftKnee` curve, runs `BlurPasses` separable 9-tap Gaussian horizontal and vertical passes (optionally at half resolution via `HalfRes`), and composites the glow additively with `Intensity`. - **Portability, lifecycle, and reference renders**: every pass uses fragment-only portable WGSL with explicit `textureSampleLevel` and algebraic/precomputed weights (no compute shaders or `exp`/`log2` instructions), running on both full and `nsgotest.NoGPUCompute` (WebGL 2 / OpenGL ES 3.0) profiles, supporting `Resize(dev, w, h)` and `Retained` device-loss recovery. Golden reference renders (`render3d/testdata/golden/post3d_bloom.png`, `post3d_ssao.png`, `post3d_dof.png`, and `post3d_combined.png`) verify each pass and the combined stack; `UPDATE_GOLDEN=1` rewrites them. + +## Clustered forward lighting (`ClusteredLightSystem`, `ClusterGrid`) + +`ClusterGrid` and `ClusteredLightSystem` scale local point and spot lighting to hundreds of simultaneous lights by partitioning the view frustum into a 3D screen-tile × logarithmic-depth-slice grid (default `16 × 9 × 24`, up to `512` visible lights and `64` lights per cluster), with automatic fallback to a pure uniform-buffer shader on targets without storage buffers or compute shaders (WebGL 2, OpenGL ES 3.0, and headless tests using `nsgotest.NoGPUCompute`): + +```go +camBuf, err := render3d.NewCameraBuffer(cx, dev) +lights, err := render3d.NewClusteredLightSystem(cx, dev, render3d.DefaultClusterConfig()) + +// Compile the shader matching the active path (ClusteredLitWGSL or ClusteredFallbackWGSL): +mod, err := gpu.CompileWGSL(lights.WGSL()) +pipe, err := dev.CreatePipeline(cx, gpu.PipelineDesc{ + Vertex: gpu.ShaderStage{Module: mod, EntryPoint: "vs_main"}, + Fragment: gpu.ShaderStage{Module: mod, EntryPoint: "fs_main"}, + Layouts: []*gpu.BindGroupLayout{render3d.CameraGroup: camBuf.Layout(), render3d.ClusteredLightGroup: lights.Layout()}, + VertexBuffers: []gpu.VertexBufferLayout{render3d.MeshVertexLayout()}, + DepthStencil: &gpu.DepthStencilState{Format: gpu.FormatDepth24Plus, DepthWrite: true, DepthCompare: gpu.CompareLess}, + Targets: []gpu.ColorTargetState{{Format: dev.SurfaceFormat(), WriteMask: gpu.ColorWriteAll}}, +}) + +// Each frame, before recording draws: +camBuf.WriteCamera(cam) +stats := lights.UpdateCamera(dev, cam, viewW, viewH, ambient, sceneLights) + +pass.SetPipeline(pipe) +pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) +lights.Bind(pass, render3d.ClusteredLightGroup) +mesh.Draw(pass) +``` + +- **Zero-allocation CPU clustering (`ClusterGrid`)**: view-space cluster AABBs are cached by `(proj, near, far)` and reused across camera motion. `AssignLights` culls off-frustum lights, computes tight screen-tile and logarithmic depth-slice bounds, tests sphere-vs-AABB (plus conservative cone-vs-AABB rejection for `ClusterLightSpot`), and packs compact `Offsets` and `LightIndices` slices with zero steady-state allocations. +- **Portable depth-slice lookup**: the clustered fragment shader (`ClusteredBindingsWGSL` / `ClusteredLitWGSL`) maps each fragment's view-space depth to its slice via a 6-step binary search over the uniform split-depth table rather than `log2`/`exp`, so it produces identical results on Metal, Direct3D 11, OpenGL 3.3, WebGPU, and NSGo's software GPU VM. +- **Automatic mobile / WebGL 2 fallback**: when `DeviceSupportsClusteredLighting(dev)` is false (or `ClusterConfig.ForceFallback` is set), `NewClusteredLightSystem` switches to a single 1,056-byte uniform buffer (`ClusteredFallbackBindingsWGSL` / `ClusteredFallbackWGSL`) and selects up to `FallbackMaxLights` (default `16`) highest-priority lights each frame via `SelectFallbackLights`. Both shader paths expose the identical `evaluate_clustered_lights(world_pos, normal, frag_pos)` WGSL helper so custom material shaders share one fragment body across desktop and mobile. +- **Attenuation & CPU reference**: point and spot lights (`NewPointClusterLight`, `NewSpotClusterLight`) use glTF `KHR_lights_punctual` smooth range and cone attenuation; `EvaluateLightAttenuation`, `EvaluateDirectLights`, and `EvaluateClusteredLights` provide pure-Go reference shading matching the WGSL math. +- **Lifecycle & device loss**: set `ClusterConfig.Retained` to restore buffers across GPU device loss automatically; `ByteSize()` reports GPU buffer bytes for `RenderStats` and budgets, and `Close()` releases resources eagerly. diff --git a/docs/zh/render3d.md b/docs/zh/render3d.md index 28ea7d55..990f7d61 100644 --- a/docs/zh/render3d.md +++ b/docs/zh/render3d.md @@ -1177,3 +1177,38 @@ _ = stack.SetCamera(cam) - **景深(`DepthOfFieldConfig`、`DepthOfFieldPass`)**:支持透视与正交 `[0, 1]` 深度线性化,围绕 `FocusDistance` ± `FocusRange` 计算带符号弥散圆(CoC),并通过 18 采样双环圆盘散景模糊平滑虚化近景与远景,同时阻止背景模糊色溢入清晰的焦内轮廓。 - **泛光(`BloomConfig`、`BloomPass`)**:用二次软拐点阈值曲线(`Threshold`、`SoftKnee`)提取 LDR 或 HDR(`> 1.0`)高亮像素,执行 `BlurPasses` 轮可分离 9 采样高斯横纵模糊(可通过 `HalfRes` 启用半分辨率以获得更宽柔和光晕),再以 `Intensity` 加法混合回场景。 - **跨后端兼容性、生命周期与参考渲染**:所有通道均使用纯片元可移植 WGSL、显式 `textureSampleLevel` 以及代数/预计算权重(不依赖计算着色器,也不使用 `exp`/`log2` 指令),同时兼容完整能力与 `nsgotest.NoGPUCompute`(WebGL 2 / OpenGL ES 3.0)配置,并支持 `Resize(dev, w, h)` 与 `Retained` 设备丢失恢复。黄金参考图(`render3d/testdata/golden/post3d_bloom.png`、`post3d_ssao.png`、`post3d_dof.png` 与 `post3d_combined.png`)用于验证各个独立通道与组合栈;设置 `UPDATE_GOLDEN=1` 可重写参考图。 + +## 集群前向光照(`ClusteredLightSystem`、`ClusterGrid`) + +`ClusterGrid` 与 `ClusteredLightSystem` 将视锥体划分为屏幕瓦片 × 对数深度切片的 3D 网格(默认 `16 × 9 × 24`,最多支持 `512` 个可见局部光源、单格最多 `64` 个光源),让数百个点光源与聚光灯保持在帧预算内;在不支持存储缓冲或计算着色器的目标(WebGL 2、OpenGL ES 3.0 及 `nsgotest.NoGPUCompute` 无头测试)上自动回退为纯 uniform 缓冲着色路径: + +```go +camBuf, err := render3d.NewCameraBuffer(cx, dev) +lights, err := render3d.NewClusteredLightSystem(cx, dev, render3d.DefaultClusterConfig()) + +// 编译与当前生效路径匹配的着色器(ClusteredLitWGSL 或 ClusteredFallbackWGSL): +mod, err := gpu.CompileWGSL(lights.WGSL()) +pipe, err := dev.CreatePipeline(cx, gpu.PipelineDesc{ + Vertex: gpu.ShaderStage{Module: mod, EntryPoint: "vs_main"}, + Fragment: gpu.ShaderStage{Module: mod, EntryPoint: "fs_main"}, + Layouts: []*gpu.BindGroupLayout{render3d.CameraGroup: camBuf.Layout(), render3d.ClusteredLightGroup: lights.Layout()}, + VertexBuffers: []gpu.VertexBufferLayout{render3d.MeshVertexLayout()}, + DepthStencil: &gpu.DepthStencilState{Format: gpu.FormatDepth24Plus, DepthWrite: true, DepthCompare: gpu.CompareLess}, + Targets: []gpu.ColorTargetState{{Format: dev.SurfaceFormat(), WriteMask: gpu.ColorWriteAll}}, +}) + +// 每帧录制绘制命令前更新相机与光源集群: +camBuf.WriteCamera(cam) +stats := lights.UpdateCamera(dev, cam, viewW, viewH, ambient, sceneLights) + +pass.SetPipeline(pipe) +pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) +lights.Bind(pass, render3d.ClusteredLightGroup) +mesh.Draw(pass) +``` + +- **稳态零分配 CPU 集群分配(`ClusterGrid`)**:视空间集群 AABB 按 `(proj, near, far)` 缓存并在相机移动/旋转时直接复用。`AssignLights` 剔除视锥外光源,计算紧凑的屏幕瓦片与对数深度切片范围,执行球体与 AABB 相交检测(聚光灯 `ClusterLightSpot` 额外执行保守圆锥-AABB 剔除),并稳态零分配地打包 `Offsets` 与 `LightIndices`。 +- **可移植的深度切片查找**:集群片元着色器(`ClusteredBindingsWGSL` / `ClusteredLitWGSL`)在 uniform 分割深度表上通过 6 步二分查找定位视空间深度切片,而非依赖 `log2`/`exp`,在 Metal、Direct3D 11、OpenGL 3.3、WebGPU 与 NSGo 软件 GPU 虚拟机上行为完全一致。 +- **移动端 / WebGL 2 自动回退**:当 `DeviceSupportsClusteredLighting(dev)` 为 false(或设置 `ClusterConfig.ForceFallback`)时,`NewClusteredLightSystem` 自动切换为单个 1,056 字节的 uniform 缓冲(`ClusteredFallbackBindingsWGSL` / `ClusteredFallbackWGSL`),每帧通过 `SelectFallbackLights` 选取优先级最高的 `FallbackMaxLights`(默认 `16`)个光源。两条路径提供完全同名的 `evaluate_clustered_lights(world_pos, normal, frag_pos)` WGSL 辅助函数,自定义材质着色器无需分叉即可同时兼容桌面端与移动端。 +- **衰减模型与纯 Go 参考**:点光源与聚光灯(`NewPointClusterLight`、`NewSpotClusterLight`)遵循 glTF `KHR_lights_punctual` 平滑距离窗口与聚光灯锥角衰减;`EvaluateLightAttenuation`、`EvaluateDirectLights` 与 `EvaluateClusteredLights` 提供与 WGSL 一致的纯 Go 参考计算。 +- **生命周期与设备丢失恢复**:开启 `ClusterConfig.Retained` 可在 GPU 设备丢失恢复后自动重建缓冲;`ByteSize()` 上报显存占用供 `RenderStats` 与预算检查使用,`Close()` 可提前释放资源。 diff --git a/packages/game/render3d/clustered.go b/packages/game/render3d/clustered.go new file mode 100644 index 00000000..79487d6e --- /dev/null +++ b/packages/game/render3d/clustered.go @@ -0,0 +1,1691 @@ +package render3d + +import ( + "encoding/binary" + "errors" + "fmt" + "math" + "sort" + + "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" +) + +// Defaults and buffer layout constants for clustered forward lighting. +const ( + // DefaultClusterTilesX is the default number of horizontal screen-space tiles. + DefaultClusterTilesX = 16 + // DefaultClusterTilesY is the default number of vertical screen-space tiles. + DefaultClusterTilesY = 9 + // DefaultClusterSlicesZ is the default number of logarithmic view-space depth slices. + DefaultClusterSlicesZ = 24 + // DefaultClusterMaxLights is the default storage-buffer light capacity in clustered mode. + DefaultClusterMaxLights = 512 + // DefaultMaxLightsPerCluster is the default maximum number of lights recorded per cluster cell. + DefaultMaxLightsPerCluster = 64 + // DefaultFallbackMaxLights is the default uniform-buffer light cap for mobile / WebGL 2 / GLES 3.0 fallback. + DefaultFallbackMaxLights = 16 + + // MaxClusterSlicesZ is the maximum depth slice count supported by the uniform split-depth table (65 slice boundaries packed into 17 vec4 entries). + MaxClusterSlicesZ = 64 + // MaxFallbackLights is the uniform-buffer array capacity of [ClusteredFallbackWGSL]. + MaxFallbackLights = 16 + + // ClusteredLightGroup is the bind group index declared by [ClusteredBindingsWGSL], [ClusteredFallbackBindingsWGSL], [ClusteredLitWGSL], and [ClusteredFallbackWGSL] (group 1, alongside [CameraGroup] at group 0). + ClusteredLightGroup = 1 + + // ClusterLightGPUSize is the byte size of one GPU light record (4 vec4, 16-byte aligned in both std140 and std430). + ClusterLightGPUSize = 64 + // ClusterParamsUniformSize is the byte size of the clustered-path ClusterParams uniform block: grid_info (16) + viewport_depth (16) + ambient (16) + 17*vec4 slice_depths (272) = 320 bytes. + ClusterParamsUniformSize = 320 + // ClusterCellGPUSize is the byte size of one cluster cell offset/count entry (vec4, 16-byte aligned across all backends). + ClusterCellGPUSize = 16 + // ClusteredFallbackUniformSize is the byte size of the fallback uniform block: info (16) + ambient (16) + 16*ClusterLightGPUSize (1024) = 1056 bytes. + ClusteredFallbackUniformSize = 32 + MaxFallbackLights*ClusterLightGPUSize + + clusterMinStorageBindingBytes = 64 * 1024 +) + +// Sentinel errors returned for invalid clustered lighting configuration or light data. +var ( + // ErrInvalidClusterConfig is wrapped by every error [ClusterConfig.Validate], [NewClusterGrid], and [NewClusteredLightSystem] return for malformed cluster settings. + ErrInvalidClusterConfig = errors.New("render3d: invalid cluster config") + // ErrInvalidClusterLight is wrapped by every error [ClusterLight.Validate] returns for malformed light data. + ErrInvalidClusterLight = errors.New("render3d: invalid cluster light") +) + +// ClusterLightKind selects the emission geometry of a [ClusterLight]. +type ClusterLightKind uint32 + +const ( + // ClusterLightPoint radiates isotropically within Range. + ClusterLightPoint ClusterLightKind = 0 + // ClusterLightSpot radiates within a cone around Direction with smooth inner-to-outer angular attenuation. + ClusterLightSpot ClusterLightKind = 1 +) + +// ClusterLight describes a local punctual light (point or spot) in world space. +// +// Range attenuation follows glTF KHR_lights_punctual: clamp(1 - (d/Range)^4, 0, 1)^2 / max(d^2, 1e-4). +// Spot lights additionally multiply by clamp(dot(dir, lightToPoint)*spotScale + spotOffset, 0, 1)^2. +type ClusterLight struct { + Kind ClusterLightKind + Position math3d.Vec3 + Range float32 + Color math3d.Vec3 + Intensity float32 + // Direction is the world-space emission axis for [ClusterLightSpot]. Normalized automatically; zero defaults to (0, -1, 0). + Direction math3d.Vec3 + // InnerConeCos and OuterConeCos are cos(innerHalfAngle) and cos(outerHalfAngle) for [ClusterLightSpot] with 1 >= InnerConeCos >= OuterConeCos >= -1. + InnerConeCos float32 + OuterConeCos float32 +} + +// NewPointClusterLight returns a [ClusterLightPoint] with finite range and linear RGB color. +func NewPointClusterLight(pos, color math3d.Vec3, intensity, lightRange float32) ClusterLight { + return ClusterLight{ + Kind: ClusterLightPoint, + Position: pos, + Range: lightRange, + Color: color, + Intensity: intensity, + } +} + +// NewSpotClusterLight returns a [ClusterLightSpot] aiming along dir with inner and outer cone half-angles in radians (clamped so 0 <= inner <= outer <= pi). +func NewSpotClusterLight(pos, dir, color math3d.Vec3, intensity, lightRange, innerConeRad, outerConeRad float32) ClusterLight { + if dir.LenSq() < 1e-12 { + dir = math3d.Vec3{Y: -1} + } else { + dir = dir.Norm() + } + if innerConeRad < 0 { + innerConeRad = 0 + } + if outerConeRad < innerConeRad { + outerConeRad = innerConeRad + } + if outerConeRad > math.Pi { + outerConeRad = math.Pi + } + return ClusterLight{ + Kind: ClusterLightSpot, + Position: pos, + Range: lightRange, + Color: color, + Intensity: intensity, + Direction: dir, + InnerConeCos: float32(math.Cos(float64(innerConeRad))), + OuterConeCos: float32(math.Cos(float64(outerConeRad))), + } +} + +// Validate checks that l has finite parameters, a known kind, positive Range, non-negative Color and Intensity, and valid cone cosines for spot lights. Every error wraps [ErrInvalidClusterLight]. +func (l ClusterLight) Validate() error { + if l.Kind != ClusterLightPoint && l.Kind != ClusterLightSpot { + return fmt.Errorf("%w: unknown light kind %d", ErrInvalidClusterLight, l.Kind) + } + if !finite3(l.Position) { + return fmt.Errorf("%w: position is not finite", ErrInvalidClusterLight) + } + if !finite(l.Range) || l.Range <= 0 { + return fmt.Errorf("%w: range %v must be finite and positive", ErrInvalidClusterLight, l.Range) + } + if !finite3(l.Color) || l.Color.X < 0 || l.Color.Y < 0 || l.Color.Z < 0 { + return fmt.Errorf("%w: color %v must be finite and non-negative", ErrInvalidClusterLight, l.Color) + } + if !finite(l.Intensity) || l.Intensity < 0 { + return fmt.Errorf("%w: intensity %v must be finite and non-negative", ErrInvalidClusterLight, l.Intensity) + } + if l.Kind == ClusterLightSpot { + if !finite3(l.Direction) { + return fmt.Errorf("%w: spot direction is not finite", ErrInvalidClusterLight) + } + if !finite(l.InnerConeCos) || !finite(l.OuterConeCos) { + return fmt.Errorf("%w: spot cone cosines must be finite", ErrInvalidClusterLight) + } + if l.InnerConeCos < -1 || l.InnerConeCos > 1 || l.OuterConeCos < -1 || l.OuterConeCos > 1 { + return fmt.Errorf("%w: spot cone cosines (%v, %v) out of [-1, 1]", ErrInvalidClusterLight, l.InnerConeCos, l.OuterConeCos) + } + if l.OuterConeCos > l.InnerConeCos { + return fmt.Errorf("%w: OuterConeCos (%v) exceeds InnerConeCos (%v)", ErrInvalidClusterLight, l.OuterConeCos, l.InnerConeCos) + } + } + return nil +} + +func (l ClusterLight) normalizedDir() math3d.Vec3 { + if l.Direction.LenSq() < 1e-12 { + return math3d.Vec3{Y: -1} + } + return l.Direction.Norm() +} + +func (l ClusterLight) spotScaleOffset() (scale, offset float32) { + if l.Kind != ClusterLightSpot { + return 0, 1 + } + inner := math3d.Clamp(l.InnerConeCos, -1, 1) + outer := math3d.Clamp(l.OuterConeCos, -1, inner) + denom := inner - outer + if denom < 1e-4 { + denom = 1e-4 + } + scale = 1.0 / denom + offset = -outer * scale + return scale, offset +} + +func (l ClusterLight) isActive() bool { + if l.Kind != ClusterLightPoint && l.Kind != ClusterLightSpot { + return false + } + if !finite3(l.Position) || !finite(l.Range) || l.Range <= 0 { + return false + } + if !finite(l.Intensity) || l.Intensity <= 0 || !finite3(l.Color) { + return false + } + if l.Color.X <= 0 && l.Color.Y <= 0 && l.Color.Z <= 0 { + return false + } + return true +} + +// ClusterConfig configures the 3D frustum-cluster grid and its mobile uniform-buffer fallback. Zero fields use defaults from [DefaultClusterConfig]. +type ClusterConfig struct { + // TilesX is the number of screen-space horizontal tiles (default 16). + TilesX int + // TilesY is the number of screen-space vertical tiles (default 9). + TilesY int + // SlicesZ is the number of logarithmic view-space depth slices (default 24, max 64). + SlicesZ int + // MaxLights is the maximum number of visible local lights stored in clustered mode (default 512). + MaxLights int + // MaxLightsPerCluster caps how many lights can be assigned to one cluster cell (default 64). + MaxLightsPerCluster int + // FallbackMaxLights caps how many prioritized lights are uploaded in uniform-buffer fallback mode (default 16, max 16). + FallbackMaxLights int + // ForceFallback forces the uniform-buffer fallback path even on devices that support storage buffers and compute. + ForceFallback bool + // Retained keeps CPU copies of GPU buffers so NSGo recreates them after a device loss. + Retained bool + // Label prefixes GPU resource debug labels. + Label string +} + +// DefaultClusterConfig returns the standard 16x9x24 frustum-cluster grid supporting 512 lights (64 per cluster) and a 16-light mobile/WebGL 2 fallback. +func DefaultClusterConfig() ClusterConfig { + return ClusterConfig{ + TilesX: DefaultClusterTilesX, + TilesY: DefaultClusterTilesY, + SlicesZ: DefaultClusterSlicesZ, + MaxLights: DefaultClusterMaxLights, + MaxLightsPerCluster: DefaultMaxLightsPerCluster, + FallbackMaxLights: DefaultFallbackMaxLights, + } +} + +func (c ClusterConfig) withDefaults() ClusterConfig { + if c.TilesX == 0 { + c.TilesX = DefaultClusterTilesX + } + if c.TilesY == 0 { + c.TilesY = DefaultClusterTilesY + } + if c.SlicesZ == 0 { + c.SlicesZ = DefaultClusterSlicesZ + } + if c.MaxLights == 0 { + c.MaxLights = DefaultClusterMaxLights + } + if c.MaxLightsPerCluster == 0 { + c.MaxLightsPerCluster = DefaultMaxLightsPerCluster + } + if c.FallbackMaxLights == 0 { + c.FallbackMaxLights = DefaultFallbackMaxLights + } + return c +} + +// Validate checks that every field (after applying defaults to zero fields) is within supported limits. Every error wraps [ErrInvalidClusterConfig]. +func (c ClusterConfig) Validate() error { + c = c.withDefaults() + if c.TilesX < 1 || c.TilesY < 1 { + return fmt.Errorf("%w: tile grid %dx%d must be positive", ErrInvalidClusterConfig, c.TilesX, c.TilesY) + } + if c.SlicesZ < 1 || c.SlicesZ > MaxClusterSlicesZ { + return fmt.Errorf("%w: SlicesZ %d must be in [1, %d]", ErrInvalidClusterConfig, c.SlicesZ, MaxClusterSlicesZ) + } + if c.MaxLights < 1 { + return fmt.Errorf("%w: MaxLights %d must be positive", ErrInvalidClusterConfig, c.MaxLights) + } + if c.MaxLightsPerCluster < 1 { + return fmt.Errorf("%w: MaxLightsPerCluster %d must be positive", ErrInvalidClusterConfig, c.MaxLightsPerCluster) + } + if c.FallbackMaxLights < 1 || c.FallbackMaxLights > MaxFallbackLights { + return fmt.Errorf("%w: FallbackMaxLights %d must be in [1, %d]", ErrInvalidClusterConfig, c.FallbackMaxLights, MaxFallbackLights) + } + totalClusters := uint64(c.TilesX) * uint64(c.TilesY) * uint64(c.SlicesZ) + if totalClusters == 0 || totalClusters > 1<<20 { + return fmt.Errorf("%w: cluster count %d out of range", ErrInvalidClusterConfig, totalClusters) + } + return nil +} + +// ClusterCount returns the total number of 3D frustum clusters (TilesX * TilesY * SlicesZ) after applying defaults. +func (c ClusterConfig) ClusterCount() int { + c = c.withDefaults() + return c.TilesX * c.TilesY * c.SlicesZ +} + +// ClusterOffsetCount identifies the contiguous slice of [ClusterGrid.LightIndices] assigned to one cluster cell: indices[Offset : Offset+Count]. +type ClusterOffsetCount struct { + Offset uint32 + Count uint32 +} + +// ClusterStats reports per-frame light culling and cluster packing metrics. +type ClusterStats struct { + InputLights int + VisibleLights int + CulledLights int + ActiveClusters int + TotalAssignments int + MaxClusterLights int + AvgLightsPerActive float32 + TruncatedClusters int + TruncatedLights int +} + +// ClusterGrid builds a 3D view-space frustum cluster grid and assigns local point and spot lights to intersecting cells with zero steady-state allocations. +// +// Cluster AABBs are cached by (proj, near, far) so camera rotation/translation frames reuse the frustum cells without recomputing them. +type ClusterGrid struct { + cfg ClusterConfig + + // Cached frustum AABB parameters. + hasGrid bool + cachedProj math3d.Mat4 + cachedNear float32 + cachedFar float32 + sliceDepths [MaxClusterSlicesZ + 1]float32 + aabbs []math3d.AABB + + // Preallocated per-frame assignment scratch and packed outputs. + activeLights []ClusterLight + clusterCounts []uint32 + clusterTrunc []bool + scratchIndices []uint32 + offsets []ClusterOffsetCount + lightIndices []uint32 + lastStats ClusterStats +} + +// NewClusterGrid validates cfg and allocates reusable storage for frustum clusters and light assignment. +func NewClusterGrid(cfg ClusterConfig) (*ClusterGrid, error) { + if err := cfg.Validate(); err != nil { + return nil, err + } + cfg = cfg.withDefaults() + numClusters := cfg.ClusterCount() + return &ClusterGrid{ + cfg: cfg, + aabbs: make([]math3d.AABB, numClusters), + activeLights: make([]ClusterLight, 0, cfg.MaxLights), + clusterCounts: make([]uint32, numClusters), + clusterTrunc: make([]bool, numClusters), + scratchIndices: make([]uint32, numClusters*cfg.MaxLightsPerCluster), + offsets: make([]ClusterOffsetCount, numClusters), + lightIndices: make([]uint32, 0, numClusters*min(cfg.MaxLightsPerCluster, 16)), + }, nil +} + +// Config returns the normalized [ClusterConfig] of g. +func (g *ClusterGrid) Config() ClusterConfig { return g.cfg } + +// ClusterCount returns the total number of frustum cells (TilesX * TilesY * SlicesZ). +func (g *ClusterGrid) ClusterCount() int { return len(g.aabbs) } + +// SliceDepths returns the positive view-space depth boundaries [near .. far] of length SlicesZ+1 computed on the most recent [ClusterGrid.AssignLights] or [ClusterGrid.BuildFrustum]. +func (g *ClusterGrid) SliceDepths() []float32 { return g.sliceDepths[:g.cfg.SlicesZ+1] } + +// ClusterAABB returns the cached view-space AABB of cluster (tileX, tileY, sliceZ). +func (g *ClusterGrid) ClusterAABB(tileX, tileY, sliceZ int) math3d.AABB { + idx := g.ClusterIndex(tileX, tileY, sliceZ) + if idx < 0 || idx >= len(g.aabbs) { + return math3d.AABBEmpty() + } + return g.aabbs[idx] +} + +// ClusterIndex returns the flat linear index for cluster coordinates (tileX, tileY, sliceZ). +func (g *ClusterGrid) ClusterIndex(tileX, tileY, sliceZ int) int { + return (sliceZ*g.cfg.TilesY+tileY)*g.cfg.TilesX + tileX +} + +// ActiveLights returns the frustum-visible lights packed by the most recent [ClusterGrid.AssignLights] call (indices in [ClusterGrid.LightIndices] reference this slice). +func (g *ClusterGrid) ActiveLights() []ClusterLight { return g.activeLights } + +// Offsets returns the per-cluster offset/count table packed by the most recent [ClusterGrid.AssignLights] call. +func (g *ClusterGrid) Offsets() []ClusterOffsetCount { return g.offsets } + +// LightIndices returns the flat packed light-index list referenced by [ClusterGrid.Offsets]. +func (g *ClusterGrid) LightIndices() []uint32 { return g.lightIndices } + +// ClusterLightIndices returns the light indices assigned to cluster (tileX, tileY, sliceZ) on the last [ClusterGrid.AssignLights] call. +func (g *ClusterGrid) ClusterLightIndices(tileX, tileY, sliceZ int) []uint32 { + idx := g.ClusterIndex(tileX, tileY, sliceZ) + if idx < 0 || idx >= len(g.offsets) { + return nil + } + oc := g.offsets[idx] + end := uint64(oc.Offset) + uint64(oc.Count) + if end > uint64(len(g.lightIndices)) { + return nil + } + return g.lightIndices[oc.Offset:end] +} + +// LastStats returns the [ClusterStats] from the most recent [ClusterGrid.AssignLights] call. +func (g *ClusterGrid) LastStats() ClusterStats { return g.lastStats } + +// SliceForDepth maps a positive view-space depth viewZ to its depth slice index in [0, SlicesZ-1] using the exact same binary search over [ClusterGrid.SliceDepths] as the GPU fragment shader. +func (g *ClusterGrid) SliceForDepth(viewZ float32) int { + n := g.cfg.SlicesZ + if n <= 1 { + return 0 + } + lo, hi := 0, n-1 + for lo < hi { + mid := (lo + hi) >> 1 + if viewZ >= g.sliceDepths[mid+1] { + lo = mid + 1 + } else { + hi = mid + } + } + return lo +} + +// BuildFrustum computes view-space depth slice boundaries and per-cluster view-space AABBs for (proj, near, far), caching the result until any of those inputs change. +func (g *ClusterGrid) BuildFrustum(proj math3d.Mat4, near, far float32) bool { + if !finite(near) || !finite(far) || far <= near { + return false + } + if g.hasGrid && g.cachedProj == proj && g.cachedNear == near && g.cachedFar == far { + return true + } + invProj, ok := proj.Inverse() + if !ok { + return false + } + + slices := g.cfg.SlicesZ + useLog := near > 0 && proj[11] != 0 + if useLog { + ratio := float64(far) / float64(near) + invSlices := 1.0 / float64(slices) + g.sliceDepths[0] = near + for s := 1; s < slices; s++ { + g.sliceDepths[s] = float32(float64(near) * math.Pow(ratio, float64(s)*invSlices)) + } + g.sliceDepths[slices] = far + } else { + span := float64(far - near) + invSlices := 1.0 / float64(slices) + for s := 0; s <= slices; s++ { + g.sliceDepths[s] = float32(float64(near) + span*float64(s)*invSlices) + } + } + + txN := g.cfg.TilesX + tyN := g.cfg.TilesY + invTX := 2.0 / float32(txN) + invTY := 2.0 / float32(tyN) + + // Unproject a screen-NDC corner (nx, ny) onto view plane z = -depth using invProj. + unprojectAtDepth := func(nx, ny, depth float32) math3d.Vec3 { + z := -depth + clipZ := proj[10]*z + proj[14] + clipW := proj[11]*z + proj[15] + if clipW == 0 { + return math3d.Vec3{Z: z} + } + ndcZ := clipZ / clipW + p := invProj.TransformPoint(math3d.Vec3{X: nx, Y: ny, Z: ndcZ}) + p.Z = z + return p + } + + for s := range slices { + z0 := g.sliceDepths[s] + z1 := g.sliceDepths[s+1] + sliceBase := s * tyN * txN + for ty := range tyN { + ndcYTop := 1.0 - float32(ty)*invTY + ndcYBot := 1.0 - float32(ty+1)*invTY + rowBase := sliceBase + ty*txN + for tx := range txN { + ndcXL := -1.0 + float32(tx)*invTX + ndcXR := -1.0 + float32(tx+1)*invTX + + c0 := unprojectAtDepth(ndcXL, ndcYBot, z0) + c1 := unprojectAtDepth(ndcXR, ndcYBot, z0) + c2 := unprojectAtDepth(ndcXL, ndcYTop, z0) + c3 := unprojectAtDepth(ndcXR, ndcYTop, z0) + c4 := unprojectAtDepth(ndcXL, ndcYBot, z1) + c5 := unprojectAtDepth(ndcXR, ndcYBot, z1) + c6 := unprojectAtDepth(ndcXL, ndcYTop, z1) + c7 := unprojectAtDepth(ndcXR, ndcYTop, z1) + + minV := c0.Min(c1).Min(c2).Min(c3).Min(c4).Min(c5).Min(c6).Min(c7) + maxV := c0.Max(c1).Max(c2).Max(c3).Max(c4).Max(c5).Max(c6).Max(c7) + g.aabbs[rowBase+tx] = math3d.AABB{Min: minV, Max: maxV} + } + } + } + + g.hasGrid = true + g.cachedProj = proj + g.cachedNear = near + g.cachedFar = far + return true +} + +// AssignLights transforms lights into view space, culls lights outside the camera frustum, tests each visible light against its candidate frustum clusters (sphere-vs-AABB for all lights plus exact cone-vs-AABB rejection for spot lights), and packs compact offset/count and index arrays. +// +// Steady-state calls perform zero heap allocations. +func (g *ClusterGrid) AssignLights(view, proj math3d.Mat4, near, far float32, lights []ClusterLight) ClusterStats { + stats := ClusterStats{InputLights: len(lights)} + g.activeLights = g.activeLights[:0] + clear(g.clusterCounts) + clear(g.clusterTrunc) + g.lightIndices = g.lightIndices[:0] + + numClusters := len(g.aabbs) + if !g.BuildFrustum(proj, near, far) || len(lights) == 0 { + clear(g.offsets) + stats.CulledLights = len(lights) + g.lastStats = stats + return stats + } + + tilesX := g.cfg.TilesX + tilesY := g.cfg.TilesY + slicesZ := g.cfg.SlicesZ + maxPerCluster := g.cfg.MaxLightsPerCluster + isPersp := proj[11] != 0 + + for i := range lights { + l := lights[i] + if !l.isActive() { + stats.CulledLights++ + continue + } + + posV := view.TransformPoint(l.Position) + sphereCenter := posV + sphereRadius := l.Range + + var dirV math3d.Vec3 + var cosOuter, sinOuter float32 + isSpot := l.Kind == ClusterLightSpot + if isSpot { + dirW := l.normalizedDir() + dirV = view.TransformDir(dirW) + if dirV.LenSq() < 1e-12 { + dirV = math3d.Vec3{Y: -1} + } else { + dirV = dirV.Norm() + } + cosOuter = math3d.Clamp(l.OuterConeCos, -1, 1) + sinSq := 1.0 - cosOuter*cosOuter + if sinSq < 0 { + sinSq = 0 + } + sinOuter = float32(math.Sqrt(float64(sinSq))) + sphereCenter, sphereRadius = spotBoundingSphere(posV, dirV, l.Range, cosOuter, sinOuter) + } + + // Quick view-space depth rejection (camera looks down -Z, positive depth = -z). + minDepth := -sphereCenter.Z - sphereRadius + maxDepth := -sphereCenter.Z + sphereRadius + if maxDepth < near || minDepth > far { + stats.CulledLights++ + continue + } + + // Tight screen-tile rectangle in [0, tilesX-1] x [0, tilesY-1]. + txMin, txMax, tyMin, tyMax, visible := projectSphereTiles(proj, isPersp, near, far, sphereCenter, sphereRadius, tilesX, tilesY) + if !visible { + stats.CulledLights++ + continue + } + + if len(g.activeLights) >= g.cfg.MaxLights { + stats.TruncatedLights++ + continue + } + + lightIdx := uint32(len(g.activeLights)) + g.activeLights = append(g.activeLights, l) + + // Tight Z-slice range via binary search on cached depth splits. + sliceMin := 0 + if minDepth > near { + sliceMin = g.SliceForDepth(minDepth) + } + sliceMax := slicesZ - 1 + if maxDepth < far { + sliceMax = g.SliceForDepth(maxDepth) + } + if sliceMax < sliceMin { + sliceMax = sliceMin + } + + rSq := sphereRadius * sphereRadius + anyCell := false + for s := sliceMin; s <= sliceMax; s++ { + sliceBase := s * tilesY * tilesX + for ty := tyMin; ty <= tyMax; ty++ { + rowBase := sliceBase + ty*tilesX + for tx := txMin; tx <= txMax; tx++ { + cIdx := rowBase + tx + box := g.aabbs[cIdx] + if !sphereIntersectsAABBSq(sphereCenter, rSq, box) { + continue + } + if isSpot && cosOuter > 0 { + if !spotConeIntersectsAABB(posV, dirV, l.Range, cosOuter, sinOuter, box) { + continue + } + } + anyCell = true + cnt := int(g.clusterCounts[cIdx]) + if cnt < maxPerCluster { + g.scratchIndices[cIdx*maxPerCluster+cnt] = lightIdx + g.clusterCounts[cIdx] = uint32(cnt + 1) + } else { + g.clusterTrunc[cIdx] = true + } + } + } + } + + if !anyCell { + // Light passed coarse screen-rect test but touched no cluster AABB. + g.activeLights = g.activeLights[:len(g.activeLights)-1] + stats.CulledLights++ + continue + } + } + + stats.VisibleLights = len(g.activeLights) + + // Compact scratch lists into contiguous lightIndices + offsets table. + var total int + for cIdx := range numClusters { + cnt := int(g.clusterCounts[cIdx]) + if g.clusterTrunc[cIdx] { + stats.TruncatedClusters++ + } + if cnt == 0 { + g.offsets[cIdx] = ClusterOffsetCount{} + continue + } + stats.ActiveClusters++ + if cnt > stats.MaxClusterLights { + stats.MaxClusterLights = cnt + } + g.offsets[cIdx] = ClusterOffsetCount{ + Offset: uint32(total), + Count: uint32(cnt), + } + total += cnt + } + + if cap(g.lightIndices) < total { + g.lightIndices = make([]uint32, total) + } else { + g.lightIndices = g.lightIndices[:total] + } + for cIdx := range numClusters { + cnt := int(g.clusterCounts[cIdx]) + if cnt == 0 { + continue + } + off := int(g.offsets[cIdx].Offset) + srcOff := cIdx * maxPerCluster + copy(g.lightIndices[off:off+cnt], g.scratchIndices[srcOff:srcOff+cnt]) + } + + stats.TotalAssignments = total + if stats.ActiveClusters > 0 { + stats.AvgLightsPerActive = float32(total) / float32(stats.ActiveClusters) + } + g.lastStats = stats + return stats +} + +// spotBoundingSphere computes the minimal bounding sphere enclosing a spotlight cone (Bart Wronski / Frostbite formulation). +func spotBoundingSphere(apex, dir math3d.Vec3, lightRange, cosOuter, sinOuter float32) (math3d.Vec3, float32) { + if cosOuter <= 0 { + return apex, lightRange + } + const cos45 = 0.70710678 + if cosOuter < cos45 { + return apex.Add(dir.Scale(lightRange * cosOuter)), lightRange * sinOuter + } + r := lightRange / (2.0 * cosOuter) + return apex.Add(dir.Scale(r)), r +} + +func sphereIntersectsAABBSq(center math3d.Vec3, radiusSq float32, b math3d.AABB) bool { + cx := math3d.Clamp(center.X, b.Min.X, b.Max.X) + cy := math3d.Clamp(center.Y, b.Min.Y, b.Max.Y) + cz := math3d.Clamp(center.Z, b.Min.Z, b.Max.Z) + dx := center.X - cx + dy := center.Y - cy + dz := center.Z - cz + return dx*dx+dy*dy+dz*dz <= radiusSq +} + +// spotConeIntersectsAABB conservatively tests whether a spotlight cone (cosOuter > 0) intersects box b by testing the cone against b's bounding sphere. Guaranteed zero false negatives. +func spotConeIntersectsAABB(apex, dir math3d.Vec3, lightRange, cosOuter, sinOuter float32, b math3d.AABB) bool { + center := b.Center() + radius := b.HalfExtents().Len() + + v := center.Sub(apex) + vLenSq := v.LenSq() + v1Len := v.Dot(dir) + + if v1Len < -radius || v1Len > lightRange+radius { + return false + } + + perpSq := vLenSq - v1Len*v1Len + if perpSq < 0 { + perpSq = 0 + } + dPerp := float32(math.Sqrt(float64(perpSq))) + + // Projection along the closest cone generator ray: if <= 0, the apex is the closest point on the cone. + if v1Len*cosOuter+dPerp*sinOuter <= 0 { + return vLenSq <= radius*radius + } + closestDist := dPerp*cosOuter - v1Len*sinOuter + return closestDist <= radius +} + +// projectSphereTiles computes a conservative [txMin..txMax] x [tyMin..tyMax] screen-tile rectangle for a view-space bounding sphere. +func projectSphereTiles(proj math3d.Mat4, isPersp bool, near, far float32, center math3d.Vec3, radius float32, tilesX, tilesY int) (txMin, txMax, tyMin, tyMax int, visible bool) { + zMax := center.Z + radius + zMin := center.Z - radius + if isPersp && zMax >= -near*1.001 { + // Sphere crosses or touches the near plane: conservatively span the full screen so near-plane clipping never produces a false negative. + return 0, tilesX - 1, 0, tilesY - 1, true + } + if zMin < -far { + zMin = -far + } + if zMax > -near { + zMax = -near + } + + xs := [2]float32{center.X - radius, center.X + radius} + ys := [2]float32{center.Y - radius, center.Y + radius} + zs := [2]float32{zMin, zMax} + + minX, maxX := float32(math.Inf(1)), float32(math.Inf(-1)) + minY, maxY := float32(math.Inf(1)), float32(math.Inf(-1)) + + for _, x := range xs { + for _, y := range ys { + for _, z := range zs { + clip := proj.MulVec4(math3d.Vec4{X: x, Y: y, Z: z, W: 1}) + if clip.W <= 1e-6 { + return 0, tilesX - 1, 0, tilesY - 1, true + } + invW := 1.0 / clip.W + nx := clip.X * invW + ny := clip.Y * invW + if nx < minX { + minX = nx + } + if nx > maxX { + maxX = nx + } + if ny < minY { + minY = ny + } + if ny > maxY { + maxY = ny + } + } + } + } + + if maxX < -1 || minX > 1 || maxY < -1 || minY > 1 { + return 0, 0, 0, 0, false + } + + txMin = clusterClampInt(int(math.Floor(float64((minX+1)*0.5*float32(tilesX)))), 0, tilesX-1) + txMax = clusterClampInt(int(math.Floor(float64((maxX+1)*0.5*float32(tilesX)))), 0, tilesX-1) + tyMin = clusterClampInt(int(math.Floor(float64((1-maxY)*0.5*float32(tilesY)))), 0, tilesY-1) + tyMax = clusterClampInt(int(math.Floor(float64((1-minY)*0.5*float32(tilesY)))), 0, tilesY-1) + return txMin, txMax, tyMin, tyMax, true +} + +func clusterClampInt(v, lo, hi int) int { + if v < lo { + return lo + } + if v > hi { + return hi + } + return v +} + +type scoredClusterLight struct { + index int + score float32 +} + +// SelectFallbackLights chooses up to maxLights highest-priority local lights for mobile / WebGL 2 / GLES 3.0 uniform-buffer fallback shading. +// +// Active lights are ranked deterministically by radiant luminance, proximity to cameraPos (and distance relative to Range), and whether their sphere extends in front of cameraForward, breaking ties by input order. Results are appended to dst[:0]. +func SelectFallbackLights(dst []ClusterLight, cameraPos, cameraForward math3d.Vec3, lights []ClusterLight, maxLights int) []ClusterLight { + dst = dst[:0] + if maxLights <= 0 || len(lights) == 0 { + return dst + } + scored := make([]scoredClusterLight, 0, len(lights)) + return selectFallbackLightsWithScratch(dst, &scored, cameraPos, cameraForward, lights, maxLights) +} + +func selectFallbackLightsWithScratch(dst []ClusterLight, scratch *[]scoredClusterLight, cameraPos, cameraForward math3d.Vec3, lights []ClusterLight, maxLights int) []ClusterLight { + dst = dst[:0] + if maxLights <= 0 || len(lights) == 0 { + return dst + } + fwd := cameraForward + if fwd.LenSq() < 1e-12 { + fwd = math3d.Vec3Forward() + } else { + fwd = fwd.Norm() + } + + scored := (*scratch)[:0] + for i := range lights { + l := lights[i] + if !l.isActive() { + continue + } + lum := 0.2126*l.Color.X + 0.7152*l.Color.Y + 0.0722*l.Color.Z + if lum <= 0 { + lum = max(l.Color.X, max(l.Color.Y, l.Color.Z)) + } + toLight := l.Position.Sub(cameraPos) + distSq := toLight.LenSq() + dist := float32(math.Sqrt(float64(distSq))) + + // Smooth importance combining power, range coverage, and camera distance. + denom := distSq + 0.25 + score := l.Intensity * lum * (l.Range * l.Range) / (denom * (1.0 + dist/max(l.Range, 1e-3))) + + // Prefer lights whose sphere extends in front of the camera plane. + if toLight.Dot(fwd)+l.Range >= 0 { + score *= 4.0 + } else { + score *= 0.25 + } + scored = append(scored, scoredClusterLight{index: i, score: score}) + } + *scratch = scored + + if len(scored) == 0 { + return dst + } + sort.Slice(scored, func(i, j int) bool { + if scored[i].score != scored[j].score { + return scored[i].score > scored[j].score + } + return scored[i].index < scored[j].index + }) + keep := min(len(scored), maxLights) + if cap(dst) < keep { + dst = make([]ClusterLight, 0, keep) + } + for i := range keep { + dst = append(dst, lights[scored[i].index]) + } + return dst +} + +// EvaluateLightAttenuation computes the unit direction from worldPos to light and its combined glTF KHR_lights_punctual range, intensity, and spotlight angular attenuation. +func EvaluateLightAttenuation(light ClusterLight, worldPos math3d.Vec3) (dirToLight math3d.Vec3, attenuation float32) { + if !light.isActive() { + return math3d.Vec3{}, 0 + } + toLight := light.Position.Sub(worldPos) + distSq := toLight.LenSq() + dist := float32(math.Sqrt(float64(distSq))) + if dist >= light.Range { + return math3d.Vec3{}, 0 + } + if dist > 1e-6 { + dirToLight = toLight.Scale(1.0 / dist) + } else { + dirToLight = math3d.Vec3Up() + } + + ratio := dist / light.Range + r2 := ratio * ratio + r4 := r2 * r2 + win := math3d.Clamp(1.0-r4, 0, 1) + atten := (win * win) / max(distSq, 1e-4) + + if light.Kind == ClusterLightSpot { + lightDir := light.normalizedDir() + scale, offset := light.spotScaleOffset() + cd := lightDir.Dot(dirToLight.Neg()) + spot := math3d.Clamp(cd*scale+offset, 0, 1) + atten *= spot * spot + } + return dirToLight, atten * light.Intensity +} + +// EvaluateDirectLights computes the pure-Go analytic Lambertian diffuse radiance for worldPos and normal over all lights, matching [ClusteredFallbackWGSL] and serving as ground truth for clustered lighting parity tests. +func EvaluateDirectLights(worldPos, normal, albedo, ambient math3d.Vec3, lights []ClusterLight) math3d.Vec3 { + n := normal + if n.LenSq() > 1e-12 { + n = n.Norm() + } + irr := ambient + for i := range lights { + l := lights[i] + lDir, atten := EvaluateLightAttenuation(l, worldPos) + if atten <= 0 { + continue + } + ndl := max(n.Dot(lDir), 0) + if ndl <= 0 { + continue + } + irr = irr.Add(l.Color.Scale(atten * ndl)) + } + return math3d.Vec3{X: irr.X * albedo.X, Y: irr.Y * albedo.Y, Z: irr.Z * albedo.Z} +} + +// EvaluateClusteredLights computes the pure-Go analytic Lambertian diffuse radiance at worldPos using only the lights assigned to worldPos's frustum cluster in grid, matching [ClusteredLitWGSL] byte-for-byte in formula. +func EvaluateClusteredLights(worldPos, normal, albedo, ambient math3d.Vec3, grid *ClusterGrid, view, proj math3d.Mat4, viewportW, viewportH float32) math3d.Vec3 { + if grid == nil { + return math3d.Vec3{X: ambient.X * albedo.X, Y: ambient.Y * albedo.Y, Z: ambient.Z * albedo.Z} + } + viewPos := view.TransformPoint(worldPos) + viewZ := -viewPos.Z + + clip := proj.MulVec4(viewPos.Vec4(1)) + if clip.W <= 1e-6 { + return math3d.Vec3{X: ambient.X * albedo.X, Y: ambient.Y * albedo.Y, Z: ambient.Z * albedo.Z} + } + ndcX := clip.X / clip.W + ndcY := clip.Y / clip.W + fragX := (ndcX + 1.0) * 0.5 * viewportW + fragY := (1.0 - ndcY) * 0.5 * viewportH + + tx := clusterClampInt(int(max(fragX, 0)/max(viewportW, 1)*float32(grid.cfg.TilesX)), 0, grid.cfg.TilesX-1) + ty := clusterClampInt(int(max(fragY, 0)/max(viewportH, 1)*float32(grid.cfg.TilesY)), 0, grid.cfg.TilesY-1) + sz := grid.SliceForDepth(viewZ) + + n := normal + if n.LenSq() > 1e-12 { + n = n.Norm() + } + irr := ambient + for _, lightIdx := range grid.ClusterLightIndices(tx, ty, sz) { + l := grid.activeLights[lightIdx] + lDir, atten := EvaluateLightAttenuation(l, worldPos) + if atten <= 0 { + continue + } + ndl := max(n.Dot(lDir), 0) + if ndl <= 0 { + continue + } + irr = irr.Add(l.Color.Scale(atten * ndl)) + } + return math3d.Vec3{X: irr.X * albedo.X, Y: irr.Y * albedo.Y, Z: irr.Z * albedo.Z} +} + +// DeviceSupportsClusteredLighting reports whether dev exposes the storage-buffer and compute capabilities needed for the clustered forward shading path. Devices without them (such as WebGL 2, OpenGL ES 3.0, or headless tests under nsgotest.NoGPUCompute) fall back to the uniform-buffer path automatically. +func DeviceSupportsClusteredLighting(dev *gpu.Device) bool { + if dev == nil { + return false + } + caps := dev.Capabilities() + return caps.Features.StorageBuffers && + caps.Features.Compute && + caps.Limits.MaxStorageBufferBindingSize >= clusterMinStorageBindingBytes +} + +// ClusteredBindingsWGSL declares the @group(1) uniform and read-only storage bindings plus evaluate_clustered_lights(world_pos, normal, frag_pos) for the desktop clustered forward shading path. +// +// Depth slicing uses a 6-step binary search over the uniform slice_depths split table (avoiding log2/exp so it runs identically on Metal, D3D11, OpenGL, WebGPU, and NSGo's software GPU VM). +const ClusteredBindingsWGSL = ` +struct ClusterLightGPU { + pos_range: vec4, + color_intensity: vec4, + dir_kind: vec4, + spot_params: vec4, +} + +struct ClusterParams { + grid_info: vec4, + viewport_depth: vec4, + ambient: vec4, + slice_depths: array, 17>, +} + +@group(1) @binding(0) var cluster_params: ClusterParams; +@group(1) @binding(1) var cluster_lights: array; +@group(1) @binding(2) var cluster_cells: array>; +@group(1) @binding(3) var cluster_indices: array; + +fn cluster_slice_depth(idx: u32) -> f32 { + let v = cluster_params.slice_depths[idx / 4u]; + let lane = idx % 4u; + if (lane == 0u) { return v.x; } + if (lane == 1u) { return v.y; } + if (lane == 2u) { return v.z; } + return v.w; +} + +fn cluster_find_slice(view_z: f32) -> u32 { + let slices = cluster_params.grid_info.z; + if (slices <= 1u) { + return 0u; + } + var lo: u32 = 0u; + var hi: u32 = slices - 1u; + for (var step: u32 = 0u; step < 6u; step = step + 1u) { + if (lo < hi) { + let mid = (lo + hi) / 2u; + if (view_z >= cluster_slice_depth(mid + 1u)) { + lo = mid + 1u; + } else { + hi = mid; + } + } + } + return min(lo, slices - 1u); +} + +fn cluster_eval_one_light(light: ClusterLightGPU, world_pos: vec3, normal: vec3) -> vec3 { + let light_range = light.pos_range.w; + let intensity = light.color_intensity.w; + if (light_range <= 0.0 || intensity <= 0.0) { + return vec3(0.0, 0.0, 0.0); + } + let to_light = light.pos_range.xyz - world_pos; + let dist_sq = dot(to_light, to_light); + let dist = sqrt(dist_sq); + if (dist >= light_range) { + return vec3(0.0, 0.0, 0.0); + } + var l_dir = vec3(0.0, 1.0, 0.0); + if (dist > 0.000001) { + l_dir = to_light / dist; + } + let ndl = max(dot(normal, l_dir), 0.0); + if (ndl <= 0.0) { + return vec3(0.0, 0.0, 0.0); + } + let ratio = dist / light_range; + let r2 = ratio * ratio; + let r4 = r2 * r2; + let win = clamp(1.0 - r4, 0.0, 1.0); + var atten = (win * win) / max(dist_sq, 0.0001); + if (light.dir_kind.w > 0.5) { + let cd = dot(light.dir_kind.xyz, -l_dir); + let spot = clamp(cd * light.spot_params.x + light.spot_params.y, 0.0, 1.0); + atten = atten * spot * spot; + } + return light.color_intensity.rgb * (intensity * atten * ndl); +} + +fn evaluate_clustered_lights(world_pos: vec3, normal: vec3, frag_pos: vec4) -> vec3 { + let n = normalize(normal); + var irradiance = cluster_params.ambient.rgb; + let tiles_x = cluster_params.grid_info.x; + let tiles_y = cluster_params.grid_info.y; + if (tiles_x == 0u || tiles_y == 0u) { + return irradiance; + } + let vp_w = max(cluster_params.viewport_depth.x, 1.0); + let vp_h = max(cluster_params.viewport_depth.y, 1.0); + let tx = min(u32(max(frag_pos.x, 0.0) / vp_w * f32(tiles_x)), tiles_x - 1u); + let ty = min(u32(max(frag_pos.y, 0.0) / vp_h * f32(tiles_y)), tiles_y - 1u); + let view_pos = camera.view * vec4(world_pos, 1.0); + let slice_z = cluster_find_slice(-view_pos.z); + let cluster_idx = (slice_z * tiles_y + ty) * tiles_x + tx; + let cell = cluster_cells[cluster_idx]; + let offset = cell.x; + let count = cell.y; + for (var i: u32 = 0u; i < count; i = i + 1u) { + let light_idx = cluster_indices[offset + i]; + irradiance = irradiance + cluster_eval_one_light(cluster_lights[light_idx], world_pos, n); + } + return irradiance; +} +` + +// ClusteredFallbackBindingsWGSL declares the @group(1) pure uniform-buffer binding plus evaluate_clustered_lights(world_pos, normal, frag_pos) with the identical signature as [ClusteredBindingsWGSL], using zero storage buffers and zero compute shaders for WebGL 2 / OpenGL ES 3.0 targets. +const ClusteredFallbackBindingsWGSL = ` +struct ClusterLightGPU { + pos_range: vec4, + color_intensity: vec4, + dir_kind: vec4, + spot_params: vec4, +} + +struct FallbackLightUniform { + info: vec4, + ambient: vec4, + lights: array, +} + +@group(1) @binding(0) var fallback_lights: FallbackLightUniform; + +fn cluster_eval_one_light(light: ClusterLightGPU, world_pos: vec3, normal: vec3) -> vec3 { + let light_range = light.pos_range.w; + let intensity = light.color_intensity.w; + if (light_range <= 0.0 || intensity <= 0.0) { + return vec3(0.0, 0.0, 0.0); + } + let to_light = light.pos_range.xyz - world_pos; + let dist_sq = dot(to_light, to_light); + let dist = sqrt(dist_sq); + if (dist >= light_range) { + return vec3(0.0, 0.0, 0.0); + } + var l_dir = vec3(0.0, 1.0, 0.0); + if (dist > 0.000001) { + l_dir = to_light / dist; + } + let ndl = max(dot(normal, l_dir), 0.0); + if (ndl <= 0.0) { + return vec3(0.0, 0.0, 0.0); + } + let ratio = dist / light_range; + let r2 = ratio * ratio; + let r4 = r2 * r2; + let win = clamp(1.0 - r4, 0.0, 1.0); + var atten = (win * win) / max(dist_sq, 0.0001); + if (light.dir_kind.w > 0.5) { + let cd = dot(light.dir_kind.xyz, -l_dir); + let spot = clamp(cd * light.spot_params.x + light.spot_params.y, 0.0, 1.0); + atten = atten * spot * spot; + } + return light.color_intensity.rgb * (intensity * atten * ndl); +} + +fn evaluate_clustered_lights(world_pos: vec3, normal: vec3, frag_pos: vec4) -> vec3 { + let n = normalize(normal); + var irradiance = fallback_lights.ambient.rgb; + let count = min(fallback_lights.info.x, 16u); + for (var i: u32 = 0u; i < count; i = i + 1u) { + irradiance = irradiance + cluster_eval_one_light(fallback_lights.lights[i], world_pos, n); + } + return irradiance; +} +` + +const clusteredDefaultStageWGSL = ` +struct ClusterVertexIn { + @location(0) pos: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, +} + +struct ClusterVertexOut { + @builtin(position) clip: vec4, + @location(0) world_pos: vec3, + @location(1) normal: vec3, +} + +@vertex +fn vs_main(in: ClusterVertexIn) -> ClusterVertexOut { + var out: ClusterVertexOut; + out.clip = camera.view_proj * vec4(in.pos, 1.0); + out.world_pos = in.pos; + out.normal = in.normal; + return out; +} + +@fragment +fn fs_main(in: ClusterVertexOut) -> @location(0) vec4 { + let lit = evaluate_clustered_lights(in.world_pos, in.normal, in.clip); + return vec4(clamp(lit, vec3(0.0), vec3(1.0)), 1.0); +} +` + +// ClusteredLitWGSL is a ready-to-compile WGSL module for [MeshVertexLayout] meshes combining [CameraWGSL] (@group(0)) and [ClusteredBindingsWGSL] (@group(1)). +const ClusteredLitWGSL = CameraWGSL + ClusteredBindingsWGSL + clusteredDefaultStageWGSL + +// ClusteredFallbackWGSL is a ready-to-compile WGSL module for [MeshVertexLayout] meshes combining [CameraWGSL] (@group(0)) and [ClusteredFallbackBindingsWGSL] (@group(1)) without storage buffers or compute shaders. +const ClusteredFallbackWGSL = CameraWGSL + ClusteredFallbackBindingsWGSL + clusteredDefaultStageWGSL + +// ClusteredLightSystem manages the GPU buffers, bind group layout, and bind group for clustered forward shading with automatic fallback to a pure uniform-buffer path on devices without storage buffers or compute (WebGL 2, OpenGL ES 3.0, nsgotest.NoGPUCompute). +// +// Create it once on device readiness, call [ClusteredLightSystem.Update] or [ClusteredLightSystem.UpdateCamera] each frame, bind [ClusteredLightSystem.BindGroup] at [ClusteredLightGroup] (group 1), and shade with [ClusteredLightSystem.WGSL] or your own shader prepending [CameraWGSL] + [ClusteredLightSystem.BindingsWGSL]. +type ClusteredLightSystem struct { + cfg ClusterConfig + fallback bool + grid *ClusterGrid + + // GPU resources (owned by the core.Scope passed to NewClusteredLightSystem). + layout *gpu.BindGroupLayout + group *gpu.BindGroup + paramsBuf *gpu.Buffer // clustered: ClusterParams uniform; fallback: FallbackLightUniform + lightsBuf *gpu.Buffer // clustered only: storage array + cellsBuf *gpu.Buffer // clustered only: storage array> + indicesBuf *gpu.Buffer // clustered only: storage array + indicesCap int // capacity of indicesBuf in uint32 entries + fallbackDst []ClusterLight + fallbackTmp []scoredClusterLight + lastStats ClusterStats + + // Reusable CPU upload scratch buffers (zero steady-state allocations). + paramsBytes [ClusterParamsUniformSize]byte + fallbackData [ClusteredFallbackUniformSize]byte + lightsBytes []byte + cellsBytes []byte + indicesBytes []byte +} + +// NewClusteredLightSystem validates cfg, inspects dev's GPU capabilities, and allocates either the storage-buffer clustered lighting path or the uniform-buffer mobile/WebGL 2 fallback path scoped to cx. +func NewClusteredLightSystem(cx *core.Scope, dev *gpu.Device, cfg ClusterConfig) (*ClusteredLightSystem, error) { + if err := cfg.Validate(); err != nil { + return nil, err + } + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + cfg = cfg.withDefaults() + + useFallback := cfg.ForceFallback || !DeviceSupportsClusteredLighting(dev) + + label := cfg.Label + if label == "" { + label = "render3d.clustered" + } + + if useFallback { + return newClusteredFallbackSystem(cx, dev, cfg, label) + } + return newClusteredStorageSystem(cx, dev, cfg, label) +} + +func newClusteredFallbackSystem(cx *core.Scope, dev *gpu.Device, cfg ClusterConfig, label string) (*ClusteredLightSystem, error) { + buf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + " fallback lights", + Size: ClusteredFallbackUniformSize, + Usage: gpu.UsageUniform | gpu.UsageCopyDst, + Retained: cfg.Retained, + }) + if err != nil { + return nil, err + } + layout, err := dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{ + Label: label + " fallback layout", + Entries: []gpu.BindGroupLayoutEntry{{ + Binding: 0, + Visibility: gpu.StageFragment, + Type: gpu.BindingUniform, + }}, + }) + if err != nil { + _ = buf.Close() + return nil, err + } + group, err := dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{ + Label: label + " fallback group", + Layout: layout, + Entries: []gpu.BindGroupEntry{{ + Binding: 0, + Buffer: buf, + Size: ClusteredFallbackUniformSize, + }}, + }) + if err != nil { + _ = layout.Close() + _ = buf.Close() + return nil, err + } + + return &ClusteredLightSystem{ + cfg: cfg, + fallback: true, + layout: layout, + group: group, + paramsBuf: buf, + fallbackDst: make([]ClusterLight, 0, cfg.FallbackMaxLights), + fallbackTmp: make([]scoredClusterLight, 0, cfg.MaxLights), + }, nil +} + +func newClusteredStorageSystem(cx *core.Scope, dev *gpu.Device, cfg ClusterConfig, label string) (*ClusteredLightSystem, error) { + grid, err := NewClusterGrid(cfg) + if err != nil { + return nil, err + } + + numClusters := cfg.ClusterCount() + lightsSize := uint64(cfg.MaxLights) * ClusterLightGPUSize + cellsSize := uint64(numClusters) * ClusterCellGPUSize + indicesCap := numClusters * cfg.MaxLightsPerCluster + indicesSize := uint64(indicesCap) * 4 + + // Respect MaxStorageBufferBindingSize by capping indices buffer capacity safely if needed. + maxBind := dev.Capabilities().Limits.MaxStorageBufferBindingSize + if maxBind > 0 && indicesSize > maxBind { + indicesCap = max(int(maxBind/4), 1) + indicesSize = uint64(indicesCap) * 4 + } + + var toClose []interface{ Close() error } + fail := func(err error) (*ClusteredLightSystem, error) { + for i := len(toClose) - 1; i >= 0; i-- { + _ = toClose[i].Close() + } + return nil, err + } + + paramsBuf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + " params", + Size: ClusterParamsUniformSize, + Usage: gpu.UsageUniform | gpu.UsageCopyDst, + Retained: cfg.Retained, + }) + if err != nil { + return fail(err) + } + toClose = append(toClose, paramsBuf) + + lightsBuf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + " lights", + Size: lightsSize, + Usage: gpu.UsageStorage | gpu.UsageCopyDst, + Retained: cfg.Retained, + }) + if err != nil { + return fail(err) + } + toClose = append(toClose, lightsBuf) + + cellsBuf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + " cells", + Size: cellsSize, + Usage: gpu.UsageStorage | gpu.UsageCopyDst, + Retained: cfg.Retained, + }) + if err != nil { + return fail(err) + } + toClose = append(toClose, cellsBuf) + + indicesBuf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + " indices", + Size: indicesSize, + Usage: gpu.UsageStorage | gpu.UsageCopyDst, + Retained: cfg.Retained, + }) + if err != nil { + return fail(err) + } + toClose = append(toClose, indicesBuf) + + layout, err := dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{ + Label: label + " layout", + Entries: []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageFragment, Type: gpu.BindingUniform}, + {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingStorageRead}, + {Binding: 2, Visibility: gpu.StageFragment, Type: gpu.BindingStorageRead}, + {Binding: 3, Visibility: gpu.StageFragment, Type: gpu.BindingStorageRead}, + }, + }) + if err != nil { + return fail(err) + } + toClose = append(toClose, layout) + + group, err := dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{ + Label: label + " group", + Layout: layout, + Entries: []gpu.BindGroupEntry{ + {Binding: 0, Buffer: paramsBuf, Size: ClusterParamsUniformSize}, + {Binding: 1, Buffer: lightsBuf, Size: lightsSize}, + {Binding: 2, Buffer: cellsBuf, Size: cellsSize}, + {Binding: 3, Buffer: indicesBuf, Size: indicesSize}, + }, + }) + if err != nil { + return fail(err) + } + + return &ClusteredLightSystem{ + cfg: cfg, + fallback: false, + grid: grid, + layout: layout, + group: group, + paramsBuf: paramsBuf, + lightsBuf: lightsBuf, + cellsBuf: cellsBuf, + indicesBuf: indicesBuf, + indicesCap: indicesCap, + lightsBytes: make([]byte, lightsSize), + cellsBytes: make([]byte, cellsSize), + indicesBytes: make([]byte, indicesSize), + }, nil +} + +// IsClustered reports whether s is running the storage-buffer clustered forward shading path. +func (s *ClusteredLightSystem) IsClustered() bool { return s != nil && !s.fallback } + +// IsFallback reports whether s is running the uniform-buffer mobile / WebGL 2 / GLES 3.0 fallback path. +func (s *ClusteredLightSystem) IsFallback() bool { return s != nil && s.fallback } + +// Config returns the normalized [ClusterConfig] used to construct s. +func (s *ClusteredLightSystem) Config() ClusterConfig { + if s == nil { + return ClusterConfig{} + } + return s.cfg +} + +// Grid returns the underlying [ClusterGrid] in clustered mode, or nil in fallback mode. +func (s *ClusteredLightSystem) Grid() *ClusterGrid { + if s == nil { + return nil + } + return s.grid +} + +// Layout returns the bind group layout a pipeline lists at [ClusteredLightGroup] (group 1). +func (s *ClusteredLightSystem) Layout() *gpu.BindGroupLayout { + if s == nil { + return nil + } + return s.layout +} + +// BindGroup returns the bind group a render pass sets at [ClusteredLightGroup] (group 1). +func (s *ClusteredLightSystem) BindGroup() *gpu.BindGroup { + if s == nil { + return nil + } + return s.group +} + +// WGSL returns the ready-to-compile WGSL shader matching s's active path ([ClusteredLitWGSL] or [ClusteredFallbackWGSL]). +func (s *ClusteredLightSystem) WGSL() string { + if s.IsFallback() { + return ClusteredFallbackWGSL + } + return ClusteredLitWGSL +} + +// BindingsWGSL returns the @group(1) declarations and evaluate_clustered_lights function matching s's active path ([ClusteredBindingsWGSL] or [ClusteredFallbackBindingsWGSL]). +func (s *ClusteredLightSystem) BindingsWGSL() string { + if s.IsFallback() { + return ClusteredFallbackBindingsWGSL + } + return ClusteredBindingsWGSL +} + +// FallbackLights returns the prioritized lights uploaded on the most recent update in fallback mode (nil in clustered mode). +func (s *ClusteredLightSystem) FallbackLights() []ClusterLight { + if s == nil || !s.fallback { + return nil + } + return s.fallbackDst +} + +// LastStats returns the [ClusterStats] from the most recent [ClusteredLightSystem.Update] or [ClusteredLightSystem.UpdateCamera] call. +func (s *ClusteredLightSystem) LastStats() ClusterStats { + if s == nil { + return ClusterStats{} + } + return s.lastStats +} + +// ByteSize returns the total GPU buffer memory owned by s, for [RenderStats] and [Budget] accounting. +func (s *ClusteredLightSystem) ByteSize() uint64 { + if s == nil { + return 0 + } + var total uint64 + for _, b := range []*gpu.Buffer{s.paramsBuf, s.lightsBuf, s.cellsBuf, s.indicesBuf} { + if b != nil { + total += b.Size() + } + } + return total +} + +// Valid reports whether s's GPU resources are open and belong to a live device. +func (s *ClusteredLightSystem) Valid() bool { + if s == nil || !s.paramsBuf.Valid() || !s.layout.Valid() || !s.group.Valid() { + return false + } + if s.fallback { + return true + } + return s.lightsBuf.Valid() && s.cellsBuf.Valid() && s.indicesBuf.Valid() +} + +// Bind sets s's bind group at group on pass. It records nothing when s is not [ClusteredLightSystem.Valid]. +func (s *ClusteredLightSystem) Bind(pass *gpu.RenderPass, group uint32) { + if !s.Valid() || pass == nil { + return + } + pass.SetBindGroup(group, s.group) +} + +// Update assigns lights for the frame and uploads the resulting lighting buffers to dev. +// +// In clustered mode, lights are binned into view-space frustum clusters via [ClusterGrid.AssignLights] and uploaded into the uniform and storage buffers. In fallback mode, the top [ClusterConfig.FallbackMaxLights] prioritized lights are selected via [SelectFallbackLights] and uploaded into the uniform buffer. +func (s *ClusteredLightSystem) Update(dev *gpu.Device, view, proj math3d.Mat4, near, far, viewportW, viewportH float32, ambient math3d.Vec3, lights []ClusterLight) ClusterStats { + if s == nil { + return ClusterStats{} + } + if s.fallback { + camPos, camFwd := cameraPoseFromView(view) + s.fallbackDst = selectFallbackLightsWithScratch(s.fallbackDst, &s.fallbackTmp, camPos, camFwd, lights, s.cfg.FallbackMaxLights) + stats := ClusterStats{ + InputLights: len(lights), + VisibleLights: len(s.fallbackDst), + CulledLights: len(lights) - len(s.fallbackDst), + } + if len(s.fallbackTmp) > len(s.fallbackDst) { + stats.TruncatedLights = len(s.fallbackTmp) - len(s.fallbackDst) + } + s.lastStats = stats + if dev != nil && s.Valid() { + encodeFallbackUniform(&s.fallbackData, ambient, s.fallbackDst) + dev.WriteBuffer(s.paramsBuf, 0, s.fallbackData[:]) + } + return stats + } + + stats := s.grid.AssignLights(view, proj, near, far, lights) + s.lastStats = stats + if dev == nil || !s.Valid() { + return stats + } + + encodeClusterParams(&s.paramsBytes, s.cfg, uint32(len(s.grid.activeLights)), viewportW, viewportH, near, far, ambient, s.grid.SliceDepths()) + dev.WriteBuffer(s.paramsBuf, 0, s.paramsBytes[:]) + + active := s.grid.activeLights + if len(active) > 0 { + nBytes := len(active) * ClusterLightGPUSize + for i := range active { + encodeClusterLightGPU(s.lightsBytes[i*ClusterLightGPUSize:], active[i]) + } + dev.WriteBuffer(s.lightsBuf, 0, s.lightsBytes[:nBytes]) + } + + offsets := s.grid.offsets + indices := s.grid.lightIndices + maxIdx := uint32(s.indicesCap) + for i, oc := range offsets { + off := oc.Offset + cnt := oc.Count + if off >= maxIdx { + off = 0 + cnt = 0 + } else if off+cnt > maxIdx { + cnt = maxIdx - off + } + base := i * ClusterCellGPUSize + binary.LittleEndian.PutUint32(s.cellsBytes[base+0:], off) + binary.LittleEndian.PutUint32(s.cellsBytes[base+4:], cnt) + binary.LittleEndian.PutUint32(s.cellsBytes[base+8:], 0) + binary.LittleEndian.PutUint32(s.cellsBytes[base+12:], 0) + } + dev.WriteBuffer(s.cellsBuf, 0, s.cellsBytes) + + if len(indices) > 0 { + nIdx := min(len(indices), s.indicesCap) + for i := range nIdx { + binary.LittleEndian.PutUint32(s.indicesBytes[i*4:], indices[i]) + } + dev.WriteBuffer(s.indicesBuf, 0, s.indicesBytes[:nIdx*4]) + } + + return stats +} + +// UpdateCamera is a convenience wrapper around [ClusteredLightSystem.Update] extracting view, projection, near, and far from cam. +func (s *ClusteredLightSystem) UpdateCamera(dev *gpu.Device, cam *scene3d.Camera, viewportW, viewportH float32, ambient math3d.Vec3, lights []ClusterLight) ClusterStats { + if cam == nil { + return ClusterStats{} + } + near := cam.Projection.Near + far := cam.Projection.Far + if near <= 0 && cam.Projection.Kind != scene3d.ProjectionOrthographic { + near = 0.1 + } + if near == 0 && far == 0 { + near, far = 0.1, 1000 + } else if far <= near { + far = near + 1000 + } + return s.Update(dev, cam.ViewMatrix(), cam.ProjMatrix(), near, far, viewportW, viewportH, ambient, lights) +} + +// Close releases all GPU resources owned by s now instead of when their scope is disposed. Safe to call on nil or more than once. +func (s *ClusteredLightSystem) Close() error { + if s == nil { + return nil + } + var err error + for _, c := range []interface{ Close() error }{s.group, s.layout, s.indicesBuf, s.cellsBuf, s.lightsBuf, s.paramsBuf} { + if c == nil { + continue + } + err = errors.Join(err, c.Close()) + } + return err +} + +func cameraPoseFromView(view math3d.Mat4) (pos, forward math3d.Vec3) { + // Camera forward in world space is -row(2) of an orthonormal view matrix; camera position is -R^T * t. + if inv, ok := view.Inverse(); ok { + pos = math3d.Vec3{X: inv[12], Y: inv[13], Z: inv[14]} + forward = math3d.Vec3{X: -inv[8], Y: -inv[9], Z: -inv[10]} + if forward.LenSq() > 1e-12 { + forward = forward.Norm() + } else { + forward = math3d.Vec3Forward() + } + return pos, forward + } + return math3d.Vec3Zero(), math3d.Vec3Forward() +} + +func encodeClusterLightGPU(dst []byte, l ClusterLight) { + dir := l.normalizedDir() + scale, offset := l.spotScaleOffset() + kind := float32(0) + if l.Kind == ClusterLightSpot { + kind = 1 + } + // vec4 pos_range + clusterPutFloat32LE(dst[0:], l.Position.X) + clusterPutFloat32LE(dst[4:], l.Position.Y) + clusterPutFloat32LE(dst[8:], l.Position.Z) + clusterPutFloat32LE(dst[12:], l.Range) + // vec4 color_intensity + clusterPutFloat32LE(dst[16:], l.Color.X) + clusterPutFloat32LE(dst[20:], l.Color.Y) + clusterPutFloat32LE(dst[24:], l.Color.Z) + clusterPutFloat32LE(dst[28:], l.Intensity) + // vec4 dir_kind + clusterPutFloat32LE(dst[32:], dir.X) + clusterPutFloat32LE(dst[36:], dir.Y) + clusterPutFloat32LE(dst[40:], dir.Z) + clusterPutFloat32LE(dst[44:], kind) + // vec4 spot_params + clusterPutFloat32LE(dst[48:], scale) + clusterPutFloat32LE(dst[52:], offset) + clusterPutFloat32LE(dst[56:], l.OuterConeCos) + clusterPutFloat32LE(dst[60:], l.InnerConeCos) +} + +func encodeClusterParams(dst *[ClusterParamsUniformSize]byte, cfg ClusterConfig, lightCount uint32, viewportW, viewportH, near, far float32, ambient math3d.Vec3, sliceDepths []float32) { + clear(dst[:]) + // grid_info: vec4 + binary.LittleEndian.PutUint32(dst[0:], uint32(cfg.TilesX)) + binary.LittleEndian.PutUint32(dst[4:], uint32(cfg.TilesY)) + binary.LittleEndian.PutUint32(dst[8:], uint32(cfg.SlicesZ)) + binary.LittleEndian.PutUint32(dst[12:], lightCount) + // viewport_depth: vec4 + clusterPutFloat32LE(dst[16:], viewportW) + clusterPutFloat32LE(dst[20:], viewportH) + clusterPutFloat32LE(dst[24:], near) + clusterPutFloat32LE(dst[28:], far) + // ambient: vec4 + clusterPutFloat32LE(dst[32:], ambient.X) + clusterPutFloat32LE(dst[36:], ambient.Y) + clusterPutFloat32LE(dst[40:], ambient.Z) + clusterPutFloat32LE(dst[44:], 0) + // slice_depths: array, 17> (68 float32 slots starting at byte 48) + n := min(len(sliceDepths), MaxClusterSlicesZ+1) + for i := range n { + clusterPutFloat32LE(dst[48+i*4:], sliceDepths[i]) + } +} + +func encodeFallbackUniform(dst *[ClusteredFallbackUniformSize]byte, ambient math3d.Vec3, lights []ClusterLight) { + clear(dst[:]) + n := min(len(lights), MaxFallbackLights) + binary.LittleEndian.PutUint32(dst[0:], uint32(n)) + clusterPutFloat32LE(dst[16:], ambient.X) + clusterPutFloat32LE(dst[20:], ambient.Y) + clusterPutFloat32LE(dst[24:], ambient.Z) + clusterPutFloat32LE(dst[28:], 0) + for i := range n { + encodeClusterLightGPU(dst[32+i*ClusterLightGPUSize:], lights[i]) + } +} + +func clusterPutFloat32LE(dst []byte, v float32) { + binary.LittleEndian.PutUint32(dst, math.Float32bits(v)) +} diff --git a/packages/game/render3d/clustered_test.go b/packages/game/render3d/clustered_test.go new file mode 100644 index 00000000..9053dea4 --- /dev/null +++ b/packages/game/render3d/clustered_test.go @@ -0,0 +1,908 @@ +package render3d_test + +import ( + "errors" + "image" + "image/color" + "math" + "testing" + "time" + + "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" +) + +func clusterTestFloorMesh(half float32) render3d.Mesh { + up := math3d.Vec3Up() + return render3d.Mesh{ + Positions: []math3d.Vec3{ + {X: -half, Y: 0, Z: half}, + {X: half, Y: 0, Z: half}, + {X: half, Y: 0, Z: -half}, + {X: -half, Y: 0, Z: -half}, + }, + Normals: []math3d.Vec3{up, up, up, up}, + UVs: []math3d.Vec2{ + {X: 0, Y: 1}, + {X: 1, Y: 1}, + {X: 1, Y: 0}, + {X: 0, Y: 0}, + }, + Indices: []uint32{0, 1, 2, 0, 2, 3}, + } +} + +func clusterTest256PointLights() []render3d.ClusterLight { + lights := make([]render3d.ClusterLight, 0, 256) + palette := [...]math3d.Vec3{ + {X: 1.0, Y: 0.25, Z: 0.15}, + {X: 0.15, Y: 1.0, Z: 0.25}, + {X: 0.2, Y: 0.35, Z: 1.0}, + {X: 1.0, Y: 0.85, Z: 0.2}, + {X: 0.9, Y: 0.25, Z: 0.95}, + {X: 0.2, Y: 0.95, Z: 0.95}, + } + // 16x16 grid spanning X in [-15, 15], Z in [-15, 15] at Y = 1.25. + for gz := range 16 { + for gx := range 16 { + idx := gz*16 + gx + x := -15.0 + float32(gx)*2.0 + z := -15.0 + float32(gz)*2.0 + col := palette[idx%len(palette)] + lights = append(lights, render3d.NewPointClusterLight( + math3d.Vec3{X: x, Y: 1.25, Z: z}, + col, + 1.8, + 2.8, + )) + } + } + return lights +} + +func clusterTestClampByte(v float32) uint8 { + if v <= 0 { + return 0 + } + if v >= 1 { + return 255 + } + return uint8(math.Round(float64(v) * 255.0)) +} + +func clusterTestVec3ToRGBA(v math3d.Vec3) color.RGBA { + return color.RGBA{ + R: clusterTestClampByte(v.X), + G: clusterTestClampByte(v.Y), + B: clusterTestClampByte(v.Z), + A: 255, + } +} + +func clusterTestAssertPixelNear(t *testing.T, img *image.RGBA, x, y int, want color.RGBA, tol int, label string) { + t.Helper() + got := img.RGBAAt(x, y) + diff := func(a, b uint8) int { + d := int(a) - int(b) + if d < 0 { + return -d + } + return d + } + if diff(got.R, want.R) > tol || diff(got.G, want.G) > tol || diff(got.B, want.B) > tol || diff(got.A, want.A) > tol { + t.Errorf("%s at (%d,%d): got RGBA(%d,%d,%d,%d), want RGBA(%d,%d,%d,%d) ±%d", + label, x, y, got.R, got.G, got.B, got.A, want.R, want.G, want.B, want.A, tol) + } +} + +func clusterTestBuildPipeline(t *testing.T, cx *core.Scope, dev *gpu.Device, camLayout *gpu.BindGroupLayout, sys *render3d.ClusteredLightSystem, depth gpu.TextureFormat) *gpu.Pipeline { + t.Helper() + mod, err := gpu.CompileWGSL(sys.WGSL()) + if err != nil { + t.Fatalf("CompileWGSL: %v", err) + } + layouts := make([]*gpu.BindGroupLayout, render3d.ClusteredLightGroup+1) + layouts[render3d.CameraGroup] = camLayout + layouts[render3d.ClusteredLightGroup] = sys.Layout() + + desc := gpu.PipelineDesc{ + Label: "clustered-lit", + Vertex: gpu.ShaderStage{Module: mod, EntryPoint: "vs_main"}, + Fragment: gpu.ShaderStage{Module: mod, EntryPoint: "fs_main"}, + Layouts: layouts, + VertexBuffers: []gpu.VertexBufferLayout{render3d.MeshVertexLayout()}, + Primitive: gpu.PrimitiveState{Topology: gpu.TopologyTriangleList, CullMode: gpu.CullNone}, + Targets: []gpu.ColorTargetState{{Format: dev.SurfaceFormat(), WriteMask: gpu.ColorWriteAll}}, + } + if depth != gpu.FormatUndefined { + desc.DepthStencil = &gpu.DepthStencilState{ + Format: depth, + DepthWrite: true, + DepthCompare: gpu.CompareLess, + } + } + pipe, err := dev.CreatePipeline(cx, desc) + if err != nil { + t.Fatalf("CreatePipeline: %v", err) + } + return pipe +} + +func clusterTestWorldPointAtPixel(cam *scene3d.Camera, px, py, w, h float32) (math3d.Vec3, bool) { + // Intersect screen ray through pixel center (px+0.5, py+0.5) with Y=0 floor plane. + ray := cam.ScreenRay(px+0.5, py+0.5, w, h) + if math.Abs(float64(ray.Dir.Y)) < 1e-6 { + return math3d.Vec3{}, false + } + t := -ray.Origin.Y / ray.Dir.Y + if t <= 0 { + return math3d.Vec3{}, false + } + return ray.At(t), true +} + +func TestClusterConfigAndLightValidation(t *testing.T) { + if err := (render3d.ClusterConfig{}).Validate(); err != nil { + t.Fatalf("zero ClusterConfig should apply defaults and validate: %v", err) + } + def := render3d.DefaultClusterConfig() + if got := def.ClusterCount(); got != 16*9*24 { + t.Fatalf("DefaultClusterConfig().ClusterCount() = %d, want %d", got, 16*9*24) + } + + badConfigs := []struct { + name string + cfg render3d.ClusterConfig + }{ + {"negative TilesX", render3d.ClusterConfig{TilesX: -1}}, + {"negative TilesY", render3d.ClusterConfig{TilesY: -2}}, + {"SlicesZ too large", render3d.ClusterConfig{SlicesZ: render3d.MaxClusterSlicesZ + 1}}, + {"negative SlicesZ", render3d.ClusterConfig{SlicesZ: -1}}, + {"negative MaxLights", render3d.ClusterConfig{MaxLights: -5}}, + {"negative MaxLightsPerCluster", render3d.ClusterConfig{MaxLightsPerCluster: -1}}, + {"FallbackMaxLights too large", render3d.ClusterConfig{FallbackMaxLights: render3d.MaxFallbackLights + 1}}, + {"negative FallbackMaxLights", render3d.ClusterConfig{FallbackMaxLights: -1}}, + } + for _, tc := range badConfigs { + t.Run(tc.name, func(t *testing.T) { + err := tc.cfg.Validate() + if !errors.Is(err, render3d.ErrInvalidClusterConfig) { + t.Fatalf("Validate() = %v, want wrapping ErrInvalidClusterConfig", err) + } + if _, err := render3d.NewClusterGrid(tc.cfg); !errors.Is(err, render3d.ErrInvalidClusterConfig) { + t.Fatalf("NewClusterGrid() = %v, want wrapping ErrInvalidClusterConfig", err) + } + }) + } + + pt := render3d.NewPointClusterLight(math3d.Vec3{Y: 2}, math3d.Vec3{X: 1, Y: 1, Z: 1}, 3, 5) + if err := pt.Validate(); err != nil { + t.Fatalf("valid point light failed Validate: %v", err) + } + sp := render3d.NewSpotClusterLight(math3d.Vec3{Y: 3}, math3d.Vec3{Y: -1}, math3d.Vec3{X: 1}, 2, 6, 0.2, 0.5) + if err := sp.Validate(); err != nil { + t.Fatalf("valid spot light failed Validate: %v", err) + } + + badLights := []struct { + name string + l render3d.ClusterLight + }{ + {"unknown kind", render3d.ClusterLight{Kind: 99, Range: 1, Color: math3d.Vec3{X: 1}, Intensity: 1}}, + {"zero range", render3d.NewPointClusterLight(math3d.Vec3Zero(), math3d.Vec3{X: 1}, 1, 0)}, + {"NaN pos", render3d.NewPointClusterLight(math3d.Vec3{X: float32(math.NaN())}, math3d.Vec3{X: 1}, 1, 5)}, + {"negative color", render3d.NewPointClusterLight(math3d.Vec3Zero(), math3d.Vec3{X: -0.1}, 1, 5)}, + {"negative intensity", render3d.NewPointClusterLight(math3d.Vec3Zero(), math3d.Vec3{X: 1}, -1, 5)}, + {"inverted spot cones", render3d.ClusterLight{Kind: render3d.ClusterLightSpot, Range: 5, Color: math3d.Vec3{X: 1}, Intensity: 1, Direction: math3d.Vec3{Y: -1}, InnerConeCos: 0.5, OuterConeCos: 0.8}}, + {"out of range cone cos", render3d.ClusterLight{Kind: render3d.ClusterLightSpot, Range: 5, Color: math3d.Vec3{X: 1}, Intensity: 1, Direction: math3d.Vec3{Y: -1}, InnerConeCos: 1.5, OuterConeCos: 0.5}}, + } + for _, tc := range badLights { + t.Run(tc.name, func(t *testing.T) { + if err := tc.l.Validate(); !errors.Is(err, render3d.ErrInvalidClusterLight) { + t.Fatalf("Validate() = %v, want wrapping ErrInvalidClusterLight", err) + } + }) + } +} + +func TestClusterGridLogarithmicSlicesAndBinarySearch(t *testing.T) { + grid, err := render3d.NewClusterGrid(render3d.DefaultClusterConfig()) + if err != nil { + t.Fatalf("NewClusterGrid: %v", err) + } + near, far := float32(0.5), float32(100.0) + proj := math3d.Perspective(math3d.DegToRad(60), 16.0/9.0, near, far) + if !grid.BuildFrustum(proj, near, far) { + t.Fatal("BuildFrustum returned false for valid perspective matrix") + } + + depths := grid.SliceDepths() + if len(depths) != render3d.DefaultClusterSlicesZ+1 { + t.Fatalf("len(SliceDepths) = %d, want %d", len(depths), render3d.DefaultClusterSlicesZ+1) + } + for s := 0; s <= render3d.DefaultClusterSlicesZ; s++ { + want := float32(float64(near) * math.Pow(float64(far)/float64(near), float64(s)/float64(render3d.DefaultClusterSlicesZ))) + if math.Abs(float64(depths[s]-want)) > 1e-4*float64(want+1) { + t.Fatalf("slice depth[%d] = %v, want %v", s, depths[s], want) + } + } + + // Verify SliceForDepth matches exact logarithmic intervals. + if got := grid.SliceForDepth(near * 0.5); got != 0 { + t.Fatalf("SliceForDepth(before near) = %d, want 0", got) + } + if got := grid.SliceForDepth(far * 2.0); got != render3d.DefaultClusterSlicesZ-1 { + t.Fatalf("SliceForDepth(past far) = %d, want %d", got, render3d.DefaultClusterSlicesZ-1) + } + for s := range render3d.DefaultClusterSlicesZ { + mid := 0.5 * (depths[s] + depths[s+1]) + if got := grid.SliceForDepth(mid); got != s { + t.Fatalf("SliceForDepth(mid of slice %d = %v) = %d, want %d", s, mid, got, s) + } + } + + // Orthographic projection should also build linear depth slices cleanly. + ortho := math3d.Ortho(-10, 10, -10, 10, 0.1, 50) + if !grid.BuildFrustum(ortho, 0.1, 50) { + t.Fatal("BuildFrustum returned false for orthographic matrix") + } + orthoDepths := grid.SliceDepths() + if math.Abs(float64(orthoDepths[12]-25.05)) > 1e-3 { + t.Fatalf("ortho midpoint depth = %v, want ~25.05", orthoDepths[12]) + } +} + +func TestClusterGridCullingSpotBoundsAndZeroAllocs(t *testing.T) { + grid, err := render3d.NewClusterGrid(render3d.DefaultClusterConfig()) + if err != nil { + t.Fatalf("NewClusterGrid: %v", err) + } + + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{Y: 2, Z: 10}, math3d.DegToRad(60), 16.0/9.0, 0.5, 50) + cam.LookAt(math3d.Vec3{Y: 0, Z: 0}, math3d.Vec3Up()) + view := cam.ViewMatrix() + proj := cam.ProjMatrix() + + // 1. Lights behind camera, beyond far plane, far off to side, or zero intensity must be culled. + culledSet := []render3d.ClusterLight{ + render3d.NewPointClusterLight(math3d.Vec3{Y: 2, Z: 25}, math3d.Vec3{X: 1}, 2, 3), // behind camera + render3d.NewPointClusterLight(math3d.Vec3{Y: 2, Z: -70}, math3d.Vec3{X: 1}, 2, 3), // beyond far + render3d.NewPointClusterLight(math3d.Vec3{X: 90, Y: 2, Z: 0}, math3d.Vec3{X: 1}, 2, 3), // outside frustum right + render3d.NewPointClusterLight(math3d.Vec3{Y: 1, Z: 0}, math3d.Vec3{X: 1}, 0, 3), // zero intensity + } + st := grid.AssignLights(view, proj, 0.5, 50, culledSet) + if st.VisibleLights != 0 || st.CulledLights != len(culledSet) || st.ActiveClusters != 0 { + t.Fatalf("expected all lights culled, got stats %+v", st) + } + + // 2. Spot light narrow cone should occupy strictly fewer clusters than an equal-range point light. + pointAtCenter := []render3d.ClusterLight{ + render3d.NewPointClusterLight(math3d.Vec3{Y: 2, Z: 0}, math3d.Vec3{X: 1, Y: 1, Z: 1}, 2, 5), + } + spotAtCenter := []render3d.ClusterLight{ + render3d.NewSpotClusterLight(math3d.Vec3{Y: 2, Z: 0}, math3d.Vec3{Y: -1}, math3d.Vec3{X: 1, Y: 1, Z: 1}, 2, 5, math3d.DegToRad(10), math3d.DegToRad(18)), + } + ptStats := grid.AssignLights(view, proj, 0.5, 50, pointAtCenter) + spStats := grid.AssignLights(view, proj, 0.5, 50, spotAtCenter) + if spStats.ActiveClusters == 0 || spStats.ActiveClusters >= ptStats.ActiveClusters { + t.Fatalf("expected narrow spot (%d clusters) to occupy >0 and fewer clusters than equal-range point (%d clusters)", + spStats.ActiveClusters, ptStats.ActiveClusters) + } + + // 3. Light straddling the camera / near plane must still assign clusters (no false negative). + nearLight := []render3d.ClusterLight{ + render3d.NewPointClusterLight(math3d.Vec3{Y: 2, Z: 10}, math3d.Vec3{X: 1}, 2, 4), // centered on camera! + } + nearStats := grid.AssignLights(view, proj, 0.5, 50, nearLight) + if nearStats.VisibleLights != 1 || nearStats.ActiveClusters == 0 { + t.Fatalf("camera-straddling light was dropped: %+v", nearStats) + } + + // 4. Steady-state 256 lights AssignLights must perform zero heap allocations. + lights256 := clusterTest256PointLights() + // Warm up once (builds frustum cache & sizes lightIndices). + grid.AssignLights(view, proj, 0.5, 50, lights256) + allocs := testing.AllocsPerRun(50, func() { + grid.AssignLights(view, proj, 0.5, 50, lights256) + }) + if allocs != 0 { + t.Fatalf("steady-state AssignLights(256 lights) allocated %.2f times/op, want 0", allocs) + } +} + +func TestClustered256PointLightsParityAndBudget(t *testing.T) { + const ( + viewW = 128 + viewH = 96 + near = float32(0.5) + far = float32(60.0) + ) + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 14, Z: 18}, math3d.DegToRad(50), float32(viewW)/float32(viewH), near, far) + cam.LookAt(math3d.Vec3{X: 0, Y: 0, Z: 0}, math3d.Vec3Up()) + ambient := math3d.Vec3{X: 0.04, Y: 0.04, Z: 0.05} + lights := clusterTest256PointLights() + + sr := gpu.NewSoftwareRenderer(viewW, viewH, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + dev := sr.Device() + + if !render3d.DeviceSupportsClusteredLighting(dev) { + t.Fatal("default SoftwareRenderer must support clustered lighting") + } + + camBuf, err := render3d.NewCameraBuffer(nil, dev) + if err != nil { + t.Fatalf("NewCameraBuffer: %v", err) + } + t.Cleanup(func() { _ = camBuf.Close() }) + + sys, err := render3d.NewClusteredLightSystem(nil, dev, render3d.DefaultClusterConfig()) + if err != nil { + t.Fatalf("NewClusteredLightSystem: %v", err) + } + t.Cleanup(func() { _ = sys.Close() }) + + if !sys.IsClustered() || sys.IsFallback() { + t.Fatalf("expected clustered mode on full device, got clustered=%v fallback=%v", sys.IsClustered(), sys.IsFallback()) + } + if sys.ByteSize() == 0 { + t.Fatal("expected positive GPU ByteSize") + } + + floor, err := render3d.UploadMesh(nil, dev, clusterTestFloorMesh(20), render3d.MeshUpload{Label: "floor"}) + if err != nil { + t.Fatalf("UploadMesh: %v", err) + } + t.Cleanup(func() { _ = floor.Close() }) + + pipe := clusterTestBuildPipeline(t, nil, dev, camBuf.Layout(), sys, gpu.FormatDepth24Plus) + t.Cleanup(func() { _ = pipe.Close() }) + + // Warm up frustum cache once, then time 256-light assignment against the 16.6ms 60fps desktop budget. + _ = sys.UpdateCamera(dev, cam, viewW, viewH, ambient, lights) + start := time.Now() + stats := sys.UpdateCamera(dev, cam, viewW, viewH, ambient, lights) + assignElapsed := time.Since(start) + + if stats.InputLights != 256 { + t.Fatalf("InputLights = %d, want 256", stats.InputLights) + } + if stats.VisibleLights < 100 { + t.Fatalf("expected >= 100 visible point lights across the 16x16 grid, got %d (stats=%+v)", stats.VisibleLights, stats) + } + if stats.ActiveClusters == 0 { + t.Fatalf("expected active clusters > 0, got %+v", stats) + } + if assignElapsed > 16*time.Millisecond { + t.Fatalf("256-light UpdateCamera took %v, exceeding 16ms frame budget", assignElapsed) + } + + // Render the floor lit by all 256 clustered point lights. + camBuf.WriteCamera(cam) + enc := dev.BeginEncoder() + pass := enc.BeginRenderPass(gpu.RenderPassDesc{ + Label: "clustered-256", + ColorAttachments: []gpu.ColorAttachment{{ + LoadOp: gpu.LoadClear, + StoreOp: gpu.StoreStore, + ClearColor: core.RGB(0x050608), + }}, + DepthStencil: &gpu.DepthStencilAttachment{ + DepthLoadOp: gpu.LoadClear, + DepthStoreOp: gpu.StoreDiscard, + ClearDepth: 1, + }, + }) + pass.SetPipeline(pipe) + pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) + sys.Bind(pass, render3d.ClusteredLightGroup) + floor.Draw(pass) + pass.End() + dev.Submit(enc.Finish()) + sr.WaitIdle() + if err := sr.LastError(); err != nil { + t.Fatalf("software renderer: %v", err) + } + + img := sr.Image() + view := cam.ViewMatrix() + proj := cam.ProjMatrix() + white := math3d.Vec3{X: 1, Y: 1, Z: 1} + up := math3d.Vec3Up() + + // Sample a 7x5 grid across the visible floor and assert BOTH: + // 1. Pure-Go clustered evaluation matches brute-force EvaluateDirectLights (zero false culls across 256 lights). + // 2. GPU rasterized pixel matches pure-Go analytic reference within ±3/255. + litSamples := 0 + for sy := 24; sy <= 80; sy += 14 { + for sx := 20; sx <= 108; sx += 14 { + worldPt, ok := clusterTestWorldPointAtPixel(cam, float32(sx), float32(sy), viewW, viewH) + if !ok || math.Abs(float64(worldPt.X)) > 19 || math.Abs(float64(worldPt.Z)) > 19 { + continue + } + direct := render3d.EvaluateDirectLights(worldPt, up, white, ambient, lights) + clustered := render3d.EvaluateClusteredLights(worldPt, up, white, ambient, sys.Grid(), view, proj, viewW, viewH) + if math.Abs(float64(direct.X-clustered.X)) > 1e-4 || + math.Abs(float64(direct.Y-clustered.Y)) > 1e-4 || + math.Abs(float64(direct.Z-clustered.Z)) > 1e-4 { + t.Fatalf("CPU clustered vs direct mismatch at pixel (%d,%d) world %v: clustered=%v direct=%v", + sx, sy, worldPt, clustered, direct) + } + wantRGBA := clusterTestVec3ToRGBA(direct) + clusterTestAssertPixelNear(t, img, sx, sy, wantRGBA, 3, "clustered-256") + if wantRGBA.R > 25 || wantRGBA.G > 25 || wantRGBA.B > 25 { + litSamples++ + } + } + } + if litSamples < 10 { + t.Fatalf("expected at least 10 visibly lit floor sample points, got %d", litSamples) + } +} + +func TestClusteredMixedPointAndSpotLightsGPU(t *testing.T) { + const ( + viewW = 96 + viewH = 96 + near = float32(0.5) + far = float32(40.0) + ) + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 10, Z: 10}, math3d.DegToRad(50), 1, near, far) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + ambient := math3d.Vec3{X: 0.02, Y: 0.02, Z: 0.02} + + lights := []render3d.ClusterLight{ + // Red point light on the left (-3, 1.5, 0). + render3d.NewPointClusterLight(math3d.Vec3{X: -3, Y: 1.5, Z: 0}, math3d.Vec3{X: 1, Y: 0.1, Z: 0.1}, 3.0, 4.5), + // Green downward spotlight on the right (3, 3, 0) with a tight cone (15 deg inner, 25 deg outer). + render3d.NewSpotClusterLight( + math3d.Vec3{X: 3, Y: 3, Z: 0}, + math3d.Vec3{Y: -1}, + math3d.Vec3{X: 0.1, Y: 1, Z: 0.1}, + 8.0, 7.0, + math3d.DegToRad(15), math3d.DegToRad(25), + ), + // Blue spotlight at center aiming UP away from the floor -> must contribute zero to the floor! + render3d.NewSpotClusterLight( + math3d.Vec3{X: 0, Y: 2, Z: 0}, + math3d.Vec3{Y: 1}, + math3d.Vec3{X: 0.1, Y: 0.2, Z: 1}, + 10.0, 8.0, + math3d.DegToRad(20), math3d.DegToRad(35), + ), + } + + sr := gpu.NewSoftwareRenderer(viewW, viewH, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + dev := sr.Device() + + camBuf, err := render3d.NewCameraBuffer(nil, dev) + if err != nil { + t.Fatalf("NewCameraBuffer: %v", err) + } + t.Cleanup(func() { _ = camBuf.Close() }) + + sys, err := render3d.NewClusteredLightSystem(nil, dev, render3d.DefaultClusterConfig()) + if err != nil { + t.Fatalf("NewClusteredLightSystem: %v", err) + } + t.Cleanup(func() { _ = sys.Close() }) + + floor, err := render3d.UploadMesh(nil, dev, clusterTestFloorMesh(10), render3d.MeshUpload{}) + if err != nil { + t.Fatalf("UploadMesh: %v", err) + } + t.Cleanup(func() { _ = floor.Close() }) + + pipe := clusterTestBuildPipeline(t, nil, dev, camBuf.Layout(), sys, gpu.FormatDepth24Plus) + t.Cleanup(func() { _ = pipe.Close() }) + + sys.UpdateCamera(dev, cam, viewW, viewH, ambient, lights) + camBuf.WriteCamera(cam) + + enc := dev.BeginEncoder() + pass := enc.BeginRenderPass(gpu.RenderPassDesc{ + ColorAttachments: []gpu.ColorAttachment{{LoadOp: gpu.LoadClear, StoreOp: gpu.StoreStore, ClearColor: core.RGB(0x000000)}}, + DepthStencil: &gpu.DepthStencilAttachment{DepthLoadOp: gpu.LoadClear, DepthStoreOp: gpu.StoreDiscard, ClearDepth: 1}, + }) + pass.SetPipeline(pipe) + pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) + sys.Bind(pass, render3d.ClusteredLightGroup) + floor.Draw(pass) + pass.End() + dev.Submit(enc.Finish()) + sr.WaitIdle() + if err := sr.LastError(); err != nil { + t.Fatalf("software renderer: %v", err) + } + + img := sr.Image() + white := math3d.Vec3{X: 1, Y: 1, Z: 1} + up := math3d.Vec3Up() + + // Project key world points to pixel coordinates and verify exact shading. + checks := []struct { + name string + world math3d.Vec3 + }{ + {"under-red-point", math3d.Vec3{X: -3, Y: 0, Z: 0}}, + {"under-green-spot-center", math3d.Vec3{X: 3, Y: 0, Z: 0}}, + {"green-spot-penumbra", math3d.Vec3{X: 3 + 1.05, Y: 0, Z: 0}}, + {"outside-green-spot-cone", math3d.Vec3{X: 3 + 2.5, Y: 0, Z: 0}}, + {"under-upward-blue-spot", math3d.Vec3{X: 0, Y: 0, Z: 0}}, + } + for _, ch := range checks { + scr, _, vis := cam.WorldToScreen(ch.world, viewW, viewH) + if !vis { + t.Fatalf("%s not visible on screen", ch.name) + } + px, py := int(scr.X), int(scr.Y) + exactWorld, ok := clusterTestWorldPointAtPixel(cam, float32(px), float32(py), viewW, viewH) + if !ok { + t.Fatalf("%s failed raycast", ch.name) + } + want := clusterTestVec3ToRGBA(render3d.EvaluateDirectLights(exactWorld, up, white, ambient, lights)) + clusterTestAssertPixelNear(t, img, px, py, want, 3, ch.name) + + // Sanity checks on expected visual contrast. + switch ch.name { + case "under-red-point": + if want.R < 150 || want.G > 40 { + t.Fatalf("expected bright red under point light, got %+v", want) + } + case "under-green-spot-center": + if want.G < 150 || want.R > 40 { + t.Fatalf("expected bright green under spot light, got %+v", want) + } + case "under-upward-blue-spot": + if want.B > 30 { + t.Fatalf("upward spotlight should not light floor, got %+v", want) + } + } + } +} + +func TestClusteredFallbackNoGPUComputeAndForceFallback(t *testing.T) { + const ( + viewW = 64 + viewH = 64 + near = float32(0.5) + far = float32(60.0) + ) + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 14, Z: 18}, math3d.DegToRad(50), 1, near, far) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + ambient := math3d.Vec3{X: 0.03, Y: 0.03, Z: 0.04} + // Start with 256 point lights across the floor plus bright foreground lights near the center so both clustered and fallback modes visibly illuminate the sampled pixels. + lights := clusterTest256PointLights() + lights[0] = render3d.NewPointClusterLight(math3d.Vec3{X: 0, Y: 1.5, Z: 0}, math3d.Vec3{X: 1, Y: 0.3, Z: 0.2}, 6.0, 6.0) + lights[1] = render3d.NewPointClusterLight(math3d.Vec3{X: -3, Y: 1.5, Z: 1}, math3d.Vec3{X: 0.2, Y: 1, Z: 0.3}, 6.0, 6.0) + lights[2] = render3d.NewPointClusterLight(math3d.Vec3{X: 3, Y: 1.5, Z: 1}, math3d.Vec3{X: 0.2, Y: 0.4, Z: 1}, 6.0, 6.0) + + modes := []struct { + name string + cfg render3d.ClusterConfig + appOpts []nsgotest.Option + wantCluster bool + wantCaps bool + }{ + { + name: "full-clustered", + cfg: render3d.DefaultClusterConfig(), + appOpts: nil, + wantCluster: true, + wantCaps: true, + }, + { + name: "webgl2-gles3-no-compute-fallback", + cfg: render3d.DefaultClusterConfig(), + appOpts: []nsgotest.Option{nsgotest.NoGPUCompute()}, + wantCluster: false, + wantCaps: false, + }, + { + name: "force-fallback-on-full-device", + cfg: render3d.ClusterConfig{ + ForceFallback: true, + FallbackMaxLights: 8, + }, + appOpts: nil, + wantCluster: false, + wantCaps: true, + }, + } + + for _, m := range modes { + t.Run(m.name, func(t *testing.T) { + var ( + camBuf *render3d.CameraBuffer + sys *render3d.ClusteredLightSystem + floor *render3d.GPUMesh + pipe *gpu.Pipeline + gotCaps bool + gotStats render3d.ClusterStats + ) + opts := append([]nsgotest.Option{nsgotest.Size(viewW, viewH), nsgotest.ManualFrames()}, m.appOpts...) + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return gpu.View(cx, gpu.ViewProps{ + TestID: "cluster-view", + Style: core.Style{Width: core.Pt(viewW), Height: core.Pt(viewH)}, + DepthFormat: gpu.FormatDepth24Plus, + OnReady: func(dev *gpu.Device) { + gotCaps = render3d.DeviceSupportsClusteredLighting(dev) + var err error + camBuf, err = render3d.NewCameraBuffer(cx, dev) + if err != nil { + t.Fatalf("NewCameraBuffer: %v", err) + } + sys, err = render3d.NewClusteredLightSystem(cx, dev, m.cfg) + if err != nil { + t.Fatalf("NewClusteredLightSystem: %v", err) + } + floor, err = render3d.UploadMesh(cx, dev, clusterTestFloorMesh(20), render3d.MeshUpload{}) + if err != nil { + t.Fatalf("UploadMesh: %v", err) + } + pipe = clusterTestBuildPipeline(t, cx, dev, camBuf.Layout(), sys, gpu.FormatDepth24Plus) + }, + OnFrame: func(frame *gpu.Frame) { + dev := frame.Device() + camBuf.WriteCamera(cam) + gotStats = sys.UpdateCamera(dev, cam, viewW, viewH, ambient, lights) + pass := frame.BeginRenderPass(gpu.RenderPassDesc{}) + pass.ClearColor(core.RGB(0x050608)) + pass.ClearDepth(1) + pass.SetPipeline(pipe) + pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) + sys.Bind(pass, render3d.ClusteredLightGroup) + floor.Draw(pass) + pass.End() + frame.Submit() + }, + }) + }, opts...) + + app.Advance(16 * time.Millisecond) + + if gotCaps != m.wantCaps { + t.Fatalf("DeviceSupportsClusteredLighting = %v, want %v", gotCaps, m.wantCaps) + } + if sys.IsClustered() != m.wantCluster || sys.IsFallback() == m.wantCluster { + t.Fatalf("mode mismatch: IsClustered=%v IsFallback=%v, wantCluster=%v", sys.IsClustered(), sys.IsFallback(), m.wantCluster) + } + + img, err := app.GPUReadPixels("id:cluster-view") + if err != nil { + t.Fatalf("GPUReadPixels: %v", err) + } + + white := math3d.Vec3{X: 1, Y: 1, Z: 1} + up := math3d.Vec3Up() + refLights := lights + if sys.IsFallback() { + wantCap := m.cfg.FallbackMaxLights + if wantCap == 0 { + wantCap = render3d.DefaultFallbackMaxLights + } + refLights = sys.FallbackLights() + if len(refLights) != wantCap { + t.Fatalf("fallback selected %d lights, want %d (stats=%+v)", len(refLights), wantCap, gotStats) + } + if gotStats.TruncatedLights != 256-wantCap { + t.Fatalf("TruncatedLights = %d, want %d", gotStats.TruncatedLights, 256-wantCap) + } + } + + // Verify pixel parity against analytic reference for active light set and confirm non-trivial lighting. + litCount := 0 + for _, pt := range [][2]int{{22, 32}, {32, 32}, {42, 32}, {32, 42}} { + worldPt, ok := clusterTestWorldPointAtPixel(cam, float32(pt[0]), float32(pt[1]), viewW, viewH) + if !ok { + continue + } + want := clusterTestVec3ToRGBA(render3d.EvaluateDirectLights(worldPt, up, white, ambient, refLights)) + clusterTestAssertPixelNear(t, img, pt[0], pt[1], want, 3, m.name) + if want.R > 40 || want.G > 40 || want.B > 40 { + litCount++ + } + } + if litCount == 0 { + t.Fatalf("%s: expected visibly lit pixels above ambient/clear", m.name) + } + }) + } +} + +func TestClusteredEmptyLightsResizeRetainedAndClose(t *testing.T) { + // 1. Nil device error & nil receiver safety. + if _, err := render3d.NewClusteredLightSystem(nil, nil, render3d.DefaultClusterConfig()); err == nil { + t.Fatal("expected error for nil device") + } + var nilSys *render3d.ClusteredLightSystem + if nilSys.Valid() || nilSys.IsClustered() || nilSys.IsFallback() || nilSys.ByteSize() != 0 { + t.Fatal("nil ClusteredLightSystem returned unexpected non-zero state") + } + if err := nilSys.Close(); err != nil { + t.Fatalf("nil Close: %v", err) + } + + // 2. Empty lights + viewport resize + Retained device-loss recovery on both full and NoGPUCompute profiles. + profiles := []struct { + name string + opts []nsgotest.Option + }{ + {"full", nil}, + {"webgl2-gles3", []nsgotest.Option{nsgotest.NoGPUCompute()}}, + } + for _, prof := range profiles { + t.Run(prof.name, func(t *testing.T) { + const size = 48 + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 6, Z: 6}, math3d.DegToRad(50), 1, 0.5, 40) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + ambient := math3d.Vec3{X: 0.2, Y: 0.3, Z: 0.4} + activeLights := []render3d.ClusterLight{} // start empty, then populate + + var ( + camBuf *render3d.CameraBuffer + sys *render3d.ClusteredLightSystem + floor *render3d.GPUMesh + pipe *gpu.Pipeline + ) + opts := append([]nsgotest.Option{nsgotest.Size(size, size), nsgotest.ManualFrames()}, prof.opts...) + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return gpu.View(cx, gpu.ViewProps{ + TestID: "ret-view", + Style: core.Style{Width: core.Pt(size), Height: core.Pt(size)}, + DepthFormat: gpu.FormatDepth24Plus, + OnReady: func(dev *gpu.Device) { + var err error + if sys == nil { + cfg := render3d.DefaultClusterConfig() + cfg.Retained = true + sys, err = render3d.NewClusteredLightSystem(cx, dev, cfg) + if err != nil { + t.Fatalf("NewClusteredLightSystem: %v", err) + } + floor, err = render3d.UploadMesh(cx, dev, clusterTestFloorMesh(10), render3d.MeshUpload{Retained: true}) + if err != nil { + t.Fatalf("UploadMesh: %v", err) + } + } + camBuf, err = render3d.NewCameraBuffer(cx, dev) + if err != nil { + t.Fatalf("NewCameraBuffer: %v", err) + } + pipe = clusterTestBuildPipeline(t, cx, dev, camBuf.Layout(), sys, gpu.FormatDepth24Plus) + }, + OnFrame: func(frame *gpu.Frame) { + dev := frame.Device() + w, h := dev.SurfaceSize() + cam.SetViewport(float32(w), float32(h)) + camBuf.WriteCamera(cam) + sys.UpdateCamera(dev, cam, float32(w), float32(h), ambient, activeLights) + pass := frame.BeginRenderPass(gpu.RenderPassDesc{}) + pass.ClearColor(core.RGB(0x000000)) + pass.ClearDepth(1) + pass.SetPipeline(pipe) + pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) + sys.Bind(pass, render3d.ClusteredLightGroup) + floor.Draw(pass) + pass.End() + frame.Submit() + }, + }) + }, opts...) + + // Frame 1: 0 lights -> pure ambient color. + app.Advance(16 * time.Millisecond) + img, err := app.GPUReadPixels("id:ret-view") + if err != nil { + t.Fatalf("GPUReadPixels empty: %v", err) + } + clusterTestAssertPixelNear(t, img, size/2, size/2, clusterTestVec3ToRGBA(ambient), 3, "empty-ambient") + + // Frame 2: add bright yellow light at origin. + activeLights = []render3d.ClusterLight{ + render3d.NewPointClusterLight(math3d.Vec3{Y: 1.5}, math3d.Vec3{X: 1, Y: 0.9, Z: 0.1}, 4.0, 6.0), + } + app.Advance(16 * time.Millisecond) + beforeLoss, err := app.GPUReadPixels("id:ret-view") + if err != nil { + t.Fatalf("GPUReadPixels before loss: %v", err) + } + centerBefore := beforeLoss.RGBAAt(size/2, size/2) + if centerBefore.R < 150 || centerBefore.G < 150 { + t.Fatalf("expected bright yellow center before loss, got %+v", centerBefore) + } + + // Trigger device loss and restore: retained ClusteredLightSystem must recover cleanly. + firstSys := sys + app.TriggerGPUDeviceLost("id:ret-view", nsgotest.GPULostContextLost, "context lost") + if firstSys.Valid() { + t.Fatal("ClusteredLightSystem still Valid while device is lost") + } + app.RestoreGPUDevice("id:ret-view") + if sys != firstSys || !firstSys.Valid() { + t.Fatalf("retained ClusteredLightSystem not restored: same=%v valid=%v", sys == firstSys, firstSys.Valid()) + } + + app.Advance(16 * time.Millisecond) + afterRestore, err := app.GPUReadPixels("id:ret-view") + if err != nil { + t.Fatalf("GPUReadPixels after restore: %v", err) + } + clusterTestAssertPixelNear(t, afterRestore, size/2, size/2, centerBefore, 2, "after-restore") + + // Close is idempotent. + if err := sys.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + if sys.Valid() { + t.Fatal("ClusteredLightSystem still Valid after Close") + } + if err := sys.Close(); err != nil { + t.Fatalf("second Close: %v", err) + } + }) + } +} + +func TestSelectFallbackLightsPrioritization(t *testing.T) { + camPos := math3d.Vec3{Z: 10} + camFwd := math3d.Vec3Forward() // (0, 0, -1) + lights := []render3d.ClusterLight{ + render3d.NewPointClusterLight(math3d.Vec3{Z: 20}, math3d.Vec3{X: 1}, 2, 3), // behind camera + render3d.NewPointClusterLight(math3d.Vec3{Z: 5}, math3d.Vec3{Y: 1}, 5, 6), // closest & bright in front + render3d.NewPointClusterLight(math3d.Vec3{Z: -30}, math3d.Vec3{Z: 1}, 1, 3), // far in front + render3d.NewPointClusterLight(math3d.Vec3{Z: 4}, math3d.Vec3{X: 1}, 0, 5), // inactive (zero intensity) + render3d.NewPointClusterLight(math3d.Vec3{Z: 6}, math3d.Vec3{X: 1}, 3, 6), // second best in front + } + picked := render3d.SelectFallbackLights(nil, camPos, camFwd, lights, 2) + if len(picked) != 2 { + t.Fatalf("picked %d lights, want 2", len(picked)) + } + // Light index 1 (Z=5, intensity=5, green) and index 4 (Z=6, intensity=3, red) must be the top two. + if picked[0].Position.Z != 5 && picked[1].Position.Z != 5 { + t.Fatalf("expected closest bright front light (Z=5) in top 2, got %+v", picked) + } + if picked[0].Position.Z != 6 && picked[1].Position.Z != 6 { + t.Fatalf("expected second front light (Z=6) in top 2, got %+v", picked) + } +} + +func BenchmarkClusterAssign256Lights(b *testing.B) { + grid, err := render3d.NewClusterGrid(render3d.DefaultClusterConfig()) + if err != nil { + b.Fatalf("NewClusterGrid: %v", err) + } + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 14, Z: 18}, math3d.DegToRad(50), 16.0/9.0, 0.5, 60) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + view := cam.ViewMatrix() + proj := cam.ProjMatrix() + lights := clusterTest256PointLights() + + // Warm up frustum cache and scratch capacity. + grid.AssignLights(view, proj, 0.5, 60, lights) + + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + grid.AssignLights(view, proj, 0.5, 60, lights) + } +} + +func BenchmarkClusterFallbackSelect256Lights(b *testing.B) { + camPos := math3d.Vec3{X: 0, Y: 14, Z: 18} + camFwd := math3d.Vec3{X: 0, Y: -14, Z: -18}.Norm() + lights := clusterTest256PointLights() + dst := make([]render3d.ClusterLight, 0, render3d.DefaultFallbackMaxLights) + + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + dst = render3d.SelectFallbackLights(dst, camPos, camFwd, lights, render3d.DefaultFallbackMaxLights) + } +} From 6d02dabcd840084fef539ec1eebe0b69985bab45 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 03:36:08 +0900 Subject: [PATCH 2/2] refactor(render3d): build clustered lighting on the LightRig group and PBR shading ClusteredLightSystem now owns the whole LightGroup bind group: the LightRig uniform LightWGSL reads stays at binding 0, and the cluster parameters or fallback lights and the storage buffers move to bindings 1 to 4, so clustered local lights combine with the rig's ambient, directional, point and spot lights in one shader. ClusteredLightGroup is gone and Bind(pass) matches GPULightBuffer.Bind. shade_pbr_clustered replaces the Lambert-only evaluate_clustered_lights: it adds each clustered light to shade_pbr through pbr_brdf, point_light_attenuation and spot_cone_attenuation, and ClusteredLitWGSL / ClusteredFallbackWGSL are LitPBRWGSL with it, writing linear_to_srgb. NewClusteredLitPBRPipeline builds them. On the CPU, EvaluateLightAttenuation reuses PointLightAttenuation and SpotConeAttenuation, and ShadeClusteredPoint / ShadeClusteredGridPoint replace EvaluateDirectLights / EvaluateClusteredLights. ClusterLightFromPoint and ClusterLightFromSpot convert the existing light types and derive a cutoff range for Range 0, and Update returns an error for an invalid light or rig instead of dropping it. SelectFallbackLights frustum-culls before ranking and sorts with slices.SortFunc so the fallback path allocates nothing; fallback stats count culled and truncated lights separately. Validate bounds MaxLights, MaxLightsPerCluster and the index slots, and a storage buffer above the device's binding limit is an error instead of a silent clamp. Tests cover truncation, the converters, invalid input and fallback allocations, and the wall-clock assertion moved out of the unit test. Docs, the changelog fragment and the design note describe the new design, link it from the LightRig section, and say to pass ScaledSize() under dynamic resolution. --- .../2026-11-24-render3d-clustered-forward.md | 47 +- changelog.d/render3d-clustered-forward-382.md | 2 +- docs/en/render3d.md | 48 +- docs/zh/render3d.md | 50 +- packages/game/render3d/clustered.go | 869 ++++++++---------- packages/game/render3d/clustered_test.go | 605 ++++++------ 6 files changed, 807 insertions(+), 814 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-11-24-render3d-clustered-forward.md b/.agents/notes/implemented/feature/2026-11-24-render3d-clustered-forward.md index c72f6906..8bb704c3 100644 --- a/.agents/notes/implemented/feature/2026-11-24-render3d-clustered-forward.md +++ b/.agents/notes/implemented/feature/2026-11-24-render3d-clustered-forward.md @@ -4,38 +4,51 @@ Status: implemented ## Problem -`render3d` needs to render scenes with hundreds of local point and spot lights (256+ lights within a 60 fps desktop frame budget) without switching away from forward rendering or breaking mobile and browser targets (WebGL 2 / OpenGL ES 3.0) that lack compute shaders and storage buffers (`Features.Compute == false`, `Features.StorageBuffers == false`, simulated in tests via `nsgotest.NoGPUCompute`). +`render3d` needs to render scenes with hundreds of local point and spot lights without leaving forward rendering, and without breaking mobile and browser targets (WebGL 2 / OpenGL ES 3.0) that lack compute shaders and storage buffers (`Features.Compute == false`, `Features.StorageBuffers == false`, simulated in tests via `nsgotest.NoGPUCompute`). -Three NSGo-specific constraints shape the design: -- NSGo v0.3.0's software GPU VM (used by headless `nsgotest` and `gpu.NewSoftwareRenderer`) omits `shaderir.Log2`, `shaderir.Exp`, and `shaderir.Exp2`, so the textbook `floor(log2(z / near) * scale)` depth-slice formula in WGSL would fail in software GPU tests. -- WebGL 2 and OpenGL ES 3.0 disallow `UsageStorage` buffers and `BindingStorageRead` bind-group entries; any light system targeting all NSGo backends must automatically drop to a pure uniform-buffer path when `DeviceSupportsClusteredLighting(dev)` is false. -- Retained GPU resources survive device loss and restore by retargeting buffers to the restored device; holding a stale `*gpu.Device` inside the light system breaks updates after `RestoreGPUDevice`. +The scene lighting model already exists: `light.go` defines `LightRig` (ambient, up to 4 directional, 16 point and 8 spot lights) at `LightGroup` binding 0, the Cook-Torrance `pbr_brdf`, `point_light_attenuation`, `spot_cone_attenuation`, `shade_pbr`, and `LitPBRWGSL` with sRGB output. Clustered lights must combine with that rig in one shader and look identical to rig lights, not introduce a second shading model or a second binding at `@group(1) @binding(0)`. + +Constraints: + +- NSGo v0.3.0's software GPU VM (headless `nsgotest`, `gpu.NewSoftwareRenderer`) has no case for `log`, `log2`, `exp` or `exp2` in `evalCall` (`internal/driver/gpu_software.go`) and silently returns zero, so the textbook `floor(log2(z / near) * scale)` slice formula would shade every fragment from slice 0 in software tests. Upstream main still lacks them. +- WebGL 2 and OpenGL ES 3.0 disallow storage buffers, so the system must fall back to uniform buffers when `DeviceSupportsClusteredLighting(dev)` is false. +- Retained GPU resources survive device loss by retargeting buffers; holding a stale `*gpu.Device` breaks updates after `RestoreGPUDevice`. ## Decision -`packages/game/render3d/clustered.go` implements a dual-path clustered forward lighting system (`ClusterGrid`, `ClusteredLightSystem`, `ClusterLight`, `ClusterConfig`) alongside pure-Go analytic evaluators (`EvaluateLightAttenuation`, `EvaluateDirectLights`, `EvaluateClusteredLights`): +`packages/game/render3d/clustered.go` makes `ClusteredLightSystem` own the whole `LightGroup` bind group: -- **Zero-allocation CPU frustum clustering (`ClusterGrid`)**: Partitions view space into `TilesX × TilesY × SlicesZ` (default `16 × 9 × 24 = 3,456` clusters) using logarithmic depth splits `z_i = near * (far/near)^(i/SlicesZ)` for perspective projections (and linear splits for orthographic). Cluster view-space AABBs are cached by `(proj, near, far)` and reused across camera translation/rotation. `AssignLights` culls off-frustum lights, computes conservative screen-tile and Z-slice bounds (clamping near-plane-straddling lights to the full tile span so there are zero false negatives), runs exact sphere-vs-AABB plus Bart Wronski tight bounding-sphere + cone-vs-AABB rejection for `ClusterLightSpot`, and packs contiguous `ClusterOffsetCount` + `LightIndices` slices with 0 heap allocations in steady state. -- **Portable binary-search depth slicing in WGSL**: `ClusteredBindingsWGSL` passes up to `MaxClusterSlicesZ + 1` (65) slice boundaries in a fixed 17 × `vec4` uniform array (`ClusterParams.slice_depths`) and computes `slice_z` with a fixed 6-step binary search (`cluster_find_slice`) over `view_z = -(camera.view * vec4(world_pos, 1.0)).z`. This avoids `log2`/`exp`, avoids dynamic vector indexing, and works identically across Metal, Direct3D 11, OpenGL 3.3, WebGPU, and NSGo's software GPU VM. -- **Automatic capability-gated fallback (`ClusteredLightSystem`)**: `NewClusteredLightSystem` inspects `DeviceSupportsClusteredLighting(dev)` (requiring `Features.StorageBuffers`, `Features.Compute`, and `MaxStorageBufferBindingSize >= 64 KiB`, unless `ForceFallback` is set). On capable devices it binds 1 uniform buffer (`ClusterParams`, 320 bytes) + 3 read-only storage buffers (`cluster_lights`, `cluster_cells`, `cluster_indices`) at `@group(1)` (`ClusteredLightGroup = 1`), all 16-byte aligned (`vec4` / `vec4`). On WebGL 2 / OpenGL ES 3.0 / `nsgotest.NoGPUCompute` devices it allocates a single 1,056-byte uniform buffer (`FallbackLightUniform`) holding up to `FallbackMaxLights` (default/max `16`) lights prioritized per frame by `SelectFallbackLights`. -- **Shared WGSL evaluation signature**: Both `ClusteredBindingsWGSL` and `ClusteredFallbackBindingsWGSL` expose `evaluate_clustered_lights(world_pos, normal, frag_pos) -> vec3` with glTF `KHR_lights_punctual` smooth range and spotlight attenuation, so both the built-in shaders (`ClusteredLitWGSL`, `ClusteredFallbackWGSL`) and user material shaders share one fragment body across desktop and mobile paths. -- **Explicit `*gpu.Device` on `Update`/`UpdateCamera`**: Matching `GPUTexture` and `GPUMorphMesh`, `ClusteredLightSystem` never caches a `*gpu.Device` pointer, allowing `ClusterConfig.Retained` buffers to recover and resume updating cleanly across GPU device loss and restore. +- **One light group, one shading model**: binding 0 is the `LightRig` uniform `LightWGSL` declares, encoded with `packLightUniforms` / `LightUniforms.Encode`; binding 1 is the cluster parameters (clustered) or the fallback light array (fallback); bindings 2 to 4 are the light, cell and index storage buffers. `ClusteredBindingsWGSL` and `ClusteredFallbackBindingsWGSL` are `LightWGSL` plus those bindings and `shade_pbr_clustered`, which returns `shade_pbr` plus each local light through `pbr_brdf`, `point_light_attenuation` and `spot_cone_attenuation`. `ClusteredLitWGSL` / `ClusteredFallbackWGSL` are `LitPBRWGSL` with `shade_pbr_clustered`, writing `linear_to_srgb`, and `NewClusteredLitPBRPipeline` builds them with `newLitPBRPipeline`. `Bind(pass)` matches `GPULightBuffer.Bind`. +- **Lights from the existing types**: `ClusterLight` stays as the packed record the grid bins, but `ClusterLightFromPoint` / `ClusterLightFromSpot` build it from `PointLight` / `SpotLight`, and `EvaluateLightAttenuation` reuses `PointLightAttenuation` and `SpotConeAttenuation` (with the same `minSpotConeCosDelta`). Clustering needs a bounding sphere, so `Range` must be positive: the converters derive one for `Range == 0` (where `Intensity * max(Color) / d^2` falls to `ClusterRangeCutoff`, 1/256), and `Update` returns an error for an invalid light instead of dropping it. +- **Zero-allocation CPU clustering (`ClusterGrid`)**: logarithmic depth splits for perspective, linear for orthographic, cluster AABBs cached by `(proj, near, far)`, conservative tile and slice bounds, sphere-vs-AABB plus cone rejection for spot lights, and packed offsets and indices with no steady-state allocations. Overflow past `MaxLights` or `MaxLightsPerCluster` drops lights in input order and is reported in the stats. +- **Binary-search depth slicing in WGSL**: up to 65 slice boundaries in a 17 × `vec4` uniform table and a fixed 6-step binary search, instead of `log2` / `exp`. +- **Fallback selection**: `SelectFallbackLights` frustum-culls light bounding spheres before ranking, so off-screen lights never take one of the 16 uniform slots, and sorts with `slices.SortFunc` so the per-frame path allocates nothing. +- **Bounded sizes**: `Validate` caps `MaxLights` (65,536), `MaxLightsPerCluster <= MaxLights`, and index slots (`MaxClusterIndexEntries`); `NewClusteredLightSystem` refuses a storage buffer larger than the device's binding limit instead of clamping it. +- **Explicit `*gpu.Device` on `Update` / `UpdateCamera`**, as `GPUTexture` and `GPUMorphMesh` do. ## Alternatives considered +### Clustered bindings next to a separate `GPULightBuffer` + +Keeping `GPULightBuffer` at group 1 and putting the cluster buffers in another group would avoid touching the rig upload, but group 2 is `PBRDrawGroup` and group 3 is a custom material's extra layout, so the clustered pass would need a fourth group that WebGL 2 pipelines with materials cannot spare. One bind group with the rig at binding 0 keeps `LightWGSL` unchanged and fits every existing pipeline layout. + +### A Lambert-only clustered shader + +The first version shaded clustered lights with `color * intensity * atten * ndotl` and wrote linear color. It was simpler, but a scene mixing it with `LitPBRWGSL` would be darker and inconsistent, and it duplicated the attenuation math. Reusing `pbr_brdf` costs a few more ALU operations per light and keeps one shading model. + ### Compute-shader light assignment on the GPU -Assigning lights to clusters in a WGSL compute pass avoids uploading per-frame cell and index buffers from the CPU. However, NSGo's software GPU device runs compute workgroups sequentially on the CPU (making 3,456 × 256 invocations far slower in headless tests), requires atomic append counters in WGSL (`atomicAdd`) across all native backends, and still needs a CPU path for capability-limited targets. CPU `ClusterGrid.AssignLights` handles 256 point lights in well under 1 ms with 0 heap allocations, keeps buffer sizes deterministic (~884 KiB max index buffer), and lets headless tests and servers share the exact same culling logic. +Assigning lights in a compute pass avoids uploading cell and index buffers, but the software GPU runs compute workgroups sequentially, native backends need atomic append counters, and capability-limited targets still need a CPU path. `ClusterGrid.AssignLights` handles 256 lights with no allocations (`BenchmarkClusterAssign256Lights`). ### `log2(view_z / near)` slice indexing in WGSL -Computing `u32(log2(view_z / near) * inv_log_ratio)` saves 272 bytes in `ClusterParams`. It was rejected because NSGo v0.3.0's software GPU VM does not implement `shaderir.Log2`, which would break headless GPU parity tests, and because a uniform split-depth table also supports orthographic linear slicing and custom depth distributions with zero shader changes. +It would save 272 bytes of uniforms, but NSGo's software VM evaluates `log2` to zero, and a split table also covers orthographic slicing. -### Packing clustered light lists into a 2D RGBA32UI texture for WebGL 2 +### Packing light lists into textures for WebGL 2 -Emulating storage buffers via `textureLoad` on floating-point/integer textures could allow clustering on WebGL 2 without storage buffers, at the cost of requiring `Features.ExtendedFormats` (`FormatRGBA32Float` / integer texture formats) and much higher fragment-shader texture-fetch pressure on mobile tile GPUs. A prioritized 16-light uniform-buffer fallback (`SelectFallbackLights`) uses only core WebGL 2 / GLES 3.0 uniform buffers and stays comfortably within mobile fragment budgets. +Emulating storage buffers with integer textures needs `Features.ExtendedFormats` and costs texture fetches per light on mobile tile GPUs. A 16-light uniform fallback uses only core WebGL 2 / GLES 3.0 features. ## Consequences -- **Benefits**: Desktop GPU targets render 256+ local point and spot lights with zero steady-state CPU allocations, exact CPU-vs-GPU pixel parity (verified by `TestClustered256PointLightsParityAndBudget` and `TestClusteredMixedPointAndSpotLightsGPU`), and automatic seamless fallback on `nsgotest.NoGPUCompute` (WebGL 2 / GLES 3.0) with `Retained` device-loss recovery. Keeping all code in standalone `clustered.go` / `clustered_test.go` avoids merge conflicts with parallel `render3d` work. -- **Costs**: Cluster assignment runs on the CPU and uploads `cells` and `indices` buffers each frame via `Device.WriteBuffer` (scaling linearly with active cluster assignments, capped by `MaxLightsPerCluster` and `MaxStorageBufferBindingSize`). Depth slice count is capped at `MaxClusterSlicesZ = 64` to fit the fixed 17 × `vec4` uniform split table, and `FallbackMaxLights` is capped at `16` to stay compact inside WebGL 2 / GLES 3.0 uniform buffers. +- **Benefits**: clustered and rig lights share one BRDF, one attenuation curve and one sRGB output; GPU pixels match `ShadeClusteredPoint` / `ShadeClusteredGridPoint` on the full and `NoGPUCompute` profiles, including a 256-light scene; glTF lights with no range work through the converters. +- **Costs**: cluster assignment runs on the CPU and uploads cell and index buffers each frame. The shader-side cost of 256 lights at desktop resolution on native GPUs has not been measured here; only the software renderer and the CPU benchmark run in CI. Depth slices are capped at 64 and fallback lights at 16. The tile lookup assumes the viewport starts at the attachment origin, so callers pass `DynamicResolutionTarget.ScaledSize()` under dynamic resolution. diff --git a/changelog.d/render3d-clustered-forward-382.md b/changelog.d/render3d-clustered-forward-382.md index 99d3ea97..250b6662 100644 --- a/changelog.d/render3d-clustered-forward-382.md +++ b/changelog.d/render3d-clustered-forward-382.md @@ -1,3 +1,3 @@ ### Added -- `game/render3d`: clustered forward shading (`ClusterGrid`, `ClusteredLightSystem`, `ClusterLight`, `ClusterConfig`, `SelectFallbackLights`, `ClusteredLitWGSL`, `ClusteredFallbackWGSL`) supporting hundreds of point and spot lights on desktop storage-buffer devices with automatic prioritized uniform-buffer fallback on WebGL 2 / OpenGL ES 3.0 targets without compute or storage buffers (#382). +- `game/render3d`: clustered forward shading for hundreds of point and spot lights. `ClusteredLightSystem` takes a `GPULightBuffer`'s place at `LightGroup`, uploads the same `LightRig` and adds `ClusterLight`s (`ClusterLightFromPoint`, `ClusterLightFromSpot`) binned by `ClusterGrid`, shaded with the same PBR BRDF through `NewClusteredLitPBRPipeline` / `ClusteredLitWGSL` or `shade_pbr_clustered` in custom shaders. On WebGL 2 and OpenGL ES 3.0 it falls back to the 16 most important visible lights in a uniform buffer (#382). diff --git a/docs/en/render3d.md b/docs/en/render3d.md index 130f21a3..3d93b6fd 100644 --- a/docs/en/render3d.md +++ b/docs/en/render3d.md @@ -137,6 +137,8 @@ mesh.Draw(pass) Custom 3D shaders can prepend `CameraWGSL + LightWGSL` to read `@group(1) @binding(0) var lights: LightRigUniform` and call the portable WGSL helpers `point_light_attenuation`, `spot_cone_attenuation`, `pbr_brdf`, `shade_pbr`, and `linear_to_srgb`. `LitPBRWGSL` combines them with `MeshVertexLayout` and a per-draw `PBRDrawUniform` at `PBRDrawGroup` (group 2). +For more local lights than the rig holds, bind a `ClusteredLightSystem` at `LightGroup` instead of a `GPULightBuffer`: it uploads the same rig and adds any number of clustered point and spot lights, shaded with the same BRDF ([Clustered forward lighting](#clustered-forward-lighting-clusteredlightsystem-clustergrid)). + The shading model follows glTF 2.0 metallic-roughness PBR (dielectric `F0 = 0.04`, Schlick Fresnel, Trowbridge-Reitz GGX normal distribution, height-correlated Smith-GGX visibility, energy-conserving Lambertian diffuse, perceptual roughness floored at `0.045`, and IEC 61966-2-1 linear-to-sRGB output). `EvaluatePBR`, `ShadePoint`, `PointLightAttenuation`, `SpotConeAttenuation`, and `LinearToSRGB` implement the exact same equations on the CPU; `LightRig.AppendUniformData` and `LightUniforms.Encode` pack the uniform block without allocating. Reference tests verify GPU output pixel-for-pixel against CPU `ShadePoint`, exercise both full and WebGL 2 / GLES 3.0 (`nsgotest.NoGPUCompute`) profiles plus `Retained` device loss, and compare lit scenes against `render3d/testdata/golden/lights_pbr_scene.png`, `lights_point_falloff.png` and `spot_lights_scene.png`. ## Distance and height fog (`Fog`, `GPUFogBuffer`) @@ -1180,35 +1182,39 @@ _ = stack.SetCamera(cam) ## Clustered forward lighting (`ClusteredLightSystem`, `ClusterGrid`) -`ClusterGrid` and `ClusteredLightSystem` scale local point and spot lighting to hundreds of simultaneous lights by partitioning the view frustum into a 3D screen-tile × logarithmic-depth-slice grid (default `16 × 9 × 24`, up to `512` visible lights and `64` lights per cluster), with automatic fallback to a pure uniform-buffer shader on targets without storage buffers or compute shaders (WebGL 2, OpenGL ES 3.0, and headless tests using `nsgotest.NoGPUCompute`): +A `LightRig` shades at most 16 point and 8 spot lights. For scenes with hundreds of local lights, `ClusteredLightSystem` takes the place of `GPULightBuffer` at `LightGroup`: it uploads the same `LightRig` (ambient, directional, and the rig's own point and spot lights) at binding 0, and bins any number of extra local lights (`ClusterLight`) into a 3D grid of screen tiles × logarithmic depth slices (default `16 × 9 × 24`, up to `512` visible lights and `64` per cluster). Each fragment then shades only the lights in its own cluster, with the same Cook-Torrance BRDF and glTF `KHR_lights_punctual` falloff as `shade_pbr`, so clustered and rig lights look identical. On targets without storage buffers or compute shaders (WebGL 2, OpenGL ES 3.0, and headless tests using `nsgotest.NoGPUCompute`) it falls back to one uniform buffer holding the `FallbackMaxLights` (default `16`) most important visible lights: ```go -camBuf, err := render3d.NewCameraBuffer(cx, dev) -lights, err := render3d.NewClusteredLightSystem(cx, dev, render3d.DefaultClusterConfig()) - -// Compile the shader matching the active path (ClusteredLitWGSL or ClusteredFallbackWGSL): -mod, err := gpu.CompileWGSL(lights.WGSL()) -pipe, err := dev.CreatePipeline(cx, gpu.PipelineDesc{ - Vertex: gpu.ShaderStage{Module: mod, EntryPoint: "vs_main"}, - Fragment: gpu.ShaderStage{Module: mod, EntryPoint: "fs_main"}, - Layouts: []*gpu.BindGroupLayout{render3d.CameraGroup: camBuf.Layout(), render3d.ClusteredLightGroup: lights.Layout()}, - VertexBuffers: []gpu.VertexBufferLayout{render3d.MeshVertexLayout()}, - DepthStencil: &gpu.DepthStencilState{Format: gpu.FormatDepth24Plus, DepthWrite: true, DepthCompare: gpu.CompareLess}, - Targets: []gpu.ColorTargetState{{Format: dev.SurfaceFormat(), WriteMask: gpu.ColorWriteAll}}, -}) +sys, err := render3d.NewClusteredLightSystem(cx, dev, render3d.DefaultClusterConfig()) +pipe, err := render3d.NewClusteredLitPBRPipeline(cx, dev, camBuf.Layout(), sys, drawBuf.Layout(), gpu.FormatDepth24Plus) + +// Convert scene lights once; a Range of 0 (unbounded) gets a derived cutoff range. +local := make([]render3d.ClusterLight, 0, len(lamps)) +for _, l := range lamps { + cl, err := render3d.ClusterLightFromPoint(l) + if err != nil { + return err + } + local = append(local, cl) +} // Each frame, before recording draws: camBuf.WriteCamera(cam) -stats := lights.UpdateCamera(dev, cam, viewW, viewH, ambient, sceneLights) +stats, err := sys.UpdateCamera(frame.Device(), cam, viewW, viewH, rig, local) pass.SetPipeline(pipe) pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) -lights.Bind(pass, render3d.ClusteredLightGroup) +sys.Bind(pass) +pass.SetBindGroup(render3d.PBRDrawGroup, drawBuf.BindGroup()) mesh.Draw(pass) ``` -- **Zero-allocation CPU clustering (`ClusterGrid`)**: view-space cluster AABBs are cached by `(proj, near, far)` and reused across camera motion. `AssignLights` culls off-frustum lights, computes tight screen-tile and logarithmic depth-slice bounds, tests sphere-vs-AABB (plus conservative cone-vs-AABB rejection for `ClusterLightSpot`), and packs compact `Offsets` and `LightIndices` slices with zero steady-state allocations. -- **Portable depth-slice lookup**: the clustered fragment shader (`ClusteredBindingsWGSL` / `ClusteredLitWGSL`) maps each fragment's view-space depth to its slice via a 6-step binary search over the uniform split-depth table rather than `log2`/`exp`, so it produces identical results on Metal, Direct3D 11, OpenGL 3.3, WebGPU, and NSGo's software GPU VM. -- **Automatic mobile / WebGL 2 fallback**: when `DeviceSupportsClusteredLighting(dev)` is false (or `ClusterConfig.ForceFallback` is set), `NewClusteredLightSystem` switches to a single 1,056-byte uniform buffer (`ClusteredFallbackBindingsWGSL` / `ClusteredFallbackWGSL`) and selects up to `FallbackMaxLights` (default `16`) highest-priority lights each frame via `SelectFallbackLights`. Both shader paths expose the identical `evaluate_clustered_lights(world_pos, normal, frag_pos)` WGSL helper so custom material shaders share one fragment body across desktop and mobile. -- **Attenuation & CPU reference**: point and spot lights (`NewPointClusterLight`, `NewSpotClusterLight`) use glTF `KHR_lights_punctual` smooth range and cone attenuation; `EvaluateLightAttenuation`, `EvaluateDirectLights`, and `EvaluateClusteredLights` provide pure-Go reference shading matching the WGSL math. -- **Lifecycle & device loss**: set `ClusterConfig.Retained` to restore buffers across GPU device loss automatically; `ByteSize()` reports GPU buffer bytes for `RenderStats` and budgets, and `Close()` releases resources eagerly. +- **Lights**: `ClusterLight` is a point or spot record whose `Range` must be positive, because clustering needs a bounding sphere. `ClusterLightFromPoint` and `ClusterLightFromSpot` convert a `PointLight` or `SpotLight` and, for `Range == 0`, derive the distance at which `Intensity * max(Color) / d^2` falls to `ClusterRangeCutoff` (1/256). `Update` returns an error wrapping `ErrInvalidClusterLight` for a light that fails `Validate` (including `Range == 0`) or `ErrInvalidLight` for a malformed rig, instead of dropping it. `EvaluateLightAttenuation` reuses `PointLightAttenuation` and `SpotConeAttenuation`. +- **Viewport size**: `viewW` and `viewH` must be the size of the area the pass renders, starting at its origin, because the shader finds a fragment's tile from `@builtin(position)`. Under a `DynamicResolutionTarget`, pass `ScaledSize()`, not the native size. +- **Shaders**: `NewClusteredLitPBRPipeline` compiles `ClusteredLitWGSL` or `ClusteredFallbackWGSL` (whichever matches `sys.WGSL()`), the `LitPBRWGSL` module with `shade_pbr_clustered` in place of `shade_pbr`, writing sRGB. Custom shaders prepend `CameraWGSL` and `sys.BindingsWGSL()` (`ClusteredBindingsWGSL` or `ClusteredFallbackBindingsWGSL`, both of which include `LightWGSL`) and call `shade_pbr_clustered(world_pos, normal, view_dir, base_color, metallic, roughness, frag_pos)`, which has the same signature on both paths. +- **CPU clustering (`ClusterGrid`)**: view-space cluster AABBs are cached by `(proj, near, far)` and reused across camera motion. `AssignLights` culls off-frustum lights, computes tight screen-tile and depth-slice bounds, tests sphere-vs-AABB (plus conservative cone-vs-AABB rejection for spot lights), and packs `Offsets` and `LightIndices` with zero steady-state allocations. Lights beyond `MaxLights`, and lights beyond `MaxLightsPerCluster` in one cell, are dropped in input order (`TruncatedLights`, `TruncatedClusters`), so put important lights first when a scene can exceed either cap. +- **Fallback selection**: `SelectFallbackLights` drops lights whose bounding sphere is outside the view frustum, then ranks the rest by power, range and distance to the camera. In fallback mode `CulledLights` counts lights outside the frustum or without power, and `TruncatedLights` the visible lights the cap left out. +- **Depth-slice lookup**: the shader finds a fragment's depth slice with a 6-step binary search over a uniform split-depth table rather than `log2` and `exp`, because NSGo v0.3.0's software GPU renderer evaluates those builtins to zero. +- **CPU reference**: `ShadeClusteredPoint` is `ShadePoint` plus every clustered light, and `ShadeClusteredGridPoint` uses only the lights of the fragment's cluster, exactly as the GPU does. Tests compare GPU pixels against them on the full and `NoGPUCompute` profiles, including a 256-light scene. +- **Limits**: `Validate` caps `MaxLights` at `MaxClusterLights` (65,536), keeps `MaxLightsPerCluster` at or below `MaxLights`, and caps index slots (`TilesX * TilesY * SlicesZ * MaxLightsPerCluster`) at `MaxClusterIndexEntries`; `NewClusteredLightSystem` returns `ErrInvalidClusterConfig` when a storage buffer would exceed the device's `MaxStorageBufferBindingSize`. +- **Lifecycle**: set `ClusterConfig.Retained` to restore buffers across GPU device loss; `ByteSize()` reports GPU buffer bytes for `RenderStats` and budgets, and `Close()` releases resources eagerly. diff --git a/docs/zh/render3d.md b/docs/zh/render3d.md index 990f7d61..bb620ad3 100644 --- a/docs/zh/render3d.md +++ b/docs/zh/render3d.md @@ -137,6 +137,8 @@ mesh.Draw(pass) 自定义 3D 着色器只需在开头拼接 `CameraWGSL + LightWGSL`,即可访问 `@group(1) @binding(0) var lights: LightRigUniform` 并调用可移植 WGSL 函数 `point_light_attenuation`、`spot_cone_attenuation`、`pbr_brdf`、`shade_pbr` 与 `linear_to_srgb`。`LitPBRWGSL` 将它们与 `MeshVertexLayout` 及位于 `PBRDrawGroup`(第 2 组)的逐绘制 `PBRDrawUniform` 组合为完整管线。 +如果局部光源多于 rig 的容量,请在 `LightGroup` 上绑定 `ClusteredLightSystem` 来代替 `GPULightBuffer`:它上传同一个 rig,并加入任意数量的集群点光源和聚光灯,使用同一个 BRDF 着色([集群前向光照](#集群前向光照clusteredlightsystemclustergrid))。 + 着色模型遵循 glTF 2.0 金属度-粗糙度 PBR(电介质 `F0 = 0.04`、Schlick 菲涅尔、Trowbridge-Reitz GGX 法线分布、高度相关 Smith-GGX 可见度项、能量守恒 Lambert 漫反射、感知粗糙度下限 `0.045`,以及 IEC 61966-2-1 线性到 sRGB 输出)。`EvaluatePBR`、`ShadePoint`、`PointLightAttenuation`、`SpotConeAttenuation` 与 `LinearToSRGB` 在 CPU 上实现完全一致的公式;`LightRig.AppendUniformData` 与 `LightUniforms.Encode` 零分配打包 uniform 块。测试逐像素比对 GPU 渲染结果与 CPU `ShadePoint`,覆盖完整能力与 WebGL 2 / GLES 3.0(`nsgotest.NoGPUCompute`)配置及 `Retained` 设备丢失恢复,并将光照场景与 `render3d/testdata/golden/lights_pbr_scene.png`、`lights_point_falloff.png` 和 `spot_lights_scene.png` 参考图比对。 ## 距离雾与高度雾(`Fog`、`GPUFogBuffer`) @@ -1180,35 +1182,39 @@ _ = stack.SetCamera(cam) ## 集群前向光照(`ClusteredLightSystem`、`ClusterGrid`) -`ClusterGrid` 与 `ClusteredLightSystem` 将视锥体划分为屏幕瓦片 × 对数深度切片的 3D 网格(默认 `16 × 9 × 24`,最多支持 `512` 个可见局部光源、单格最多 `64` 个光源),让数百个点光源与聚光灯保持在帧预算内;在不支持存储缓冲或计算着色器的目标(WebGL 2、OpenGL ES 3.0 及 `nsgotest.NoGPUCompute` 无头测试)上自动回退为纯 uniform 缓冲着色路径: +`LightRig` 最多着色 16 个点光源和 8 个聚光灯。对于有数百个局部光源的场景,`ClusteredLightSystem` 在 `LightGroup` 上取代 `GPULightBuffer`:它在绑定 0 上传同一个 `LightRig`(环境光、方向光以及 rig 自身的点光源和聚光灯),并把任意数量的额外局部光源(`ClusterLight`)分配到由屏幕图块 × 对数深度切片组成的三维网格中(默认 `16 × 9 × 24`,最多 `512` 个可见光源、每个集群 `64` 个)。每个片元只着色自己所在集群的光源,使用与 `shade_pbr` 相同的 Cook-Torrance BRDF 和 glTF `KHR_lights_punctual` 衰减,因此集群光源与 rig 光源的效果完全一致。在不支持存储缓冲区或计算着色器的目标上(WebGL 2、OpenGL ES 3.0,以及使用 `nsgotest.NoGPUCompute` 的无头测试),它回退为单个 uniform 缓冲区,存放 `FallbackMaxLights`(默认 `16`)个最重要的可见光源: ```go -camBuf, err := render3d.NewCameraBuffer(cx, dev) -lights, err := render3d.NewClusteredLightSystem(cx, dev, render3d.DefaultClusterConfig()) - -// 编译与当前生效路径匹配的着色器(ClusteredLitWGSL 或 ClusteredFallbackWGSL): -mod, err := gpu.CompileWGSL(lights.WGSL()) -pipe, err := dev.CreatePipeline(cx, gpu.PipelineDesc{ - Vertex: gpu.ShaderStage{Module: mod, EntryPoint: "vs_main"}, - Fragment: gpu.ShaderStage{Module: mod, EntryPoint: "fs_main"}, - Layouts: []*gpu.BindGroupLayout{render3d.CameraGroup: camBuf.Layout(), render3d.ClusteredLightGroup: lights.Layout()}, - VertexBuffers: []gpu.VertexBufferLayout{render3d.MeshVertexLayout()}, - DepthStencil: &gpu.DepthStencilState{Format: gpu.FormatDepth24Plus, DepthWrite: true, DepthCompare: gpu.CompareLess}, - Targets: []gpu.ColorTargetState{{Format: dev.SurfaceFormat(), WriteMask: gpu.ColorWriteAll}}, -}) +sys, err := render3d.NewClusteredLightSystem(cx, dev, render3d.DefaultClusterConfig()) +pipe, err := render3d.NewClusteredLitPBRPipeline(cx, dev, camBuf.Layout(), sys, drawBuf.Layout(), gpu.FormatDepth24Plus) + +// 场景光源只需转换一次;Range 为 0(无界)时会推导出截止范围。 +local := make([]render3d.ClusterLight, 0, len(lamps)) +for _, l := range lamps { + cl, err := render3d.ClusterLightFromPoint(l) + if err != nil { + return err + } + local = append(local, cl) +} -// 每帧录制绘制命令前更新相机与光源集群: +// 每帧录制绘制命令之前: camBuf.WriteCamera(cam) -stats := lights.UpdateCamera(dev, cam, viewW, viewH, ambient, sceneLights) +stats, err := sys.UpdateCamera(frame.Device(), cam, viewW, viewH, rig, local) pass.SetPipeline(pipe) pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) -lights.Bind(pass, render3d.ClusteredLightGroup) +sys.Bind(pass) +pass.SetBindGroup(render3d.PBRDrawGroup, drawBuf.BindGroup()) mesh.Draw(pass) ``` -- **稳态零分配 CPU 集群分配(`ClusterGrid`)**:视空间集群 AABB 按 `(proj, near, far)` 缓存并在相机移动/旋转时直接复用。`AssignLights` 剔除视锥外光源,计算紧凑的屏幕瓦片与对数深度切片范围,执行球体与 AABB 相交检测(聚光灯 `ClusterLightSpot` 额外执行保守圆锥-AABB 剔除),并稳态零分配地打包 `Offsets` 与 `LightIndices`。 -- **可移植的深度切片查找**:集群片元着色器(`ClusteredBindingsWGSL` / `ClusteredLitWGSL`)在 uniform 分割深度表上通过 6 步二分查找定位视空间深度切片,而非依赖 `log2`/`exp`,在 Metal、Direct3D 11、OpenGL 3.3、WebGPU 与 NSGo 软件 GPU 虚拟机上行为完全一致。 -- **移动端 / WebGL 2 自动回退**:当 `DeviceSupportsClusteredLighting(dev)` 为 false(或设置 `ClusterConfig.ForceFallback`)时,`NewClusteredLightSystem` 自动切换为单个 1,056 字节的 uniform 缓冲(`ClusteredFallbackBindingsWGSL` / `ClusteredFallbackWGSL`),每帧通过 `SelectFallbackLights` 选取优先级最高的 `FallbackMaxLights`(默认 `16`)个光源。两条路径提供完全同名的 `evaluate_clustered_lights(world_pos, normal, frag_pos)` WGSL 辅助函数,自定义材质着色器无需分叉即可同时兼容桌面端与移动端。 -- **衰减模型与纯 Go 参考**:点光源与聚光灯(`NewPointClusterLight`、`NewSpotClusterLight`)遵循 glTF `KHR_lights_punctual` 平滑距离窗口与聚光灯锥角衰减;`EvaluateLightAttenuation`、`EvaluateDirectLights` 与 `EvaluateClusteredLights` 提供与 WGSL 一致的纯 Go 参考计算。 -- **生命周期与设备丢失恢复**:开启 `ClusterConfig.Retained` 可在 GPU 设备丢失恢复后自动重建缓冲;`ByteSize()` 上报显存占用供 `RenderStats` 与预算检查使用,`Close()` 可提前释放资源。 +- **光源**:`ClusterLight` 是点光源或聚光灯记录,其 `Range` 必须为正,因为集群划分需要包围球。`ClusterLightFromPoint` 和 `ClusterLightFromSpot` 转换 `PointLight` 或 `SpotLight`;`Range == 0` 时,推导出 `Intensity * max(Color) / d^2` 降到 `ClusterRangeCutoff`(1/256)的距离。对于未通过 `Validate` 的光源(包括 `Range == 0`),`Update` 返回包装 `ErrInvalidClusterLight` 的错误;对于格式错误的 rig 返回包装 `ErrInvalidLight` 的错误,而不是丢弃它。`EvaluateLightAttenuation` 复用 `PointLightAttenuation` 和 `SpotConeAttenuation`。 +- **视口尺寸**:`viewW` 和 `viewH` 必须是该渲染通道实际渲染区域的尺寸,且区域从原点开始,因为着色器根据 `@builtin(position)` 计算片元所在的图块。使用 `DynamicResolutionTarget` 时,传入 `ScaledSize()`,而不是原生尺寸。 +- **着色器**:`NewClusteredLitPBRPipeline` 编译 `ClusteredLitWGSL` 或 `ClusteredFallbackWGSL`(与 `sys.WGSL()` 一致的那个),即把 `LitPBRWGSL` 中的 `shade_pbr` 换成 `shade_pbr_clustered` 的模块,输出 sRGB。自定义着色器在前面拼接 `CameraWGSL` 和 `sys.BindingsWGSL()`(`ClusteredBindingsWGSL` 或 `ClusteredFallbackBindingsWGSL`,两者都已包含 `LightWGSL`),并调用 `shade_pbr_clustered(world_pos, normal, view_dir, base_color, metallic, roughness, frag_pos)`,它在两条路径上签名相同。 +- **CPU 集群划分(`ClusterGrid`)**:视图空间的集群 AABB 按 `(proj, near, far)` 缓存,相机移动时复用。`AssignLights` 剔除视锥外的光源,计算紧凑的屏幕图块和深度切片范围,进行球体与 AABB 相交测试(聚光灯另加保守的圆锥与 AABB 剔除),并在稳态下零分配地打包 `Offsets` 和 `LightIndices`。超出 `MaxLights` 的光源,以及单个集群中超出 `MaxLightsPerCluster` 的光源,按输入顺序丢弃(`TruncatedLights`、`TruncatedClusters`),因此当场景可能超出任一上限时,请把重要光源放在前面。 +- **回退选择**:`SelectFallbackLights` 先丢弃包围球在视锥外的光源,再按功率、范围和到相机的距离对其余光源排序。回退模式下,`CulledLights` 统计视锥外或没有功率的光源,`TruncatedLights` 统计因上限而未被选中的可见光源。 +- **深度切片查找**:着色器在 uniform 切分深度表上做 6 步二分查找来确定片元的深度切片,而不使用 `log2` 和 `exp`,因为 NSGo v0.3.0 的软件 GPU 渲染器会把这些内置函数求值为零。 +- **CPU 参考实现**:`ShadeClusteredPoint` 是 `ShadePoint` 加上所有集群光源,`ShadeClusteredGridPoint` 只使用片元所在集群的光源,与 GPU 完全一致。测试在完整能力和 `NoGPUCompute` 配置下将 GPU 像素与它们比对,包括一个 256 光源的场景。 +- **上限**:`Validate` 将 `MaxLights` 限制在 `MaxClusterLights`(65,536)以内,要求 `MaxLightsPerCluster` 不超过 `MaxLights`,并将索引槽数(`TilesX * TilesY * SlicesZ * MaxLightsPerCluster`)限制在 `MaxClusterIndexEntries` 以内;当某个存储缓冲区超过设备的 `MaxStorageBufferBindingSize` 时,`NewClusteredLightSystem` 返回 `ErrInvalidClusterConfig`。 +- **生命周期**:设置 `ClusterConfig.Retained` 可在 GPU 设备丢失后恢复缓冲区;`ByteSize()` 报告 GPU 缓冲区字节数,供 `RenderStats` 和预算使用,`Close()` 立即释放资源。 diff --git a/packages/game/render3d/clustered.go b/packages/game/render3d/clustered.go index 79487d6e..96093013 100644 --- a/packages/game/render3d/clustered.go +++ b/packages/game/render3d/clustered.go @@ -5,7 +5,7 @@ import ( "errors" "fmt" "math" - "sort" + "slices" "github.com/nsgo-dev/game/packages/game/math3d" "github.com/nsgo-dev/game/packages/game/scene3d" @@ -33,19 +33,25 @@ const ( // MaxFallbackLights is the uniform-buffer array capacity of [ClusteredFallbackWGSL]. MaxFallbackLights = 16 - // ClusteredLightGroup is the bind group index declared by [ClusteredBindingsWGSL], [ClusteredFallbackBindingsWGSL], [ClusteredLitWGSL], and [ClusteredFallbackWGSL] (group 1, alongside [CameraGroup] at group 0). - ClusteredLightGroup = 1 + // MaxClusterLights is the largest [ClusterConfig.MaxLights] accepted. + MaxClusterLights = 1 << 16 + // MaxClusterIndexEntries bounds TilesX * TilesY * SlicesZ * MaxLightsPerCluster, the number of light-index slots [ClusterGrid] preallocates (64 MiB of uint32 indices). + MaxClusterIndexEntries = 1 << 24 // ClusterLightGPUSize is the byte size of one GPU light record (4 vec4, 16-byte aligned in both std140 and std430). ClusterLightGPUSize = 64 - // ClusterParamsUniformSize is the byte size of the clustered-path ClusterParams uniform block: grid_info (16) + viewport_depth (16) + ambient (16) + 17*vec4 slice_depths (272) = 320 bytes. - ClusterParamsUniformSize = 320 + // ClusterParamsUniformSize is the byte size of the clustered-path ClusterParams uniform block at [LightGroup] binding 1: grid_info (16) + viewport_depth (16) + 17*vec4 slice_depths (272) = 304 bytes. + ClusterParamsUniformSize = 304 // ClusterCellGPUSize is the byte size of one cluster cell offset/count entry (vec4, 16-byte aligned across all backends). ClusterCellGPUSize = 16 - // ClusteredFallbackUniformSize is the byte size of the fallback uniform block: info (16) + ambient (16) + 16*ClusterLightGPUSize (1024) = 1056 bytes. - ClusteredFallbackUniformSize = 32 + MaxFallbackLights*ClusterLightGPUSize + // ClusteredFallbackUniformSize is the byte size of the fallback uniform block at [LightGroup] binding 1: info (16) + 16*ClusterLightGPUSize (1024) = 1040 bytes. + ClusteredFallbackUniformSize = 16 + MaxFallbackLights*ClusterLightGPUSize + + // ClusterRangeCutoff is the radiance below which [ClusterLightFromPoint] and [ClusterLightFromSpot] treat a light with Range 0 (unbounded, the glTF default) as finished: the derived range is sqrt(Intensity * max(Color) / ClusterRangeCutoff). + ClusterRangeCutoff = 1.0 / 256 clusterMinStorageBindingBytes = 64 * 1024 + minClusterLightRange = 1e-3 ) // Sentinel errors returned for invalid clustered lighting configuration or light data. @@ -66,10 +72,9 @@ const ( ClusterLightSpot ClusterLightKind = 1 ) -// ClusterLight describes a local punctual light (point or spot) in world space. +// ClusterLight is the record [ClusterGrid] bins and [ClusteredLightSystem] uploads for one local point or spot light in world space. Build it from a [PointLight] or [SpotLight] with [ClusterLightFromPoint] or [ClusterLightFromSpot], or directly with [NewPointClusterLight] and [NewSpotClusterLight]. // -// Range attenuation follows glTF KHR_lights_punctual: clamp(1 - (d/Range)^4, 0, 1)^2 / max(d^2, 1e-4). -// Spot lights additionally multiply by clamp(dot(dir, lightToPoint)*spotScale + spotOffset, 0, 1)^2. +// Distance falloff is [PointLightAttenuation] with Range, and spot lights also multiply by [SpotConeAttenuation], so a light shades exactly as the [PointLight] or [SpotLight] it came from. Unlike those, Range must be positive: clustering needs a bounding sphere, so a light with Range 0 (unbounded) is refused by [ClusterLight.Validate] and [ClusteredLightSystem.Update]; the converters derive a range for it from [ClusterRangeCutoff]. type ClusterLight struct { Kind ClusterLightKind Position math3d.Vec3 @@ -83,6 +88,41 @@ type ClusterLight struct { OuterConeCos float32 } +// ClusterLightFromPoint validates l and converts it to a [ClusterLightPoint]. When l.Range is 0 (unbounded), the range is derived as sqrt(Intensity * max(Color) / [ClusterRangeCutoff]), where the light's unwindowed radiance falls to the cutoff; the windowed falloff then reaches exactly zero there instead of trailing off forever. Errors wrap [ErrInvalidLight]. +func ClusterLightFromPoint(l PointLight) (ClusterLight, error) { + if err := l.Validate(); err != nil { + return ClusterLight{}, err + } + return NewPointClusterLight(l.Position, l.Color, l.Intensity, clusterRange(l.Range, l.Color, l.Intensity)), nil +} + +// ClusterLightFromSpot validates l and converts it to a [ClusterLightSpot] with the same cone, deriving a range for Range 0 as [ClusterLightFromPoint] does. Errors wrap [ErrInvalidLight]. +func ClusterLightFromSpot(l SpotLight) (ClusterLight, error) { + if err := l.Validate(); err != nil { + return ClusterLight{}, err + } + dir, _ := spotUnitDirection(l) + return ClusterLight{ + Kind: ClusterLightSpot, + Position: l.Position, + Range: clusterRange(l.Range, l.Color, l.Intensity), + Color: l.Color, + Intensity: l.Intensity, + Direction: dir, + InnerConeCos: float32(math.Cos(float64(l.InnerConeAngle))), + OuterConeCos: float32(math.Cos(float64(l.OuterConeAngle))), + }, nil +} + +// clusterRange returns lightRange when it is positive, and otherwise the distance at which intensity * max(color) / d^2 falls to [ClusterRangeCutoff], at least minClusterLightRange. +func clusterRange(lightRange float32, color math3d.Vec3, intensity float32) float32 { + if lightRange > 0 { + return lightRange + } + power := float64(intensity) * float64(max(color.X, color.Y, color.Z)) + return max(float32(math.Sqrt(power/ClusterRangeCutoff)), minClusterLightRange) +} + // NewPointClusterLight returns a [ClusterLightPoint] with finite range and linear RGB color. func NewPointClusterLight(pos, color math3d.Vec3, intensity, lightRange float32) ClusterLight { return ClusterLight{ @@ -131,7 +171,7 @@ func (l ClusterLight) Validate() error { return fmt.Errorf("%w: position is not finite", ErrInvalidClusterLight) } if !finite(l.Range) || l.Range <= 0 { - return fmt.Errorf("%w: range %v must be finite and positive", ErrInvalidClusterLight, l.Range) + return fmt.Errorf("%w: range %v must be finite and positive (ClusterLightFromPoint and ClusterLightFromSpot derive one for an unbounded light)", ErrInvalidClusterLight, l.Range) } if !finite3(l.Color) || l.Color.X < 0 || l.Color.Y < 0 || l.Color.Z < 0 { return fmt.Errorf("%w: color %v must be finite and non-negative", ErrInvalidClusterLight, l.Color) @@ -169,10 +209,7 @@ func (l ClusterLight) spotScaleOffset() (scale, offset float32) { } inner := math3d.Clamp(l.InnerConeCos, -1, 1) outer := math3d.Clamp(l.OuterConeCos, -1, inner) - denom := inner - outer - if denom < 1e-4 { - denom = 1e-4 - } + denom := max(inner-outer, minSpotConeCosDelta) scale = 1.0 / denom offset = -outer * scale return scale, offset @@ -259,11 +296,11 @@ func (c ClusterConfig) Validate() error { if c.SlicesZ < 1 || c.SlicesZ > MaxClusterSlicesZ { return fmt.Errorf("%w: SlicesZ %d must be in [1, %d]", ErrInvalidClusterConfig, c.SlicesZ, MaxClusterSlicesZ) } - if c.MaxLights < 1 { - return fmt.Errorf("%w: MaxLights %d must be positive", ErrInvalidClusterConfig, c.MaxLights) + if c.MaxLights < 1 || c.MaxLights > MaxClusterLights { + return fmt.Errorf("%w: MaxLights %d must be in [1, %d]", ErrInvalidClusterConfig, c.MaxLights, MaxClusterLights) } - if c.MaxLightsPerCluster < 1 { - return fmt.Errorf("%w: MaxLightsPerCluster %d must be positive", ErrInvalidClusterConfig, c.MaxLightsPerCluster) + if c.MaxLightsPerCluster < 1 || c.MaxLightsPerCluster > c.MaxLights { + return fmt.Errorf("%w: MaxLightsPerCluster %d must be in [1, MaxLights %d]", ErrInvalidClusterConfig, c.MaxLightsPerCluster, c.MaxLights) } if c.FallbackMaxLights < 1 || c.FallbackMaxLights > MaxFallbackLights { return fmt.Errorf("%w: FallbackMaxLights %d must be in [1, %d]", ErrInvalidClusterConfig, c.FallbackMaxLights, MaxFallbackLights) @@ -272,6 +309,9 @@ func (c ClusterConfig) Validate() error { if totalClusters == 0 || totalClusters > 1<<20 { return fmt.Errorf("%w: cluster count %d out of range", ErrInvalidClusterConfig, totalClusters) } + if entries := totalClusters * uint64(c.MaxLightsPerCluster); entries > MaxClusterIndexEntries { + return fmt.Errorf("%w: %d clusters x %d lights per cluster = %d index slots exceed MaxClusterIndexEntries (%d)", ErrInvalidClusterConfig, totalClusters, c.MaxLightsPerCluster, entries, MaxClusterIndexEntries) + } return nil } @@ -497,7 +537,7 @@ func (g *ClusterGrid) BuildFrustum(proj math3d.Mat4, near, far float32) bool { // AssignLights transforms lights into view space, culls lights outside the camera frustum, tests each visible light against its candidate frustum clusters (sphere-vs-AABB for all lights plus exact cone-vs-AABB rejection for spot lights), and packs compact offset/count and index arrays. // -// Steady-state calls perform zero heap allocations. +// Lights that fail [ClusterLight.Validate] or have no power are skipped and counted in CulledLights; [ClusteredLightSystem.Update] validates first and reports them as errors. Once MaxLights lights are visible, further lights are dropped in input order (TruncatedLights), and once a cell holds MaxLightsPerCluster lights it drops the rest in input order (TruncatedClusters), so put the most important lights first when a scene can exceed either cap. Steady-state calls perform zero heap allocations. func (g *ClusterGrid) AssignLights(view, proj math3d.Mat4, near, far float32, lights []ClusterLight) ClusterStats { stats := ClusterStats{InputLights: len(lights)} g.activeLights = g.activeLights[:0] @@ -794,171 +834,149 @@ type scoredClusterLight struct { score float32 } -// SelectFallbackLights chooses up to maxLights highest-priority local lights for mobile / WebGL 2 / GLES 3.0 uniform-buffer fallback shading. +// SelectFallbackLights chooses up to maxLights local lights for the uniform-buffer fallback path (mobile, WebGL 2, OpenGL ES 3.0) and appends them to dst[:0]. // -// Active lights are ranked deterministically by radiant luminance, proximity to cameraPos (and distance relative to Range), and whether their sphere extends in front of cameraForward, breaking ties by input order. Results are appended to dst[:0]. -func SelectFallbackLights(dst []ClusterLight, cameraPos, cameraForward math3d.Vec3, lights []ClusterLight, maxLights int) []ClusterLight { +// Lights whose bounding sphere lies outside the view frustum of proj * view, or that fail [ClusterLight.Validate] or have no power, are dropped first, so off-screen lights never take a slot from visible ones. The rest are ranked deterministically by luminous power, range, and distance to the camera, breaking ties by input order. This allocates a scratch slice per call; [ClusteredLightSystem.Update] reuses one. +func SelectFallbackLights(dst []ClusterLight, view, proj math3d.Mat4, lights []ClusterLight, maxLights int) []ClusterLight { dst = dst[:0] if maxLights <= 0 || len(lights) == 0 { return dst } scored := make([]scoredClusterLight, 0, len(lights)) - return selectFallbackLightsWithScratch(dst, &scored, cameraPos, cameraForward, lights, maxLights) + return selectFallbackLightsWithScratch(dst, &scored, view, proj, lights, maxLights) } -func selectFallbackLightsWithScratch(dst []ClusterLight, scratch *[]scoredClusterLight, cameraPos, cameraForward math3d.Vec3, lights []ClusterLight, maxLights int) []ClusterLight { +// clusterLightBounds returns a world-space sphere enclosing everything l can light. +func clusterLightBounds(l ClusterLight) math3d.Sphere { + if l.Kind != ClusterLightSpot { + return math3d.Sphere{Center: l.Position, Radius: l.Range} + } + cosOuter := math3d.Clamp(l.OuterConeCos, -1, 1) + sinOuter := float32(math.Sqrt(float64(max(1-cosOuter*cosOuter, 0)))) + c, r := spotBoundingSphere(l.Position, l.normalizedDir(), l.Range, cosOuter, sinOuter) + return math3d.Sphere{Center: c, Radius: r} +} + +func selectFallbackLightsWithScratch(dst []ClusterLight, scratch *[]scoredClusterLight, view, proj math3d.Mat4, lights []ClusterLight, maxLights int) []ClusterLight { dst = dst[:0] + *scratch = (*scratch)[:0] if maxLights <= 0 || len(lights) == 0 { return dst } - fwd := cameraForward - if fwd.LenSq() < 1e-12 { - fwd = math3d.Vec3Forward() - } else { - fwd = fwd.Norm() - } + frustum := math3d.FrustumFromMat4(proj.Mul(view)) + cameraPos, _ := cameraPoseFromView(view) scored := (*scratch)[:0] for i := range lights { l := lights[i] - if !l.isActive() { + if !l.isActive() || !frustum.IntersectsSphere(clusterLightBounds(l)) { continue } lum := 0.2126*l.Color.X + 0.7152*l.Color.Y + 0.0722*l.Color.Z if lum <= 0 { - lum = max(l.Color.X, max(l.Color.Y, l.Color.Z)) + lum = max(l.Color.X, l.Color.Y, l.Color.Z) } - toLight := l.Position.Sub(cameraPos) - distSq := toLight.LenSq() + distSq := l.Position.Sub(cameraPos).LenSq() dist := float32(math.Sqrt(float64(distSq))) - // Smooth importance combining power, range coverage, and camera distance. - denom := distSq + 0.25 - score := l.Intensity * lum * (l.Range * l.Range) / (denom * (1.0 + dist/max(l.Range, 1e-3))) - - // Prefer lights whose sphere extends in front of the camera plane. - if toLight.Dot(fwd)+l.Range >= 0 { - score *= 4.0 - } else { - score *= 0.25 - } + score := l.Intensity * lum * (l.Range * l.Range) / ((distSq + 0.25) * (1.0 + dist/max(l.Range, minClusterLightRange))) scored = append(scored, scoredClusterLight{index: i, score: score}) } *scratch = scored - if len(scored) == 0 { - return dst - } - sort.Slice(scored, func(i, j int) bool { - if scored[i].score != scored[j].score { - return scored[i].score > scored[j].score - } - return scored[i].index < scored[j].index - }) + slices.SortFunc(scored, compareScoredClusterLights) keep := min(len(scored), maxLights) - if cap(dst) < keep { - dst = make([]ClusterLight, 0, keep) - } for i := range keep { dst = append(dst, lights[scored[i].index]) } return dst } -// EvaluateLightAttenuation computes the unit direction from worldPos to light and its combined glTF KHR_lights_punctual range, intensity, and spotlight angular attenuation. +// compareScoredClusterLights orders by descending score, then ascending input index. +func compareScoredClusterLights(a, b scoredClusterLight) int { + switch { + case a.score > b.score: + return -1 + case a.score < b.score: + return 1 + } + return a.index - b.index +} + +// EvaluateLightAttenuation returns the unit direction from worldPos toward light and the light's attenuation times its Intensity: [PointLightAttenuation] with Range, times [SpotConeAttenuation] for a [ClusterLightSpot]. It returns zeros for a light with no power or an invalid record, and when worldPos coincides with the light. func EvaluateLightAttenuation(light ClusterLight, worldPos math3d.Vec3) (dirToLight math3d.Vec3, attenuation float32) { if !light.isActive() { return math3d.Vec3{}, 0 } toLight := light.Position.Sub(worldPos) distSq := toLight.LenSq() - dist := float32(math.Sqrt(float64(distSq))) - if dist >= light.Range { + if distSq <= minLightDirLenSq { return math3d.Vec3{}, 0 } - if dist > 1e-6 { - dirToLight = toLight.Scale(1.0 / dist) - } else { - dirToLight = math3d.Vec3Up() - } - - ratio := dist / light.Range - r2 := ratio * ratio - r4 := r2 * r2 - win := math3d.Clamp(1.0-r4, 0, 1) - atten := (win * win) / max(distSq, 1e-4) - + dirToLight = toLight.Scale(float32(1.0 / math.Sqrt(float64(distSq)))) + atten := PointLightAttenuation(distSq, light.Range) if light.Kind == ClusterLightSpot { - lightDir := light.normalizedDir() scale, offset := light.spotScaleOffset() - cd := lightDir.Dot(dirToLight.Neg()) - spot := math3d.Clamp(cd*scale+offset, 0, 1) - atten *= spot * spot + atten *= SpotConeAttenuation(light.normalizedDir(), dirToLight, scale, offset) } return dirToLight, atten * light.Intensity } -// EvaluateDirectLights computes the pure-Go analytic Lambertian diffuse radiance for worldPos and normal over all lights, matching [ClusteredFallbackWGSL] and serving as ground truth for clustered lighting parity tests. -func EvaluateDirectLights(worldPos, normal, albedo, ambient math3d.Vec3, lights []ClusterLight) math3d.Vec3 { - n := normal - if n.LenSq() > 1e-12 { - n = n.Norm() +// ShadeClusteredPoint is [ShadePoint] for rig plus every light in lights, shaded with the same Cook-Torrance BRDF ([EvaluatePBR]). It is the brute-force reference for shade_pbr_clustered in [ClusteredBindingsWGSL] and [ClusteredFallbackBindingsWGSL] when no light is culled or truncated; call [LinearToSRGB] on the result to compare it with what [ClusteredLitWGSL] writes. +func ShadeClusteredPoint(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig, lights []ClusterLight) math3d.Vec3 { + lo := ShadePoint(worldPos, normal, viewDir, mat, rig) + n, v, ok := clusterUnitNormalView(normal, viewDir) + if !ok { + return lo } - irr := ambient for i := range lights { - l := lights[i] - lDir, atten := EvaluateLightAttenuation(l, worldPos) - if atten <= 0 { - continue - } - ndl := max(n.Dot(lDir), 0) - if ndl <= 0 { - continue - } - irr = irr.Add(l.Color.Scale(atten * ndl)) + lo = lo.Add(clusterLightRadiance(lights[i], worldPos, n, v, mat)) } - return math3d.Vec3{X: irr.X * albedo.X, Y: irr.Y * albedo.Y, Z: irr.Z * albedo.Z} + return lo } -// EvaluateClusteredLights computes the pure-Go analytic Lambertian diffuse radiance at worldPos using only the lights assigned to worldPos's frustum cluster in grid, matching [ClusteredLitWGSL] byte-for-byte in formula. -func EvaluateClusteredLights(worldPos, normal, albedo, ambient math3d.Vec3, grid *ClusterGrid, view, proj math3d.Mat4, viewportW, viewportH float32) math3d.Vec3 { - if grid == nil { - return math3d.Vec3{X: ambient.X * albedo.X, Y: ambient.Y * albedo.Y, Z: ambient.Z * albedo.Z} +// ShadeClusteredGridPoint is [ShadeClusteredPoint] restricted to the lights grid assigned, on its last [ClusterGrid.AssignLights], to the cluster that holds worldPos in a viewportW x viewportH viewport, looked up exactly as shade_pbr_clustered in [ClusteredBindingsWGSL] looks it up. +func ShadeClusteredGridPoint(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig, grid *ClusterGrid, view, proj math3d.Mat4, viewportW, viewportH float32) math3d.Vec3 { + lo := ShadePoint(worldPos, normal, viewDir, mat, rig) + n, v, ok := clusterUnitNormalView(normal, viewDir) + if grid == nil || !ok { + return lo } viewPos := view.TransformPoint(worldPos) - viewZ := -viewPos.Z - clip := proj.MulVec4(viewPos.Vec4(1)) if clip.W <= 1e-6 { - return math3d.Vec3{X: ambient.X * albedo.X, Y: ambient.Y * albedo.Y, Z: ambient.Z * albedo.Z} + return lo } - ndcX := clip.X / clip.W - ndcY := clip.Y / clip.W - fragX := (ndcX + 1.0) * 0.5 * viewportW - fragY := (1.0 - ndcY) * 0.5 * viewportH - + fragX := (clip.X/clip.W + 1.0) * 0.5 * viewportW + fragY := (1.0 - clip.Y/clip.W) * 0.5 * viewportH tx := clusterClampInt(int(max(fragX, 0)/max(viewportW, 1)*float32(grid.cfg.TilesX)), 0, grid.cfg.TilesX-1) ty := clusterClampInt(int(max(fragY, 0)/max(viewportH, 1)*float32(grid.cfg.TilesY)), 0, grid.cfg.TilesY-1) - sz := grid.SliceForDepth(viewZ) + sz := grid.SliceForDepth(-viewPos.Z) + for _, lightIdx := range grid.ClusterLightIndices(tx, ty, sz) { + lo = lo.Add(clusterLightRadiance(grid.activeLights[lightIdx], worldPos, n, v, mat)) + } + return lo +} - n := normal - if n.LenSq() > 1e-12 { - n = n.Norm() +func clusterUnitNormalView(normal, viewDir math3d.Vec3) (n, v math3d.Vec3, ok bool) { + nLenSq := normal.LenSq() + vLenSq := viewDir.LenSq() + if nLenSq <= minLightDirLenSq || vLenSq <= minLightDirLenSq { + return math3d.Vec3{}, math3d.Vec3{}, false } - irr := ambient - for _, lightIdx := range grid.ClusterLightIndices(tx, ty, sz) { - l := grid.activeLights[lightIdx] - lDir, atten := EvaluateLightAttenuation(l, worldPos) - if atten <= 0 { - continue - } - ndl := max(n.Dot(lDir), 0) - if ndl <= 0 { - continue - } - irr = irr.Add(l.Color.Scale(atten * ndl)) + return normal.Scale(float32(1.0 / math.Sqrt(float64(nLenSq)))), viewDir.Scale(float32(1.0 / math.Sqrt(float64(vLenSq)))), true +} + +// clusterLightRadiance is the outgoing radiance one local light adds at worldPos for unit n and v, matching cluster_light_radiance in the clustered WGSL. +func clusterLightRadiance(l ClusterLight, worldPos, n, v math3d.Vec3, mat PBRMaterial) math3d.Vec3 { + lDir, atten := EvaluateLightAttenuation(l, worldPos) + ndotl := n.Dot(lDir) + if atten <= 0 || ndotl <= 0 { + return math3d.Vec3{} } - return math3d.Vec3{X: irr.X * albedo.X, Y: irr.Y * albedo.Y, Z: irr.Z * albedo.Z} + brdf := EvaluatePBR(n, v, lDir, mat) + rad := l.Color.Scale(atten * ndotl) + return math3d.Vec3{X: brdf.X * rad.X, Y: brdf.Y * rad.Y, Z: brdf.Z * rad.Z} } // DeviceSupportsClusteredLighting reports whether dev exposes the storage-buffer and compute capabilities needed for the clustered forward shading path. Devices without them (such as WebGL 2, OpenGL ES 3.0, or headless tests under nsgotest.NoGPUCompute) fall back to the uniform-buffer path automatically. @@ -972,10 +990,20 @@ func DeviceSupportsClusteredLighting(dev *gpu.Device) bool { caps.Limits.MaxStorageBufferBindingSize >= clusterMinStorageBindingBytes } -// ClusteredBindingsWGSL declares the @group(1) uniform and read-only storage bindings plus evaluate_clustered_lights(world_pos, normal, frag_pos) for the desktop clustered forward shading path. +// ClusteredBindingsWGSL is [LightWGSL] (the [LightRig] block at [LightGroup] binding 0 and its PBR helpers) plus the clustered forward bindings at bindings 1 to 4 of the same group and this helper: // -// Depth slicing uses a 6-step binary search over the uniform slice_depths split table (avoiding log2/exp so it runs identically on Metal, D3D11, OpenGL, WebGPU, and NSGo's software GPU VM). -const ClusteredBindingsWGSL = ` +// - shade_pbr_clustered(world_pos, normal, view_dir, base_color, metallic, roughness, frag_pos) -> vec3 +// +// It returns shade_pbr for the rig plus every local light binned into the cluster that holds the fragment, each shaded with pbr_brdf, point_light_attenuation and spot_cone_attenuation, so it matches [ShadeClusteredGridPoint]. frag_pos is the fragment's @builtin(position). Prepend [CameraWGSL], which supplies camera.view for the depth slice, and pair it with a [ClusteredLightSystem] in clustered mode; [ClusteredFallbackBindingsWGSL] declares the same helper for the fallback path. +// +// Depth slicing is a 6-step binary search over the uniform split-depth table rather than log2 and exp, because NSGo v0.3.0's software GPU VM has no log, log2, exp or exp2 builtin and silently evaluates them to zero (internal/driver/gpu_software.go, evalCall). +const ClusteredBindingsWGSL = LightWGSL + clusteredStorageWGSL + +// ClusteredFallbackBindingsWGSL is [LightWGSL] plus the fallback uniform block at [LightGroup] binding 1 and shade_pbr_clustered with the same signature as in [ClusteredBindingsWGSL], using no storage buffers or compute, for WebGL 2 and OpenGL ES 3.0 targets. frag_pos is ignored: every uploaded light is evaluated for every fragment. +const ClusteredFallbackBindingsWGSL = LightWGSL + clusteredFallbackWGSL + +// clusterLightRadianceWGSL declares the light record both paths upload and cluster_light_radiance, the outgoing radiance one local light adds, matching clusterLightRadiance. +const clusterLightRadianceWGSL = ` struct ClusterLightGPU { pos_range: vec4, color_intensity: vec4, @@ -983,17 +1011,41 @@ struct ClusterLightGPU { spot_params: vec4, } +fn cluster_light_radiance(light: ClusterLightGPU, world_pos: vec3, n: vec3, v: vec3, base_color: vec3, metallic: f32, roughness: f32) -> vec3 { + let intensity = light.color_intensity.w; + if (light.pos_range.w <= 0.0 || intensity <= 0.0) { + return vec3(0.0, 0.0, 0.0); + } + let to_light = light.pos_range.xyz - world_pos; + let dist_sq = dot(to_light, to_light); + if (dist_sq <= 1e-12) { + return vec3(0.0, 0.0, 0.0); + } + let l = to_light / sqrt(dist_sq); + var atten = point_light_attenuation(dist_sq, light.pos_range.w); + if (light.dir_kind.w > 0.5) { + atten = atten * spot_cone_attenuation(light.dir_kind.xyz, l, light.spot_params.x, light.spot_params.y); + } + let ndotl = dot(n, l); + if (atten <= 0.0 || ndotl <= 0.0) { + return vec3(0.0, 0.0, 0.0); + } + return pbr_brdf(n, v, l, base_color, metallic, roughness) * (light.color_intensity.rgb * (intensity * atten * ndotl)); +} +` + +// clusteredStorageWGSL is the storage-buffer half of [ClusteredBindingsWGSL], after [LightWGSL]. +const clusteredStorageWGSL = clusterLightRadianceWGSL + ` struct ClusterParams { grid_info: vec4, viewport_depth: vec4, - ambient: vec4, slice_depths: array, 17>, } -@group(1) @binding(0) var cluster_params: ClusterParams; -@group(1) @binding(1) var cluster_lights: array; -@group(1) @binding(2) var cluster_cells: array>; -@group(1) @binding(3) var cluster_indices: array; +@group(1) @binding(1) var cluster_params: ClusterParams; +@group(1) @binding(2) var cluster_lights: array; +@group(1) @binding(3) var cluster_cells: array>; +@group(1) @binding(4) var cluster_indices: array; fn cluster_slice_depth(idx: u32) -> f32 { let v = cluster_params.slice_depths[idx / 4u]; @@ -1024,164 +1076,93 @@ fn cluster_find_slice(view_z: f32) -> u32 { return min(lo, slices - 1u); } -fn cluster_eval_one_light(light: ClusterLightGPU, world_pos: vec3, normal: vec3) -> vec3 { - let light_range = light.pos_range.w; - let intensity = light.color_intensity.w; - if (light_range <= 0.0 || intensity <= 0.0) { - return vec3(0.0, 0.0, 0.0); - } - let to_light = light.pos_range.xyz - world_pos; - let dist_sq = dot(to_light, to_light); - let dist = sqrt(dist_sq); - if (dist >= light_range) { - return vec3(0.0, 0.0, 0.0); - } - var l_dir = vec3(0.0, 1.0, 0.0); - if (dist > 0.000001) { - l_dir = to_light / dist; - } - let ndl = max(dot(normal, l_dir), 0.0); - if (ndl <= 0.0) { - return vec3(0.0, 0.0, 0.0); - } - let ratio = dist / light_range; - let r2 = ratio * ratio; - let r4 = r2 * r2; - let win = clamp(1.0 - r4, 0.0, 1.0); - var atten = (win * win) / max(dist_sq, 0.0001); - if (light.dir_kind.w > 0.5) { - let cd = dot(light.dir_kind.xyz, -l_dir); - let spot = clamp(cd * light.spot_params.x + light.spot_params.y, 0.0, 1.0); - atten = atten * spot * spot; - } - return light.color_intensity.rgb * (intensity * atten * ndl); -} - -fn evaluate_clustered_lights(world_pos: vec3, normal: vec3, frag_pos: vec4) -> vec3 { - let n = normalize(normal); - var irradiance = cluster_params.ambient.rgb; +fn shade_pbr_clustered(world_pos: vec3, normal: vec3, view_dir: vec3, base_color: vec3, metallic: f32, roughness: f32, frag_pos: vec4) -> vec3 { + var lo = shade_pbr(world_pos, normal, view_dir, base_color, metallic, roughness); let tiles_x = cluster_params.grid_info.x; let tiles_y = cluster_params.grid_info.y; if (tiles_x == 0u || tiles_y == 0u) { - return irradiance; + return lo; } + let n = normalize(normal); + let v = normalize(view_dir); let vp_w = max(cluster_params.viewport_depth.x, 1.0); let vp_h = max(cluster_params.viewport_depth.y, 1.0); let tx = min(u32(max(frag_pos.x, 0.0) / vp_w * f32(tiles_x)), tiles_x - 1u); let ty = min(u32(max(frag_pos.y, 0.0) / vp_h * f32(tiles_y)), tiles_y - 1u); let view_pos = camera.view * vec4(world_pos, 1.0); let slice_z = cluster_find_slice(-view_pos.z); - let cluster_idx = (slice_z * tiles_y + ty) * tiles_x + tx; - let cell = cluster_cells[cluster_idx]; - let offset = cell.x; - let count = cell.y; - for (var i: u32 = 0u; i < count; i = i + 1u) { - let light_idx = cluster_indices[offset + i]; - irradiance = irradiance + cluster_eval_one_light(cluster_lights[light_idx], world_pos, n); + let cell = cluster_cells[(slice_z * tiles_y + ty) * tiles_x + tx]; + for (var i: u32 = 0u; i < cell.y; i = i + 1u) { + let light_idx = cluster_indices[cell.x + i]; + lo = lo + cluster_light_radiance(cluster_lights[light_idx], world_pos, n, v, base_color, metallic, roughness); } - return irradiance; + return lo; } ` -// ClusteredFallbackBindingsWGSL declares the @group(1) pure uniform-buffer binding plus evaluate_clustered_lights(world_pos, normal, frag_pos) with the identical signature as [ClusteredBindingsWGSL], using zero storage buffers and zero compute shaders for WebGL 2 / OpenGL ES 3.0 targets. -const ClusteredFallbackBindingsWGSL = ` -struct ClusterLightGPU { - pos_range: vec4, - color_intensity: vec4, - dir_kind: vec4, - spot_params: vec4, -} - +// clusteredFallbackWGSL is the uniform-buffer half of [ClusteredFallbackBindingsWGSL], after [LightWGSL]. +const clusteredFallbackWGSL = clusterLightRadianceWGSL + ` struct FallbackLightUniform { info: vec4, - ambient: vec4, - lights: array, + local: array, } -@group(1) @binding(0) var fallback_lights: FallbackLightUniform; - -fn cluster_eval_one_light(light: ClusterLightGPU, world_pos: vec3, normal: vec3) -> vec3 { - let light_range = light.pos_range.w; - let intensity = light.color_intensity.w; - if (light_range <= 0.0 || intensity <= 0.0) { - return vec3(0.0, 0.0, 0.0); - } - let to_light = light.pos_range.xyz - world_pos; - let dist_sq = dot(to_light, to_light); - let dist = sqrt(dist_sq); - if (dist >= light_range) { - return vec3(0.0, 0.0, 0.0); - } - var l_dir = vec3(0.0, 1.0, 0.0); - if (dist > 0.000001) { - l_dir = to_light / dist; - } - let ndl = max(dot(normal, l_dir), 0.0); - if (ndl <= 0.0) { - return vec3(0.0, 0.0, 0.0); - } - let ratio = dist / light_range; - let r2 = ratio * ratio; - let r4 = r2 * r2; - let win = clamp(1.0 - r4, 0.0, 1.0); - var atten = (win * win) / max(dist_sq, 0.0001); - if (light.dir_kind.w > 0.5) { - let cd = dot(light.dir_kind.xyz, -l_dir); - let spot = clamp(cd * light.spot_params.x + light.spot_params.y, 0.0, 1.0); - atten = atten * spot * spot; - } - return light.color_intensity.rgb * (intensity * atten * ndl); -} +@group(1) @binding(1) var fallback_lights: FallbackLightUniform; -fn evaluate_clustered_lights(world_pos: vec3, normal: vec3, frag_pos: vec4) -> vec3 { +fn shade_pbr_clustered(world_pos: vec3, normal: vec3, view_dir: vec3, base_color: vec3, metallic: f32, roughness: f32, frag_pos: vec4) -> vec3 { + var lo = shade_pbr(world_pos, normal, view_dir, base_color, metallic, roughness); let n = normalize(normal); - var irradiance = fallback_lights.ambient.rgb; + let v = normalize(view_dir); let count = min(fallback_lights.info.x, 16u); for (var i: u32 = 0u; i < count; i = i + 1u) { - irradiance = irradiance + cluster_eval_one_light(fallback_lights.lights[i], world_pos, n); + lo = lo + cluster_light_radiance(fallback_lights.local[i], world_pos, n, v, base_color, metallic, roughness); } - return irradiance; + return lo; } ` -const clusteredDefaultStageWGSL = ` -struct ClusterVertexIn { - @location(0) pos: vec3, - @location(1) normal: vec3, - @location(2) uv: vec2, -} - -struct ClusterVertexOut { - @builtin(position) clip: vec4, - @location(0) world_pos: vec3, - @location(1) normal: vec3, -} - -@vertex -fn vs_main(in: ClusterVertexIn) -> ClusterVertexOut { - var out: ClusterVertexOut; - out.clip = camera.view_proj * vec4(in.pos, 1.0); - out.world_pos = in.pos; - out.normal = in.normal; - return out; -} - +// clusteredLitFragmentWGSL is the fragment stage of [ClusteredLitWGSL] and [ClusteredFallbackWGSL]: [LitPBRWGSL]'s, with shade_pbr_clustered in place of shade_pbr. +const clusteredLitFragmentWGSL = ` @fragment -fn fs_main(in: ClusterVertexOut) -> @location(0) vec4 { - let lit = evaluate_clustered_lights(in.world_pos, in.normal, in.clip); - return vec4(clamp(lit, vec3(0.0), vec3(1.0)), 1.0); +fn fs_main(in: PBRVertexOut) -> @location(0) vec4 { + let view_dir = normalize(camera.eye.xyz - in.world_pos * camera.eye.w); + let lit = shade_pbr_clustered( + in.world_pos, + in.world_normal, + view_dir, + pbr_draw.base_color.rgb, + pbr_draw.pbr_params.x, + pbr_draw.pbr_params.y, + in.clip, + ) + pbr_draw.emissive.rgb; + return vec4(linear_to_srgb(lit), pbr_draw.base_color.a); } ` -// ClusteredLitWGSL is a ready-to-compile WGSL module for [MeshVertexLayout] meshes combining [CameraWGSL] (@group(0)) and [ClusteredBindingsWGSL] (@group(1)). -const ClusteredLitWGSL = CameraWGSL + ClusteredBindingsWGSL + clusteredDefaultStageWGSL +// ClusteredLitWGSL is [LitPBRWGSL] with clustered local lights: the same metallic-roughness module on [CameraWGSL], [MeshVertexLayout] and a per-draw [PBRDrawUniform] at [PBRDrawGroup], whose fragment stage shades with shade_pbr_clustered from [ClusteredBindingsWGSL] and writes sRGB. [NewClusteredLitPBRPipeline] creates a pipeline from it. +const ClusteredLitWGSL = litPBRPreludeWGSL + clusteredStorageWGSL + clusteredLitFragmentWGSL -// ClusteredFallbackWGSL is a ready-to-compile WGSL module for [MeshVertexLayout] meshes combining [CameraWGSL] (@group(0)) and [ClusteredFallbackBindingsWGSL] (@group(1)) without storage buffers or compute shaders. -const ClusteredFallbackWGSL = CameraWGSL + ClusteredFallbackBindingsWGSL + clusteredDefaultStageWGSL +// ClusteredFallbackWGSL is [ClusteredLitWGSL] built on [ClusteredFallbackBindingsWGSL], for devices without storage buffers or compute. +const ClusteredFallbackWGSL = litPBRPreludeWGSL + clusteredFallbackWGSL + clusteredLitFragmentWGSL -// ClusteredLightSystem manages the GPU buffers, bind group layout, and bind group for clustered forward shading with automatic fallback to a pure uniform-buffer path on devices without storage buffers or compute (WebGL 2, OpenGL ES 3.0, nsgotest.NoGPUCompute). +// NewClusteredLitPBRPipeline compiles sys's ready-made shader ([ClusteredLitWGSL] or [ClusteredFallbackWGSL]) and creates the same back-face-culled pipeline as [NewLitPBRPipeline], with sys's layout at [LightGroup] in place of a [GPULightBuffer]'s. Pass depthFormat = [gpu.FormatUndefined] when rendering without a depth attachment. +func NewClusteredLitPBRPipeline(cx *core.Scope, dev *gpu.Device, camLayout *gpu.BindGroupLayout, sys *ClusteredLightSystem, drawLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error) { + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + if sys == nil { + return nil, fmt.Errorf("%w: nil ClusteredLightSystem", ErrInvalidClusterConfig) + } + layouts := make([]*gpu.BindGroupLayout, PBRDrawGroup+1) + layouts[CameraGroup] = camLayout + layouts[LightGroup] = sys.Layout() + layouts[PBRDrawGroup] = drawLayout + return newLitPBRPipeline(cx, dev, "render3d.clustered_lit_pbr", sys.WGSL(), layouts, MeshVertexLayout(), dev.SurfaceFormat(), depthFormat) +} + +// ClusteredLightSystem owns the whole [LightGroup] bind group for clustered forward shading: the [LightRig] uniform [LightWGSL] reads at binding 0 (ambient, directional, and the rig's own point and spot lights) and the local-light buffers at bindings 1 to 4. On devices without storage buffers or compute (WebGL 2, OpenGL ES 3.0, nsgotest.NoGPUCompute) it falls back to one uniform buffer at binding 1 holding the [ClusterConfig.FallbackMaxLights] most important visible lights. // -// Create it once on device readiness, call [ClusteredLightSystem.Update] or [ClusteredLightSystem.UpdateCamera] each frame, bind [ClusteredLightSystem.BindGroup] at [ClusteredLightGroup] (group 1), and shade with [ClusteredLightSystem.WGSL] or your own shader prepending [CameraWGSL] + [ClusteredLightSystem.BindingsWGSL]. +// Create it once the device is ready, call [ClusteredLightSystem.Update] or [ClusteredLightSystem.UpdateCamera] each frame, and draw with [NewClusteredLitPBRPipeline] or a custom shader that prepends [CameraWGSL] and [ClusteredLightSystem.BindingsWGSL], binding the system with [ClusteredLightSystem.Bind] in place of a [GPULightBuffer]. type ClusteredLightSystem struct { cfg ClusterConfig fallback bool @@ -1190,16 +1171,17 @@ type ClusteredLightSystem struct { // GPU resources (owned by the core.Scope passed to NewClusteredLightSystem). layout *gpu.BindGroupLayout group *gpu.BindGroup - paramsBuf *gpu.Buffer // clustered: ClusterParams uniform; fallback: FallbackLightUniform - lightsBuf *gpu.Buffer // clustered only: storage array - cellsBuf *gpu.Buffer // clustered only: storage array> - indicesBuf *gpu.Buffer // clustered only: storage array - indicesCap int // capacity of indicesBuf in uint32 entries + rigBuf *gpu.Buffer // binding 0: LightRig uniform + paramsBuf *gpu.Buffer // binding 1: clustered ClusterParams uniform, or fallback FallbackLightUniform + lightsBuf *gpu.Buffer // clustered only, binding 2: storage array + cellsBuf *gpu.Buffer // clustered only, binding 3: storage array> + indicesBuf *gpu.Buffer // clustered only, binding 4: storage array fallbackDst []ClusterLight fallbackTmp []scoredClusterLight lastStats ClusterStats // Reusable CPU upload scratch buffers (zero steady-state allocations). + rigBytes [LightUniformSize]byte paramsBytes [ClusterParamsUniformSize]byte fallbackData [ClusteredFallbackUniformSize]byte lightsBytes []byte @@ -1207,7 +1189,7 @@ type ClusteredLightSystem struct { indicesBytes []byte } -// NewClusteredLightSystem validates cfg, inspects dev's GPU capabilities, and allocates either the storage-buffer clustered lighting path or the uniform-buffer mobile/WebGL 2 fallback path scoped to cx. +// NewClusteredLightSystem validates cfg, inspects dev's GPU capabilities, and allocates either the storage-buffer clustered lighting path or the uniform-buffer fallback path scoped to cx. In clustered mode it returns an error wrapping [ErrInvalidClusterConfig] when the light or index storage buffer cfg needs exceeds dev's MaxStorageBufferBindingSize. func NewClusteredLightSystem(cx *core.Scope, dev *gpu.Device, cfg ClusterConfig) (*ClusteredLightSystem, error) { if err := cfg.Validate(); err != nil { return nil, err @@ -1217,84 +1199,42 @@ func NewClusteredLightSystem(cx *core.Scope, dev *gpu.Device, cfg ClusterConfig) } cfg = cfg.withDefaults() - useFallback := cfg.ForceFallback || !DeviceSupportsClusteredLighting(dev) - label := cfg.Label if label == "" { label = "render3d.clustered" } - - if useFallback { - return newClusteredFallbackSystem(cx, dev, cfg, label) + if cfg.ForceFallback || !DeviceSupportsClusteredLighting(dev) { + return newClusteredSystem(cx, dev, cfg, label, true) } - return newClusteredStorageSystem(cx, dev, cfg, label) + return newClusteredSystem(cx, dev, cfg, label, false) } -func newClusteredFallbackSystem(cx *core.Scope, dev *gpu.Device, cfg ClusterConfig, label string) (*ClusteredLightSystem, error) { - buf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ - Label: label + " fallback lights", - Size: ClusteredFallbackUniformSize, - Usage: gpu.UsageUniform | gpu.UsageCopyDst, - Retained: cfg.Retained, - }) - if err != nil { - return nil, err - } - layout, err := dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{ - Label: label + " fallback layout", - Entries: []gpu.BindGroupLayoutEntry{{ - Binding: 0, - Visibility: gpu.StageFragment, - Type: gpu.BindingUniform, - }}, - }) - if err != nil { - _ = buf.Close() - return nil, err - } - group, err := dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{ - Label: label + " fallback group", - Layout: layout, - Entries: []gpu.BindGroupEntry{{ - Binding: 0, - Buffer: buf, - Size: ClusteredFallbackUniformSize, - }}, - }) - if err != nil { - _ = layout.Close() - _ = buf.Close() - return nil, err - } - - return &ClusteredLightSystem{ - cfg: cfg, - fallback: true, - layout: layout, - group: group, - paramsBuf: buf, - fallbackDst: make([]ClusterLight, 0, cfg.FallbackMaxLights), - fallbackTmp: make([]scoredClusterLight, 0, cfg.MaxLights), - }, nil -} - -func newClusteredStorageSystem(cx *core.Scope, dev *gpu.Device, cfg ClusterConfig, label string) (*ClusteredLightSystem, error) { - grid, err := NewClusterGrid(cfg) - if err != nil { - return nil, err - } - - numClusters := cfg.ClusterCount() - lightsSize := uint64(cfg.MaxLights) * ClusterLightGPUSize - cellsSize := uint64(numClusters) * ClusterCellGPUSize - indicesCap := numClusters * cfg.MaxLightsPerCluster - indicesSize := uint64(indicesCap) * 4 - - // Respect MaxStorageBufferBindingSize by capping indices buffer capacity safely if needed. - maxBind := dev.Capabilities().Limits.MaxStorageBufferBindingSize - if maxBind > 0 && indicesSize > maxBind { - indicesCap = max(int(maxBind/4), 1) - indicesSize = uint64(indicesCap) * 4 +func newClusteredSystem(cx *core.Scope, dev *gpu.Device, cfg ClusterConfig, label string, fallback bool) (*ClusteredLightSystem, error) { + s := &ClusteredLightSystem{cfg: cfg, fallback: fallback} + var lightsSize, cellsSize, indicesSize uint64 + if fallback { + s.fallbackDst = make([]ClusterLight, 0, cfg.FallbackMaxLights) + s.fallbackTmp = make([]scoredClusterLight, 0, cfg.MaxLights) + } else { + grid, err := NewClusterGrid(cfg) + if err != nil { + return nil, err + } + s.grid = grid + numClusters := uint64(cfg.ClusterCount()) + lightsSize = uint64(cfg.MaxLights) * ClusterLightGPUSize + cellsSize = numClusters * ClusterCellGPUSize + indicesSize = numClusters * uint64(cfg.MaxLightsPerCluster) * 4 + if maxBind := dev.Capabilities().Limits.MaxStorageBufferBindingSize; maxBind > 0 { + for _, b := range []struct { + name string + size uint64 + }{{"lights", lightsSize}, {"cells", cellsSize}, {"indices", indicesSize}} { + if b.size > maxBind { + return nil, fmt.Errorf("%w: %s storage buffer of %d bytes exceeds the device's MaxStorageBufferBindingSize (%d); lower MaxLights, MaxLightsPerCluster or the grid size", ErrInvalidClusterConfig, b.name, b.size, maxBind) + } + } + } } var toClose []interface{ Close() error } @@ -1304,94 +1244,71 @@ func newClusteredStorageSystem(cx *core.Scope, dev *gpu.Device, cfg ClusterConfi } return nil, err } - - paramsBuf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ - Label: label + " params", - Size: ClusterParamsUniformSize, - Usage: gpu.UsageUniform | gpu.UsageCopyDst, - Retained: cfg.Retained, - }) - if err != nil { - return fail(err) + newBuffer := func(name string, size uint64, usage gpu.BufferUsage) (*gpu.Buffer, error) { + buf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + " " + name, + Size: size, + Usage: usage | gpu.UsageCopyDst, + Retained: cfg.Retained, + }) + if err == nil { + toClose = append(toClose, buf) + } + return buf, err } - toClose = append(toClose, paramsBuf) - lightsBuf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ - Label: label + " lights", - Size: lightsSize, - Usage: gpu.UsageStorage | gpu.UsageCopyDst, - Retained: cfg.Retained, - }) - if err != nil { + var err error + if s.rigBuf, err = newBuffer("rig", LightUniformSize, gpu.UsageUniform); err != nil { return fail(err) } - toClose = append(toClose, lightsBuf) - - cellsBuf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ - Label: label + " cells", - Size: cellsSize, - Usage: gpu.UsageStorage | gpu.UsageCopyDst, - Retained: cfg.Retained, - }) - if err != nil { - return fail(err) + paramsSize := uint64(ClusterParamsUniformSize) + if fallback { + paramsSize = ClusteredFallbackUniformSize } - toClose = append(toClose, cellsBuf) - - indicesBuf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ - Label: label + " indices", - Size: indicesSize, - Usage: gpu.UsageStorage | gpu.UsageCopyDst, - Retained: cfg.Retained, - }) - if err != nil { + if s.paramsBuf, err = newBuffer("params", paramsSize, gpu.UsageUniform); err != nil { return fail(err) } - toClose = append(toClose, indicesBuf) - - layout, err := dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{ - Label: label + " layout", - Entries: []gpu.BindGroupLayoutEntry{ - {Binding: 0, Visibility: gpu.StageFragment, Type: gpu.BindingUniform}, - {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingStorageRead}, - {Binding: 2, Visibility: gpu.StageFragment, Type: gpu.BindingStorageRead}, - {Binding: 3, Visibility: gpu.StageFragment, Type: gpu.BindingStorageRead}, - }, - }) - if err != nil { + layoutEntries := []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageVertex | gpu.StageFragment, Type: gpu.BindingUniform}, + {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingUniform}, + } + groupEntries := []gpu.BindGroupEntry{ + {Binding: 0, Buffer: s.rigBuf, Size: LightUniformSize}, + {Binding: 1, Buffer: s.paramsBuf, Size: paramsSize}, + } + if !fallback { + if s.lightsBuf, err = newBuffer("lights", lightsSize, gpu.UsageStorage); err != nil { + return fail(err) + } + if s.cellsBuf, err = newBuffer("cells", cellsSize, gpu.UsageStorage); err != nil { + return fail(err) + } + if s.indicesBuf, err = newBuffer("indices", indicesSize, gpu.UsageStorage); err != nil { + return fail(err) + } + layoutEntries = append(layoutEntries, + gpu.BindGroupLayoutEntry{Binding: 2, Visibility: gpu.StageFragment, Type: gpu.BindingStorageRead}, + gpu.BindGroupLayoutEntry{Binding: 3, Visibility: gpu.StageFragment, Type: gpu.BindingStorageRead}, + gpu.BindGroupLayoutEntry{Binding: 4, Visibility: gpu.StageFragment, Type: gpu.BindingStorageRead}, + ) + groupEntries = append(groupEntries, + gpu.BindGroupEntry{Binding: 2, Buffer: s.lightsBuf, Size: lightsSize}, + gpu.BindGroupEntry{Binding: 3, Buffer: s.cellsBuf, Size: cellsSize}, + gpu.BindGroupEntry{Binding: 4, Buffer: s.indicesBuf, Size: indicesSize}, + ) + s.lightsBytes = make([]byte, lightsSize) + s.cellsBytes = make([]byte, cellsSize) + s.indicesBytes = make([]byte, indicesSize) + } + + if s.layout, err = dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{Label: label + " layout", Entries: layoutEntries}); err != nil { return fail(err) } - toClose = append(toClose, layout) - - group, err := dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{ - Label: label + " group", - Layout: layout, - Entries: []gpu.BindGroupEntry{ - {Binding: 0, Buffer: paramsBuf, Size: ClusterParamsUniformSize}, - {Binding: 1, Buffer: lightsBuf, Size: lightsSize}, - {Binding: 2, Buffer: cellsBuf, Size: cellsSize}, - {Binding: 3, Buffer: indicesBuf, Size: indicesSize}, - }, - }) - if err != nil { + toClose = append(toClose, s.layout) + if s.group, err = dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{Label: label + " group", Layout: s.layout, Entries: groupEntries}); err != nil { return fail(err) } - - return &ClusteredLightSystem{ - cfg: cfg, - fallback: false, - grid: grid, - layout: layout, - group: group, - paramsBuf: paramsBuf, - lightsBuf: lightsBuf, - cellsBuf: cellsBuf, - indicesBuf: indicesBuf, - indicesCap: indicesCap, - lightsBytes: make([]byte, lightsSize), - cellsBytes: make([]byte, cellsSize), - indicesBytes: make([]byte, indicesSize), - }, nil + return s, nil } // IsClustered reports whether s is running the storage-buffer clustered forward shading path. @@ -1416,7 +1333,7 @@ func (s *ClusteredLightSystem) Grid() *ClusterGrid { return s.grid } -// Layout returns the bind group layout a pipeline lists at [ClusteredLightGroup] (group 1). +// Layout returns the bind group layout a pipeline lists at [LightGroup]. func (s *ClusteredLightSystem) Layout() *gpu.BindGroupLayout { if s == nil { return nil @@ -1424,7 +1341,7 @@ func (s *ClusteredLightSystem) Layout() *gpu.BindGroupLayout { return s.layout } -// BindGroup returns the bind group a render pass sets at [ClusteredLightGroup] (group 1). +// BindGroup returns the bind group a render pass sets at [LightGroup]. func (s *ClusteredLightSystem) BindGroup() *gpu.BindGroup { if s == nil { return nil @@ -1432,7 +1349,7 @@ func (s *ClusteredLightSystem) BindGroup() *gpu.BindGroup { return s.group } -// WGSL returns the ready-to-compile WGSL shader matching s's active path ([ClusteredLitWGSL] or [ClusteredFallbackWGSL]). +// WGSL returns the ready-made shader matching s's active path ([ClusteredLitWGSL] or [ClusteredFallbackWGSL]). func (s *ClusteredLightSystem) WGSL() string { if s.IsFallback() { return ClusteredFallbackWGSL @@ -1440,7 +1357,7 @@ func (s *ClusteredLightSystem) WGSL() string { return ClusteredLitWGSL } -// BindingsWGSL returns the @group(1) declarations and evaluate_clustered_lights function matching s's active path ([ClusteredBindingsWGSL] or [ClusteredFallbackBindingsWGSL]). +// BindingsWGSL returns the [LightGroup] declarations and shade_pbr_clustered helper matching s's active path ([ClusteredBindingsWGSL] or [ClusteredFallbackBindingsWGSL]). func (s *ClusteredLightSystem) BindingsWGSL() string { if s.IsFallback() { return ClusteredFallbackBindingsWGSL @@ -1470,7 +1387,7 @@ func (s *ClusteredLightSystem) ByteSize() uint64 { return 0 } var total uint64 - for _, b := range []*gpu.Buffer{s.paramsBuf, s.lightsBuf, s.cellsBuf, s.indicesBuf} { + for _, b := range []*gpu.Buffer{s.rigBuf, s.paramsBuf, s.lightsBuf, s.cellsBuf, s.indicesBuf} { if b != nil { total += b.Size() } @@ -1480,7 +1397,7 @@ func (s *ClusteredLightSystem) ByteSize() uint64 { // Valid reports whether s's GPU resources are open and belong to a live device. func (s *ClusteredLightSystem) Valid() bool { - if s == nil || !s.paramsBuf.Valid() || !s.layout.Valid() || !s.group.Valid() { + if s == nil || !s.rigBuf.Valid() || !s.paramsBuf.Valid() || !s.layout.Valid() || !s.group.Valid() { return false } if s.fallback { @@ -1489,93 +1406,94 @@ func (s *ClusteredLightSystem) Valid() bool { return s.lightsBuf.Valid() && s.cellsBuf.Valid() && s.indicesBuf.Valid() } -// Bind sets s's bind group at group on pass. It records nothing when s is not [ClusteredLightSystem.Valid]. -func (s *ClusteredLightSystem) Bind(pass *gpu.RenderPass, group uint32) { +// Bind sets s's bind group at [LightGroup] on pass, like [GPULightBuffer.Bind]. It records nothing when s is not [ClusteredLightSystem.Valid]. +func (s *ClusteredLightSystem) Bind(pass *gpu.RenderPass) { if !s.Valid() || pass == nil { return } - pass.SetBindGroup(group, s.group) + pass.SetBindGroup(LightGroup, s.group) } -// Update assigns lights for the frame and uploads the resulting lighting buffers to dev. +// Update validates rig and lights, assigns lights for the frame, and uploads the rig and the resulting light buffers to dev. viewportW and viewportH are the size of the rendered area the fragment shader's @builtin(position) covers, starting at its origin: under a [DynamicResolutionTarget] pass [DynamicResolutionTarget.ScaledSize], not the native size. +// +// It returns an error wrapping [ErrInvalidLight] for a malformed rig, or [ErrInvalidClusterLight] for a light that fails [ClusterLight.Validate] (including Range 0; see [ClusterLightFromPoint]), and uploads nothing in that case. Lights with zero intensity or color are culled. // -// In clustered mode, lights are binned into view-space frustum clusters via [ClusterGrid.AssignLights] and uploaded into the uniform and storage buffers. In fallback mode, the top [ClusterConfig.FallbackMaxLights] prioritized lights are selected via [SelectFallbackLights] and uploaded into the uniform buffer. -func (s *ClusteredLightSystem) Update(dev *gpu.Device, view, proj math3d.Mat4, near, far, viewportW, viewportH float32, ambient math3d.Vec3, lights []ClusterLight) ClusterStats { +// In clustered mode, lights are binned into view-space frustum clusters via [ClusterGrid.AssignLights]. In fallback mode, the top [ClusterConfig.FallbackMaxLights] visible lights are selected as [SelectFallbackLights] does; CulledLights counts lights outside the frustum or without power and TruncatedLights those dropped by the cap. Steady-state calls allocate nothing beyond the copies gpu.Device.WriteBuffer queues. +func (s *ClusteredLightSystem) Update(dev *gpu.Device, view, proj math3d.Mat4, near, far, viewportW, viewportH float32, rig LightRig, lights []ClusterLight) (ClusterStats, error) { if s == nil { - return ClusterStats{} + return ClusterStats{}, nil + } + if err := rig.Validate(); err != nil { + return ClusterStats{}, err + } + for i := range lights { + if err := lights[i].Validate(); err != nil { + return ClusterStats{}, fmt.Errorf("lights[%d]: %w", i, err) + } } + upload := dev != nil && s.Valid() + if upload { + u := packLightUniforms(rig) + u.Encode(s.rigBytes[:]) + dev.WriteBuffer(s.rigBuf, 0, s.rigBytes[:]) + } + if s.fallback { - camPos, camFwd := cameraPoseFromView(view) - s.fallbackDst = selectFallbackLightsWithScratch(s.fallbackDst, &s.fallbackTmp, camPos, camFwd, lights, s.cfg.FallbackMaxLights) + s.fallbackDst = selectFallbackLightsWithScratch(s.fallbackDst, &s.fallbackTmp, view, proj, lights, s.cfg.FallbackMaxLights) stats := ClusterStats{ - InputLights: len(lights), - VisibleLights: len(s.fallbackDst), - CulledLights: len(lights) - len(s.fallbackDst), - } - if len(s.fallbackTmp) > len(s.fallbackDst) { - stats.TruncatedLights = len(s.fallbackTmp) - len(s.fallbackDst) + InputLights: len(lights), + VisibleLights: len(s.fallbackDst), + CulledLights: len(lights) - len(s.fallbackTmp), + TruncatedLights: len(s.fallbackTmp) - len(s.fallbackDst), } s.lastStats = stats - if dev != nil && s.Valid() { - encodeFallbackUniform(&s.fallbackData, ambient, s.fallbackDst) + if upload { + encodeFallbackUniform(&s.fallbackData, s.fallbackDst) dev.WriteBuffer(s.paramsBuf, 0, s.fallbackData[:]) } - return stats + return stats, nil } stats := s.grid.AssignLights(view, proj, near, far, lights) s.lastStats = stats - if dev == nil || !s.Valid() { - return stats + if !upload { + return stats, nil } - encodeClusterParams(&s.paramsBytes, s.cfg, uint32(len(s.grid.activeLights)), viewportW, viewportH, near, far, ambient, s.grid.SliceDepths()) + encodeClusterParams(&s.paramsBytes, s.cfg, uint32(len(s.grid.activeLights)), viewportW, viewportH, near, far, s.grid.SliceDepths()) dev.WriteBuffer(s.paramsBuf, 0, s.paramsBytes[:]) active := s.grid.activeLights if len(active) > 0 { - nBytes := len(active) * ClusterLightGPUSize for i := range active { encodeClusterLightGPU(s.lightsBytes[i*ClusterLightGPUSize:], active[i]) } - dev.WriteBuffer(s.lightsBuf, 0, s.lightsBytes[:nBytes]) - } - - offsets := s.grid.offsets - indices := s.grid.lightIndices - maxIdx := uint32(s.indicesCap) - for i, oc := range offsets { - off := oc.Offset - cnt := oc.Count - if off >= maxIdx { - off = 0 - cnt = 0 - } else if off+cnt > maxIdx { - cnt = maxIdx - off - } + dev.WriteBuffer(s.lightsBuf, 0, s.lightsBytes[:len(active)*ClusterLightGPUSize]) + } + + // Every cell holds at most MaxLightsPerCluster indices, so the packed list always fits the indices buffer. + for i, oc := range s.grid.offsets { base := i * ClusterCellGPUSize - binary.LittleEndian.PutUint32(s.cellsBytes[base+0:], off) - binary.LittleEndian.PutUint32(s.cellsBytes[base+4:], cnt) + binary.LittleEndian.PutUint32(s.cellsBytes[base+0:], oc.Offset) + binary.LittleEndian.PutUint32(s.cellsBytes[base+4:], oc.Count) binary.LittleEndian.PutUint32(s.cellsBytes[base+8:], 0) binary.LittleEndian.PutUint32(s.cellsBytes[base+12:], 0) } dev.WriteBuffer(s.cellsBuf, 0, s.cellsBytes) - if len(indices) > 0 { - nIdx := min(len(indices), s.indicesCap) - for i := range nIdx { - binary.LittleEndian.PutUint32(s.indicesBytes[i*4:], indices[i]) + if indices := s.grid.lightIndices; len(indices) > 0 { + for i, idx := range indices { + binary.LittleEndian.PutUint32(s.indicesBytes[i*4:], idx) } - dev.WriteBuffer(s.indicesBuf, 0, s.indicesBytes[:nIdx*4]) + dev.WriteBuffer(s.indicesBuf, 0, s.indicesBytes[:len(indices)*4]) } - - return stats + return stats, nil } -// UpdateCamera is a convenience wrapper around [ClusteredLightSystem.Update] extracting view, projection, near, and far from cam. -func (s *ClusteredLightSystem) UpdateCamera(dev *gpu.Device, cam *scene3d.Camera, viewportW, viewportH float32, ambient math3d.Vec3, lights []ClusterLight) ClusterStats { +// UpdateCamera is [ClusteredLightSystem.Update] with view, projection, near, and far taken from cam. +func (s *ClusteredLightSystem) UpdateCamera(dev *gpu.Device, cam *scene3d.Camera, viewportW, viewportH float32, rig LightRig, lights []ClusterLight) (ClusterStats, error) { if cam == nil { - return ClusterStats{} + return ClusterStats{}, nil } near := cam.Projection.Near far := cam.Projection.Far @@ -1587,7 +1505,7 @@ func (s *ClusteredLightSystem) UpdateCamera(dev *gpu.Device, cam *scene3d.Camera } else if far <= near { far = near + 1000 } - return s.Update(dev, cam.ViewMatrix(), cam.ProjMatrix(), near, far, viewportW, viewportH, ambient, lights) + return s.Update(dev, cam.ViewMatrix(), cam.ProjMatrix(), near, far, viewportW, viewportH, rig, lights) } // Close releases all GPU resources owned by s now instead of when their scope is disposed. Safe to call on nil or more than once. @@ -1596,7 +1514,7 @@ func (s *ClusteredLightSystem) Close() error { return nil } var err error - for _, c := range []interface{ Close() error }{s.group, s.layout, s.indicesBuf, s.cellsBuf, s.lightsBuf, s.paramsBuf} { + for _, c := range []interface{ Close() error }{s.group, s.layout, s.indicesBuf, s.cellsBuf, s.lightsBuf, s.paramsBuf, s.rigBuf} { if c == nil { continue } @@ -1649,7 +1567,7 @@ func encodeClusterLightGPU(dst []byte, l ClusterLight) { clusterPutFloat32LE(dst[60:], l.InnerConeCos) } -func encodeClusterParams(dst *[ClusterParamsUniformSize]byte, cfg ClusterConfig, lightCount uint32, viewportW, viewportH, near, far float32, ambient math3d.Vec3, sliceDepths []float32) { +func encodeClusterParams(dst *[ClusterParamsUniformSize]byte, cfg ClusterConfig, lightCount uint32, viewportW, viewportH, near, far float32, sliceDepths []float32) { clear(dst[:]) // grid_info: vec4 binary.LittleEndian.PutUint32(dst[0:], uint32(cfg.TilesX)) @@ -1661,28 +1579,19 @@ func encodeClusterParams(dst *[ClusterParamsUniformSize]byte, cfg ClusterConfig, clusterPutFloat32LE(dst[20:], viewportH) clusterPutFloat32LE(dst[24:], near) clusterPutFloat32LE(dst[28:], far) - // ambient: vec4 - clusterPutFloat32LE(dst[32:], ambient.X) - clusterPutFloat32LE(dst[36:], ambient.Y) - clusterPutFloat32LE(dst[40:], ambient.Z) - clusterPutFloat32LE(dst[44:], 0) - // slice_depths: array, 17> (68 float32 slots starting at byte 48) + // slice_depths: array, 17> (68 float32 slots starting at byte 32) n := min(len(sliceDepths), MaxClusterSlicesZ+1) for i := range n { - clusterPutFloat32LE(dst[48+i*4:], sliceDepths[i]) + clusterPutFloat32LE(dst[32+i*4:], sliceDepths[i]) } } -func encodeFallbackUniform(dst *[ClusteredFallbackUniformSize]byte, ambient math3d.Vec3, lights []ClusterLight) { +func encodeFallbackUniform(dst *[ClusteredFallbackUniformSize]byte, lights []ClusterLight) { clear(dst[:]) n := min(len(lights), MaxFallbackLights) binary.LittleEndian.PutUint32(dst[0:], uint32(n)) - clusterPutFloat32LE(dst[16:], ambient.X) - clusterPutFloat32LE(dst[20:], ambient.Y) - clusterPutFloat32LE(dst[24:], ambient.Z) - clusterPutFloat32LE(dst[28:], 0) for i := range n { - encodeClusterLightGPU(dst[32+i*ClusterLightGPUSize:], lights[i]) + encodeClusterLightGPU(dst[16+i*ClusterLightGPUSize:], lights[i]) } } diff --git a/packages/game/render3d/clustered_test.go b/packages/game/render3d/clustered_test.go index 9053dea4..c8771f5c 100644 --- a/packages/game/render3d/clustered_test.go +++ b/packages/game/render3d/clustered_test.go @@ -16,6 +16,8 @@ import ( "github.com/nsgo-dev/nsgo/nsgotest" ) +var clusterTestMat = render3d.PBRMaterial{BaseColor: math3d.Vec3{X: 0.9, Y: 0.9, Z: 0.9}, Roughness: 0.6} + func clusterTestFloorMesh(half float32) render3d.Mesh { up := math3d.Vec3Up() return render3d.Mesh{ @@ -52,33 +54,27 @@ func clusterTest256PointLights() []render3d.ClusterLight { idx := gz*16 + gx x := -15.0 + float32(gx)*2.0 z := -15.0 + float32(gz)*2.0 - col := palette[idx%len(palette)] - lights = append(lights, render3d.NewPointClusterLight( - math3d.Vec3{X: x, Y: 1.25, Z: z}, - col, - 1.8, - 2.8, - )) + lights = append(lights, render3d.NewPointClusterLight(math3d.Vec3{X: x, Y: 1.25, Z: z}, palette[idx%len(palette)], 5.5, 2.8)) } } return lights } -func clusterTestClampByte(v float32) uint8 { - if v <= 0 { - return 0 - } - if v >= 1 { - return 255 +// clusterTestRig is a LightRig with ambient, a dim sun and one rig point light, shaded together with the clustered lights. +func clusterTestRig() render3d.LightRig { + return render3d.LightRig{ + Ambient: render3d.AmbientLight{Color: math3d.Vec3{X: 0.2, Y: 0.2, Z: 0.25}, Intensity: 0.2}, + Directional: []render3d.DirectionalLight{{Direction: math3d.Vec3{X: 0.3, Y: -1, Z: -0.2}, Color: math3d.Vec3{X: 1, Y: 0.95, Z: 0.9}, Intensity: 0.3}}, + Point: []render3d.PointLight{{Position: math3d.Vec3{X: 6, Y: 2, Z: 4}, Color: math3d.Vec3{X: 0.6, Y: 0.6, Z: 1}, Intensity: 4, Range: 6}}, } - return uint8(math.Round(float64(v) * 255.0)) } -func clusterTestVec3ToRGBA(v math3d.Vec3) color.RGBA { +func clusterTestSRGB(lin math3d.Vec3) color.RGBA { + srgb := render3d.LinearToSRGB(lin) return color.RGBA{ - R: clusterTestClampByte(v.X), - G: clusterTestClampByte(v.Y), - B: clusterTestClampByte(v.Z), + R: uint8(math.Round(float64(srgb.X) * 255)), + G: uint8(math.Round(float64(srgb.Y) * 255)), + B: uint8(math.Round(float64(srgb.Z) * 255)), A: 255, } } @@ -94,42 +90,73 @@ func clusterTestAssertPixelNear(t *testing.T, img *image.RGBA, x, y int, want co return d } if diff(got.R, want.R) > tol || diff(got.G, want.G) > tol || diff(got.B, want.B) > tol || diff(got.A, want.A) > tol { - t.Errorf("%s at (%d,%d): got RGBA(%d,%d,%d,%d), want RGBA(%d,%d,%d,%d) ±%d", - label, x, y, got.R, got.G, got.B, got.A, want.R, want.G, want.B, want.A, tol) + t.Errorf("%s at (%d,%d): got RGBA(%d,%d,%d,%d), want RGBA(%d,%d,%d,%d) ±%d", label, x, y, got.R, got.G, got.B, got.A, want.R, want.G, want.B, want.A, tol) + } +} + +func clusterTestAssertVecNear(t *testing.T, got, want math3d.Vec3, label string) { + t.Helper() + near := func(a, b float32) bool { return math.Abs(float64(a-b)) <= 1e-4*(1+math.Abs(float64(b))) } + if !near(got.X, want.X) || !near(got.Y, want.Y) || !near(got.Z, want.Z) { + t.Fatalf("%s: got %v, want %v", label, got, want) } } -func clusterTestBuildPipeline(t *testing.T, cx *core.Scope, dev *gpu.Device, camLayout *gpu.BindGroupLayout, sys *render3d.ClusteredLightSystem, depth gpu.TextureFormat) *gpu.Pipeline { +// clusterTestGPU holds the camera, per-draw and pipeline resources a clustered draw needs besides the ClusteredLightSystem. +type clusterTestGPU struct { + cam *render3d.CameraBuffer + draw *render3d.PBRDrawBuffer + pipe *gpu.Pipeline +} + +func newClusterTestGPU(t *testing.T, cx *core.Scope, dev *gpu.Device, sys *render3d.ClusteredLightSystem) clusterTestGPU { t.Helper() - mod, err := gpu.CompileWGSL(sys.WGSL()) + camBuf, err := render3d.NewCameraBuffer(cx, dev) if err != nil { - t.Fatalf("CompileWGSL: %v", err) - } - layouts := make([]*gpu.BindGroupLayout, render3d.ClusteredLightGroup+1) - layouts[render3d.CameraGroup] = camLayout - layouts[render3d.ClusteredLightGroup] = sys.Layout() - - desc := gpu.PipelineDesc{ - Label: "clustered-lit", - Vertex: gpu.ShaderStage{Module: mod, EntryPoint: "vs_main"}, - Fragment: gpu.ShaderStage{Module: mod, EntryPoint: "fs_main"}, - Layouts: layouts, - VertexBuffers: []gpu.VertexBufferLayout{render3d.MeshVertexLayout()}, - Primitive: gpu.PrimitiveState{Topology: gpu.TopologyTriangleList, CullMode: gpu.CullNone}, - Targets: []gpu.ColorTargetState{{Format: dev.SurfaceFormat(), WriteMask: gpu.ColorWriteAll}}, - } - if depth != gpu.FormatUndefined { - desc.DepthStencil = &gpu.DepthStencilState{ - Format: depth, - DepthWrite: true, - DepthCompare: gpu.CompareLess, - } + t.Fatalf("NewCameraBuffer: %v", err) } - pipe, err := dev.CreatePipeline(cx, desc) + drawBuf, err := render3d.NewPBRDrawBuffer(cx, dev, nil, render3d.NewPBRDrawUniform(math3d.Mat4Identity(), clusterTestMat), false) if err != nil { - t.Fatalf("CreatePipeline: %v", err) + t.Fatalf("NewPBRDrawBuffer: %v", err) } - return pipe + pipe, err := render3d.NewClusteredLitPBRPipeline(cx, dev, camBuf.Layout(), sys, drawBuf.Layout(), gpu.FormatDepth24Plus) + if err != nil { + t.Fatalf("NewClusteredLitPBRPipeline: %v", err) + } + if cx == nil { + t.Cleanup(func() { + _ = pipe.Close() + _ = drawBuf.Close() + _ = camBuf.Close() + }) + } + return clusterTestGPU{cam: camBuf, draw: drawBuf, pipe: pipe} +} + +func (g clusterTestGPU) record(pass *gpu.RenderPass, sys *render3d.ClusteredLightSystem, mesh *render3d.GPUMesh) { + pass.SetPipeline(g.pipe) + pass.SetBindGroup(render3d.CameraGroup, g.cam.BindGroup()) + sys.Bind(pass) + pass.SetBindGroup(render3d.PBRDrawGroup, g.draw.BindGroup()) + mesh.Draw(pass) +} + +func clusterTestRenderSoftware(t *testing.T, sr *gpu.SoftwareRenderer, g clusterTestGPU, sys *render3d.ClusteredLightSystem, mesh *render3d.GPUMesh) *image.RGBA { + t.Helper() + dev := sr.Device() + enc := dev.BeginEncoder() + pass := enc.BeginRenderPass(gpu.RenderPassDesc{ + ColorAttachments: []gpu.ColorAttachment{{LoadOp: gpu.LoadClear, StoreOp: gpu.StoreStore, ClearColor: core.RGB(0x000000)}}, + DepthStencil: &gpu.DepthStencilAttachment{DepthLoadOp: gpu.LoadClear, DepthStoreOp: gpu.StoreDiscard, ClearDepth: 1}, + }) + g.record(pass, sys, mesh) + pass.End() + dev.Submit(enc.Finish()) + sr.WaitIdle() + if err := sr.LastError(); err != nil { + t.Fatalf("software renderer: %v", err) + } + return sr.Image() } func clusterTestWorldPointAtPixel(cam *scene3d.Camera, px, py, w, h float32) (math3d.Vec3, bool) { @@ -145,6 +172,15 @@ func clusterTestWorldPointAtPixel(cam *scene3d.Camera, px, py, w, h float32) (ma return ray.At(t), true } +func clusterTestUpdate(t *testing.T, sys *render3d.ClusteredLightSystem, dev *gpu.Device, cam *scene3d.Camera, w, h float32, rig render3d.LightRig, lights []render3d.ClusterLight) render3d.ClusterStats { + t.Helper() + stats, err := sys.UpdateCamera(dev, cam, w, h, rig, lights) + if err != nil { + t.Fatalf("UpdateCamera: %v", err) + } + return stats +} + func TestClusterConfigAndLightValidation(t *testing.T) { if err := (render3d.ClusterConfig{}).Validate(); err != nil { t.Fatalf("zero ClusterConfig should apply defaults and validate: %v", err) @@ -163,7 +199,10 @@ func TestClusterConfigAndLightValidation(t *testing.T) { {"SlicesZ too large", render3d.ClusterConfig{SlicesZ: render3d.MaxClusterSlicesZ + 1}}, {"negative SlicesZ", render3d.ClusterConfig{SlicesZ: -1}}, {"negative MaxLights", render3d.ClusterConfig{MaxLights: -5}}, + {"MaxLights too large", render3d.ClusterConfig{MaxLights: render3d.MaxClusterLights + 1}}, {"negative MaxLightsPerCluster", render3d.ClusterConfig{MaxLightsPerCluster: -1}}, + {"MaxLightsPerCluster above MaxLights", render3d.ClusterConfig{MaxLights: 8, MaxLightsPerCluster: 9}}, + {"index slots overflow", render3d.ClusterConfig{TilesX: 64, TilesY: 64, SlicesZ: 64, MaxLights: 4096, MaxLightsPerCluster: 4096}}, {"FallbackMaxLights too large", render3d.ClusterConfig{FallbackMaxLights: render3d.MaxFallbackLights + 1}}, {"negative FallbackMaxLights", render3d.ClusterConfig{FallbackMaxLights: -1}}, } @@ -209,6 +248,63 @@ func TestClusterConfigAndLightValidation(t *testing.T) { } } +func TestClusterLightFromPointAndSpotMatchLightRigAttenuation(t *testing.T) { + ranged := render3d.PointLight{Position: math3d.Vec3{X: 1, Y: 2, Z: -1}, Color: math3d.Vec3{X: 1, Y: 0.5, Z: 0.25}, Intensity: 3, Range: 5} + cl, err := render3d.ClusterLightFromPoint(ranged) + if err != nil { + t.Fatalf("ClusterLightFromPoint: %v", err) + } + if cl.Kind != render3d.ClusterLightPoint || cl.Range != 5 { + t.Fatalf("ClusterLightFromPoint = %+v, want a point light with Range 5", cl) + } + spot := render3d.SpotLight{Position: math3d.Vec3{Y: 4}, Direction: math3d.Vec3{X: 0.2, Y: -1}, Color: math3d.Vec3{X: 0.5, Y: 1, Z: 0.5}, Intensity: 8, Range: 9, InnerConeAngle: 0.2, OuterConeAngle: 0.6} + cs, err := render3d.ClusterLightFromSpot(spot) + if err != nil { + t.Fatalf("ClusterLightFromSpot: %v", err) + } + for _, p := range []math3d.Vec3{{}, {X: 0.5, Z: 0.3}, {X: 1.5, Y: 0.2, Z: -1}, {X: 3}, {X: -2, Z: 2}} { + _, got := render3d.EvaluateLightAttenuation(cl, p) + want := render3d.PointLightAttenuation(ranged.Position.Sub(p).LenSq(), ranged.Range) * ranged.Intensity + if math.Abs(float64(got-want)) > 1e-5*(1+float64(want)) { + t.Fatalf("point attenuation at %v = %v, want %v", p, got, want) + } + _, got = render3d.EvaluateLightAttenuation(cs, p) + want = spot.Attenuation(p) * spot.Intensity + if math.Abs(float64(got-want)) > 1e-5*(1+float64(want)) { + t.Fatalf("spot attenuation at %v = %v, want %v", p, got, want) + } + } + + // Range 0 is unbounded in a LightRig; the converters derive the distance where the radiance falls to ClusterRangeCutoff. + unbounded := render3d.PointLight{Position: math3d.Vec3{Y: 1}, Color: math3d.Vec3{X: 0.5, Y: 1, Z: 0.25}, Intensity: 4} + cu, err := render3d.ClusterLightFromPoint(unbounded) + if err != nil { + t.Fatalf("ClusterLightFromPoint(unbounded): %v", err) + } + if want := float32(math.Sqrt(4 * 1 / render3d.ClusterRangeCutoff)); math.Abs(float64(cu.Range-want)) > 1e-3 { + t.Fatalf("derived range = %v, want %v", cu.Range, want) + } + if err := cu.Validate(); err != nil { + t.Fatalf("converted unbounded light fails Validate: %v", err) + } + unboundedSpot := spot + unboundedSpot.Range = 0 + if c, err := render3d.ClusterLightFromSpot(unboundedSpot); err != nil || c.Range <= 0 { + t.Fatalf("ClusterLightFromSpot(unbounded) = %+v, %v; want a positive range", c, err) + } + dark, err := render3d.ClusterLightFromPoint(render3d.PointLight{Color: math3d.Vec3{X: 1}}) + if err != nil || dark.Validate() != nil { + t.Fatalf("zero-intensity light converts to %+v, %v; want a valid record", dark, err) + } + + if _, err := render3d.ClusterLightFromPoint(render3d.PointLight{Color: math3d.Vec3{X: -1}, Intensity: 1}); !errors.Is(err, render3d.ErrInvalidLight) { + t.Fatalf("invalid point light error = %v, want ErrInvalidLight", err) + } + if _, err := render3d.ClusterLightFromSpot(render3d.SpotLight{Direction: math3d.Vec3{Y: -1}, Color: math3d.Vec3{X: 1}, Intensity: 1, InnerConeAngle: 0.5, OuterConeAngle: 0.4}); !errors.Is(err, render3d.ErrInvalidLight) { + t.Fatalf("invalid spot light error = %v, want ErrInvalidLight", err) + } +} + func TestClusterGridLogarithmicSlicesAndBinarySearch(t *testing.T) { grid, err := render3d.NewClusterGrid(render3d.DefaultClusterConfig()) if err != nil { @@ -231,7 +327,6 @@ func TestClusterGridLogarithmicSlicesAndBinarySearch(t *testing.T) { } } - // Verify SliceForDepth matches exact logarithmic intervals. if got := grid.SliceForDepth(near * 0.5); got != 0 { t.Fatalf("SliceForDepth(before near) = %d, want 0", got) } @@ -289,13 +384,12 @@ func TestClusterGridCullingSpotBoundsAndZeroAllocs(t *testing.T) { ptStats := grid.AssignLights(view, proj, 0.5, 50, pointAtCenter) spStats := grid.AssignLights(view, proj, 0.5, 50, spotAtCenter) if spStats.ActiveClusters == 0 || spStats.ActiveClusters >= ptStats.ActiveClusters { - t.Fatalf("expected narrow spot (%d clusters) to occupy >0 and fewer clusters than equal-range point (%d clusters)", - spStats.ActiveClusters, ptStats.ActiveClusters) + t.Fatalf("expected narrow spot (%d clusters) to occupy >0 and fewer clusters than equal-range point (%d clusters)", spStats.ActiveClusters, ptStats.ActiveClusters) } // 3. Light straddling the camera / near plane must still assign clusters (no false negative). nearLight := []render3d.ClusterLight{ - render3d.NewPointClusterLight(math3d.Vec3{Y: 2, Z: 10}, math3d.Vec3{X: 1}, 2, 4), // centered on camera! + render3d.NewPointClusterLight(math3d.Vec3{Y: 2, Z: 10}, math3d.Vec3{X: 1}, 2, 4), // centered on camera } nearStats := grid.AssignLights(view, proj, 0.5, 50, nearLight) if nearStats.VisibleLights != 1 || nearStats.ActiveClusters == 0 { @@ -304,7 +398,6 @@ func TestClusterGridCullingSpotBoundsAndZeroAllocs(t *testing.T) { // 4. Steady-state 256 lights AssignLights must perform zero heap allocations. lights256 := clusterTest256PointLights() - // Warm up once (builds frustum cache & sizes lightIndices). grid.AssignLights(view, proj, 0.5, 50, lights256) allocs := testing.AllocsPerRun(50, func() { grid.AssignLights(view, proj, 0.5, 50, lights256) @@ -314,7 +407,46 @@ func TestClusterGridCullingSpotBoundsAndZeroAllocs(t *testing.T) { } } -func TestClustered256PointLightsParityAndBudget(t *testing.T) { +func TestClusterGridTruncationKeepsInputOrder(t *testing.T) { + cfg := render3d.ClusterConfig{TilesX: 4, TilesY: 4, SlicesZ: 4, MaxLights: 4, MaxLightsPerCluster: 2} + grid, err := render3d.NewClusterGrid(cfg) + if err != nil { + t.Fatalf("NewClusterGrid: %v", err) + } + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{Y: 2, Z: 10}, math3d.DegToRad(60), 1, 0.5, 50) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + + // Ten overlapping lights in front of the camera: the grid keeps the first four (MaxLights) and every shared cell keeps the first two of those (MaxLightsPerCluster). + lights := make([]render3d.ClusterLight, 10) + for i := range lights { + lights[i] = render3d.NewPointClusterLight(math3d.Vec3{X: float32(i) * 0.01, Y: 1}, math3d.Vec3{X: 1, Y: 1, Z: 1}, 1, 3) + } + st := grid.AssignLights(cam.ViewMatrix(), cam.ProjMatrix(), 0.5, 50, lights) + if st.VisibleLights != 4 || st.TruncatedLights != 6 || st.CulledLights != 0 { + t.Fatalf("stats = %+v, want 4 visible, 6 truncated, 0 culled", st) + } + if st.TruncatedClusters == 0 || st.MaxClusterLights != 2 { + t.Fatalf("stats = %+v, want truncated clusters holding MaxLightsPerCluster (2) lights", st) + } + for i, l := range grid.ActiveLights() { + if l.Position != lights[i].Position { + t.Fatalf("active light %d = %v, want input light %d at %v", i, l.Position, i, lights[i].Position) + } + } + for c, oc := range grid.Offsets() { + if oc.Count > 2 { + t.Fatalf("cluster %d holds %d lights, want at most 2", c, oc.Count) + } + for _, idx := range grid.LightIndices()[oc.Offset : oc.Offset+oc.Count] { + if idx > 1 { + t.Fatalf("cluster %d holds light %d, want only the first two lights in input order", c, idx) + } + } + } +} + +// TestClustered256PointLightsParity renders a floor lit by a LightRig plus 256 clustered point lights through NewClusteredLitPBRPipeline and checks that the grid lookup misses no light and that the pixels match the CPU reference. +func TestClustered256PointLightsParity(t *testing.T) { const ( viewW = 128 viewH = 96 @@ -323,7 +455,7 @@ func TestClustered256PointLightsParityAndBudget(t *testing.T) { ) cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 14, Z: 18}, math3d.DegToRad(50), float32(viewW)/float32(viewH), near, far) cam.LookAt(math3d.Vec3{X: 0, Y: 0, Z: 0}, math3d.Vec3Up()) - ambient := math3d.Vec3{X: 0.04, Y: 0.04, Z: 0.05} + rig := clusterTestRig() lights := clusterTest256PointLights() sr := gpu.NewSoftwareRenderer(viewW, viewH, gpu.FormatDepth24Plus) @@ -333,19 +465,11 @@ func TestClustered256PointLightsParityAndBudget(t *testing.T) { if !render3d.DeviceSupportsClusteredLighting(dev) { t.Fatal("default SoftwareRenderer must support clustered lighting") } - - camBuf, err := render3d.NewCameraBuffer(nil, dev) - if err != nil { - t.Fatalf("NewCameraBuffer: %v", err) - } - t.Cleanup(func() { _ = camBuf.Close() }) - sys, err := render3d.NewClusteredLightSystem(nil, dev, render3d.DefaultClusterConfig()) if err != nil { t.Fatalf("NewClusteredLightSystem: %v", err) } t.Cleanup(func() { _ = sys.Close() }) - if !sys.IsClustered() || sys.IsFallback() { t.Fatalf("expected clustered mode on full device, got clustered=%v fallback=%v", sys.IsClustered(), sys.IsFallback()) } @@ -358,65 +482,22 @@ func TestClustered256PointLightsParityAndBudget(t *testing.T) { t.Fatalf("UploadMesh: %v", err) } t.Cleanup(func() { _ = floor.Close() }) + g := newClusterTestGPU(t, nil, dev, sys) - pipe := clusterTestBuildPipeline(t, nil, dev, camBuf.Layout(), sys, gpu.FormatDepth24Plus) - t.Cleanup(func() { _ = pipe.Close() }) - - // Warm up frustum cache once, then time 256-light assignment against the 16.6ms 60fps desktop budget. - _ = sys.UpdateCamera(dev, cam, viewW, viewH, ambient, lights) - start := time.Now() - stats := sys.UpdateCamera(dev, cam, viewW, viewH, ambient, lights) - assignElapsed := time.Since(start) - + stats := clusterTestUpdate(t, sys, dev, cam, viewW, viewH, rig, lights) if stats.InputLights != 256 { t.Fatalf("InputLights = %d, want 256", stats.InputLights) } - if stats.VisibleLights < 100 { - t.Fatalf("expected >= 100 visible point lights across the 16x16 grid, got %d (stats=%+v)", stats.VisibleLights, stats) - } - if stats.ActiveClusters == 0 { - t.Fatalf("expected active clusters > 0, got %+v", stats) - } - if assignElapsed > 16*time.Millisecond { - t.Fatalf("256-light UpdateCamera took %v, exceeding 16ms frame budget", assignElapsed) + if stats.VisibleLights < 100 || stats.ActiveClusters == 0 || stats.TruncatedLights != 0 || stats.TruncatedClusters != 0 { + t.Fatalf("expected >= 100 visible lights in active clusters with no truncation, got %+v", stats) } - // Render the floor lit by all 256 clustered point lights. - camBuf.WriteCamera(cam) - enc := dev.BeginEncoder() - pass := enc.BeginRenderPass(gpu.RenderPassDesc{ - Label: "clustered-256", - ColorAttachments: []gpu.ColorAttachment{{ - LoadOp: gpu.LoadClear, - StoreOp: gpu.StoreStore, - ClearColor: core.RGB(0x050608), - }}, - DepthStencil: &gpu.DepthStencilAttachment{ - DepthLoadOp: gpu.LoadClear, - DepthStoreOp: gpu.StoreDiscard, - ClearDepth: 1, - }, - }) - pass.SetPipeline(pipe) - pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) - sys.Bind(pass, render3d.ClusteredLightGroup) - floor.Draw(pass) - pass.End() - dev.Submit(enc.Finish()) - sr.WaitIdle() - if err := sr.LastError(); err != nil { - t.Fatalf("software renderer: %v", err) - } + g.cam.WriteCamera(cam) + img := clusterTestRenderSoftware(t, sr, g, sys, floor) - img := sr.Image() view := cam.ViewMatrix() proj := cam.ProjMatrix() - white := math3d.Vec3{X: 1, Y: 1, Z: 1} up := math3d.Vec3Up() - - // Sample a 7x5 grid across the visible floor and assert BOTH: - // 1. Pure-Go clustered evaluation matches brute-force EvaluateDirectLights (zero false culls across 256 lights). - // 2. GPU rasterized pixel matches pure-Go analytic reference within ±3/255. litSamples := 0 for sy := 24; sy <= 80; sy += 14 { for sx := 20; sx <= 108; sx += 14 { @@ -424,23 +505,19 @@ func TestClustered256PointLightsParityAndBudget(t *testing.T) { if !ok || math.Abs(float64(worldPt.X)) > 19 || math.Abs(float64(worldPt.Z)) > 19 { continue } - direct := render3d.EvaluateDirectLights(worldPt, up, white, ambient, lights) - clustered := render3d.EvaluateClusteredLights(worldPt, up, white, ambient, sys.Grid(), view, proj, viewW, viewH) - if math.Abs(float64(direct.X-clustered.X)) > 1e-4 || - math.Abs(float64(direct.Y-clustered.Y)) > 1e-4 || - math.Abs(float64(direct.Z-clustered.Z)) > 1e-4 { - t.Fatalf("CPU clustered vs direct mismatch at pixel (%d,%d) world %v: clustered=%v direct=%v", - sx, sy, worldPt, clustered, direct) - } - wantRGBA := clusterTestVec3ToRGBA(direct) - clusterTestAssertPixelNear(t, img, sx, sy, wantRGBA, 3, "clustered-256") - if wantRGBA.R > 25 || wantRGBA.G > 25 || wantRGBA.B > 25 { + viewDir := cam.Pos.Sub(worldPt) + direct := render3d.ShadeClusteredPoint(worldPt, up, viewDir, clusterTestMat, rig, lights) + clustered := render3d.ShadeClusteredGridPoint(worldPt, up, viewDir, clusterTestMat, rig, sys.Grid(), view, proj, viewW, viewH) + clusterTestAssertVecNear(t, clustered, direct, "grid lookup vs brute force") + want := clusterTestSRGB(direct) + clusterTestAssertPixelNear(t, img, sx, sy, want, 3, "clustered-256") + if base := clusterTestSRGB(render3d.ShadePoint(worldPt, up, viewDir, clusterTestMat, rig)); int(want.R)+int(want.G)+int(want.B) > int(base.R)+int(base.G)+int(base.B)+30 { litSamples++ } } } if litSamples < 10 { - t.Fatalf("expected at least 10 visibly lit floor sample points, got %d", litSamples) + t.Fatalf("expected at least 10 samples visibly lit by clustered lights, got %d", litSamples) } } @@ -453,78 +530,44 @@ func TestClusteredMixedPointAndSpotLightsGPU(t *testing.T) { ) cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 10, Z: 10}, math3d.DegToRad(50), 1, near, far) cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) - ambient := math3d.Vec3{X: 0.02, Y: 0.02, Z: 0.02} + rig := render3d.LightRig{Ambient: render3d.AmbientLight{Color: math3d.Vec3{X: 1, Y: 1, Z: 1}, Intensity: 0.02}} + spot, err := render3d.ClusterLightFromSpot(render3d.SpotLight{ + Position: math3d.Vec3{X: 3, Y: 3}, Direction: math3d.Vec3{Y: -1}, Color: math3d.Vec3{X: 0.1, Y: 1, Z: 0.1}, + Intensity: 24, Range: 7, InnerConeAngle: math3d.DegToRad(15), OuterConeAngle: math3d.DegToRad(25), + }) + if err != nil { + t.Fatalf("ClusterLightFromSpot: %v", err) + } lights := []render3d.ClusterLight{ - // Red point light on the left (-3, 1.5, 0). - render3d.NewPointClusterLight(math3d.Vec3{X: -3, Y: 1.5, Z: 0}, math3d.Vec3{X: 1, Y: 0.1, Z: 0.1}, 3.0, 4.5), - // Green downward spotlight on the right (3, 3, 0) with a tight cone (15 deg inner, 25 deg outer). - render3d.NewSpotClusterLight( - math3d.Vec3{X: 3, Y: 3, Z: 0}, - math3d.Vec3{Y: -1}, - math3d.Vec3{X: 0.1, Y: 1, Z: 0.1}, - 8.0, 7.0, - math3d.DegToRad(15), math3d.DegToRad(25), - ), - // Blue spotlight at center aiming UP away from the floor -> must contribute zero to the floor! - render3d.NewSpotClusterLight( - math3d.Vec3{X: 0, Y: 2, Z: 0}, - math3d.Vec3{Y: 1}, - math3d.Vec3{X: 0.1, Y: 0.2, Z: 1}, - 10.0, 8.0, - math3d.DegToRad(20), math3d.DegToRad(35), - ), + // Red point light on the left. + render3d.NewPointClusterLight(math3d.Vec3{X: -3, Y: 1.5, Z: 0}, math3d.Vec3{X: 1, Y: 0.1, Z: 0.1}, 5.0, 4.5), + // Green downward spot light on the right with a 15 to 25 degree cone. + spot, + // Blue spot light at the center aiming up, away from the floor: it must add nothing. + render3d.NewSpotClusterLight(math3d.Vec3{X: 0, Y: 2, Z: 0}, math3d.Vec3{Y: 1}, math3d.Vec3{X: 0.1, Y: 0.2, Z: 1}, 30.0, 8.0, math3d.DegToRad(20), math3d.DegToRad(35)), } sr := gpu.NewSoftwareRenderer(viewW, viewH, gpu.FormatDepth24Plus) t.Cleanup(sr.Close) dev := sr.Device() - - camBuf, err := render3d.NewCameraBuffer(nil, dev) - if err != nil { - t.Fatalf("NewCameraBuffer: %v", err) - } - t.Cleanup(func() { _ = camBuf.Close() }) - sys, err := render3d.NewClusteredLightSystem(nil, dev, render3d.DefaultClusterConfig()) if err != nil { t.Fatalf("NewClusteredLightSystem: %v", err) } t.Cleanup(func() { _ = sys.Close() }) - floor, err := render3d.UploadMesh(nil, dev, clusterTestFloorMesh(10), render3d.MeshUpload{}) if err != nil { t.Fatalf("UploadMesh: %v", err) } t.Cleanup(func() { _ = floor.Close() }) + g := newClusterTestGPU(t, nil, dev, sys) - pipe := clusterTestBuildPipeline(t, nil, dev, camBuf.Layout(), sys, gpu.FormatDepth24Plus) - t.Cleanup(func() { _ = pipe.Close() }) - - sys.UpdateCamera(dev, cam, viewW, viewH, ambient, lights) - camBuf.WriteCamera(cam) - - enc := dev.BeginEncoder() - pass := enc.BeginRenderPass(gpu.RenderPassDesc{ - ColorAttachments: []gpu.ColorAttachment{{LoadOp: gpu.LoadClear, StoreOp: gpu.StoreStore, ClearColor: core.RGB(0x000000)}}, - DepthStencil: &gpu.DepthStencilAttachment{DepthLoadOp: gpu.LoadClear, DepthStoreOp: gpu.StoreDiscard, ClearDepth: 1}, - }) - pass.SetPipeline(pipe) - pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) - sys.Bind(pass, render3d.ClusteredLightGroup) - floor.Draw(pass) - pass.End() - dev.Submit(enc.Finish()) - sr.WaitIdle() - if err := sr.LastError(); err != nil { - t.Fatalf("software renderer: %v", err) - } + clusterTestUpdate(t, sys, dev, cam, viewW, viewH, rig, lights) + g.cam.WriteCamera(cam) + img := clusterTestRenderSoftware(t, sr, g, sys, floor) - img := sr.Image() - white := math3d.Vec3{X: 1, Y: 1, Z: 1} up := math3d.Vec3Up() - - // Project key world points to pixel coordinates and verify exact shading. checks := []struct { name string world math3d.Vec3 @@ -545,27 +588,58 @@ func TestClusteredMixedPointAndSpotLightsGPU(t *testing.T) { if !ok { t.Fatalf("%s failed raycast", ch.name) } - want := clusterTestVec3ToRGBA(render3d.EvaluateDirectLights(exactWorld, up, white, ambient, lights)) + want := clusterTestSRGB(render3d.ShadeClusteredPoint(exactWorld, up, cam.Pos.Sub(exactWorld), clusterTestMat, rig, lights)) clusterTestAssertPixelNear(t, img, px, py, want, 3, ch.name) - // Sanity checks on expected visual contrast. switch ch.name { case "under-red-point": - if want.R < 150 || want.G > 40 { + if want.R < 150 || 2*int(want.G) > int(want.R) { t.Fatalf("expected bright red under point light, got %+v", want) } case "under-green-spot-center": - if want.G < 150 || want.R > 40 { + if want.G < 150 || 2*int(want.R) > int(want.G) { t.Fatalf("expected bright green under spot light, got %+v", want) } case "under-upward-blue-spot": - if want.B > 30 { - t.Fatalf("upward spotlight should not light floor, got %+v", want) + if want.B > 50 { + t.Fatalf("upward spot light should not light the floor, got %+v", want) } } } } +func TestClusteredUpdateRejectsInvalidLights(t *testing.T) { + sr := gpu.NewSoftwareRenderer(16, 16, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + dev := sr.Device() + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{Y: 4, Z: 6}, math3d.DegToRad(50), 1, 0.5, 40) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + for _, force := range []bool{false, true} { + sys, err := render3d.NewClusteredLightSystem(nil, dev, render3d.ClusterConfig{ForceFallback: force}) + if err != nil { + t.Fatalf("NewClusteredLightSystem: %v", err) + } + // Range 0 is unbounded in a LightRig, so the clustered system refuses it instead of dropping it silently. + unbounded := render3d.NewPointClusterLight(math3d.Vec3{Y: 1}, math3d.Vec3{X: 1, Y: 1, Z: 1}, 2, 0) + if _, err := sys.UpdateCamera(dev, cam, 16, 16, render3d.LightRig{}, []render3d.ClusterLight{unbounded}); !errors.Is(err, render3d.ErrInvalidClusterLight) { + t.Fatalf("fallback=%v: Update with a Range 0 light = %v, want ErrInvalidClusterLight", force, err) + } + badRig := render3d.LightRig{Ambient: render3d.AmbientLight{Intensity: -1}} + if _, err := sys.UpdateCamera(dev, cam, 16, 16, badRig, nil); !errors.Is(err, render3d.ErrInvalidLight) { + t.Fatalf("fallback=%v: Update with a malformed rig = %v, want ErrInvalidLight", force, err) + } + converted, err := render3d.ClusterLightFromPoint(render3d.PointLight{Position: math3d.Vec3{Y: 1}, Color: math3d.Vec3{X: 1, Y: 1, Z: 1}, Intensity: 2}) + if err != nil { + t.Fatalf("ClusterLightFromPoint: %v", err) + } + st, err := sys.UpdateCamera(dev, cam, 16, 16, render3d.LightRig{}, []render3d.ClusterLight{converted}) + if err != nil || st.VisibleLights != 1 { + t.Fatalf("fallback=%v: Update with a converted unbounded light = %+v, %v; want 1 visible light", force, st, err) + } + _ = sys.Close() + } +} + func TestClusteredFallbackNoGPUComputeAndForceFallback(t *testing.T) { const ( viewW = 64 @@ -575,12 +649,12 @@ func TestClusteredFallbackNoGPUComputeAndForceFallback(t *testing.T) { ) cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 14, Z: 18}, math3d.DegToRad(50), 1, near, far) cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) - ambient := math3d.Vec3{X: 0.03, Y: 0.03, Z: 0.04} - // Start with 256 point lights across the floor plus bright foreground lights near the center so both clustered and fallback modes visibly illuminate the sampled pixels. + rig := clusterTestRig() + // 256 point lights across the floor plus bright foreground lights near the center so every mode visibly lights the sampled pixels. lights := clusterTest256PointLights() - lights[0] = render3d.NewPointClusterLight(math3d.Vec3{X: 0, Y: 1.5, Z: 0}, math3d.Vec3{X: 1, Y: 0.3, Z: 0.2}, 6.0, 6.0) - lights[1] = render3d.NewPointClusterLight(math3d.Vec3{X: -3, Y: 1.5, Z: 1}, math3d.Vec3{X: 0.2, Y: 1, Z: 0.3}, 6.0, 6.0) - lights[2] = render3d.NewPointClusterLight(math3d.Vec3{X: 3, Y: 1.5, Z: 1}, math3d.Vec3{X: 0.2, Y: 0.4, Z: 1}, 6.0, 6.0) + lights[0] = render3d.NewPointClusterLight(math3d.Vec3{X: 0, Y: 1.5, Z: 0}, math3d.Vec3{X: 1, Y: 0.3, Z: 0.2}, 18.0, 6.0) + lights[1] = render3d.NewPointClusterLight(math3d.Vec3{X: -3, Y: 1.5, Z: 1}, math3d.Vec3{X: 0.2, Y: 1, Z: 0.3}, 18.0, 6.0) + lights[2] = render3d.NewPointClusterLight(math3d.Vec3{X: 3, Y: 1.5, Z: 1}, math3d.Vec3{X: 0.2, Y: 0.4, Z: 1}, 18.0, 6.0) modes := []struct { name string @@ -589,39 +663,17 @@ func TestClusteredFallbackNoGPUComputeAndForceFallback(t *testing.T) { wantCluster bool wantCaps bool }{ - { - name: "full-clustered", - cfg: render3d.DefaultClusterConfig(), - appOpts: nil, - wantCluster: true, - wantCaps: true, - }, - { - name: "webgl2-gles3-no-compute-fallback", - cfg: render3d.DefaultClusterConfig(), - appOpts: []nsgotest.Option{nsgotest.NoGPUCompute()}, - wantCluster: false, - wantCaps: false, - }, - { - name: "force-fallback-on-full-device", - cfg: render3d.ClusterConfig{ - ForceFallback: true, - FallbackMaxLights: 8, - }, - appOpts: nil, - wantCluster: false, - wantCaps: true, - }, + {name: "full-clustered", cfg: render3d.DefaultClusterConfig(), wantCluster: true, wantCaps: true}, + {name: "webgl2-gles3-no-compute-fallback", cfg: render3d.DefaultClusterConfig(), appOpts: []nsgotest.Option{nsgotest.NoGPUCompute()}}, + {name: "force-fallback-on-full-device", cfg: render3d.ClusterConfig{ForceFallback: true, FallbackMaxLights: 8}, wantCaps: true}, } for _, m := range modes { t.Run(m.name, func(t *testing.T) { var ( - camBuf *render3d.CameraBuffer sys *render3d.ClusteredLightSystem floor *render3d.GPUMesh - pipe *gpu.Pipeline + g clusterTestGPU gotCaps bool gotStats render3d.ClusterStats ) @@ -634,10 +686,6 @@ func TestClusteredFallbackNoGPUComputeAndForceFallback(t *testing.T) { OnReady: func(dev *gpu.Device) { gotCaps = render3d.DeviceSupportsClusteredLighting(dev) var err error - camBuf, err = render3d.NewCameraBuffer(cx, dev) - if err != nil { - t.Fatalf("NewCameraBuffer: %v", err) - } sys, err = render3d.NewClusteredLightSystem(cx, dev, m.cfg) if err != nil { t.Fatalf("NewClusteredLightSystem: %v", err) @@ -646,19 +694,16 @@ func TestClusteredFallbackNoGPUComputeAndForceFallback(t *testing.T) { if err != nil { t.Fatalf("UploadMesh: %v", err) } - pipe = clusterTestBuildPipeline(t, cx, dev, camBuf.Layout(), sys, gpu.FormatDepth24Plus) + g = newClusterTestGPU(t, cx, dev, sys) }, OnFrame: func(frame *gpu.Frame) { dev := frame.Device() - camBuf.WriteCamera(cam) - gotStats = sys.UpdateCamera(dev, cam, viewW, viewH, ambient, lights) + g.cam.WriteCamera(cam) + gotStats = clusterTestUpdate(t, sys, dev, cam, viewW, viewH, rig, lights) pass := frame.BeginRenderPass(gpu.RenderPassDesc{}) pass.ClearColor(core.RGB(0x050608)) pass.ClearDepth(1) - pass.SetPipeline(pipe) - pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) - sys.Bind(pass, render3d.ClusteredLightGroup) - floor.Draw(pass) + g.record(pass, sys, floor) pass.End() frame.Submit() }, @@ -679,8 +724,6 @@ func TestClusteredFallbackNoGPUComputeAndForceFallback(t *testing.T) { t.Fatalf("GPUReadPixels: %v", err) } - white := math3d.Vec3{X: 1, Y: 1, Z: 1} - up := math3d.Vec3Up() refLights := lights if sys.IsFallback() { wantCap := m.cfg.FallbackMaxLights @@ -688,24 +731,24 @@ func TestClusteredFallbackNoGPUComputeAndForceFallback(t *testing.T) { wantCap = render3d.DefaultFallbackMaxLights } refLights = sys.FallbackLights() - if len(refLights) != wantCap { + if len(refLights) != wantCap || gotStats.VisibleLights != wantCap { t.Fatalf("fallback selected %d lights, want %d (stats=%+v)", len(refLights), wantCap, gotStats) } - if gotStats.TruncatedLights != 256-wantCap { - t.Fatalf("TruncatedLights = %d, want %d", gotStats.TruncatedLights, 256-wantCap) + if gotStats.TruncatedLights == 0 || gotStats.CulledLights+gotStats.TruncatedLights+gotStats.VisibleLights != 256 { + t.Fatalf("fallback stats %+v must split 256 lights into culled, truncated and visible with some truncated", gotStats) } } - // Verify pixel parity against analytic reference for active light set and confirm non-trivial lighting. + up := math3d.Vec3Up() litCount := 0 for _, pt := range [][2]int{{22, 32}, {32, 32}, {42, 32}, {32, 42}} { worldPt, ok := clusterTestWorldPointAtPixel(cam, float32(pt[0]), float32(pt[1]), viewW, viewH) if !ok { continue } - want := clusterTestVec3ToRGBA(render3d.EvaluateDirectLights(worldPt, up, white, ambient, refLights)) + want := clusterTestSRGB(render3d.ShadeClusteredPoint(worldPt, up, cam.Pos.Sub(worldPt), clusterTestMat, rig, refLights)) clusterTestAssertPixelNear(t, img, pt[0], pt[1], want, 3, m.name) - if want.R > 40 || want.G > 40 || want.B > 40 { + if want.R > 120 || want.G > 120 || want.B > 120 { litCount++ } } @@ -716,8 +759,31 @@ func TestClusteredFallbackNoGPUComputeAndForceFallback(t *testing.T) { } } +func TestClusteredFallbackUpdateZeroAllocs(t *testing.T) { + sr := gpu.NewSoftwareRenderer(16, 16, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + sys, err := render3d.NewClusteredLightSystem(nil, sr.Device(), render3d.ClusterConfig{ForceFallback: true}) + if err != nil { + t.Fatalf("NewClusteredLightSystem: %v", err) + } + t.Cleanup(func() { _ = sys.Close() }) + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{Y: 14, Z: 18}, math3d.DegToRad(50), 16.0/9.0, 0.5, 60) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + view, proj := cam.ViewMatrix(), cam.ProjMatrix() + rig := clusterTestRig() + lights := clusterTest256PointLights() + update := func() { + if _, err := sys.Update(nil, view, proj, 0.5, 60, 1280, 720, rig, lights); err != nil { + t.Fatalf("Update: %v", err) + } + } + update() + if allocs := testing.AllocsPerRun(50, update); allocs != 0 { + t.Fatalf("steady-state fallback Update(256 lights) allocated %.2f times/op, want 0", allocs) + } +} + func TestClusteredEmptyLightsResizeRetainedAndClose(t *testing.T) { - // 1. Nil device error & nil receiver safety. if _, err := render3d.NewClusteredLightSystem(nil, nil, render3d.DefaultClusterConfig()); err == nil { t.Fatal("expected error for nil device") } @@ -729,7 +795,6 @@ func TestClusteredEmptyLightsResizeRetainedAndClose(t *testing.T) { t.Fatalf("nil Close: %v", err) } - // 2. Empty lights + viewport resize + Retained device-loss recovery on both full and NoGPUCompute profiles. profiles := []struct { name string opts []nsgotest.Option @@ -742,14 +807,13 @@ func TestClusteredEmptyLightsResizeRetainedAndClose(t *testing.T) { const size = 48 cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 6, Z: 6}, math3d.DegToRad(50), 1, 0.5, 40) cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) - ambient := math3d.Vec3{X: 0.2, Y: 0.3, Z: 0.4} - activeLights := []render3d.ClusterLight{} // start empty, then populate + rig := render3d.LightRig{Ambient: render3d.AmbientLight{Color: math3d.Vec3{X: 0.2, Y: 0.3, Z: 0.4}, Intensity: 1}} + activeLights := []render3d.ClusterLight{} var ( - camBuf *render3d.CameraBuffer - sys *render3d.ClusteredLightSystem - floor *render3d.GPUMesh - pipe *gpu.Pipeline + sys *render3d.ClusteredLightSystem + floor *render3d.GPUMesh + g clusterTestGPU ) opts := append([]nsgotest.Option{nsgotest.Size(size, size), nsgotest.ManualFrames()}, prof.opts...) app := nsgotest.Start(t, func(cx *core.Scope) core.Node { @@ -771,42 +835,36 @@ func TestClusteredEmptyLightsResizeRetainedAndClose(t *testing.T) { t.Fatalf("UploadMesh: %v", err) } } - camBuf, err = render3d.NewCameraBuffer(cx, dev) - if err != nil { - t.Fatalf("NewCameraBuffer: %v", err) - } - pipe = clusterTestBuildPipeline(t, cx, dev, camBuf.Layout(), sys, gpu.FormatDepth24Plus) + g = newClusterTestGPU(t, cx, dev, sys) }, OnFrame: func(frame *gpu.Frame) { dev := frame.Device() w, h := dev.SurfaceSize() cam.SetViewport(float32(w), float32(h)) - camBuf.WriteCamera(cam) - sys.UpdateCamera(dev, cam, float32(w), float32(h), ambient, activeLights) + g.cam.WriteCamera(cam) + clusterTestUpdate(t, sys, dev, cam, float32(w), float32(h), rig, activeLights) pass := frame.BeginRenderPass(gpu.RenderPassDesc{}) pass.ClearColor(core.RGB(0x000000)) pass.ClearDepth(1) - pass.SetPipeline(pipe) - pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) - sys.Bind(pass, render3d.ClusteredLightGroup) - floor.Draw(pass) + g.record(pass, sys, floor) pass.End() frame.Submit() }, }) }, opts...) - // Frame 1: 0 lights -> pure ambient color. + // Frame 1: no local lights, so only the rig's ambient term lights the floor. app.Advance(16 * time.Millisecond) img, err := app.GPUReadPixels("id:ret-view") if err != nil { t.Fatalf("GPUReadPixels empty: %v", err) } - clusterTestAssertPixelNear(t, img, size/2, size/2, clusterTestVec3ToRGBA(ambient), 3, "empty-ambient") + ambientOnly := render3d.ShadeClusteredPoint(math3d.Vec3Zero(), math3d.Vec3Up(), cam.Pos, clusterTestMat, rig, nil) + clusterTestAssertPixelNear(t, img, size/2, size/2, clusterTestSRGB(ambientOnly), 3, "empty-ambient") - // Frame 2: add bright yellow light at origin. + // Frame 2: add a bright yellow light above the origin. activeLights = []render3d.ClusterLight{ - render3d.NewPointClusterLight(math3d.Vec3{Y: 1.5}, math3d.Vec3{X: 1, Y: 0.9, Z: 0.1}, 4.0, 6.0), + render3d.NewPointClusterLight(math3d.Vec3{Y: 1.5}, math3d.Vec3{X: 1, Y: 0.9, Z: 0.1}, 12.0, 6.0), } app.Advance(16 * time.Millisecond) beforeLoss, err := app.GPUReadPixels("id:ret-view") @@ -818,7 +876,7 @@ func TestClusteredEmptyLightsResizeRetainedAndClose(t *testing.T) { t.Fatalf("expected bright yellow center before loss, got %+v", centerBefore) } - // Trigger device loss and restore: retained ClusteredLightSystem must recover cleanly. + // Lose and restore the device: the retained ClusteredLightSystem must recover. firstSys := sys app.TriggerGPUDeviceLost("id:ret-view", nsgotest.GPULostContextLost, "context lost") if firstSys.Valid() { @@ -836,7 +894,6 @@ func TestClusteredEmptyLightsResizeRetainedAndClose(t *testing.T) { } clusterTestAssertPixelNear(t, afterRestore, size/2, size/2, centerBefore, 2, "after-restore") - // Close is idempotent. if err := sys.Close(); err != nil { t.Fatalf("Close: %v", err) } @@ -851,28 +908,30 @@ func TestClusteredEmptyLightsResizeRetainedAndClose(t *testing.T) { } func TestSelectFallbackLightsPrioritization(t *testing.T) { - camPos := math3d.Vec3{Z: 10} - camFwd := math3d.Vec3Forward() // (0, 0, -1) + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{Z: 10}, math3d.DegToRad(60), 1, 0.5, 100) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) lights := []render3d.ClusterLight{ - render3d.NewPointClusterLight(math3d.Vec3{Z: 20}, math3d.Vec3{X: 1}, 2, 3), // behind camera - render3d.NewPointClusterLight(math3d.Vec3{Z: 5}, math3d.Vec3{Y: 1}, 5, 6), // closest & bright in front - render3d.NewPointClusterLight(math3d.Vec3{Z: -30}, math3d.Vec3{Z: 1}, 1, 3), // far in front - render3d.NewPointClusterLight(math3d.Vec3{Z: 4}, math3d.Vec3{X: 1}, 0, 5), // inactive (zero intensity) - render3d.NewPointClusterLight(math3d.Vec3{Z: 6}, math3d.Vec3{X: 1}, 3, 6), // second best in front - } - picked := render3d.SelectFallbackLights(nil, camPos, camFwd, lights, 2) + render3d.NewPointClusterLight(math3d.Vec3{Z: 20}, math3d.Vec3{X: 1}, 2, 3), // behind the camera + render3d.NewPointClusterLight(math3d.Vec3{Z: 5}, math3d.Vec3{Y: 1}, 5, 6), // closest and bright in front + render3d.NewPointClusterLight(math3d.Vec3{Z: -30}, math3d.Vec3{Z: 1}, 1, 3), // far in front + render3d.NewPointClusterLight(math3d.Vec3{Z: 4}, math3d.Vec3{X: 1}, 0, 5), // no power + render3d.NewPointClusterLight(math3d.Vec3{Z: 6}, math3d.Vec3{X: 1}, 3, 6), // second best in front + render3d.NewPointClusterLight(math3d.Vec3{X: 60, Z: 8}, math3d.Vec3{X: 1}, 500, 6), // brightest of all, but off screen to the side + } + picked := render3d.SelectFallbackLights(nil, cam.ViewMatrix(), cam.ProjMatrix(), lights, 2) if len(picked) != 2 { t.Fatalf("picked %d lights, want 2", len(picked)) } - // Light index 1 (Z=5, intensity=5, green) and index 4 (Z=6, intensity=3, red) must be the top two. - if picked[0].Position.Z != 5 && picked[1].Position.Z != 5 { - t.Fatalf("expected closest bright front light (Z=5) in top 2, got %+v", picked) + if picked[0].Position.Z != 5 || picked[1].Position.Z != 6 { + t.Fatalf("picked %+v, want the visible lights at Z=5 then Z=6", picked) } - if picked[0].Position.Z != 6 && picked[1].Position.Z != 6 { - t.Fatalf("expected second front light (Z=6) in top 2, got %+v", picked) + all := render3d.SelectFallbackLights(nil, cam.ViewMatrix(), cam.ProjMatrix(), lights, 16) + if len(all) != 3 { + t.Fatalf("picked %d lights with room for 16, want the 3 visible powered lights: %+v", len(all), all) } } +// BenchmarkClusterAssign256Lights measures the CPU side of clustering 256 lights per frame, which a 60 FPS desktop frame must fit in well under 16 ms. func BenchmarkClusterAssign256Lights(b *testing.B) { grid, err := render3d.NewClusterGrid(render3d.DefaultClusterConfig()) if err != nil { @@ -884,7 +943,6 @@ func BenchmarkClusterAssign256Lights(b *testing.B) { proj := cam.ProjMatrix() lights := clusterTest256PointLights() - // Warm up frustum cache and scratch capacity. grid.AssignLights(view, proj, 0.5, 60, lights) b.ReportAllocs() @@ -895,14 +953,15 @@ func BenchmarkClusterAssign256Lights(b *testing.B) { } func BenchmarkClusterFallbackSelect256Lights(b *testing.B) { - camPos := math3d.Vec3{X: 0, Y: 14, Z: 18} - camFwd := math3d.Vec3{X: 0, Y: -14, Z: -18}.Norm() + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 14, Z: 18}, math3d.DegToRad(50), 16.0/9.0, 0.5, 60) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + view, proj := cam.ViewMatrix(), cam.ProjMatrix() lights := clusterTest256PointLights() dst := make([]render3d.ClusterLight, 0, render3d.DefaultFallbackMaxLights) b.ReportAllocs() b.ResetTimer() for b.Loop() { - dst = render3d.SelectFallbackLights(dst, camPos, camFwd, lights, render3d.DefaultFallbackMaxLights) + dst = render3d.SelectFallbackLights(dst, view, proj, lights, render3d.DefaultFallbackMaxLights) } }