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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Agent Note: 3D Post-Processing (Bloom, SSAO, Depth of Field) in render3d

Status: implemented

## Problem

3D games built on `game/render3d` and NSGo's `gpu.View` need multi-pass offscreen 3D post-processing — HDR Bloom, depth-based Screen-Space Ambient Occlusion (SSAO), and Depth of Field (DoF) — running over `gpu.RenderTarget` color and depth attachments (#282, part of #279).

The existing 2D `game/effects` package fuses Kage fragment passes into a single draw without intermediate textures or a 3D depth buffer (see [CRT scanlines note](2026-11-24-effects-crt-scanlines.md)), so it cannot sample a 3D `texture_depth_2d` attachment, preserve HDR floating-point highlights (`FormatRGBA16Float`), or run multi-pass separable blurs. Building portable 3D post-processing on NSGo v0.3.0 also carries concrete cross-backend constraints:

- NSGo's software GPU VM omits `shaderir.Exp`, `shaderir.Exp2`, `shaderir.Log2`, and screen-space derivative builtins (`dpdx`/`dpdy`), so shaders that rely on `exp` Gaussian weights or `dpdx`/`dpdy` normal reconstruction fail or produce wrong output in headless tests.
- All `Device.WriteBuffer` calls queued within a frame execute before any render passes in that frame, so sharing one uniform buffer across horizontal and vertical blur passes overwrites the horizontal direction before it runs.
- WebGPU and GLES 3.0 require non-filtering (`FilterNearest`) samplers for non-comparison `texture_depth_2d` reads and require `textureSampleLevel` inside non-uniform control flow (loops or early-exit branches).
- WebGL 2 / OpenGL ES 3.0 (`nsgotest.NoGPUCompute`) lack compute shaders, so every pass must run as fragment render passes.

## Decision

`packages/game/render3d/post3d.go` adds standalone passes (`BloomPass`, `SSAOPass`, `DepthOfFieldPass`) and a composable `PostStack3D` manager with validated configs (`BloomConfig`, `SSAOConfig`, `DepthOfFieldConfig`, wrapping invalid inputs in `ErrInvalidPostProcess`):

- **Dedicated offscreen render targets and fixed stage order**: `PostStack3D` owns an offscreen color+depth scene target (`FormatRGBA16Float` + `FormatDepth32Float` by default, configurable to `FormatRGBA8Unorm` / `FormatDepth24Plus`) and two ping-pong color targets. Enabled passes run in order **SSAO -> Depth of Field -> Bloom** so ambient occlusion darkens crevices before optical blur and highlights bloom afterward. Each pass holds separate intermediate (`ColorFormat`) and output (`OutputFormat`) composite pipelines so the final enabled pass writes directly to the swapchain or destination texture without an extra copy pass.
- **Portable fragment-only WGSL**: All passes use a shared 3-vertex retained fullscreen triangle buffer (`z = 0.0`, avoiding far-plane `z = 1.0` clipping and empty-VAO WebGL 2 quirks), explicit `textureSampleLevel`, `FilterNearest` depth samplers, precomputed 9-tap separable Gaussian weights (Bloom), algebraic bilateral depth weights `1 / (1 + (dz / thresh)^2)` (SSAO blur), and edge-preserving 4-neighbor depth-difference normal reconstruction with a deterministic 4×4 stratified rotation pattern (SSAO). Zero `exp`/`exp2`/`log2`, `dpdx`/`dpdy`, or compute shaders are used.
- **Per-stage uniform buffers and bind-group caching**: Each sub-pass (`extract`, `horizBlur`, `vertBlur`, `composite`, `ssao`, `ssaoBlur`, `coc`, `bokeh`) owns its own uniform buffer so multi-pass submissions in one `gpu.Frame` or `gpu.Encoder` never clobber earlier passes' uniforms. External input bind groups are cached by texture handle and closed on change, `Resize`, or `Close` to avoid steady-state leaks.
- **Device-parameterized methods (`RenderPassRecorder`)**: Following [textures and samplers](2026-11-24-render3d-textures-and-samplers.md), passes never cache `*gpu.Device`; `Apply`, `ComputeAO`, and `Resize` accept `dev *gpu.Device` explicitly and the package's existing `RenderPassRecorder` interface (shared with `DynamicResolutionTarget`) satisfied by both `*gpu.Frame` and `*gpu.Encoder`, allowing `Retained: true` resources to survive device loss and restoration cleanly.

## Alternatives considered

### Compute-shader Bloom, SSAO, and DoF

