17 KiB
Architecture
This document describes the system as it exists in this checkout, plus the product vision that motivates it. For implementation-level detail see:
voxel-cache.md— pages, pointers, requests, eviction, tables.shaders.md— Slang/WGSL shader architecture and compilation.pipeline-and-producers.md— how data gets into the cache.
Temporary code:
crates/vxls/src/main.rsandcrates/vxls/src/producers.rsare a playground/test harness built alongside the cache. They contain hardcoded parameters and blocking workarounds. Do not treat them as stable architecture, public API, or examples of intended concurrency. The durable system iscrates/vxls-voxel-cache/src/*andshaders/.
1. What this project is
A Rust + wgpu voxel renderer built around a GPU-resident sparse voxel cache (GigaVoxels-style: Crassin et al.). The tree is a 4×4×4 N-tree — every node has 64 children — and nodes are stored in flat GPU page pools rather than a separate brick pool.
The renderer's goal is to display very large, addressable worlds while only a small working set of voxels is resident on the GPU. Rendering, request generation, page insertion, and eviction all run on the GPU; the CPU orchestrates passes and fulfils producer requests.
Product vision
- Voxel size around pebble scale (~5–10 cm) near the player.
- Render distance of tens of kilometres, with several valleys and mountain ranges visible at once.
- Billions to hundreds of billions of addressable voxels, with only a small working set resident.
- Interactive frame rates (the original target was ~60 fps at 1440p on mid-range hardware) with a stylized-voxel look but realistic large-scale terrain structure.
- Longer term: a renderer a real game can be built on — dynamic edits, entities, water, vegetation, lighting, tooling, a stable API.
Architectural principles
These principles are the yardstick for changes. They are not all satisfied yet.
- GPU-driven, CPU-light. The CPU orchestrates; it must not iterate over voxels or per-frame visibility. Prefer indirect dispatch and GPU-side compaction of request lists.
- Working-set bound, not world-size bound. Cost must scale with screen pixels and cache size, never with total world size. Flag anything that violates this.
- LOD is native to the structure. Ray marching terminates at a level chosen by projected voxel size (about one pixel or less). Coarser levels must carry well-filtered data.
- Asynchronous and latency-tolerant. Missing data must never stall the frame. Render with the best available coarser level and refine as data arrives. Avoid visible popping where possible (blending, hysteresis, prioritisation by screen coverage and distance).
- Producers are pluggable. The renderer only knows "request node/brick X at level L, give me payload". Procedural terrain, heightmap-derived data, edited chunks, and baked/disk-streamed data should sit behind the same interface.
- Measure first. No optimisation advice without a way to measure it (timestamp queries, counters in a debug buffer, RenderDoc/Nsight/RGP captures). Suggest instrumentation before suggesting rewrites.
Roadmap context
The roadmap below is from the original project notes and is not a commitment. Treat it as direction, not a specification.
- Near term: stabilise the cache + request pipeline, lighting/shadows, atmosphere, a real terrain producer, camera-relative coordinates.
- Mid term: world edits, entities and depth compositing, TAA, vegetation/props.
- Long term: engine API, tooling, physics integration, disk streaming.
2. Current state at a glance
Implemented and wired into the running demo:
- GPU voxel cache with 4×4×4 branching and configurable page/request counts.
- GPU-emitted requests based on per-child counters, top-K selection, and a descending radix sort.
- Page recycling driven by LRU timestamps, with deepest-first depth ties (see
voxel-cache.md). - External (structure-table) and internal (cache) insertion modes.
- Structure tables: a fixed dense table and a toroidal wrapper for an "infinite" block of chunks around the camera.
- Slang ray-marching shaders with pixel-footprint LOD, compiled ahead of time.
- WGSL cache-management shaders, specialised at runtime with generated constants.
- Procedural fixtures (
SdfGenerator,TerrainGenerator,BallGenerator) and a blocking host request-fulfilment loop inmain.rsbuilt onRequestQueue,Producer/ProducedNode, andCacheInsertionData::upload.
Not wired in: the terrain/ball fixtures, tree.rs, and VoxelGiPipeline
(module compiles but is never instantiated). The demo uses TreeProducer and
the production subsystem's queue. See the module map below.
3. High-level data flow
flowchart LR
Cam[Camera / window] --> Render[Render compute pass<br/>voxel.slang]
Render -->|reads| Cache[(Voxel cache pages)]
Render -->|reads| Table[(Structure table)]
Render -->|increments| Req[(Per-page request counters)]
Table -->|increments| TReq[(Table request counters)]
Req --> Gather[gather_requests<br/>top-K + radix sort]
TReq --> TGather[table gather_requests]
Gather --> RBuffer[(Request buffer<br/>anchor, node_id, child)]
TGather --> TRBuffer[(Table request buffer<br/>anchor, slot)]
RBuffer --> Host[Host fulfils requests]
TRBuffer --> Host
Host -->|CacheInsertionData| Insert[VoxelCache::insert]
Host -->|structure insertion| TableInsert[ToroidalStructureTable::insert]
Insert -->|writes| Cache
Insert -->|recycles pages| Evict[Evictor]
TableInsert -->|root pointers| Table
Two request/response loops are visible:
- Structure-table loop. The table maps chunk coordinates to the root pointer of each chunk's tree in the cache. A miss requests a chunk root.
- Cache loop. During ray marching, the cache tracer requests missing children of nodes that are marked subdividable but not resident.
Both loops share the same request-buffer implementation and host download path.
4. Frame lifecycle (what the current driver does)
State::render in crates/vxls/src/main.rs is the only driver. One iteration does roughly:
- Move the toroidal table to the camera position. Chunks leaving the block are invalidated; chunks entering are marked as needing a root pointer.
- Render pass (
ray_march_computeinvoxel.slang):- trace the toroidal chunk grid, then descend the voxel cache;
- write position/albedo/normal G-buffers;
- update per-page usage timestamps;
- increment request counters for missing children.
- GI / AO pass (
gi.slang) — reads the world-space G-buffer, traces a few short hemisphere rays per pixel withany_hitand a finitet_max, and multiplies albedo by the AO term. - Blit / UI — copy the selected debug texture, draw egui, download a usage histogram for the plot.
- Encode request gathering for both the cache and the structure table
(unless
Fis held): top-K, gather, radix sort, write request buffers, reset counters. - Submit and present.
- Read back timings asynchronously.
- Fulfil requests and insert (unless
Fis held):- start asynchronous downloads of both request buffers;
- busily poll the device until both callbacks have run;
- on the CPU, produce nodes for every request (parallel over requests);
- upload
CacheInsertionDatabuffers; - encode
VoxelCache::insertwith both an external insertion (table roots) and an internal insertion (cache children); - encode
ToroidalStructureTable::insertto point table entries at the new root pages; - submit.
Consequences agents should keep in mind:
- Inserted pages become visible on the next frame; the render pass of the current frame already ran.
- The host step is synchronous and blocking even though the download API is
callback-based. The
loop { device.poll(...) }at the end ofrenderis a workaround, not the intended design. - Holding
Ffreezes cache management so the resident set can be inspected. - Debug display keys:
Ttarget,Nnormals,Qalbedo,Pposition.
5. Module map
| Path | Role | Status |
|---|---|---|
crates/vxls/src/main.rs |
Window, wgpu setup, frame loop, host fulfilment | Temporary playground |
crates/vxls/src/producers.rs |
ChunkedProducer + procedural fixtures |
Temporary playground (trait is the useful part) |
crates/vxls-voxel-cache/src/lib.rs |
VoxelCache orchestrator, public API, raytrace bind group |
Active, durable |
crates/vxls-voxel-cache/src/schema.rs |
Pointer bits, page structs, request structs | Active, durable |
crates/vxls-attributes/src/attributes.rs |
Producer-facing Attribute/Attributes traits and static attribute layouts |
Active, durable |
crates/vxls-attributes-derive/src/lib.rs |
#[derive(Attributes)] layout generator |
Active, durable |
crates/vxls-voxel-cache/src/layout.rs |
CacheAttribute/CacheLayout, bridge from AttributesLayout, generated WGSL constants |
Active, durable |
crates/vxls-voxel-cache/src/attributes.rs |
Attribute page buffers and bind group | Active, durable |
crates/vxls-voxel-cache/src/structure.rs |
Pointer/location/depth page buffers | Active, durable |
crates/vxls-voxel-cache/src/requests.rs |
Request counters, request buffer, top-K/sort, host download | Active, durable |
crates/vxls-voxel-cache/src/insertion.rs |
CacheInsertionData upload buffers |
Active, durable |
crates/vxls-voxel-cache/src/eviction.rs |
Timestamp buffer and eviction ordering | Active, durable |
crates/vxls-voxel-cache/src/pipelines.rs |
Write-requests, insertion, invalidation, write-pointers passes | Active, durable |
crates/vxls-voxel-cache/src/tables.rs |
FixedStructureTable (dense root pointers) |
Active, durable |
crates/vxls-terrain/src/lib.rs |
ToroidalStructureTable wrapper around the fixed table |
Active, durable (name is misleading) |
crates/vxls-bvh/src/lib.rs (+ aabb, build, debug, gpu) |
CPU BVH2 build, GPU buffers, and debug render | Active infrastructure |
crates/vxls-gpu/src/ |
Radix sort, top-K, indirect dispatch, compaction helpers | Active infrastructure |
crates/vxls-profiler/src/ |
Timestamp profiling and memory accounting wrappers | Active infrastructure |
crates/vxls/src/gi_pipeline.rs (+ sparse_set.rs) |
Planned GI pipeline using cache attribute sets | Compiled but never instantiated |
crates/vxls-production/src/lib.rs |
Producer ID, StructureAnchor re-export, Producer/ProducedNode |
Compiled; durable contract |
crates/vxls-production/src/tree_locator.rs |
Compact N-tree locator encoding | Active via RequestKey::node_locator and TreeProducer |
crates/vxls-production/src/request_queue.rs |
Bounded, deduplicating, priority-ordered request queue | Active in the demo driver, unit-tested |
crates/vxls/src/sparse_tree.rs |
CPU NTree prototype, packed color helper and node locator used by producers |
Active via main.rs/producers.rs |
The workspace uses edition 2024. Crates that use const-generic expressions enable
generic_const_exprs (voxel cache, production, BVH, terrain, app); float_algebraic
is only used by the app crate. Building requires a nightly toolchain.
6. Coordinate and tree model
The world is treated as a floating-point cube; the cache exploits float mantissas to derive tree levels.
- Branching factor
N = 4; a node hasN³ = 64children. - Child index is
x + 4*y + 16*z(x fastest). This matches the WGSLchild_indexand the Rust producer loops. - A node's level is encoded by
scale_exp:scale_exp = 23 - 2*depthfor single-precision floats. The root starts atscale_exp = 21(depth 1 in that mapping); each subdivision subtracts 2. - Because 23 mantissa bits are available, the tree has room for roughly
11 levels of 2-bit levels. The configured demo uses
chunk_power = 5, i.e. a chunk is4^5 = 1024voxels per axis. - Position-to-child conversion takes two mantissa bits at the current
scale_exp, so the tree is effectively spatially indexed by float bit patterns. This is why the tracer can descend without explicit bounding boxes.
The trace stack is caller-owned through ITraceStack. The local
implementation (LocalTraceStack in voxel_tracing.slang) is a 5-entry stack
indexed by 10 - scale_exp/2. That hardcodes the maximum supported depth and
the branching factor. It also assumes chunk_power = 5; changing chunk depth
without updating the stack breaks tracing. A groupshared-backed implementation
is a front-end change and needs no trace-core edits.
The toroidal table is a dense 3D grid of chunk root pointers. It wraps with
imod, so moving the camera across a chunk boundary invalidates the departing
slab and reuses those slots for incoming chunks. Identity is kept separate from
placement: each slot carries a table-defined StructureAnchor (world position
plus a version word), and the anchor is the structure identity. Anchors that stay
in view keep their identity while their slot may change; anchors that leave are
retired. In-flight root work carries the anchor and the latest slot, and the GPU
rejects an insertion whose anchor no longer matches the slot, so queue
invalidation is only a cancellation optimisation.
7. Shader split
There are two independent shader worlds, described fully in
shaders.md:
- Slang (
shaders/*.slang) for rendering. Built offline withslangcinto checked-inshaders/out/*.spv, embedded withinclude_spirv_source!, and loaded as passthrough modules. - WGSL (
crates/vxls-voxel-cache/src/shaders/*.wgsl) for cache management. Concatenated at runtime with generated constants (CHILDREN_COUNT,PAGE_COUNT, attribute metadata) and compiled withinclude_wgsl!-style module creation.
The two worlds agree only by convention on data layout. Attribute order, page stride, child index, and pointer bits are load-bearing contracts between them.
8. Memory and performance envelope
The demo configuration is VoxelCache<4> with 150,000 pages and 1,024 maximum
requests, plus a 20×20×20 toroidal table.
Approximate steady-state GPU buffers (decimal units, CHILDREN_COUNT = 64):
| Buffer | Bytes per page | At 150k pages |
|---|---|---|
Pointer pages (u64 mask + 64×u32) |
264 | ~39.6 MB |
| Location pages (allocated at 264 B; see below) | 264 | ~39.6 MB |
| Depth pages | 4 | ~0.6 MB |
color attribute (1 word × 64) |
256 | ~38.4 MB |
normal attribute (3 words × 64) |
768 | ~115.2 MB |
Request counters (64×u32) |
256 | ~38.4 MB |
Sorted requests (64×u32) |
256 | ~38.4 MB |
Scratch (64×u32) |
256 | ~38.4 MB |
| Timestamps + LRU list | 8 | ~1.2 MB |
Total is roughly 400 MB before pipelines, bind groups, profiler buffers, and the separate structure-table allocations. The single largest avoidable waste is the location-page over-allocation described in the issues table.
Performance is dominated by ray marching, not by cache management in the current demo; the UI plots both a frame timer and a ray-march timer.
9. Known issues (architecture level)
| Symptom | Location | Impact | Confidence |
|---|---|---|---|
Location pages are sized with size_of::<StructurePage<N>>() (264 B at N=4) instead of LocationPage (28 B). |
crates/vxls-voxel-cache/src/structure.rs:44 |
~39.6 MB allocated where ~4.2 MB is needed. | High — direct code read. |
The host request path busy-waits on device.poll, making a callback design behave synchronously. |
crates/vxls/src/main.rs around the loop { ... poll ... } after request downloads |
Stalls the CPU on the render thread; prevents real pipelining/streaming. | High. |
The caller-owned trace stack (LocalTraceStack, or a groupshared-backed ITraceStack) is 5 entries and indexes entries[10 - scale_exp/2], assuming N = 4 and chunk_power = 5. |
shaders/voxel_tracing.slang, shaders/voxel_cache.slang |
Changing branching or chunk depth silently corrupts tracing. | High. |
Slang hardcodes 64 children per node and attribute meanings (0 = packed color, 1 = 3-word normal). |
shaders/voxel_cache.slang, shaders/voxel.slang |
Any cache layout change must be mirrored in Slang; mismatches are not caught at compile time. | High. |
gi.slang is a simple AO pass (4 fixed hemisphere rays, no denoiser), not a full GI solution. |
shaders/gi.slang |
Noisy, view-dependent AO; it exists as a secondary-ray smoke test. | High. |
FixedStructureTable / ToroidalStructureTable naming: the toroidal wrapper delegates to the fixed table, and fixed_structure_table.slang is imported but unused by voxel.slang. |
crates/vxls-terrain/src/lib.rs, shaders/fixed_structure_table.slang, shaders/voxel.slang:3 |
Readers may look for toroidal logic in the wrong shader/module. | High. |
| Several subsystems are present but not wired into the binary (see module map). | crates/vxls/src/gi_pipeline.rs, terrain/ball fixtures |
Dead code can be mistaken for current architecture; it does not compile into the binary unless declared. | High. |
The demo worker thread still lives in main.rs, so scheduling and producer ownership are not reusable. |
crates/vxls/src/main.rs |
Production types are durable; the host service around them is playground code. | Medium. |