StructureID separate from chunk 'anchor'

This commit is contained in:
2026-11-09 11:44:13 +01:00
parent e855ccd904
commit b6f4a9c432
19 changed files with 944 additions and 136 deletions
+9
View File
@@ -84,6 +84,14 @@ Do not change these casually; they are contracts between Rust, WGSL, and Slang.
10. **Eviction order:** timestamp-major (least recently used first), depth-minor
(deepest first). The depth pass runs descending and the timestamp pass runs
stable so equal timestamps keep the deepest-first order.
11. **Identity is not placement.** `StructureId` is stable tree identity
(monotonic per producer, never reused for another anchor). `StructureAnchor`
is the opaque, table-defined content identity (toroidal table: world
position + version). `TableSlot` is table-private placement and may change
freely. Root identity is `(ProducerId, StructureId, StructureAnchor)`; the
slot travels only as attachment metadata. Request keys, `LocationPage`,
`RequestInformation`, and `InsertionParent` must not treat the slot as
identity.
## Where to look for common tasks
@@ -95,6 +103,7 @@ Do not change these casually; they are contracts between Rust, WGSL, and Slang.
| Change eviction | `src/voxel_cache/eviction.rs`, `src/voxel_cache/shaders/eviction.wgsl`, `src/voxel_cache/shaders/insertion.wgsl` |
| Change insertion semantics | `src/voxel_cache.rs` (`insert`), `src/voxel_cache/pipelines.rs`, `src/voxel_cache/shaders/insertion.wgsl`, `write_pointers.wgsl` |
| Change world/chunk lookup | `src/voxel_cache/tables.rs`, `src/terrain.rs`, `shaders/toroidal_structure_table.slang` |
| Change structure identity / anchors | `src/voxel_cache/schema.rs` (`StructureAnchor`, wire structs), `src/production/request_queue.rs`, `src/voxel_cache/tables.rs`, `src/voxel_cache/shaders/common.wgsl`, fixed-table shaders |
| Change ray marching/LOD | `shaders/voxel.slang`, `shaders/voxel_cache.slang`, `shaders/lod_policies.slang` |
| Add a producer | `src/producers.rs` (interface), `src/main.rs` (`fullfill_request`), [`docs/pipeline-and-producers.md`](./docs/pipeline-and-producers.md) |
+14 -8
View File
@@ -113,8 +113,8 @@ flowchart LR
Req --> Gather[gather_requests<br/>top-K + radix sort]
TReq --> TGather[table gather_requests]
Gather --> RBuffer[(Request buffer<br/>structure_id, node_id, child)]
TGather --> TRBuffer[(Table request buffer)]
Gather --> RBuffer[(Request buffer<br/>structure_id, anchor, node_id, child)]
TGather --> TRBuffer[(Table request buffer<br/>structure_id, anchor, slot)]
RBuffer --> Host[Host fulfils requests]
TRBuffer --> Host
@@ -198,10 +198,10 @@ Consequences agents should keep in mind:
| `src/gpu/` | Radix sort, top-K, indirect dispatch, compaction helpers | Active infrastructure |
| `src/gpu_profiler/` | Timestamp profiling and memory accounting wrappers | Active infrastructure |
| `src/gi_pipeline.rs` (+ `sparse_set.rs`) | Planned GI pipeline using cache attribute sets | **Compiled but never instantiated** |
| `src/production.rs` | Producer/structure IDs and `VoxelProducer` trait | **Not declared in `main.rs`; inactive** |
| `src/production/host_production.rs` | Rayon-based `HostRequestHandler` | **Inactive** |
| `src/production/tree_locator.rs` | Compact N-tree locator encoding | **Inactive** |
| `src/production/request_queue.rs` | WIP request queue | **Untracked / WIP, inactive** |
| `src/production.rs` | Producer/structure IDs, `StructureAnchor` re-export, `VoxelProducer` trait | Compiled; durable contract |
| `src/production/host_production.rs` | Rayon-based `HostRequestHandler` | Compiled; `fullfill` still a stub |
| `src/production/tree_locator.rs` | Compact N-tree locator encoding | Compiled; inactive |
| `src/production/request_queue.rs` | Bounded, deduplicating, priority-ordered request queue | Compiled, unit-tested; not yet on the live async path |
| `src/host_production.rs` | Legacy `ChunkVoxelProducer` trait | **Inactive** |
| `src/tree.rs` | CPU N-tree prototype | **Inactive** |
| `src/sparse_tree.rs` | Packed color helper and node locator used by producers | Active via `main.rs`/`producers.rs` |
@@ -236,7 +236,13 @@ updating the stack breaks tracing.
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.
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 a stable `StructureId`. Anchors that stay in view keep
their id while their slot may change; anchors that leave retire their id, which
is never reused. In-flight root work carries the anchor and the latest slot, and
the GPU rejects an insertion whose anchor/id no longer matches the slot, so queue
invalidation is only a cancellation optimisation.
---
@@ -289,7 +295,7 @@ demo; the UI plots both a frame timer and a ray-march timer.
| Symptom | Location | Impact | Confidence |
|---|---|---|---|
| Location pages are sized with `size_of::<StructurePage<N>>()` (264 B at N=4) instead of `LocationPage` (8 B). | `src/voxel_cache/structure.rs:44` | ~39.6 MB allocated where ~1.2 MB is needed. | High — direct code read. |
| Location pages are sized with `size_of::<StructurePage<N>>()` (264 B at N=4) instead of `LocationPage` (28 B). | `src/voxel_cache/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. | `src/main.rs` around the `loop { ... poll ... }` after request downloads | Stalls the CPU on the render thread; prevents real pipelining/streaming. | High. |
| `VoxelTraceStack` is 5 entries and indexes `stack[10 - scale_exp/2]`, assuming `N = 4` and `chunk_power = 5`. | `shaders/voxel_cache.slang:93-96,177,189,257` | 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. |
+61 -17
View File
@@ -29,8 +29,8 @@ sequenceDiagram
Note over C,T: end of draw
C->>C: top-K + gather + descending radix sort
T->>T: top-K + gather + descending radix sort
C-->>H: request buffer (structure_id, node_id, child, producer, demand)
T-->>H: table request buffer (slot, 0, 0, producer, demand)
C-->>H: request buffer (structure_id, anchor, node_id, child, producer, demand)
T-->>H: table request buffer (structure_id, anchor, slot, 0, producer, demand)
H->>H: queue + produce one node per request (parallel, possibly across frames)
H->>I: upload CacheInsertionData (info, location, parent, attributes, count)
I->>C: validate/compact, recycle pages, write pages, invalidate stale pointers
@@ -51,11 +51,13 @@ response to frame N are first visible in frame N+1.
```rust
struct RequestInformation {
structure_id: u32, // which structure (chunk/table slot)
structure_id: u32, // stable tree identity (per producer)
node_id: u32, // locator of the *parent* node
children_index: u32, // which child is missing
producer_id: u32, // owner of the parent node
demand: u32, // request counter for this slot this frame
anchor: StructureAnchor, // opaque, table-defined content identity
table_slot: u32, // external root placement, NO_TABLE_SLOT internally
}
struct RequestMeta {
@@ -69,14 +71,22 @@ struct RequestMeta {
build the insertion's `InsertionParent` without referring back to a request
buffer.
- For external requests from a structure table: `RequestMeta.page_index =
0xFFFFFFFF`, `node_id = 0`, `children_index = 0`, and `structure_id` is the
table slot.
0xFFFFFFFF`, `node_id = 0`, `children_index = 0`, `structure_id` is the stable
tree id, `anchor` is the table-defined content identity, and `table_slot` is
the current placement.
- The root/child distinction must use `RequestMeta.page_index == 0xFFFFFFFF`,
**not** `node_id == 0`: child 0 of the root also has `node_id = 0`.
- Requests are sorted by demand (highest counter first) and capped at
`max_requests`.
- `producer_id` and `demand` are on the wire so the host queue can deduplicate
and prioritise without guessing.
- `structure_id`, `anchor`, and `table_slot` are three different things:
- `StructureId` is stable tree identity, monotonic per producer, never reused
for another anchor;
- `StructureAnchor` is the table-defined content identity (for the toroidal
table, world position plus a version word);
- `table_slot` is table-private placement and may change while the id and
anchor stay the same. It is deliberately not part of a request key.
### 2.2 Response
@@ -92,6 +102,7 @@ struct LocationPage {
structure_id: u32,
node_id: u32, // locator of the node itself
producer_id: u32,
anchor: StructureAnchor,
}
struct InsertionParent {
@@ -102,6 +113,8 @@ struct InsertionParent {
structure_id: u32,
node_id: u32, // parent locator (0 for an external root)
producer_id: u32,
anchor: StructureAnchor,
table_slot: u32, // external root placement, NO_TABLE_SLOT internally
}
```
@@ -110,9 +123,11 @@ Plus one attribute payload per entry (color and normal in the demo).
Before allocating pages, the cache validates every entry against the current
parent:
- internal: the parent page must still have the same identity and the child slot
must still be `subdividable, unavailable`;
- external: the table slot must still be `subdividable, unavailable`.
- internal: the parent page must still have the same structure id, producer,
locator, **and anchor**, and the child slot must still be
`subdividable, unavailable`;
- external: the named table slot must still carry the same anchor and structure
id, and its pointer must still be `subdividable, unavailable`.
Valid entries are compacted into `valid_indices`/`valid_count`; only those
consume eviction pages. The cache fills `destination_indices[i]` with the page
@@ -178,12 +193,13 @@ child instead of hardcoding color/normal.
The demo's `fullfill_request` (`src/main.rs`) does:
1. Map `structure_id` to an absolute chunk coordinate using
`ToroidalStructureTable::get_request_position`.
1. Decode the table-defined anchor with
`ToroidalStructureTable::position_for_anchor` to get an absolute chunk
coordinate.
2. Add the playground offset `+5000` to x and z and take `abs()` of y.
3. If `request_meta.page_index == 0xFFFFFFFF` (an external table request),
produce the chunk root at depth 0, emit the root locator, and emit
`InsertionParent::external(structure_id, producer_id)`.
`InsertionParent::external(structure_id, producer_id, anchor, table_slot)`.
4. Otherwise (an internal child request):
- decode the parent `NTreeNodeLocator<4>` from `node_id`;
- decode `children_index` into `(child_x, child_y, child_z)` with x fastest;
@@ -191,7 +207,8 @@ The demo's `fullfill_request` (`src/main.rs`) does:
- produce the child node at `parent_depth + 1` with the child's node
coordinates;
- emit the child locator as the new `LocationPage.node_id`;
- emit `InsertionParent::internal(meta, structure_id, node_id, producer_id)`.
- emit `InsertionParent::internal(meta, structure_id, node_id, producer_id,
anchor)`.
The root/child test must use `RequestMeta.page_index`, not `node_id`: child 0
of the root also has `node_id = 0`.
@@ -325,6 +342,7 @@ Defines a more ambitious interface:
pub struct ProducerId(pub u32);
pub struct StructureId(pub u32);
pub struct StructureLocator(pub u32);
pub use crate::voxel_cache::schema::StructureAnchor;
pub trait VoxelAttributes<const N: usize> {
fn attribute_count() -> usize;
@@ -337,6 +355,7 @@ pub trait VoxelProducer<const N: usize> {
&self,
producer_id: ProducerId,
id: StructureId,
anchor: StructureAnchor,
locator: StructureLocator,
) -> (InsertionInformation<N>, [Self::Output; N * N * N]);
}
@@ -349,6 +368,23 @@ Differences from the demo interface:
color/normal buffers.
- The producer receives a `StructureLocator` rather than depth + coordinates,
pushing locator arithmetic into the producer.
- `anchor` is the content identity. A producer must derive world position from
it (or from the id, which is stable) and never from a table slot.
### 6.1.1 Identity model
| Concept | Meaning |
|---|---|
| `ProducerId` | Which producer fulfils the request. |
| `StructureId` | Stable identity of one tree instance. Monotonic per producer, never reused for a different anchor. |
| `StructureAnchor` | Opaque, table-defined content identity. Two live slots must never share one anchor. |
| `TableSlot` | Table-private placement. Recycled freely and never part of tree identity. |
Root identity is `(producer, structure_id, anchor)`; child identity adds the
parent locator and child index. The table slot travels only as attachment
metadata. The toroidal table reuses a `StructureId` for an anchor that stays in
view, allocates fresh ids for anchors entering the window, and retires ids for
anchors that leave. Retired ids are never reassigned.
### 6.2 `src/production/host_production.rs`
@@ -373,6 +409,7 @@ Key model:
RequestKey {
producer_id,
structure_id,
anchor, // table-defined content identity
target: Root | Child { parent: StructureLocator, children_index },
}
```
@@ -393,10 +430,15 @@ Properties:
are dropped and re-emitted next frame.
- Each job has a generation and attempt count. Completions from evicted,
expired, retried, or invalidated jobs are discarded.
- `invalidate_structure(id)` and `invalidate_producer(id)` remove all matching
queued/in-flight/ready jobs. Use the former for toroidal slot reuse.
- `table_slot` is attachment metadata, not part of the key. It is refreshed on
every re-emission, including while a job is in flight or ready, so a produced
root can follow its anchor to a new slot.
- `invalidate_structure(id)`, `invalidate_producer(id)`, and
`invalidate_anchor(anchor)` remove matching queued/in-flight/ready jobs.
Invalidation is a cancellation/cleanup hint, **not** a correctness mechanism:
the GPU rejects stale insertions by checking the current anchor/id/slot.
- `ReadyItem::insertion_parent()` builds the `InsertionParent` for the insertion
batch from the latest `RequestMeta`.
batch from the key, the latest `RequestMeta`, and the latest `table_slot`.
The queue is unit-tested without a GPU (`cargo test production::request_queue`).
@@ -452,8 +494,10 @@ Minimum viable path with the current demo interface:
4. Emit a `LocationPage` matching the produced node. For internal requests,
it must be `parent.child(child_x, child_y, child_z)`.
5. Emit an `InsertionParent`:
- external: `InsertionParent::external(structure_id, producer_id)`;
- internal: `InsertionParent::internal(meta, structure_id, node_id, producer_id)`.
- external: `InsertionParent::external(structure_id, producer_id, anchor,
table_slot)`;
- internal: `InsertionParent::internal(meta, structure_id, node_id,
producer_id, anchor)`.
6. Set `page_count_buffer` to the number of entries. Order does not matter, but
every entry must have matching information, location, parent, and attributes.
7. Update the size passed to `CacheInsertionData::new` if the maximum batch can
+15 -6
View File
@@ -397,9 +397,18 @@ 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`, `InsertionParent`,
`AttributeArray`, `LocationPage`, and child-pointer helpers so the Rust and WGSL
sides share names.
`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`](./voxel-cache.md#22-location-page).
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`,
binding 1 `fixed_table_structure_ids`.
### 9.2 WGSL modules and entry points
@@ -412,9 +421,9 @@ sides share names.
| `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. |
| `fixed_table/validate_insertion.wgsl` | `validate_external` | Keep only root entries whose slot still waits for a page. |
| `fixed_table/insertion.wgsl` | `insertion` | Point table slots at inserted root pages. |
| `fixed_table/write_requests.wgsl` | `write_requests` | Emit root requests for table slots, resolving the slot's current structure id and anchor. |
| `fixed_table/validate_insertion.wgsl` | `validate_external` | Keep only root entries whose named slot still carries the same anchor/id and waits for a page. |
| `fixed_table/insertion.wgsl` | `insertion` | Re-check anchor/id/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. |
+53 -26
View File
@@ -68,14 +68,19 @@ For `N = 4`, a pointer page is `8 + 64*4 = 264` bytes.
```rust
struct LocationPage {
structure_id: u32, // which structure (world chunk, etc.)
structure_id: u32, // stable tree identity
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. In the demo,
`node_id` is an `NTreeNodeLocator` and `structure_id` is a toroidal table slot.
`node_id` is an `NTreeNodeLocator`, `structure_id` is a stable per-producer tree
id, and `anchor` is the toroidal table's world position plus a version word.
Child requests inherit the anchor from their parent page, so producers never need
a host-side `StructureId -> anchor` directory. `LocationPage` is 28 bytes.
### 2.3 Depth page
@@ -266,10 +271,12 @@ pub trait CacheInvalidable<const N: usize> {
```
`validate_insertion` runs before page allocation: the table checks that each
external root's slot is still `subdividable, unavailable` and 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.
external root's named slot still carries the same `anchor` and `structure_id`
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/id check is what makes host queue invalidation a cancellation hint rather
than a correctness requirement.
### 4.3 Insertion data
@@ -306,9 +313,18 @@ struct InsertionParent {
structure_id: u32, // structure the parent belongs to
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 `structure_id`, `node_id`, `producer_id`, and `anchor`.
For an external insertion, validation requires the slot indexed by `table_slot`
to currently hold the parent's `structure_id` and `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.
@@ -370,11 +386,13 @@ flowchart LR
```rust
struct RequestInformation {
structure_id: u32, // from LocationPage
structure_id: u32, // from LocationPage (stable tree identity)
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)
table_slot: u32, // 0xFFFFFFFF internally; external root placement
}
struct RequestMeta {
@@ -386,7 +404,8 @@ struct RequestMeta {
`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.
as the primary priority key. `anchor` lets producers stay stateless and lets the
queue key roots by content identity instead of table placement.
The external-root marker is `RequestMeta.page_index == 0xFFFFFFFF`, **not**
`node_id == 0`. Both an external root and child 0 of the root carry
@@ -412,20 +431,22 @@ The callback is asynchronous by API, but the demo blocks on it with a
For an **internal** request:
- `structure_id` and `node_id` identify the **parent** node.
- `structure_id`, `node_id`, and `anchor` identify the **parent** node.
- `children_index` identifies which child is missing.
- The producer must generate that child node and emit a `LocationPage` for the
child (typically `parent_locator.child(x, y, z)`).
child (typically `parent_locator.child(x, y, z)`) with the same anchor.
- It must also emit an internal `InsertionParent` carrying the parent page,
child index, depth, and parent identity.
child index, depth, parent identity, and anchor.
For an **external** (structure-table) request:
- `structure_id` is the table slot.
- `structure_id` is the stable tree id and `anchor` is the table-defined content
identity; `table_slot` is where the table currently points.
- `node_id` and `children_index` are 0, and `RequestMeta.page_index` is
`0xFFFFFFFF`.
- The producer must generate a chunk root and emit its `LocationPage` plus an
external `InsertionParent`.
external `InsertionParent` with `structure_id`, `producer_id`, `anchor`, and
`table_slot`.
There is no output-order requirement. Each insertion is attached to its parent
by its own `InsertionParent`.
@@ -467,10 +488,12 @@ first, with deeper pages first among equal timestamps. See §7.
Before any page is allocated, each batch is validated:
- **Internal** (`insertion.wgsl`, `validate_internal`): the parent page must
still have the same `structure_id`, `node_id`, `producer_id`, and depth, and
the requested child pointer must still be `subdividable, unavailable`.
- **External** (`fixed_table/validate_insertion.wgsl`): the table slot must still
be `subdividable, unavailable`.
still have the same `structure_id`, `node_id`, `producer_id`, anchor, and
depth, and the requested child pointer must still be `subdividable,
unavailable`.
- **External** (`fixed_table/validate_insertion.wgsl`): the named table slot
must still carry the same `structure_id` and `anchor`, and must still be
`subdividable, unavailable`.
Valid entries are compacted into `valid_indices` and counted in `valid_count`.
The validation pass resets every `destination_indices` entry to `0xFFFFFFFF`,
@@ -610,15 +633,19 @@ The table is dense: allocation is `slot_count * 4` bytes for pointers plus
- `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` computes a new integer offset around the camera and runs
`terrain/shaders/toroidal_structure.wgsl`: any slot whose world position
changed is reset to `subdividable, unavailable`, so it will be re-requested.
It also returns the list of changed slot ids on the CPU. The host must feed
that list to the request queue (`invalidate_structure`) before batching
insertions, otherwise a response produced for the slot's old position could
be accepted after the toroidal move.
- `get_request_position(structure_id)` maps a slot back to an absolute chunk
coordinate using the current offset and `rem_euclid`.
- `move_position(queue, encoder, position)` computes a new integer offset,
reassigns every slot's anchor through `FixedStructureTable::reassign_slots`,
and runs `terrain/shaders/toroidal_structure.wgsl`: any slot whose world
position changed is reset to `subdividable, unavailable`, so it will be
re-requested.
- Slot identity is preserved across the move: anchors that stay in view keep
their `StructureId` even if they change slot, anchors that enter get fresh
monotonic ids, and anchors that leave retire their id (never reused).
`reassign_slots` returns the retired ids so the host can cancel speculative
queue work; correctness does not depend on it because the GPU validates
`anchor`/`structure_id`/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
+20 -25
View File
@@ -1,7 +1,6 @@
#![feature(generic_const_exprs)]
#![feature(float_algebraic)]
use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
@@ -20,7 +19,6 @@ use glam::Mat4;
use glam::Vec3;
use glam::Vec4;
use itertools::Itertools;
use rayon::iter::IndexedParallelIterator;
use rayon::iter::IntoParallelRefIterator;
use rayon::iter::ParallelIterator;
use wgpu::BindGroupLayout;
@@ -48,20 +46,16 @@ use winit::event_loop::ActiveEventLoop;
use winit::event_loop::ControlFlow;
use winit::event_loop::EventLoop;
use winit::event_loop::OwnedDisplayHandle;
use winit::platform::x11::EventLoopBuilderExtX11;
use winit::window::Window;
use winit::window::WindowId;
use crate::camera::Camera;
use crate::egui_renderer::EguiRenderer;
use crate::gpu::radix_sort;
use crate::gpu::radix_sort::RadixSorter;
use crate::gpu_profiler::Frame;
use crate::gpu_profiler::Profile;
use crate::gpu_profiler::ProfilingEncoder;
use crate::producers::ChunkedProducer;
use crate::producers::SdfGenerator;
use crate::producers::TerrainGenerator;
use crate::production::request_queue::FrameId;
use crate::production::request_queue::IncomingRequest;
use crate::production::request_queue::QueueConfig;
@@ -75,12 +69,7 @@ use crate::voxel_cache::VoxelCacheInsertion;
use crate::voxel_cache::insertion::CacheInsertionData;
use crate::voxel_cache::requests::CacheRequestBuffer;
use crate::voxel_cache::schema::InsertionInformation;
use crate::voxel_cache::schema::InsertionParent;
use crate::voxel_cache::schema::LocationPage;
use crate::voxel_cache::schema::NO_PARENT_PAGE;
use crate::voxel_cache::schema::RequestInformation;
use crate::voxel_cache::schema::RequestMeta;
use crate::voxel_cache::tables::FixedStructureTable;
mod camera;
mod egui_renderer;
@@ -145,7 +134,6 @@ struct State
structure_table: Arc<Mutex<ToroidalStructureTable>>,
structure_table_request_buffer: Arc<CacheRequestBuffer>,
structure_table_cache_insertion: Arc<CacheInsertionData<4>>,
chunk_pos_map: Arc<HashMap<u32, (usize, usize, usize)>>,
instance_buffer: Buffer,
instance_count: usize,
usage_vec: Arc<Mutex<Vec<usize>>>,
@@ -214,6 +202,7 @@ impl State
.request_adapter(&wgpu::RequestAdapterOptions::default())
.await
.unwrap();
println!("{:#?}", adapter.get_info());
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
required_features: Features::IMMEDIATES
@@ -419,7 +408,6 @@ impl State
terrain_width * terrain_height * terrain_alt
);
let mut chunk_pos_map = HashMap::new();
let total_chunk_count = terrain_height * terrain_width * terrain_alt;
let structure_table_request_buffer = CacheRequestBuffer::new(&device, 128);
@@ -443,7 +431,6 @@ impl State
//dbg!(chunk_id);
let chunk_id = y * terrain_width * terrain_height + z * terrain_width + x;
chunk_pos_map.insert(chunk_id as u32, (x, y, z));
InstanceAttribute {
x: x as f32,
y: y as f32,
@@ -720,7 +707,6 @@ impl State
let d = fullfill_request(
&terrain_generator,
&work_item.key,
&Default::default(),
&structure_table_1,
);
(
@@ -795,7 +781,6 @@ impl State
camera: Default::default(),
instance_buffer,
instance_count,
chunk_pos_map: chunk_pos_map.into(),
rm_time: Arc::new(Mutex::new(0.)),
frame_time: Arc::new(Mutex::new(0.)),
terrain_width,
@@ -1107,9 +1092,19 @@ impl State
let mut prof_command_encoder = ProfilingEncoder::new(&self.device, &mut command_encoder);
{
self.structure_table
.lock()
.move_position(&mut prof_command_encoder, self.camera.position);
let retired = self.structure_table.lock().move_position(
&self.queue,
&mut prof_command_encoder,
self.camera.position,
);
// Cancellation is only an optimisation: stale insertions are
// rejected by the GPU because they no longer match the slot.
let mut request_queue = self.request_queue.lock();
for structure in retired
{
request_queue.invalidate_structure(structure);
}
}
{
@@ -1369,7 +1364,6 @@ impl State
self.insertion_debounce = true;
let frame_id: FrameId = self.voxel_cache.lock().current_timestamp().into();
let cloned_queue = self.queue.clone();
let cloned_map = self.chunk_pos_map.clone();
let finished = Arc::new(AtomicU32::new(0));
// Cache requests
@@ -1474,7 +1468,6 @@ impl State
);
let cloned_queue = self.queue.clone();
let cloned_map = self.chunk_pos_map.clone();
// Structure table requests
let cloned_st_insertion_data = self.structure_table_cache_insertion.clone();
@@ -1752,7 +1745,6 @@ pub struct ChunkImmediate
fn fullfill_request<const N: usize>(
generator: &dyn ChunkedProducer<N>,
request: &RequestKey,
map: &HashMap<u32, (usize, usize, usize)>,
table: &Arc<Mutex<ToroidalStructureTable>>,
) -> (
[u32; N * N * N],
@@ -1763,9 +1755,10 @@ fn fullfill_request<const N: usize>(
where
[(); N * N * N]:,
{
// Unpack structure id
//let (chunk_x, chunk_y, chunk_z) = *map.get(&request.structure_id).unwrap();
let (chunk_x, chunk_y, chunk_z) = table.lock().get_request_position(request.structure_id.0);
// Unpack structure identity: the anchor is the table-defined content
// identity, independent of the table slot that currently holds it.
let anchor = request.anchor;
let (chunk_x, chunk_y, chunk_z) = table.lock().position_for_anchor(anchor);
// let (chunk_x, chunk_y, chunk_z) = (
// (u32::MAX as isize + chunk_x) as usize,
@@ -1795,6 +1788,7 @@ where
structure_id: request.structure_id.0,
node_id: NTreeNodeLocator::<4>::root().as_usize() as u32,
producer_id: request.producer_id.0,
anchor,
};
}
else
@@ -1826,6 +1820,7 @@ where
structure_id: request.structure_id.0,
node_id: child_locator.as_usize() as u32,
producer_id: request.producer_id.0,
anchor,
};
}
+8 -1
View File
@@ -3,6 +3,8 @@ use bytemuck::Zeroable;
use crate::voxel_cache::schema::InsertionInformation;
pub use crate::voxel_cache::schema::StructureAnchor;
/// A structure locator format to locate node within an ntree
pub mod tree_locator;
@@ -53,11 +55,16 @@ where
type Output: VoxelAttributes<N>;
/// A pure function that can produce a voxel node based on the owner produer id, requesting structure, and the
/// requesting location within the structure
/// requesting location within the structure.
///
/// `anchor` is the table-defined content identity of the structure. Producers
/// must derive world position/content from it rather than from `id` or any
/// table slot: slots are placement and may change while `id` stays stable.
fn produce(
&self,
producer_id: ProducerId,
id: StructureId,
anchor: StructureAnchor,
locator: StructureLocator,
) -> (InsertionInformation<N>, [Self::Output; N * N * N]);
}
+1
View File
@@ -58,6 +58,7 @@ where
let (info, attributes) = self.producer.produce(
super::ProducerId(0),
super::StructureId(request.structure_id),
request.anchor,
super::StructureLocator(request.node_id),
);
+212 -19
View File
@@ -7,8 +7,10 @@ use crate::production::StructureId;
use crate::production::StructureLocator;
use crate::voxel_cache::schema::InsertionParent;
use crate::voxel_cache::schema::NO_PARENT_PAGE;
use crate::voxel_cache::schema::NO_TABLE_SLOT;
use crate::voxel_cache::schema::RequestInformation;
use crate::voxel_cache::schema::RequestMeta;
use crate::voxel_cache::schema::StructureAnchor;
/// Monotonic frame counter owned by the host. Using `u64` avoids concerns about
/// the cache's `u32` timestamp wrapping.
@@ -34,21 +36,31 @@ pub enum RequestTarget
}
/// Unique identity of an outstanding request.
///
/// The structure-table slot is deliberately absent: it is placement metadata,
/// not identity. Excluding it lets an in-flight root job survive a slot move
/// while the same anchor stays in view.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct RequestKey
{
pub producer_id: ProducerId,
pub structure_id: StructureId,
pub anchor: StructureAnchor,
pub target: RequestTarget,
}
impl RequestKey
{
pub fn root(producer_id: ProducerId, structure_id: StructureId) -> Self
pub fn root(
producer_id: ProducerId,
structure_id: StructureId,
anchor: StructureAnchor,
) -> Self
{
Self {
producer_id,
structure_id,
anchor,
target: RequestTarget::Root,
}
}
@@ -56,6 +68,7 @@ impl RequestKey
pub fn child(
producer_id: ProducerId,
structure_id: StructureId,
anchor: StructureAnchor,
parent: StructureLocator,
children_index: u32,
) -> Self
@@ -63,6 +76,7 @@ impl RequestKey
Self {
producer_id,
structure_id,
anchor,
target: RequestTarget::Child {
parent,
children_index,
@@ -144,6 +158,10 @@ pub struct IncomingRequest
/// Parent page information captured at the latest emission.
pub meta: RequestMeta,
/// Latest table slot reported for an external root; [`NO_TABLE_SLOT`]
/// otherwise. Refreshed on every re-emission.
pub table_slot: u32,
}
impl IncomingRequest
@@ -155,11 +173,12 @@ impl IncomingRequest
{
let producer_id = ProducerId(request.producer_id);
let structure_id = StructureId(request.structure_id);
let anchor = request.anchor;
let (key, priority) = if meta.page_index == NO_PARENT_PAGE
{
(
RequestKey::root(producer_id, structure_id),
RequestKey::root(producer_id, structure_id, anchor),
RequestPriority::root(request.demand),
)
}
@@ -169,6 +188,7 @@ impl IncomingRequest
RequestKey::child(
producer_id,
structure_id,
anchor,
StructureLocator(request.node_id),
request.children_index,
),
@@ -176,10 +196,20 @@ impl IncomingRequest
)
};
let table_slot = if key.is_root()
{
request.table_slot
}
else
{
NO_TABLE_SLOT
};
Self {
key,
priority,
meta: *meta,
table_slot,
}
}
}
@@ -208,6 +238,7 @@ pub struct ReadyItem<T>
{
pub key: RequestKey,
pub meta: RequestMeta,
pub table_slot: u32,
pub payload: T,
}
@@ -221,7 +252,12 @@ impl<T> ReadyItem<T>
{
RequestTarget::Root =>
{
InsertionParent::external(self.key.structure_id.0, self.key.producer_id.0)
InsertionParent::external(
self.key.structure_id.0,
self.key.producer_id.0,
self.key.anchor,
self.table_slot,
)
}
RequestTarget::Child {
parent,
@@ -240,6 +276,7 @@ impl<T> ReadyItem<T>
self.key.structure_id.0,
parent.0,
self.key.producer_id.0,
self.key.anchor,
)
}
}
@@ -320,6 +357,9 @@ struct Job<T>
first_seen: FrameId,
last_seen: FrameId,
meta: RequestMeta,
/// Latest slot reported for an external root. Refreshed even while the job
/// is in flight or ready so a produced root can follow a slot move.
table_slot: u32,
generation: u64,
attempt: u32,
payload: Option<T>,
@@ -440,6 +480,7 @@ impl<T> RequestQueue<T>
job.priority = request.priority;
job.meta = request.meta;
job.table_slot = request.table_slot;
job.last_seen = frame;
match job.state
@@ -496,6 +537,7 @@ impl<T> RequestQueue<T>
first_seen: frame,
last_seen: frame,
meta: request.meta,
table_slot: request.table_slot,
generation,
attempt: 0,
payload: None,
@@ -680,6 +722,7 @@ impl<T> RequestQueue<T>
result.push(ReadyItem {
key: job.key,
meta: job.meta,
table_slot: job.table_slot,
payload,
});
}
@@ -690,8 +733,9 @@ impl<T> RequestQueue<T>
/// Removes every job belonging to a structure.
///
/// Used when a structure slot is invalidated or reused (for example when
/// the toroidal structure table moves).
/// Correctness is enforced on the GPU by validating the insertion against
/// the current anchor/id/slot. Invalidation only cancels speculative work
/// and avoids wasted production.
pub fn invalidate_structure(&mut self, structure: StructureId) -> usize
{
self.invalidate_matching(|key| key.structure_id == structure)
@@ -703,6 +747,12 @@ impl<T> RequestQueue<T>
self.invalidate_matching(|key| key.producer_id == producer)
}
/// Removes every job whose anchor matches.
pub fn invalidate_anchor(&mut self, anchor: StructureAnchor) -> usize
{
self.invalidate_matching(|key| key.anchor == anchor)
}
fn invalidate_matching<F>(&mut self, mut predicate: F) -> usize
where
F: FnMut(&RequestKey) -> bool,
@@ -815,6 +865,7 @@ mod tests
const PRODUCER: ProducerId = ProducerId(0);
const STRUCTURE: StructureId = StructureId(1);
const ANCHOR: StructureAnchor = StructureAnchor::ZERO;
fn meta(page: u32, child: u32, depth: u32) -> RequestMeta
{
@@ -827,7 +878,13 @@ mod tests
fn child_key(parent: u32, child: u32) -> RequestKey
{
RequestKey::child(PRODUCER, STRUCTURE, StructureLocator(parent), child)
RequestKey::child(
PRODUCER,
STRUCTURE,
ANCHOR,
StructureLocator(parent),
child,
)
}
fn incoming(key: RequestKey, priority: RequestPriority) -> IncomingRequest
@@ -836,9 +893,11 @@ mod tests
key,
priority,
meta: meta(0, 0, 0),
table_slot: NO_TABLE_SLOT,
}
}
#[allow(clippy::too_many_arguments)]
fn wire(
structure: u32,
node: u32,
@@ -847,6 +906,8 @@ mod tests
demand: u32,
parent_page: u32,
depth: u32,
anchor: StructureAnchor,
table_slot: u32,
) -> (RequestInformation, RequestMeta)
{
(
@@ -856,6 +917,8 @@ mod tests
children_index: child,
producer_id: producer,
demand,
anchor,
table_slot,
},
RequestMeta {
page_index: parent_page,
@@ -880,7 +943,7 @@ mod tests
fn root_and_root_child_zero_do_not_collide()
{
let mut q = queue(8, 1, 8);
let root = RequestKey::root(PRODUCER, STRUCTURE);
let root = RequestKey::root(PRODUCER, STRUCTURE, ANCHOR);
let child = child_key(0, 0);
q.ingest(
@@ -899,16 +962,29 @@ mod tests
#[test]
fn from_wire_distinguishes_root_from_root_child_zero()
{
let (root_info, root_meta) = wire(STRUCTURE.0, 0, 0, PRODUCER.0, 7, u32::MAX, u32::MAX);
let (child_info, child_meta) = wire(STRUCTURE.0, 0, 0, PRODUCER.0, 7, 3, 0);
let (root_info, root_meta) = wire(
STRUCTURE.0,
0,
0,
PRODUCER.0,
7,
u32::MAX,
u32::MAX,
ANCHOR,
3,
);
let (child_info, child_meta) =
wire(STRUCTURE.0, 0, 0, PRODUCER.0, 7, 3, 0, ANCHOR, NO_TABLE_SLOT);
let root = IncomingRequest::from_wire(&root_info, &root_meta);
let child = IncomingRequest::from_wire(&child_info, &child_meta);
assert_eq!(root.key, RequestKey::root(PRODUCER, STRUCTURE));
assert_eq!(root.key, RequestKey::root(PRODUCER, STRUCTURE, ANCHOR));
assert_eq!(root.table_slot, 3);
assert_eq!(child.table_slot, NO_TABLE_SLOT);
assert_eq!(
child.key,
RequestKey::child(PRODUCER, STRUCTURE, StructureLocator(0), 0)
RequestKey::child(PRODUCER, STRUCTURE, ANCHOR, StructureLocator(0), 0)
);
assert_ne!(root.key, child.key);
}
@@ -916,7 +992,17 @@ mod tests
#[test]
fn from_wire_carries_demand_and_depth_into_priority()
{
let (info, meta) = wire(STRUCTURE.0, 5, 2, PRODUCER.0, 11, 9, 3);
let (info, meta) = wire(
STRUCTURE.0,
5,
2,
PRODUCER.0,
11,
9,
3,
ANCHOR,
NO_TABLE_SLOT,
);
let request = IncomingRequest::from_wire(&info, &meta);
assert_eq!(request.priority, RequestPriority::child(11, 3));
@@ -928,17 +1014,23 @@ mod tests
fn ready_item_builds_stateless_insertion_parent()
{
let mut q = queue(8, 2, 8);
let root = RequestKey::root(PRODUCER, STRUCTURE);
let root = RequestKey::root(PRODUCER, STRUCTURE, ANCHOR);
let child = child_key(4, 2);
q.ingest(
0,
[
incoming(root, RequestPriority::root(1)),
IncomingRequest {
key: root,
priority: RequestPriority::root(1),
meta: meta(0, 0, 0),
table_slot: 5,
},
IncomingRequest {
key: child,
priority: RequestPriority::child(1, 3),
meta: meta(7, 2, 3),
table_slot: NO_TABLE_SLOT,
},
],
);
@@ -956,6 +1048,8 @@ mod tests
assert_eq!(external.page_index, NO_PARENT_PAGE);
assert_eq!(external.structure_id, STRUCTURE.0);
assert_eq!(external.producer_id, PRODUCER.0);
assert_eq!(external.anchor, ANCHOR);
assert_eq!(external.table_slot, 5);
let internal = ready[1].insertion_parent();
assert!(internal.is_internal());
@@ -964,6 +1058,8 @@ mod tests
assert_eq!(internal.depth, 3);
assert_eq!(internal.node_id, 4);
assert_eq!(internal.structure_id, STRUCTURE.0);
assert_eq!(internal.anchor, ANCHOR);
assert_eq!(internal.table_slot, NO_TABLE_SLOT);
}
#[test]
@@ -978,6 +1074,7 @@ mod tests
key: child,
priority: RequestPriority::child(1, 3),
meta: meta(7, 5, 3),
table_slot: NO_TABLE_SLOT,
}],
);
@@ -995,8 +1092,8 @@ mod tests
fn producer_id_disambiguates_identical_structure_keys()
{
let mut q = queue(8, 1, 8);
let a = RequestKey::child(ProducerId(0), STRUCTURE, StructureLocator(7), 3);
let b = RequestKey::child(ProducerId(1), STRUCTURE, StructureLocator(7), 3);
let a = RequestKey::child(ProducerId(0), STRUCTURE, ANCHOR, StructureLocator(7), 3);
let b = RequestKey::child(ProducerId(1), STRUCTURE, ANCHOR, StructureLocator(7), 3);
q.ingest(
0,
@@ -1048,7 +1145,7 @@ mod tests
fn roots_outrank_children()
{
let mut q = queue(8, 8, 8);
let root = RequestKey::root(PRODUCER, STRUCTURE);
let root = RequestKey::root(PRODUCER, STRUCTURE, ANCHOR);
let child = child_key(0, 0);
q.ingest(
@@ -1324,8 +1421,8 @@ mod tests
fn invalidate_producer_only_removes_that_producer()
{
let mut q = queue(8, 8, 8);
let a = RequestKey::child(ProducerId(0), STRUCTURE, StructureLocator(1), 0);
let b = RequestKey::child(ProducerId(1), STRUCTURE, StructureLocator(1), 0);
let a = RequestKey::child(ProducerId(0), STRUCTURE, ANCHOR, StructureLocator(1), 0);
let b = RequestKey::child(ProducerId(1), STRUCTURE, ANCHOR, StructureLocator(1), 0);
q.ingest(
0,
@@ -1348,4 +1445,100 @@ mod tests
assert_eq!(stats.dropped, 1);
assert!(q.is_empty());
}
fn root_incoming(slot: u32) -> IncomingRequest
{
IncomingRequest {
key: RequestKey::root(PRODUCER, STRUCTURE, ANCHOR),
priority: RequestPriority::root(1),
meta: meta(NO_PARENT_PAGE, 0, NO_PARENT_PAGE),
table_slot: slot,
}
}
#[test]
fn root_job_refreshes_table_slot_while_in_flight()
{
let mut q = queue(8, 1, 8);
q.ingest(0, [root_incoming(1)]);
let item = q.pop().unwrap();
// The same anchor reappears at a new slot before the result is drained.
q.ingest(0, [root_incoming(2)]);
assert_eq!(q.complete(item, 7), CompleteOutcome::Accepted);
let ready = q.drain_ready_matching(0, 8, |_| true);
assert_eq!(ready.len(), 1);
let parent = ready[0].insertion_parent();
assert!(parent.is_external());
assert_eq!(parent.table_slot, 2);
assert_eq!(parent.anchor, ANCHOR);
assert_eq!(parent.structure_id, STRUCTURE.0);
}
#[test]
fn root_key_is_stable_across_slot_moves()
{
let mut q = queue(8, 1, 8);
q.ingest(0, [root_incoming(1)]);
q.ingest(1, [root_incoming(9)]);
// Same producer/id/anchor: one job, refreshed in place, not duplicated.
assert_eq!(q.len(), 1);
assert!(q.contains(&RequestKey::root(PRODUCER, STRUCTURE, ANCHOR)));
let item = q.pop().unwrap();
q.complete(item, 1);
let ready = q.drain_ready_matching(1, 8, |_| true);
assert_eq!(ready[0].table_slot, 9);
}
#[test]
fn different_anchors_with_same_structure_are_distinct()
{
// A correct table never does this, but the queue must not merge them.
let mut q = queue(8, 1, 8);
let a = RequestKey::child(PRODUCER, STRUCTURE, ANCHOR, StructureLocator(1), 0);
let b = RequestKey::child(
PRODUCER,
STRUCTURE,
StructureAnchor::from_world(1, 2, 3, 0),
StructureLocator(1),
0,
);
q.ingest(
0,
[
incoming(a, RequestPriority::child(1, 0)),
incoming(b, RequestPriority::child(1, 0)),
],
);
assert_eq!(q.len(), 2);
}
#[test]
fn invalidate_anchor_removes_matching_jobs()
{
let mut q = queue(8, 8, 8);
let anchor = StructureAnchor::from_world(4, 5, 6, 0);
let a = RequestKey::child(PRODUCER, STRUCTURE, anchor, StructureLocator(1), 0);
let b = child_key(1, 0);
q.ingest(
0,
[
incoming(a, RequestPriority::child(1, 0)),
incoming(b, RequestPriority::child(1, 0)),
],
);
assert_eq!(q.invalidate_anchor(anchor), 1);
assert!(q.contains(&b));
assert!(!q.contains(&a));
}
}
+41 -20
View File
@@ -7,7 +7,9 @@ use wgpu::CommandEncoder;
use wgpu::include_wgsl;
use crate::gpu::create_multi_buffers_bind_group_layout;
use crate::production::StructureId;
use crate::voxel_cache;
use crate::voxel_cache::schema::StructureAnchor;
use crate::voxel_cache::tables::FixedStructureTable;
/// A torroidal structure table for "infinite" world purposes.
@@ -55,6 +57,15 @@ impl ToroidalStructureTable
let current_offset = Self::offset_from_center(extent, initial_position);
// Initial anchor of every slot is its world position in the starting
// window. Structure ids are table-internal and start at `0..size`.
let anchors = (0..size)
.map(|slot| {
let (x, y, z) = Self::position_for_offset(extent, slot, current_offset);
StructureAnchor::from_world(x as i32, y as i32, z as i32, 0)
})
.collect();
let bind_group_layout = create_multi_buffers_bind_group_layout(
device,
1,
@@ -82,11 +93,12 @@ impl ToroidalStructureTable
ToroidalStructureTable {
extent,
fixed_structure_table: FixedStructureTable::new(
fixed_structure_table: FixedStructureTable::new_with_anchors(
device,
size,
max_requests,
producer_id,
anchors,
),
position: initial_position,
current_offset,
@@ -95,35 +107,43 @@ impl ToroidalStructureTable
}
/// Moves the center position to `new_position`.
/// This requires updating to structure table to remove disapearing chunks.
/// This requires updating the structure table to remove disapearing chunks.
///
/// Returns the structure slots whose world position changed. The host must
/// invalidate any pending request/insertion work for those slots before it
/// batches insertions for this frame.
/// Slots whose world position changed get a new anchor. Anchors that remain
/// in view keep their [`StructureId`]; anchors that leave are retired. The
/// invalidation pass resets the pointers of moved slots so their roots are
/// requested again.
///
/// Returns the retired structure ids. The host may use them to cancel
/// speculative queue work; correctness does not depend on it because GPU
/// insertion validates the anchor/id/slot.
pub fn move_position(
&mut self,
queue: &wgpu::Queue,
encoder: &mut CommandEncoder,
new_position: Vec3,
) -> Vec<u32>
) -> Vec<StructureId>
{
let previous_offset = self.current_offset;
let new_offset = Self::offset_from_center(self.extent, new_position);
self.current_offset = new_offset;
self.position = new_position;
let mut invalidated = Vec::new();
let mut retired = Vec::new();
if previous_offset != new_offset
{
let size = self.extent.0 * self.extent.1 * self.extent.2;
for id in 0..size
{
let previous = Self::position_for_offset(self.extent, id, previous_offset);
let current = Self::position_for_offset(self.extent, id, new_offset);
if previous != current
{
invalidated.push(id as u32);
}
}
let new_anchors: Vec<StructureAnchor> = (0..size)
.map(|slot| {
let (x, y, z) = Self::position_for_offset(self.extent, slot, new_offset);
StructureAnchor::from_world(x as i32, y as i32, z as i32, 0)
})
.collect();
let (_assignments, retired_ids) = self
.fixed_structure_table
.reassign_slots(queue, &new_anchors);
retired = retired_ids;
}
let invalidation_parameters = ToroidalInvalidationImmediates {
@@ -161,13 +181,14 @@ impl ToroidalStructureTable
self.extent.2.div_ceil(4) as u32,
);
invalidated
retired
}
/// Given the structure id, returns the position of the requesting chunk
pub fn get_request_position(&self, structure_id: u32) -> (isize, isize, isize)
/// Returns the world position encoded in a table anchor.
pub fn position_for_anchor(&self, anchor: StructureAnchor) -> (isize, isize, isize)
{
Self::position_for_offset(self.extent, structure_id as usize, self.current_offset)
let (x, y, z, _version) = anchor.world();
(x as isize, y as isize, z as isize)
}
fn position_for_offset(
+105 -1
View File
@@ -99,6 +99,60 @@ where
// SAFETY: u64, then packed u32s ([`CachePointer`]s), so no padding, all bit patterns are allowed
unsafe impl<const N: usize> Pod for StructurePage<N> where [(); N * N * N]: {}
/// Number of `u32` words in a [`StructureAnchor`].
pub const ANCHOR_WORDS: usize = 4;
/// Sentinel used in [`RequestInformation::table_slot`] and
/// [`InsertionParent::table_slot`] to mark an insertion that is not attached to
/// a structure-table slot (internal requests).
pub const NO_TABLE_SLOT: u32 = u32::MAX;
/// Sentinel reserved so that a structure id is never allocated. Structure ids
/// are monotonic per producer and a value is never reused for another anchor.
pub const NO_STRUCTURE_ID: u32 = u32::MAX;
/// Opaque, table-defined identity of a structure's *content*.
///
/// The cache and the request queue never interpret these words. A table decides
/// what an anchor means (for example a world position plus a version) and is
/// responsible for never exposing two live slots with the same anchor. The
/// anchor travels on the wire so producers stay stateless and so stale
/// insertions can be rejected against the current table state.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)]
#[repr(C)]
pub struct StructureAnchor
{
pub words: [u32; ANCHOR_WORDS],
}
impl StructureAnchor
{
/// Convenience anchor used by tests and by tables that do not need a
/// distinguishable identity at startup.
#[allow(dead_code)]
pub const ZERO: Self = Self {
words: [0; ANCHOR_WORDS],
};
/// Table-defined helper for world-position anchors: `(x, y, z, version)`.
pub fn from_world(x: i32, y: i32, z: i32, version: u32) -> Self
{
Self {
words: [x as u32, y as u32, z as u32, version],
}
}
pub fn world(self) -> (i32, i32, i32, u32)
{
(
self.words[0] as i32,
self.words[1] as i32,
self.words[2] as i32,
self.words[3],
)
}
}
/// Data stored alongside cache structure so that application can locate a
/// particular request
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
@@ -113,6 +167,9 @@ pub struct LocationPage
/// Identifier of the producer that owns this node
pub producer_id: u32,
/// Opaque content identity inherited from the root request.
pub anchor: StructureAnchor,
}
/// Page storing the depth of the current node related to its root.
@@ -159,6 +216,13 @@ pub struct RequestInformation
/// The amount of times this request was emitted this frame. Higher means more urgent.
pub demand: u32,
/// Opaque content identity of the structure this request belongs to.
pub anchor: StructureAnchor,
/// Table slot for an external root request; [`NO_TABLE_SLOT`] for internal
/// requests.
pub table_slot: u32,
}
/// Metainformation kept along each request, to know which node made the demand
@@ -228,6 +292,13 @@ pub struct InsertionParent
/// Producer that owns the parent.
pub producer_id: u32,
/// Opaque content identity of the structure the parent belongs to.
pub anchor: StructureAnchor,
/// Table slot of an external root; [`NO_TABLE_SLOT`] for internal
/// insertions.
pub table_slot: u32,
}
impl InsertionParent
@@ -238,6 +309,7 @@ impl InsertionParent
structure_id: u32,
node_id: u32,
producer_id: u32,
anchor: StructureAnchor,
) -> Self
{
Self {
@@ -248,11 +320,18 @@ impl InsertionParent
structure_id,
node_id,
producer_id,
anchor,
table_slot: NO_TABLE_SLOT,
}
}
/// Parent information for the root of an external structure.
pub fn external(structure_id: u32, producer_id: u32) -> Self
pub fn external(
structure_id: u32,
producer_id: u32,
anchor: StructureAnchor,
table_slot: u32,
) -> Self
{
Self {
kind: InsertionParentKind::EXTERNAL.raw(),
@@ -262,6 +341,8 @@ impl InsertionParent
structure_id,
node_id: 0,
producer_id,
anchor,
table_slot,
}
}
@@ -335,3 +416,26 @@ where
// SAFETY: Packed array of u32, no padding, all bit patterns allowed
unsafe impl<const N: usize> Pod for InsertionInformation<N> where [(); N * N * N]: {}
#[cfg(test)]
mod tests
{
use super::*;
#[test]
fn wire_layout_sizes_are_stable()
{
assert_eq!(size_of::<StructureAnchor>(), 16);
assert_eq!(size_of::<RequestInformation>(), 40);
assert_eq!(size_of::<LocationPage>(), 28);
assert_eq!(size_of::<InsertionParent>(), 48);
assert_eq!(size_of::<RequestMeta>(), 12);
}
#[test]
fn anchor_world_round_trips_negative_coordinates()
{
let anchor = StructureAnchor::from_world(-17, 42, -3, 7);
assert_eq!(anchor.world(), (-17, 42, -3, 7));
}
}
+28 -1
View File
@@ -5,13 +5,35 @@ struct CacheIndex
page_index: u32,
children_index: u32,
}
const ANCHOR_WORDS: u32 = 4u;
struct StructureAnchor
{
words: array<u32, 4>
}
fn anchor_eq(a: StructureAnchor, b: StructureAnchor) -> bool
{
for(var i = 0u; i < ANCHOR_WORDS; i++)
{
if(a.words[i] != b.words[i])
{
return false;
}
}
return true;
}
struct RequestInformation
{
structure_id: u32,
node_id: u32,
children_index: u32,
producer_id: u32,
demand: u32
demand: u32,
anchor: StructureAnchor,
table_slot: u32
}
struct RequestMeta
@@ -25,6 +47,8 @@ struct RequestMeta
const NO_PARENT_PAGE: u32 = 0xFFFFFFFFu;
const INSERTION_PARENT_INTERNAL: u32 = 0u;
const INSERTION_PARENT_EXTERNAL: u32 = 1u;
// No structure-table slot (internal request/insertion).
const NO_TABLE_SLOT: u32 = 0xFFFFFFFFu;
struct InsertionParent
{
@@ -35,6 +59,8 @@ struct InsertionParent
structure_id: u32,
node_id: u32,
producer_id: u32,
anchor: StructureAnchor,
table_slot: u32
}
struct AttributeArray
@@ -47,6 +73,7 @@ struct LocationPage
structure_id: u32,
node_id: u32,
producer_id: u32,
anchor: StructureAnchor
}
fn child_information_occupied(info: u32) -> bool
@@ -10,8 +10,24 @@
@group(1) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
@group(1) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
// Group 2: Slot metadata
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
@group(2) @binding(1) var<storage, read_write> fixed_table_structure_ids: array<u32>;
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
fn slot_matches(parent: InsertionParent) -> bool
{
let slot = parent.table_slot;
if(slot == NO_TABLE_SLOT || slot >= arrayLength(&fixed_table_anchors))
{
return false;
}
return parent.structure_id == fixed_table_structure_ids[slot]
&& anchor_eq(parent.anchor, fixed_table_anchors[slot]);
}
@compute
@workgroup_size(256, 1, 1)
fn insertion(@builtin(global_invocation_id) gid: vec3<u32>)
@@ -35,17 +51,25 @@ fn insertion(@builtin(global_invocation_id) gid: vec3<u32>)
return;
}
if(parent.structure_id >= arrayLength(&fixed_table_pointers))
// Re-check identity and pointer state after allocation. A slot move between
// validation and insertion must not link the wrong tree.
if(!slot_matches(parent))
{
return;
}
let slot = parent.table_slot;
if(slot >= arrayLength(&fixed_table_pointers))
{
return;
}
// Re-check that the slot is still waiting for this root.
let pointer = fixed_table_pointers[parent.structure_id];
let pointer = fixed_table_pointers[slot];
if(!child_pointer_subdivided(pointer) || child_pointer_available(pointer))
{
return;
}
fixed_table_pointers[parent.structure_id] = child_pointer_make_available(destination);
fixed_table_pointers[slot] = child_pointer_make_available(destination);
}
@@ -10,8 +10,27 @@
@group(1) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
@group(1) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
// Group 2: Slot metadata
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
@group(2) @binding(1) var<storage, read_write> fixed_table_structure_ids: array<u32>;
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
/// The slot named by the parent still holds the same anchor and structure id.
/// This is what makes queue invalidation optional: a stale root response for a
/// retired or reused slot can no longer win.
fn slot_matches(parent: InsertionParent) -> bool
{
let slot = parent.table_slot;
if(slot == NO_TABLE_SLOT || slot >= arrayLength(&fixed_table_anchors))
{
return false;
}
return parent.structure_id == fixed_table_structure_ids[slot]
&& anchor_eq(parent.anchor, fixed_table_anchors[slot]);
}
/// Validates external root insertions against the structure table.
///
/// A root is still wanted while its table slot is subdivisible but not yet
@@ -40,17 +59,23 @@ fn validate_external(@builtin(global_invocation_id) gid: vec3<u32>)
return;
}
if(parent.structure_id >= arrayLength(&fixed_table_pointers))
if(!slot_matches(parent))
{
return;
}
let pointer = fixed_table_pointers[parent.structure_id];
let slot = parent.table_slot;
if(slot >= arrayLength(&fixed_table_pointers))
{
return;
}
let pointer = fixed_table_pointers[slot];
if(!child_pointer_subdivided(pointer) || child_pointer_available(pointer))
{
return;
}
let slot = atomicAdd(&insertion_data_valid_count, 1u);
insertion_data_valid_indices[slot] = index;
let valid_slot = atomicAdd(&insertion_data_valid_count, 1u);
insertion_data_valid_indices[valid_slot] = index;
}
@@ -8,6 +8,10 @@
@group(1) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
@group(1) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
/// Group 2: Slot metadata (current anchor/id assignment)
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
@group(2) @binding(1) var<storage, read_write> fixed_table_structure_ids: array<u32>;
var<immediate> table_producer_id: u32;
@compute
@@ -21,14 +25,22 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
return;
}
let structure_id = request_handler_requests[index];
// The request handler emits a slot index; resolve its current assignment so
// the request carries stable identity plus the current placement.
let slot = request_handler_requests[index];
if(slot >= arrayLength(&fixed_table_anchors))
{
return;
}
var request_info: RequestInformation;
request_info.structure_id = structure_id;
request_info.structure_id = fixed_table_structure_ids[slot];
request_info.node_id = 0;
request_info.children_index = 0;
request_info.producer_id = table_producer_id;
request_info.demand = request_handler_counts[structure_id];
request_info.demand = request_handler_counts[slot];
request_info.anchor = fixed_table_anchors[slot];
request_info.table_slot = slot;
var request_meta: RequestMeta;
// External requests have no parent page.
+2 -1
View File
@@ -46,7 +46,8 @@ fn internal_parent_is_valid(parent: InsertionParent) -> bool
let location = structure_location_pages[parent.page_index];
if(location.structure_id != parent.structure_id ||
location.node_id != parent.node_id ||
location.producer_id != parent.producer_id)
location.producer_id != parent.producer_id ||
!anchor_eq(location.anchor, parent.anchor))
{
return false;
}
+2 -1
View File
@@ -52,7 +52,8 @@ fn write_pointers(@builtin(global_invocation_id) gid: vec3<u32>)
let location = structure_location_pages[parent.page_index];
if(location.structure_id != parent.structure_id ||
location.node_id != parent.node_id ||
location.producer_id != parent.producer_id)
location.producer_id != parent.producer_id ||
!anchor_eq(location.anchor, parent.anchor))
{
return;
}
@@ -38,6 +38,8 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
request_information.children_index = request_location.children_index;
request_information.producer_id = structure_location_pages[page_index].producer_id;
request_information.demand = request_handler_counts[request_index];
request_information.anchor = structure_location_pages[page_index].anchor;
request_information.table_slot = NO_TABLE_SLOT;
// Fill out request meta information
var request_meta: RequestMeta;
+300
View File
@@ -3,6 +3,7 @@ use wgpu::util::DeviceExt;
use crate::gpu::indirect_buffer::IndirectBuffer1D;
use crate::gpu_profiler::ScopeEncoder;
use crate::gpu_profiler::memory_profiler::MemoryProfile;
use crate::production::StructureId;
use crate::voxel_cache::CacheInvalidable;
use crate::voxel_cache::CacheRessources;
use crate::voxel_cache::create_multi_buffers_bg_bg_layout;
@@ -12,6 +13,8 @@ use crate::voxel_cache::layout::CacheLayout;
use crate::voxel_cache::requests::CacheRequestBuffer;
use crate::voxel_cache::requests::CacheRequestHandler;
use crate::voxel_cache::schema::CachePointer;
use crate::voxel_cache::schema::NO_STRUCTURE_ID;
use crate::voxel_cache::schema::StructureAnchor;
use super::pipelines::include_cache_wgsl;
@@ -37,6 +40,78 @@ macro_rules! include_table_wgsl {
}};
}
/// One slot whose anchor or structure id changed during a reassignment.
///
/// Returned for diagnostics and optional host-side cancellation. Correctness
/// does not depend on callers reading these fields; the GPU validates the
/// current slot metadata before accepting an insertion.
#[derive(Clone, Copy, Debug)]
#[allow(dead_code)]
pub struct SlotAssignment
{
pub slot: u32,
pub previous_anchor: StructureAnchor,
pub previous_structure: StructureId,
pub anchor: StructureAnchor,
pub structure: StructureId,
}
/// Reuses ids for anchors that are still present, allocates fresh ids for
/// anchors entering the table, and returns the ids that are no longer used.
///
/// A structure id is never reused for a different anchor. Exhaustion is a fatal
/// error rather than a wrap, because wrapping would silently alias identities.
fn plan_slot_reassignment(
old_anchors: &[StructureAnchor],
old_ids: &[StructureId],
new_anchors: &[StructureAnchor],
next_structure_id: &mut u32,
) -> (Vec<StructureId>, Vec<StructureId>)
{
use std::collections::HashMap;
use std::collections::HashSet;
assert_eq!(old_anchors.len(), old_ids.len());
assert!(
new_anchors.iter().collect::<HashSet<_>>().len() == new_anchors.len(),
"a structure table must not expose two live slots with the same anchor"
);
let mut by_anchor = HashMap::with_capacity(old_anchors.len());
for (&anchor, &id) in old_anchors.iter().zip(old_ids)
{
by_anchor.insert(anchor, id);
}
let mut new_ids = Vec::with_capacity(new_anchors.len());
for &anchor in new_anchors
{
if let Some(&id) = by_anchor.get(&anchor)
{
new_ids.push(id);
}
else
{
assert_ne!(
*next_structure_id, NO_STRUCTURE_ID,
"structure id space exhausted"
);
new_ids.push(StructureId(*next_structure_id));
*next_structure_id += 1;
}
}
let live: HashSet<StructureAnchor> = new_anchors.iter().copied().collect();
let retired = old_anchors
.iter()
.zip(old_ids)
.filter(|(anchor, _)| !live.contains(anchor))
.map(|(_, id)| *id)
.collect();
(new_ids, retired)
}
/// A structure table with a fixed length
pub struct FixedStructureTable
{
@@ -47,6 +122,17 @@ pub struct FixedStructureTable
common_ressources: CacheRessources<1>,
request_handler: CacheRequestHandler<1>,
/// Slot-indexed opaque anchors.
anchors: wgpu::Buffer,
/// Slot-indexed stable structure ids.
structure_ids: wgpu::Buffer,
metadata_bind_group: wgpu::BindGroup,
/// Host mirrors used to preserve identity across slot moves.
slot_anchors: Vec<StructureAnchor>,
slot_structure_ids: Vec<StructureId>,
next_structure_id: u32,
/// Producer that owns the root structures stored by this table
producer_id: u32,
@@ -64,6 +150,11 @@ pub struct FixedStructureTable
impl FixedStructureTable
{
/// Creates a static table with one distinct anchor per slot.
///
/// Retained for callers that do not move slots; [`Self::new_with_anchors`]
/// is the general constructor.
#[allow(dead_code)]
pub fn new(
device: &wgpu::Device,
size: usize,
@@ -71,6 +162,55 @@ impl FixedStructureTable
producer_id: u32,
) -> Self
{
let anchors = (0..size)
.map(|slot| StructureAnchor {
words: [slot as u32, 0, 0, 0],
})
.collect();
Self::new_with_anchors(device, size, max_requests, producer_id, anchors)
}
/// Creates a table whose slots start with the given anchors.
///
/// Initial structure ids are `0..size`; later anchors receive ids from a
/// monotonic counter that never reuses a value.
pub fn new_with_anchors(
device: &wgpu::Device,
size: usize,
max_requests: usize,
producer_id: u32,
anchors: Vec<StructureAnchor>,
) -> Self
{
assert_eq!(anchors.len(), size);
assert!(
size < NO_STRUCTURE_ID as usize,
"structure id space exhausted"
);
let structure_ids: Vec<u32> = (0..size as u32).collect();
let slot_structure_ids: Vec<StructureId> =
structure_ids.iter().copied().map(StructureId).collect();
let anchors_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("FixedStructureTable::anchors"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
contents: bytemuck::cast_slice(&anchors),
});
let structure_ids_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("FixedStructureTable::structure_ids"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
contents: bytemuck::cast_slice(&structure_ids),
});
let (metadata_bind_group_layout, metadata_bind_group) =
create_multi_buffers_bg_bg_layout(
device,
&[&anchors_buffer, &structure_ids_buffer],
Some("FixedStructureTable::metadata"),
);
let pointer = CachePointer::new(Some(None));
let pointers = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("FixedStructureTable::pointers"),
@@ -101,6 +241,7 @@ impl FixedStructureTable
let write_requests_bindings = [
Some(&CacheRequestHandler::<1>::create_bind_group_layout(device)),
Some(&CacheRequestBuffer::create_bind_group_layout(device)),
Some(&metadata_bind_group_layout),
];
let write_requests_pipeline_layout =
@@ -162,6 +303,7 @@ impl FixedStructureTable
Some(&CacheInsertionData::<1>::create_bind_group_layout(
device, None,
)),
Some(&metadata_bind_group_layout),
];
let insertion_pipeline_layout =
@@ -202,6 +344,12 @@ impl FixedStructureTable
pointers_bind_group,
common_ressources,
request_handler,
anchors: anchors_buffer,
structure_ids: structure_ids_buffer,
metadata_bind_group,
slot_anchors: anchors,
slot_structure_ids,
next_structure_id: size as u32,
producer_id,
indirect_buffer: IndirectBuffer1D::new(device),
write_requests_pass,
@@ -214,6 +362,88 @@ impl FixedStructureTable
}
}
/// Changes the anchor of every slot while preserving structure ids for
/// anchors that remain present.
///
/// Returns the changed assignments and the ids that are no longer used.
/// Retired ids are suitable for cancelling speculative queue work; they are
/// never reassigned to a different anchor.
pub fn reassign_slots(
&mut self,
queue: &wgpu::Queue,
new_anchors: &[StructureAnchor],
) -> (Vec<SlotAssignment>, Vec<StructureId>)
{
assert_eq!(new_anchors.len(), self.size);
let (new_ids, retired) = plan_slot_reassignment(
&self.slot_anchors,
&self.slot_structure_ids,
new_anchors,
&mut self.next_structure_id,
);
let mut assignments = Vec::new();
for slot in 0..self.size
{
let previous_anchor = self.slot_anchors[slot];
let previous_structure = self.slot_structure_ids[slot];
let anchor = new_anchors[slot];
let structure = new_ids[slot];
if previous_anchor == anchor && previous_structure == structure
{
continue;
}
self.slot_anchors[slot] = anchor;
self.slot_structure_ids[slot] = structure;
queue.write_buffer(
&self.anchors,
(slot * size_of::<StructureAnchor>()) as u64,
bytemuck::bytes_of(&anchor),
);
queue.write_buffer(
&self.structure_ids,
(slot * size_of::<u32>()) as u64,
bytemuck::bytes_of(&structure.0),
);
assignments.push(SlotAssignment {
slot: slot as u32,
previous_anchor,
previous_structure,
anchor,
structure,
});
}
(assignments, retired)
}
/// Returns the current slot for an anchor, if it is in the table.
#[allow(dead_code)]
pub fn slot_for_anchor(&self, anchor: &StructureAnchor) -> Option<u32>
{
self.slot_anchors
.iter()
.position(|candidate| candidate == anchor)
.map(|slot| slot as u32)
}
#[allow(dead_code)]
pub fn slot_anchor(&self, slot: u32) -> Option<StructureAnchor>
{
self.slot_anchors.get(slot as usize).copied()
}
#[allow(dead_code)]
pub fn slot_structure_id(&self, slot: u32) -> Option<StructureId>
{
self.slot_structure_ids.get(slot as usize).copied()
}
pub fn gather_requests(
&self,
device: &wgpu::Device,
@@ -255,6 +485,7 @@ impl FixedStructureTable
write_requests_pass.set_pipeline(&self.write_requests_pass);
write_requests_pass.set_bind_group(0, self.request_handler.bind_group(), &[]);
write_requests_pass.set_bind_group(1, request_buffer.bind_group(), &[]);
write_requests_pass.set_bind_group(2, &self.metadata_bind_group, &[]);
write_requests_pass.set_immediates(0, bytemuck::bytes_of(&self.producer_id));
write_requests_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0);
}
@@ -290,6 +521,7 @@ impl FixedStructureTable
insertion_pass.set_bind_group(0, &self.pointers_bind_group, &[]);
insertion_pass.set_bind_group(1, insertion.bind_group_no_attributes(), &[]);
insertion_pass.set_bind_group(2, &self.metadata_bind_group, &[]);
insertion_pass.set_pipeline(&self.insertion_pass);
insertion_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0);
@@ -317,6 +549,73 @@ impl FixedStructureTable
}
}
#[cfg(test)]
mod tests
{
use super::*;
fn anchor(x: i32) -> StructureAnchor
{
StructureAnchor::from_world(x, 0, 0, 0)
}
#[test]
fn permuted_anchors_keep_their_ids()
{
let old_anchors = [anchor(0), anchor(1), anchor(2)];
let old_ids = [StructureId(10), StructureId(11), StructureId(12)];
let new_anchors = [anchor(2), anchor(0), anchor(1)];
let mut next = 20;
let (ids, retired) =
plan_slot_reassignment(&old_anchors, &old_ids, &new_anchors, &mut next);
assert_eq!(ids, vec![StructureId(12), StructureId(10), StructureId(11)]);
assert!(retired.is_empty());
assert_eq!(next, 20);
}
#[test]
fn entering_anchor_gets_a_fresh_id_and_leaving_anchor_retires()
{
let old_anchors = [anchor(0), anchor(1)];
let old_ids = [StructureId(10), StructureId(11)];
let new_anchors = [anchor(1), anchor(2)];
let mut next = 12;
let (ids, retired) =
plan_slot_reassignment(&old_anchors, &old_ids, &new_anchors, &mut next);
assert_eq!(ids, vec![StructureId(11), StructureId(12)]);
assert_eq!(retired, vec![StructureId(10)]);
assert_eq!(next, 13);
}
#[test]
fn ids_are_never_reused_across_round_trips()
{
let mut next = 1;
let mut anchors = [anchor(0)];
let mut ids = [StructureId(0)];
let (new_ids, _) = plan_slot_reassignment(&anchors, &ids, &[anchor(5)], &mut next);
anchors = [anchor(5)];
ids = [new_ids[0]];
let (new_ids, _) = plan_slot_reassignment(&anchors, &ids, &[anchor(0)], &mut next);
assert_eq!(new_ids[0], StructureId(2));
assert_eq!(next, 3);
}
#[test]
#[should_panic(expected = "structure id space exhausted")]
fn allocator_exhaustion_is_fatal()
{
let mut next = NO_STRUCTURE_ID;
let _ = plan_slot_reassignment(&[], &[], &[anchor(0)], &mut next);
}
}
impl<const N: usize> CacheInvalidable<N> for FixedStructureTable
where
[(); N * N * N]:,
@@ -341,6 +640,7 @@ where
validate_pass.set_bind_group(0, &self.pointers_bind_group, &[]);
validate_pass.set_bind_group(1, insertion.bind_group_no_attributes(), &[]);
validate_pass.set_bind_group(2, &self.metadata_bind_group, &[]);
validate_pass.set_pipeline(&self.validation_pass);
validate_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0);