Running separable blur, SSAO, and CoC gather in compute shaders with shared workgroup memory reduces texture bandwidth on desktop/modern mobile GPUs. Rejected because NSGo targets WebGL 2 and OpenGL ES 3.0 (`nsgotest.NoGPUCompute`), where compute pipelines and storage textures return `gpu.ErrUnsupported`. Fragment passes over `gpu.RenderTarget` work identically across Metal, Direct3D 11, OpenGL 3.3, WebGPU, WebGL 2, OpenGL ES 3.0, and the software device.

### Reconstructing SSAO normals with `dpdx`/`dpdy`

Using `normalize(cross(dpdx(viewPos), dpdy(viewPos)))` avoids four neighboring depth texture fetches per pixel. Rejected because NSGo's software GPU VM does not evaluate 2×2 fragment quads or implement `Dfdx`/`Dfdy`, and raw `dpdx`/`dpdy` produces silhouette-edge normal artifacts across depth discontinuities whereas minimum-delta 4-neighbor depth differencing is edge-preserving and deterministic everywhere.

### Extending `game/effects` with 3D post-processing

Placing 3D Bloom, SSAO, and DoF in `game/effects` would group all screen-space effects under one package. Rejected because `game/effects` is coupled to Kage single-pass fusion over 2D `core.ImageSource` layers without `gpu.Device`, `gpu.RenderTarget`, `texture_depth_2d`, or `scene3d.Camera` projection matrices; keeping 3D post-processing in `game/render3d` aligns with `CameraBuffer`, `GPUMesh`, and `GPUTexture`.

## Consequences

- **Benefits**: Games get composable or standalone HDR Bloom, depth-reconstructed SSAO (with inspectable `AOTexture()` and bilateral blur), and depth-aware disc bokeh Depth of Field running on every NSGo backend including `NoGPUCompute`, with `Resize`, `Retained` device-loss restoration, zero steady-state bind-group leaks, and deterministic golden reference tests (`post3d_bloom.png`, `post3d_ssao.png`, `post3d_dof.png`, `post3d_combined.png`).
- **Costs**: `PostStack3D` allocates offscreen scene, ping-pong, and per-pass render targets up front (even for passes initially disabled, so toggling via `SetSSAO`/`SetDepthOfField`/`SetBloom` allocates nothing at runtime); callers needing only one effect can instantiate `BloomPass`, `SSAOPass`, or `DepthOfFieldPass` standalone to avoid unused target memory. SSAO bilateral blur runs as a 2D neighborhood loop (capped at `BlurRadius <= 4`) rather than a separable pass, trading slightly more software-VM test time for stronger diagonal edge preservation.
3 changes: 3 additions & 0 deletions changelog.d/render3d-post-processing-282.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Added

