Compare commits
2
Commits
7e4fdf3f4e
...
27f660f6fb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
27f660f6fb | ||
|
|
c31f3a9bc3 |
@@ -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) |
|
||||
|
||||
+1
-1
@@ -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"
|
||||
|
||||
@@ -113,8 +113,8 @@ flowchart LR
|
||||
|
||||
Req --> Gather[gather_requests<br/>top-K + radix sort]
|
||||
TReq --> TGather[table gather_requests]
|
||||
Gather --> RBuffer[(Request buffer<br/>structure_id, anchor, node_id, child)]
|
||||
TGather --> TRBuffer[(Table request buffer<br/>structure_id, anchor, slot)]
|
||||
Gather --> RBuffer[(Request buffer<br/>anchor, node_id, child)]
|
||||
TGather --> TRBuffer[(Table request buffer<br/>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.
|
||||
|
||||
---
|
||||
|
||||
@@ -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<N> {
|
||||
}
|
||||
|
||||
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<const N: usize> {
|
||||
fn produce(
|
||||
&self,
|
||||
producer_id: ProducerId,
|
||||
id: StructureId,
|
||||
anchor: StructureAnchor,
|
||||
locator: StructureLocator,
|
||||
) -> (InsertionInformation<N>, [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.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+4
-5
@@ -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. |
|
||||
|
||||
|
||||
+67
-34
@@ -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<const N: usize> {
|
||||
```
|
||||
|
||||
`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<u32>`
|
||||
pops a slot and installs the anchor; `release(queue, slot) -> Option<StructureAnchor>`
|
||||
clears the pointer and pushes the slot back. Allocating an already-live anchor
|
||||
is idempotent and returns its existing slot. `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
|
||||
|
||||
+1
-4
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
+406
@@ -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<BvhHandle, BvhObject>,
|
||||
|
||||
/// Objects alive in the bvh have a slot in the dynamic table
|
||||
slots: HashMap<BvhHandle, u32>,
|
||||
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::<GpuBvhNode>(device, 1, "bvh_nodes");
|
||||
let bvh_objects = create_bvh_buffer::<GpuObject>(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<GpuBvhNode>, Vec<GpuObject>)
|
||||
{
|
||||
// Collect primitives
|
||||
let mut primitives = self
|
||||
.objects
|
||||
.iter()
|
||||
.map(|(handle, object)| BvhPrimitive {
|
||||
aabb: object.world_bounding_box(),
|
||||
handle: *handle,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let bvh = build_bvh(&mut primitives, 2);
|
||||
|
||||
// Build gpu bvh
|
||||
let gpu_nodes = bvh
|
||||
.nodes
|
||||
.iter()
|
||||
.map(|node| (*node).into())
|
||||
.collect::<Vec<GpuBvhNode>>();
|
||||
|
||||
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::<Vec<_>>();
|
||||
(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::<GpuBvhNode>(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::<GpuObject>(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<T>(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::<T>()) 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(),
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
+468
@@ -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<Item = Vec3>) -> 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<Item = Vec3>
|
||||
{
|
||||
(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::<Aabb>(), 24);
|
||||
assert_eq!(bytemuck::bytes_of(&Aabb::EMPTY).len(), 24);
|
||||
}
|
||||
}
|
||||
@@ -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<GpuBvhNode> for BvhNode
|
||||
{
|
||||
fn from(value: GpuBvhNode) -> Self
|
||||
{
|
||||
Self {
|
||||
aabb: value.aabb.into(),
|
||||
count: value.count,
|
||||
first_or_left: value.first_or_left,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<BvhNode> 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<u32>, 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<u32>
|
||||
{
|
||||
if !self.is_leaf()
|
||||
{
|
||||
None
|
||||
}
|
||||
else
|
||||
{
|
||||
Some(self.first_or_left)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn count(&self) -> Option<u32>
|
||||
{
|
||||
if !self.is_leaf()
|
||||
{
|
||||
None
|
||||
}
|
||||
else
|
||||
{
|
||||
Some(self.count)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn left(&self) -> Option<u32>
|
||||
{
|
||||
if !self.is_internal()
|
||||
{
|
||||
None
|
||||
}
|
||||
else
|
||||
{
|
||||
Some(self.first_or_left)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn right(&self) -> Option<u32>
|
||||
{
|
||||
self.left().map(|x| x + 1)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BvhPrimitive<T>
|
||||
{
|
||||
pub aabb: Aabb,
|
||||
pub handle: T,
|
||||
}
|
||||
|
||||
pub struct Bvh
|
||||
{
|
||||
/// List of the bvh's nodes
|
||||
pub nodes: Vec<BvhNode>,
|
||||
}
|
||||
|
||||
pub fn build_bvh<T>(primitives: &mut [BvhPrimitive<T>], 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<T>(
|
||||
node_index: usize,
|
||||
primitives: &mut [BvhPrimitive<T>],
|
||||
nodes: &mut Vec<BvhNode>,
|
||||
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<T>(primitives: &[BvhPrimitive<T>], 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))
|
||||
}
|
||||
}
|
||||
@@ -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::<crate::bvh::gpu::GpuBvhNode>() == 40);
|
||||
assert!(size_of::<crate::bvh::gpu::GpuObject>() == 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::<Mat4>() 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::<Mat4>() 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);
|
||||
}
|
||||
}
|
||||
@@ -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<f32>,
|
||||
world_to_local: mat4x4<f32>,
|
||||
table_slot: u32,
|
||||
_pad0: u32,
|
||||
_pad1: u32,
|
||||
_pad2: u32,
|
||||
};
|
||||
|
||||
@group(0) @binding(0) var<storage, read> nodes: array<GpuBvhNode>;
|
||||
@group(0) @binding(1) var<storage, read> objects: array<GpuObject>;
|
||||
@group(0) @binding(2) var<uniform> view_proj: mat4x4<f32>;
|
||||
|
||||
struct VertexOutput
|
||||
{
|
||||
@builtin(position) clip_position: vec4<f32>,
|
||||
@location(0) color: vec3<f32>,
|
||||
@location(1) normal: vec3<f32>,
|
||||
};
|
||||
|
||||
const INTERNAL_NODE_COLOR = vec3<f32>(0.15, 0.70, 1.0);
|
||||
const LEAF_NODE_COLOR = vec3<f32>(1.0, 0.85, 0.20);
|
||||
const OBJECT_COLOR = vec3<f32>(1.0, 0.45, 0.12);
|
||||
|
||||
// Pushed fully outside the clip volume so skipped nodes/objects produce no
|
||||
// fragments.
|
||||
const DEGENERATE_POSITION = vec4<f32>(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<u32, 24>(
|
||||
// -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<u32, 36>(
|
||||
// -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<vec3<f32>, 6>(
|
||||
vec3<f32>(0.0, 0.0, -1.0),
|
||||
vec3<f32>(0.0, 0.0, 1.0),
|
||||
vec3<f32>(0.0, -1.0, 0.0),
|
||||
vec3<f32>(0.0, 1.0, 0.0),
|
||||
vec3<f32>(-1.0, 0.0, 0.0),
|
||||
vec3<f32>(1.0, 0.0, 0.0),
|
||||
);
|
||||
|
||||
fn corner_position(min_corner: vec3<f32>, max_corner: vec3<f32>, corner: u32) -> vec3<f32>
|
||||
{
|
||||
return vec3<f32>(
|
||||
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<f32>(0.0, 0.0, 1.0);
|
||||
|
||||
if instance_index >= arrayLength(&nodes)
|
||||
{
|
||||
return out;
|
||||
}
|
||||
|
||||
let node = nodes[instance_index];
|
||||
let min_corner = vec3<f32>(node.min_x, node.min_y, node.min_z);
|
||||
let max_corner = vec3<f32>(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<f32>(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<f32>(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<f32>(0.0, 0.0, 0.0),
|
||||
vec3<f32>(1.0, 1.0, 1.0),
|
||||
TRIANGLE_CORNERS[local_vertex_index],
|
||||
);
|
||||
let world_position = object.local_to_world * vec4<f32>(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<f32>(FACE_NORMALS[face], 0.0)).xyz,
|
||||
);
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_lines(input: VertexOutput) -> @location(0) vec4<f32>
|
||||
{
|
||||
return vec4<f32>(input.color, 1.0);
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_solids(input: VertexOutput) -> @location(0) vec4<f32>
|
||||
{
|
||||
let normal = normalize(input.normal);
|
||||
let light_direction = normalize(vec3<f32>(0.45, 0.80, 0.55));
|
||||
let diffuse = max(dot(normal, light_direction), 0.0);
|
||||
|
||||
return vec4<f32>(input.color * (0.35 + 0.65 * diffuse), 1.0);
|
||||
}
|
||||
@@ -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<Aabb> for GpuAabb
|
||||
{
|
||||
fn from(value: Aabb) -> Self
|
||||
{
|
||||
Self::new(value.min(), value.max())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<GpuAabb> 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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
+224
-25
@@ -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<Mutex<ToroidalStructureTable>>,
|
||||
structure_table_request_buffer: Arc<CacheRequestBuffer>,
|
||||
structure_table_cache_insertion: Arc<CacheInsertionData<4>>,
|
||||
instance_buffer: Buffer,
|
||||
instance_count: usize,
|
||||
usage_vec: Arc<Mutex<Vec<usize>>>,
|
||||
rm_time: Arc<Mutex<f32>>,
|
||||
frame_time: Arc<Mutex<f32>>,
|
||||
@@ -153,6 +169,9 @@ struct State
|
||||
|
||||
// Producers workers
|
||||
wakeup: Sender<()>,
|
||||
|
||||
bvh: BvhStructureTable,
|
||||
bvh_debug: BvhDebugPipeline,
|
||||
}
|
||||
|
||||
pub unsafe fn as_raw_bytes<T: Sized>(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<const N: usize>(
|
||||
tree: &NTree<N>,
|
||||
request: &RequestKey,
|
||||
) -> (
|
||||
[u32; N * N * N],
|
||||
[[f32; 3]; N * N * N],
|
||||
InsertionInformation<N>,
|
||||
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::<N>::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::<N>::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<N> = 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<const N: usize>(
|
||||
generator: &dyn ChunkedProducer<N>,
|
||||
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::<N>::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,
|
||||
)
|
||||
}
|
||||
*/
|
||||
|
||||
+4
-13
@@ -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<N>;
|
||||
|
||||
/// A pure function that can produce a voxel node based on the owner produer id, requesting structure, and the
|
||||
/// requesting location within the structure.
|
||||
/// 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<N>, [Self::Output; N * N * N]);
|
||||
|
||||
@@ -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),
|
||||
);
|
||||
|
||||
+49
-130
@@ -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<T>
|
||||
{
|
||||
pub key: RequestKey,
|
||||
pub meta: RequestMeta,
|
||||
pub table_slot: u32,
|
||||
pub payload: T,
|
||||
}
|
||||
|
||||
@@ -250,15 +224,11 @@ impl<T> ReadyItem<T>
|
||||
{
|
||||
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<T> ReadyItem<T>
|
||||
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<T>
|
||||
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<T>,
|
||||
@@ -480,7 +443,6 @@ impl<T> RequestQueue<T>
|
||||
|
||||
job.priority = request.priority;
|
||||
job.meta = request.meta;
|
||||
job.table_slot = request.table_slot;
|
||||
job.last_seen = frame;
|
||||
|
||||
match job.state
|
||||
@@ -537,7 +499,6 @@ impl<T> RequestQueue<T>
|
||||
first_seen: frame,
|
||||
last_seen: frame,
|
||||
meta: request.meta,
|
||||
table_slot: request.table_slot,
|
||||
generation,
|
||||
attempt: 0,
|
||||
payload: None,
|
||||
@@ -722,7 +683,6 @@ impl<T> RequestQueue<T>
|
||||
result.push(ReadyItem {
|
||||
key: job.key,
|
||||
meta: job.meta,
|
||||
table_slot: job.table_slot,
|
||||
payload,
|
||||
});
|
||||
}
|
||||
@@ -731,16 +691,6 @@ impl<T> RequestQueue<T>
|
||||
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(
|
||||
|
||||
@@ -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<const N: usize>
|
||||
{
|
||||
x: u32,
|
||||
@@ -200,7 +200,7 @@ impl<const N: usize> TreeLocator<N>
|
||||
(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<const N: usize> TreeLocator<N>
|
||||
|
||||
(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);
|
||||
}
|
||||
}
|
||||
|
||||
+92
-165
@@ -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<const N: usize>
|
||||
{
|
||||
map: HashMap<NTreeNodeLocator<N>, NTreeNode>,
|
||||
map: HashMap<TreeLocator<N>, NTreeNode>,
|
||||
|
||||
// Depth is the parameter such that
|
||||
// N^depth == max_number_of_voxels
|
||||
@@ -54,19 +57,16 @@ pub struct NTree<const N: usize>
|
||||
pub struct NTreeIter<'a, const N: usize>
|
||||
{
|
||||
tree: &'a NTree<N>,
|
||||
dfs_stack: Vec<NTreeNodeLocator<N>>,
|
||||
dfs_stack: Vec<TreeLocator<N>>,
|
||||
}
|
||||
|
||||
#[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<const N: usize>(usize);
|
||||
|
||||
impl<const N: usize> NTree<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
@@ -78,7 +78,7 @@ where
|
||||
color,
|
||||
subdivided: false,
|
||||
};
|
||||
map.insert(NTreeNodeLocator::<N>::root(), root);
|
||||
map.insert(TreeLocator::<N>::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::<N>::root();
|
||||
let mut current_node_loc = TreeLocator::<N>::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::<N>::root();
|
||||
let mut current_node_loc = TreeLocator::<N>::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<N>, color: Color)
|
||||
fn make_constant(&mut self, locator: TreeLocator<N>, 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::<N>::new(depth, x, y, z);
|
||||
let mut locator =
|
||||
TreeLocator::<N>::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::<N>::new(depth - current_power, block_x, block_y, block_z);
|
||||
let locator = TreeLocator::<N>::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<ExplicitNTreeNode<N>>)
|
||||
pub fn get_by_loc(&self, locator: TreeLocator<N>) -> Option<NTreeNode>
|
||||
{
|
||||
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<const N: usize>(mut number: usize) -> Option<u32>
|
||||
@@ -417,117 +381,80 @@ fn base_trailing_zeroes<const N: usize>(mut number: usize) -> Option<u32>
|
||||
Some(trailing_zeroes)
|
||||
}
|
||||
|
||||
impl<const N: usize> NTreeNodeLocator<N>
|
||||
pub fn load_ply<P: AsRef<std::path::Path>, const N: usize>(path: P) -> NTree<N>
|
||||
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::<u32>().unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
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::<u32>().unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
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<Self>
|
||||
{
|
||||
// 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<Self>
|
||||
{
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
+8
-10
@@ -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<StructureId>
|
||||
) -> Vec<StructureAnchor>
|
||||
{
|
||||
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;
|
||||
|
||||
-837
@@ -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<const N: usize>
|
||||
{
|
||||
structure: HashMap<NTreeLocator<N>, NTreeNode<N>>,
|
||||
depth: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct NTreeNode<const N: usize>
|
||||
{
|
||||
color: Color,
|
||||
subdivided: bool,
|
||||
}
|
||||
|
||||
impl<const N: usize> NTree<N>
|
||||
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::<N>::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::<N>::from_depth_coords(x, y, z, depth as usize),
|
||||
NTreeNode::<N> {
|
||||
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::<N>::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::<Vec<_>>();
|
||||
|
||||
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::<N> {
|
||||
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::<N> {
|
||||
color: Color::average(
|
||||
children
|
||||
.iter()
|
||||
.map(|x| x.color)
|
||||
.collect::<Vec<_>>()
|
||||
.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::<N>(x)
|
||||
.unwrap_or(depth)
|
||||
.min(trailing_zeroes::<N>(y).unwrap_or(depth))
|
||||
.min(trailing_zeroes::<N>(z).unwrap_or(depth));
|
||||
|
||||
let prev_color = chunk[x + y * width + z * width * width];
|
||||
let mut locator = NTreeLocator::<N>::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::<N>::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::<Vec<_>>();
|
||||
structure.insert(
|
||||
locator,
|
||||
NTreeNode::<N> {
|
||||
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::<N>::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::<N> {
|
||||
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::<Vec<_>>();
|
||||
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<GPUStructureTile<N>>, 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::<N>::root())
|
||||
.unwrap()
|
||||
.color,
|
||||
vec![],
|
||||
vec![],
|
||||
);
|
||||
}
|
||||
|
||||
let mut structure_tiles = vec![GPUStructureTile::<N>::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::<N>::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::<Vec<_>>();
|
||||
|
||||
let mut structure_tile = GPUStructureTile::<N>::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::<N>::root())
|
||||
.unwrap()
|
||||
.color,
|
||||
structure_tiles,
|
||||
color_tiles,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct GPUStructureTile<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
children: [GPUStructureTileIndex; N * N * N],
|
||||
}
|
||||
|
||||
impl<const N: usize> GPUStructureTile<N>
|
||||
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::<f32>();
|
||||
|
||||
Color(sum.0 / len, sum.1 / len, sum.2 / len, sum.3 / len)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
|
||||
pub struct NTreeLocator<const N: usize>(usize, usize, usize);
|
||||
|
||||
impl<const N: usize> NTreeLocator<N>
|
||||
{
|
||||
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<Item = NTreeLocator<N>>
|
||||
{
|
||||
(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<const N: usize>(mut n: usize) -> Option<usize>
|
||||
{
|
||||
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::<N>::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::<N>::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::<N>::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::<N>::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::<N>::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::<f32>();
|
||||
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::<N>::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::<f32>();
|
||||
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::<N>::root(),
|
||||
NTreeLocator::<N>::from_depth_coords(1, 2, 3, 0)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
NTreeLocator::<N>::root().get_child(1, 2, 3),
|
||||
NTreeLocator::<N>::from_depth_coords(1, 2, 3, 1)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
NTreeLocator::<N>::root()
|
||||
.get_child(1, 1, 1)
|
||||
.get_child(1, 2, 3),
|
||||
NTreeLocator::<N>::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);
|
||||
}
|
||||
}
|
||||
+10
-31
@@ -102,15 +102,11 @@ unsafe impl<const N: usize> Pod for StructurePage<N> where [(); N * N * N]: {}
|
||||
/// Number of `u32` words in a [`StructureAnchor`].
|
||||
pub const ANCHOR_WORDS: usize = 4;
|
||||
|
||||
/// Sentinel used in [`RequestInformation::table_slot`] and
|
||||
/// 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::<StructureAnchor>(), 16);
|
||||
assert_eq!(size_of::<RequestInformation>(), 40);
|
||||
assert_eq!(size_of::<LocationPage>(), 28);
|
||||
assert_eq!(size_of::<InsertionParent>(), 48);
|
||||
assert_eq!(size_of::<RequestMeta>(), 12);
|
||||
assert_eq!(size_of::<RequestInformation>(), 32);
|
||||
assert_eq!(size_of::<LocationPage>(), 24);
|
||||
assert_eq!(size_of::<InsertionParent>(), 44);
|
||||
assert_eq!(size_of::<RequestMeta>(), 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
|
||||
// Group 2: Slot metadata
|
||||
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
|
||||
@group(2) @binding(1) var<storage, read_write> fixed_table_structure_ids: array<u32>;
|
||||
|
||||
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -12,13 +12,12 @@
|
||||
|
||||
// Group 2: Slot metadata
|
||||
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
|
||||
@group(2) @binding(1) var<storage, read_write> fixed_table_structure_ids: array<u32>;
|
||||
|
||||
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
|
||||
|
||||
/// The slot named by the parent still holds the same anchor and structure id.
|
||||
/// This is what makes queue invalidation optional: a stale root response for a
|
||||
/// retired or reused slot can no longer win.
|
||||
/// 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.
|
||||
|
||||
@@ -8,9 +8,8 @@
|
||||
@group(1) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
|
||||
@group(1) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
|
||||
|
||||
/// Group 2: Slot metadata (current anchor/id assignment)
|
||||
/// Group 2: Slot metadata (current anchor assignment)
|
||||
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
|
||||
@group(2) @binding(1) var<storage, read_write> fixed_table_structure_ids: array<u32>;
|
||||
|
||||
var<immediate> table_producer_id: u32;
|
||||
|
||||
@@ -34,13 +33,11 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
}
|
||||
|
||||
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<u32>)
|
||||
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;
|
||||
|
||||
@@ -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))
|
||||
{
|
||||
|
||||
@@ -50,8 +50,7 @@ fn write_pointers(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
}
|
||||
|
||||
let location = structure_location_pages[parent.page_index];
|
||||
if(location.structure_id != parent.structure_id ||
|
||||
location.node_id != parent.node_id ||
|
||||
if(location.node_id != parent.node_id ||
|
||||
location.producer_id != parent.producer_id ||
|
||||
!anchor_eq(location.anchor, parent.anchor))
|
||||
{
|
||||
|
||||
@@ -33,19 +33,18 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
|
||||
// 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;
|
||||
|
||||
+867
-295
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user