34 KiB
Voxel cache
crates/vxls-voxel-cache/src/lib.rs and crates/vxls-voxel-cache/src/* implement a GPU-resident sparse
voxel cache. This document covers the page model, pointer encoding, public API,
request/insertion pipelines, eviction, and the structure tables that provide
entry points into the cache.
Temporary caller: the public
VoxelCachesurface is intended API;crates/vxls/src/main.rsis only one caller and currently uses it in a blocking, single-threaded playground way. Seepipeline-and-producers.md.
1. Model
- An N-tree with branching factor
N(N = 4in the demo). One node hasN³ = 64children. - The cache owns a fixed pool of pages. A page stores everything about one node: its 64 child pointers, a 64-bit occupancy mask, its location tag, its depth, and the node's attributes. There is no separate brick pool.
- Pages are recycled. When a page is reused, every pointer that targeted it must be invalidated.
- The unit of transfer is a page (one node's worth of data), not a single voxel or a brick.
Key invariants:
page_indexmust fit in 30 bits (CachePointerstores it in bits 0..29).- An insertion is identified by its own
InsertionParent, not by its position in a request buffer. Request order and insertion order may differ. - Slang consumers assume a child count of 64 and the demo attribute order. Changing the cache layout requires editing the Slang shaders.
- A page's
LocationPagemust describe the node the page represents, not its parent.
2. Page layouts
2.1 Pointer page
struct PointerPage { // WGSL (cache_common.wgsl)
occupancy_low: u32,
occupancy_high: u32,
pointers: array<u32, 64>,
}
struct StructurePage<N> { // Rust (schema.rs), used for sizing only
occupancy_mask: u64,
pointers: [CachePointer; N*N*N],
}
occupancy_low/occupancy_high are the low/high halves of the same 64-bit
mask as StructurePage::occupancy_mask on little-endian hardware. Bit i means
child i is occupied (may produce a hit). The occupancy mask lets the tracer
skip empty regions and coalesce DDA steps.
The Rust StructurePage is only used to size pointer_pages; the authoritative
layout is the WGSL PointerPage. Keep them in sync.
For N = 4, a pointer page is 8 + 64*4 = 264 bytes.
2.2 Location page
struct LocationPage {
node_id: u32, // application-defined locator within that structure
producer_id: u32, // producer that owns the node
anchor: StructureAnchor, // opaque, table-defined content identity
}
The cache never interprets these values; they are copied from insertion data and
returned in requests so the producer knows which node is missing. On the Rust
side, node_id is a StructureLocator encoded through TreeLocator<N>. In the
demo the active BVH table uses zeroed anchors; the toroidal table variant uses
world position plus a version word. The anchor is the structure identity, so
child requests inherit it from their parent page and producers never need a
host-side identity directory. LocationPage is 24 bytes.
On the Rust side, node_id and producer_id are the typed
StructureLocator and ProducerId newtypes (both #[repr(transparent)]
over u32), so the on-GPU layout above is unchanged. The same applies to
RequestInformation and InsertionParent.
2.3 Depth page
struct DepthPage(u32); // u32::MAX = unused
- External insertions start at depth 0.
- Internal insertions get parent depth + 1.
- Unused pages use
u32::MAX. - Depth is the eviction tie-breaker: pages are sorted deepest-first before the stable timestamp sort, so deeper pages win ties (see §7).
2.4 Attribute pages
Each attribute is its own buffer:
attribute buffer layout (per attribute)
┌────────────────────────────── page 0 ──────────────────────────────┐
│ child 0 words[0..W] │ child 1 words[0..W] │ ... │ child 63 words[0..W] │
├────────────────────────────── page 1 ──────────────────────────────┤
│ ... │
└────────────────────────────────────────────────────────────────────┘
total size = page_count * 64 * W * 4 bytes
An attribute is described by CacheAttribute:
pub struct CacheAttribute {
pub label: Option<&'static str>,
pub word_count: u32,
pub init: CacheAttributeInit,
}
pub enum CacheAttributeInit {
External, // copied from insertion data
DontTouch, // cache never writes it; application owns it
}
CacheLayout::add_attribute returns the attribute index. The layout generates
WGSL constants used by the insertion shader:
const ATTRIBUTE_COUNT: u32 = ...;
const ATTRIBUTE_WORD_COUNTS: array<u32, ...> = ...;
const ATTRIBUTE_COPY: array<bool, ...> = ...; // true for External
The demo layout is:
| Index | Label | Words | Meaning |
|---|---|---|---|
| 0 | color |
1 | packed RGBA bytes |
| 1 | normal |
3 | three floats |
Slang hardcodes these meanings (color at index 0, normal at index 1, stride 64).
CacheAttributeInit::DontTouch exists for application-computed data such as GI
or a leaf list; VoxelGiPipeline intended to use it but is not wired in.
3. Pointer encoding
bit 31 30 29 .. 0
┌───────────┬──────────┬────────────────────────┐
│subdividable│available │ page pointer (30 bits) │
└───────────┴──────────┴────────────────────────┘
| Bits 31/30 | Meaning |
|---|---|
0/0 |
Leaf: cannot be subdivided. No payload. |
1/0 |
Subdividable but not resident. A request may be issued. |
1/1 |
Subdividable, resident. Bits 0..29 are the page index. |
Rust API: CachePointer::new(Option<Option<u32>>).
| Argument | Bits | Meaning |
|---|---|---|
None |
0x00000000 |
leaf / unsubdividable |
Some(None) |
0x80000000 |
subdividable, unavailable |
Some(Some(p)) |
0xC0000000 | p |
subdividable, available at page p |
WGSL helpers in crates/vxls-voxel-cache/src/shaders/common.wgsl:
child_pointer_empty(subdivisible)child_pointer_subdivided(pointer)child_pointer_available(pointer)— checks both bitschild_pointer_pointer(pointer)— masks to 30 bitschild_pointer_make_available(pointer)
Child index convention (Rust and WGSL):
child_index = x + 4*y + 16*z // x fastest
pointer_index_to_cache_index(i) decomposes a flat request index into
page_index = i / 64, children_index = i % 64.
4. Public API
4.1 Construction
impl<const N: usize> VoxelCache<N>
where [(); N * N * N]:,
{
pub fn new(
device: &wgpu::Device,
page_count: usize,
max_requests: usize,
layout: &CacheLayout,
) -> Self;
pub fn gather_requests(
&self,
device: &wgpu::Device,
encoder: &mut ScopeEncoder<CommandEncoder>,
request_buffer: &CacheRequestBuffer,
);
pub fn insert(
&mut self,
device: &wgpu::Device,
encoder: &mut ScopeEncoder<CommandEncoder>,
insertions: &mut [&mut VoxelCacheInsertion<N>],
);
pub fn current_timestamp(&self) -> u32;
pub fn raytrace_bind_group_layout(&self) -> &BindGroupLayout;
pub fn raytrace_bind_group(&self) -> &BindGroup;
// debug
pub fn usage_timestamps(&self) -> &wgpu::Buffer;
}
page_count fixes every pool size. max_requests fixes the top-K capacity and
the request buffer capacity. Both are immutable after construction.
N is the branching factor, so N=4 means 64 children. This is a different N
from the N in Slang's VoxelCacheParameters<N>, which is the attribute
count (2 in the demo). This naming collision is a common source of confusion.
4.2 Insertion modes
pub enum VoxelCacheInsertion<'a, const N: usize> {
ExternalRequest(&'a CacheInsertionData<N>, &'a mut dyn CacheInvalidable<N>),
InternalRequest(&'a CacheInsertionData<N>),
}
- External — bring brand-new pages into the cache (e.g. a structure root). After insertion, the external owner is told to invalidate any of its pointers that targeted recycled pages.
- Internal — respond to cache-emitted requests. After insertion, the cache writes the new page indices into the requesting pages' child pointers.
You can pass several insertions in one call; they share one eviction preparation pass and one timestamp.
CacheInvalidable is implemented by the structure tables:
pub trait CacheInvalidable<const N: usize> {
fn invalidate(
&mut self,
encoder: &mut ScopeEncoder<CommandEncoder>,
cache_evictor: &CacheEvictor,
invalid_timestamp: u32,
);
fn validate_insertion(
&mut self,
device: &Device,
encoder: &mut ScopeEncoder<CommandEncoder>,
insertion: &CacheInsertionData<N>,
);
}
validate_insertion runs before page allocation: the table checks that each
external root's named slot still carries the same anchor and is still
subdividable, unavailable, then compacts the valid entries. This prevents a
stale root response from consuming a page, and lets a slot be reused (toroidal
move) without accepting a response for its old world position. The anchor check
is what makes host queue invalidation a cancellation hint rather than a
correctness requirement.
4.3 Insertion data
CacheInsertionData::new(device, max_page_count, layout) allocates:
| Buffer | Contents |
|---|---|
page_count |
number of entries in this batch |
insertion_information |
dense InsertionInformation<N> per entry |
location_pages |
dense LocationPage per entry (includes producer_id) |
insertion_parents |
dense InsertionParent per entry |
destination_indices |
reset to 0xFFFFFFFF by the validation pass; the insertion pass writes the destination page for accepted entries |
valid_indices |
filled by the validation pass: compacted indices of valid entries |
valid_count |
CacheInsertionData::upload writes 0; the validation pass fills the amount of valid entries |
| attribute buffers | dense per-entry attribute payloads |
Build the layout from a producer payload with
CacheLayout::from_attributes(&A::LAYOUT, &extras): producer attributes become
CacheAttributeInit::External and come first, extras are appended for
GPU-only data.
Upload a complete batch with
let entries: Vec<InsertionEntry<N>> = ...;
insertion.upload(&queue, &entries, &voxels)?;
InsertionEntry bundles the produced page's InsertionInformation, its
InsertionParent, and its LocationPage. voxels is a slice in
[entry][child] order (child order is x + 4*y + 16*z) and must contain
exactly entries.len() * N^3 elements. upload writes the structure, location,
and parent arrays, resets valid_count, sets page_count, and delegates the
attribute payloads to write_attributes. It does not pre-fill
destination_indices; both validation shaders reset every entry they process.
write_attributes validates that A::LAYOUT matches the cache layout and writes
one buffer per attribute. The DontTouch attributes after the producer prefix
are left untouched.
InsertionInformation<N> is just children: [ChildInformation; 64], where each
ChildInformation uses the four-state encoding below.
bit 31 = subdividable
bit 30 = occupied
InsertionParent makes the batch self-describing. It is what replaces the
former request-buffer lookup:
struct InsertionParent {
kind: u32, // 0 = internal child, 1 = external root
page_index: u32, // parent cache page, or 0xFFFFFFFF for an external root
children_index: u32, // child slot in the parent
depth: u32, // parent depth, or 0xFFFFFFFF for an external root
node_id: u32, // locator of the parent (0 for an external root)
producer_id: u32, // producer that owns the parent
anchor: StructureAnchor, // content identity of the structure
table_slot: u32, // external root placement, 0xFFFFFFFF internally
}
For an internal insertion, validation requires the parent page's
LocationPage to match node_id, producer_id, and anchor.
For an external insertion, validation requires the slot indexed by table_slot
to currently hold the parent's anchor. write_pointers.wgsl
repeats the internal check before linking, and the table insertion pass repeats
the external check after page allocation.
A batch no longer has to be ordered like the request buffer. The host may reorder, filter, or produce entries on different frames; the GPU validates each entry independently.
The insertion shader converts child information into a PointerPage:
- every child pointer starts as
empty(subdividable); - the occupancy mask bits are assembled from
occupied; - attributes are copied for
Externalattributes only.
destination_indices is an output used by write_pointers and by the structure
table insertion pass. 0xFFFFFFFF means "not inserted" (out of capacity, too
recently used, or invalid).
5. Request pipeline
5.1 Where requests come from
- During rendering,
VoxelCacheTracer::tracedescends nodes. If a child is subdividable, not resident, and the LOD says "keep going", it doesrequest_buffer[current_node_index].requests[child_index].add(1). - The structure tracer does the same for table slots whose root pointer is subdividable but unavailable.
- Every invocation also writes
usage_buffer[page] = frame_timestampfor pages it touches (if usage reporting is enabled).
The request-counter buffers are indexed per child, not per page:
request_counts_pages[page_index * 64 + child_index].
5.2 VoxelCache::gather_requests
Encoded in this order:
flowchart LR
A[request_counts_pages<br/>9.6M u32] --> B[top-K select<br/>k = max_requests]
B --> C[gather<br/>keys = counts<br/>values = indices]
C --> D[radix sort<br/>descending by count]
D --> E[write_requests.wgsl]
E --> F[(CacheRequestBuffer)]
B -.->|reset| A
- Top-K (
TopKSelector::select): selects up tokof the flatpage*64 + childcounters with the highest counts.kisrequest_buffer.max_requests(1024 in the demo).selected_countis written to a buffer; a zero count means no dispatch. - Gather (
gather_requests.wgsl): copies the selected counts into the shared scratch buffer as radix keys and the selected flat indices intosorted_requestsas radix values. Dispatch is indirect fromselected_count. - Radix sort (
RadixSorter::sort, descending): sorts the selected requests by request count, highest first. - Write requests (
write_requests.wgsl): for each sorted index, converts the flat index to(page_index, children_index), looks up the page'sLocationPage, and writes:
struct RequestInformation {
node_id: u32, // from LocationPage (the parent node)
children_index: u32, // requested child
producer_id: u32, // from LocationPage
demand: u32, // request counter for this slot this frame
anchor: StructureAnchor, // from LocationPage (content identity)
}
struct RequestMeta {
page_index: u32, // parent page, or 0xFFFFFFFF if external
children_index: u32,
depth: u32, // parent depth
table_slot: u32, // 0xFFFFFFFF internally; external root placement
}
producer_id lets a cache mix several producers and lets the host queue route
requests without guessing. demand is the raw request counter; the queue uses it
as the primary priority key. anchor lets producers stay stateless and lets the
queue key roots by content identity instead of table placement. table_slot
travels in RequestMeta because it is reinsertion/attachment information, not
request identity.
The external-root marker is RequestMeta.page_index == 0xFFFFFFFF, not
node_id == 0. Both an external root and child 0 of the root carry
node_id = 0, children_index = 0, so a queue keyed on those fields alone would
collapse them.
- Reset (
requests.wgsl): zeroes all request counters for the next frame.
request_count is copied from top_k.selected_count and then clamped in
write_requests.wgsl to the request-buffer capacity.
5.3 Host download
CacheRequestBuffer::host_download_requests(device, queue, callback) uses three
DownloadBuffer::read_buffer calls (count + informations + meta). A small
RequestMapState waits for all three and invokes the callback with
&request_informations[0..count] and &request_meta[0..count].
The callback is asynchronous by API, but the demo blocks on it with a
device.poll loop. The callback only ingests the wire requests into the
RequestQueue; the demo drains produced results and uploads the insertion batch
after both request buffers have landed. See
pipeline-and-producers.md.
5.4 What a producer receives
For an internal request:
node_idandanchoridentify the parent node.children_indexidentifies which child is missing.- The producer generates that child node as a
ProducedNode. It does not emit aLocationPageorInsertionParent:RequestKey::node_locator::<N>()names the produced node, andReadyItem::insertion_entry()derives both from the request key.
For an external (structure-table) request:
anchoris the table-defined content identity;table_slotis where the table currently points.node_idandchildren_indexare 0, andRequestMeta.page_indexis0xFFFFFFFF.- The producer generates a chunk root as a
ProducedNode; the queue derives the rootLocationPageand an externalInsertionParentwithproducer_id,anchor, andtable_slot.
There is no output-order requirement. Each insertion is attached to its parent
by its own InsertionParent.
6. Insertion pipeline
VoxelCache::insert runs these stages in one encoder:
flowchart TD
A[prepare eviction list] --> B[validate + compact<br/>one per insertion]
B --> C[insertion pass<br/>one per insertion]
C --> D[external invalidation]
D --> E[cache invalidation]
E --> F[write pointers<br/>internal insertions only]
F --> G[frame_timestamp += 1]
6.1 Eviction preparation
CacheEvictor::prepare_eviction_list:
reset_lru_list:lru_list[i] = i,consumed_count = 0.- Copy
depth_pagesinto the scratch buffer and radix-sort descending withlru_listas values.lru_listis now page indices ordered deepest first. indirect_copy:scratch[i] = timestamp_pages[lru_list[i]], rearranging timestamps into depth order.- Radix-sort
scratchascending withlru_listas values. This sort is stable, so equal timestamps keep the deepest-first order from step 2.
The resulting order is timestamp-major, depth-minor: least recently used first, with deeper pages first among equal timestamps. See §7.
6.2 Validation and insertion
Before any page is allocated, each batch is validated:
- Internal (
insertion.wgsl,validate_internal): the parent page must still have the samenode_id,producer_id, anchor, and depth, and the requested child pointer must still besubdividable, unavailable. - External (
fixed_table/validate_insertion.wgsl): the named table slot must still carry the sameanchor, and must still besubdividable, unavailable.
Valid entries are compacted into valid_indices and counted in valid_count.
The validation pass resets every destination_indices entry to 0xFFFFFFFF,
so invalid entries never get a page even if the host reuses an insertion buffer.
For each insertion, CacheInsertionPass::encode then:
- Dispatches
insertionindirectly frompage_count. - Reads
valid_countand computesavailable_amount = min(page_count_free - consumed, valid_count). - For compacted slot
i:- if
i >= available_amount, leavedestination_indices[entry]at0xFFFFFFFF(already reset by validation); - pick
page_index = lru_list[i + consumed_count]; - if
timestamp_pages[page_index] >= new_timestamp - 1, do not insert (protects pages touched in the previous frame). Note: on the very firstinsertcall,new_timestampis 1 and unused pages have timestamp 0, so0 >= 0rejects every page. The first insertion is therefore a no-op and the cache only starts filling on the second call. See §11; - otherwise mark the page, increment
pass_inserted_count, write location, pointer page, timestamp, depth 0, and copy external attributes.
- if
- Dispatch
consume(1 workgroup):consumed_count += inserted_count, then resetinserted_count.
Each insertion in the same insert call sees the updated consumed_count
because the passes are ordered, so multiple batches consume disjoint pages.
6.3 External invalidation
For each ExternalRequest, the cache calls invalidable.invalidate(...).
FixedStructureTable/ToroidalStructureTable scan their pointer arrays and
clear any pointer whose target page has timestamp == new_timestamp (i.e. was
just recycled).
6.4 Cache invalidation
invalidation.wgsl scans every page's 64 pointers. If a pointer is available
and points at a page whose timestamp equals new_timestamp, the pointer is reset
to empty(subdividable = true) — i.e. the node becomes "missing again" and can
be requested later.
6.5 Write pointers
For each internal insertion, write_pointers.wgsl reads the batch's own
InsertionParent (there is no request buffer):
let parent = insertion_data_parents[index];
if(parent.kind == INSERTION_PARENT_INTERNAL &&
insertion_data_destination_indices[index] != 0xFFFFFFFF &&
parent.page_index != insertion_data_destination_indices[index] &&
location_pages[parent.page_index] still has parent's identity)
{
structure_pointer_pages[parent.page_index].pointers[parent.children_index]
= child_pointer_make_available(destination_index);
structure_depth_pages[destination_index] = parent.depth + 1;
}
This is the step that actually links the new pages into the tree. The identity re-check catches the case where the parent page itself was recycled by the same insertion batch.
6.6 Timestamp advance
At the end of insert, frame_timestamp += 1. The renderer reads this value
via current_timestamp() and passes it to the shader as frame_timestamp, so
usage reporting and "dirty last frame" detection share one clock.
7. Eviction policy — timestamp-major, deepest-first ties
The eviction order is built in two radix passes:
- Depth, descending. Pages are sorted deepest first. This is the tie-breaker, not the primary key.
- Timestamp, ascending and stable. Pages are sorted by last-use timestamp. Because the radix sort is stable, equal timestamps keep the deepest-first order from pass 1.
Final order:
- Primary: least recently used first (oldest timestamp).
- Tie-break: deepest first (largest depth).
Consumption is in list order, so the oldest pages are reused first. The deepest-first tie-break means that, among pages last used at the same time, a page's resident children (which are deeper) appear earlier in the list and are reused first. This avoids recycling a parent and orphaning a subtree that is still resident, assuming the children's timestamps are equal or older.
Additional details:
- Unused pages have depth
u32::MAXand initial timestamp 0, so they lead both orderings and are normally consumed before resident data. - The insertion shader additionally rejects pages with
timestamp >= new_timestamp - 1, so pages touched in the immediately previous frame are skipped even if selected. - For pages with distinct timestamps, the depth tie-break has no effect; the result behaves like a pure LRU list.
8. Structure tables
The cache needs an entry point: given a world/chunk coordinate, where is the root page? Structure tables answer that and emit requests when it is missing.
8.1 FixedStructureTable
crates/vxls-voxel-cache/src/tables.rs.
- Backing buffer: one
CachePointerper slot, initialised tosubdividable, unavailable. - One request counter per slot (
CacheRequestHandler<1>). raytrace_bind_group: bindings[pointers, request_counts](group 1 in the render pipeline).gather_requests: top-K + sort +fixed_table/write_requests.wgsl; emitsnode_id = 0,children_index = 0,producer_id = table producer,demand = slot counter,anchor = slot anchor, andRequestMeta.page_index = 0xFFFFFFFF.validate_insertion:fixed_table/validate_insertion.wgslkeeps only slots that are stillsubdividable, unavailableand compacts their indices.insert:fixed_table/insertion.wgslreads each entry'sInsertionParentand setspointers[slot] = available(destination_indices[i])for external roots whose slot is still waiting.invalidate: clears slots pointing at pages recycled this insert.
The table is dense: allocation is slot_count * 4 bytes for pointers plus
slot_count * 4 for request counters.
8.2 ToroidalStructureTable
crates/vxls-terrain/src/lib.rs. Wraps FixedStructureTable with a movable block of chunks.
extent = (x, y, z)chunk counts.- Slot index from local coordinates:
x + z*extent.x + y*extent.x*extent.z(shader) — note the y/z order. move_position(queue, encoder, position)computes a new integer offset, reassigns every slot's anchor throughFixedStructureTable::reassign_slots, and runsterrain/shaders/toroidal_structure.wgsl: any slot whose world position changed is reset tosubdividable, unavailable, so it will be re-requested.- Slot identity is preserved across the move: the anchor is the structure
identity, so anchors that stay in view keep it even if they change slot, and
anchors that leave are retired.
reassign_slotsreturns the retired anchors so the host can cancel speculative queue work; correctness does not depend on it because the GPU validatesanchor/slot before linking a root. position_for_anchor(anchor)decodes a table anchor back to an absolute chunk coordinate.- Everything else delegates to the fixed table.
The Slang module toroidal_structure_table.slang mirrors this indexing and walks
the block of chunks (ToroidalStructureTableTracer). fixed_structure_table.slang
is imported by voxel.slang but unused.
8.3 DynamicStructureTable
crates/vxls-voxel-cache/src/tables.rs. A table whose slots are allocated and released at
runtime. It shares the GPU scaffolding with FixedStructureTable through the
private StructureTableCore; only the host-side slot management differs.
- Allocator. A host-side LIFO free list.
allocate(queue, anchor) -> Option<u32>pops a slot and installs the anchor;release(queue, slot) -> Option<StructureAnchor>clears the pointer and pushes the slot back. Allocating an already-live anchor is idempotent and returns its existing slot.allocatereturnsNonewhen the table is full. - Stable slot indices. A slot index never moves for the lifetime of an allocation, so it is safe to store in a TLAS or any other long-lived handle. This is why the table uses a free list rather than compaction.
- GPU liveness. A free slot has pointer
0(not subdividable), so the tracer skips it and insertion/validation reject it. An allocated slot is initialised tosubdividable, unavailable, exactly like a fixed-table slot, so the normal request/insertion path fills it. Released slots keep their stale anchor on the GPU until reused; the empty pointer is what makes them inert. - Stale requests.
fixed_table/write_requests.wgsl,validate_insertion.wgslandinsertion.wgslare reused unchanged. They already re-check the slot anchor and pointer state, so a request produced before a release/reuse cannot link the wrong root. - Growth.
reserve(device, queue, min_capacity)grows by doubling andgrowdoubles directly. Growth copies the pointer and anchor buffers into larger buffers (zeroing the new tail), rebuilds the size-dependent request handler, scratch resources and bind groups, and keeps the bind group layouts and pipelines. It must happen between frames, and any bind group obtained before growth must be re-fetched.allocate_or_growis a convenience wrapper. - Release semantics.
releaseunlinks the root; it does not free cache pages. Those become unreachable and are reclaimed by normal LRU eviction. The returned anchor can be passed to the request queue to cancel speculative work. - Reuse responsibility. Slots are reused immediately. The caller must not reuse a slot while a GPU structure (e.g. a TLAS) still references it. A deferred-free/retire queue can be layered on top later without changing the allocator.
9. Bind groups
9.1 Raytrace bind group (group 0 of the render pipeline)
| Binding | Buffer | Access |
|---|---|---|
| 0 | pointer_pages |
read-only storage |
| 1 | request_counts_pages |
read-write storage |
| 2 | timestamp_pages (usage) |
read-write storage |
| 3 | attribute buffers (binding_array) |
read-write storage |
The Slang VoxelCacheParameters<2> parameter block maps to these four bindings
in this order.
9.2 CacheStructure bind group
| Binding | Buffer |
|---|---|
| 0 | pointer pages |
| 1 | location pages |
| 2 | depth pages |
Used by write-requests, insertion, invalidation, and write-pointers passes.
9.3 Other pass bind groups
| Pass | Group 0 | Group 1 | Group 2 | Group 3 | Group 4 |
|---|---|---|---|---|---|
WriteRequestsPass |
structure | request handler (count + sorted) | request buffer | — | — |
CacheInsertionPass |
cache attributes | structure | insertion data | evictor | inserted count |
CacheInvalidationPass |
structure | evictor | — | — | — |
WritePointersPass |
structure | insertion data | — | — | — |
| Eviction reset / indirect copy | evictor | structure | scratch | — | — |
10. Configuration and sizing
The demo (main.rs) uses:
let mut layout = CacheLayout::default();
layout.add_attribute(CacheAttribute { label: Some("color"), word_count: 1, init: External });
layout.add_attribute(CacheAttribute { label: Some("normal"), word_count: 3, init: External });
let request_buffer = CacheRequestBuffer::new(&device, 1024);
let cache = VoxelCache::<4>::new(&device, 150_000, request_buffer.max_requests, &layout);
let insertion = CacheInsertionData::new(&device, 1024, &layout);
Scaling rules:
- Doubling
page_countdoubles every page pool, every attribute pool, the request counter array, the sorted request array, and the scratch buffer. page_count * N³must fit inu32(the request handler asserts this).page_countmust be< 2^30because pointers use 30 bits.max_requestsbounds top-K and the host request buffers. It does not boundInsertionData; the demo keeps them equal by convention.- Each attribute adds
page_count * 64 * word_count * 4bytes. DontTouchattributes are allocated but never written by the cache, so the application must initialise and maintain them.
Memory example at 150k pages and 2 attributes is tabulated in
architecture.md.
11. Known issues
| Symptom | Location | Impact | Confidence |
|---|---|---|---|
CacheStructure::new allocates location_pages with size_of::<StructurePage<N>>() instead of size_of::<LocationPage>(). |
crates/vxls-voxel-cache/src/structure.rs:44 |
At N=4, 264 B/page instead of 8 B/page: ~39.6 MB instead of ~1.2 MB for 150k pages. No correctness issue because shaders index by LocationPage stride. |
High |
StructurePage (Rust, u64 mask) and PointerPage (WGSL, two u32) are duplicated layout definitions. |
crates/vxls-voxel-cache/src/schema.rs:89-100, crates/vxls-voxel-cache/src/shaders/cache_common.wgsl:3-8 |
Little-endian compatible today; any field reorder breaks silently. StructurePage is only used for sizing. |
High |
request_buffer_count is written by every invocation of write_requests.wgsl with the same value. |
crates/vxls-voxel-cache/src/shaders/write_requests.wgsl:50 |
Benign data race (identical writes), but unnecessary and confusing. | Medium |
Insertion order no longer matters: each entry is validated against its InsertionParent and linked statelessly. |
insertion.wgsl, write_pointers.wgsl, fixed_table/insertion.wgsl |
A producer may reorder or filter results; unchanged request order is no longer a correctness requirement. | High |
CacheInsertionPass can silently insert fewer pages than requested (0xFFFFFFFF destinations) with no host feedback. |
crates/vxls-voxel-cache/src/shaders/insertion.wgsl |
Producer believes data is resident; requests may repeat or data may be missing. | High |
The first VoxelCache::insert call inserts nothing: new_timestamp = 1, unused pages have timestamp 0, and the guard rejects 0 >= new_timestamp - 1 (0 >= 0). |
crates/vxls-voxel-cache/src/lib.rs:248, crates/vxls-voxel-cache/src/shaders/insertion.wgsl:141-146 |
One-frame startup delay; any external roots submitted in the first batch are dropped and must be re-requested. | High |
Pointer/page-count limits are implicit (< 2^30, total elements < 2^32). |
schema.rs, requests.rs:82-85 |
Large configurations fail via asserts or truncation. | High |
CacheAttributeInit::DontTouch attributes can become stale after a page is recycled; the cache deliberately does not clear them. |
crates/vxls-voxel-cache/src/shaders/insertion.wgsl:164-178 |
Any consumer of such an attribute must tolerate garbage for recycled pages. | Medium |
The cache exposes usage_timestamps() for debugging only; timestamps are also used internally for invalidation and eviction. |
crates/vxls-voxel-cache/src/lib.rs:445-449 |
Easy to corrupt cache behaviour by writing to that buffer. | Medium |