- `game/render3d`: composable 3D post-processing via offscreen `gpu.RenderTarget` passes (`PostStack3D`, `BloomPass`, `SSAOPass`, `DepthOfFieldPass`) supporting HDR bright-extract + separable Gaussian Bloom, depth-reconstructed SSAO with bilateral blur, and depth-aware disc bokeh Depth of Field across full and compute-free (`WebGL 2` / `GLES 3.0`) NSGo GPU profiles (#282).
39 changes: 39 additions & 0 deletions docs/en/render3d.md
Original file line number Diff line number Diff line change
Expand Up @@ -1138,3 +1138,42 @@ for face := range gpu.CubeFace(render3d.PointShadowFaceCount) {
- **Filtering and bias**: `LocalShadowFilterHard` (one nearest comparison tap) or `LocalShadowFilterPCF3x3` (nine linear taps), with a constant `DepthBias` and a world-space `NormalBias`.
- **Bind group 3**: `LocalShadowGroup` is `ShadowGroup` (3), the group the directional shadow, fog, IBL and skinning also use, so a lit PBR pipeline takes one of them (`LitPBRPipelineOptions.SpotShadowLayout` or `PointShadowLayout`). A custom shader that needs both, or group 3 for something else, places the bindings with `SpotShadowWGSLForGroup` / `PointShadowWGSLForGroup` and scales its lights with `shade_pbr_visibility(…, directional0_vis, point0_vis, spot0_vis)` from `LightWGSL`.
- **Device loss and CPU references**: with `Retained: true` the depth target, sampler, buffers, bind groups and depth pipeline come back after a device loss. `EvaluateSpotShadow`, `EvaluatePointShadow` and `PointShadowSelectFace` mirror the WGSL, and `ShadePointVisibility` with a `LightVisibility` reproduces the lit pixel; the tests compare them with the GPU and with the golden renders `render3d/testdata/golden/local_shadow_spot.png` and `local_shadow_point.png` (`UPDATE_GOLDEN=1` rewrites them).

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

`PostStack3D` composes screen-space ambient occlusion (`SSAOPass`), depth-aware disc bokeh Depth of Field (`DepthOfFieldPass`), and HDR Bloom (`BloomPass`) over an offscreen 3D color+depth `gpu.RenderTarget` (`FormatRGBA16Float` + `FormatDepth32Float` by default) and writes the final image to the swapchain or a chosen destination texture:

```go
stack, err := render3d.NewPostStack3D(cx, dev, render3d.PostStack3DOptions{
Width: uint32(w),
Height: uint32(h),
OutputFormat: dev.SurfaceFormat(),
Retained: true,
EnableSSAO: true,
SSAO: render3d.SSAOConfigFromCamera(cam),
EnableDoF: true,
DoF: render3d.DepthOfFieldConfigFromCamera(cam, 5.0, 2.0, 5.0),
EnableBloom: true,
Bloom: render3d.DefaultBloomConfig(),
})

// In OnFrame:
pass := stack.BeginScenePass(frame, core.RGB(0x0c1018))
// ... draw 3D meshes into stack.SceneTarget() ...
pass.End()
_ = stack.ApplyScene(frame.Device(), frame, nil) // SSAO -> Depth of Field -> Bloom -> swapchain
frame.Submit()

// When the view resizes (or the camera zooms), refresh the projection SSAO and DoF depend on:
_ = stack.Resize(dev, uint32(w), uint32(h))
cam.SetViewport(float32(w), float32(h))
_ = stack.SetCamera(cam)
```

- **Composable order and standalone passes**: `PostStack3D` runs enabled stages in fixed order — **SSAO -> Depth of Field -> Bloom** — routing intermediate results through ping-pong offscreen targets and writing the final stage directly in `OutputFormat` (or blitting cleanly when all stages are disabled). `SetSSAO`, `SetDepthOfField` and `SetBloom` toggle a stage; a zero config keeps its current settings, so `stack.SetSSAO(false, render3d.SSAOConfig{})` only turns SSAO off. Each pass (`SSAOPass`, `DepthOfFieldPass`, `BloomPass`) can also be constructed and applied standalone against any caller-owned `gpu.Texture` color and depth attachments via `RenderPassRecorder` (satisfied by both `*gpu.Frame` and `*gpu.Encoder`).
- **Formats and destinations**: `ColorFormat` (scene and intermediate targets) is `FormatRGBA16Float` (default), `FormatRGBA8Unorm`, `FormatRGBA8UnormSRGB`, `FormatBGRA8Unorm` or `FormatBGRA8UnormSRGB`: four filterable channels, because Depth of Field stores its Circle of Confusion in alpha. A nil destination writes to the swapchain in `OutputFormat`; a destination texture must be in `ColorFormat` or `OutputFormat`, and the last stage draws with the pipeline built for that format. Every input and destination must have the pass or stack size, and the destination cannot also be an input; otherwise `Apply` returns `ErrInvalidPostProcess`.
- **Camera projection**: `SSAOConfigFromCamera` captures `cam.ProjMatrix()` and `DepthOfFieldConfigFromCamera` reads the near and far planes and projection kind from that matrix, so the defaults `scene3d.Projection` fills in for zero fields (and an orthographic near plane at or behind the camera) match the depth buffer. Both are captured once; call `PostStack3D.SetCamera` (or `SetConfig` on a standalone pass) whenever the projection changes. With a zero `ProjMatrix`, SSAO falls back to a 60° perspective at the pass aspect ratio with the config's `Near` and `Far`.
- **SSAO (`SSAOConfig`, `SSAOPass`)**: reconstructs view-space positions and edge-preserving normals from the 3D depth buffer, evaluates a deterministic 4–16-sample hemisphere kernel with stratified 4×4 tangent rotation, applies an optional depth-aware bilateral blur (`BlurRadius`, `DepthThreshold`), and multiplies ambient occlusion into the scene color (`AOTexture` exposes the AO map for inspection).
- **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.
39 changes: 39 additions & 0 deletions docs/zh/render3d.md
Original file line number Diff line number Diff line change
Expand Up @@ -1138,3 +1138,42 @@ for face := range gpu.CubeFace(render3d.PointShadowFaceCount) {
- **滤波与偏移**:`LocalShadowFilterHard`(一次最近邻比较采样)或 `LocalShadowFilterPCF3x3`(九次线性采样),配合常量 `DepthBias` 与世界空间 `NormalBias`。
- **第 3 绑定组**:`LocalShadowGroup` 即 `ShadowGroup`(3),方向光阴影、雾、IBL 与蒙皮也使用该组,因此一条带光照的 PBR 管线只能选用其中之一(`LitPBRPipelineOptions.SpotShadowLayout` 或 `PointShadowLayout`)。需要同时使用两种阴影、或第 3 组另有用途的自定义着色器,可用 `SpotShadowWGSLForGroup` / `PointShadowWGSLForGroup` 放置绑定,并用 `LightWGSL` 中的 `shade_pbr_visibility(…, directional0_vis, point0_vis, spot0_vis)` 缩放各光源。
- **设备丢失与 CPU 参考实现**:设置 `Retained: true` 后,深度目标、采样器、缓冲、绑定组与深度管线会在设备丢失后恢复。`EvaluateSpotShadow`、`EvaluatePointShadow` 与 `PointShadowSelectFace` 与 WGSL 一一对应,`ShadePointVisibility` 配合 `LightVisibility` 可复现带光照的像素;测试将它们与 GPU 结果以及参考渲染图 `render3d/testdata/golden/local_shadow_spot.png` 和 `local_shadow_point.png`(`UPDATE_GOLDEN=1` 可重写)进行比较。

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

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

```go
stack, err := render3d.NewPostStack3D(cx, dev, render3d.PostStack3DOptions{
Width: uint32(w),
Height: uint32(h),
OutputFormat: dev.SurfaceFormat(),
Retained: true,
EnableSSAO: true,
SSAO: render3d.SSAOConfigFromCamera(cam),
EnableDoF: true,
DoF: render3d.DepthOfFieldConfigFromCamera(cam, 5.0, 2.0, 5.0),
EnableBloom: true,
Bloom: render3d.DefaultBloomConfig(),
})

// 在 OnFrame 中:
pass := stack.BeginScenePass(frame, core.RGB(0x0c1018))
// ... 将 3D 网格绘制到 stack.SceneTarget() ...
pass.End()
_ = stack.ApplyScene(frame.Device(), frame, nil) // SSAO -> 景深 -> Bloom -> 交换链
frame.Submit()

// 视图尺寸变化(或相机缩放)时,刷新 SSAO 与景深所依赖的投影:
_ = stack.Resize(dev, uint32(w), uint32(h))
cam.SetViewport(float32(w), float32(h))
_ = stack.SetCamera(cam)
```

- **可组合管线与独立通道**:`PostStack3D` 按固定顺序执行已启用的阶段——**SSAO → 景深 → Bloom**——中间结果在乒乓离屏渲染目标之间流转,最后一个阶段直接以 `OutputFormat` 输出(全部关闭时执行干净直通复制)。`SetSSAO`、`SetDepthOfField` 与 `SetBloom` 用于开关单个阶段;传入零值配置时保留当前设置,因此 `stack.SetSSAO(false, render3d.SSAOConfig{})` 只会关闭 SSAO。每个通道(`SSAOPass`、`DepthOfFieldPass`、`BloomPass`)也可独立创建,并通过 `RenderPassRecorder`(`*gpu.Frame` 与 `*gpu.Encoder` 均已实现)作用于调用方自建的 `gpu.Texture` 颜色与深度附件。
- **格式与输出目标**:`ColorFormat`(场景与中间渲染目标)可取 `FormatRGBA16Float`(默认)、`FormatRGBA8Unorm`、`FormatRGBA8UnormSRGB`、`FormatBGRA8Unorm` 或 `FormatBGRA8UnormSRGB`,即可过滤采样的四通道格式,因为景深把弥散圆存放在 alpha 通道中。目标为 nil 时以 `OutputFormat` 写入交换链;目标纹理必须是 `ColorFormat` 或 `OutputFormat`,最后一个阶段使用为该格式构建的管线绘制。所有输入与目标纹理的尺寸都必须与通道或后处理栈一致,且目标不能同时是输入,否则 `Apply` 返回 `ErrInvalidPostProcess`。
- **相机投影**:`SSAOConfigFromCamera` 记录 `cam.ProjMatrix()`,`DepthOfFieldConfigFromCamera` 从该矩阵读取近、远裁剪面与投影类型,因此 `scene3d.Projection` 为零值字段填入的默认值(以及位于相机处或其后方的正交近裁剪面)都与深度缓冲一致。两者只在创建配置时记录一次;投影变化时请调用 `PostStack3D.SetCamera`(独立通道则调用 `SetConfig`)。`ProjMatrix` 为零时,SSAO 回退为按通道宽高比、使用配置中 `Near` 与 `Far` 的 60° 透视投影。
- **SSAO(`SSAOConfig`、`SSAOPass`)**:从 3D 深度缓冲重建视空间位置与保边法线,使用带 4×4 分层切线旋转的确定性 4–16 采样半球核计算遮蔽,支持可选的深度感知双边模糊(`BlurRadius`、`DepthThreshold`),并将环境光遮蔽乘入场景颜色(可通过 `AOTexture` 获取 AO 纹理)。
- **景深(`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` 可重写参考图。
Loading
Loading