From 7e4fdf3f4e3895b1293b8083435a1d8556a1ffb6 Mon Sep 17 00:00:00 2001 From: Albin Chaboissier Date: Wed, 11 Nov 2026 23:06:15 +0100 Subject: [PATCH] BVH+DynamicStructureTable+StructureId removal+Tree --- AGENTS.md | 24 +- Cargo.toml | 2 +- docs/architecture.md | 14 +- docs/pipeline-and-producers.md | 83 +- docs/shaders.md | 9 +- docs/voxel-cache.md | 101 +- shaders/voxel.slang | 5 +- src/bvh.rs | 406 ++++++ src/bvh/aabb.rs | 468 +++++++ src/bvh/build.rs | 354 +++++ src/bvh/debug.rs | 257 ++++ src/bvh/debug.wgsl | 202 +++ src/bvh/gpu.rs | 79 ++ src/main.rs | 249 +++- src/production.rs | 17 +- src/production/host_production.rs | 1 - src/production/request_queue.rs | 179 +-- src/production/tree_locator.rs | 23 +- src/sparse_tree.rs | 257 ++-- src/terrain.rs | 18 +- src/tree.rs | 837 ------------ src/voxel_cache/schema.rs | 41 +- src/voxel_cache/shaders/common.wgsl | 9 +- .../shaders/fixed_table/insertion.wgsl | 4 +- .../fixed_table/validate_insertion.wgsl | 10 +- .../shaders/fixed_table/write_requests.wgsl | 6 +- src/voxel_cache/shaders/insertion.wgsl | 3 +- src/voxel_cache/shaders/write_pointers.wgsl | 3 +- src/voxel_cache/shaders/write_requests.wgsl | 3 +- src/voxel_cache/tables.rs | 1162 ++++++++++++----- 30 files changed, 3183 insertions(+), 1643 deletions(-) create mode 100644 src/bvh.rs create mode 100644 src/bvh/aabb.rs create mode 100644 src/bvh/build.rs create mode 100644 src/bvh/debug.rs create mode 100644 src/bvh/debug.wgsl create mode 100644 src/bvh/gpu.rs delete mode 100644 src/tree.rs diff --git a/AGENTS.md b/AGENTS.md index 2e85abc..c015699 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,8 +17,9 @@ The durable system is: - `src/voxel_cache/shaders/*.wgsl` — runtime-specialised cache shaders. - `src/gpu/*` — radix sort, top-K, indirect dispatch, compaction. - `shaders/*.slang` — render-side ray marching, compiled ahead of time. -- `src/voxel_cache/tables.rs` + `src/terrain.rs` — structure tables and the - toroidal world wrapper. +- `src/voxel_cache/tables.rs` + `src/terrain.rs` — structure tables + (`FixedStructureTable`, the freelist-backed `DynamicStructureTable`, and the + shared `StructureTableCore`) and the toroidal world wrapper. > **Temporary code:** `src/main.rs` and `src/producers.rs` are a playground/test > harness built alongside the cache. They contain hardcoded parameters and @@ -84,14 +85,16 @@ 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. +11. **Identity is not placement.** `StructureAnchor` is the opaque, table-defined + content identity and the *only* structure identity (toroidal table: world + position + version). A table must never expose two live slots with the same + anchor, and an anchor must keep naming the same content if it leaves and + later re-enters; bump the version word when content generation changes for + the same coordinates. `TableSlot` is table-private placement and may change + freely. Root identity is `(ProducerId, StructureAnchor)`; the slot travels + only as attachment metadata (`RequestMeta`, `InsertionParent`). Request keys, + `LocationPage`, `RequestInformation`, `RequestMeta`, and `InsertionParent` + must not treat the slot as identity. ## Where to look for common tasks @@ -103,6 +106,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` | +| Add/change slot allocation or table growth | `src/voxel_cache/tables.rs` (`DynamicStructureTable`, `SlotAllocator`, `StructureTableCore`) | | 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) | diff --git a/Cargo.toml b/Cargo.toml index 404128a..b658c97 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ egui_ltreeview = "0.9.0" egui_plot = "0.37.0" env_logger = "0.11.11" fastapprox = "0.3.1" -glam = "0.33.5" +glam = { version = "0.33.5", features = ["bytemuck"] } image = "0.25.10" indicatif = "0.18.6" itertools = "0.15.0" diff --git a/docs/architecture.md b/docs/architecture.md index 0b7b3bf..b2673a8 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -113,8 +113,8 @@ flowchart LR Req --> Gather[gather_requests
top-K + radix sort] TReq --> TGather[table gather_requests] - Gather --> RBuffer[(Request buffer
structure_id, anchor, node_id, child)] - TGather --> TRBuffer[(Table request buffer
structure_id, anchor, slot)] + Gather --> RBuffer[(Request buffer
anchor, node_id, child)] + TGather --> TRBuffer[(Table request buffer
anchor, slot)] RBuffer --> Host[Host fulfils requests] TRBuffer --> Host @@ -198,7 +198,7 @@ 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, `StructureAnchor` re-export, `VoxelProducer` trait | Compiled; durable contract | +| `src/production.rs` | Producer ID, `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 | @@ -238,10 +238,10 @@ The toroidal table is a dense 3D grid of chunk root pointers. It wraps with `imod`, so moving the camera across a chunk boundary invalidates the departing slab and reuses those slots for incoming chunks. Identity is kept separate from placement: each slot carries a table-defined `StructureAnchor` (world position -plus a version word) and 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 +plus a version word), and the anchor is the structure identity. Anchors that stay +in view keep their identity while their slot may change; anchors that leave are +retired. In-flight root work carries the anchor and the latest slot, and the GPU +rejects an insertion whose anchor no longer matches the slot, so queue invalidation is only a cancellation optimisation. --- diff --git a/docs/pipeline-and-producers.md b/docs/pipeline-and-producers.md index bffbf23..c4bde83 100644 --- a/docs/pipeline-and-producers.md +++ b/docs/pipeline-and-producers.md @@ -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, anchor, node_id, child, producer, demand) - T-->>H: table request buffer (structure_id, anchor, slot, 0, producer, demand) + C-->>H: request buffer (anchor, node_id, child, producer, demand) + T-->>H: table request buffer (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,19 +51,18 @@ response to frame N are first visible in frame N+1. ```rust struct RequestInformation { - 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 { page_index: u32, // parent page (internal) or 0xFFFFFFFF (external) children_index: u32, depth: u32, // parent depth + table_slot: u32, // external root placement, NO_TABLE_SLOT internally } ``` @@ -71,22 +70,19 @@ 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`, `structure_id` is the stable - tree id, `anchor` is the table-defined content identity, and `table_slot` is - the current placement. + 0xFFFFFFFF`, `node_id = 0`, `children_index = 0`, `anchor` is the table-defined + content identity, and `RequestMeta.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. +- `anchor` and `table_slot` are two different things: + - `StructureAnchor` is the table-defined content identity and the structure + identity (for the toroidal table, world position plus a version word); + - `table_slot` is table-private placement and may change while the anchor + stays the same. It is deliberately not part of a request key. ### 2.2 Response @@ -99,7 +95,6 @@ struct InsertionInformation { } struct LocationPage { - structure_id: u32, node_id: u32, // locator of the node itself producer_id: u32, anchor: StructureAnchor, @@ -110,7 +105,6 @@ struct InsertionParent { page_index: u32, // parent page, or 0xFFFFFFFF for an external root children_index: u32, depth: u32, // parent depth, or 0xFFFFFFFF - structure_id: u32, node_id: u32, // parent locator (0 for an external root) producer_id: u32, anchor: StructureAnchor, @@ -123,11 +117,10 @@ 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 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`. +- internal: the parent page must still have the same 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 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 @@ -199,7 +192,7 @@ The demo's `fullfill_request` (`src/main.rs`) does: 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, anchor, table_slot)`. + `InsertionParent::external(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; @@ -207,8 +200,7 @@ 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, - anchor)`. + - emit `InsertionParent::internal(meta, 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`. @@ -340,7 +332,6 @@ Defines a more ambitious interface: ```rust pub struct ProducerId(pub u32); -pub struct StructureId(pub u32); pub struct StructureLocator(pub u32); pub use crate::voxel_cache::schema::StructureAnchor; @@ -354,7 +345,6 @@ pub trait VoxelProducer { fn produce( &self, producer_id: ProducerId, - id: StructureId, anchor: StructureAnchor, locator: StructureLocator, ) -> (InsertionInformation, [Self::Output; N * N * N]); @@ -369,22 +359,21 @@ Differences from the demo interface: - 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. + it 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. | +| `StructureAnchor` | Opaque, table-defined content identity and the only structure 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. +Root identity is `(producer, anchor)`; child identity adds the parent locator and +child index. The table slot travels only as attachment metadata. The toroidal +table keeps an anchor's identity while it stays in view and retires anchors that +leave. An anchor must keep naming the same content if it later re-enters; bump +its version word when content generation changes for the same coordinates. ### 6.2 `src/production/host_production.rs` @@ -408,7 +397,6 @@ Key model: ```rust RequestKey { producer_id, - structure_id, anchor, // table-defined content identity target: Root | Child { parent: StructureLocator, children_index }, } @@ -430,15 +418,16 @@ 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. -- `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. +- `table_slot` lives in `RequestMeta` as attachment metadata, not part of the + key. Because the whole `RequestMeta` is refreshed on every re-emission, + including while a job is in flight or ready, a produced root can follow its + anchor to a new slot. +- `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/slot. - `ReadyItem::insertion_parent()` builds the `InsertionParent` for the insertion - batch from the key, the latest `RequestMeta`, and the latest `table_slot`. + batch from the key and the latest `RequestMeta` (which carries `table_slot`). The queue is unit-tested without a GPU (`cargo test production::request_queue`). @@ -494,10 +483,8 @@ 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, anchor, - table_slot)`; - - internal: `InsertionParent::internal(meta, structure_id, node_id, - producer_id, anchor)`. + - external: `InsertionParent::external(producer_id, anchor, table_slot)`; + - internal: `InsertionParent::internal(meta, 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 @@ -512,7 +499,7 @@ A production-ready producer should additionally: - handle `destination_indices == 0xFFFFFFFF` by retrying the request; - implement filtering/mip generation for coarser levels so LOD stops do not alias; -- support multiple structures/producers per cache via IDs. +- support multiple structures/producers per cache via `ProducerId` and anchors. --- diff --git a/docs/shaders.md b/docs/shaders.md index 1712b59..60ed995 100644 --- a/docs/shaders.md +++ b/docs/shaders.md @@ -407,8 +407,7 @@ 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`. +- group 2 — slot metadata: binding 0 `fixed_table_anchors`. ### 9.2 WGSL modules and entry points @@ -421,9 +420,9 @@ group: | `shaders/invalidation.wgsl` | `invalidation` | Clear cache pointers that reference pages recycled this insert. | | `shaders/write_pointers.wgsl` | `write_pointers` | Link internal insertion results into parent pages using the batch's `InsertionParent`. | | `shaders/eviction.wgsl` | `reset_lru_list`, `indirect_copy` | Build the eviction candidate list: descending depth sort, then gather timestamps for the stable timestamp sort. | -| `fixed_table/write_requests.wgsl` | `write_requests` | Emit root requests for table slots, resolving the slot's current 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/write_requests.wgsl` | `write_requests` | Emit root requests for table slots, resolving the slot's current anchor. | +| `fixed_table/validate_insertion.wgsl` | `validate_external` | Keep only root entries whose named slot still carries the same anchor and waits for a page. | +| `fixed_table/insertion.wgsl` | `insertion` | Re-check anchor/slot, then point the table slot at the inserted root page. | | `fixed_table/invalidation.wgsl` | `invalidation` | Clear table slots pointing at recycled pages. | | `terrain/shaders/toroidal_structure.wgsl` | `invalidate_new` | Reset table slots whose world position changed. | diff --git a/docs/voxel-cache.md b/docs/voxel-cache.md index 5a8b7de..10957a8 100644 --- a/docs/voxel-cache.md +++ b/docs/voxel-cache.md @@ -68,7 +68,6 @@ For `N = 4`, a pointer page is `8 + 64*4 = 264` bytes. ```rust struct LocationPage { - 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 @@ -77,10 +76,10 @@ struct LocationPage { 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`, `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. +`node_id` is an `NTreeNodeLocator` and `anchor` is the toroidal table's 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. ### 2.3 Depth page @@ -271,12 +270,12 @@ pub trait CacheInvalidable { ``` `validate_insertion` runs before page allocation: the table checks that each -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. +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 @@ -310,7 +309,6 @@ struct InsertionParent { 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 - 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 @@ -319,9 +317,9 @@ struct InsertionParent { ``` For an internal insertion, validation requires the parent page's -`LocationPage` to match `structure_id`, `node_id`, `producer_id`, and `anchor`. +`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 `structure_id` and `anchor`. `write_pointers.wgsl` +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. @@ -386,26 +384,27 @@ flowchart LR ```rust struct RequestInformation { - 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 { 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. +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 @@ -431,7 +430,7 @@ The callback is asynchronous by API, but the demo blocks on it with a For an **internal** request: -- `structure_id`, `node_id`, and `anchor` identify the **parent** node. +- `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)`) with the same anchor. @@ -440,13 +439,12 @@ For an **internal** request: For an **external** (structure-table) request: -- `structure_id` is the stable tree id and `anchor` is the table-defined content - identity; `table_slot` is where the table currently points. +- `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` with `structure_id`, `producer_id`, `anchor`, and - `table_slot`. + external `InsertionParent` with `producer_id`, `anchor`, and `table_slot`. There is no output-order requirement. Each insertion is attached to its parent by its own `InsertionParent`. @@ -488,11 +486,10 @@ 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`, anchor, and - depth, and the requested child pointer must still be `subdividable, - unavailable`. + still have the same `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 + must still carry the same `anchor`, and must still be `subdividable, unavailable`. Valid entries are compacted into `valid_indices` and counted in `valid_count`. @@ -613,8 +610,8 @@ root page? Structure tables answer that and emit requests when it is missing. - `raytrace_bind_group`: bindings `[pointers, request_counts]` (group 1 in the render pipeline). - `gather_requests`: top-K + sort + `fixed_table/write_requests.wgsl`; emits - `structure_id = slot`, `node_id = 0`, `children_index = 0`, - `producer_id = table producer`, `demand = slot counter`, and + `node_id = 0`, `children_index = 0`, `producer_id = table producer`, + `demand = slot counter`, `anchor = slot anchor`, and `RequestMeta.page_index = 0xFFFFFFFF`. - `validate_insertion`: `fixed_table/validate_insertion.wgsl` keeps only slots that are still `subdividable, unavailable` and compacts their indices. @@ -638,12 +635,11 @@ The table is dense: allocation is `slot_count * 4` bytes for pointers plus 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. +- 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_slots` returns the retired anchors + so the host can cancel speculative queue work; correctness does not depend on + it because the GPU validates `anchor`/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. @@ -652,6 +648,43 @@ The Slang module `toroidal_structure_table.slang` mirrors this indexing and walk the block of chunks (`ToroidalStructureTableTracer`). `fixed_structure_table.slang` is imported by `voxel.slang` but unused. +### 8.3 `DynamicStructureTable` + +`src/voxel_cache/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` + pops a slot and installs the anchor; `release(queue, slot) -> Option` + clears the pointer and pushes the slot back. Allocating an already-live anchor + is idempotent and returns its existing slot. `allocate` returns `None` when 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 to + `subdividable, 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.wgsl` and `insertion.wgsl` are 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 and + `grow` doubles 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_grow` is a convenience wrapper. +- **Release semantics.** `release` unlinks 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 diff --git a/shaders/voxel.slang b/shaders/voxel.slang index aa4331b..a27b73f 100644 --- a/shaders/voxel.slang +++ b/shaders/voxel.slang @@ -32,12 +32,9 @@ public struct VertexOutput public float3 world_position; [vk::location(1)] - public nointerpolation uint32_t structure_id; - - [vk::location(2)] public float3 cam_position; - [vk::location(3)] + [vk::location(2)] public float3 chunk_position; } diff --git a/src/bvh.rs b/src/bvh.rs new file mode 100644 index 0000000..0a171d3 --- /dev/null +++ b/src/bvh.rs @@ -0,0 +1,406 @@ +//! This is an implementation of a BVH2 as a top level ray acceleration +//! structure for objects in a scene. +//! The build is done only on CPU and uploaded on GPU. + +use std::collections::HashMap; +use std::mem::size_of; + +use glam::Mat4; + +use crate::bvh::aabb::Aabb; +use crate::bvh::build::BvhPrimitive; +use crate::bvh::build::build_bvh; +use crate::bvh::gpu::GpuBvhNode; +use crate::bvh::gpu::GpuObject; +use crate::production::ProducerId; +use crate::production::StructureAnchor; +use crate::voxel_cache::tables::DynamicStructureTable; + +pub mod aabb; +pub mod build; +pub mod debug; +pub mod gpu; + +/// To handle an object stored in the bvh +#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)] +pub struct BvhHandle +{ + pub anchor: StructureAnchor, + pub producer_id: ProducerId, + + /// Key discriminator, there might be multiple objects with the same anchor and producer_id + /// within the bvh + pub key: u64, +} + +/// An object that is stored by the BVH structure +pub struct BvhObject +{ + /// Identity of the voxel data + pub anchor: StructureAnchor, + pub producer_id: ProducerId, + + /// The transform of the object in the BvhSpace + pub transform: Mat4, + + /// A object is a voxel chunk, which in local space is in the [0,1]^3 cube + /// This bounding_box wraps more tightly arround the actual data stored. + pub bounding_box: Aabb, +} + +impl BvhObject +{ + pub fn world_bounding_box(&self) -> Aabb + { + self.bounding_box.as_transformed_by(&self.transform) + } + + pub fn structure_anchor(&self) -> StructureAnchor + { + self.anchor + } +} + +/// A BVH-backed structure table. +/// +/// GPU state is uploaded lazily: host-side mutations mark the table dirty and +/// [`Self::rebuild_if_dirty`] must be called between frames before using the +/// raytrace bind group. Buffers and the bind group may be recreated when the +/// BVH or the inner table grows, so re-fetch them after each rebuild. +/// +/// Raytrace bindings: +/// 0 = `GpuBvhNode[]` (read-only), 1 = `GpuObject[]` (read-only), +/// 2 = inner structure-table pointers, 3 = inner structure-table requests. +pub struct BvhStructureTable +{ + /// Handle to object in the bvh + objects: HashMap, + + /// Objects alive in the bvh have a slot in the dynamic table + slots: HashMap, + structure_table: DynamicStructureTable, + + /// discriminator key allocator + current_key: u64, + + /// GPU BVH nodes, indexed by [`GpuBvhNode`] order. + bvh_nodes: wgpu::Buffer, + + /// GPU BVH objects, indexed by leaf `first_or_left`. + bvh_objects: wgpu::Buffer, + + node_capacity: usize, + object_capacity: usize, + + node_count: u32, + object_count: u32, + + raytrace_bind_group_layout: wgpu::BindGroupLayout, + raytrace_bind_group: wgpu::BindGroup, + + /// True when the CPU BVH no longer matches the GPU buffers. + dirty: bool, +} + +#[allow(dead_code)] +impl BvhStructureTable +{ + pub fn new(device: &wgpu::Device, initial_capacity: usize, max_requests: usize) -> Self + { + let structure_table = DynamicStructureTable::new(device, initial_capacity, max_requests, 0); + + let raytrace_bind_group_layout = create_bvh_raytrace_bind_group_layout(device); + let bvh_nodes = create_bvh_buffer::(device, 1, "bvh_nodes"); + let bvh_objects = create_bvh_buffer::(device, 1, "bvh_objects"); + let raytrace_bind_group = create_bvh_raytrace_bind_group( + device, + &raytrace_bind_group_layout, + &bvh_nodes, + &bvh_objects, + structure_table.pointers_buffer(), + structure_table.request_pages_buffer(), + ); + + Self { + objects: Default::default(), + slots: Default::default(), + structure_table, + current_key: 0, + bvh_nodes, + bvh_objects, + node_capacity: 1, + object_capacity: 1, + node_count: 0, + object_count: 0, + raytrace_bind_group_layout, + raytrace_bind_group, + dirty: false, + } + } + + pub fn add( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + object: BvhObject, + ) -> BvhHandle + { + let key = self.current_key; + self.current_key += 1; + let handle = BvhHandle { + anchor: object.anchor, + producer_id: object.producer_id, + key, + }; + let slot = self + .structure_table + .allocate_or_grow(device, queue, object.anchor) + .unwrap(); + self.slots.insert(handle, slot); + self.objects.insert(handle, object); + self.dirty = true; + handle + } + + pub fn build(&self) -> (Vec, Vec) + { + // Collect primitives + let mut primitives = self + .objects + .iter() + .map(|(handle, object)| BvhPrimitive { + aabb: object.world_bounding_box(), + handle: *handle, + }) + .collect::>(); + let bvh = build_bvh(&mut primitives, 2); + + // Build gpu bvh + let gpu_nodes = bvh + .nodes + .iter() + .map(|node| (*node).into()) + .collect::>(); + + let gpu_primitives = primitives + .iter() + .map(|primitive| { + GpuObject::new( + *self.slots.get(&primitive.handle).expect("Unallocated slot"), + self.objects + .get(&primitive.handle) + .expect("Object removed") + .transform, + ) + }) + .collect::>(); + (gpu_nodes, gpu_primitives) + } + + /// Marks the CPU BVH as changed. The GPU buffers are rebuilt on the next + /// [`Self::rebuild_if_dirty`] call. + pub fn mark_dirty(&mut self) + { + self.dirty = true; + } + + /// Returns true if the GPU buffers no longer match the CPU BVH. + pub fn is_dirty(&self) -> bool + { + self.dirty + } + + /// Rebuilds the CPU BVH and uploads it to the GPU. + pub fn rebuild(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) + { + let (nodes, objects) = self.build(); + self.upload(device, queue, &nodes, &objects); + } + + /// Rebuilds only if the BVH changed since the last upload. + pub fn rebuild_if_dirty(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) + { + if self.dirty + { + self.rebuild(device, queue); + } + } + + fn upload( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + nodes: &[GpuBvhNode], + objects: &[GpuObject], + ) + { + let node_capacity = grown_capacity(self.node_capacity, nodes.len()); + if node_capacity > self.node_capacity + { + self.node_capacity = node_capacity; + self.bvh_nodes = create_bvh_buffer::(device, node_capacity, "bvh_nodes"); + } + + let object_capacity = grown_capacity(self.object_capacity, objects.len()); + if object_capacity > self.object_capacity + { + self.object_capacity = object_capacity; + self.bvh_objects = + create_bvh_buffer::(device, object_capacity, "bvh_objects"); + } + + if !nodes.is_empty() + { + queue.write_buffer(&self.bvh_nodes, 0, bytemuck::cast_slice(nodes)); + } + if !objects.is_empty() + { + queue.write_buffer(&self.bvh_objects, 0, bytemuck::cast_slice(objects)); + } + + self.node_count = nodes.len() as u32; + self.object_count = objects.len() as u32; + + // The inner table may have grown (replacing its buffers) since the last + // bind group was created, so always recreate it after an upload. + let raytrace_bind_group = create_bvh_raytrace_bind_group( + device, + &self.raytrace_bind_group_layout, + &self.bvh_nodes, + &self.bvh_objects, + self.structure_table.pointers_buffer(), + self.structure_table.request_pages_buffer(), + ); + self.raytrace_bind_group = raytrace_bind_group; + + self.dirty = false; + } + + pub fn bvh_nodes(&self) -> &wgpu::Buffer + { + &self.bvh_nodes + } + + pub fn bvh_objects(&self) -> &wgpu::Buffer + { + &self.bvh_objects + } + + pub fn node_count(&self) -> u32 + { + self.node_count + } + + pub fn object_count(&self) -> u32 + { + self.object_count + } + + pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout + { + &self.raytrace_bind_group_layout + } + + pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup + { + &self.raytrace_bind_group + } +} + +fn create_bvh_buffer(device: &wgpu::Device, capacity: usize, label: &str) -> wgpu::Buffer +{ + let capacity = capacity.max(1); + device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: (capacity * size_of::()) as u64, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }) +} + +fn grown_capacity(current: usize, required: usize) -> usize +{ + if required <= current + { + return current; + } + + let mut capacity = current.max(1); + while capacity < required + { + capacity = capacity.saturating_mul(2); + } + capacity +} + +fn create_bvh_raytrace_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout +{ + let storage = |read_only: bool| wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only }, + has_dynamic_offset: false, + min_binding_size: None, + }; + + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("BvhStructureTable::raytrace_bind_group_layout"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::COMPUTE, + ty: storage(true), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::COMPUTE, + ty: storage(true), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::COMPUTE, + ty: storage(false), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 3, + visibility: wgpu::ShaderStages::COMPUTE, + ty: storage(false), + count: None, + }, + ], + }) +} + +fn create_bvh_raytrace_bind_group( + device: &wgpu::Device, + layout: &wgpu::BindGroupLayout, + nodes: &wgpu::Buffer, + objects: &wgpu::Buffer, + structure_pointers: &wgpu::Buffer, + structure_requests: &wgpu::Buffer, +) -> wgpu::BindGroup +{ + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("BvhStructureTable::raytrace_bind_group"), + layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: nodes.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: objects.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: structure_pointers.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: structure_requests.as_entire_binding(), + }, + ], + }) +} diff --git a/src/bvh/aabb.rs b/src/bvh/aabb.rs new file mode 100644 index 0000000..35bd2bb --- /dev/null +++ b/src/bvh/aabb.rs @@ -0,0 +1,468 @@ +//! Axis aligned bounding box used by the BVH build. + +use glam::Mat4; +use glam::Vec3; + +/// An axis aligned bounding box. +/// +/// A box is empty when `min` is greater than `max` on any axis. [`Aabb::EMPTY`] +/// uses inverted infinities, which makes it the identity element for +/// [`Aabb::union`] and [`Aabb::union_point`]. +#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)] +#[repr(C)] +pub struct Aabb +{ + min: Vec3, + max: Vec3, +} + +impl Aabb +{ + /// The empty box: it contains no point and is the identity element for + /// union operations. + pub const EMPTY: Self = Self { + min: Vec3::INFINITY, + max: Vec3::NEG_INFINITY, + }; + + /// The local voxel chunk space is [0,1]^3. + /// This is the box that encompasses that block. + pub const CHUNK: Self = Self { + min: Vec3::ZERO, + max: Vec3::ONE, + }; + + /// Builds a box from its corners. + /// + /// No validation is performed so that [`Aabb::EMPTY`] can be built; use + /// [`Aabb::is_empty`] to check the result. + pub const fn new(min: Vec3, max: Vec3) -> Self + { + Self { min, max } + } + + /// Builds a box from a center and the half extents along each axis. + pub fn from_center_half_extents(center: Vec3, half_extents: Vec3) -> Self + { + Self { + min: center - half_extents, + max: center + half_extents, + } + } + + /// Builds the tightest box containing every point. + /// + /// An empty iterator produces [`Aabb::EMPTY`]. + pub fn from_points(points: impl IntoIterator) -> Self + { + let mut aabb = Self::EMPTY; + for point in points + { + aabb.union_point(point); + } + aabb + } + + pub const fn min(&self) -> Vec3 + { + self.min + } + + pub const fn max(&self) -> Vec3 + { + self.max + } + + /// Center of the box. Not meaningful for an empty box. + pub fn center(&self) -> Vec3 + { + (self.min + self.max) * 0.5 + } + + /// Full extent of the box along each axis (`max - min`). + pub fn size(&self) -> Vec3 + { + self.max - self.min + } + + /// Half extent of the box along each axis. + pub fn half_size(&self) -> Vec3 + { + self.size() * 0.5 + } + + /// Surface area of the box, used by SAH heuristics. + pub fn surface_area(&self) -> f32 + { + let size = self.size(); + 2.0 * (size.x * size.y + size.y * size.z + size.z * size.x) + } + + pub fn volume(&self) -> f32 + { + self.size().element_product() + } + + /// Index of the axis with the largest extent (0 = x, 1 = y, 2 = z). + /// + /// Ties are broken in favor of the lower axis. + pub fn longest_axis(&self) -> usize + { + let size = self.size(); + if size.x >= size.y && size.x >= size.z + { + 0 + } + else if size.y >= size.z + { + 1 + } + else + { + 2 + } + } + + /// Returns `true` when the box contains no point. + pub fn is_empty(&self) -> bool + { + self.min.x > self.max.x || self.min.y > self.max.y || self.min.z > self.max.z + } + + /// Returns `true` when both corners are finite. + pub fn is_finite(&self) -> bool + { + self.min.is_finite() && self.max.is_finite() + } + + pub fn contains_point(&self, point: Vec3) -> bool + { + point.cmpge(self.min).all() && point.cmple(self.max).all() + } + + /// Returns `true` when `other` is fully inside `self`. + /// + /// An empty `other` is contained in every box. + pub fn contains(&self, other: &Self) -> bool + { + other.is_empty() || (self.min.cmple(other.min).all() && self.max.cmpge(other.max).all()) + } + + /// Returns `true` when both boxes share at least one point. + /// + /// Boxes touching exactly on a face, edge or corner do intersect. + pub fn intersects(&self, other: &Self) -> bool + { + !self.is_empty() + && !other.is_empty() + && self.min.cmple(other.max).all() + && other.min.cmple(self.max).all() + } + + /// Overlap of both boxes. + /// + /// The result is empty when the boxes do not intersect. + pub fn intersection(&self, other: &Self) -> Self + { + Self { + min: self.min.max(other.min), + max: self.max.min(other.max), + } + } + + /// Grows the box to contain `point`. + pub fn union_point(&mut self, point: Vec3) + { + self.min = self.min.min(point); + self.max = self.max.max(point); + } + + /// Grows the box to contain `other`. + pub fn union(&mut self, other: &Self) + { + self.min = self.min.min(other.min); + self.max = self.max.max(other.max); + } + + /// Returns a copy of the box grown by `margin` on every side. + pub fn expanded(&self, margin: f32) -> Self + { + let margin = Vec3::splat(margin); + Self { + min: self.min - margin, + max: self.max + margin, + } + } + + /// Returns a copy of the box with every axis at least `min_size` long, + /// keeping the center unchanged. + /// + /// This avoids degenerate (flat) boxes, which are problematic for SAH + /// splitting. An empty box is returned unchanged. + pub fn padded_to_min_size(&self, min_size: f32) -> Self + { + if self.is_empty() + { + return Self::EMPTY; + } + + let half_extents = self.half_size().max(Vec3::splat(min_size * 0.5)); + Self::from_center_half_extents(self.center(), half_extents) + } + + /// Returns an iterator over all of the corner points of the box + pub fn corner_points(&self) -> impl Iterator + { + (0..=7).map(|i| { + let a = &self.min; + let b = &self.max; + + Vec3::new( + if i & 1 == 0 { a.x } else { b.x }, + if i & 2 == 0 { a.y } else { b.y }, + if i & 4 == 0 { a.z } else { b.z }, + ) + }) + } + + /// Returns the Aabb bounding box of the box transformed by `transformed` + pub fn as_transformed_by(&self, transform: &Mat4) -> Self + { + Self::from_points( + self.corner_points() + .map(|point| transform.transform_point3(point)), + ) + } +} + +impl Default for Aabb +{ + fn default() -> Self + { + Self::EMPTY + } +} + +#[cfg(test)] +mod tests +{ + use super::*; + + const EPSILON: f32 = 1e-6; + + fn assert_vec3_eq(a: Vec3, b: Vec3) + { + assert!( + (a - b).abs().max_element() <= EPSILON, + "expected {b:?}, got {a:?}" + ); + } + + #[test] + fn empty_box_contains_nothing() + { + let aabb = Aabb::EMPTY; + assert!(aabb.is_empty()); + assert!(!aabb.contains_point(Vec3::ZERO)); + assert!(!aabb.intersects(&Aabb::new(Vec3::ZERO, Vec3::ONE))); + } + + #[test] + fn empty_is_identity_for_union() + { + let aabb = Aabb::new(Vec3::ZERO, Vec3::ONE); + + let mut grown = Aabb::EMPTY; + grown.union(&aabb); + assert_eq!(grown, aabb); + + let mut grown = aabb; + grown.union(&Aabb::EMPTY); + assert_eq!(grown, aabb); + } + + #[test] + fn from_points_of_empty_iterator_is_empty() + { + assert!(Aabb::from_points(std::iter::empty()).is_empty()); + } + + #[test] + fn from_points_bounds_all_points() + { + let points = [ + Vec3::new(1.0, -2.0, 3.0), + Vec3::new(-4.0, 5.0, -6.0), + Vec3::new(0.0, 0.0, 0.0), + ]; + + let aabb = Aabb::from_points(points); + assert_eq!(aabb.min(), Vec3::new(-4.0, -2.0, -6.0)); + assert_eq!(aabb.max(), Vec3::new(1.0, 5.0, 3.0)); + for point in points + { + assert!(aabb.contains_point(point)); + } + } + + #[test] + fn center_and_size() + { + let aabb = Aabb::new(Vec3::new(-1.0, 0.0, 2.0), Vec3::new(3.0, 4.0, 6.0)); + + assert_vec3_eq(aabb.center(), Vec3::new(1.0, 2.0, 4.0)); + assert_vec3_eq(aabb.size(), Vec3::new(4.0, 4.0, 4.0)); + assert_vec3_eq(aabb.half_size(), Vec3::new(2.0, 2.0, 2.0)); + } + + #[test] + fn from_center_half_extents_round_trips() + { + let aabb = Aabb::from_center_half_extents(Vec3::new(1.0, 2.0, 3.0), Vec3::splat(2.0)); + + assert_eq!(aabb.min(), Vec3::new(-1.0, 0.0, 1.0)); + assert_eq!(aabb.max(), Vec3::new(3.0, 4.0, 5.0)); + } + + #[test] + fn union_grows_to_contain_both_boxes() + { + let a = Aabb::new(Vec3::ZERO, Vec3::ONE); + let b = Aabb::new(Vec3::splat(2.0), Vec3::splat(4.0)); + + let mut union = a; + union.union(&b); + + assert_eq!(union.min(), Vec3::ZERO); + assert_eq!(union.max(), Vec3::splat(4.0)); + assert!(union.contains(&a)); + assert!(union.contains(&b)); + } + + #[test] + fn contains_point_respects_faces() + { + let aabb = Aabb::new(Vec3::ZERO, Vec3::ONE); + + assert!(aabb.contains_point(Vec3::ZERO)); + assert!(aabb.contains_point(Vec3::ONE)); + assert!(aabb.contains_point(Vec3::splat(0.5))); + assert!(!aabb.contains_point(Vec3::splat(-EPSILON))); + assert!(!aabb.contains_point(Vec3::splat(1.0 + EPSILON))); + } + + #[test] + fn contains_box() + { + let outer = Aabb::new(Vec3::ZERO, Vec3::splat(4.0)); + let inner = Aabb::new(Vec3::ONE, Vec3::splat(3.0)); + + assert!(outer.contains(&inner)); + assert!(!inner.contains(&outer)); + assert!(outer.contains(&Aabb::EMPTY)); + } + + #[test] + fn separated_boxes_do_not_intersect() + { + let a = Aabb::new(Vec3::ZERO, Vec3::ONE); + let b = Aabb::new(Vec3::new(2.0, 0.0, 0.0), Vec3::new(3.0, 1.0, 1.0)); + + assert!(!a.intersects(&b)); + assert!(!b.intersects(&a)); + assert!(a.intersection(&b).is_empty()); + } + + #[test] + fn touching_boxes_intersect() + { + let a = Aabb::new(Vec3::ZERO, Vec3::ONE); + let b = Aabb::new(Vec3::new(1.0, 0.0, 0.0), Vec3::new(2.0, 1.0, 1.0)); + + assert!(a.intersects(&b)); + assert_eq!(a.intersection(&b).size(), Vec3::new(0.0, 1.0, 1.0)); + } + + #[test] + fn overlapping_boxes_intersect() + { + let a = Aabb::new(Vec3::ZERO, Vec3::splat(2.0)); + let b = Aabb::new(Vec3::ONE, Vec3::splat(3.0)); + + assert!(a.intersects(&b)); + + let intersection = a.intersection(&b); + assert_eq!(intersection.min(), Vec3::ONE); + assert_eq!(intersection.max(), Vec3::splat(2.0)); + } + + #[test] + fn surface_area_and_volume() + { + let aabb = Aabb::new(Vec3::ZERO, Vec3::new(2.0, 3.0, 4.0)); + + assert!((aabb.volume() - 24.0).abs() <= EPSILON); + assert!((aabb.surface_area() - 52.0).abs() <= EPSILON); + } + + #[test] + fn longest_axis_picks_largest_extent() + { + assert_eq!( + Aabb::new(Vec3::ZERO, Vec3::new(3.0, 1.0, 2.0)).longest_axis(), + 0 + ); + assert_eq!( + Aabb::new(Vec3::ZERO, Vec3::new(1.0, 3.0, 2.0)).longest_axis(), + 1 + ); + assert_eq!( + Aabb::new(Vec3::ZERO, Vec3::new(1.0, 2.0, 3.0)).longest_axis(), + 2 + ); + } + + #[test] + fn expanded_adds_margin_on_every_side() + { + let aabb = Aabb::new(Vec3::ZERO, Vec3::ONE).expanded(0.5); + + assert_eq!(aabb.min(), Vec3::splat(-0.5)); + assert_eq!(aabb.max(), Vec3::splat(1.5)); + assert!(aabb.contains(&Aabb::new(Vec3::ZERO, Vec3::ONE))); + } + + #[test] + fn padded_to_min_size_keeps_flat_box_usable() + { + let flat = Aabb::new(Vec3::new(0.0, 0.0, 5.0), Vec3::new(2.0, 2.0, 5.0)); + let padded = flat.padded_to_min_size(1.0); + + assert!(!padded.is_empty()); + assert!((padded.size().z - 1.0).abs() <= EPSILON); + assert_eq!(padded.size().x, 2.0); + assert_eq!(padded.size().y, 2.0); + assert_vec3_eq(padded.center(), flat.center()); + assert!(padded.contains(&flat)); + } + + #[test] + fn padded_empty_box_stays_empty() + { + assert!(Aabb::EMPTY.padded_to_min_size(1.0).is_empty()); + } + + #[test] + fn default_is_empty() + { + assert_eq!(Aabb::default(), Aabb::EMPTY); + assert!(Aabb::default().is_empty()); + } + + #[test] + fn layout_is_two_vec3s() + { + assert_eq!(std::mem::size_of::(), 24); + assert_eq!(bytemuck::bytes_of(&Aabb::EMPTY).len(), 24); + } +} diff --git a/src/bvh/build.rs b/src/bvh/build.rs new file mode 100644 index 0000000..d7a69b4 --- /dev/null +++ b/src/bvh/build.rs @@ -0,0 +1,354 @@ +//! Implementation of fast binary BVH build with binned SAH +//! + +use std::num::NonZero; + +use egui::emath::OrderedFloat; + +use crate::bvh::gpu::GpuBvhNode; + +use super::aabb::Aabb; + +macro_rules! get_dim { + ($v:expr, $d:expr) => { + match $d + { + 0 => $v.x, + 1 => $v.y, + _ => $v.z, + } + }; +} + +// Sah heuristic parameters + +/// Intersection time +const SAH_INTERSECT: f32 = 1.; + +/// Bin count +const SAH_BIN_COUNT: usize = 16; + +#[derive(Clone, Copy)] +pub struct BvhNode +{ + /// The bounding box of this bvh node + aabb: Aabb, + + /// 0 if this is not a leaf + /// n if it is a leaf containing objects + count: u32, + + /// If this node is not a leaf, the index in the list of nodes of the left node + /// Otherwise the index in the list of primitive of the first object + first_or_left: u32, +} + +impl From for BvhNode +{ + fn from(value: GpuBvhNode) -> Self + { + Self { + aabb: value.aabb.into(), + count: value.count, + first_or_left: value.first_or_left, + } + } +} + +impl From for GpuBvhNode +{ + fn from(value: BvhNode) -> Self + { + GpuBvhNode { + aabb: value.aabb.into(), + count: value.count, + first_or_left: value.first_or_left, + } + } +} + +impl BvhNode +{ + pub fn internal(aabb: Aabb, left: u32) -> BvhNode + { + Self { + aabb, + count: 0, + first_or_left: left, + } + } + + pub fn leaf(aabb: Aabb, count: NonZero, first_index: u32) -> BvhNode + { + Self { + aabb, + count: count.into(), + first_or_left: first_index, + } + } + + pub fn is_internal(&self) -> bool + { + self.count == 0 + } + + pub fn is_leaf(&self) -> bool + { + self.count != 0 + } + + pub fn first(&self) -> Option + { + if !self.is_leaf() + { + None + } + else + { + Some(self.first_or_left) + } + } + + pub fn count(&self) -> Option + { + if !self.is_leaf() + { + None + } + else + { + Some(self.count) + } + } + + pub fn left(&self) -> Option + { + if !self.is_internal() + { + None + } + else + { + Some(self.first_or_left) + } + } + + pub fn right(&self) -> Option + { + self.left().map(|x| x + 1) + } +} + +pub struct BvhPrimitive +{ + pub aabb: Aabb, + pub handle: T, +} + +pub struct Bvh +{ + /// List of the bvh's nodes + pub nodes: Vec, +} + +pub fn build_bvh(primitives: &mut [BvhPrimitive], leaf_max: usize) -> Bvh +{ + let mut nodes = Vec::new(); + //let mut prim_indices = Vec::new(); + + if primitives.is_empty() + { + return Bvh { + nodes, + //prim_indices, + }; + } + + // Build root node + let mut aabb = Aabb::EMPTY; + primitives.iter().for_each(|p| aabb.union(&p.aabb)); + + nodes.push(BvhNode::leaf( + aabb, + NonZero::new(primitives.len() as u32).unwrap(), + 0, + )); + + build_node(0, primitives, &mut nodes, leaf_max); + + Bvh { nodes } +} + +pub fn build_node( + node_index: usize, + primitives: &mut [BvhPrimitive], + nodes: &mut Vec, + leaf_max: usize, +) +{ + // We only extend a leaf if necessary + assert!(nodes[node_index].is_leaf()); + let offset = nodes[node_index].first().expect("Node is leaf"); + let count = nodes[node_index].count().expect("Node is leaf"); + + // Primitives owned by this node + let node_primitives = &mut primitives[(offset as usize)..((offset + count) as usize)]; + + // We must now decide to keep the node as a leaf, or split using the heuristic: + let split = sah_split(node_primitives, leaf_max); + + match split + { + Some((split_dimension, split_plane)) => + { + // Sah says split, do the split + // We sort along the split dimension + node_primitives.sort_unstable_by_key(|primitive| { + OrderedFloat(get_dim!(primitive.aabb.center(), split_dimension)) + }); + + // We now now that the split_plane splits node_primitives into two subslices + let mut left_count = 0u32; + let mut left_aabb = Aabb::EMPTY; + let mut right_aabb = Aabb::EMPTY; + + for primitive in node_primitives.iter() + { + if get_dim!(primitive.aabb.center(), split_dimension) < split_plane + { + left_count += 1; + left_aabb.union(&primitive.aabb); + } + else + { + right_aabb.union(&primitive.aabb); + } + } + + let right_count = node_primitives.len() as u32 - left_count; + + let left_node = BvhNode::leaf( + left_aabb, + NonZero::new(left_count).expect("Empty leaf impossible."), + offset, + ); + let right_node = BvhNode::leaf( + right_aabb, + NonZero::new(right_count).expect("Empty leaf impossible."), + offset + left_count, // As the slice is sorted + ); + + // Allocate spot in the node array + let left_index = nodes.len(); + // Left and right are contiguous + nodes.push(left_node); + nodes.push(right_node); + + // Change this node to be internal + nodes[node_index] = BvhNode::internal(nodes[node_index].aabb, left_index as u32); + + // Build children + build_node(left_index, primitives, nodes, leaf_max); + build_node(left_index + 1, primitives, nodes, leaf_max); + } + None => + { + // Sah says keep as leaf, do nothing + } + } +} + +/// Returns Some if SAH says split, none if it wants a leaf +pub fn sah_split(primitives: &[BvhPrimitive], leaf_max: usize) -> Option<(usize, f32)> +{ + // Don't even bother, spliting it does nothing + if primitives.len() <= 2 + { + return None; + } + + // Cost if this node was a leaf + let leaf_sah = primitives.len() as f32 * SAH_INTERSECT; + + // Compute the bounding box contains the centroids of the primitives + let mut centroid_bounds = Aabb::EMPTY; + primitives + .iter() + .for_each(|prim| centroid_bounds.union_point(prim.aabb.center())); + + // Evaluate sah per dimension + let mut best_dimension = 0; + let mut minimum_cost = f32::INFINITY; + let mut minimum_split_plane = 0.; + for dimension in 0..3usize + { + let cetroid_min = get_dim!(centroid_bounds.min(), dimension); + + // The size of a bin in this dimension + let bin_width = get_dim!(centroid_bounds.size(), dimension) / SAH_BIN_COUNT as f32; + + // Indicies of elements per bin + let mut bins: [Aabb; SAH_BIN_COUNT] = Default::default(); + let mut bin_counts: [usize; SAH_BIN_COUNT] = Default::default(); + + // Bin elements + for primitive in primitives.iter() + { + let centroid = get_dim!(primitive.aabb.center(), dimension); + let bin_index = + (((centroid - cetroid_min) / bin_width) as usize).clamp(0, SAH_BIN_COUNT - 1); + + // Put it into its bin + bins[bin_index].union(&primitive.aabb); + bin_counts[bin_index] += 1; + } + + // Build prefix and suffix bins + let mut prefix: [Aabb; SAH_BIN_COUNT] = bins; + let mut prefix_counts: [usize; SAH_BIN_COUNT] = bin_counts; + let mut suffix: [Aabb; SAH_BIN_COUNT] = bins; + let mut suffix_counts: [usize; SAH_BIN_COUNT] = bin_counts; + + // We build prefix and suffix simultaneously + for i in 1..SAH_BIN_COUNT + { + let prefix_previous = prefix[i - 1]; + prefix[i].union(&prefix_previous); + prefix_counts[i] += prefix_counts[i - 1]; + + let suffix_previous = suffix[SAH_BIN_COUNT - i]; + suffix[SAH_BIN_COUNT - 1 - i].union(&suffix_previous); + suffix_counts[SAH_BIN_COUNT - 1 - i] += suffix_counts[SAH_BIN_COUNT - i]; + } + + // Chose a split + // We iterate only up to SAH_BIN_COUNT - 1 + // as we dont want to put all primitves on the left or right + for i in 0..(SAH_BIN_COUNT - 1) + { + let left_sah = prefix[i].surface_area() * prefix_counts[i] as f32; + let right_sah = suffix[i + 1].surface_area() * suffix_counts[i + 1] as f32; + + let split_sah = left_sah + right_sah; + if split_sah < minimum_cost + { + best_dimension = dimension; + minimum_cost = split_sah; + + // Take bin boundary as split point + minimum_split_plane = cetroid_min + (i + 1) as f32 * bin_width; + } + } + } + + if leaf_sah < minimum_cost && primitives.len() <= leaf_max + { + // SAH requires leaf + None + } + else + { + // SAH requires split + Some((best_dimension, minimum_split_plane)) + } +} diff --git a/src/bvh/debug.rs b/src/bvh/debug.rs new file mode 100644 index 0000000..56348c3 --- /dev/null +++ b/src/bvh/debug.rs @@ -0,0 +1,257 @@ +//! Contains rendering code to display a debug overlay for the BVH. + +use glam::Mat4; + +// debug.wgsl mirrors the GPU structs manually. Keep the array strides in sync: +// WGSL would otherwise round them up to 16-byte alignment. +const _: () = { + assert!(size_of::() == 40); + assert!(size_of::() == 144); +}; + +/// Renders a GPU BVH as debug geometry. +/// +/// Every node's AABB is drawn as a wireframe box. Leaves additionally draw one +/// filled box per object, using the object's `local_to_world` transform on the +/// local `[0, 1]^3` cube. +/// +/// One instance is one `GpuBvhNode`; the shader generates all vertices, so no +/// vertex or index buffer is needed. +pub struct BvhDebugPipeline +{ + solid_pipeline: wgpu::RenderPipeline, + line_pipeline: wgpu::RenderPipeline, + bind_group_layout: wgpu::BindGroupLayout, + view_proj_buffer: wgpu::Buffer, +} + +impl BvhDebugPipeline +{ + /// `color_format` must match the render pass attachment, including its sRGB + /// suffix. `depth_format` must match `depth_view` in [`Self::render`]. + pub fn new( + device: &wgpu::Device, + color_format: wgpu::TextureFormat, + depth_format: wgpu::TextureFormat, + ) -> Self + { + let shader = device.create_shader_module(wgpu::include_wgsl!("debug.wgsl")); + + let bind_group_layout = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("bvh_debug_bind_group_layout"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: true }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: true }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: wgpu::BufferSize::new( + size_of::() as u64 + ), + }, + count: None, + }, + ], + }); + + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("bvh_debug_pipeline_layout"), + bind_group_layouts: &[Some(&bind_group_layout)], + immediate_size: 0, + }); + + let view_proj_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("bvh_debug_view_proj_buffer"), + size: size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + + let create_pipeline = + |label: &str, + vertex_entry: &str, + fragment_entry: &str, + topology: wgpu::PrimitiveTopology, + depth_write_enabled: bool| + -> wgpu::RenderPipeline { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some(vertex_entry), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: wgpu::PrimitiveState { + topology, + strip_index_format: None, + front_face: wgpu::FrontFace::Ccw, + // Boxes stay visible even when the camera is inside one. + cull_mode: None, + unclipped_depth: false, + polygon_mode: wgpu::PolygonMode::Fill, + conservative: false, + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: depth_format, + depth_write_enabled: Some(depth_write_enabled), + depth_compare: Some(wgpu::CompareFunction::LessEqual), + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some(fragment_entry), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: color_format, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) + }; + + let solid_pipeline = create_pipeline( + "bvh_debug_solid_pipeline", + "vs_solids", + "fs_solids", + wgpu::PrimitiveTopology::TriangleList, + true, + ); + let line_pipeline = create_pipeline( + "bvh_debug_line_pipeline", + "vs_lines", + "fs_lines", + wgpu::PrimitiveTopology::LineList, + false, + ); + + Self { + solid_pipeline, + line_pipeline, + bind_group_layout, + view_proj_buffer, + } + } + + /// Records a debug render pass into `encoder`. + /// + /// The pass loads the existing color contents, overlays the BVH, and clears + /// the depth buffer before drawing. Record it after the scene has been + /// written to `color_view` and before the UI is drawn. + /// + /// `max_objects_per_leaf` is the leaf capacity used when building the BVH + /// (the `leaf_max` argument of `build_bvh`), currently `2`. + #[allow(clippy::too_many_arguments)] + pub fn render( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + color_view: &wgpu::TextureView, + depth_view: &wgpu::TextureView, + view_proj: Mat4, + node_buffer: &wgpu::Buffer, + object_buffer: &wgpu::Buffer, + node_count: u32, + max_objects_per_leaf: u32, + ) + { + if node_count == 0 + { + return; + } + + queue.write_buffer( + &self.view_proj_buffer, + 0, + bytemuck::bytes_of(&view_proj), + ); + + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("bvh_debug_bind_group"), + layout: &self.bind_group_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: node_buffer.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: object_buffer.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: self.view_proj_buffer.as_entire_binding(), + }, + ], + }); + + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("bvh_debug_render_pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: color_view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: depth_view, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, + }), + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + + pass.set_bind_group(0, &bind_group, &[]); + + // Filled object boxes first so the wireframes can depth-test against + // them. + if max_objects_per_leaf > 0 + { + pass.set_pipeline(&self.solid_pipeline); + pass.draw( + 0..36 * max_objects_per_leaf, + 0..node_count, + ); + } + + pass.set_pipeline(&self.line_pipeline); + pass.draw(0..24, 0..node_count); + } +} diff --git a/src/bvh/debug.wgsl b/src/bvh/debug.wgsl new file mode 100644 index 0000000..e2416ed --- /dev/null +++ b/src/bvh/debug.wgsl @@ -0,0 +1,202 @@ +//! Debug rendering for the GPU BVH. +//! +//! Every box is generated procedurally from the vertex index, so there is no +//! mesh or vertex buffer. One instance is one `GpuBvhNode`. + +struct GpuBvhNode +{ + // Kept as scalar fields on purpose. WGSL rounds structs containing vec3/vec4 + // up to a 16-byte alignment (48-byte array stride), while the Rust side is + // a 40-byte `#[repr(C)]` struct. + min_x: f32, + min_y: f32, + min_z: f32, + _pad0: f32, + max_x: f32, + max_y: f32, + max_z: f32, + _pad1: u32, + count: u32, + first_or_left: u32, +}; + +struct GpuObject +{ + local_to_world: mat4x4, + world_to_local: mat4x4, + table_slot: u32, + _pad0: u32, + _pad1: u32, + _pad2: u32, +}; + +@group(0) @binding(0) var nodes: array; +@group(0) @binding(1) var objects: array; +@group(0) @binding(2) var view_proj: mat4x4; + +struct VertexOutput +{ + @builtin(position) clip_position: vec4, + @location(0) color: vec3, + @location(1) normal: vec3, +}; + +const INTERNAL_NODE_COLOR = vec3(0.15, 0.70, 1.0); +const LEAF_NODE_COLOR = vec3(1.0, 0.85, 0.20); +const OBJECT_COLOR = vec3(1.0, 0.45, 0.12); + +// Pushed fully outside the clip volume so skipped nodes/objects produce no +// fragments. +const DEGENERATE_POSITION = vec4(2.0, 2.0, 2.0, 1.0); + +const VERTICES_PER_OBJECT: u32 = 36u; + +// Corner numbering: bit 0 = x, bit 1 = y, bit 2 = z. +const EDGE_CORNERS = array( + // -Z face + 0u, 1u, 1u, 3u, 3u, 2u, 2u, 0u, + // +Z face + 4u, 5u, 5u, 7u, 7u, 6u, 6u, 4u, + // vertical edges + 0u, 4u, 1u, 5u, 2u, 6u, 3u, 7u, +); + +const TRIANGLE_CORNERS = array( + // -Z + 0u, 2u, 1u, 1u, 2u, 3u, + // +Z + 4u, 5u, 6u, 5u, 7u, 6u, + // -Y + 0u, 1u, 4u, 1u, 5u, 4u, + // +Y + 2u, 6u, 3u, 3u, 6u, 7u, + // -X + 0u, 4u, 2u, 2u, 4u, 6u, + // +X + 1u, 3u, 5u, 3u, 7u, 5u, +); + +const FACE_NORMALS = array, 6>( + vec3(0.0, 0.0, -1.0), + vec3(0.0, 0.0, 1.0), + vec3(0.0, -1.0, 0.0), + vec3(0.0, 1.0, 0.0), + vec3(-1.0, 0.0, 0.0), + vec3(1.0, 0.0, 0.0), +); + +fn corner_position(min_corner: vec3, max_corner: vec3, corner: u32) -> vec3 +{ + return vec3( + select(min_corner.x, max_corner.x, (corner & 1u) != 0u), + select(min_corner.y, max_corner.y, (corner & 2u) != 0u), + select(min_corner.z, max_corner.z, (corner & 4u) != 0u), + ); +} + +@vertex +fn vs_lines( + @builtin(vertex_index) vertex_index: u32, + @builtin(instance_index) instance_index: u32, +) -> VertexOutput +{ + var out: VertexOutput; + out.clip_position = DEGENERATE_POSITION; + out.color = INTERNAL_NODE_COLOR; + out.normal = vec3(0.0, 0.0, 1.0); + + if instance_index >= arrayLength(&nodes) + { + return out; + } + + let node = nodes[instance_index]; + let min_corner = vec3(node.min_x, node.min_y, node.min_z); + let max_corner = vec3(node.max_x, node.max_y, node.max_z); + let world_position = corner_position( + min_corner, + max_corner, + EDGE_CORNERS[vertex_index], + ); + + out.clip_position = view_proj * vec4(world_position, 1.0); + if node.count != 0u + { + out.color = LEAF_NODE_COLOR; + } + + return out; +} + +@vertex +fn vs_solids( + @builtin(vertex_index) vertex_index: u32, + @builtin(instance_index) instance_index: u32, +) -> VertexOutput +{ + var out: VertexOutput; + out.clip_position = DEGENERATE_POSITION; + out.color = OBJECT_COLOR; + out.normal = vec3(0.0, 0.0, 1.0); + + if instance_index >= arrayLength(&nodes) + { + return out; + } + + let node = nodes[instance_index]; + + // Only leaves own objects. + if node.count == 0u + { + return out; + } + + let object_index = vertex_index / VERTICES_PER_OBJECT; + if object_index >= node.count + { + return out; + } + + let object_array_index = node.first_or_left + object_index; + if object_array_index >= arrayLength(&objects) + { + return out; + } + let object = objects[object_array_index]; + + let local_vertex_index = vertex_index % VERTICES_PER_OBJECT; + let local_position = corner_position( + vec3(0.0, 0.0, 0.0), + vec3(1.0, 1.0, 1.0), + TRIANGLE_CORNERS[local_vertex_index], + ); + let world_position = object.local_to_world * vec4(local_position, 1.0); + + out.clip_position = view_proj * world_position; + + // normals transform with the inverse transpose of local_to_world, which is + // transpose(world_to_local). + let face = local_vertex_index / 6u; + out.normal = normalize( + (transpose(object.world_to_local) * vec4(FACE_NORMALS[face], 0.0)).xyz, + ); + + return out; +} + +@fragment +fn fs_lines(input: VertexOutput) -> @location(0) vec4 +{ + return vec4(input.color, 1.0); +} + +@fragment +fn fs_solids(input: VertexOutput) -> @location(0) vec4 +{ + let normal = normalize(input.normal); + let light_direction = normalize(vec3(0.45, 0.80, 0.55)); + let diffuse = max(dot(normal, light_direction), 0.0); + + return vec4(input.color * (0.35 + 0.65 * diffuse), 1.0); +} diff --git a/src/bvh/gpu.rs b/src/bvh/gpu.rs new file mode 100644 index 0000000..cfe82f8 --- /dev/null +++ b/src/bvh/gpu.rs @@ -0,0 +1,79 @@ +//! GPU ready structures for the BVH representation + +use glam::Mat4; +use glam::Vec3; + +use crate::bvh::aabb::Aabb; + +#[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)] +#[repr(C)] +pub struct GpuAabb +{ + pub min: Vec3, + _pad0: u32, // On the GPU vec3 are aligned to 4 u32 + pub max: Vec3, + _pad1: u32, +} + +/// Follow the same documentation as [`BvhNode`] +#[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)] +#[repr(C)] +pub struct GpuBvhNode +{ + pub aabb: GpuAabb, + pub count: u32, + pub first_or_left: u32, +} + +/// To be a leaf of a GPU BVH +#[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)] +#[repr(C)] +pub struct GpuObject +{ + local_to_world: Mat4, // Tranform + world_to_local: Mat4, // Ray to chunk + table_slot: u32, + _pad0: [u32; 3], +} + +impl From for GpuAabb +{ + fn from(value: Aabb) -> Self + { + Self::new(value.min(), value.max()) + } +} + +impl From for Aabb +{ + fn from(value: GpuAabb) -> Self + { + Aabb::new(value.min, value.max) + } +} + +impl GpuObject +{ + pub fn new(slot: u32, transform: Mat4) -> Self + { + GpuObject { + local_to_world: transform, + world_to_local: transform.inverse(), + table_slot: slot, + _pad0: Default::default(), + } + } +} + +impl GpuAabb +{ + pub fn new(min: Vec3, max: Vec3) -> Self + { + Self { + min, + _pad0: Default::default(), + max, + _pad1: Default::default(), + } + } +} diff --git a/src/main.rs b/src/main.rs index ac0e5b5..45af6b0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,12 +1,14 @@ #![feature(generic_const_exprs)] #![feature(float_algebraic)] +use std::arch::x86_64; use std::marker::PhantomData; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicU32; use std::sync::mpsc::Sender; use std::thread::Thread; +use std::time::Instant; use bytemuck::Pod; use bytemuck::Zeroable; @@ -16,9 +18,12 @@ use egui::Color32; use egui::mutex::Mutex; use egui_plot::BarChart; use glam::Mat4; +use glam::Quat; use glam::Vec3; use glam::Vec4; use itertools::Itertools; +use rand::random_bool; +use rand::random_range; use rayon::iter::IntoParallelRefIterator; use rayon::iter::ParallelIterator; use wgpu::BindGroupLayout; @@ -49,6 +54,10 @@ use winit::event_loop::OwnedDisplayHandle; use winit::window::Window; use winit::window::WindowId; +use crate::bvh::BvhObject; +use crate::bvh::BvhStructureTable; +use crate::bvh::aabb::Aabb; +use crate::bvh::debug::BvhDebugPipeline; use crate::camera::Camera; use crate::egui_renderer::EguiRenderer; use crate::gpu_profiler::Frame; @@ -56,21 +65,31 @@ use crate::gpu_profiler::Profile; use crate::gpu_profiler::ProfilingEncoder; use crate::producers::ChunkedProducer; use crate::producers::SdfGenerator; +use crate::production::ProducerId; +use crate::production::StructureAnchor; +use crate::production::StructureLocator; use crate::production::request_queue::FrameId; use crate::production::request_queue::IncomingRequest; use crate::production::request_queue::QueueConfig; use crate::production::request_queue::RequestKey; use crate::production::request_queue::RequestQueue; use crate::production::request_queue::RequestTarget; -use crate::sparse_tree::NTreeNodeLocator; +use crate::production::tree_locator::TreeLocator; +use crate::sparse_tree::Color; +use crate::sparse_tree::NTree; +use crate::sparse_tree::NTreeNode; +use crate::sparse_tree::load_ply; use crate::terrain::ToroidalStructureTable; use crate::voxel_cache::VoxelCache; use crate::voxel_cache::VoxelCacheInsertion; use crate::voxel_cache::insertion::CacheInsertionData; use crate::voxel_cache::requests::CacheRequestBuffer; +use crate::voxel_cache::schema::ChildInformation; use crate::voxel_cache::schema::InsertionInformation; use crate::voxel_cache::schema::LocationPage; +use crate::voxel_cache::tables::FixedStructureTable; +pub mod bvh; mod camera; mod egui_renderer; mod gi_pipeline; @@ -81,7 +100,6 @@ mod production; mod sparse_tree; mod terrain; mod voxel_cache; -// enum DisplayTexture { @@ -134,8 +152,6 @@ struct State structure_table: Arc>, structure_table_request_buffer: Arc, structure_table_cache_insertion: Arc>, - instance_buffer: Buffer, - instance_count: usize, usage_vec: Arc>>, rm_time: Arc>, frame_time: Arc>, @@ -153,6 +169,9 @@ struct State // Producers workers wakeup: Sender<()>, + + bvh: BvhStructureTable, + bvh_debug: BvhDebugPipeline, } pub unsafe fn as_raw_bytes(slice: &[T]) -> &[u8] @@ -358,6 +377,19 @@ impl State panic!(); */ + // Load dragon ply + let tree: NTree<4> = load_ply("dragon.txt"); + // let mut arrays = vec![Color(0., 0., 0., 0.); 256 * 256 * 256]; + // for ((x, y), z) in (0..256).cartesian_product(0..256).cartesian_product(0..256) + // { + // if Vec3::new(x as f32, y as f32, z as f32).length() < 128. + // { + // let index = x + y * 256 + z * 256 * 256; + // //arrays[index] = Color(1., 1., 1., 1.); + // } + // } + // let tree: NTree<4> = NTree::from_array(&arrays, 4); + let size = window.inner_size(); let surface = instance.create_surface(window.clone()).unwrap(); @@ -413,11 +445,12 @@ impl State let total_chunk_count = terrain_height * terrain_width * terrain_alt; let structure_table_request_buffer = CacheRequestBuffer::new(&device, 128); - //let structure_table = FixedStructureTable::new( - // &device, - // total_chunk_count, - // structure_table_request_buffer.max_requests, - //); + // let structure_table = FixedStructureTable::new( + // &device, + // total_chunk_count, + // structure_table_request_buffer.max_requests, + // 0, + // ); let structure_table = ToroidalStructureTable::new( &device, (terrain_width, terrain_alt, terrain_height), @@ -490,6 +523,48 @@ impl State // ) // }; + let mut bvh = BvhStructureTable::new(&device, 128, 128); + let extent = Aabb::new(-10. * Vec3::ONE, 10. * Vec3::ONE); + for _ in 0..200 + { + let transform = Mat4::from_rotation_translation( + Quat::from_euler( + glam::EulerRot::XYZ, + random_range(-3.1..3.1), + random_range(-3.1..3.1), + random_range(-3.1..3.1), + ), + Vec3::new( + random_range(extent.min().x..extent.max().x), + random_range(extent.min().y..extent.max().y), + random_range(extent.min().z..extent.max().z), + ), + ); + + bvh.add( + &device, + &queue, + BvhObject { + anchor: StructureAnchor::zeroed(), + producer_id: ProducerId(0), + transform, + bounding_box: Aabb::CHUNK, + }, + ); + } + + let now = Instant::now(); + bvh.rebuild(&device, &queue); + let time = Instant::now() - now; + + println!("Bvh build time : {}ms", time.as_millis()); + + let bvh_debug = BvhDebugPipeline::new( + &device, + surface_format.add_srgb_suffix(), + wgpu::TextureFormat::Depth24PlusStencil8, + ); + let shader_module = unsafe { device.create_shader_module_passthrough({ wgpu::ShaderModuleDescriptorPassthrough { @@ -706,11 +781,12 @@ impl State let finshed = work .par_iter() .map(|work_item| { - let d = fullfill_request( - &terrain_generator, - &work_item.key, - &structure_table_1, - ); + // let d = fullfill_request( + // &terrain_generator, + // &work_item.key, + // &structure_table_1, + // ); + let d = fullfill_request_tree(&tree, &work_item.key); ( work_item, VoxelPayload { @@ -781,8 +857,6 @@ impl State insertion_debounce: false, camera: Default::default(), - instance_buffer, - instance_count, rm_time: Arc::new(Mutex::new(0.)), frame_time: Arc::new(Mutex::new(0.)), terrain_width, @@ -792,6 +866,8 @@ impl State insert_profile: Arc::new(Mutex::new(Profile::default())), cursor_grabed: true, wakeup: wakeup_tx, + bvh, + bvh_debug, }; // Configure surface for the first time @@ -1103,9 +1179,9 @@ impl State // 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 + for anchor in retired { - request_queue.invalidate_structure(structure); + request_queue.invalidate_anchor(anchor); } } @@ -1147,6 +1223,7 @@ impl State chunk_height: self.terrain_height as u32, chunk_alt: self.terrain_alt as u32, + //table_base_slot: Default::default(), table_base_slot, }]; renderpass.set_immediates(0, unsafe { as_raw_bytes(&imm) }); @@ -1177,6 +1254,19 @@ impl State self.target_blitter .copy(&self.device, &mut encoder, target_view, &texture_view); + self.bvh_debug.render( + &self.device, + &self.queue, + &mut encoder, + &texture_view, + &self.depth_buffer.1, + self.camera.view_proj(), + self.bvh.bvh_nodes(), + self.bvh.bvh_objects(), + self.bvh.node_count(), + 2, + ); + // ~~ EGUI Render pass ~~ { self.egui_renderer.begin_frame(&self.window); @@ -1747,6 +1837,108 @@ pub struct ChunkImmediate frame_timestamp: u32, } +fn fullfill_request_tree( + tree: &NTree, + request: &RequestKey, +) -> ( + [u32; N * N * N], + [[f32; 3]; N * N * N], + InsertionInformation, + LocationPage, +) +{ + match request.target + { + RequestTarget::Root => + { + let root = tree + .get_by_loc(TreeLocator::root()) + .expect("Root must exist"); + + if !root.subdivided + { + // Produce little node of constant + ( + [root.color.as_packed_u32(); N * N * N], + //[sparse_tree::Color(1., 1., 1., 1.).as_packed_u32(); N * N * N], + [Default::default(); N * N * N], + InsertionInformation { + children: [ChildInformation::new(false, root.color.3 != 0.); N * N * N], + }, + LocationPage { + node_id: StructureLocator::from(TreeLocator::::root()).0, + producer_id: 0, + anchor: StructureAnchor::zeroed(), + }, + ) + } + else + { + let mut colors = vec![]; + let mut children = vec![]; + TreeLocator::root().children().for_each(|loc| { + let node = tree.get_by_loc(loc).unwrap(); + colors.push(node.color.as_packed_u32()); + children.push(ChildInformation::new( + node.subdivided, + node.subdivided || node.color.3 != 0., + )); + }); + + ( + std::array::from_fn(|i| colors[i]), + [Default::default(); N * N * N], + InsertionInformation { + children: std::array::from_fn(|i| children[i]), + }, + LocationPage { + node_id: StructureLocator::from(TreeLocator::::root()).0, + producer_id: 0, + anchor: StructureAnchor::zeroed(), + }, + ) + } + } + RequestTarget::Child { + parent, + children_index, + } => + { + let child_z = children_index / (4 * 4); + let child_y = (children_index % (4 * 4)) / 4; + let child_x = children_index % 4; + + let loc: TreeLocator = parent.into(); + let loc = loc.child(child_x, child_y, child_z); + + let mut colors = vec![]; + let mut children = vec![]; + loc.children().for_each(|child_loc| { + let node = tree.get_by_loc(child_loc).unwrap(); + colors.push(node.color.as_packed_u32()); + children.push(ChildInformation::new( + node.subdivided, + node.subdivided || node.color.3 != 0., + )); + }); + + ( + std::array::from_fn(|i| colors[i]), + [Default::default(); N * N * N], + InsertionInformation { + children: std::array::from_fn(|i| children[i]), + }, + LocationPage { + node_id: StructureLocator::from(loc).0, + producer_id: 0, + anchor: StructureAnchor::zeroed(), + }, + ) + } + } +} + +/* fn fullfill_request( generator: &dyn ChunkedProducer, request: &RequestKey, @@ -1789,9 +1981,9 @@ where // one without a parent page; `node_id == 0` also happens for child 0 of // the root, so it cannot be used to detect roots. node = generator.produce_node(0, 0, 0, 0, (chunk_x, chunk_y, chunk_z)); + let locator: StructureLocator = TreeLocator::::root().into(); location = LocationPage { - structure_id: request.structure_id.0, - node_id: NTreeNodeLocator::<4>::root().as_usize() as u32, + node_id: locator.0, producer_id: request.producer_id.0, anchor, }; @@ -1807,7 +1999,7 @@ where unreachable!(); }; // Figure out depth of request - let locator = NTreeNodeLocator::<4>::from_usize(parent.0 as usize); + let locator: TreeLocator<4> = (*parent).into(); let depth = locator.depth(); //let (x, y, z) = locator.node_location(); @@ -1815,15 +2007,21 @@ where let child_y = (children_index % (4 * 4)) / 4; let child_x = children_index % 4; - let child_locator = locator.child(child_x as usize, child_y as usize, child_z as usize); + let child_locator = locator.child(child_x, child_y, child_z); let (nx, ny, nz) = child_locator.node_location(); - node = generator.produce_node(depth + 1, nx, ny, nz, (chunk_x, chunk_y, chunk_z)); + node = generator.produce_node( + (depth + 1) as usize, + nx as usize, + ny as usize, + nz as usize, + (chunk_x, chunk_y, chunk_z), + ); + let st_loc: StructureLocator = child_locator.into(); location = LocationPage { - structure_id: request.structure_id.0, - node_id: child_locator.as_usize() as u32, + node_id: st_loc.0 as u32, producer_id: request.producer_id.0, anchor, }; @@ -1838,3 +2036,4 @@ where location, ) } +*/ diff --git a/src/production.rs b/src/production.rs index e0c2160..bd82e78 100644 --- a/src/production.rs +++ b/src/production.rs @@ -22,14 +22,6 @@ pub mod request_queue; #[repr(transparent)] pub struct ProducerId(pub u32); -/// A producer can manage differnet independent voxel structure, with their own roots. -/// As such a producer can tag, to its discretion, its own structure with an Id. -/// -/// All node of a same tree thus share the same structure Id -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)] -#[repr(transparent)] -pub struct StructureId(pub u32); - /// A request can come from anywhere inside the structure. The producer can thus tag each node with /// a locator, to know where the request was issued. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)] @@ -54,16 +46,15 @@ where /// The voxel data produced by this producer type Output: VoxelAttributes; - /// A pure function that can produce a voxel node based on the owner produer id, requesting structure, and the - /// requesting location within the structure. + /// A pure function that can produce a voxel node based on the owner producer + /// id, requesting structure, and the 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. + /// must derive world position/content from it rather than from any table + /// slot: slots are placement and may change while the anchor stays stable. fn produce( &self, producer_id: ProducerId, - id: StructureId, anchor: StructureAnchor, locator: StructureLocator, ) -> (InsertionInformation, [Self::Output; N * N * N]); diff --git a/src/production/host_production.rs b/src/production/host_production.rs index 5f9978e..c96d313 100644 --- a/src/production/host_production.rs +++ b/src/production/host_production.rs @@ -57,7 +57,6 @@ where .for_each(|((request, dest_information), dest_attributes)| { let (info, attributes) = self.producer.produce( super::ProducerId(0), - super::StructureId(request.structure_id), request.anchor, super::StructureLocator(request.node_id), ); diff --git a/src/production/request_queue.rs b/src/production/request_queue.rs index 7ac2617..059351d 100644 --- a/src/production/request_queue.rs +++ b/src/production/request_queue.rs @@ -3,11 +3,9 @@ use std::collections::BTreeSet; use std::collections::HashMap; use crate::production::ProducerId; -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; @@ -44,22 +42,16 @@ pub enum RequestTarget 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, - anchor: StructureAnchor, - ) -> Self + pub fn root(producer_id: ProducerId, anchor: StructureAnchor) -> Self { Self { producer_id, - structure_id, anchor, target: RequestTarget::Root, } @@ -67,7 +59,6 @@ impl RequestKey pub fn child( producer_id: ProducerId, - structure_id: StructureId, anchor: StructureAnchor, parent: StructureLocator, children_index: u32, @@ -75,7 +66,6 @@ impl RequestKey { Self { producer_id, - structure_id, anchor, target: RequestTarget::Child { parent, @@ -156,12 +146,9 @@ pub struct IncomingRequest pub key: RequestKey, pub priority: RequestPriority, - /// Parent page information captured at the latest emission. + /// Parent/reinsertion information captured at the latest emission, + /// including the latest table slot for an external root. 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 @@ -172,13 +159,12 @@ impl IncomingRequest pub fn from_wire(request: &RequestInformation, meta: &RequestMeta) -> Self { 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, anchor), + RequestKey::root(producer_id, anchor), RequestPriority::root(request.demand), ) } @@ -187,7 +173,6 @@ impl IncomingRequest ( RequestKey::child( producer_id, - structure_id, anchor, StructureLocator(request.node_id), request.children_index, @@ -196,20 +181,10 @@ impl IncomingRequest ) }; - let table_slot = if key.is_root() - { - request.table_slot - } - else - { - NO_TABLE_SLOT - }; - Self { key, priority, meta: *meta, - table_slot, } } } @@ -238,7 +213,6 @@ pub struct ReadyItem { pub key: RequestKey, pub meta: RequestMeta, - pub table_slot: u32, pub payload: T, } @@ -250,15 +224,11 @@ impl ReadyItem { match self.key.target { - RequestTarget::Root => - { - InsertionParent::external( - self.key.structure_id.0, - self.key.producer_id.0, - self.key.anchor, - self.table_slot, - ) - } + RequestTarget::Root => InsertionParent::external( + self.key.producer_id.0, + self.key.anchor, + self.meta.table_slot, + ), RequestTarget::Child { parent, children_index, @@ -271,13 +241,7 @@ impl ReadyItem children_index, ..self.meta }; - InsertionParent::internal( - &meta, - self.key.structure_id.0, - parent.0, - self.key.producer_id.0, - self.key.anchor, - ) + InsertionParent::internal(&meta, parent.0, self.key.producer_id.0, self.key.anchor) } } } @@ -317,9 +281,9 @@ impl Default for QueueConfig { Self { max_queued: 4096, - max_in_flight: 4, + max_in_flight: 64, max_ready: 1024, - stale_after: 8, + stale_after: 2, max_attempts: 3, } } @@ -356,10 +320,9 @@ struct Job priority: RequestPriority, first_seen: FrameId, last_seen: FrameId, + /// Parent/reinsertion information, including the latest table slot. + /// Refreshed even while the job is in flight or ready. 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, @@ -480,7 +443,6 @@ impl RequestQueue job.priority = request.priority; job.meta = request.meta; - job.table_slot = request.table_slot; job.last_seen = frame; match job.state @@ -537,7 +499,6 @@ impl RequestQueue first_seen: frame, last_seen: frame, meta: request.meta, - table_slot: request.table_slot, generation, attempt: 0, payload: None, @@ -722,7 +683,6 @@ impl RequestQueue result.push(ReadyItem { key: job.key, meta: job.meta, - table_slot: job.table_slot, payload, }); } @@ -731,16 +691,6 @@ impl RequestQueue result } - /// Removes every job belonging to a structure. - /// - /// 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) - } - /// Removes every job belonging to a producer. pub fn invalidate_producer(&mut self, producer: ProducerId) -> usize { @@ -863,8 +813,9 @@ mod tests { use super::*; + use crate::voxel_cache::schema::NO_TABLE_SLOT; + const PRODUCER: ProducerId = ProducerId(0); - const STRUCTURE: StructureId = StructureId(1); const ANCHOR: StructureAnchor = StructureAnchor::ZERO; fn meta(page: u32, child: u32, depth: u32) -> RequestMeta @@ -873,18 +824,13 @@ mod tests page_index: page, children_index: child, depth, + table_slot: NO_TABLE_SLOT, } } fn child_key(parent: u32, child: u32) -> RequestKey { - RequestKey::child( - PRODUCER, - STRUCTURE, - ANCHOR, - StructureLocator(parent), - child, - ) + RequestKey::child(PRODUCER, ANCHOR, StructureLocator(parent), child) } fn incoming(key: RequestKey, priority: RequestPriority) -> IncomingRequest @@ -893,13 +839,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, child: u32, producer: u32, @@ -912,18 +856,17 @@ mod tests { ( RequestInformation { - structure_id: structure, node_id: node, children_index: child, producer_id: producer, demand, anchor, - table_slot, }, RequestMeta { page_index: parent_page, children_index: child, depth, + table_slot, }, ) } @@ -943,7 +886,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, ANCHOR); + let root = RequestKey::root(PRODUCER, ANCHOR); let child = child_key(0, 0); q.ingest( @@ -962,29 +905,18 @@ 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, - ANCHOR, - 3, - ); - let (child_info, child_meta) = - wire(STRUCTURE.0, 0, 0, PRODUCER.0, 7, 3, 0, ANCHOR, NO_TABLE_SLOT); + let (root_info, root_meta) = wire(0, 0, PRODUCER.0, 7, u32::MAX, u32::MAX, ANCHOR, 3); + let (child_info, child_meta) = wire(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, ANCHOR)); - assert_eq!(root.table_slot, 3); - assert_eq!(child.table_slot, NO_TABLE_SLOT); + assert_eq!(root.key, RequestKey::root(PRODUCER, ANCHOR)); + assert_eq!(root.meta.table_slot, 3); + assert_eq!(child.meta.table_slot, NO_TABLE_SLOT); assert_eq!( child.key, - RequestKey::child(PRODUCER, STRUCTURE, ANCHOR, StructureLocator(0), 0) + RequestKey::child(PRODUCER, ANCHOR, StructureLocator(0), 0) ); assert_ne!(root.key, child.key); } @@ -992,17 +924,7 @@ 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, - ANCHOR, - NO_TABLE_SLOT, - ); + let (info, meta) = wire(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)); @@ -1014,7 +936,7 @@ mod tests fn ready_item_builds_stateless_insertion_parent() { let mut q = queue(8, 2, 8); - let root = RequestKey::root(PRODUCER, STRUCTURE, ANCHOR); + let root = RequestKey::root(PRODUCER, ANCHOR); let child = child_key(4, 2); q.ingest( @@ -1023,14 +945,15 @@ mod tests IncomingRequest { key: root, priority: RequestPriority::root(1), - meta: meta(0, 0, 0), - table_slot: 5, + meta: RequestMeta { + table_slot: 5, + ..meta(0, 0, 0) + }, }, IncomingRequest { key: child, priority: RequestPriority::child(1, 3), meta: meta(7, 2, 3), - table_slot: NO_TABLE_SLOT, }, ], ); @@ -1046,7 +969,6 @@ mod tests let external = ready[0].insertion_parent(); assert!(external.is_external()); 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); @@ -1057,7 +979,6 @@ mod tests assert_eq!(internal.children_index, 2); 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); } @@ -1074,7 +995,6 @@ mod tests key: child, priority: RequestPriority::child(1, 3), meta: meta(7, 5, 3), - table_slot: NO_TABLE_SLOT, }], ); @@ -1092,8 +1012,8 @@ mod tests fn producer_id_disambiguates_identical_structure_keys() { let mut q = queue(8, 1, 8); - let a = RequestKey::child(ProducerId(0), STRUCTURE, ANCHOR, StructureLocator(7), 3); - let b = RequestKey::child(ProducerId(1), STRUCTURE, ANCHOR, StructureLocator(7), 3); + let a = RequestKey::child(ProducerId(0), ANCHOR, StructureLocator(7), 3); + let b = RequestKey::child(ProducerId(1), ANCHOR, StructureLocator(7), 3); q.ingest( 0, @@ -1145,7 +1065,7 @@ mod tests fn roots_outrank_children() { let mut q = queue(8, 8, 8); - let root = RequestKey::root(PRODUCER, STRUCTURE, ANCHOR); + let root = RequestKey::root(PRODUCER, ANCHOR); let child = child_key(0, 0); q.ingest( @@ -1411,7 +1331,7 @@ mod tests let item = q.pop().unwrap(); q.complete(item, 1); - assert_eq!(q.invalidate_structure(STRUCTURE), 2); + assert_eq!(q.invalidate_anchor(ANCHOR), 2); assert!(q.is_empty()); assert_eq!(q.in_flight_len(), 0); assert_eq!(q.ready_len(), 0); @@ -1421,8 +1341,8 @@ mod tests fn invalidate_producer_only_removes_that_producer() { let mut q = queue(8, 8, 8); - let a = RequestKey::child(ProducerId(0), STRUCTURE, ANCHOR, StructureLocator(1), 0); - let b = RequestKey::child(ProducerId(1), STRUCTURE, ANCHOR, StructureLocator(1), 0); + let a = RequestKey::child(ProducerId(0), ANCHOR, StructureLocator(1), 0); + let b = RequestKey::child(ProducerId(1), ANCHOR, StructureLocator(1), 0); q.ingest( 0, @@ -1449,10 +1369,12 @@ mod tests fn root_incoming(slot: u32) -> IncomingRequest { IncomingRequest { - key: RequestKey::root(PRODUCER, STRUCTURE, ANCHOR), + key: RequestKey::root(PRODUCER, ANCHOR), priority: RequestPriority::root(1), - meta: meta(NO_PARENT_PAGE, 0, NO_PARENT_PAGE), - table_slot: slot, + meta: RequestMeta { + table_slot: slot, + ..meta(NO_PARENT_PAGE, 0, NO_PARENT_PAGE) + }, } } @@ -1475,7 +1397,6 @@ mod tests assert!(parent.is_external()); assert_eq!(parent.table_slot, 2); assert_eq!(parent.anchor, ANCHOR); - assert_eq!(parent.structure_id, STRUCTURE.0); } #[test] @@ -1486,25 +1407,23 @@ mod tests q.ingest(0, [root_incoming(1)]); q.ingest(1, [root_incoming(9)]); - // Same producer/id/anchor: one job, refreshed in place, not duplicated. + // Same producer/anchor: one job, refreshed in place, not duplicated. assert_eq!(q.len(), 1); - assert!(q.contains(&RequestKey::root(PRODUCER, STRUCTURE, ANCHOR))); + assert!(q.contains(&RequestKey::root(PRODUCER, 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); + assert_eq!(ready[0].meta.table_slot, 9); } #[test] - fn different_anchors_with_same_structure_are_distinct() + fn different_anchors_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 a = RequestKey::child(PRODUCER, ANCHOR, StructureLocator(1), 0); let b = RequestKey::child( PRODUCER, - STRUCTURE, StructureAnchor::from_world(1, 2, 3, 0), StructureLocator(1), 0, @@ -1526,7 +1445,7 @@ mod tests { 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 a = RequestKey::child(PRODUCER, anchor, StructureLocator(1), 0); let b = child_key(1, 0); q.ingest( diff --git a/src/production/tree_locator.rs b/src/production/tree_locator.rs index 0cec62e..1459ef0 100644 --- a/src/production/tree_locator.rs +++ b/src/production/tree_locator.rs @@ -14,7 +14,7 @@ use crate::production::StructureLocator; /// an encoded location of `1032` for a 4-tree, refers to from the root : going into the 0th /// child, then 3rd child, then 2nd child. It refers to a node of depth 3. /// -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)] pub struct TreeLocator { x: u32, @@ -200,7 +200,7 @@ impl TreeLocator (0..N as u32) .cartesian_product(0..N as u32) .cartesian_product(0..N as u32) - .map(|((x, y), z)| self.child(x, y, z)) + .map(|((z, y), x)| self.child(x, y, z)) } /// Returns the coordinate of this node inside its parent. @@ -218,6 +218,16 @@ impl TreeLocator (x, y, z) } + + /// Returns the location of this node at in the space of this depth + pub fn node_location(&self) -> (u32, u32, u32) + { + let depth = self.depth(); + + // Puts a one in base-N on the Nth digit + let one = N.pow(depth) as u32; + (self.x % one, self.y % one, self.z % one) + } } #[cfg(test)] @@ -419,4 +429,13 @@ mod tests l = l.child(1, 1, 1); } } + + #[test] + fn node_at_depth_roundtrip() + { + let l = TreeLocator::<4>::from_node_coords(3, 8, 1, 18); + let (nx, ny, nz) = l.node_location(); + let l2 = TreeLocator::<4>::from_node_coords(3, nx, ny, nz); + assert!(l == l2); + } } diff --git a/src/sparse_tree.rs b/src/sparse_tree.rs index 36f6400..8b14955 100644 --- a/src/sparse_tree.rs +++ b/src/sparse_tree.rs @@ -4,6 +4,9 @@ use std::collections::VecDeque; use bytemuck::Pod; use bytemuck::Zeroable; use itertools::Itertools; +use noise::Terrace; + +use crate::production::tree_locator::TreeLocator; #[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)] #[repr(C)] @@ -43,7 +46,7 @@ impl Color #[derive(Debug, Clone)] pub struct NTree { - map: HashMap, NTreeNode>, + map: HashMap, NTreeNode>, // Depth is the parameter such that // N^depth == max_number_of_voxels @@ -54,19 +57,16 @@ pub struct NTree pub struct NTreeIter<'a, const N: usize> { tree: &'a NTree, - dfs_stack: Vec>, + dfs_stack: Vec>, } #[derive(Debug, Clone, Copy)] pub struct NTreeNode { - color: Color, - subdivided: bool, + pub color: Color, + pub subdivided: bool, } -#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] -pub struct NTreeNodeLocator(usize); - impl NTree where [(); N * N * N]:, @@ -78,7 +78,7 @@ where color, subdivided: false, }; - map.insert(NTreeNodeLocator::::root(), root); + map.insert(TreeLocator::::root(), root); Self { map, depth } } @@ -94,7 +94,7 @@ where assert!(z < N.pow(self.depth as u32)); // Try to walk down the tree, and create necessary nodes - let mut current_node_loc = NTreeNodeLocator::::root(); + let mut current_node_loc = TreeLocator::::root(); let mut current_node_size = N.pow(self.depth as u32); let mut current_node = self.map.get(¤t_node_loc).unwrap(); @@ -112,7 +112,8 @@ where let child_z = (z % current_node_size) / child_node_size; current_node_size = child_node_size; - current_node_loc = current_node_loc.child(child_x, child_y, child_z); + current_node_loc = + current_node_loc.child(child_x as u32, child_y as u32, child_z as u32); current_node = self.map.get(¤t_node_loc).unwrap(); } } @@ -124,7 +125,7 @@ where assert!(z < N.pow(depth as u32)); // Try to walk down the tree, and create necessary nodes - let mut current_node_loc = NTreeNodeLocator::::root(); + let mut current_node_loc = TreeLocator::::root(); let mut current_node_size = N.pow(self.depth as u32); let mut current_depth = 0; let mut current_node = self.map.get_mut(¤t_node_loc).unwrap(); @@ -145,7 +146,7 @@ where color: current_node.color, subdivided: false, }; - current_node_loc.children().into_iter().for_each(|child| { + current_node_loc.children().for_each(|child| { self.map.insert(child, new_nodes); }); } @@ -158,7 +159,8 @@ where current_node_size = child_node_size; current_depth += 1; - current_node_loc = current_node_loc.child(child_x, child_y, child_z); + current_node_loc = + current_node_loc.child(child_x as u32, child_y as u32, child_z as u32); current_node = self.map.get_mut(¤t_node_loc).unwrap(); } @@ -184,8 +186,7 @@ where // Access all children's colors let children_color_avg = current_node_loc .children() - .iter() - .map(|child_loc| self.map.get(child_loc).unwrap().color) + .map(|child_loc| self.map.get(&child_loc).unwrap().color) // AGGREGATE AND AVERAGE HERE !! .next() .unwrap(); @@ -200,7 +201,7 @@ where } } - fn make_constant(&mut self, locator: NTreeNodeLocator, color: Color) + fn make_constant(&mut self, locator: TreeLocator, color: Color) { let mut dfs_stack = Vec::new(); dfs_stack.push(locator); @@ -236,17 +237,17 @@ where let mut merged_size = vec![0; array.len()]; let width = N.pow(depth as u32); - for (x, y) in (0..width).cartesian_product(0..width) + for (z, y) in (0..width).cartesian_product(0..width) { - let mut z = 0; - while z < width + let mut x = 0; + while x < width { if merged_size[x + y * width + z * width * width] != 0 { // If current voxel has already been accounted for -> skip // We stumbled on a big merged block, we can skip it as a whole on the inner // dimension - z += merged_size[x + y * width + z * width * width]; + x += merged_size[x + y * width + z * width * width]; continue; } @@ -261,12 +262,13 @@ where // Try to merge for each depth let mut max_power_merge = 0; // Single voxel can always be merged let color = array[x + y * width + z * width * width]; - let mut locator = NTreeNodeLocator::::new(depth, x, y, z); + let mut locator = + TreeLocator::::from_node_coords(depth as u32, x as u32, y as u32, z as u32); 'power_search: for power in 1..=block_power { let block_size = N.pow(power); // Check if candidate block has the same color - for ((merge_x, merge_y), merge_z) in (0..block_size) + for ((merge_z, merge_y), merge_x) in (0..block_size) .cartesian_product(0..block_size) .cartesian_product(0..block_size) { @@ -286,7 +288,7 @@ where // We know which size we can know merge // Say we accounted for those voxels : let block_size = N.pow(max_power_merge); - for ((merge_x, merge_y), merge_z) in (0..block_size) + for ((merge_z, merge_y), merge_x) in (0..block_size) .cartesian_product(0..block_size) .cartesian_product(0..block_size) { @@ -302,7 +304,7 @@ where subdivided: false, }; structure.insert(locator, node); - z += block_size; + x += block_size; } } @@ -329,15 +331,18 @@ where } // Add hierarchy node - let locator = - NTreeNodeLocator::::new(depth - current_power, block_x, block_y, block_z); + let locator = TreeLocator::::from_node_coords( + (depth - current_power) as u32, + block_x as u32, + block_y as u32, + block_z as u32, + ); // Get average color of children let color = Color::average( locator .children() - .iter() - .map(|child_loc| structure.get(child_loc).unwrap().color), + .map(|child_loc| structure.get(&child_loc).unwrap().color), ); let hierarchy_node = NTreeNode { @@ -354,51 +359,10 @@ where } } - /* - pub fn as_explicit_structure(&self) -> (Color, Vec>) + pub fn get_by_loc(&self, locator: TreeLocator) -> Option { - let root = self.map.get(&NTreeNodeLocator::root()).unwrap(); - if !root.subdivided - { - return (root.color, vec![]); - } - - let new_node = ExplicitNTreeNode { - structure: [StructurePointer(0); _], - colors: [Color(0., 0., 0., 0.); _], - }; - let mut explicit_structure = vec![new_node.clone()]; - let mut bfs_queue = VecDeque::new(); - - bfs_queue.push_back((NTreeNodeLocator::root(), 0)); - - while let Some((node_loc, explicit_loc)) = bfs_queue.pop_front() - { - // Iterate on children, that must exist - for (i, child_loc) in node_loc.children().iter().enumerate() - { - let child_data = self.map.get(child_loc).unwrap(); - explicit_structure[explicit_loc].colors[i] = child_data.color; - - if !child_data.subdivided - { - explicit_structure[explicit_loc].structure[i] = - StructurePointer::new(false, true, 0); - continue; - } - - // Child is subdivided, it needs to be handled. - let spot = explicit_structure.len(); - explicit_structure.push(new_node.clone()); - bfs_queue.push_back((*child_loc, spot)); - explicit_structure[explicit_loc].structure[i] = - StructurePointer::new(true, true, spot as u32); - } - } - - (root.color, explicit_structure) + self.map.get(&locator).copied() } - */ } fn base_trailing_zeroes(mut number: usize) -> Option @@ -417,117 +381,80 @@ fn base_trailing_zeroes(mut number: usize) -> Option Some(trailing_zeroes) } -impl NTreeNodeLocator +pub fn load_ply, const N: usize>(path: P) -> NTree +where + [(); N * N * N]:, { - pub fn root() -> Self + let file = std::fs::read_to_string(path).unwrap(); + + let mut colors = vec![Color(0., 0., 0., 0.); 256 * 256 * 256]; + for line in file.lines() { - Self(1) + let coords = line + .split(',') + .take(3) + .map(|s| s.trim_end().trim_start().parse::().unwrap()) + .collect::>(); + let (x, y, z) = (coords[0], coords[1], coords[2]); + let index = x + z * 256 + y * 256 * 256; + colors[index as usize] = Color(1., 1., 1., 1.); } - pub fn from_usize(n: usize) -> Self + NTree::from_array(&colors, 4) +} + +mod test +{ + use glam::Vec3; + use rand::random; + + use crate::production::tree_locator::TreeLocator; + use crate::sparse_tree::Color; + use crate::sparse_tree::NTree; + + #[test] + fn constant_set() { - Self(n) + let mut tree = NTree::<4>::constant(Color(0., 0., 0., 0.), 4); + assert!(tree.get(0, 0, 0) == Color(0., 0., 0., 0.)); + tree.set(0, 0, 0, Color(1., 1., 1., 1.)); + assert!(tree.get(0, 0, 0) == Color(1., 1., 1., 1.)); } - pub fn new(mut depth: usize, x: usize, y: usize, z: usize) -> Self + #[test] + fn load_read_same() { - let mut loc = Self::root(); - let mut size = N.pow(depth as u32); - while depth != 0 + let file = std::fs::read_to_string("dragon.txt").unwrap(); + + let mut colors = vec![Color(0., 0., 0., 0.); 256 * 256 * 256]; + for line in file.lines() { - size /= N; - let child_x = (x / size) % N; - let child_y = (y / size) % N; - let child_z = (z / size) % N; - loc = loc.child(child_x, child_y, child_z); - depth -= 1; + let coords = line + .split(',') + .take(3) + .map(|s| s.trim_end().trim_start().parse::().unwrap()) + .collect::>(); + let (x, y, z) = (coords[0], coords[1], coords[2]); + let index = x + z * 256 + y * 256 * 256; + colors[index as usize] = Color(1., 1., 1., 1.); } - return loc; - } + println!("building tree"); + let tree = NTree::<4>::from_array(&colors, 4); + println!("ok"); - pub fn depth(&self) -> usize - { - let mut n = self.0; - let mut depth = 0; - while n != 1 + for x in 0..256 { - n /= N * N * N; - depth += 1; - } - depth - } - - pub fn child_location(&self) -> (usize, usize, usize) - { - let mut n = self.0; - let z = n % N; - n /= N; - let y = n % N; - n /= N; - let x = n % N; - - (x, y, z) - } - - pub fn node_location(&self) -> (usize, usize, usize) - { - let mut locator = *self; - let mut nx = 0; - let mut ny = 0; - let mut nz = 0; - let mut size = 1; - while locator.0 != 1 - { - let (cx, cy, cz) = locator.child_location(); - - nx += cx * size; - ny += cy * size; - nz += cz * size; - size *= N; - - locator = locator.parent().unwrap(); - } - - (nx, ny, nz) - } - - pub fn as_usize(&self) -> usize - { - self.0 - } - - pub fn parent(&self) -> Option - { - // Shift left by 3 digits in base N - let loc = self.0 / (N * N * N); - if loc == 0 { None } else { Some(Self(loc)) } - } - - pub fn child(&self, x: usize, y: usize, z: usize) -> Self - { - assert!(x < N); - assert!(y < N); - assert!(z < N); - - let child_loc = (self.0 * N * N * N) + (x * N * N) + (y * N) + z; - NTreeNodeLocator(child_loc) - } - - pub fn children(&self) -> Vec - { - let mut children = vec![]; - - for x in 0..N - { - for y in 0..N + for y in 0..256 { - for z in 0..N + for z in 0..256 { - children.push(self.child(x, y, z)); + let index = x + y * 256 + z * 256 * 256; + let color = colors[index]; + let t = tree.get(x, y, z); + assert!(t == color); } } } - children } } diff --git a/src/terrain.rs b/src/terrain.rs index f208a0c..30350c0 100644 --- a/src/terrain.rs +++ b/src/terrain.rs @@ -7,7 +7,6 @@ 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; @@ -110,19 +109,19 @@ impl ToroidalStructureTable /// This requires updating the structure table to remove disapearing chunks. /// /// Slots whose world position changed get a new anchor. Anchors that remain - /// in view keep their [`StructureId`]; anchors that leave are retired. The + /// in view keep their identity; 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. + /// Returns the retired anchors. The host may use them to cancel speculative + /// queue work; correctness does not depend on it because GPU insertion + /// validates the anchor/slot. pub fn move_position( &mut self, queue: &wgpu::Queue, encoder: &mut CommandEncoder, new_position: Vec3, - ) -> Vec + ) -> Vec { let previous_offset = self.current_offset; let new_offset = Self::offset_from_center(self.extent, new_position); @@ -140,10 +139,9 @@ impl ToroidalStructureTable }) .collect(); - let (_assignments, retired_ids) = self + retired = self .fixed_structure_table .reassign_slots(queue, &new_anchors); - retired = retired_ids; } let invalidation_parameters = ToroidalInvalidationImmediates { @@ -208,12 +206,12 @@ impl ToroidalStructureTable fn position_for_offset( extent: (usize, usize, usize), - structure_id: usize, + slot: usize, offset: (isize, isize, isize), ) -> (isize, isize, isize) { let (ex, ey, ez) = (extent.0 as isize, extent.1 as isize, extent.2 as isize); - let id = structure_id as isize; + let id = slot as isize; let sx = id % ex; let sz = (id / ex) % ez; diff --git a/src/tree.rs b/src/tree.rs deleted file mode 100644 index d3ecc8f..0000000 --- a/src/tree.rs +++ /dev/null @@ -1,837 +0,0 @@ -use std::collections::HashMap; -use std::collections::VecDeque; -use std::hash::Hash; -use std::vec; - -use itertools::Itertools; - -#[derive(Clone, Copy, PartialEq, Debug)] -pub struct Color(pub f32, pub f32, pub f32, pub f32); - -pub struct NTree -{ - structure: HashMap, NTreeNode>, - depth: u32, -} - -#[derive(Clone, Copy)] -struct NTreeNode -{ - color: Color, - subdivided: bool, -} - -impl NTree -where - [(); N * N * N]:, -{ - pub fn constant(color: Color, depth: u32) -> Self - { - let mut structure = HashMap::new(); - structure.insert( - NTreeLocator::root(), - NTreeNode { - color, - subdivided: false, - }, - ); - Self { structure, depth } - } - - pub fn get(&self, x: usize, y: usize, z: usize) -> Color - { - let mut local_x = x; - let mut local_y = y; - let mut local_z = z; - - let mut size = N.pow(self.depth); - assert!(x < size && y < size && z < size); - - let mut current_loc = NTreeLocator::::root(); - let mut current_node = *self.structure.get(¤t_loc).unwrap(); - - loop - { - if !current_node.subdivided - { - return current_node.color; - } - - size /= N; - - // Descend - let child_x = local_x / size; - let child_y = local_y / size; - let child_z = local_z / size; - - // Node is subdivided, descend - current_loc = current_loc.get_child(child_x, child_y, child_z); - current_node = *self.structure.get(¤t_loc).unwrap(); - - local_x -= child_x * size; - local_y -= child_y * size; - local_z -= child_z * size; - } - } - - pub fn from_arrays_old(chunk: &[Color], depth: u32) -> Self - { - let chunk_width = N.pow(depth); - let mut structure = HashMap::with_capacity(chunk_width * chunk_width * chunk_width); - println!("Inserting voxels"); - for ((x, y), z) in (0..chunk_width) - .cartesian_product(0..chunk_width) - .cartesian_product(0..chunk_width) - { - structure.insert( - NTreeLocator::::from_depth_coords(x, y, z, depth as usize), - NTreeNode:: { - color: chunk[x + y * chunk_width + z * chunk_width * chunk_width], - subdivided: false, - }, - ); - } - - println!("Starting bottom up"); - let mut current_size = 1; - for d in (0..depth).rev() - { - println!("depth: {d}"); - current_size *= N; - for ((x, y), z) in (0..(chunk_width / current_size)) - .cartesian_product(0..(chunk_width / current_size)) - .cartesian_product(0..(chunk_width / current_size)) - { - let loc = NTreeLocator::::from_depth_coords(x, y, z, d as usize); - let children = (0..N) - .cartesian_product(0..N) - .cartesian_product(0..N) - .map(|((cx, cy), cz)| structure.get(&loc.get_child(cx, cy, cz)).unwrap()) - .collect::>(); - - let (can_merge, _) = children.iter().fold((true, None), |acc, child| match acc - { - (_, None) => (true, Some(child.color)), - (b, Some(color)) => - { - (b && !child.subdivided && color == child.color, Some(color)) - } - }); - - let node; - if can_merge - { - node = NTreeNode:: { - color: children[0].color, - subdivided: false, - }; - - //Remove merged childrenn - (0..N) - .cartesian_product(0..N) - .cartesian_product(0..N) - .for_each(|((cx, cy), cz)| { - structure.remove(&loc.get_child(cx, cy, cz)).unwrap(); - }); - } - else - { - node = NTreeNode:: { - color: Color::average( - children - .iter() - .map(|x| x.color) - .collect::>() - .as_slice(), - ), - subdivided: true, - }; - } - structure.insert(loc, node); - } - } - - Self { structure, depth } - } - - pub fn from_arrays(chunk: &[Color], depth: usize) -> Self - { - let width = N.pow(depth as u32); - let mut structure = HashMap::new(); - let mut taken = vec![0; chunk.len()]; // Whether or not the current voxel has been added - - // Voxel insertion/combination pass - for (y, z) in (0..width).cartesian_product(0..width) - { - let mut x = 0; - while x < width - { - if taken[x + y * width + z * width * width] != 0 - { - x += taken[x + y * width + z * width * width]; - continue; - } - - let max_combination_depth = trailing_zeroes::(x) - .unwrap_or(depth) - .min(trailing_zeroes::(y).unwrap_or(depth)) - .min(trailing_zeroes::(z).unwrap_or(depth)); - - let prev_color = chunk[x + y * width + z * width * width]; - let mut locator = NTreeLocator::::from_depth_coords(x, y, z, depth); - //let mut insertion_depth = depth; - let mut block_width = 1; - 'depth_loop: for depth in 1..=max_combination_depth - { - let combination_width = N.pow(depth as u32); - for ((sx, sy), sz) in (0..combination_width) - .cartesian_product(0..combination_width) - .cartesian_product(0..combination_width) - { - let voxel_color = - chunk[(x + sx) + (y + sy) * width + (z + sz) * width * width]; - let voxel_taken = - taken[(x + sx) + (y + sy) * width + (z + sz) * width * width]; - if prev_color != voxel_color || voxel_taken != 0 - { - // Cannot merge further - break 'depth_loop; - } - } - - // At this point, voxel in combination_width^3 block can be merged - block_width = combination_width; - //insertion_depth -= 1; - locator = locator.get_parent(); - } - - structure.insert( - locator, - NTreeNode { - color: prev_color, - subdivided: false, - }, - ); - - // Mark as taken - for ((sx, sy), sz) in (0..block_width) - .cartesian_product(0..block_width) - .cartesian_product(0..block_width) - { - taken[(x + sx) + (y + sy) * width + (z + sz) * width * width] = block_width; - } - - x += block_width; - } - } - - // Increase pass - for d in (0..=(depth - 1)).rev() - { - // Iterate on blocks of depth d - let block_count = N.pow(d as u32); // Number of such blocks along axis - let block_width = width / block_count; // Number of such blocks along axis - for ((bx, by), bz) in (0..(block_count)) - .cartesian_product(0..(block_count)) - .cartesian_product(0..(block_count)) - { - // Get how was the origin voxel merged - let merged_width = taken[(bx * block_width) - + (by * block_width) * width - + (bz * block_width) * width * width]; - - if merged_width >= block_width - { - // Current voxels have been merged in bigger or equal block - continue; - } - - let locator = NTreeLocator::::from_depth_coords(bx, by, bz, d); - - // Otherwise, merge - - // Children CANNOT be merged, Otherwise they would have been already - // Compute average color - - let colors = locator - .iter_children() - .map(|loc| structure.get(&loc).unwrap().color) - .collect::>(); - structure.insert( - locator, - NTreeNode:: { - color: Color::average(&colors), - subdivided: true, - }, - ); - } - } - - Self { - structure, - depth: depth as u32, - } - } - - pub fn set(&mut self, x: usize, y: usize, z: usize, color: Color) - { - let mut local_x = x; - let mut local_y = y; - let mut local_z = z; - - let mut size = N.pow(self.depth); - assert!(x < size && y < size && z < size); - - let mut current_loc = NTreeLocator::::root(); - let mut current_node = *self.structure.get(¤t_loc).unwrap(); - let mut current_depth = 0; - - loop - { - // Subnodes alread with correct color - if current_node.color == color - { - return; - } - - if current_depth == self.depth - { - current_node.color = color; - self.structure.get_mut(¤t_loc).unwrap().color = color; - break; - } - - if !current_node.subdivided - { - // Have to subdivide - let sub_child = NTreeNode:: { - color: current_node.color, - subdivided: false, - }; - // Set node as subdivided - self.structure.get_mut(¤t_loc).unwrap().subdivided = true; - current_node.subdivided = true; - - // Insert new children - current_loc.iter_children().for_each(|x| { - self.structure.insert(x, sub_child); - }); - } - - if current_node.subdivided - { - size /= N; - let child_x = local_x / size; - let child_y = local_y / size; - let child_z = local_z / size; - - // Node is subdivided, descend - current_loc = current_loc.get_child(child_x, child_y, child_z); - current_node = *self.structure.get(¤t_loc).unwrap(); - current_depth += 1; - - local_x -= child_x * size; - local_y -= child_y * size; - local_z -= child_z * size; - } - } - - // Insertion has been done, travel back up to optimise - loop - { - // Try to simplify, compute average - if current_node.subdivided - { - let (compressable, color) = current_loc - .iter_children() - .map(|x| self.structure.get(&x).unwrap()) - .fold((true, None), |state, child| match state - { - (_, None) => (!child.subdivided, Some(child.color)), - (b, Some(c)) => (b && !child.subdivided && c == child.color, Some(c)), - }); - - if compressable - { - // Compress - *self.structure.get_mut(¤t_loc).unwrap() = NTreeNode { - color: color.unwrap(), - subdivided: false, - }; - - // Remove children - current_loc.iter_children().for_each(|x| { - self.structure.remove(&x).unwrap(); - }); - } - else - { - // Update average color - let colors = current_loc - .iter_children() - .map(|x| self.structure.get(&x).unwrap().color) - .collect::>(); - self.structure.get_mut(¤t_loc).unwrap().color = - Color::average(colors.as_slice()); - } - } - - // Travel up - if current_depth == 0 - { - break; // Finished - } - - current_loc = current_loc.get_parent(); - current_node = *self.structure.get(¤t_loc).unwrap(); - current_depth -= 1; - } - } - - pub fn to_gpu_rep(&self) -> (Color, Vec>, Vec<[Color; N * N * N]>) - { - // No root + group by child group - let tile_count = (self.structure.len() - 1) / (N * N * N); - if tile_count == 0 - { - return ( - self.structure - .get(&NTreeLocator::::root()) - .unwrap() - .color, - vec![], - vec![], - ); - } - - let mut structure_tiles = vec![GPUStructureTile::::zero(); tile_count]; - let mut color_tiles = vec![[Color(0., 0., 0., 0.); N * N * N]; tile_count]; - - let mut current_tile = 0usize; - let mut queue = VecDeque::new(); - queue.push_back((NTreeLocator::::root(), current_tile)); - current_tile += 1; - while !queue.is_empty() - { - let (loc, dest_tile) = queue.pop_front().unwrap(); - - let children = loc - .iter_children() - .map(|x| (x, self.structure.get(&x).unwrap())) - .collect::>(); - - let mut structure_tile = GPUStructureTile::::zero(); - let mut color_tile = [Color(0., 0., 0., 0.); N * N * N]; - - for (i, (child_loc, child)) in children.into_iter().enumerate() - { - structure_tile.children[i] = GPUStructureTileIndex::new( - child.subdivided, - child.subdivided, - current_tile as u32, - ); - color_tile[i] = child.color; - - if child.subdivided - { - queue.push_back((child_loc, current_tile)); - current_tile += 1; - } - } - - structure_tiles[dest_tile] = structure_tile; - color_tiles[dest_tile] = color_tile; - } - - println!( - "node count: {}, current_tile: {}", - self.structure.len(), - current_tile - ); - ( - self.structure - .get(&NTreeLocator::::root()) - .unwrap() - .color, - structure_tiles, - color_tiles, - ) - } -} - -#[derive(Clone, Copy)] -pub struct GPUStructureTile -where - [(); N * N * N]:, -{ - children: [GPUStructureTileIndex; N * N * N], -} - -impl GPUStructureTile -where - [(); N * N * N]:, -{ - pub fn zero() -> Self - { - GPUStructureTile { - children: [GPUStructureTileIndex::zero(); N * N * N], - } - } -} - -#[derive(Clone, Copy)] -pub struct GPUStructureTileIndex(u32); - -impl GPUStructureTileIndex -{ - pub fn zero() -> Self - { - GPUStructureTileIndex(0) - } - - pub fn new(subdivided: bool, leaf: bool, ptr: u32) -> Self - { - assert_eq!((ptr >> 30), 0); - GPUStructureTileIndex(ptr | ((leaf as u32) << 30) | ((subdivided as u32) << 31)) - } - - pub fn index(&self) -> u32 - { - self.0 & 0x3FFFFFFFu32 - } - - pub fn subdivided(&self) -> bool - { - (self.0 >> 31) == 1 - } - - pub fn leaf(&self) -> bool - { - ((self.0 >> 30) & 1) == 1 - } -} - -impl Color -{ - pub fn average(colors: &[Color]) -> Color - { - let sum = colors - .iter() - .copied() - .reduce(|Color(r_a, g_a, b_a, a_a), Color(r_b, g_b, b_b, a_b)| { - Color(r_a + r_b, g_a + g_b, b_a + b_b, a_a + a_b) - }) - .unwrap_or(Color(0., 0., 0., 0.)); - //let len = colors.len().max(1) as f32; - let len = colors.iter().map(|x| x.3).sum::(); - - Color(sum.0 / len, sum.1 / len, sum.2 / len, sum.3 / len) - } -} - -#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)] -pub struct NTreeLocator(usize, usize, usize); - -impl NTreeLocator -{ - pub fn root() -> Self - { - Self(1, 1, 1) - } - - pub fn get_child(&self, child_x: usize, child_y: usize, child_z: usize) -> Self - { - assert!(child_x < N && child_y < N && child_z < N); - let mut new_loc_x = self.0; - let mut new_loc_y = self.1; - let mut new_loc_z = self.2; - - // Shift to left three times - new_loc_x *= N; - new_loc_x += child_x; - - new_loc_y *= N; - new_loc_y += child_y; - - new_loc_z *= N; - new_loc_z += child_z; - - Self(new_loc_x, new_loc_y, new_loc_z) - } - - pub fn from_depth_coords(x: usize, y: usize, z: usize, depth: usize) -> Self - { - if depth == 0 - { - return Self::root(); - } - let off = N.pow(depth as u32); - Self(off + x, off + y, off + z) - } - - pub fn iter_children(&self) -> impl Iterator> - { - (0..N) - .cartesian_product(0..N) - .cartesian_product(0..N) - .map(|((x, y), z)| self.get_child(x, y, z)) - } - - pub fn get_parent(&self) -> Self - { - if self.0 == 0 - { - *self - } - else - { - Self(self.0 / N, self.1 / N, self.2 / N) - } - } - - pub fn get_local_location(&self) -> (usize, usize, usize) - { - let mut loc = self.0; - let z = loc % N; - loc /= N; - - let y = loc % N; - loc /= N; - - let x = loc % N; - - (x, y, z) - } - - pub fn is_root(&self) -> bool - { - self.0 == 1 - } -} - -fn trailing_zeroes(mut n: usize) -> Option -{ - if n == 0 - { - return None; - } - let mut i = 0; - while n.is_multiple_of(N) - // n % N == 0 - { - i += 1; - n /= N; - } - Some(i) -} - -#[cfg(test)] -mod test -{ - - use crate::voxel::trailing_zeroes; - use itertools::Itertools; - use rand::Rng; - use rand::RngExt; - - use crate::voxel::Color; - use crate::voxel::NTree; - use crate::voxel::NTreeLocator; - - #[test] - pub fn constant() - { - let color = Color(0.5, 0.3, 0.5, 1.); - let depth = 5; - const N: usize = 3; - let width = N.pow(depth); - let ntree = NTree::::constant(color, depth); - - for ((x, y), z) in (0..width) - .cartesian_product(0..width) - .cartesian_product(0..width) - { - assert_eq!(ntree.get(x, y, z), color); - } - } - - #[test] - pub fn full_insert() - { - const DEPTH: u32 = 4; - const N: usize = 3; - const WIDTH: usize = N.pow(DEPTH); - let mut ntree = NTree::::constant(Color(1., 0., 0., 0.), DEPTH); - - let mut rng = rand::rng(); - let mut storage = vec![vec![vec![Color(0., 0., 0., 0.); WIDTH]; WIDTH]; WIDTH]; - for ((x, y), z) in (0..WIDTH) - .cartesian_product(0..WIDTH) - .cartesian_product(0..WIDTH) - { - let color = Color(rng.random(), rng.random(), rng.random(), rng.random()); - storage[x][y][z] = color; - ntree.set(x, y, z, color); - } - - for ((x, y), z) in (0..WIDTH) - .cartesian_product(0..WIDTH) - .cartesian_product(0..WIDTH) - { - let color = ntree.get(x, y, z); - assert_eq!(storage[x][y][z], color); - } - println!("Total nodes {}", ntree.structure.len()); - } - - #[test] - pub fn full_insert_bottom_up() - { - const DEPTH: u32 = 4; - const N: usize = 3; - const WIDTH: usize = N.pow(DEPTH); - - let mut rng = rand::rng(); - let mut storage = vec![Color(0., 0., 0., 0.); WIDTH * WIDTH * WIDTH]; - for ((x, y), z) in (0..WIDTH) - .cartesian_product(0..WIDTH) - .cartesian_product(0..WIDTH) - { - let color = Color(rng.random(), rng.random(), rng.random(), rng.random()); - storage[x + WIDTH * y + WIDTH * WIDTH * z] = color; - } - let ntree = NTree::::from_arrays(&storage, DEPTH as usize); - - for ((x, y), z) in (0..WIDTH) - .cartesian_product(0..WIDTH) - .cartesian_product(0..WIDTH) - { - let color = ntree.get(x, y, z); - assert_eq!(storage[x + WIDTH * y + WIDTH * WIDTH * z], color); - } - println!("Total nodes {}", ntree.structure.len()); - } - - #[test] - pub fn full_insert_const() - { - const DEPTH: u32 = 4; - const N: usize = 3; - const WIDTH: usize = N.pow(DEPTH); - const NEW_COLOR: Color = Color(0., 1., 0., 1.); - let mut ntree = NTree::::constant(Color(1., 0., 1., 0.), DEPTH); - - for ((x, y), z) in (0..WIDTH) - .cartesian_product(0..WIDTH) - .cartesian_product(0..WIDTH) - { - ntree.set(x, y, z, NEW_COLOR); - } - - for ((x, y), z) in (0..WIDTH) - .cartesian_product(0..WIDTH) - .cartesian_product(0..WIDTH) - { - let color = ntree.get(x, y, z); - assert_eq!(NEW_COLOR, color); - } - - println!("Total nodes {}", ntree.structure.len()); - } - - #[test] - pub fn full_insert_quantized() - { - const DEPTH: u32 = 4; - const N: usize = 3; - const WIDTH: usize = N.pow(DEPTH); - let mut ntree = NTree::::constant(Color(0., 0., 0., 0.), DEPTH); - - let mut rng = rand::rng(); - let mut storage = vec![vec![vec![Color(0., 0., 0., 0.); WIDTH]; WIDTH]; WIDTH]; - for ((x, y), z) in (0..WIDTH) - .cartesian_product(0..WIDTH) - .cartesian_product(0..WIDTH) - { - let nbr = rng.random::(); - let mut color = Color(0., 1., 0., 0.); - // Only 1 percent of different color - if nbr > 0.01 - { - color = Color(1., 0., 0., 0.); - } - storage[x][y][z] = color; - ntree.set(x, y, z, color); - } - - for ((x, y), z) in (0..WIDTH) - .cartesian_product(0..WIDTH) - .cartesian_product(0..WIDTH) - { - let color = ntree.get(x, y, z); - assert_eq!(storage[x][y][z], color); - } - println!("Total nodes {}", ntree.structure.len()); - } - - #[test] - pub fn gpu_rep_quantized() - { - const DEPTH: u32 = 4; - const N: usize = 3; - const WIDTH: usize = N.pow(DEPTH); - let mut ntree = NTree::::constant(Color(0., 0., 0., 0.), DEPTH); - - let mut rng = rand::rng(); - let mut storage = vec![vec![vec![Color(0., 0., 0., 0.); WIDTH]; WIDTH]; WIDTH]; - for ((x, y), z) in (0..WIDTH) - .cartesian_product(0..WIDTH) - .cartesian_product(0..WIDTH) - { - let nbr = rng.random::(); - let mut color = Color(0., 1., 0., 0.); - // Only 1 percent of different color - if nbr > 0.01 - { - color = Color(1., 0., 0., 0.); - } - storage[x][y][z] = color; - ntree.set(x, y, z, color); - } - - let (_color, _a, _b) = ntree.to_gpu_rep(); - - drop(_a); - drop(_b); - } - - #[test] - pub fn tree_locator_from_depth_coords() - { - const N: usize = 4; - assert_eq!( - NTreeLocator::::root(), - NTreeLocator::::from_depth_coords(1, 2, 3, 0) - ); - - assert_eq!( - NTreeLocator::::root().get_child(1, 2, 3), - NTreeLocator::::from_depth_coords(1, 2, 3, 1) - ); - - assert_eq!( - NTreeLocator::::root() - .get_child(1, 1, 1) - .get_child(1, 2, 3), - NTreeLocator::::from_depth_coords(4 + 1, 4 + 2, 4 + 3, 2) - ); - } - - #[test] - fn trailing_zeroes_base10() - { - let n = 2139800000; - assert_eq!(trailing_zeroes::<10>(n), Some(5)); - assert_eq!(trailing_zeroes::<10>(0), None); - } -} diff --git a/src/voxel_cache/schema.rs b/src/voxel_cache/schema.rs index d8b32dd..61f0c2c 100644 --- a/src/voxel_cache/schema.rs +++ b/src/voxel_cache/schema.rs @@ -102,15 +102,11 @@ unsafe impl Pod for StructurePage where [(); N * N * N]: {} /// Number of `u32` words in a [`StructureAnchor`]. pub const ANCHOR_WORDS: usize = 4; -/// Sentinel used in [`RequestInformation::table_slot`] and +/// Sentinel used in [`RequestMeta::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 @@ -159,9 +155,6 @@ impl StructureAnchor #[repr(C)] pub struct LocationPage { - /// Identifier for the structure to which the node pertains - pub structure_id: u32, - /// Identifier for locating this particular node within the structure pub node_id: u32, @@ -202,9 +195,6 @@ impl DepthPage #[repr(C)] pub struct RequestInformation { - /// Identifier for the structure to which the node pertains - pub structure_id: u32, - /// Identifier for locating this particular node within the structure pub node_id: u32, @@ -219,10 +209,6 @@ pub struct RequestInformation /// 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 @@ -239,6 +225,10 @@ pub struct RequestMeta /// The depth on which the request was issued pub depth: u32, + + /// Table slot for an external root request; [`NO_TABLE_SLOT`] for internal + /// requests. + pub table_slot: u32, } /// Sentinel used in [`RequestMeta::page_index`] and [`InsertionParent::page_index`] to mark a @@ -284,9 +274,6 @@ pub struct InsertionParent /// Depth of the parent. [`NO_PARENT_PAGE`] for external roots. pub depth: u32, - /// Structure the parent belongs to. - pub structure_id: u32, - /// Locator of the parent inside the structure. `0` for external roots. pub node_id: u32, @@ -306,7 +293,6 @@ impl InsertionParent /// Parent information for a child of a resident cache page. pub fn internal( meta: &RequestMeta, - structure_id: u32, node_id: u32, producer_id: u32, anchor: StructureAnchor, @@ -317,7 +303,6 @@ impl InsertionParent page_index: meta.page_index, children_index: meta.children_index, depth: meta.depth, - structure_id, node_id, producer_id, anchor, @@ -326,19 +311,13 @@ impl InsertionParent } /// Parent information for the root of an external structure. - pub fn external( - structure_id: u32, - producer_id: u32, - anchor: StructureAnchor, - table_slot: u32, - ) -> Self + pub fn external(producer_id: u32, anchor: StructureAnchor, table_slot: u32) -> Self { Self { kind: InsertionParentKind::EXTERNAL.raw(), page_index: NO_PARENT_PAGE, children_index: 0, depth: NO_PARENT_PAGE, - structure_id, node_id: 0, producer_id, anchor, @@ -426,10 +405,10 @@ mod tests fn wire_layout_sizes_are_stable() { assert_eq!(size_of::(), 16); - assert_eq!(size_of::(), 40); - assert_eq!(size_of::(), 28); - assert_eq!(size_of::(), 48); - assert_eq!(size_of::(), 12); + assert_eq!(size_of::(), 32); + assert_eq!(size_of::(), 24); + assert_eq!(size_of::(), 44); + assert_eq!(size_of::(), 16); } #[test] diff --git a/src/voxel_cache/shaders/common.wgsl b/src/voxel_cache/shaders/common.wgsl index fc637e9..a8e001a 100644 --- a/src/voxel_cache/shaders/common.wgsl +++ b/src/voxel_cache/shaders/common.wgsl @@ -27,20 +27,19 @@ fn anchor_eq(a: StructureAnchor, b: StructureAnchor) -> bool struct RequestInformation { - structure_id: u32, node_id: u32, children_index: u32, producer_id: u32, demand: u32, - anchor: StructureAnchor, - table_slot: u32 + anchor: StructureAnchor } struct RequestMeta { page_index: u32, children_index: u32, - depth: u32 + depth: u32, + table_slot: u32 } // No cache parent (external root insertion). @@ -56,7 +55,6 @@ struct InsertionParent page_index: u32, children_index: u32, depth: u32, - structure_id: u32, node_id: u32, producer_id: u32, anchor: StructureAnchor, @@ -70,7 +68,6 @@ struct AttributeArray struct LocationPage { - structure_id: u32, node_id: u32, producer_id: u32, anchor: StructureAnchor diff --git a/src/voxel_cache/shaders/fixed_table/insertion.wgsl b/src/voxel_cache/shaders/fixed_table/insertion.wgsl index b11dd64..7dc301a 100644 --- a/src/voxel_cache/shaders/fixed_table/insertion.wgsl +++ b/src/voxel_cache/shaders/fixed_table/insertion.wgsl @@ -12,7 +12,6 @@ // Group 2: Slot metadata @group(2) @binding(0) var fixed_table_anchors: array; -@group(2) @binding(1) var fixed_table_structure_ids: array; const DESTINATION_NONE: u32 = 0xFFFFFFFFu; @@ -24,8 +23,7 @@ fn slot_matches(parent: InsertionParent) -> bool return false; } - return parent.structure_id == fixed_table_structure_ids[slot] - && anchor_eq(parent.anchor, fixed_table_anchors[slot]); + return anchor_eq(parent.anchor, fixed_table_anchors[slot]); } @compute diff --git a/src/voxel_cache/shaders/fixed_table/validate_insertion.wgsl b/src/voxel_cache/shaders/fixed_table/validate_insertion.wgsl index b83099d..90f5e01 100644 --- a/src/voxel_cache/shaders/fixed_table/validate_insertion.wgsl +++ b/src/voxel_cache/shaders/fixed_table/validate_insertion.wgsl @@ -12,13 +12,12 @@ // Group 2: Slot metadata @group(2) @binding(0) var fixed_table_anchors: array; -@group(2) @binding(1) var fixed_table_structure_ids: array; 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. +/// The slot named by the parent still holds the same anchor. 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; @@ -27,8 +26,7 @@ fn slot_matches(parent: InsertionParent) -> bool return false; } - return parent.structure_id == fixed_table_structure_ids[slot] - && anchor_eq(parent.anchor, fixed_table_anchors[slot]); + return anchor_eq(parent.anchor, fixed_table_anchors[slot]); } /// Validates external root insertions against the structure table. diff --git a/src/voxel_cache/shaders/fixed_table/write_requests.wgsl b/src/voxel_cache/shaders/fixed_table/write_requests.wgsl index a9b0d66..f850ce3 100644 --- a/src/voxel_cache/shaders/fixed_table/write_requests.wgsl +++ b/src/voxel_cache/shaders/fixed_table/write_requests.wgsl @@ -8,9 +8,8 @@ @group(1) @binding(1) var request_buffer_informations: array; @group(1) @binding(2) var request_buffer_meta: array; -/// Group 2: Slot metadata (current anchor/id assignment) +/// Group 2: Slot metadata (current anchor assignment) @group(2) @binding(0) var fixed_table_anchors: array; -@group(2) @binding(1) var fixed_table_structure_ids: array; var table_producer_id: u32; @@ -34,13 +33,11 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3) } var request_info: RequestInformation; - 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[slot]; request_info.anchor = fixed_table_anchors[slot]; - request_info.table_slot = slot; var request_meta: RequestMeta; // External requests have no parent page. @@ -48,6 +45,7 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3) request_meta.children_index = 0; // u32s wrap arround request_meta.depth = 0xFFFFFFFF; + request_meta.table_slot = slot; request_buffer_informations[index] = request_info; request_buffer_meta[index] = request_meta; diff --git a/src/voxel_cache/shaders/insertion.wgsl b/src/voxel_cache/shaders/insertion.wgsl index 6d69df9..13bc6c0 100644 --- a/src/voxel_cache/shaders/insertion.wgsl +++ b/src/voxel_cache/shaders/insertion.wgsl @@ -44,8 +44,7 @@ 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 || + if(location.node_id != parent.node_id || location.producer_id != parent.producer_id || !anchor_eq(location.anchor, parent.anchor)) { diff --git a/src/voxel_cache/shaders/write_pointers.wgsl b/src/voxel_cache/shaders/write_pointers.wgsl index f7dba38..ffcaa9e 100644 --- a/src/voxel_cache/shaders/write_pointers.wgsl +++ b/src/voxel_cache/shaders/write_pointers.wgsl @@ -50,8 +50,7 @@ fn write_pointers(@builtin(global_invocation_id) gid: vec3) } let location = structure_location_pages[parent.page_index]; - if(location.structure_id != parent.structure_id || - location.node_id != parent.node_id || + if(location.node_id != parent.node_id || location.producer_id != parent.producer_id || !anchor_eq(location.anchor, parent.anchor)) { diff --git a/src/voxel_cache/shaders/write_requests.wgsl b/src/voxel_cache/shaders/write_requests.wgsl index e14d686..71497a7 100644 --- a/src/voxel_cache/shaders/write_requests.wgsl +++ b/src/voxel_cache/shaders/write_requests.wgsl @@ -33,19 +33,18 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3) // Fill out request information var request_information: RequestInformation; - request_information.structure_id = structure_location_pages[page_index].structure_id; request_information.node_id = structure_location_pages[page_index].node_id; 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; request_meta.page_index = page_index; request_meta.children_index = request_location.children_index; request_meta.depth = structure_depth_pages[page_index]; + request_meta.table_slot = NO_TABLE_SLOT; // Write them to request buffer request_buffer_informations[index] = request_information; diff --git a/src/voxel_cache/tables.rs b/src/voxel_cache/tables.rs index da8bae4..79fcfcb 100644 --- a/src/voxel_cache/tables.rs +++ b/src/voxel_cache/tables.rs @@ -1,23 +1,21 @@ +use std::collections::HashMap; + use wgpu::util::DeviceExt; +use crate::gpu::create_multi_buffers_bind_group; 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; use crate::voxel_cache::eviction::CacheEvictor; use crate::voxel_cache::insertion::CacheInsertionData; -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; - /// Cache keeps pages from different structures within itself. /// Pages are pieces of structure pointing to each other. But, in order to start tracing inside the /// voxels, we must enter the cache from somewhere @@ -40,83 +38,187 @@ macro_rules! include_table_wgsl { }}; } -/// One slot whose anchor or structure id changed during a reassignment. +/// Returns the anchors that were present in the table before the reassignment +/// but are absent afterwards. /// -/// 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( +/// The anchor is the structure identity, so an anchor that stays in view keeps +/// its identity regardless of which slot it occupies. A table must never expose +/// two live slots with the same anchor. +fn retired_anchors( old_anchors: &[StructureAnchor], - old_ids: &[StructureId], new_anchors: &[StructureAnchor], - next_structure_id: &mut u32, -) -> (Vec, Vec) +) -> Vec { - use std::collections::HashMap; use std::collections::HashSet; - assert_eq!(old_anchors.len(), old_ids.len()); assert!( new_anchors.iter().collect::>().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 = new_anchors.iter().copied().collect(); - let retired = old_anchors + old_anchors .iter() - .zip(old_ids) - .filter(|(anchor, _)| !live.contains(anchor)) - .map(|(_, id)| *id) - .collect(); - - (new_ids, retired) + .copied() + .filter(|anchor| !live.contains(anchor)) + .collect() } -/// A structure table with a fixed length -pub struct FixedStructureTable +/// Host-side free-list allocator for structure-table slots. +/// +/// Slots are fixed-size, so a freed slot is always reusable and a free list is +/// all that is needed. A slot index is stable for the lifetime of an allocation, +/// which is what makes it safe to store in a TLAS or any other long-lived handle. +/// +/// The GPU does not know about this allocator. Liveness is expressed on the GPU +/// by the slot pointer being empty ([`CachePointer::new(None)`]). A released slot +/// keeps its stale anchor on the GPU until it is reused; the empty pointer keeps +/// the tracer from ever treating it as live. +#[allow(dead_code)] +struct SlotAllocator +{ + /// Slot-indexed liveness. `None` means the slot is free. + slot_anchors: Vec>, + + /// O(1) anchor -> slot lookup. + anchor_slot: HashMap, + + /// Free slot indices. A LIFO stack, so recent frees are reused first. + free: Vec, + + live: usize, +} + +#[allow(dead_code)] +impl SlotAllocator +{ + fn new(capacity: usize) -> Self + { + assert!( + capacity <= u32::MAX as usize, + "structure table capacity exceeds the u32 slot index space" + ); + + Self { + slot_anchors: vec![None; capacity], + anchor_slot: HashMap::new(), + // Reversed so a fresh table allocates 0, 1, 2, ... + free: (0..capacity as u32).rev().collect(), + live: 0, + } + } + + fn allocate(&mut self, anchor: StructureAnchor) -> Option + { + // Allocating an anchor that is already live is idempotent. + if let Some(&slot) = self.anchor_slot.get(&anchor) + { + return Some(slot); + } + + let slot = self.free.pop()?; + self.slot_anchors[slot as usize] = Some(anchor); + self.anchor_slot.insert(anchor, slot); + self.live += 1; + Some(slot) + } + + fn release(&mut self, slot: u32) -> Option + { + let anchor = self.slot_anchors.get_mut(slot as usize)?.take()?; + self.anchor_slot.remove(&anchor); + self.live -= 1; + self.free.push(slot); + Some(anchor) + } + + /// Extends the slot space. Existing allocations keep their slot indices. + fn grow(&mut self, new_capacity: usize) + { + let old_capacity = self.slot_anchors.len(); + if new_capacity <= old_capacity + { + return; + } + + assert!( + new_capacity <= u32::MAX as usize, + "structure table capacity exceeds the u32 slot index space" + ); + + self.slot_anchors.resize(new_capacity, None); + // Push the new indices reversed so the lowest new slots are allocated + // first, matching the fresh-table behaviour. + self.free + .extend((old_capacity..new_capacity).rev().map(|slot| slot as u32)); + } + + fn capacity(&self) -> usize + { + self.slot_anchors.len() + } + + fn live_count(&self) -> usize + { + self.live + } + + fn is_full(&self) -> bool + { + self.free.is_empty() + } + + fn is_live(&self, slot: u32) -> bool + { + self.slot_anchors + .get(slot as usize) + .is_some_and(|anchor| anchor.is_some()) + } + + fn slot_anchor(&self, slot: u32) -> Option + { + self.slot_anchors.get(slot as usize).copied().flatten() + } + + fn slot_for_anchor(&self, anchor: &StructureAnchor) -> Option + { + self.anchor_slot.get(anchor).copied() + } +} + +/// GPU-side scaffolding shared by every structure table. +/// +/// This owns the slot-indexed pointer and anchor buffers, the request handler, +/// the insertion/invalidation pipelines, and the bind groups. It is independent +/// of how slots are assigned; [`FixedStructureTable`] and +/// [`DynamicStructureTable`] differ only in their host-side slot management. +/// +/// Fields are split into size-independent objects (bind group layouts, +/// pipelines, indirect buffer) and size-dependent ones (buffers, bind groups, +/// request handler, scratch resources). [`Self::resize`] rebuilds only the +/// latter so external pipeline layouts stay valid. +struct StructureTableCore { size: usize, - /// Contains [`CachePointer`]s to locations in the cahce + #[allow(dead_code)] + max_requests: u32, + producer_id: u32, + + // Size-independent: kept across a resize. + #[allow(dead_code)] + pointers_bind_group_layout: wgpu::BindGroupLayout, + #[allow(dead_code)] + metadata_bind_group_layout: wgpu::BindGroupLayout, + raytrace_bind_group_layout: wgpu::BindGroupLayout, + indirect_buffer: IndirectBuffer1D, + write_requests_pass: wgpu::ComputePipeline, + invalidation_pass: wgpu::ComputePipeline, + validation_pass: wgpu::ComputePipeline, + insertion_pass: wgpu::ComputePipeline, + + // Size-dependent: rebuilt by `resize`. + /// Contains [`CachePointer`]s to locations in the cache. + #[allow(dead_code)] pointers: wgpu::Buffer, pointers_bind_group: wgpu::BindGroup, common_ressources: CacheRessources<1>, @@ -124,101 +226,59 @@ pub struct FixedStructureTable /// 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, - slot_structure_ids: Vec, - next_structure_id: u32, - - /// Producer that owns the root structures stored by this table - producer_id: u32, - - // To dispatch write request passes per request count - indirect_buffer: IndirectBuffer1D, - write_requests_pass: wgpu::ComputePipeline, - invalidation_pass: wgpu::ComputePipeline, - validation_pass: wgpu::ComputePipeline, - insertion_pass: wgpu::ComputePipeline, - // Raytrace - raytrace_bind_group_layout: wgpu::BindGroupLayout, raytrace_bind_group: wgpu::BindGroup, } -impl FixedStructureTable +impl StructureTableCore { - /// 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( + fn new( device: &wgpu::Device, size: usize, max_requests: usize, producer_id: u32, + initial_anchors: &[StructureAnchor], + initial_pointers: &[CachePointer], ) -> 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, - ) -> Self - { - assert_eq!(anchors.len(), size); - assert!( - size < NO_STRUCTURE_ID as usize, - "structure id space exhausted" - ); - - let structure_ids: Vec = (0..size as u32).collect(); - let slot_structure_ids: Vec = - structure_ids.iter().copied().map(StructureId).collect(); + assert_eq!(initial_anchors.len(), size); + assert_eq!(initial_pointers.len(), size); 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), + label: Some("StructureTableCore::anchors"), + usage: wgpu::BufferUsages::STORAGE + | wgpu::BufferUsages::COPY_DST + | wgpu::BufferUsages::COPY_SRC, + contents: bytemuck::cast_slice(initial_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), + // Slot pointers are written from the host on allocate/release (and read + // back on resize), so they need COPY_DST and COPY_SRC in addition to + // being a storage buffer. + let pointers = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("StructureTableCore::pointers"), + usage: wgpu::BufferUsages::STORAGE + | wgpu::BufferUsages::COPY_DST + | wgpu::BufferUsages::COPY_SRC, + contents: bytemuck::cast_slice(initial_pointers), }); let (metadata_bind_group_layout, metadata_bind_group) = create_multi_buffers_bg_bg_layout( device, - &[&anchors_buffer, &structure_ids_buffer], - Some("FixedStructureTable::metadata"), + &[&anchors_buffer], + Some("StructureTableCore::metadata"), ); - let pointer = CachePointer::new(Some(None)); - let pointers = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("FixedStructureTable::pointers"), - usage: wgpu::BufferUsages::STORAGE, - contents: bytemuck::cast_slice(&vec![pointer; size]), - }); + let (pointers_bind_group_layout, pointers_bind_group) = create_multi_buffers_bg_bg_layout( + device, + &[&pointers], + Some("StructureTableCore::pointers"), + ); - let mut memory_profile = MemoryProfile::new("FixedStructureTable"); + let mut memory_profile = MemoryProfile::new("StructureTableCore"); let mut mem_device = memory_profile.begin(device); let request_handler = CacheRequestHandler::<1>::new( @@ -231,12 +291,6 @@ impl FixedStructureTable drop(mem_device); drop(memory_profile); - let (pointers_bind_group_layout, pointers_bind_group) = create_multi_buffers_bg_bg_layout( - device, - &[&pointers], - Some("FixedStructureTable::pointers"), - ); - // Write requests let write_requests_bindings = [ Some(&CacheRequestHandler::<1>::create_bind_group_layout(device)), @@ -246,7 +300,7 @@ impl FixedStructureTable let write_requests_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("FixedStructureTable::pipeline_layout"), + label: Some("StructureTableCore::write_requests_pipeline_layout"), bind_group_layouts: &write_requests_bindings, immediate_size: size_of::() as u32, }); @@ -257,7 +311,7 @@ impl FixedStructureTable let write_requests_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("FixedStructureTable::write_requests_pass"), + label: Some("StructureTableCore::write_requests_pass"), layout: Some(&write_requests_pipeline_layout), module: &write_requests_shader_module, entry_point: Some("write_requests"), @@ -273,7 +327,7 @@ impl FixedStructureTable let invalidation_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("FixedStructureTable::invalidation_pipeline_layout"), + label: Some("StructureTableCore::invalidation_pipeline_layout"), bind_group_layouts: &invalidation_bindings, immediate_size: size_of::() as u32, }); @@ -283,7 +337,7 @@ impl FixedStructureTable )); let invalidation_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("FixedStructureTable::invalidation_pass"), + label: Some("StructureTableCore::invalidation_pass"), layout: Some(&invalidation_pipeline_layout), module: &invalidation_shader_module, entry_point: Some("invalidation"), @@ -294,7 +348,7 @@ impl FixedStructureTable let (raytrace_bind_group_layout, raytrace_bind_group) = create_multi_buffers_bg_bg_layout( device, &[&pointers, request_handler.request_pages_buffer()], - Some("FixedStructureTable::raytrace_bind_group"), + Some("StructureTableCore::raytrace_bind_group"), ); // Insertion @@ -308,7 +362,7 @@ impl FixedStructureTable let insertion_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("FixedStructureTable::insertion_pipeline_layout"), + label: Some("StructureTableCore::insertion_pipeline_layout"), bind_group_layouts: &insertion_bindings, immediate_size: 0, }); @@ -317,7 +371,7 @@ impl FixedStructureTable .create_shader_module(include_table_wgsl!("./shaders/fixed_table/insertion.wgsl")); let insertion_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("FixedStructureTable::insertion_pass"), + label: Some("StructureTableCore::insertion_pass"), layout: Some(&insertion_pipeline_layout), module: &insertion_shader_module, entry_point: Some("insertion"), @@ -330,7 +384,7 @@ impl FixedStructureTable )); let validation_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("FixedStructureTable::validation_pass"), + label: Some("StructureTableCore::validation_pass"), layout: Some(&insertion_pipeline_layout), module: &validation_shader_module, entry_point: Some("validate_external"), @@ -340,111 +394,150 @@ impl FixedStructureTable Self { size, - pointers, - 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, + max_requests: max_requests as u32, producer_id, + pointers_bind_group_layout, + metadata_bind_group_layout, + raytrace_bind_group_layout, indirect_buffer: IndirectBuffer1D::new(device), write_requests_pass, invalidation_pass, validation_pass, insertion_pass, - + pointers, + pointers_bind_group, + common_ressources, + request_handler, + anchors: anchors_buffer, + metadata_bind_group, raytrace_bind_group, - raytrace_bind_group_layout, } } - /// Changes the anchor of every slot while preserving structure ids for - /// anchors that remain present. + /// Grows the slot-indexed GPU state, preserving the existing slots. /// - /// 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, Vec) + /// The pointer and anchor buffers are copied into larger buffers before the + /// old ones are dropped. The new tail is zeroed explicitly so new free slots + /// can never look available to the tracer. + /// + /// Bind groups are recreated with the existing layouts, so pipelines built + /// outside this type remain compatible. Any bind group obtained before the + /// resize must be re-fetched. + #[allow(dead_code)] + fn resize(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, new_size: usize) { - assert_eq!(new_anchors.len(), self.size); + if new_size <= self.size + { + return; + } - let (new_ids, retired) = plan_slot_reassignment( - &self.slot_anchors, - &self.slot_structure_ids, - new_anchors, - &mut self.next_structure_id, + let old_size = self.size; + + let pointers = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("StructureTableCore::pointers"), + size: new_size as u64 * size_of::() as u64, + usage: wgpu::BufferUsages::STORAGE + | wgpu::BufferUsages::COPY_DST + | wgpu::BufferUsages::COPY_SRC, + mapped_at_creation: false, + }); + + let anchors = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("StructureTableCore::anchors"), + size: new_size as u64 * size_of::() as u64, + usage: wgpu::BufferUsages::STORAGE + | wgpu::BufferUsages::COPY_DST + | wgpu::BufferUsages::COPY_SRC, + mapped_at_creation: false, + }); + + { + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("StructureTableCore::resize"), + }); + + encoder.clear_buffer(&pointers, 0, None); + encoder.clear_buffer(&anchors, 0, None); + encoder.copy_buffer_to_buffer( + &self.pointers, + 0, + &pointers, + 0, + old_size as u64 * size_of::() as u64, + ); + encoder.copy_buffer_to_buffer( + &self.anchors, + 0, + &anchors, + 0, + old_size as u64 * size_of::() as u64, + ); + + queue.submit([encoder.finish()]); + } + + let mut memory_profile = MemoryProfile::new("StructureTableCore::resize"); + let mut mem_device = memory_profile.begin(device); + + let request_handler = CacheRequestHandler::<1>::new( + &mut mem_device.group("CacheRequestHandler"), + new_size, + self.max_requests, + ); + let common_ressources = + CacheRessources::new(&mut mem_device.group("CacheRessources"), new_size); + drop(mem_device); + drop(memory_profile); + + let pointers_bind_group = create_multi_buffers_bind_group( + device, + &self.pointers_bind_group_layout, + &[&pointers], + Some("StructureTableCore::pointers"), + ); + let metadata_bind_group = create_multi_buffers_bind_group( + device, + &self.metadata_bind_group_layout, + &[&anchors], + Some("StructureTableCore::metadata"), + ); + let raytrace_bind_group = create_multi_buffers_bind_group( + device, + &self.raytrace_bind_group_layout, + &[&pointers, request_handler.request_pages_buffer()], + Some("StructureTableCore::raytrace_bind_group"), ); - 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::()) as u64, - bytemuck::bytes_of(&anchor), - ); - queue.write_buffer( - &self.structure_ids, - (slot * size_of::()) as u64, - bytemuck::bytes_of(&structure.0), - ); - - assignments.push(SlotAssignment { - slot: slot as u32, - previous_anchor, - previous_structure, - anchor, - structure, - }); - } - - (assignments, retired) + self.size = new_size; + self.pointers = pointers; + self.pointers_bind_group = pointers_bind_group; + self.request_handler = request_handler; + self.common_ressources = common_ressources; + self.anchors = anchors; + self.metadata_bind_group = metadata_bind_group; + self.raytrace_bind_group = raytrace_bind_group; } - /// 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 + fn write_anchor(&self, queue: &wgpu::Queue, slot: u32, anchor: StructureAnchor) { - self.slot_anchors - .iter() - .position(|candidate| candidate == anchor) - .map(|slot| slot as u32) + queue.write_buffer( + &self.anchors, + slot as u64 * size_of::() as u64, + bytemuck::bytes_of(&anchor), + ); } #[allow(dead_code)] - pub fn slot_anchor(&self, slot: u32) -> Option + fn write_pointer(&self, queue: &wgpu::Queue, slot: u32, pointer: CachePointer) { - self.slot_anchors.get(slot as usize).copied() + queue.write_buffer( + &self.pointers, + slot as u64 * size_of::() as u64, + bytemuck::bytes_of(&pointer), + ); } - #[allow(dead_code)] - pub fn slot_structure_id(&self, slot: u32) -> Option - { - self.slot_structure_ids.get(slot as usize).copied() - } - - pub fn gather_requests( + fn gather_requests( &self, device: &wgpu::Device, encoder: &mut ScopeEncoder, @@ -478,7 +571,7 @@ impl FixedStructureTable { let mut write_requests_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { - label: Some("FixedStructureTable::write_requests_pass"), + label: Some("StructureTableCore::write_requests_pass"), timestamp_writes: None, }); @@ -493,12 +586,12 @@ impl FixedStructureTable self.request_handler.reset(encoder); } - /// After requests emited by this table, the user creates a [`CacheInsertionData`] struct that + /// After requests emitted by this table, the user creates a [`CacheInsertionData`] struct that /// populates the cache. After the cache insertion operation, said [`CacheInsertionData`] /// contains location of written pages in the cache. /// This function takes this information and populates the structure so that it points into the /// cache - pub fn insert( + fn insert( &self, device: &wgpu::Device, encoder: &mut ScopeEncoder, @@ -515,7 +608,7 @@ impl FixedStructureTable { let mut insertion_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { - label: Some("FixedStructureTable::insertion_pass"), + label: Some("StructureTableCore::insertion_pass"), timestamp_writes: None, }); @@ -528,27 +621,443 @@ impl FixedStructureTable } } - pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout + fn validate_insertion( + &self, + device: &wgpu::Device, + encoder: &mut ScopeEncoder, + insertion: &CacheInsertionData, + ) where + [(); N * N * N]:, + { + let workgroup_count_buffer = self.indirect_buffer.workgroup_count( + device, + encoder, + insertion.page_count_buffer(), + 256, + ); + + let mut validate_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("StructureTableCore::validate_pass"), + timestamp_writes: None, + }); + + 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); + } + + fn invalidate( + &self, + encoder: &mut ScopeEncoder, + cache_evictor: &CacheEvictor, + invalid_timestamp: u32, + ) + { + let mut invalidate_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("StructureTableCore::invalidate_pass"), + timestamp_writes: None, + }); + + invalidate_pass.set_bind_group(0, &self.pointers_bind_group, &[]); + invalidate_pass.set_bind_group(1, cache_evictor.bind_group(), &[]); + + invalidate_pass.set_pipeline(&self.invalidation_pass); + invalidate_pass.set_immediates(0, bytemuck::bytes_of(&invalid_timestamp)); + invalidate_pass.dispatch_workgroups(self.size.div_ceil(256) as u32, 1, 1); + } + + fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout { &self.raytrace_bind_group_layout } - pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup + fn raytrace_bind_group(&self) -> &wgpu::BindGroup { &self.raytrace_bind_group } - pub fn pointers_buffer(&self) -> &wgpu::Buffer + #[allow(dead_code)] + fn pointers_buffer(&self) -> &wgpu::Buffer { &self.pointers } - pub fn pointers_bind_group(&self) -> &wgpu::BindGroup + fn request_pages_buffer(&self) -> &wgpu::Buffer + { + self.request_handler.request_pages_buffer() + } + + fn pointers_bind_group(&self) -> &wgpu::BindGroup { &self.pointers_bind_group } } +/// A structure table with a fixed length. +/// +/// Every slot is live and is kept in sync with [`Self::reassign_slots`]. +pub struct FixedStructureTable +{ + core: StructureTableCore, + + /// Host mirror used to preserve identity across slot moves. + slot_anchors: Vec, +} + +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, + max_requests: usize, + 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. + pub fn new_with_anchors( + device: &wgpu::Device, + size: usize, + max_requests: usize, + producer_id: u32, + anchors: Vec, + ) -> Self + { + assert_eq!(anchors.len(), size); + + let pointers = vec![CachePointer::new(Some(None)); size]; + let core = StructureTableCore::new( + device, size, max_requests, producer_id, &anchors, &pointers, + ); + + Self { + core, + slot_anchors: anchors, + } + } + + /// Changes the anchor of every slot. + /// + /// Returns the anchors that are no longer present. Retired anchors are + /// suitable for cancelling speculative queue work; the anchor is the + /// structure identity, so an anchor that stays in view keeps it regardless + /// of which slot it occupies. + pub fn reassign_slots( + &mut self, + queue: &wgpu::Queue, + new_anchors: &[StructureAnchor], + ) -> Vec + { + assert_eq!(new_anchors.len(), self.core.size); + + let retired = retired_anchors(&self.slot_anchors, new_anchors); + + for slot in 0..self.core.size + { + let anchor = new_anchors[slot]; + if self.slot_anchors[slot] == anchor + { + continue; + } + + self.slot_anchors[slot] = anchor; + self.core.write_anchor(queue, slot as u32, anchor); + } + + 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 + { + self.slot_anchors + .iter() + .position(|candidate| candidate == anchor) + .map(|slot| slot as u32) + } + + #[allow(dead_code)] + pub fn slot_anchor(&self, slot: u32) -> Option + { + self.slot_anchors.get(slot as usize).copied() + } + + pub fn gather_requests( + &self, + device: &wgpu::Device, + encoder: &mut ScopeEncoder, + request_buffer: &CacheRequestBuffer, + ) + { + self.core.gather_requests(device, encoder, request_buffer); + } + + /// See [`StructureTableCore::insert`]. + pub fn insert( + &self, + device: &wgpu::Device, + encoder: &mut ScopeEncoder, + insertion: &CacheInsertionData, + ) where + [(); N * N * N]:, + { + self.core.insert(device, encoder, insertion); + } + + pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout + { + self.core.raytrace_bind_group_layout() + } + + pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup + { + self.core.raytrace_bind_group() + } + + #[allow(dead_code)] + pub fn pointers_buffer(&self) -> &wgpu::Buffer + { + self.core.pointers_buffer() + } + + pub fn pointers_bind_group(&self) -> &wgpu::BindGroup + { + self.core.pointers_bind_group() + } +} + +/// A structure table whose slots are allocated and released at runtime. +/// +/// Slots are handed out by a host-side free list. A slot index is stable for the +/// whole lifetime of an allocation, so it is safe to store it in a TLAS or any +/// other long-lived handle. Released slots are reused; the caller is responsible +/// for not reusing a slot while a GPU structure (for example a TLAS) still +/// references it. +/// +/// The table starts with `capacity` slots and can grow. Growth rebuilds the +/// size-dependent GPU resources, so it must happen between frames; any bind +/// group obtained from the table before growth must be re-fetched. +#[allow(dead_code)] +pub struct DynamicStructureTable +{ + core: StructureTableCore, + allocator: SlotAllocator, +} + +#[allow(dead_code)] +impl DynamicStructureTable +{ + /// Creates a table with `capacity` free slots. + pub fn new( + device: &wgpu::Device, + capacity: usize, + max_requests: usize, + producer_id: u32, + ) -> Self + { + // Free slots keep a stale (here zero) anchor; only the empty pointer is + // meaningful for liveness. + let anchors = vec![StructureAnchor::ZERO; capacity]; + let pointers = vec![CachePointer::new(None); capacity]; + let core = StructureTableCore::new( + device, capacity, max_requests, producer_id, &anchors, &pointers, + ); + + Self { + core, + allocator: SlotAllocator::new(capacity), + } + } + + /// Allocates a slot for `anchor` and returns its stable index. + /// + /// Returns `None` if the table is full. Allocating an anchor that is already + /// live returns its existing slot. The slot is marked subdivisible but not + /// available, so the cache emits a root request for it. + pub fn allocate(&mut self, queue: &wgpu::Queue, anchor: StructureAnchor) -> Option + { + let slot = self.allocator.allocate(anchor)?; + + self.core.write_anchor(queue, slot, anchor); + self.core + .write_pointer(queue, slot, CachePointer::new(Some(None))); + + Some(slot) + } + + /// Releases the slot, returning the anchor that was stored in it. + /// + /// The slot pointer is cleared so the tracer skips it. The stale anchor is + /// left on the GPU until the slot is reused. The returned anchor can be fed + /// to the request queue to cancel speculative work; correctness does not + /// depend on it because insertions re-validate anchor and pointer. + /// + /// This does not free cache pages: the root becomes unreachable and its + /// pages are reclaimed by the normal LRU eviction. + pub fn release(&mut self, queue: &wgpu::Queue, slot: u32) -> Option + { + let anchor = self.allocator.release(slot)?; + self.core + .write_pointer(queue, slot, CachePointer::new(None)); + Some(anchor) + } + + /// Ensures the table can hold at least `min_capacity` slots. + /// + /// Capacity doubles from the current value until it reaches `min_capacity`. + /// Must be called between frames. + pub fn reserve( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + min_capacity: usize, + ) + { + assert!( + min_capacity <= u32::MAX as usize, + "structure table capacity exceeds the u32 slot index space" + ); + + let new_capacity = self.grown_capacity(min_capacity); + if new_capacity <= self.capacity() + { + return; + } + + self.core.resize(device, queue, new_capacity); + self.allocator.grow(new_capacity); + } + + /// Doubles the table capacity. Must be called between frames. + pub fn grow(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) + { + let max = u32::MAX as usize; + let min_capacity = self.capacity().saturating_mul(2).min(max).max(1); + self.reserve(device, queue, min_capacity); + } + + /// Allocates a slot, growing the table if it is full. + pub fn allocate_or_grow( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + anchor: StructureAnchor, + ) -> Option + { + if let Some(slot) = self.allocator.slot_for_anchor(&anchor) + { + return Some(slot); + } + + if self.allocator.is_full() + { + self.grow(device, queue); + } + + self.allocate(queue, anchor) + } + + fn grown_capacity(&self, min_capacity: usize) -> usize + { + let max = u32::MAX as usize; + let mut capacity = self.capacity().max(1); + while capacity < min_capacity + { + capacity = capacity.saturating_mul(2).min(max); + } + capacity + } + + pub fn capacity(&self) -> usize + { + self.allocator.capacity() + } + + pub fn live_count(&self) -> usize + { + self.allocator.live_count() + } + + pub fn is_live(&self, slot: u32) -> bool + { + self.allocator.is_live(slot) + } + + pub fn slot_anchor(&self, slot: u32) -> Option + { + self.allocator.slot_anchor(slot) + } + + pub fn slot_for_anchor(&self, anchor: &StructureAnchor) -> Option + { + self.allocator.slot_for_anchor(anchor) + } + + pub fn gather_requests( + &self, + device: &wgpu::Device, + encoder: &mut ScopeEncoder, + request_buffer: &CacheRequestBuffer, + ) + { + self.core.gather_requests(device, encoder, request_buffer); + } + + /// See [`StructureTableCore::insert`]. + pub fn insert( + &self, + device: &wgpu::Device, + encoder: &mut ScopeEncoder, + insertion: &CacheInsertionData, + ) where + [(); N * N * N]:, + { + self.core.insert(device, encoder, insertion); + } + + pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout + { + self.core.raytrace_bind_group_layout() + } + + pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup + { + self.core.raytrace_bind_group() + } + + #[allow(dead_code)] + pub fn pointers_buffer(&self) -> &wgpu::Buffer + { + self.core.pointers_buffer() + } + + pub fn request_pages_buffer(&self) -> &wgpu::Buffer + { + self.core.request_pages_buffer() + } + + pub fn pointers_bind_group(&self) -> &wgpu::BindGroup + { + self.core.pointers_bind_group() + } +} + #[cfg(test)] mod tests { @@ -560,59 +1069,125 @@ mod tests } #[test] - fn permuted_anchors_keep_their_ids() + fn permuted_anchors_retire_nothing() { 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); + let retired = retired_anchors(&old_anchors, &new_anchors); - 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() + fn 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); + let retired = retired_anchors(&old_anchors, &new_anchors); - assert_eq!(ids, vec![StructureId(11), StructureId(12)]); - assert_eq!(retired, vec![StructureId(10)]); - assert_eq!(next, 13); + assert_eq!(retired, vec![anchor(0)]); } #[test] - fn ids_are_never_reused_across_round_trips() + fn reentering_anchor_is_the_same_identity() { - let mut next = 1; - let mut anchors = [anchor(0)]; - let mut ids = [StructureId(0)]; + let first = retired_anchors(&[anchor(0)], &[anchor(5)]); + assert_eq!(first, vec![anchor(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); + let second = retired_anchors(&[anchor(5)], &[anchor(0)]); + assert_eq!(second, vec![anchor(5)]); } #[test] - #[should_panic(expected = "structure id space exhausted")] - fn allocator_exhaustion_is_fatal() + #[should_panic(expected = "a structure table must not expose two live slots")] + fn duplicate_live_anchors_are_rejected() { - let mut next = NO_STRUCTURE_ID; - let _ = plan_slot_reassignment(&[], &[], &[anchor(0)], &mut next); + let _ = retired_anchors(&[], &[anchor(0), anchor(0)]); + } + + #[test] + fn allocator_allocates_low_indices_first() + { + let mut allocator = SlotAllocator::new(4); + + assert_eq!(allocator.allocate(anchor(0)), Some(0)); + assert_eq!(allocator.allocate(anchor(1)), Some(1)); + assert_eq!(allocator.allocate(anchor(2)), Some(2)); + assert_eq!(allocator.allocate(anchor(3)), Some(3)); + assert_eq!(allocator.allocate(anchor(4)), None); + } + + #[test] + fn allocator_reuses_released_slots() + { + let mut allocator = SlotAllocator::new(2); + let a = allocator.allocate(anchor(0)).unwrap(); + let b = allocator.allocate(anchor(1)).unwrap(); + + assert_eq!(allocator.release(a), Some(anchor(0))); + assert_eq!(allocator.release(b), Some(anchor(1))); + + // LIFO: the most recently released slot is reused first. + assert_eq!(allocator.allocate(anchor(2)), Some(b)); + assert_eq!(allocator.allocate(anchor(3)), Some(a)); + } + + #[test] + fn allocator_is_idempotent_for_live_anchors() + { + let mut allocator = SlotAllocator::new(2); + let slot = allocator.allocate(anchor(0)).unwrap(); + + assert_eq!(allocator.allocate(anchor(0)), Some(slot)); + assert_eq!(allocator.live_count(), 1); + } + + #[test] + fn allocator_release_unknown_slot_is_none() + { + let mut allocator = SlotAllocator::new(2); + + assert_eq!(allocator.release(0), None); + assert_eq!(allocator.release(99), None); + } + + #[test] + fn allocator_tracks_liveness() + { + let mut allocator = SlotAllocator::new(2); + let slot = allocator.allocate(anchor(0)).unwrap(); + + assert!(allocator.is_live(slot)); + assert_eq!(allocator.slot_anchor(slot), Some(anchor(0))); + assert_eq!(allocator.slot_for_anchor(&anchor(0)), Some(slot)); + + allocator.release(slot); + + assert!(!allocator.is_live(slot)); + assert_eq!(allocator.slot_anchor(slot), None); + assert_eq!(allocator.slot_for_anchor(&anchor(0)), None); + } + + #[test] + fn allocator_grow_preserves_live_slots() + { + let mut allocator = SlotAllocator::new(2); + let a = allocator.allocate(anchor(0)).unwrap(); + let b = allocator.allocate(anchor(1)).unwrap(); + + allocator.grow(4); + + assert_eq!(allocator.capacity(), 4); + assert_eq!(allocator.live_count(), 2); + assert_eq!(allocator.slot_anchor(a), Some(anchor(0))); + assert_eq!(allocator.slot_anchor(b), Some(anchor(1))); + + // New slots are handed out in ascending order. + assert_eq!(allocator.allocate(anchor(2)), Some(2)); + assert_eq!(allocator.allocate(anchor(3)), Some(3)); + assert_eq!(allocator.allocate(anchor(4)), None); } } @@ -626,24 +1201,7 @@ where encoder: &mut ScopeEncoder, insertion: &CacheInsertionData, ) { - let workgroup_count_buffer = self.indirect_buffer.workgroup_count( - device, - encoder, - insertion.page_count_buffer(), - 256, - ); - - let mut validate_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { - label: Some("FixedStructureTable::validate_pass"), - timestamp_writes: None, - }); - - 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); + self.core.validate_insertion(device, encoder, insertion); } fn invalidate( @@ -653,16 +1211,30 @@ where invalid_timestamp: u32, ) { - let mut invalidate_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { - label: Some("FixedStructureTable::invalidate_pass"), - timestamp_writes: None, - }); + self.core.invalidate(encoder, cache_evictor, invalid_timestamp); + } +} - invalidate_pass.set_bind_group(0, &self.pointers_bind_group, &[]); - invalidate_pass.set_bind_group(1, cache_evictor.bind_group(), &[]); +impl CacheInvalidable for DynamicStructureTable +where + [(); N * N * N]:, +{ + fn validate_insertion( + &mut self, + device: &wgpu::Device, + encoder: &mut ScopeEncoder, + insertion: &CacheInsertionData, + ) { + self.core.validate_insertion(device, encoder, insertion); + } - invalidate_pass.set_pipeline(&self.invalidation_pass); - invalidate_pass.set_immediates(0, bytemuck::bytes_of(&invalid_timestamp)); - invalidate_pass.dispatch_workgroups(self.size.div_ceil(256) as u32, 1, 1); + fn invalidate( + &mut self, + encoder: &mut ScopeEncoder, + cache_evictor: &CacheEvictor, + invalid_timestamp: u32, + ) + { + self.core.invalidate(encoder, cache_evictor, invalid_timestamp); } }