Adding documentation for agents

This commit is contained in:
2026-11-08 15:02:48 +01:00
parent 6dedbbdb75
commit 82c952c6d8
10 changed files with 2139 additions and 12 deletions
+518
View File
@@ -0,0 +1,518 @@
# Shaders
The project uses two shader languages for two different jobs:
| | Slang (`shaders/*.slang`) | WGSL (`src/voxel_cache/shaders/*.wgsl`) |
|---|---|---|
| Used for | Rendering / ray marching | Cache management passes |
| Compilation | Offline via `slangc`, SPIR-V checked in | Runtime via wgpu |
| Specialisation | Compile-time types and generics | Runtime string concatenation + generated `const`s |
| Embedded with | `include_spirv_source!` / `include_spirv!` | `include_str!` into a generated module |
| Rust entry point | `main.rs` passthrough shader modules | `pipelines.rs`, `requests.rs`, `eviction.rs`, `tables.rs` |
> **Temporary code:** bind-group and pipeline setup in `src/main.rs` is part of
> the playground driver. Read shader contracts from the Rust cache/table
> wrappers (`src/voxel_cache/*`) and this document, not from `main.rs` alone.
---
## 1. Slang build model
`shaders/Makefile`:
```make
all: clean voxel.spv compaction.spv gi.spv radix_sort.spv radix_reduce.spv
clean:
rm -f out/*.spv
%.spv: %.slang
slangc $< -O3 -g0 -fp-mode fast -emit-spirv-directly -fvk-use-entrypoint-name -target spirv -o out/$@
```
Build with:
```sh
make -C shaders
```
Generated files live in `shaders/out/` and are **checked in**. Do not hand-edit
them; edit the `.slang` source and rebuild.
### How SPIR-V reaches wgpu
- Rendering shaders are loaded with
`create_shader_module_passthrough` (requires `PASSTHROUGH_SHADERS`), which
avoids wgpu's shader validation and requires explicit entry-point workgroup
sizes:
- `shaders/out/voxel.spv` → entry `ray_march_compute`, workgroup `(16,16,1)`
- `shaders/out/gi.spv` → entry `gi`, workgroup `(16,16,1)`
- Utility shaders are loaded with ordinary `include_spirv!`:
- `shaders/out/radix_sort.spv` in `src/gpu/radix_sort.rs`
- `shaders/out/compaction.spv` in `src/gpu/buffer_compactor.rs`
- `radix_reduce.spv` is built by the Makefile but currently not referenced by
Rust source.
The declared entry-point name must match `-fvk-use-entrypoint-name`; otherwise
module creation fails.
---
## 2. Slang module graph
```mermaid
flowchart TD
V[voxel.slang<br/>ray_march_compute] --> VC[voxel_cache.slang<br/>VoxelCacheTracer]
V --> VT[voxel_tracing.slang<br/>Tracer / interfaces]
V --> TST[toroidal_structure_table.slang<br/>ToroidalStructureTableTracer]
V --> LOD[lod_policies.slang<br/>PixelFootprintLod]
V -. unused import .-> FST[fixed_structure_table.slang]
VC --> VT
TST --> VT
TST --> VC
```
| File | Role |
|---|---|
| `voxel_tracing.slang` | `Ray`, `Span`, `Cell`, `Hit`; `IStructure`, `IVoxelCache`, `ILodPolicy`; generic `Tracer`. |
| `voxel_cache.slang` | `StructurePointer`, `StructureElement`, `VoxelCacheParameters`, `VoxelTraceStack`, `VoxelCacheTracer`, attribute helpers. |
| `toroidal_structure_table.slang` | Dense wrapped chunk grid; produces cache entry cells. |
| `lod_policies.slang` | `PixelFootprintLod`. |
| `fixed_structure_table.slang` | Non-wrapping chunk grid; imported by `voxel.slang` but not used. |
| `voxel.slang` | Push constants, G-buffer bindings, `ColorHit`, `ray_march_compute`. |
| `gi.slang` | Stub GI pass (copies albedo). |
| `compaction.slang`, `radix_sort.slang`, `radix_reduce.slang` | GPU utility kernels. |
---
## 3. Bindings and immediates (rendering)
`voxel.slang` declares:
```slang
[[vk::push_constant]] uniform PushConstants constants;
ParameterBlock<VoxelCacheParameters<2>> cache_parameters; // group 0
ParameterBlock<ToroidalStructureTable> table_parameters; // group 1
[[vk::binding(0,2)]] WTexture2D<float4> gbuffer_position; // group 2
[[vk::binding(1,2)]] WTexture2D<float4> gbuffer_albedo;
[[vk::binding(2,2)]] WTexture2D<float4> gbuffer_normal;
```
### Group 0 — cache (`VoxelCacheParameters<N>`)
| Binding | Contents |
|---|---|
| 0 | `structure_pool`: pointer pages (`StructureElement`) |
| 1 | `request_buffer`: per-child atomic counters (`RequestBufferElement`) |
| 2 | `usage_buffer`: per-page timestamp |
| 3 | `attributes_pool[N]`: attribute pages (N = attribute count = 2 here) |
### Group 1 — structure table
| Binding | Contents |
|---|---|
| 0 | `structure_table_pointer`: one `StructurePointer` per chunk slot |
| 1 | `structure_table_request_buffer`: one atomic counter per slot |
### Group 2 — G-buffers
Three `rgba32f` storage textures written by the main pass; `gi.slang` binds
target + position + albedo + normal instead.
### Push constants / immediates
```slang
struct PushConstants {
float4x4 view_proj;
float3 cam_pos;
uint32_t frame_timestamp;
uint32_t width;
uint32_t height;
uint32_t chunk_width;
uint32_t chunk_height;
uint32_t chunk_alt;
}
```
Rust passes `camera.view_proj().inverse()` in `view_proj`, while the shader does
`mul(constants.view_proj, ndc)`. The pair reconstructs a world-space ray
direction. `chunk_*` feeds the toroidal table extent; in the demo all three are
20, which hides an ordering inconsistency in the naming (Rust passes
`(width, alt, height)` to the table but `(width, height, alt)` to the shader).
`frame_timestamp` must equal `VoxelCache::current_timestamp()` when the render
pass is recorded; it is used both for usage reporting and for deciding which
pages were touched this frame.
---
## 4. Tracing interfaces
`voxel_tracing.slang` defines the composition pattern:
```slang
public interface IStructure {
associatedtype Cursor;
Cursor begin(Ray worldRay, Span s);
bool next(inout Cursor c, out Cell cell);
}
public interface IVoxelCache {
associatedtype GroupSharedData;
bool trace<L : ILodPolicy>(
uint32_t root, inout GroupSharedData data, Ray r, L lod, float offset_t, out Hit v);
}
public interface ILodPolicy {
bool shouldStop(float t, float nodeSize);
}
public struct Tracer<S : IStructure, C : IVoxelCache, L : ILodPolicy> {
S structure; C cache; L lod;
bool trace(inout C.GroupSharedData gsData, out Hit h, Ray r, Span s);
}
```
`Tracer::trace` walks structure cells and asks the cache to trace each one. Any
interface can be replaced without touching the others; this is the main
extensibility point on the render side.
---
## 5. `VoxelCacheTracer` algorithm
`voxel_cache.slang`. The tracer descends a 4-ary tree encoded by float mantissas.
### 5.1 Ray mirroring
To make the DDA always move toward increasing coordinates, the ray is reflected
into the positive octant:
1. `r.origin += 1` and clamp to `[1, 2)`.
2. For each axis with positive direction, flip the mantissa bits
(`asuint(origin) ^ 0x007fffff`).
3. Build `child_mirror`, which flips the 2-bit child coordinate per axis.
Hit locations are mirrored back before being returned.
### 5.2 Tree levels
```slang
uint32_t scale_exp = 23 - 2; // root level
uint32_t child_index = get_children_index(pos, scale_exp) ^ child_mirror;
```
`get_children_index` extracts two mantissa bits:
```slang
cell_position = (asuint(position) >> scale_exp) & 3;
child_index = x + y*4 + z*16;
```
Each subdivision does `scale_exp -= 2`. `node_size(scale_exp)` reconstructs the
world-space node size from the exponent/mantissa.
### 5.3 Main loop
Per iteration (max 500):
1. Read the current child pointer.
2. **Descend** while the pointer is `subdivided_valid()` (bits 31 and 30 set)
and the LOD policy says the node is still too large:
- `scale_exp -= 2`, `current_node_index = pointer()`, push onto the
`VoxelTraceStack`, report usage.
3. **Request** if the LOD still wants detail, the pointer is subdividable, and
it is not resident:
`requests[current_node_index][child_index] += 1`.
4. **Hit test** using the occupancy mask and `IVoxelHit::shouldHit`.
5. **DDA step**:
- If the coarser 2×2×2 neighbourhood is empty
(`(occupancy >> (child_index & 0b101010)) & 0x00330033 == 0`), advance one
extra level (`adv_scale_exp++`) to skip empty space.
- Compute the next face intersection from the mirrored ray, step `pos` to the
face (clamped by the neighbour maximum).
- Find the most common ancestor of old and new positions via XOR and
`firstbithigh`, then restore `scale_exp` and pop the stack to that level.
### 5.4 Stack
```slang
public struct VoxelTraceStack { public uint32_t stack[5]; }
```
`voxel.slang` allocates one per thread in groupshared memory:
```slang
groupshared VoxelTraceStack stacks[256]; // 16x16 workgroup
```
The index `stack[10 - scale_exp / 2]` hardcodes the supported depth. With
`N = 4` and `chunk_power = 5`, the deepest level used is 5, so the stack must
hold entries for levels 1..5. Changing the branching factor or chunk depth
requires changing both the stack size and this index formula.
### 5.5 Hit test
`voxel.slang` defines `ColorHit<2>`:
```slang
bool shouldHit(VoxelCacheParameters<N> cache, uint32_t node_index, uint32_t child_index) {
return ByteColor(cache.attributes_pool[0][node_index * 64 + child_index]).byte_a != 0;
}
```
So a child is a hit when the alpha byte of its packed color is non-zero. The hit
result exposes `node_index`, `child_index`, and a mirrored-back
`hit_location`.
---
## 6. Structure traversal
### 6.1 Toroidal tracer
`toroidal_structure_table.slang` walks unit cells (one cell per structure slot):
- `begin`: `current_voxel = floor(origin)`, `offset = current_voxel - extent/2`.
It initialises the 3D DDA `t` values from the ray direction.
- `next`, while the current cell is inside the block:
- compute wrapped local coordinates with `imod`;
- compute the slot index
`x + z*extent.x + y*extent.x*extent.z`;
- if the slot pointer is resident, emit a `Cell` with
`local_ray.origin = position - current_voxel` (fractional position inside the
unit cell), and return it;
- if the slot is subdividable but not resident, increment its request counter;
- step the DDA to the next cell.
In shader space one cell is a unit cube. The producer decides how many voxels
that cube contains (`chunk_power = 5` means `4^5 = 1024` voxels per axis in the
demo). The cache tracer subdivides the unit cube; it never sees the producer's
voxel count directly.
The `min_mask` + `sign(direction)` stepping means the traversal advances one
cell per axis crossing; it does not skip empty chunks based on occupancy.
### 6.2 `fixed_structure_table.slang`
A non-wrapping version of the same idea. It is imported by `voxel.slang` but not
instantiated; the Rust `FixedStructureTable` is used through the toroidal
wrapper instead.
---
## 7. LOD
```slang
struct PixelFootprintLod : ILodPolicy {
float pixelAngle; // angular size of one pixel (radians)
float pixelThreshold; // pixels a node may cover before we stop
float coneRadius0; // footprint at t = 0
float footprint(float t) { return coneRadius0 + t * pixelAngle; }
bool shouldStop(float t, float nodeSize) {
return nodeSize <= footprint(t) * pixelThreshold;
}
}
```
`create(fovYRadians, imageHeightPixels, pixelThreshold, coneRadius0)` computes
`pixelAngle = 2*tan(fovY/2)/imageHeightPixels`.
Demo call:
```slang
PixelFootprintLod lod = PixelFootprintLod.create((100.f * 3.14f) / 180.f, 1080.f, 2.f);
```
Interpretation:
- `pixelThreshold = 1.0` → stop when a node is about one pixel wide.
- `2.0` (the demo) → stop when a node is two pixels wide, i.e. coarser/faster.
- `coneRadius0 = 0` is a pinhole camera; secondary rays should inherit a
non-zero footprint from their parent bounce.
---
## 8. Main render entry point
`voxel.slang`:
```slang
[shader("compute")]
[numthreads(16,16,1)]
void ray_march_compute(uint32_t3 location : SV_DispatchThreadID,
uint32_t3 local_location : SV_GroupThreadID)
```
1. Bounds-check against `constants.width/height`.
2. Build a `VoxelCacheTracer<2, ColorHit<2>>` with usage + request reporting and
the frame timestamp.
3. Build a `ToroidalStructureTableTracer` with
`extent = (chunk_width, chunk_alt, chunk_width)`.
4. Build a `Tracer` and call `trace` with the per-thread stack.
5. On hit, fetch normal and color from attribute pools and store position,
normal, and albedo G-buffers.
6. On miss, store zero albedo.
`fetch_color` and `fetch_normal` hardcode the demo layout:
```slang
attributes_pool[0][node * 64 + child] // color
attributes_pool[1][node * 64*3 + child*3 + 0..2] // normal
```
This is the most important cross-language contract in the repo. If you reorder
or resize attributes in `CacheLayout`, update these functions and `ColorHit`.
---
## 9. WGSL cache shaders
### 9.1 Composition
Cache management shaders are assembled at runtime from concatenated strings:
```text
common.wgsl // structs, pointer helpers, enable wgpu_binding_array
<generated constants> // CHILDREN_COUNT, PAGE_COUNT, attribute metadata
cache_common.wgsl // PointerPage, InsertionInformation, index helpers
<pass file> // entry point(s)
```
`programmatic_common_wgsl!` in `pipelines.rs` generates:
```wgsl
const CHILDREN_COUNT: u32 = 64; // N*N*N
const PAGE_COUNT: u32 = 150000;
const ATTRIBUTE_COUNT: u32 = 2;
const ATTRIBUTE_WORD_COUNTS: array<u32,2> = ...;
const ATTRIBUTE_COPY: array<bool,2> = ...;
```
Structure-table shaders use a simpler concatenation:
`common.wgsl` + pass file.
`common.wgsl` starts with `enable wgpu_binding_array;` and defines the shared
`CacheIndex`, `RequestInformation`, `RequestMeta`, `AttributeArray`,
`LocationPage`, and child-pointer helpers so the Rust and WGSL sides share names.
### 9.2 WGSL modules and entry points
| File | Entry point(s) | Purpose |
|---|---|---|
| `shaders/requests.wgsl` | `reset_requests` | Zero all per-child request counters. |
| `shaders/gather_requests.wgsl` | `gather_requests` | Copy selected top-K counts/indices into radix key/value buffers. |
| `shaders/write_requests.wgsl` | `write_requests` | Convert sorted flat indices into `RequestInformation`/`RequestMeta`. |
| `shaders/insertion.wgsl` | `insertion`, `consume` | Recycle pages, write pointer/location/depth/attributes, advance consumed count. |
| `shaders/invalidation.wgsl` | `invalidation` | Clear cache pointers that reference pages recycled this insert. |
| `shaders/write_pointers.wgsl` | `write_pointers` | Link internal insertion results into parent pages. |
| `shaders/eviction.wgsl` | `reset_lru_list`, `indirect_copy` | Build the eviction candidate list: descending depth sort, then gather timestamps for the stable timestamp sort. |
| `fixed_table/write_requests.wgsl` | `write_requests` | Emit root requests for table slots. |
| `fixed_table/insertion.wgsl` | `insertion` | Point table slots at inserted root pages. |
| `fixed_table/invalidation.wgsl` | `invalidation` | Clear table slots pointing at recycled pages. |
| `terrain/shaders/toroidal_structure.wgsl` | `invalidate_new` | Reset table slots whose world position changed. |
All compute workgroups are `(256,1,1)` except `toroidal_structure.wgsl`, which
uses `(4,4,4)`.
### 9.3 Bind-group conventions
Cache shaders consistently bind:
- group 0 — cache structure (pointer, location, depth pages), except
`insertion.wgsl` where group 0 is attributes and group 1 is structure;
- group 1 — request handler, evictor, or request buffer depending on the pass;
- group 2 — request buffer, insertion data, or scratch buffer;
- group 3 — evictor or insertion data;
- group 4 — inserted-count atomic.
The authoritative table is in [`voxel-cache.md`](./voxel-cache.md#9-bind-groups).
### 9.4 Immediates
WGSL passes use `var<immediate>` for a small `u32`:
- `insertion.wgsl`: `new_timestamp` (the frame timestamp assigned to new pages).
- `invalidation.wgsl`: `new_timestamp` (marks which pages are dirty this pass).
- `toroidal_structure.wgsl`: a struct of `extent`, `previous_offset`, `offset`.
Rust sets these with `pass.set_immediates(0, ...)`; the pipeline layouts declare
`immediate_size` accordingly.
### 9.5 Attribute copy contract
`insertion.wgsl` copies attributes for each page slot:
```wgsl
for (attribute_index in 0..ATTRIBUTE_COUNT) {
if (!ATTRIBUTE_COPY[attribute_index]) { continue; }
page_stride = CHILDREN_COUNT * ATTRIBUTE_WORD_COUNTS[attribute_index];
dest_offset = page_stride * page_index;
src_offset = page_stride * insertion_slot;
for (word in 0..page_stride) {
cache_attributes[attribute_index].values[dest_offset + word]
= insertion_data_attributes[attribute_index].values[src_offset + word];
}
}
```
So attribute buffers are always `page_count * 64 * word_count` words, and the
insertion batch is indexed by request slot.
---
## 10. Changing shaders: checklist
### Adding or resizing a cache attribute
1. Add it to `CacheLayout` in the caller (order matters).
2. If the renderer reads it, update `VoxelCacheParameters` usage and
`fetch_*` functions in `voxel_cache.slang` / `voxel.slang`.
3. Update `ColorHit` if the hit criterion changes.
4. Check the `VoxelCacheParameters<N>` attribute count `N` (not the branching
factor).
5. Rebuild Slang if you changed `.slang` files.
### Changing the branching factor
Do not do this casually. Required changes include:
- `VoxelCache<N>` / producer `N` and all 64-element assumptions;
- `get_children_index` (`*4`, `*16`) and the child-mirror shifts;
- `VoxelTraceStack` size and `10 - scale_exp/2` indexing;
- `StructureElement.pointers[64]`;
- `fetch_color`/`fetch_normal` strides (`*64`, `*64*3`);
- generated WGSL `CHILDREN_COUNT`;
- the `0b101010` / `0x00330033` empty-neighbourhood test.
### Rebuilding
```sh
make -C shaders # regenerates shaders/out/*.spv
cargo run # wgpu embeds the checked-in SPIR-V at compile time
```
Because SPIR-V is embedded with `include_*!`, changing `.spv` requires a Rust
rebuild. CI or fresh checkouts must either commit the `.spv` files or run the
Makefile before building.
---
## 11. Known issues
| Symptom | Location | Impact | Confidence |
|---|---|---|---|
| `voxel.slang` imports `fixed_structure_table` but never uses it. | `shaders/voxel.slang:3` | Misleads readers; increases compile surface. | High |
| `gi.slang` declares legacy bindings (`structure_pool`, `attributes_pool`, request/usage buffers, table buffers) that do not match the GI bind group Rust actually creates. | `shaders/gi.slang:17-45`, `src/main.rs:563-611` | Works only because the mismatched bindings are unused. Any real GI work will hit validation errors. | High |
| `PixelFootprintLod` demo parameters are hardcoded (100° FOV, 1080 px, threshold 2). | `shaders/voxel.slang:149` | LOD does not follow the window/FOV; resizing the window changes effective LOD. | High |
| `VoxelTraceStack` size and indexing assume `N = 4` and `chunk_power = 5`. | `shaders/voxel_cache.slang:93-96,177,189,257` | Branching/depth changes silently break tracing. | High |
| `fetch_color` / `fetch_normal` hardcode stride 64 and attribute indices 0/1. | `shaders/voxel.slang:68-79` | Cache layout changes break rendering with no compile-time error. | High |
| The child-index and child-mirror arithmetic hardcodes `4` and `16`. | `shaders/voxel_cache.slang:103-108,154-165` | Not generic over branching factor. | High |
| The toroidal tracer walks one unit cell per axis crossing with no empty-chunk skip. | `shaders/toroidal_structure_table.slang:62-101` | Cost scales with traversed grid cells, not just occupied chunks. | Medium |
| `chunk_*` immediate field naming/order differs between Rust (`width, height, alt`) and the table extent (`width, alt, height`). | `src/main.rs:1049-1062`, `shaders/voxel.slang:140` | Hidden because the demo uses 20×20×20; non-cubic extents would mismatch. | Medium |
| `radix_reduce.spv` is built and checked in but unused. | `shaders/Makefile:1` | Confusing build artifact. | High |
| `voxel.slang` uses `groupshared VoxelTraceStack stacks[256]` but `create_shader_module_passthrough` bypasses wgpu validation. | `shaders/voxel.slang:118`, `src/main.rs:477-498` | Layout/limit errors appear as driver errors, not friendly validation messages. | Medium |