refactor: cleaner request path + raytracing code

This commit is contained in:
2026-11-23 11:32:16 +01:00
parent dd0e102348
commit dd5fdc13b8
20 changed files with 1427 additions and 618 deletions
+141 -37
View File
@@ -64,23 +64,31 @@ module creation fails.
flowchart TD
V[voxel.slang<br/>ray_march_compute] --> VC[voxel_cache.slang<br/>VoxelCacheTracer]
V --> VT[voxel_tracing.slang<br/>Tracer / interfaces]
V --> BVH[bvh.slang<br/>Bvh]
V --> TST[toroidal_structure_table.slang<br/>ToroidalStructureTableTracer]
V --> LOD[lod_policies.slang<br/>PixelFootprintLod]
V -. unused import .-> FST[fixed_structure_table.slang]
G[gi.slang<br/>AO pass] --> VC
G --> VT
G --> BVH
G --> LOD
VC --> VT
TST --> VT
TST --> VC
BVH --> VT
BVH --> 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. |
| `voxel_tracing.slang` | `Ray`, `Cell`, `Hit`, `TraceSettings`, `ITraceStack`/`LocalTraceStack`; `IStructure`, `IVoxelCache`, `ILodPolicy`; generic `Tracer`. |
| `voxel_cache.slang` | `StructurePointer`, `StructureElement`, `VoxelCacheParameters`, `VoxelCacheTracer`, `ColorHit`, attribute helpers. |
| `bvh.slang` | `Bvh` structure: restart-trail traversal, object transforms, bounded distance (`max_t`) for secondary rays. |
| `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). |
| `voxel.slang` | Push constants, G-buffer bindings, `ray_march_compute`. |
| `gi.slang` | Screen-space AO: reads the world-space G-buffer and traces short hemisphere rays with the shared tracer. |
| `compaction.slang`, `radix_sort.slang`, `radix_reduce.slang` | GPU utility kernels. |
---
@@ -118,8 +126,11 @@ ParameterBlock<ToroidalStructureTable> table_parameters; // group 1
### Group 2 — G-buffers
Three `rgba32f` storage textures written by the main pass; `gi.slang` binds
target + position + albedo + normal instead.
Three `rgba32f` storage textures written by the main pass. Position and normal
are **world space**: the tracer maps the cache's unit-cube hit through
`Cell::cube_to_world` / `Cell::world_origin`, and rotates local attribute
normals with `Hit::normal_to_world`. `gi.slang` binds target + position +
albedo + normal and uses the world-space position/normal as AO ray origins.
### Push constants / immediates
@@ -155,14 +166,14 @@ pages were touched this frame.
```slang
public interface IStructure {
associatedtype Cursor;
Cursor begin(Ray worldRay, Span s);
Cursor begin(Ray worldRay);
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);
bool trace<L : ILodPolicy, St : ITraceStack>(
uint32_t root, Ray r, L lod, TraceSettings settings,
float offset_t, inout St stack, out Hit v);
}
public interface ILodPolicy {
@@ -171,7 +182,8 @@ public interface ILodPolicy {
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);
bool trace<St : ITraceStack>(
out Hit h, Ray r, TraceSettings settings, inout St stack);
}
```
@@ -179,6 +191,24 @@ public struct Tracer<S : IStructure, C : IVoxelCache, L : ILodPolicy> {
interface can be replaced without touching the others; this is the main
extensibility point on the render side.
`TraceSettings` is the per-ray policy shared by primary and secondary rays:
```slang
public struct TraceSettings {
float t_min; // start of the search interval
float t_max; // end (exclusive); FLT_MAX for unbounded
uint32_t max_cells; // structure cells visited
uint32_t max_steps; // DDA iterations inside one cache cell
bool any_hit; // first acceptable hit instead of nearest
bool report_usage; // refresh LRU timestamps
bool report_requests; // emit cache detail requests
}
```
The same tracer therefore serves the primary pass (closest hit, camera LOD,
usage + requests) and shadow/visibility rays (`any_hit`, a finite `t_max`,
requests off) without a separate code path.
---
## 5. `VoxelCacheTracer` algorithm
@@ -216,18 +246,20 @@ world-space node size from the exponent/mantissa.
### 5.3 Main loop
Per iteration (max 500):
Per iteration (`settings.max_steps`, 500 for primary rays):
1. Read the current child pointer.
2. **Descend** while the pointer is `subdivided_valid()` (bits 31 and 30 set)
1. If `offset_t + t >= settings.t_max`, stop: the rest of the ray is outside the
requested interval.
2. Read the current child pointer.
3. **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:
trace stack, report usage when `settings.report_usage`.
4. **Request** if `settings.report_requests`, 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**:
5. **Hit test** using the occupancy mask and `IVoxelHit::shouldHit`.
6. **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.
@@ -236,26 +268,60 @@ Per iteration (max 500):
- 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.
`Tracer::trace` bounds the structure walk with `settings.max_cells`. It skips
cells that start at or beyond `t_max` or (for closest-hit traces) the best hit
so far. Structure cells are not distance ordered, so it never breaks on those
conditions.
### 5.4 Stack
```slang
public struct VoxelTraceStack { public uint32_t stack[5]; }
public interface ITraceStack {
uint32_t get(uint32_t depth);
[mutating] void set(uint32_t depth, uint32_t node);
}
public struct LocalTraceStack : ITraceStack {
public uint32_t entries[5];
// get/set index entries[depth]
}
```
`voxel.slang` allocates one per thread in groupshared memory:
The stack is **caller-owned**, so the tracer has no module-scope storage and no
dependency on the dispatch shape. `voxel.slang` keeps one per thread as a local
(`LocalTraceStack stack;`), which the driver can promote to registers or spill
to per-thread scratch. If the primary pass regresses, the front-end can switch
to groupshared storage without touching the trace core: implement `ITraceStack`
over a module-scope groupshared array plus a per-thread base slot, and pass that
handle instead.
```slang
groupshared VoxelTraceStack stacks[256]; // 16x16 workgroup
groupshared uint32_t trace_stacks[5 * 256];
public struct GroupsharedTraceStack : ITraceStack {
public uint32_t base; // slot * 5
public uint32_t get(uint32_t depth) { return trace_stacks[base + depth]; }
[mutating]
public void set(uint32_t depth, uint32_t node) { trace_stacks[base + depth] = node; }
}
// entry point
GroupsharedTraceStack stack;
stack.base = (local_location.x + local_location.y * 16) * 5;
```
The index `stack[10 - scale_exp / 2]` hardcodes the supported depth. With
Both variants compile from the same primary entry point; only the implementation
type and its construction change.
The index `depth = 10 - scale_exp / 2` hardcodes the supported trace 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>`:
`voxel_cache.slang` defines `ColorHit<2>` (shared by the primary and AO passes):
```slang
bool shouldHit(VoxelCacheParameters<N> cache, uint32_t node_index, uint32_t child_index) {
@@ -301,6 +367,23 @@ 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.
### 6.3 `bvh.slang` (active demo path)
`Bvh` walks a top-level BVH of transformed unit-cube objects and emits a `Cell`
for each object the ray can enter. Traversal uses a restart trail instead of a
stack, so the cells are **not** distance ordered (the tracer accumulates the
nearest hit and skips rather than breaks).
`Bvh::max_t` bounds the traversal: nodes and objects whose entry distance is
beyond it are culled. Primary rays set `FLT_MAX`; secondary passes (the AO pass)
set their ray length, which avoids walking the infinite ray through every object
behind the surface. The field assumes rigid rotation/translation transforms, so
local and world distances match.
Each emitted cell carries `world_origin` and `cube_to_world`; `Tracer::trace`
uses them to turn the cache's unit-cube hit into a world-space `Hit` and to
rotate local attribute normals.
---
## 7. LOD
@@ -344,18 +427,16 @@ Interpretation:
```slang
[shader("compute")]
[numthreads(16,16,1)]
void ray_march_compute(uint32_t3 location : SV_DispatchThreadID,
uint32_t3 local_location : SV_GroupThreadID)
void ray_march_compute(uint32_t3 location : SV_DispatchThreadID)
```
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.
2. Build a `VoxelCacheTracer<2, ColorHit<2>>` with the frame timestamp.
3. Fill in `TraceSettings` (unbounded closest-hit, 500 DDA steps, usage and
requests on) and declare the per-ray `LocalTraceStack`.
4. Build a `Tracer` (currently over `Bvh`) and call `trace` with the stack.
5. On hit, store the world-space hit position, the world-space normal
(`Hit::normal_to_world` rotates the local attribute normal), and albedo.
6. On miss, store zero albedo.
`fetch_color` and `fetch_normal` hardcode the demo layout:
@@ -368,6 +449,29 @@ 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`.
### 8.1 AO pass (`gi.slang`)
The AO pass is the secondary-ray smoke test. It reuses the same tracer, hit
predicate, structure (`Bvh`) and LOD policy as the primary pass:
```slang
TraceSettings settings;
settings.t_min = 0.01; // skip the surface itself
settings.t_max = 0.25; // short, local occlusion
settings.max_cells = 64;
settings.max_steps = 64;
settings.any_hit = true; // visibility, not nearest
settings.report_usage = true;
settings.report_requests = false; // secondaries do not drive detail
```
Per pixel it reconstructs a world-space origin/normal from the G-buffer, then
traces four cosine-weighted hemisphere samples rotated by a per-pixel hash. The
AO term is `1 - occluded / 4`, softened before multiplying albedo. The pass is
incoherent by nature; the caller-owned `LocalTraceStack` is reused sequentially
across the four rays, which is exactly why the stack is not tied to the
workgroup shape.
---
## 9. WGSL cache shaders
@@ -494,7 +598,7 @@ 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;
- `LocalTraceStack` size and `10 - scale_exp/2` indexing;
- `StructureElement.pointers[64]`;
- `fetch_color`/`fetch_normal` strides (`*64`, `*64*3`);
- generated WGSL `CHILDREN_COUNT`;
@@ -518,12 +622,12 @@ Makefile before building.
| 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`, `crates/vxls/src/main.rs:563-611` | Works only because the mismatched bindings are unused. Any real GI work will hit validation errors. | High |
| `gi.slang` is a simple AO pass, not a full GI solution (no bounces, no denoiser, 4 fixed hemisphere samples). | `shaders/gi.slang` | AO is noisy and view-dependent; it is a secondary-ray smoke test, not production lighting. | 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 |
| `LocalTraceStack` size and indexing assume `N = 4` and `chunk_power = 5`. | `shaders/voxel_tracing.slang` (`ITraceStack`/`LocalTraceStack`), `shaders/voxel_cache.slang` | 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`). | `crates/vxls/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`, `crates/vxls/src/main.rs:477-498` | Layout/limit errors appear as driver errors, not friendly validation messages. | Medium |
| `voxel.slang` uses `create_shader_module_passthrough`, so wgpu validation is bypassed for the render pipeline. | `crates/vxls/src/main.rs:477-498` | Layout/limit errors appear as driver errors, not friendly validation messages. | Medium |