25 KiB
Shaders
The project uses two shader languages for two different jobs:
Slang (shaders/*.slang) |
WGSL (crates/vxls-voxel-cache/src/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 consts |
| 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
crates/vxls/src/main.rsis part of the playground driver. Read shader contracts from the Rust cache/table wrappers (crates/vxls-voxel-cache/src/*) and this document, not frommain.rsalone.
1. Slang build model
shaders/Makefile:
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:
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(requiresPASSTHROUGH_SHADERS), which avoids wgpu's shader validation and requires explicit entry-point workgroup sizes:shaders/out/voxel.spv→ entryray_march_compute, workgroup(16,16,1)shaders/out/gi.spv→ entrygi, workgroup(16,16,1)
- Utility shaders are loaded with ordinary
include_spirv!:shaders/out/radix_sort.spvincrates/vxls-gpu/src/radix_sort.rsshaders/out/compaction.spvincrates/vxls-gpu/src/buffer_compactor.rs
radix_reduce.spvis 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
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, 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, 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. |
3. Bindings and immediates (rendering)
voxel.slang declares:
[[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. 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
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:
public interface IStructure {
associatedtype Cursor;
Cursor begin(Ray worldRay);
bool next(inout Cursor c, out Cell cell);
}
public interface IVoxelCache {
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 {
bool shouldStop(float t, float nodeSize);
}
public struct Tracer<S : IStructure, C : IVoxelCache, L : ILodPolicy> {
S structure; C cache; L lod;
bool trace<St : ITraceStack>(
out Hit h, Ray r, TraceSettings settings, inout St stack);
}
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.
TraceSettings is the per-ray policy shared by primary and secondary rays:
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
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:
r.origin += 1and clamp to[1, 2).- For each axis with positive direction, flip the mantissa bits
(
asuint(origin) ^ 0x007fffff). - Build
child_mirror, which flips the 2-bit child coordinate per axis.
Hit locations are mirrored back before being returned.
5.2 Tree levels
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:
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 (settings.max_steps, 500 for primary rays):
- If
offset_t + t >= settings.t_max, stop: the rest of the ray is outside the requested interval. - Read the current child pointer.
- 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 trace stack, report usage whensettings.report_usage.
- 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. - Hit test using the occupancy mask and
IVoxelHit::shouldHit. - 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
posto the face (clamped by the neighbour maximum). - Find the most common ancestor of old and new positions via XOR and
firstbithigh, then restorescale_expand pop the stack to that level.
- If the coarser 2×2×2 neighbourhood is empty
(
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
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]
}
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.
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;
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_cache.slang defines ColorHit<2> (shared by the primary and AO passes):
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 DDAtvalues 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
Cellwithlocal_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.
- compute wrapped local coordinates with
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.
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
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:
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 = 0is a pinhole camera; secondary rays should inherit a non-zero footprint from their parent bounce.
8. Main render entry point
voxel.slang:
[shader("compute")]
[numthreads(16,16,1)]
void ray_march_compute(uint32_t3 location : SV_DispatchThreadID)
- Bounds-check against
constants.width/height. - Build a
VoxelCacheTracer<2, ColorHit<2>>with the frame timestamp. - Fill in
TraceSettings(unbounded closest-hit, 500 DDA steps, usage and requests on) and declare the per-rayLocalTraceStack. - Build a
Tracer(currently overBvh) and calltracewith the stack. - On hit, store the world-space hit position, the world-space normal
(
Hit::normal_to_worldrotates the local attribute normal), and albedo. - On miss, store zero albedo.
fetch_color and fetch_normal hardcode the demo layout:
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.
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:
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
9.1 Composition
Cache management shaders are assembled at runtime from concatenated strings:
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:
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, StructureAnchor/anchor_eq, RequestInformation, RequestMeta,
InsertionParent, AttributeArray, LocationPage, and child-pointer helpers so
the Rust and WGSL sides share names. The wire structs carry the anchor and the
external table slot; see voxel-cache.md.
Structure-table shaders that emit requests or validate/insert roots bind a third group:
- group 0 — table pointers, or request handler;
- group 1 — request buffer, or insertion data;
- group 2 — slot metadata: binding 0
fixed_table_anchors.
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 |
validate_internal, insertion, consume |
Validate/compact internal entries, 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 using the batch's InsertionParent. |
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, resolving the slot's current anchor. |
fixed_table/validate_insertion.wgsl |
validate_external |
Keep only root entries whose named slot still carries the same anchor and waits for a page. |
fixed_table/insertion.wgsl |
insertion |
Re-check anchor/slot, then point the table slot at the inserted root page. |
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.wgslwhere group 0 is attributes and group 1 is structure; - group 1 — request handler, evictor, insertion data, 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.
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 ofextent,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:
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
- Add it to
CacheLayoutin the caller (order matters). - If the renderer reads it, update
VoxelCacheParametersusage andfetch_*functions invoxel_cache.slang/voxel.slang. - Update
ColorHitif the hit criterion changes. - Check the
VoxelCacheParameters<N>attribute countN(not the branching factor). - Rebuild Slang if you changed
.slangfiles.
Changing the branching factor
Do not do this casually. Required changes include:
VoxelCache<N>/ producerNand all 64-element assumptions;get_children_index(*4,*16) and the child-mirror shifts;LocalTraceStacksize and10 - scale_exp/2indexing;StructureElement.pointers[64];fetch_color/fetch_normalstrides (*64,*64*3);- generated WGSL
CHILDREN_COUNT; - the
0b101010/0x00330033empty-neighbourhood test.
Rebuilding
make -C shaders # regenerates shaders/out/*.spv
cargo run -p vxls # 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 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 |
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 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 |