Compare commits
31
Commits
11d26ad16b
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dd5fdc13b8 | ||
|
|
dd0e102348 | ||
|
|
2910314df3 | ||
|
|
34e5215001 | ||
|
|
42f85757d5 | ||
|
|
bbf9c4d0a8 | ||
|
|
b65632aab3 | ||
|
|
95a45a57d7 | ||
|
|
9b8fd9840e | ||
|
|
3ccbfe55eb | ||
|
|
cbb3b4eaf0 | ||
|
|
828806fbc8 | ||
|
|
c13a04c8e2 | ||
|
|
dd32c772e5 | ||
|
|
4581538c66 | ||
|
|
e7fbeb7887 | ||
|
|
27f660f6fb | ||
|
|
c31f3a9bc3 | ||
|
|
a39256a0f1 | ||
|
|
918eb97342 | ||
|
|
b6f4a9c432 | ||
|
|
e855ccd904 | ||
|
|
d44da4520c | ||
|
|
82c952c6d8 | ||
|
|
6dedbbdb75 | ||
|
|
1117647ca7 | ||
|
|
1e784d1a8b | ||
|
|
514bf5ba02 | ||
|
|
599a40301e | ||
|
|
9bd2cd5667 | ||
|
|
f8671bd35f |
@@ -1,5 +1,9 @@
|
||||
/target
|
||||
Cargo.lock
|
||||
.codegraph/
|
||||
.mcp.json
|
||||
opencode.jsonc
|
||||
.claude/
|
||||
|
||||
imgs.tar.gz
|
||||
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
# AGENTS.md
|
||||
|
||||
Guidance for agents working in this repository. Read this first, then the
|
||||
relevant document under [`docs/`](./docs).
|
||||
|
||||
## What this is
|
||||
|
||||
`vxls` is a Rust + wgpu voxel renderer built around a GPU-resident sparse voxel
|
||||
cache (GigaVoxels-style). The tree is 4×4×4 (64 children per node), nodes live
|
||||
in fixed GPU page pools, and there is no separate brick pool. Rendering emits
|
||||
requests for missing nodes on the GPU; a producer fulfils them on the CPU and
|
||||
the cache inserts them.
|
||||
|
||||
The durable system is:
|
||||
|
||||
- `crates/vxls-voxel-cache/src/lib.rs` and `crates/vxls-voxel-cache/src/*` — cache API and GPU passes.
|
||||
- `crates/vxls-voxel-cache/src/shaders/*.wgsl` — runtime-specialised cache shaders.
|
||||
- `crates/vxls-attributes/src/*` — producer-facing attribute traits, payload layouts, and the `Attributes` derive.
|
||||
- `crates/vxls-gpu/src/*` — radix sort, top-K, indirect dispatch, compaction.
|
||||
- `shaders/*.slang` — render-side ray marching, compiled ahead of time.
|
||||
- `crates/vxls-voxel-cache/src/tables.rs` + `crates/vxls-terrain/src/lib.rs` — structure tables
|
||||
(`FixedStructureTable`, the freelist-backed `DynamicStructureTable`, and the
|
||||
shared `StructureTableCore`) and the toroidal world wrapper.
|
||||
|
||||
> **Temporary code:** `crates/vxls/src/main.rs` and `crates/vxls/src/producers.rs` are a playground/test
|
||||
> harness built alongside the cache. They contain hardcoded parameters and
|
||||
> blocking workarounds. Do not treat them as stable architecture, public API, or
|
||||
> examples of intended concurrency. The real system is `crates/vxls-voxel-cache/src/*` and
|
||||
> `shaders/`.
|
||||
|
||||
## Build and run
|
||||
|
||||
Requirements: a **nightly** Rust toolchain (edition 2024, `generic_const_exprs`,
|
||||
`float_algebraic`) and `slangc` if you modify Slang shaders.
|
||||
|
||||
```sh
|
||||
make -C shaders # rebuild SPIR-V into shaders/out/ (checked in)
|
||||
cargo run -p vxls # window + egui overlay
|
||||
cargo check --workspace # compile check for every crate
|
||||
cargo test --workspace # unit tests (GPU tests need an adapter)
|
||||
```
|
||||
|
||||
The repository is a virtual Cargo workspace: the binary lives in `crates/vxls`,
|
||||
the durable engine is split across `crates/vxls-voxel-cache`, `crates/vxls-attributes`,
|
||||
`crates/vxls-gpu`, `crates/vxls-profiler`, `crates/vxls-production`, `crates/vxls-bvh`,
|
||||
and `crates/vxls-terrain`. Use `cargo check -p <crate>` for a single crate.
|
||||
|
||||
SPIR-V files are embedded with `include_spirv_source!` / `include_spirv!` at
|
||||
Rust compile time, so after rebuilding shaders you must also rebuild Rust.
|
||||
|
||||
Debug keys: `F` pause cache management, `T` target, `N` normals, `Q` albedo,
|
||||
`P` position.
|
||||
|
||||
## Documentation map
|
||||
|
||||
| Document | Read it for |
|
||||
|---|---|
|
||||
| [`docs/architecture.md`](./docs/architecture.md) | Vision, principles, module map, frame lifecycle, data flow, memory envelope, architecture-level issues. |
|
||||
| [`docs/voxel-cache.md`](./docs/voxel-cache.md) | Page/pointer layouts, attributes, public API, request/insertion pipelines, eviction, structure tables, bind groups. |
|
||||
| [`docs/shaders.md`](./docs/shaders.md) | Slang vs WGSL split, build/embedding, tracing algorithm, LOD, shader contracts, shader-level issues. |
|
||||
| [`docs/pipeline-and-producers.md`](./docs/pipeline-and-producers.md) | Request/response contract, current host loop, generator fixtures, unwired production subsystem, adding a producer. |
|
||||
|
||||
Suggested read order for a new agent:
|
||||
`AGENTS.md` → `docs/architecture.md` → `docs/voxel-cache.md` →
|
||||
`docs/shaders.md` → `docs/pipeline-and-producers.md`.
|
||||
|
||||
## Load-bearing conventions
|
||||
|
||||
Do not change these casually; they are contracts between Rust, WGSL, and Slang.
|
||||
|
||||
1. **Pointer bits:** bit 31 = subdividable, bit 30 = available, bits 0..29 =
|
||||
page index. `child_pointer_available` requires both high bits.
|
||||
2. **Child index:** `x + 4*y + 16*z` (x fastest), 64 children per node.
|
||||
3. **Page model:** one page = one node = 64 pointers + occupancy mask + location
|
||||
+ depth + attributes. No separate brick pool.
|
||||
4. **Request/insertion order:** request slot `i` corresponds to insertion slot
|
||||
`i`. `write_pointers` and table insertion rely on this.
|
||||
5. **Attribute order:** Slang hardcodes attribute 0 as packed RGBA color and
|
||||
attribute 1 as a 3-word normal, with stride 64. The demo's `CacheLayout`
|
||||
order is load-bearing.
|
||||
6. **`N` is overloaded:** Rust `VoxelCache<N>` / `VoxelCacheInsertion<N>` use `N`
|
||||
as the branching factor; Slang `VoxelCacheParameters<N>` uses `N` as the
|
||||
attribute count. Read the surrounding type before assuming.
|
||||
7. **Depth assumptions:** the caller-owned trace stack (`LocalTraceStack`)
|
||||
holds 5 entries and indexes `entries[10 - scale_exp/2]`, assuming branching
|
||||
4 and `chunk_power = 5`. Changing either breaks tracing silently. The stack
|
||||
is caller-owned; the tracer must not depend on where the front-end stores it.
|
||||
8. **Generated WGSL constants:** `CHILDREN_COUNT`, `PAGE_COUNT`, and attribute
|
||||
metadata are injected at runtime by `pipelines.rs`. Edit the Rust generator,
|
||||
not a generated copy.
|
||||
9. **SPIR-V is generated:** never edit `shaders/out/*.spv`; edit `.slang` and run
|
||||
`make -C shaders`.
|
||||
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.** `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
|
||||
|
||||
| Task | Start at |
|
||||
|---|---|
|
||||
| Change page/pointer layout | `crates/vxls-voxel-cache/src/schema.rs`, `crates/vxls-voxel-cache/src/shaders/cache_common.wgsl`, `crates/vxls-voxel-cache/src/shaders/common.wgsl` |
|
||||
| Add/change a cache attribute | `crates/vxls-attributes/src/attributes.rs`, `crates/vxls-voxel-cache/src/layout.rs`, `crates/vxls-voxel-cache/src/insertion.rs` (`write_attributes`), `crates/vxls-voxel-cache/src/attributes.rs`, `crates/vxls-voxel-cache/src/shaders/insertion.wgsl`, Slang `fetch_*` in `shaders/voxel.slang` |
|
||||
| Change request prioritisation | `crates/vxls-voxel-cache/src/requests.rs`, `crates/vxls-gpu/src/top_k.rs`, `crates/vxls-gpu/src/radix_sort.rs` |
|
||||
| Change eviction | `crates/vxls-voxel-cache/src/eviction.rs`, `crates/vxls-voxel-cache/src/shaders/eviction.wgsl`, `crates/vxls-voxel-cache/src/shaders/insertion.wgsl` |
|
||||
| Change insertion semantics | `crates/vxls-voxel-cache/src/lib.rs` (`insert`), `crates/vxls-voxel-cache/src/pipelines.rs`, `crates/vxls-voxel-cache/src/shaders/insertion.wgsl`, `write_pointers.wgsl` |
|
||||
| Change world/chunk lookup | `crates/vxls-voxel-cache/src/tables.rs`, `crates/vxls-terrain/src/lib.rs`, `shaders/toroidal_structure_table.slang` |
|
||||
| Add/change slot allocation or table growth | `crates/vxls-voxel-cache/src/tables.rs` (`DynamicStructureTable`, `SlotAllocator`, `StructureTableCore`) |
|
||||
| Change structure identity / anchors | `crates/vxls-voxel-cache/src/schema.rs` (`StructureAnchor`, wire structs), `crates/vxls-production/src/request_queue.rs`, `crates/vxls-voxel-cache/src/tables.rs`, `crates/vxls-voxel-cache/src/shaders/common.wgsl`, fixed-table shaders |
|
||||
| Change ray marching/LOD | `shaders/voxel.slang`, `shaders/voxel_cache.slang`, `shaders/lod_policies.slang` |
|
||||
| Add a producer | `crates/vxls/src/producers.rs` (`TreeProducer`), `crates/vxls-production/src/producer.rs` (`Producer`/`ProducedNode`), `crates/vxls-production/src/request_queue.rs`, [`docs/pipeline-and-producers.md`](./docs/pipeline-and-producers.md) |
|
||||
| Add/change a secondary-ray pass | `shaders/gi.slang` (AO), `shaders/voxel_tracing.slang` (`TraceSettings`, `ITraceStack`), `shaders/bvh.slang` (`max_t`), [`docs/shaders.md`](./docs/shaders.md#81-ao-pass-gislang) |
|
||||
|
||||
## Current demo configuration
|
||||
|
||||
```text
|
||||
VoxelCache<4> branching 64
|
||||
150_000 pages
|
||||
1_024 max requests
|
||||
attributes: color (1 word), normal (3 words), both External
|
||||
TreeProducer<4> source: dragon.txt sparse tree (SdfGenerator is an unused fixture)
|
||||
20 x 20 x 20 toroidal chunk extent
|
||||
request buffers: 1024 (cache), 128 (structure table)
|
||||
```
|
||||
|
||||
In render space one structure-table cell is a unit cube; the cache subdivides
|
||||
that cube and the producer decides how many voxels it packs into it.
|
||||
|
||||
## Known gaps and traps
|
||||
|
||||
The full tables live in the docs. The most important ones:
|
||||
|
||||
- **Location pages are over-allocated** at `size_of::<StructurePage<N>>()` per
|
||||
page instead of `LocationPage` (≈39.6 MB vs ≈1.2 MB at 150k pages).
|
||||
- **The first insertion is a no-op** because of the timestamp guard
|
||||
(`0 >= new_timestamp - 1` on the first call).
|
||||
- **The host producer path busy-waits** on `device.poll`, so "async" request
|
||||
fulfilment blocks the render thread.
|
||||
- **Insertion can silently drop pages** (`destination_indices == 0xFFFFFFFF`)
|
||||
with no signal to the producer.
|
||||
- **Several modules are not wired in:** the terrain/ball fixtures and
|
||||
`VoxelGiPipeline`. Mark them as inactive rather than treating them as current
|
||||
behaviour. The production request queue and durable producer types are on the
|
||||
demo's live path.
|
||||
- **`gi.slang` is a simple AO pass**, not full GI: a few short hemisphere rays
|
||||
per pixel, no denoiser. It is a secondary-ray smoke test.
|
||||
- **`fixed_structure_table.slang` is imported but unused**; the active path is
|
||||
the toroidal wrapper around Rust's `FixedStructureTable`.
|
||||
|
||||
## Working conventions
|
||||
|
||||
- **Ask before guessing** when behaviour or intent is undocumented. This repo
|
||||
contains experimental code and contradictory comments; prefer evidence from
|
||||
source over inference.
|
||||
- **Preserve the Rust/WGSL/Slang contract.** If you change a layout, update all
|
||||
three sides and the docs.
|
||||
- **Measure before optimising.** Timestamp queries and the memory profiler are
|
||||
already available (`crates/vxls-profiler/src`).
|
||||
- **Do not "fix" dead code by assuming it is live.** Check `mod` declarations in
|
||||
`crates/vxls/src/main.rs` first.
|
||||
- **Keep the playground separate from the engine.** New durable logic belongs in
|
||||
`crates/vxls-voxel-cache/src/*`, `crates/vxls-gpu/src/*`, or `shaders/*`, not in `main.rs`.
|
||||
- **Document discrepancies as observations.** If code and comments disagree,
|
||||
state what the code does, what the comment claims, and your confidence.
|
||||
|
||||
<!-- CODEGRAPH_START -->
|
||||
## CodeGraph
|
||||
|
||||
In repositories indexed by CodeGraph (a `.codegraph/` directory exists at the repo root), reach for it BEFORE grep/find or reading files when you need to understand or locate code:
|
||||
|
||||
- **MCP tool** (when available): `codegraph_explore` answers most code questions in one call — the relevant symbols' verbatim source plus the call paths between them, including dynamic-dispatch hops grep can't follow. Name a file or symbol in the query to read its current line-numbered source. If it's listed but deferred, load it by name via tool search.
|
||||
- **Shell** (always works): `codegraph explore "<symbol names or question>"` prints the same output.
|
||||
|
||||
If there is no `.codegraph/` directory, skip CodeGraph entirely — indexing is the user's decision.
|
||||
<!-- CODEGRAPH_END -->
|
||||
+11
-9
@@ -1,11 +1,10 @@
|
||||
[package]
|
||||
name = "vxls"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/*"]
|
||||
|
||||
[dependencies]
|
||||
bytemuck = {version = "1.25.2", features = ["derive"]}
|
||||
crevice = {version = "0.20.1", features = ["glam"]}
|
||||
[workspace.dependencies]
|
||||
bytemuck = { version = "1.25.2", features = ["derive"] }
|
||||
crevice = { version = "0.20.1", features = ["glam"] }
|
||||
egui = "0.36.1"
|
||||
egui-wgpu = "0.36.1"
|
||||
egui-winit = "0.36.1"
|
||||
@@ -13,14 +12,17 @@ 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"
|
||||
noise = "0.9.0"
|
||||
pollster = "1.0.1"
|
||||
proc-macro2 = "1"
|
||||
quote = "1"
|
||||
rand = "0.10.2"
|
||||
syn = "2"
|
||||
rayon = "1.12.0"
|
||||
tiff = "0.11.3"
|
||||
wgpu = {version = "30", features = ["spirv"]}
|
||||
wgpu = { version = "30", features = ["spirv"] }
|
||||
winit = "0.30.13"
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "vxls-attributes-derive"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
proc-macro2.workspace = true
|
||||
quote.workspace = true
|
||||
syn.workspace = true
|
||||
@@ -0,0 +1,295 @@
|
||||
//! Derive macro for the `vxls_attributes::Attributes` trait.
|
||||
//!
|
||||
//! # Example
|
||||
//!
|
||||
//! ```ignore
|
||||
//! use bytemuck::{Pod, Zeroable};
|
||||
//! use vxls_attributes::Attributes;
|
||||
//!
|
||||
//! #[derive(Clone, Copy, PartialEq, Default, Pod, Zeroable, Attributes)]
|
||||
//! #[repr(C)]
|
||||
//! pub struct VoxelAttributes
|
||||
//! {
|
||||
//! #[attribute(label = "color", semantic = "color")]
|
||||
//! pub color: u32,
|
||||
//!
|
||||
//! #[attribute(label = "normal", semantic = "normal")]
|
||||
//! pub normal: [f32; 3],
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! Each non-skipped field becomes one cache attribute, in declaration order.
|
||||
//! The derive also implements `vxls_attributes::Attribute` for the struct by
|
||||
//! averaging every field independently.
|
||||
//!
|
||||
//! Field options:
|
||||
//!
|
||||
//! - `#[attribute(label = "...")]`: name of the attribute. Defaults to the
|
||||
//! field name.
|
||||
//! - `#[attribute(semantic = "...")]`: optional shader-facing role of the
|
||||
//! attribute, stored in the layout for diagnostics.
|
||||
//! - `#[attribute(skip)]`: the field stays part of the struct but is not an
|
||||
//! attribute. It is reset to its default when averaging.
|
||||
//!
|
||||
//! The derive requires the struct to be `#[repr(C)]` or `#[repr(transparent)]`
|
||||
//! and to not be generic. It emits compile-time checks that every attribute
|
||||
//! field is a whole number of `u32` words and that the struct has no padding.
|
||||
|
||||
use proc_macro::TokenStream;
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
use quote::quote;
|
||||
use syn::Data;
|
||||
use syn::DeriveInput;
|
||||
use syn::Error;
|
||||
use syn::Fields;
|
||||
use syn::LitStr;
|
||||
use syn::Result;
|
||||
use syn::parse_macro_input;
|
||||
|
||||
#[proc_macro_derive(Attributes, attributes(attribute))]
|
||||
pub fn derive_attributes(input: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(input as DeriveInput);
|
||||
|
||||
expand(input)
|
||||
.unwrap_or_else(|error| error.to_compile_error())
|
||||
.into()
|
||||
}
|
||||
|
||||
fn expand(input: DeriveInput) -> Result<TokenStream2> {
|
||||
let ident = &input.ident;
|
||||
|
||||
if !input.generics.params.is_empty() {
|
||||
return Err(Error::new_spanned(
|
||||
&input.generics,
|
||||
"`Attributes` cannot be derived for generic structs",
|
||||
));
|
||||
}
|
||||
|
||||
check_repr(&input)?;
|
||||
|
||||
let data = match &input.data {
|
||||
Data::Struct(data) => data,
|
||||
Data::Enum(_) => {
|
||||
return Err(Error::new_spanned(
|
||||
&input.ident,
|
||||
"`Attributes` can only be derived for structs",
|
||||
));
|
||||
}
|
||||
Data::Union(_) => {
|
||||
return Err(Error::new_spanned(
|
||||
&input.ident,
|
||||
"`Attributes` can only be derived for structs",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let fields = match &data.fields {
|
||||
Fields::Named(fields) => &fields.named,
|
||||
_ => {
|
||||
return Err(Error::new_spanned(
|
||||
&data.fields,
|
||||
"`Attributes` requires named fields",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let mut descriptors = Vec::new();
|
||||
let mut getters = Vec::new();
|
||||
let mut getters_mut = Vec::new();
|
||||
let mut averages = Vec::new();
|
||||
let mut skipped = Vec::new();
|
||||
let mut field_types = Vec::new();
|
||||
let mut index = 0usize;
|
||||
|
||||
for field in fields {
|
||||
let name = field
|
||||
.ident
|
||||
.as_ref()
|
||||
.expect("named fields always have an identifier");
|
||||
let ty = &field.ty;
|
||||
|
||||
field_types.push(quote! { #ty });
|
||||
|
||||
let mut options = FieldOptions::default();
|
||||
for attribute in &field.attrs {
|
||||
if !attribute.path().is_ident("attribute") {
|
||||
continue;
|
||||
}
|
||||
|
||||
attribute.parse_nested_meta(|meta| {
|
||||
if meta.path.is_ident("skip")
|
||||
{
|
||||
options.skip = true;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if meta.path.is_ident("label")
|
||||
{
|
||||
options.label = Some(meta.value()?.parse::<LitStr>()?);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if meta.path.is_ident("semantic")
|
||||
{
|
||||
options.semantic = Some(meta.value()?.parse::<LitStr>()?);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
Err(meta.error(
|
||||
"unknown attribute option, expected `skip`, `label = \"...\"` or `semantic = \"...\"`",
|
||||
))
|
||||
})?;
|
||||
}
|
||||
|
||||
if options.skip {
|
||||
skipped.push(quote! {
|
||||
#name: ::core::default::Default::default()
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
let label = options
|
||||
.label
|
||||
.unwrap_or_else(|| LitStr::new(&name.to_string(), name.span()));
|
||||
|
||||
let semantic = match options.semantic {
|
||||
Some(semantic) => quote! { ::core::option::Option::Some(#semantic) },
|
||||
None => quote! { ::core::option::Option::None },
|
||||
};
|
||||
|
||||
descriptors.push(quote! {
|
||||
::vxls_attributes::AttributeDescriptor {
|
||||
label: #label,
|
||||
word_count: (::core::mem::size_of::<#ty>() / 4) as u32,
|
||||
semantic: #semantic,
|
||||
}
|
||||
});
|
||||
|
||||
getters.push(quote! {
|
||||
#index => ::vxls_attributes::bytemuck::bytes_of(&self.#name),
|
||||
});
|
||||
|
||||
getters_mut.push(quote! {
|
||||
#index => ::vxls_attributes::bytemuck::bytes_of_mut(&mut self.#name),
|
||||
});
|
||||
|
||||
averages.push(quote! {
|
||||
#name: <#ty as ::vxls_attributes::Attribute>::average(
|
||||
&items
|
||||
.iter()
|
||||
.map(|item| item.#name)
|
||||
.collect::<::std::vec::Vec<_>>()
|
||||
),
|
||||
});
|
||||
|
||||
index += 1;
|
||||
}
|
||||
|
||||
let field_size_sum = quote! {
|
||||
0usize #( + ::core::mem::size_of::<#field_types>() )*
|
||||
};
|
||||
|
||||
Ok(quote! {
|
||||
#[automatically_derived]
|
||||
impl ::vxls_attributes::Attributes for #ident
|
||||
{
|
||||
const LAYOUT: ::vxls_attributes::AttributesLayout =
|
||||
::vxls_attributes::AttributesLayout {
|
||||
attributes: &[ #(#descriptors),* ],
|
||||
};
|
||||
|
||||
#[inline]
|
||||
fn get_attr(&self, index: usize) -> &[u8]
|
||||
{
|
||||
match index
|
||||
{
|
||||
#(#getters)*
|
||||
_ => ::core::panic!(
|
||||
"attribute index out of bounds for `{}` ({} attributes)",
|
||||
::core::stringify!(#ident),
|
||||
#index,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn get_attr_mut(&mut self, index: usize) -> &mut [u8]
|
||||
{
|
||||
match index
|
||||
{
|
||||
#(#getters_mut)*
|
||||
_ => ::core::panic!(
|
||||
"attribute index out of bounds for `{}` ({} attributes)",
|
||||
::core::stringify!(#ident),
|
||||
#index,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[automatically_derived]
|
||||
impl ::vxls_attributes::Attribute for #ident
|
||||
{
|
||||
fn average(items: &[Self]) -> Self
|
||||
{
|
||||
if items.is_empty()
|
||||
{
|
||||
return <Self as ::core::default::Default>::default();
|
||||
}
|
||||
|
||||
Self {
|
||||
#(#averages)*
|
||||
#(#skipped,)*
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const _: () = {
|
||||
#(
|
||||
::core::assert!(
|
||||
::core::mem::size_of::<#field_types>() % 4 == 0,
|
||||
"attribute field size must be a multiple of 4 bytes",
|
||||
);
|
||||
)*
|
||||
|
||||
::core::assert!(
|
||||
::core::mem::size_of::<#ident>() == #field_size_sum,
|
||||
"`Attributes` structs must not contain padding",
|
||||
);
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
/// Collects the `#[attribute(...)]` options of a single field.
|
||||
#[derive(Default)]
|
||||
struct FieldOptions {
|
||||
skip: bool,
|
||||
label: Option<LitStr>,
|
||||
semantic: Option<LitStr>,
|
||||
}
|
||||
|
||||
fn check_repr(input: &DeriveInput) -> Result<()> {
|
||||
let mut found = false;
|
||||
|
||||
for attribute in &input.attrs {
|
||||
if !attribute.path().is_ident("repr") {
|
||||
continue;
|
||||
}
|
||||
|
||||
attribute.parse_nested_meta(|meta| {
|
||||
if meta.path.is_ident("C") || meta.path.is_ident("transparent") {
|
||||
found = true;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
|
||||
if found {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::new_spanned(
|
||||
&input.ident,
|
||||
"`Attributes` requires the struct to be `#[repr(C)]` or `#[repr(transparent)]`",
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "vxls-attributes"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
bytemuck.workspace = true
|
||||
vxls-attributes-derive = { path = "../vxls-attributes-derive" }
|
||||
@@ -0,0 +1,411 @@
|
||||
//! Voxel attribute traits and layouts.
|
||||
//!
|
||||
//! An [`Attribute`] is one datum stored per voxel. An [`Attributes`] struct
|
||||
//! bundles several of them into a payload: each field becomes one cache
|
||||
//! attribute with its own GPU buffer.
|
||||
//!
|
||||
//! The layout is part of the Rust/WGSL/Slang contract: attribute order must
|
||||
//! match the order the shaders read, and each field must be a whole number of
|
||||
//! `u32` words. `#[derive(Attributes)]` (re-exported at the crate root) builds
|
||||
//! the layout from the field order and checks both properties at compile time.
|
||||
//!
|
||||
//! This crate is deliberately free of GPU and producer dependencies. The cache
|
||||
//! consumes [`AttributesLayout`] to build its own `CacheLayout`, and producers
|
||||
//! implement [`Attributes`] for the payloads they generate.
|
||||
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
|
||||
/// A single voxel attribute.
|
||||
///
|
||||
/// Attributes are plain bits that can be moved between the CPU producer, the
|
||||
/// insertion buffers and the GPU. Equality is `PartialEq` rather than `Eq`
|
||||
/// because payloads commonly contain `f32` (for example `[f32; 3]` normals),
|
||||
/// and `Eq` cannot be implemented for foreign float arrays.
|
||||
pub trait Attribute:
|
||||
// An attribute can be turned into predictable, safe, raw bytes
|
||||
Pod +
|
||||
Zeroable +
|
||||
|
||||
// It can be compared with itself, equal attributes mean they can be merged in a sparse structure
|
||||
PartialEq +
|
||||
|
||||
// It can be created by anybody, without knowing what is inside
|
||||
Default +
|
||||
|
||||
// It can be moved around without problems, and does not depend on anything
|
||||
Clone +
|
||||
Copy +
|
||||
Send +
|
||||
Sync +
|
||||
'static
|
||||
{
|
||||
/// Many attributes can be averaged together.
|
||||
///
|
||||
/// Implementations must return `Self::default()` for an empty slice.
|
||||
fn average(attributes: &[Self]) -> Self;
|
||||
}
|
||||
|
||||
/// A bundle of attributes making up one voxel.
|
||||
///
|
||||
/// The layout of a structure is part of the cache contract: the order of the
|
||||
/// attributes must match the order the shaders read, and every attribute size
|
||||
/// must be a whole number of `u32` words.
|
||||
pub trait Attributes: Attribute {
|
||||
/// The attributes layout for this struct.
|
||||
///
|
||||
/// Built by `#[derive(Attributes)]`, but it can also be written by hand.
|
||||
const LAYOUT: AttributesLayout;
|
||||
|
||||
/// Gets the nth attribute's bytes in the struct.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `index` is not a valid attribute index.
|
||||
fn get_attr(&self, index: usize) -> &[u8];
|
||||
|
||||
/// Gets the nth attribute's bytes in the struct mutably.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `index` is not a valid attribute index.
|
||||
fn get_attr_mut(&mut self, index: usize) -> &mut [u8];
|
||||
|
||||
/// Gets the nth attribute's bytes, or [`None`] if the index is out of range.
|
||||
fn try_get_attr(&self, index: usize) -> Option<&[u8]> {
|
||||
(index < Self::LAYOUT.len()).then(|| self.get_attr(index))
|
||||
}
|
||||
|
||||
/// Gets the nth attribute's bytes mutably, or [`None`] if the index is out of range.
|
||||
fn try_get_attr_mut(&mut self, index: usize) -> Option<&mut [u8]> {
|
||||
(index < Self::LAYOUT.len()).then(|| self.get_attr_mut(index))
|
||||
}
|
||||
}
|
||||
|
||||
/// Describes one attribute of a voxel
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct AttributeDescriptor {
|
||||
/// A name for the attribute, used as the GPU buffer label
|
||||
pub label: &'static str,
|
||||
|
||||
/// The size, in 32-bit words, of the attribute
|
||||
pub word_count: u32,
|
||||
|
||||
/// Optional shader-facing role ("color", "normal", ...).
|
||||
///
|
||||
/// The cache still indexes attributes by position; this field only exists
|
||||
/// so a host can detect that the Rust side and the shaders drifted apart.
|
||||
pub semantic: Option<&'static str>,
|
||||
}
|
||||
|
||||
impl AttributeDescriptor {
|
||||
/// Creates a descriptor without a semantic role
|
||||
pub const fn new(label: &'static str, word_count: u32) -> Self {
|
||||
Self {
|
||||
label,
|
||||
word_count,
|
||||
semantic: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a semantic role to this descriptor
|
||||
pub const fn with_semantic(mut self, semantic: &'static str) -> Self {
|
||||
self.semantic = Some(semantic);
|
||||
self
|
||||
}
|
||||
|
||||
/// The size of this attribute in bytes
|
||||
pub const fn size_bytes(&self) -> u32 {
|
||||
self.word_count * size_of::<u32>() as u32
|
||||
}
|
||||
}
|
||||
|
||||
/// An attribute layout, for voxels
|
||||
///
|
||||
/// The layout is stored as a `'static` slice so it can live in an associated
|
||||
/// constant. Runtime-built layouts can copy it into a `Vec`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct AttributesLayout {
|
||||
/// The attributes, in binding order
|
||||
pub attributes: &'static [AttributeDescriptor],
|
||||
}
|
||||
|
||||
impl AttributesLayout {
|
||||
/// A layout with no attributes
|
||||
pub const EMPTY: Self = Self { attributes: &[] };
|
||||
|
||||
/// Creates a layout from a static descriptor slice
|
||||
pub const fn new(attributes: &'static [AttributeDescriptor]) -> Self {
|
||||
Self { attributes }
|
||||
}
|
||||
|
||||
/// Number of attributes
|
||||
pub const fn len(&self) -> usize {
|
||||
self.attributes.len()
|
||||
}
|
||||
|
||||
/// Whether the layout has no attributes
|
||||
pub const fn is_empty(&self) -> bool {
|
||||
self.attributes.is_empty()
|
||||
}
|
||||
|
||||
/// Gets the descriptor at `index`
|
||||
pub fn get(&self, index: usize) -> Option<&AttributeDescriptor> {
|
||||
self.attributes.get(index)
|
||||
}
|
||||
|
||||
/// Iterates over `(index, descriptor)` pairs
|
||||
pub fn iter(&self) -> impl Iterator<Item = (usize, &AttributeDescriptor)> + '_ {
|
||||
self.attributes.iter().enumerate()
|
||||
}
|
||||
|
||||
/// Sum of every attribute's word count, i.e. the words used by one voxel
|
||||
pub fn total_word_count(&self) -> u32 {
|
||||
self.attributes
|
||||
.iter()
|
||||
.map(|attribute| attribute.word_count)
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Finds an attribute by label
|
||||
pub fn by_label(&self, label: &str) -> Option<(usize, &AttributeDescriptor)> {
|
||||
self.iter().find(|(_, attribute)| attribute.label == label)
|
||||
}
|
||||
|
||||
/// Finds an attribute by semantic role
|
||||
pub fn by_semantic(&self, semantic: &str) -> Option<(usize, &AttributeDescriptor)> {
|
||||
self.iter()
|
||||
.find(|(_, attribute)| attribute.semantic == Some(semantic))
|
||||
}
|
||||
|
||||
/// Checks that the layout can be used as a cache layout
|
||||
pub fn validate(&self) -> Result<(), LayoutError> {
|
||||
if self.attributes.is_empty() {
|
||||
return Err(LayoutError::Empty);
|
||||
}
|
||||
|
||||
for (index, attribute) in self.attributes.iter().enumerate() {
|
||||
if attribute.label.is_empty() {
|
||||
return Err(LayoutError::EmptyLabel { index });
|
||||
}
|
||||
|
||||
if attribute.word_count == 0 {
|
||||
return Err(LayoutError::ZeroWordCount { index });
|
||||
}
|
||||
|
||||
if let Some((first, _)) = self
|
||||
.attributes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.take(index)
|
||||
.find(|(_, other)| other.label == attribute.label)
|
||||
{
|
||||
return Err(LayoutError::DuplicateLabel {
|
||||
first,
|
||||
second: index,
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(semantic) = attribute.semantic
|
||||
&& let Some((first, _)) = self
|
||||
.attributes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.take(index)
|
||||
.find(|(_, other)| other.semantic == Some(semantic))
|
||||
{
|
||||
return Err(LayoutError::DuplicateSemantic {
|
||||
first,
|
||||
second: index,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A stable fingerprint of the layout, used to check that a producer, a
|
||||
/// cache instance and a shader build agree on the attribute layout.
|
||||
pub fn fingerprint(&self) -> u64 {
|
||||
let mut hash = 0xcbf2_9ce4_8422_2325u64;
|
||||
|
||||
for attribute in self.attributes {
|
||||
fnv1a(&mut hash, attribute.label.as_bytes());
|
||||
fnv1a(&mut hash, &attribute.word_count.to_le_bytes());
|
||||
|
||||
match attribute.semantic {
|
||||
Some(semantic) => {
|
||||
fnv1a(&mut hash, &[1]);
|
||||
fnv1a(&mut hash, semantic.as_bytes());
|
||||
}
|
||||
None => fnv1a(&mut hash, &[0]),
|
||||
}
|
||||
}
|
||||
|
||||
hash
|
||||
}
|
||||
|
||||
///
|
||||
/// Produces a wgsl declaration describing this layout :
|
||||
///
|
||||
/// ```wgsl
|
||||
///
|
||||
/// const ATTRIBUTE_COUNT: u32 = /* attribute count */;
|
||||
/// const ATTRIBUTE_WORD_COUNTS: array<u32, ...> = {
|
||||
/// /* word count for attribute 0 */,
|
||||
/// /* word count for attribute 1 */,
|
||||
/// ...
|
||||
/// };
|
||||
///
|
||||
///
|
||||
/// ```
|
||||
pub fn wgsl_layout_decl(&self) -> String {
|
||||
let mut decl = String::new();
|
||||
|
||||
decl += &format!("const ATTRIBUTE_COUNT: u32 = {};", self.attributes.len());
|
||||
|
||||
// Word counts
|
||||
decl += &format!(
|
||||
"const ATTRIBUTE_WORD_COUNTS: array<u32, {}> = array<u32, {}>(",
|
||||
self.attributes.len(),
|
||||
self.attributes.len()
|
||||
);
|
||||
|
||||
for attribute in self.attributes.iter() {
|
||||
decl += &format!(" {},", attribute.word_count);
|
||||
}
|
||||
|
||||
decl += ");";
|
||||
|
||||
decl
|
||||
}
|
||||
}
|
||||
|
||||
fn fnv1a(hash: &mut u64, bytes: &[u8]) {
|
||||
for byte in bytes {
|
||||
*hash ^= *byte as u64;
|
||||
*hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
}
|
||||
|
||||
/// Errors reported by [`AttributesLayout::validate`]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LayoutError {
|
||||
/// The layout has no attributes, which a cache cannot represent
|
||||
Empty,
|
||||
/// An attribute has an empty label
|
||||
EmptyLabel {
|
||||
/// Index of the offending attribute
|
||||
index: usize,
|
||||
},
|
||||
/// An attribute has a zero word count
|
||||
ZeroWordCount {
|
||||
/// Index of the offending attribute
|
||||
index: usize,
|
||||
},
|
||||
/// Two attributes share a label
|
||||
DuplicateLabel {
|
||||
/// Index of the first attribute
|
||||
first: usize,
|
||||
/// Index of the duplicate attribute
|
||||
second: usize,
|
||||
},
|
||||
/// Two attributes share a semantic role
|
||||
DuplicateSemantic {
|
||||
/// Index of the first attribute
|
||||
first: usize,
|
||||
/// Index of the duplicate attribute
|
||||
second: usize,
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Display for LayoutError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Empty => write!(formatter, "attribute layout has no attributes"),
|
||||
Self::EmptyLabel { index } => {
|
||||
write!(formatter, "attribute {index} has an empty label")
|
||||
}
|
||||
Self::ZeroWordCount { index } => {
|
||||
write!(formatter, "attribute {index} has a zero word count")
|
||||
}
|
||||
Self::DuplicateLabel { first, second } => {
|
||||
write!(
|
||||
formatter,
|
||||
"attributes {first} and {second} share the same label"
|
||||
)
|
||||
}
|
||||
Self::DuplicateSemantic { first, second } => {
|
||||
write!(
|
||||
formatter,
|
||||
"attributes {first} and {second} share the same semantic role"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for LayoutError {}
|
||||
|
||||
// Primitive attributes
|
||||
|
||||
impl Attribute for u32 {
|
||||
fn average(attributes: &[Self]) -> Self {
|
||||
if attributes.is_empty() {
|
||||
return Self::default();
|
||||
}
|
||||
|
||||
(attributes.iter().map(|value| *value as u64).sum::<u64>() / attributes.len() as u64) as u32
|
||||
}
|
||||
}
|
||||
|
||||
impl Attribute for i32 {
|
||||
fn average(attributes: &[Self]) -> Self {
|
||||
if attributes.is_empty() {
|
||||
return Self::default();
|
||||
}
|
||||
|
||||
(attributes.iter().map(|value| *value as i64).sum::<i64>() / attributes.len() as i64) as i32
|
||||
}
|
||||
}
|
||||
|
||||
impl Attribute for f32 {
|
||||
fn average(attributes: &[Self]) -> Self {
|
||||
if attributes.is_empty() {
|
||||
return Self::default();
|
||||
}
|
||||
|
||||
attributes.iter().sum::<f32>() / attributes.len() as f32
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_array_attribute {
|
||||
($($count:literal),* $(,)?) => {
|
||||
$(
|
||||
impl<T: Attribute> Attribute for [T; $count]
|
||||
{
|
||||
fn average(attributes: &[Self]) -> Self
|
||||
{
|
||||
if attributes.is_empty()
|
||||
{
|
||||
return Self::default();
|
||||
}
|
||||
|
||||
::core::array::from_fn(|index| {
|
||||
T::average(
|
||||
&attributes
|
||||
.iter()
|
||||
.map(|value| value[index])
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
impl_array_attribute!(
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
|
||||
27, 28, 29, 30, 31, 32,
|
||||
);
|
||||
@@ -0,0 +1,29 @@
|
||||
//! Voxel attribute vocabulary shared by the cache and its producers.
|
||||
//!
|
||||
//! A payload struct implements [`Attributes`]. Each non-skipped field becomes
|
||||
//! one cache attribute, stored in its own GPU buffer (`word_count` 32-bit words
|
||||
//! per voxel). The order of the fields is the order of the attribute bindings,
|
||||
//! so it is the same order the shaders index.
|
||||
//!
|
||||
//! ```ignore
|
||||
//! #[derive(Clone, Copy, PartialEq, Default, Pod, Zeroable, Attributes)]
|
||||
//! #[repr(C)]
|
||||
//! struct MyAttributes
|
||||
//! {
|
||||
//! #[attribute(label = "color", semantic = "color")]
|
||||
//! color: u32,
|
||||
//! #[attribute(label = "normal", semantic = "normal")]
|
||||
//! normal: [f32; 3],
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! This crate only describes attribute data. Building a GPU-facing cache
|
||||
//! layout and uploading a slice of attributes to a
|
||||
//! `vxls_voxel_cache::CacheInsertionData` live in `vxls-voxel-cache`.
|
||||
|
||||
pub use bytemuck;
|
||||
pub use vxls_attributes_derive::Attributes;
|
||||
|
||||
mod attributes;
|
||||
|
||||
pub use attributes::*;
|
||||
@@ -0,0 +1,137 @@
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
use vxls_attributes::Attribute;
|
||||
use vxls_attributes::AttributeDescriptor;
|
||||
use vxls_attributes::Attributes;
|
||||
use vxls_attributes::AttributesLayout;
|
||||
use vxls_attributes::LayoutError;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Default, Pod, Zeroable, Attributes, Debug)]
|
||||
#[repr(C)]
|
||||
struct TestAttributes {
|
||||
#[attribute(label = "color", semantic = "color")]
|
||||
color: u32,
|
||||
|
||||
#[attribute(label = "normal", semantic = "normal")]
|
||||
normal: [f32; 3],
|
||||
|
||||
#[attribute(skip)]
|
||||
reserved: u32,
|
||||
}
|
||||
|
||||
fn sample(color: u32, normal: [f32; 3]) -> TestAttributes {
|
||||
TestAttributes {
|
||||
color,
|
||||
normal,
|
||||
reserved: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout_matches_the_declared_fields() {
|
||||
let layout = TestAttributes::LAYOUT;
|
||||
|
||||
assert_eq!(layout.len(), 2);
|
||||
assert!(!layout.is_empty());
|
||||
|
||||
assert_eq!(layout.attributes[0].label, "color");
|
||||
assert_eq!(layout.attributes[0].semantic, Some("color"));
|
||||
assert_eq!(layout.attributes[0].word_count, 1);
|
||||
|
||||
assert_eq!(layout.attributes[1].label, "normal");
|
||||
assert_eq!(layout.attributes[1].semantic, Some("normal"));
|
||||
assert_eq!(layout.attributes[1].word_count, 3);
|
||||
|
||||
assert_eq!(layout.total_word_count(), 4);
|
||||
assert!(layout.validate().is_ok());
|
||||
|
||||
assert_eq!(layout.by_label("normal").map(|(index, _)| index), Some(1));
|
||||
assert_eq!(layout.by_semantic("color").map(|(index, _)| index), Some(0));
|
||||
assert!(layout.by_label("reserved").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_attr_returns_the_field_bytes() {
|
||||
let value = sample(0x1122_3344, [1.0, 2.0, 3.0]);
|
||||
|
||||
assert_eq!(value.get_attr(0), bytemuck::bytes_of(&value.color));
|
||||
assert_eq!(value.get_attr(1), bytemuck::bytes_of(&value.normal));
|
||||
assert!(value.try_get_attr(2).is_none());
|
||||
|
||||
let mut value = value;
|
||||
value
|
||||
.get_attr_mut(0)
|
||||
.copy_from_slice(&0xAABB_CCDDu32.to_ne_bytes());
|
||||
assert_eq!(value.color, 0xAABB_CCDD);
|
||||
assert!(value.try_get_attr_mut(2).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn average_is_component_wise_and_skips_the_reserved_field() {
|
||||
let first = TestAttributes {
|
||||
color: 2,
|
||||
normal: [1.0, 2.0, 3.0],
|
||||
reserved: 7,
|
||||
};
|
||||
let second = TestAttributes {
|
||||
color: 4,
|
||||
normal: [3.0, 4.0, 5.0],
|
||||
reserved: 9,
|
||||
};
|
||||
|
||||
let average = TestAttributes::average(&[first, second]);
|
||||
|
||||
assert_eq!(average.color, 3);
|
||||
assert_eq!(average.normal, [2.0, 3.0, 4.0]);
|
||||
assert_eq!(average.reserved, 0);
|
||||
|
||||
assert_eq!(TestAttributes::average(&[]), TestAttributes::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_rejects_duplicate_labels_and_semantics() {
|
||||
const DUPLICATE_LABELS: AttributesLayout = AttributesLayout {
|
||||
attributes: &[
|
||||
AttributeDescriptor {
|
||||
label: "a",
|
||||
word_count: 1,
|
||||
semantic: None,
|
||||
},
|
||||
AttributeDescriptor {
|
||||
label: "a",
|
||||
word_count: 1,
|
||||
semantic: None,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
DUPLICATE_LABELS.validate(),
|
||||
Err(LayoutError::DuplicateLabel {
|
||||
first: 0,
|
||||
second: 1
|
||||
})
|
||||
);
|
||||
|
||||
const DUPLICATE_SEMANTICS: AttributesLayout = AttributesLayout {
|
||||
attributes: &[
|
||||
AttributeDescriptor::new("a", 1).with_semantic("color"),
|
||||
AttributeDescriptor::new("b", 1).with_semantic("color"),
|
||||
],
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
DUPLICATE_SEMANTICS.validate(),
|
||||
Err(LayoutError::DuplicateSemantic {
|
||||
first: 0,
|
||||
second: 1
|
||||
})
|
||||
);
|
||||
|
||||
assert_eq!(AttributesLayout::EMPTY.validate(), Err(LayoutError::Empty));
|
||||
|
||||
assert_ne!(
|
||||
TestAttributes::LAYOUT.fingerprint(),
|
||||
DUPLICATE_LABELS.fingerprint()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "vxls-bvh"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
bytemuck.workspace = true
|
||||
egui.workspace = true
|
||||
glam.workspace = true
|
||||
wgpu.workspace = true
|
||||
vxls-profiler = { path = "../vxls-profiler" }
|
||||
vxls-production = { path = "../vxls-production" }
|
||||
vxls-voxel-cache = { path = "../vxls-voxel-cache" }
|
||||
@@ -0,0 +1,412 @@
|
||||
//! 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,335 @@
|
||||
//! Implementation of fast binary BVH build with binned SAH
|
||||
//!
|
||||
|
||||
use std::num::NonZero;
|
||||
|
||||
use egui::emath::OrderedFloat;
|
||||
|
||||
use crate::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,
|
||||
_pad2: [0; 2],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 depth: usize,
|
||||
}
|
||||
|
||||
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,
|
||||
depth: 1,
|
||||
//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,
|
||||
));
|
||||
|
||||
let mut max_depth = 0usize;
|
||||
build_node(0, primitives, &mut nodes, leaf_max, 0, &mut max_depth);
|
||||
println!("Max depth {}", max_depth);
|
||||
|
||||
Bvh {
|
||||
nodes,
|
||||
depth: max_depth,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_node<T>(
|
||||
node_index: usize,
|
||||
primitives: &mut [BvhPrimitive<T>],
|
||||
nodes: &mut Vec<BvhNode>,
|
||||
leaf_max: usize,
|
||||
depth: usize,
|
||||
max_depth: &mut 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,
|
||||
depth + 1,
|
||||
max_depth,
|
||||
);
|
||||
build_node(
|
||||
left_index + 1,
|
||||
primitives,
|
||||
nodes,
|
||||
leaf_max,
|
||||
depth + 1,
|
||||
max_depth,
|
||||
);
|
||||
}
|
||||
None => {
|
||||
// Sah says keep as leaf, do nothing
|
||||
if depth > *max_depth {
|
||||
*max_depth = depth;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,244 @@
|
||||
//! 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 rounds structs containing vec3 up to a 16-byte alignment, so a node's
|
||||
// 40 bytes of data become a 48-byte array stride.
|
||||
const _: () = {
|
||||
assert!(size_of::<crate::gpu::GpuBvhNode>() == 48);
|
||||
assert!(size_of::<crate::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: Some(wgpu::BlendState {
|
||||
color: wgpu::BlendComponent::OVER,
|
||||
alpha: wgpu::BlendComponent::OVER,
|
||||
}),
|
||||
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,198 @@
|
||||
//! 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
|
||||
{
|
||||
// vec3 members align to 16 bytes, so this struct has a 48-byte array
|
||||
// stride. The Rust `GpuBvhNode` is padded to the same size.
|
||||
min: vec3<f32>,
|
||||
_pad0: u32,
|
||||
max: vec3<f32>,
|
||||
_pad1: u32,
|
||||
count: u32,
|
||||
first_or_left: u32,
|
||||
_pad2: vec2<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: vec4<f32>,
|
||||
@location(1) normal: vec3<f32>,
|
||||
};
|
||||
|
||||
const INTERNAL_NODE_COLOR = vec4<f32>(0.15, 0.70, 1.0, 1.0);
|
||||
const LEAF_NODE_COLOR = vec4<f32>(1.0, 0.85, 0.20, 1.0);
|
||||
const OBJECT_COLOR = vec4<f32>(1.0, 0.45, 0.12, 0.5);
|
||||
|
||||
// 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 = node.min;
|
||||
let max_corner = node.max;
|
||||
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 input.color;
|
||||
}
|
||||
|
||||
@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));
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! GPU ready structures for the BVH representation
|
||||
|
||||
use glam::Mat4;
|
||||
use glam::Vec3;
|
||||
|
||||
use crate::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`]
|
||||
///
|
||||
/// The trailing padding keeps the array stride at 48 bytes. On the GPU a struct
|
||||
/// containing `vec3` has a 16-byte alignment, so the shader rounds the 40 bytes
|
||||
/// of data up to a 48-byte stride.
|
||||
#[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
|
||||
#[repr(C)]
|
||||
pub struct GpuBvhNode {
|
||||
pub aabb: GpuAabb,
|
||||
pub count: u32,
|
||||
pub first_or_left: u32,
|
||||
pub(crate) _pad2: [u32; 2],
|
||||
}
|
||||
|
||||
/// 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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
#![allow(incomplete_features)]
|
||||
#![feature(generic_const_exprs)]
|
||||
|
||||
//! 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::aabb::Aabb;
|
||||
use crate::build::BvhPrimitive;
|
||||
use crate::build::build_bvh;
|
||||
use crate::gpu::GpuBvhNode;
|
||||
use crate::gpu::GpuObject;
|
||||
use vxls_production::ProducerId;
|
||||
use vxls_production::StructureAnchor;
|
||||
use vxls_profiler::ScopeEncoder;
|
||||
use vxls_voxel_cache::CacheInvalidable;
|
||||
use vxls_voxel_cache::eviction::CacheEvictor;
|
||||
use vxls_voxel_cache::insertion::CacheInsertionData;
|
||||
use vxls_voxel_cache::requests::CacheRequestBuffer;
|
||||
use vxls_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
|
||||
}
|
||||
|
||||
/// Gathers the root requests emitted by the inner structure table into
|
||||
/// `request_buffer`.
|
||||
pub fn gather_requests(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
|
||||
request_buffer: &CacheRequestBuffer,
|
||||
) {
|
||||
self.structure_table
|
||||
.gather_requests(device, encoder, request_buffer);
|
||||
}
|
||||
|
||||
/// Writes the cache page pointers produced by an external insertion into
|
||||
/// the inner structure table.
|
||||
pub fn insert<const N: usize>(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
|
||||
insertion: &CacheInsertionData<N>,
|
||||
) where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
self.structure_table.insert(device, encoder, insertion);
|
||||
}
|
||||
|
||||
pub fn get(&self, handle: &BvhHandle) -> Option<&BvhObject> {
|
||||
self.objects.get(handle)
|
||||
}
|
||||
|
||||
pub fn get_mut(&mut self, handle: &BvhHandle) -> Option<&mut BvhObject> {
|
||||
self.objects.get_mut(handle)
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheInvalidable<N> for BvhStructureTable
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
fn validate_insertion(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
|
||||
insertion: &CacheInsertionData<N>,
|
||||
) {
|
||||
self.structure_table
|
||||
.validate_insertion(device, encoder, insertion);
|
||||
}
|
||||
|
||||
fn invalidate(
|
||||
&mut self,
|
||||
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
|
||||
cache_evictor: &CacheEvictor,
|
||||
invalid_timestamp: u32,
|
||||
) {
|
||||
self.structure_table
|
||||
.invalidate(encoder, cache_evictor, invalid_timestamp);
|
||||
}
|
||||
}
|
||||
|
||||
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(),
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "vxls-gpu"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
bytemuck.workspace = true
|
||||
itertools.workspace = true
|
||||
wgpu.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
pollster.workspace = true
|
||||
@@ -10,11 +10,10 @@ use wgpu::Device;
|
||||
use wgpu::ShaderStages;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
pub struct NonZeroBufferCompactor
|
||||
{
|
||||
size: usize,
|
||||
pub struct NonZeroBufferCompactor {
|
||||
block_count: usize,
|
||||
reduced_buffer: Buffer,
|
||||
#[allow(unused)]
|
||||
sum_buffer: Buffer,
|
||||
count_buffer_bg_layout: BindGroupLayout,
|
||||
compaction_bg: BindGroup,
|
||||
@@ -24,11 +23,9 @@ pub struct NonZeroBufferCompactor
|
||||
scatter_pipeline: ComputePipeline,
|
||||
}
|
||||
|
||||
impl NonZeroBufferCompactor
|
||||
{
|
||||
impl NonZeroBufferCompactor {
|
||||
const THREAD_COUNT: usize = 256;
|
||||
pub fn new(device: &Device, size: usize) -> Self
|
||||
{
|
||||
pub fn new(device: &Device, size: usize) -> Self {
|
||||
let block_count = size.div_ceil(Self::THREAD_COUNT * 2);
|
||||
let reduced_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("indirect_buffer_reduced"),
|
||||
@@ -136,7 +133,7 @@ impl NonZeroBufferCompactor
|
||||
wgpu::ShaderModuleDescriptor {
|
||||
label: Some("compaction_shader_layout"),
|
||||
source: wgpu::ShaderSource::SpirV(wgpu::__macro_helpers::Cow::Borrowed(
|
||||
wgpu::include_spirv_source!("../../shaders/compaction.spv"),
|
||||
wgpu::include_spirv_source!("../../../shaders/out/compaction.spv"),
|
||||
)),
|
||||
},
|
||||
wgpu::ShaderRuntimeChecks {
|
||||
@@ -178,7 +175,6 @@ impl NonZeroBufferCompactor
|
||||
});
|
||||
|
||||
NonZeroBufferCompactor {
|
||||
size,
|
||||
block_count,
|
||||
reduced_buffer,
|
||||
sum_buffer,
|
||||
@@ -190,14 +186,12 @@ impl NonZeroBufferCompactor
|
||||
}
|
||||
}
|
||||
|
||||
pub fn total_sum_buffer(&self) -> BufferSlice<'_>
|
||||
{
|
||||
pub fn total_sum_buffer(&self) -> BufferSlice<'_> {
|
||||
self.reduced_buffer
|
||||
.slice(((size_of::<u32>() * self.block_count) as u64)..)
|
||||
}
|
||||
|
||||
pub fn copy_count_to_buffer(&self, encoder: &mut CommandEncoder, target: &Buffer)
|
||||
{
|
||||
pub fn copy_count_to_buffer(&self, encoder: &mut CommandEncoder, target: &Buffer) {
|
||||
encoder.copy_buffer_to_buffer(
|
||||
&self.reduced_buffer,
|
||||
(size_of::<u32>() * self.block_count) as u64,
|
||||
@@ -214,8 +208,7 @@ impl NonZeroBufferCompactor
|
||||
count_buffer: &Buffer,
|
||||
index_buffer: &Buffer,
|
||||
compact_buffer: Option<&Buffer>,
|
||||
)
|
||||
{
|
||||
) {
|
||||
let count_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("count_buffer_bind_group"),
|
||||
layout: &self.count_buffer_bg_layout,
|
||||
@@ -230,7 +223,7 @@ impl NonZeroBufferCompactor
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: compact_buffer.unwrap_or(&count_buffer).as_entire_binding(),
|
||||
resource: compact_buffer.unwrap_or(count_buffer).as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -254,12 +247,9 @@ impl NonZeroBufferCompactor
|
||||
compute_pass.set_pipeline(&self.scatter_pipeline);
|
||||
compute_pass.set_immediates(
|
||||
0,
|
||||
if compact_buffer.is_some()
|
||||
{
|
||||
if compact_buffer.is_some() {
|
||||
bytes_of(&1)
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
bytes_of(&0)
|
||||
},
|
||||
);
|
||||
@@ -1,11 +1,10 @@
|
||||
//! Provides utility object to manage indirect dispatches workgroup count computations on the GPU
|
||||
|
||||
use wgpu::Buffer;
|
||||
use wgpu::CommandEncoder;
|
||||
|
||||
/// Provides utility object to manage indirect dispatches workgroup count computations on the GPU
|
||||
|
||||
/// Takes in a single u32, and computes the amount of workgroups to dispatch given a workgroup size
|
||||
pub struct IndirectBuffer1D
|
||||
{
|
||||
pub struct IndirectBuffer1D {
|
||||
/// Buffer used in the indirect dispatch command
|
||||
indirect_buffer: wgpu::Buffer,
|
||||
|
||||
@@ -17,10 +16,8 @@ pub struct IndirectBuffer1D
|
||||
compute_pipeline: wgpu::ComputePipeline,
|
||||
}
|
||||
|
||||
impl IndirectBuffer1D
|
||||
{
|
||||
pub fn new(device: &wgpu::Device) -> Self
|
||||
{
|
||||
impl IndirectBuffer1D {
|
||||
pub fn new(device: &wgpu::Device) -> Self {
|
||||
let indirect_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("IndirectBuffer1D::indirect_buffer"),
|
||||
size: size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
|
||||
@@ -127,8 +124,7 @@ impl IndirectBuffer1D
|
||||
encoder: &mut CommandEncoder,
|
||||
count_buffer: &Buffer,
|
||||
workgroup_size: u32,
|
||||
) -> &Buffer
|
||||
{
|
||||
) -> &Buffer {
|
||||
// Transient bind group
|
||||
let user_count_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("IndirectBuffer1D::bind_group"),
|
||||
@@ -2,14 +2,14 @@
|
||||
pub mod buffer_compactor;
|
||||
pub mod indirect_buffer;
|
||||
pub mod radix_sort;
|
||||
pub mod top_k;
|
||||
|
||||
// Utilities
|
||||
pub fn create_multi_buffers_bind_group_layout(
|
||||
device: &wgpu::Device,
|
||||
count: u32,
|
||||
label: Option<&str>,
|
||||
) -> wgpu::BindGroupLayout
|
||||
{
|
||||
) -> wgpu::BindGroupLayout {
|
||||
let entries = (0..count)
|
||||
.map(|i| wgpu::BindGroupLayoutEntry {
|
||||
binding: i,
|
||||
@@ -34,8 +34,7 @@ pub fn create_multi_buffers_bind_group(
|
||||
layout: &wgpu::BindGroupLayout,
|
||||
buffers: &[&wgpu::Buffer],
|
||||
label: Option<&str>,
|
||||
) -> wgpu::BindGroup
|
||||
{
|
||||
) -> wgpu::BindGroup {
|
||||
let entries = buffers
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -56,8 +55,7 @@ pub fn create_multi_buffers_bg_bg_layout(
|
||||
device: &wgpu::Device,
|
||||
buffers: &[&wgpu::Buffer],
|
||||
label: Option<&str>,
|
||||
) -> (wgpu::BindGroupLayout, wgpu::BindGroup)
|
||||
{
|
||||
) -> (wgpu::BindGroupLayout, wgpu::BindGroup) {
|
||||
let layout = create_multi_buffers_bind_group_layout(device, buffers.len() as u32, label);
|
||||
let bg = create_multi_buffers_bind_group(device, &layout, buffers, label);
|
||||
(layout, bg)
|
||||
@@ -1,47 +1,40 @@
|
||||
use std::num::NonZero;
|
||||
|
||||
use itertools::Itertools;
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePass;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::Device;
|
||||
use wgpu::QuerySet;
|
||||
use wgpu::ShaderStages;
|
||||
use wgpu::include_spirv;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RadixSortDirection
|
||||
{
|
||||
pub enum RadixSortDirection {
|
||||
Ascending,
|
||||
Descending,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
|
||||
#[repr(C)]
|
||||
struct PassParameters
|
||||
{
|
||||
struct PassParameters {
|
||||
pass_index: u32,
|
||||
descending: u32,
|
||||
digit_stride: u32,
|
||||
}
|
||||
|
||||
pub struct RadixSorter
|
||||
{
|
||||
pub struct RadixSorter {
|
||||
max_size: usize,
|
||||
histogram_count: usize,
|
||||
histo_block_count: usize,
|
||||
|
||||
#[allow(unused)]
|
||||
histograms: Buffer,
|
||||
histograms_bind_group: BindGroup,
|
||||
|
||||
data_bind_group_layout: BindGroupLayout,
|
||||
|
||||
#[allow(unused)]
|
||||
double_buffer_keys: Buffer,
|
||||
#[allow(unused)]
|
||||
double_buffer_values: Buffer,
|
||||
double_buffer_bind_group: BindGroup,
|
||||
|
||||
@@ -60,8 +53,7 @@ pub struct RadixSorter
|
||||
pub timing_buffer: Buffer,
|
||||
}
|
||||
|
||||
impl RadixSorter
|
||||
{
|
||||
impl RadixSorter {
|
||||
// How many total digits u32 => 32
|
||||
const TOTAL_BIN_DIGIT_COUNT: usize = 32;
|
||||
|
||||
@@ -83,8 +75,7 @@ impl RadixSorter
|
||||
// Elements managed per workgroup for histo build
|
||||
const WG_HISTO_ELEMENTS: usize = Self::WG_THREAD_COUNT * Self::WE_HISTO_ELEMENTS;
|
||||
|
||||
pub fn new(device: &Device, max_size: usize) -> Self
|
||||
{
|
||||
pub fn new(device: &Device, max_size: usize) -> Self {
|
||||
// How many blocks (workgroups) for histobuild
|
||||
let histo_block_count = max_size.div_ceil(Self::WG_HISTO_ELEMENTS);
|
||||
|
||||
@@ -225,7 +216,7 @@ impl RadixSorter
|
||||
});
|
||||
|
||||
let radix_sort_shader_module =
|
||||
device.create_shader_module(include_spirv!("../../shaders/radix_sort.spv"));
|
||||
device.create_shader_module(include_spirv!("../../../shaders/out/radix_sort.spv"));
|
||||
|
||||
let compilation_options = wgpu::PipelineCompilationOptions {
|
||||
zero_initialize_workgroup_memory: false,
|
||||
@@ -294,7 +285,6 @@ impl RadixSorter
|
||||
|
||||
RadixSorter {
|
||||
max_size,
|
||||
histo_block_count,
|
||||
histogram_count,
|
||||
histograms,
|
||||
histograms_bind_group,
|
||||
@@ -320,6 +310,12 @@ impl RadixSorter
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs a radix sort on the `key` based on the `values`.
|
||||
/// The keys are paired one-to-one with the values. At the end both keys and values are sorted.
|
||||
/// An indirect count can be passed in `indirect` as a buffer of a single u32 on GPU.
|
||||
/// A CPU side length can be passed in `direct_length`
|
||||
/// `sort_direction` dictates the direction of the sort.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn sort(
|
||||
&self,
|
||||
device: &Device,
|
||||
@@ -329,8 +325,7 @@ impl RadixSorter
|
||||
direct_length: Option<usize>,
|
||||
encoder: &mut CommandEncoder,
|
||||
sort_direction: RadixSortDirection,
|
||||
)
|
||||
{
|
||||
) {
|
||||
let data_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("RadixSorter::data_buffer_bind_group"),
|
||||
layout: &self.data_bind_group_layout,
|
||||
@@ -378,12 +373,9 @@ impl RadixSorter
|
||||
});
|
||||
|
||||
let parameters = PassParameters {
|
||||
pass_index: if indirect.is_some()
|
||||
{
|
||||
pass_index: if indirect.is_some() {
|
||||
0
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
direct_length.unwrap_or(self.max_size) as u32
|
||||
},
|
||||
descending: 0,
|
||||
@@ -420,12 +412,10 @@ impl RadixSorter
|
||||
}),
|
||||
});
|
||||
|
||||
for i in 0..Self::PASS_COUNT
|
||||
{
|
||||
for i in 0..Self::PASS_COUNT {
|
||||
let parameters = PassParameters {
|
||||
pass_index: i as u32,
|
||||
descending: match sort_direction
|
||||
{
|
||||
descending: match sort_direction {
|
||||
RadixSortDirection::Ascending => 0,
|
||||
RadixSortDirection::Descending => 1,
|
||||
},
|
||||
@@ -0,0 +1,143 @@
|
||||
// Top-k selection over a dense array of u32 request counts.
|
||||
//
|
||||
// The Rust side prepends the following constants:
|
||||
// const BIN_COUNT: u32;
|
||||
// const SUB_BINS: u32;
|
||||
// const LOG_SUB_BINS: u32;
|
||||
// const WORKGROUP_SIZE: u32;
|
||||
|
||||
@group(0) @binding(0) var<storage, read> requests: array<u32>;
|
||||
@group(0) @binding(1) var<storage, read_write> histogram: array<atomic<u32>>;
|
||||
@group(0) @binding(2) var<storage, read_write> threshold: i32;
|
||||
@group(0) @binding(3) var<storage, read_write> selected_count: atomic<u32>;
|
||||
@group(0) @binding(4) var<storage, read_write> selected_indices: array<u32>;
|
||||
|
||||
// Threshold fill state:
|
||||
// [0] = free slots for the threshold bin (k - above_count)
|
||||
// [1] = threshold-bin candidates claimed so far
|
||||
@group(0) @binding(5) var<storage, read_write> fill_state: array<atomic<u32>>;
|
||||
|
||||
struct TopKParams
|
||||
{
|
||||
element_count: u32,
|
||||
k: u32,
|
||||
}
|
||||
|
||||
var<immediate> params: TopKParams;
|
||||
|
||||
// Monotonic log-scale quantization. Counts of zero are never candidates, but
|
||||
// the function is kept total so it is safe to call with any value.
|
||||
fn quantize(count: u32) -> u32
|
||||
{
|
||||
if (count == 0u)
|
||||
{
|
||||
return 0u;
|
||||
}
|
||||
|
||||
let exponent = 31u - countLeadingZeros(count);
|
||||
var extra: u32;
|
||||
|
||||
if (exponent >= LOG_SUB_BINS)
|
||||
{
|
||||
extra = (count >> (exponent - LOG_SUB_BINS)) & (SUB_BINS - 1u);
|
||||
}
|
||||
else
|
||||
{
|
||||
extra = (count << (LOG_SUB_BINS - exponent)) & (SUB_BINS - 1u);
|
||||
}
|
||||
|
||||
return exponent * SUB_BINS + extra;
|
||||
}
|
||||
|
||||
// Pass 1: quantize every non-zero count and accumulate the global histogram.
|
||||
@compute
|
||||
@workgroup_size(WORKGROUP_SIZE, 1, 1)
|
||||
fn histogram_pass(@builtin(global_invocation_id) global_id: vec3<u32>)
|
||||
{
|
||||
let index = global_id.x;
|
||||
if (index >= params.element_count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let count = requests[index];
|
||||
if (count == 0u)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let bin = quantize(count);
|
||||
atomicAdd(&histogram[bin], 1u);
|
||||
}
|
||||
|
||||
// Pass 2: scan the histogram from the highest bin down until adding the
|
||||
// current bin would reach k. The current bin becomes the threshold.
|
||||
// A threshold of -1 means that every non-zero element is selected.
|
||||
//
|
||||
// `sum` is the number of elements in bins strictly above the threshold. It is
|
||||
// also the number of slots already guaranteed, so the threshold bin has
|
||||
// `k - sum` free slots left to fill.
|
||||
@compute
|
||||
@workgroup_size(1, 1, 1)
|
||||
fn threshold_pass()
|
||||
{
|
||||
var sum: u32 = 0u;
|
||||
var threshold_bin: i32 = -1;
|
||||
|
||||
for (var bin: u32 = BIN_COUNT; bin > 0u; bin = bin - 1u)
|
||||
{
|
||||
let count = atomicLoad(&histogram[bin - 1u]);
|
||||
|
||||
if (sum + count >= params.k)
|
||||
{
|
||||
threshold_bin = i32(bin - 1u);
|
||||
break;
|
||||
}
|
||||
|
||||
sum = sum + count;
|
||||
}
|
||||
|
||||
threshold = threshold_bin;
|
||||
atomicStore(&fill_state[0], params.k - min(params.k, sum));
|
||||
atomicStore(&fill_state[1], 0u);
|
||||
atomicStore(&selected_count, 0u);
|
||||
}
|
||||
|
||||
// Pass 3: emit every index whose quantized bin is strictly above the
|
||||
// threshold, then fill the remaining slots from the threshold bin in arbitrary
|
||||
// order. Together these emit exactly `min(k, non-zero count)` indices.
|
||||
@compute
|
||||
@workgroup_size(WORKGROUP_SIZE, 1, 1)
|
||||
fn select_pass(@builtin(global_invocation_id) global_id: vec3<u32>)
|
||||
{
|
||||
let index = global_id.x;
|
||||
if (index >= params.element_count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let count = requests[index];
|
||||
if (count == 0u)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let bin = i32(quantize(count));
|
||||
if (bin > threshold)
|
||||
{
|
||||
// Unconditionally selected.
|
||||
let slot = atomicAdd(&selected_count, 1u);
|
||||
selected_indices[slot] = index;
|
||||
}
|
||||
else if (bin == threshold)
|
||||
{
|
||||
// Fill the remaining slots from the threshold bin, in arbitrary order.
|
||||
let remaining = atomicLoad(&fill_state[0]);
|
||||
let offset = atomicAdd(&fill_state[1], 1u);
|
||||
if (offset < remaining)
|
||||
{
|
||||
let slot = atomicAdd(&selected_count, 1u);
|
||||
selected_indices[slot] = index;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,677 @@
|
||||
//! GPU top-k selection over a dense array of `u32` request counts.
|
||||
//!
|
||||
//! The selector runs three compute passes:
|
||||
//! 1. Quantize every non-zero count into [`BIN_COUNT`] log-scale bins and build
|
||||
//! a global histogram.
|
||||
//! 2. Scan the histogram from the highest bin down until adding the current bin
|
||||
//! would reach `k`, producing a threshold bin.
|
||||
//! 3. Emit every index whose bin is strictly above the threshold bin, then fill
|
||||
//! the remaining slots from the threshold bin.
|
||||
//!
|
||||
//! The number of selected elements is therefore exactly
|
||||
//! `min(k, number of non-zero elements)`. Elements taken from the threshold bin
|
||||
//! are chosen in arbitrary order; the caller is expected to sort the output if
|
||||
//! an ordering is required.
|
||||
//!
|
||||
//! The output list is unordered: indices are appended with atomics.
|
||||
//!
|
||||
//! The selector uses shader immediates, so the device must enable
|
||||
//! [`wgpu::Features::IMMEDIATES`] and expose a `max_immediate_size` of at least
|
||||
//! `size_of::<TopKParams>()` (8 bytes).
|
||||
|
||||
use bytemuck::bytes_of;
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::Device;
|
||||
use wgpu::ShaderStages;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
/// Number of quantization bins.
|
||||
pub const BIN_COUNT: u32 = 256;
|
||||
|
||||
/// Number of sub-bins per power-of-two octave.
|
||||
const SUB_BINS: u32 = BIN_COUNT / 32;
|
||||
|
||||
/// Number of mantissa bits kept by the quantizer.
|
||||
const LOG_SUB_BINS: u32 = SUB_BINS.trailing_zeros();
|
||||
|
||||
/// Threads per workgroup for the histogram and selection passes.
|
||||
const WORKGROUP_SIZE: u32 = 256;
|
||||
|
||||
const _: () = assert!(BIN_COUNT.is_multiple_of(32));
|
||||
const _: () = assert!(SUB_BINS.is_power_of_two());
|
||||
|
||||
/// Parameters passed to the shader through immediates.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct TopKParams {
|
||||
element_count: u32,
|
||||
k: u32,
|
||||
}
|
||||
|
||||
/// GPU top-k selector over a dense array of request counts.
|
||||
///
|
||||
/// The selector owns its scratch and output buffers, so a single instance
|
||||
/// cannot be used for two overlapping selections. Create one instance per
|
||||
/// concurrent selection, or copy the results before the next call.
|
||||
pub struct TopKSelector {
|
||||
max_selected: u32,
|
||||
|
||||
histogram: Buffer,
|
||||
threshold: Buffer,
|
||||
selected_count: Buffer,
|
||||
selected_indices: Buffer,
|
||||
/// `[0]` free threshold-bin slots, `[1]` claimed threshold-bin candidates.
|
||||
fill_state: Buffer,
|
||||
|
||||
bind_group_layout: BindGroupLayout,
|
||||
histogram_pass: ComputePipeline,
|
||||
threshold_pass: ComputePipeline,
|
||||
select_pass: ComputePipeline,
|
||||
}
|
||||
|
||||
impl TopKSelector {
|
||||
/// Creates a selector that can output at most `max_selected` indices.
|
||||
pub fn new(device: &Device, max_selected: u32) -> Self {
|
||||
assert!(
|
||||
device.features().contains(wgpu::Features::IMMEDIATES),
|
||||
"TopKSelector requires the IMMEDIATES feature"
|
||||
);
|
||||
assert!(
|
||||
device.limits().max_immediate_size >= size_of::<TopKParams>() as u32,
|
||||
"TopKSelector requires a max_immediate_size of at least {} bytes",
|
||||
size_of::<TopKParams>()
|
||||
);
|
||||
|
||||
let histogram = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("TopKSelector::histogram"),
|
||||
size: (BIN_COUNT as u64) * (size_of::<u32>() as u64),
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let threshold = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("TopKSelector::threshold"),
|
||||
contents: bytes_of(&-1i32),
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
});
|
||||
|
||||
let selected_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("TopKSelector::selected_count"),
|
||||
contents: bytes_of(&0u32),
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
});
|
||||
|
||||
// Avoid zero-sized buffers when `max_selected == 0`.
|
||||
let selected_indices = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("TopKSelector::selected_indices"),
|
||||
size: (max_selected.max(1) as u64) * (size_of::<u32>() as u64),
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
// [0] free threshold-bin slots, [1] claimed threshold-bin candidates.
|
||||
// Both are reset by `threshold_pass` on every call.
|
||||
let fill_state = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("TopKSelector::fill_state"),
|
||||
contents: bytemuck::cast_slice(&[0u32; 2]),
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
});
|
||||
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("TopKSelector::bind_group_layout"),
|
||||
entries: &[
|
||||
// Requests: read-only dense array of counts
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: true },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Histogram
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Threshold bin
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Selected count
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 3,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Selected indices
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 4,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Threshold fill state
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 5,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("TopKSelector::pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&bind_group_layout)],
|
||||
immediate_size: size_of::<TopKParams>() as u32,
|
||||
});
|
||||
|
||||
// Inject the quantization constants so the Rust and WGSL sides cannot
|
||||
// drift apart.
|
||||
let header = format!(
|
||||
"const BIN_COUNT: u32 = {}u;\n\
|
||||
const SUB_BINS: u32 = {}u;\n\
|
||||
const LOG_SUB_BINS: u32 = {}u;\n\
|
||||
const WORKGROUP_SIZE: u32 = {}u;\n",
|
||||
BIN_COUNT, SUB_BINS, LOG_SUB_BINS, WORKGROUP_SIZE
|
||||
);
|
||||
|
||||
let mut shader_source = String::with_capacity(header.len() + 2048);
|
||||
shader_source.push_str(&header);
|
||||
shader_source.push_str(include_str!("./shaders/top_k.wgsl"));
|
||||
|
||||
let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("TopKSelector::shader_module"),
|
||||
source: wgpu::ShaderSource::Wgsl(shader_source.into()),
|
||||
});
|
||||
|
||||
let compilation_options = wgpu::PipelineCompilationOptions::default();
|
||||
|
||||
let histogram_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("TopKSelector::histogram_pass"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("histogram_pass"),
|
||||
compilation_options: compilation_options.clone(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let threshold_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("TopKSelector::threshold_pass"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("threshold_pass"),
|
||||
compilation_options: compilation_options.clone(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let select_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("TopKSelector::select_pass"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("select_pass"),
|
||||
compilation_options,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
max_selected,
|
||||
histogram,
|
||||
threshold,
|
||||
selected_count,
|
||||
selected_indices,
|
||||
fill_state,
|
||||
bind_group_layout,
|
||||
histogram_pass,
|
||||
threshold_pass,
|
||||
select_pass,
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the three top-k passes over `requests[0..element_count]`.
|
||||
///
|
||||
/// `k` is the requested number of elements and must not exceed the
|
||||
/// `max_selected` capacity given to [`TopKSelector::new`].
|
||||
///
|
||||
/// After this call:
|
||||
/// - [`Self::selected_count_buffer`] contains
|
||||
/// `min(k, number of non-zero elements)`.
|
||||
/// - [`Self::selected_indices_buffer`] contains that many indices, in an
|
||||
/// arbitrary order.
|
||||
/// - [`Self::threshold_buffer`] contains the threshold bin, or `-1` if all
|
||||
/// non-zero elements were selected.
|
||||
pub fn select(
|
||||
&self,
|
||||
device: &Device,
|
||||
encoder: &mut CommandEncoder,
|
||||
requests: &Buffer,
|
||||
element_count: u32,
|
||||
k: u32,
|
||||
) {
|
||||
assert!(
|
||||
k <= self.max_selected,
|
||||
"TopKSelector: k ({k}) exceeds the max_selected capacity ({})",
|
||||
self.max_selected
|
||||
);
|
||||
assert!(
|
||||
requests.size() >= (element_count as u64) * (size_of::<u32>() as u64),
|
||||
"TopKSelector: requests buffer is too small for {element_count} elements"
|
||||
);
|
||||
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("TopKSelector::bind_group"),
|
||||
layout: &self.bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: requests.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: self.histogram.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: self.threshold.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: self.selected_count.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: self.selected_indices.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 5,
|
||||
resource: self.fill_state.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// The histogram is rebuilt from scratch on every call.
|
||||
encoder.clear_buffer(&self.histogram, 0, None);
|
||||
|
||||
let params = TopKParams { element_count, k };
|
||||
let params_bytes = bytes_of(¶ms);
|
||||
let workgroup_count = element_count.div_ceil(WORKGROUP_SIZE).max(1);
|
||||
|
||||
let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("TopKSelector::select"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
compute_pass.set_bind_group(0, &bind_group, &[]);
|
||||
|
||||
compute_pass.set_pipeline(&self.histogram_pass);
|
||||
compute_pass.set_immediates(0, params_bytes);
|
||||
compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
|
||||
|
||||
compute_pass.set_pipeline(&self.threshold_pass);
|
||||
compute_pass.set_immediates(0, params_bytes);
|
||||
compute_pass.dispatch_workgroups(1, 1, 1);
|
||||
|
||||
compute_pass.set_pipeline(&self.select_pass);
|
||||
compute_pass.set_immediates(0, params_bytes);
|
||||
compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
|
||||
}
|
||||
|
||||
/// Number of indices emitted by the last [`Self::select`] call.
|
||||
pub fn selected_count_buffer(&self) -> &Buffer {
|
||||
&self.selected_count
|
||||
}
|
||||
|
||||
/// Indices emitted by the last [`Self::select`] call, in arbitrary order.
|
||||
pub fn selected_indices_buffer(&self) -> &Buffer {
|
||||
&self.selected_indices
|
||||
}
|
||||
|
||||
/// Threshold bin of the last [`Self::select`] call, or `-1` if every
|
||||
/// non-zero element was selected.
|
||||
pub fn threshold_buffer(&self) -> &Buffer {
|
||||
&self.threshold
|
||||
}
|
||||
|
||||
/// Maximum number of indices this selector can emit.
|
||||
pub fn max_selected(&self) -> u32 {
|
||||
self.max_selected
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// CPU mirror of the WGSL quantizer.
|
||||
fn quantize_cpu(count: u32) -> u32 {
|
||||
if count == 0 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let exponent = 31 - count.leading_zeros();
|
||||
let extra = if exponent >= LOG_SUB_BINS {
|
||||
(count >> (exponent - LOG_SUB_BINS)) & (SUB_BINS - 1)
|
||||
} else {
|
||||
(count << (LOG_SUB_BINS - exponent)) & (SUB_BINS - 1)
|
||||
};
|
||||
|
||||
exponent * SUB_BINS + extra
|
||||
}
|
||||
|
||||
/// CPU mirror of the three passes.
|
||||
fn select_cpu(counts: &[u32], k: u32) -> (Vec<u32>, i32) {
|
||||
let mut histogram = vec![0u32; BIN_COUNT as usize];
|
||||
|
||||
for &count in counts {
|
||||
if count != 0 {
|
||||
histogram[quantize_cpu(count) as usize] += 1;
|
||||
}
|
||||
}
|
||||
|
||||
let mut sum = 0u32;
|
||||
let mut threshold = -1i32;
|
||||
|
||||
for bin in (0..BIN_COUNT as usize).rev() {
|
||||
let count = histogram[bin];
|
||||
|
||||
if sum + count >= k {
|
||||
threshold = bin as i32;
|
||||
break;
|
||||
}
|
||||
|
||||
sum += count;
|
||||
}
|
||||
|
||||
let remaining = k.saturating_sub(sum);
|
||||
|
||||
let mut selected = counts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|&(_, &count)| count != 0 && quantize_cpu(count) as i32 > threshold)
|
||||
.map(|(index, _)| index as u32)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Fill the remaining slots from the threshold bin. The GPU picks these
|
||||
// in arbitrary order; the CPU mirror fills them in index order so the
|
||||
// tests stay deterministic.
|
||||
if threshold >= 0 {
|
||||
let mut slots = remaining;
|
||||
for (index, &count) in counts.iter().enumerate() {
|
||||
if slots == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
if count != 0 && quantize_cpu(count) as i32 == threshold {
|
||||
selected.push(index as u32);
|
||||
slots -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(selected, threshold)
|
||||
}
|
||||
|
||||
fn next_random(state: &mut u64) -> u32 {
|
||||
*state ^= *state << 13;
|
||||
*state ^= *state >> 7;
|
||||
*state ^= *state << 17;
|
||||
(*state >> 32) as u32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quantize_is_monotonic() {
|
||||
let mut previous = 0;
|
||||
|
||||
for count in 1..100_000u32 {
|
||||
let bin = quantize_cpu(count);
|
||||
assert!(bin >= previous, "quantize({count}) = {bin} < {previous}");
|
||||
assert!(bin < BIN_COUNT);
|
||||
previous = bin;
|
||||
}
|
||||
|
||||
let mut state = 0x1234_5678_9abc_def0u64;
|
||||
let mut values = (0..10_000)
|
||||
.map(|_| next_random(&mut state))
|
||||
.collect::<Vec<_>>();
|
||||
values.sort_unstable();
|
||||
|
||||
let mut previous = 0;
|
||||
for count in values {
|
||||
let bin = quantize_cpu(count);
|
||||
assert!(bin >= previous);
|
||||
assert!(bin < BIN_COUNT);
|
||||
previous = bin;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quantize_handles_zero_and_max() {
|
||||
assert_eq!(quantize_cpu(0), 0);
|
||||
assert!(quantize_cpu(u32::MAX) < BIN_COUNT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_selects_exactly_min_k_and_non_zero() {
|
||||
let mut state = 0x0ddc_0ffe_e15e_beefu64;
|
||||
|
||||
for _ in 0..100 {
|
||||
let len = 1 + (next_random(&mut state) % 1000) as usize;
|
||||
let counts = (0..len)
|
||||
.map(|_| next_random(&mut state) % 64)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let non_zero = counts.iter().filter(|&&count| count != 0).count();
|
||||
|
||||
for k in 0..=20 {
|
||||
let (selected, threshold) = select_cpu(&counts, k);
|
||||
|
||||
assert_eq!(selected.len(), (k as usize).min(non_zero));
|
||||
|
||||
let mut sorted = selected.clone();
|
||||
sorted.sort_unstable();
|
||||
sorted.dedup();
|
||||
assert_eq!(sorted.len(), selected.len(), "duplicate indices");
|
||||
|
||||
for &index in &selected {
|
||||
let count = counts[index as usize];
|
||||
assert!(count != 0);
|
||||
assert!(quantize_cpu(count) as i32 >= threshold);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_fills_threshold_bin_to_exactly_k() {
|
||||
let counts = [1, 5, 3, 5, 2];
|
||||
let (selected, _) = select_cpu(&counts, 3);
|
||||
|
||||
// The two 5s are above the threshold bin; the 3 fills the last slot.
|
||||
let mut sorted = selected;
|
||||
sorted.sort_unstable();
|
||||
assert_eq!(sorted, vec![1, 2, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_with_fewer_candidates_than_k() {
|
||||
let counts = [1, 0, 2, 0, 3];
|
||||
let (selected, threshold) = select_cpu(&counts, 10);
|
||||
|
||||
assert_eq!(threshold, -1);
|
||||
assert_eq!(selected.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_with_k_zero() {
|
||||
let counts = [1, 2, 3];
|
||||
let (selected, _) = select_cpu(&counts, 0);
|
||||
|
||||
assert!(selected.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_with_all_equal_counts_selects_k() {
|
||||
let counts = [7, 7, 7, 7];
|
||||
let (selected, threshold) = select_cpu(&counts, 2);
|
||||
|
||||
// Every element is in the threshold bin, so the first two are taken.
|
||||
assert_eq!(threshold, quantize_cpu(7) as i32);
|
||||
assert_eq!(selected, vec![0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_with_all_zero_counts() {
|
||||
let counts = [0, 0, 0, 0];
|
||||
let (selected, threshold) = select_cpu(&counts, 2);
|
||||
|
||||
assert_eq!(threshold, -1);
|
||||
assert!(selected.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a GPU adapter with the IMMEDIATES feature"]
|
||||
fn gpu_selection_smoke_test() {
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
|
||||
let adapter =
|
||||
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default()))
|
||||
.expect("no GPU adapter available");
|
||||
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
|
||||
required_features: wgpu::Features::IMMEDIATES,
|
||||
required_limits: wgpu::Limits {
|
||||
max_immediate_size: 112,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
}))
|
||||
.expect("failed to create GPU device");
|
||||
|
||||
let counts: [u32; 5] = [1, 5, 3, 5, 2];
|
||||
let requests = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("TopKSelector::test_requests"),
|
||||
contents: bytemuck::cast_slice(&counts),
|
||||
usage: BufferUsages::STORAGE,
|
||||
});
|
||||
|
||||
let selector = TopKSelector::new(&device, 8);
|
||||
|
||||
// Run the selection twice to verify that the histogram and fill state
|
||||
// are reset between calls.
|
||||
for _ in 0..2 {
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("TopKSelector::test_encoder"),
|
||||
});
|
||||
selector.select(&device, &mut encoder, &requests, counts.len() as u32, 3);
|
||||
queue.submit([encoder.finish()]);
|
||||
|
||||
let (count, indices) = read_selection(&device, &queue, &selector);
|
||||
|
||||
// The two 5s are above the threshold bin; the 3 fills the last slot.
|
||||
assert_eq!(count, 3);
|
||||
assert_eq!(indices, vec![1, 2, 3]);
|
||||
}
|
||||
|
||||
// All-equal counts: the threshold bin must fill every slot.
|
||||
let equal_counts: [u32; 4] = [7, 7, 7, 7];
|
||||
let equal_requests = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("TopKSelector::test_equal_requests"),
|
||||
contents: bytemuck::cast_slice(&equal_counts),
|
||||
usage: BufferUsages::STORAGE,
|
||||
});
|
||||
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("TopKSelector::test_encoder"),
|
||||
});
|
||||
selector.select(
|
||||
&device,
|
||||
&mut encoder,
|
||||
&equal_requests,
|
||||
equal_counts.len() as u32,
|
||||
2,
|
||||
);
|
||||
queue.submit([encoder.finish()]);
|
||||
|
||||
let (count, indices) = read_selection(&device, &queue, &selector);
|
||||
assert_eq!(count, 2);
|
||||
assert_eq!(indices.len(), 2);
|
||||
assert!(
|
||||
indices
|
||||
.iter()
|
||||
.all(|&index| index < equal_counts.len() as u32)
|
||||
);
|
||||
}
|
||||
|
||||
/// Reads back the selected count and the sorted selected indices.
|
||||
fn read_selection(
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
selector: &TopKSelector,
|
||||
) -> (u32, Vec<u32>) {
|
||||
let count = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
let count_clone = count.clone();
|
||||
wgpu::util::DownloadBuffer::read_buffer(
|
||||
device,
|
||||
queue,
|
||||
&selector.selected_count_buffer().slice(..),
|
||||
move |buffer| {
|
||||
let bytes = buffer.unwrap();
|
||||
*count_clone.lock().unwrap() = Some(bytemuck::pod_read_unaligned::<u32>(&bytes));
|
||||
},
|
||||
);
|
||||
|
||||
let indices = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
let indices_clone = indices.clone();
|
||||
wgpu::util::DownloadBuffer::read_buffer(
|
||||
device,
|
||||
queue,
|
||||
&selector.selected_indices_buffer().slice(..),
|
||||
move |buffer| {
|
||||
let bytes = buffer.unwrap();
|
||||
*indices_clone.lock().unwrap() =
|
||||
Some(bytemuck::pod_collect_to_vec::<u8, u32>(&bytes));
|
||||
},
|
||||
);
|
||||
|
||||
device
|
||||
.poll(wgpu::wgt::PollType::wait_indefinitely())
|
||||
.unwrap();
|
||||
|
||||
let count = *count.lock().unwrap().as_ref().unwrap();
|
||||
let mut indices = indices.lock().unwrap().as_ref().unwrap()[0..count as usize].to_vec();
|
||||
indices.sort_unstable();
|
||||
|
||||
(count, indices)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "vxls-production"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
bytemuck.workspace = true
|
||||
itertools.workspace = true
|
||||
rayon.workspace = true
|
||||
wgpu.workspace = true
|
||||
vxls-attributes = { path = "../vxls-attributes" }
|
||||
vxls-voxel-cache = { path = "../vxls-voxel-cache" }
|
||||
binrw = "0.15.2"
|
||||
crc32fast = "1.5.1"
|
||||
@@ -0,0 +1,214 @@
|
||||
//!
|
||||
//! # VXLS sparse-tree file format
|
||||
//!
|
||||
//! Status: implemented by `io::read` and `io::write`; this module documents
|
||||
//! the wire format they share.
|
||||
//!
|
||||
//! The layout mirrors `sparse_tree::NTree`: every node owns one attribute and
|
||||
//! one `subdivided` flag. Subdividing a node creates all `N³` children at
|
||||
//! once, so there is no per-child presence mask and no notion of a "missing"
|
||||
//! child. A leaf's attribute applies to its whole subtree; an interior node's
|
||||
//! attribute is the average of its children's, as `NTree` already maintains.
|
||||
//!
|
||||
//! The format records only tree structure, attribute word counts and labels.
|
||||
//! What the words mean and how they map onto rendering is the loader's
|
||||
//! business, not the file's.
|
||||
//!
|
||||
//! A file holds exactly one tree; there is no forest container. Compression is
|
||||
//! deliberately out of scope for this version. The format is expected to
|
||||
//! change, so when compression lands it can be a new chunk tag or a flag in an
|
||||
//! offset-table entry rather than a compatibility problem.
|
||||
//!
|
||||
//! ## Conventions
|
||||
//!
|
||||
//! - Little-endian throughout, including raw attribute words.
|
||||
//! - Structures are packed unless a `reserved` field is listed. Chunk bodies
|
||||
//! are not padded internally; chunks are separated by zero padding so that
|
||||
//! each chunk starts 8-byte aligned (see the chunk frame).
|
||||
//! - Offsets are byte offsets from the start of the file.
|
||||
//! - Sizes are in bytes unless the field name says otherwise.
|
||||
//! - Strings are UTF-8: a `u32` byte count followed by that many bytes, no
|
||||
//! terminator, no padding.
|
||||
//!
|
||||
//! ## Preamble (24 bytes)
|
||||
//!
|
||||
//! ```text
|
||||
//! offset size field
|
||||
//! 0 4 magic b"VXLS"
|
||||
//! 4 4 file_type b"ST\0\0" (sparse tree)
|
||||
//! 8 4 major_version incompatible changes
|
||||
//! 12 4 minor_version compatible additions
|
||||
//! 16 8 total_file_size exact on-disk length
|
||||
//! ```
|
||||
//!
|
||||
//! 24 bytes keeps the `u64` and everything after it naturally aligned.
|
||||
//!
|
||||
//! ## Header (at offset 24)
|
||||
//!
|
||||
//! ```text
|
||||
//! u32 header_size size of the header in bytes, including this field (>= 12)
|
||||
//! u32 tree_arity N, at least 2
|
||||
//! u32 tree_depth maximum depth, 0 = a single root node
|
||||
//! ```
|
||||
//!
|
||||
//! `tree_depth` is the capacity: nodes live at levels `0 ..= tree_depth`, and
|
||||
//! `N^tree_depth` voxels span one axis. The tree may stop shallower than that
|
||||
//! (see level chunks).
|
||||
//!
|
||||
//! Readers must skip `header_size - 12` unknown bytes instead of rejecting the
|
||||
//! file; that is how later versions append fields.
|
||||
//!
|
||||
//! ## Offset table (at offset `24 + header_size`)
|
||||
//!
|
||||
//! ```text
|
||||
//! u32 offset_table_size size of the entries in bytes, excluding this field;
|
||||
//! must be a multiple of 24
|
||||
//! entry { // packed, 24 bytes each
|
||||
//! u32 chunk_type_tag
|
||||
//! u32 reserved // 0; future flags (e.g. compression)
|
||||
//! u64 file_offset // always a multiple of 8
|
||||
//! u64 chunk_size // same value as the chunk frame's own size
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! One entry per chunk, ordered by `file_offset`; chunks themselves may appear
|
||||
//! in any order. The table is authoritative for seeking, and a reader checks
|
||||
//! that the frame at `file_offset` still matches the entry. The first chunk
|
||||
//! starts at the first 8-byte boundary at or after the end of this table, with
|
||||
//! the same zero padding rule as between chunks.
|
||||
//!
|
||||
//! ## Chunk frame
|
||||
//!
|
||||
//! ```text
|
||||
//! u32 chunk_type_tag
|
||||
//! u64 chunk_size // 12 + body length; excludes the CRC word
|
||||
//! [body: chunk_size - 12 bytes]
|
||||
//! u32 chunk_crc32 // CRC-32/ISO-HDLC (zlib) over tag + size + body
|
||||
//! ```
|
||||
//!
|
||||
//! The CRC uses the reflected polynomial `0xEDB88320`, init `0xFFFFFFFF`,
|
||||
//! final XOR `0xFFFFFFFF`. A mismatch is a hard error for required chunks.
|
||||
//!
|
||||
//! Chunk starts are 8-byte aligned: when a chunk's CRC ends at offset `e`,
|
||||
//! the next chunk starts at `align_up(e, 8)`. The gap (0 to 7 bytes) is
|
||||
//! zero-filled padding that belongs to no chunk, is not counted by any
|
||||
//! `chunk_size` and is not covered by any CRC, so `chunk_size` remains exactly
|
||||
//! `12 + body length`. There is no padding after the final chunk, and
|
||||
//! `total_file_size` includes the inter-chunk padding.
|
||||
//!
|
||||
//! Only the chunk start is aligned: a body begins 12 bytes into an 8-byte
|
||||
//! aligned chunk, so bodies are 4-byte aligned. That is enough to read `u32`
|
||||
//! attribute words directly, but not `u64` values.
|
||||
//!
|
||||
//! ## Chunk tags
|
||||
//!
|
||||
//! | tag | meaning |
|
||||
//! |------------------------|-------------------------------------------|
|
||||
//! | `0x0000_0000` | invalid |
|
||||
//! | `0x0000_0001` | attributes (required, exactly one) |
|
||||
//! | `0x8000_0000 \| level` | nodes at `level`, 0 = root |
|
||||
//!
|
||||
//! Tags with the high bit clear are non-tree chunks; unknown ones are skipped.
|
||||
//!
|
||||
//! ## Attributes chunk (tag 1)
|
||||
//!
|
||||
//! Describes the payload in cache binding order: attribute 0 is the first
|
||||
//! binding the shaders read, and that order is load-bearing.
|
||||
//!
|
||||
//! ```text
|
||||
//! u32 attribute_count
|
||||
//! attribute_count × {
|
||||
//! u32 word_count // 32-bit words per voxel
|
||||
//! u32 label_size
|
||||
//! u8 label[label_size]
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! Payload stride is `Σ word_count` words. The words are opaque: `word_count`
|
||||
//! says how many, not what they mean, so a `u32` colour and an `[f32; 3]`
|
||||
//! normal look identical. `label` is a human-readable hint; the format does
|
||||
//! not interpret it. `word_count` must be at least 1, and `label` must be
|
||||
//! valid UTF-8 (it may be empty). A single-attribute tree has
|
||||
//! `attribute_count == 1`.
|
||||
//!
|
||||
//! ## Level chunks (tag `0x8000_0000 | level`)
|
||||
//!
|
||||
//! Structure-of-arrays, one chunk per level. Nodes are stored breadth-first:
|
||||
//! the `N³` children of subdivided node `k` at level `L` (where `k` counts
|
||||
//! only subdivided nodes, in order) are nodes `N³·k .. N³·(k+1)` at level
|
||||
//! `L + 1`, in child order `c = x + N*y + N²*z` (x fastest, then y, then z) —
|
||||
//! the order `TreeLocator::children` produces.
|
||||
//!
|
||||
//! ```text
|
||||
//! u32 node_count
|
||||
//! u32 subdivided[(node_count + 31) / 32] // 1 bit per node, LSB first
|
||||
//! attr_0[node_count * word_count_0]
|
||||
//! attr_1[node_count * word_count_1]
|
||||
//! ...
|
||||
//! ```
|
||||
//!
|
||||
//! - Bit `i` of `subdivided` is node `i`'s `subdivided` flag; unused trailing
|
||||
//! bits are zero.
|
||||
//! - `node_count` at level 0 is 1, and the chunk then holds exactly the root's
|
||||
//! flag word followed by its attributes.
|
||||
//! - `node_count` at level `L + 1` is `N³ × popcount(subdivided at level L)`.
|
||||
//! - Attribute arrays hold one payload per node in attribute order, raw
|
||||
//! little-endian words, no padding between arrays.
|
||||
//! - Level chunks are a contiguous prefix `0 ..= D`: level `L + 1` exists iff
|
||||
//! level `L` has at least one bit set. `D` may be shallower than
|
||||
//! `tree_depth`, in which case every node at `D` is a leaf whose attribute
|
||||
//! covers its subtree. Every bit at `D` must be zero, so `D == tree_depth`
|
||||
//! is valid only when the tree bottoms out exactly at its capacity.
|
||||
//!
|
||||
//! A constant tree is `tree_depth == 0`: one level-0 chunk with `node_count == 1`,
|
||||
//! a zero flag word and one payload.
|
||||
//!
|
||||
//! ## Validation
|
||||
//!
|
||||
//! Check magic and type; `total_file_size` equals the real length;
|
||||
//! `header_size >= 12` and inside the file; `tree_arity >= 2`;
|
||||
//! `tree_depth <= TreeLocator::<N>::max_depth()`; `offset_table_size` is a
|
||||
//! multiple of 24; every `file_offset` is a multiple of 8 and every offset and
|
||||
//! size lies inside the file; the gaps between chunks are shorter than 8 bytes
|
||||
//! and zero-filled; chunk tags are unique; level chunks are the contiguous
|
||||
//! prefix `0 ..= D` with `D <= tree_depth` and every flag at `D` clear;
|
||||
//! level-0 `node_count == 1`; each level's `node_count` equals `N³ × popcount`
|
||||
//! of the previous level's flags; each level's `chunk_size` equals
|
||||
//! `12 + 4 + mask_words*4 + node_count × Σ word_count × 4`, where
|
||||
//! `mask_words = ceil(node_count / 32)`; CRCs of required chunks. Same major is
|
||||
//! required, a newer minor is accepted by skipping unknown tags.
|
||||
//!
|
||||
//! `total_file_size` is the offset just past the final chunk's CRC, including
|
||||
//! inter-chunk padding and with no trailing padding.
|
||||
//!
|
||||
//! ## Implementation notes
|
||||
//!
|
||||
//! - `binrw` derives cover the fixed-shape sections; the attributes and level
|
||||
//! bodies use manual `BinRead`/`BinWrite` impls because they are
|
||||
//! structure-of-arrays with counts taken from the stream.
|
||||
//! - CRC-32 comes from the `crc32fast` crate.
|
||||
//!
|
||||
//! ## Implementation map
|
||||
//!
|
||||
//! | module | contents |
|
||||
//! |---|---|
|
||||
//! | `io::format` | wire structs, tags, constants |
|
||||
//! | `io::chunk` | frame read/write, 8-byte padding, CRC |
|
||||
//! | `io::write` | [`write_tree`], [`write_tree_to_path`] |
|
||||
//! | `io::read` | [`read_tree`], [`read_tree_from_path`], [`TreeFile`] |
|
||||
//! | `io::error` | [`TreeFileError`] |
|
||||
|
||||
mod chunk;
|
||||
mod error;
|
||||
mod format;
|
||||
mod read;
|
||||
mod write;
|
||||
|
||||
pub use error::TreeFileError;
|
||||
pub use format::FileAttribute;
|
||||
pub use read::FileLayout;
|
||||
pub use read::TreeFile;
|
||||
pub use read::read_tree;
|
||||
pub use read::read_tree_from_path;
|
||||
pub use write::write_tree;
|
||||
pub use write::write_tree_to_path;
|
||||
@@ -0,0 +1,178 @@
|
||||
//! Chunk framing: 8-byte alignment, tag/size headers and CRC-32.
|
||||
|
||||
use std::io::Read;
|
||||
use std::io::Seek;
|
||||
use std::io::Write;
|
||||
|
||||
use binrw::BinRead;
|
||||
use binrw::BinWrite;
|
||||
use binrw::Endian;
|
||||
|
||||
use super::error::TreeFileError;
|
||||
use super::format::CHUNK_FRAME_SIZE;
|
||||
use super::format::ChunkFrame;
|
||||
|
||||
/// Alignment of a chunk start.
|
||||
pub const CHUNK_ALIGNMENT: u64 = 8;
|
||||
|
||||
const ZEROES: [u8; 8] = [0; 8];
|
||||
|
||||
/// A chunk read from a file, with its CRC already verified.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Chunk {
|
||||
pub tag: u32,
|
||||
pub size: u64,
|
||||
pub body: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Rounds `value` up to the next multiple of `align`, which must be a power of two.
|
||||
pub const fn align_up(value: u64, align: u64) -> u64 {
|
||||
(value + align - 1) & !(align - 1)
|
||||
}
|
||||
|
||||
/// Writes zero padding until the writer is 8-byte aligned.
|
||||
pub fn write_padding_to_alignment<W: Write + Seek>(writer: &mut W) -> Result<(), TreeFileError> {
|
||||
let position = writer.stream_position()?;
|
||||
let target = align_up(position, CHUNK_ALIGNMENT);
|
||||
let padding = (target - position) as usize;
|
||||
|
||||
if padding > 0 {
|
||||
writer.write_all(&ZEROES[..padding])?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes a complete chunk at the current position, which must already be aligned.
|
||||
pub fn write_chunk<W: Write + Seek>(
|
||||
writer: &mut W,
|
||||
tag: u32,
|
||||
body: &[u8],
|
||||
) -> Result<(), TreeFileError> {
|
||||
let position = writer.stream_position()?;
|
||||
|
||||
if position % CHUNK_ALIGNMENT != 0 {
|
||||
return Err(TreeFileError::MisalignedOffset { offset: position });
|
||||
}
|
||||
|
||||
let chunk_size = CHUNK_FRAME_SIZE + body.len() as u64;
|
||||
|
||||
ChunkFrame {
|
||||
chunk_type_tag: tag,
|
||||
chunk_size,
|
||||
}
|
||||
.write_options(writer, Endian::Little, ())?;
|
||||
|
||||
writer.write_all(body)?;
|
||||
|
||||
let mut hasher = crc32fast::Hasher::new();
|
||||
hasher.update(&tag.to_le_bytes());
|
||||
hasher.update(&chunk_size.to_le_bytes());
|
||||
hasher.update(body);
|
||||
|
||||
writer.write_all(&hasher.finalize().to_le_bytes())?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads a chunk at the current position, verifying its frame and CRC.
|
||||
///
|
||||
/// The reader is left just past the chunk's CRC word, before any padding.
|
||||
pub fn read_chunk<R: Read + Seek>(reader: &mut R, file_len: u64) -> Result<Chunk, TreeFileError> {
|
||||
let offset = reader.stream_position()?;
|
||||
|
||||
if offset % CHUNK_ALIGNMENT != 0 {
|
||||
return Err(TreeFileError::MisalignedOffset { offset });
|
||||
}
|
||||
|
||||
let frame = ChunkFrame::read_options(reader, Endian::Little, ())?;
|
||||
|
||||
if frame.chunk_size < CHUNK_FRAME_SIZE {
|
||||
return Err(TreeFileError::ChunkSizeTooSmall {
|
||||
tag: frame.chunk_type_tag,
|
||||
size: frame.chunk_size,
|
||||
});
|
||||
}
|
||||
|
||||
let end = offset
|
||||
.checked_add(frame.chunk_size)
|
||||
.and_then(|value| value.checked_add(4))
|
||||
.ok_or(TreeFileError::Overflow { what: "chunk end" })?;
|
||||
|
||||
if end > file_len {
|
||||
return Err(TreeFileError::ChunkOutOfBounds {
|
||||
tag: frame.chunk_type_tag,
|
||||
offset,
|
||||
size: frame.chunk_size,
|
||||
});
|
||||
}
|
||||
|
||||
let body_len = usize::try_from(frame.chunk_size - CHUNK_FRAME_SIZE).map_err(|_| {
|
||||
TreeFileError::Overflow {
|
||||
what: "chunk body length",
|
||||
}
|
||||
})?;
|
||||
|
||||
let mut body = vec![0u8; body_len];
|
||||
reader.read_exact(&mut body)?;
|
||||
|
||||
let mut crc_bytes = [0u8; 4];
|
||||
reader.read_exact(&mut crc_bytes)?;
|
||||
let found = u32::from_le_bytes(crc_bytes);
|
||||
|
||||
let mut hasher = crc32fast::Hasher::new();
|
||||
hasher.update(&frame.chunk_type_tag.to_le_bytes());
|
||||
hasher.update(&frame.chunk_size.to_le_bytes());
|
||||
hasher.update(&body);
|
||||
let expected = hasher.finalize();
|
||||
|
||||
if expected != found {
|
||||
return Err(TreeFileError::CrcMismatch {
|
||||
tag: frame.chunk_type_tag,
|
||||
offset,
|
||||
expected,
|
||||
found,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(Chunk {
|
||||
tag: frame.chunk_type_tag,
|
||||
size: frame.chunk_size,
|
||||
body,
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads the gap between `position` and `target`, requiring every byte to be zero.
|
||||
///
|
||||
/// The caller guarantees `position <= target < position + 8`.
|
||||
pub fn read_padding<R: Read + Seek>(reader: &mut R, target: u64) -> Result<(), TreeFileError> {
|
||||
let position = reader.stream_position()?;
|
||||
|
||||
if target < position {
|
||||
return Err(TreeFileError::ChunkOffsetMismatch {
|
||||
tag: 0,
|
||||
expected: target,
|
||||
found: position,
|
||||
});
|
||||
}
|
||||
|
||||
let length = target - position;
|
||||
|
||||
if length >= CHUNK_ALIGNMENT {
|
||||
return Err(TreeFileError::MisalignedOffset { offset: target });
|
||||
}
|
||||
|
||||
let mut buffer = [0u8; 8];
|
||||
reader.read_exact(&mut buffer[..length as usize])?;
|
||||
|
||||
for (index, byte) in buffer[..length as usize].iter().enumerate() {
|
||||
if *byte != 0 {
|
||||
return Err(TreeFileError::NonZeroPadding {
|
||||
offset: position + index as u64,
|
||||
value: *byte,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
//! Errors produced while reading or writing a VXLS sparse-tree file.
|
||||
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
|
||||
/// Anything that can go wrong reading or writing a sparse-tree file.
|
||||
#[derive(Debug)]
|
||||
pub enum TreeFileError {
|
||||
/// An underlying I/O error.
|
||||
Io(io::Error),
|
||||
|
||||
/// A structural parse error reported by `binrw`.
|
||||
Binrw(binrw::Error),
|
||||
|
||||
/// The file does not start with `b"VXLS"`.
|
||||
BadMagic { found: [u8; 4] },
|
||||
|
||||
/// The file is not a sparse tree (`b"ST\0\0"`).
|
||||
BadFileType { found: [u8; 4] },
|
||||
|
||||
/// The file's version is not readable by this implementation.
|
||||
UnsupportedVersion { major: u32, minor: u32 },
|
||||
|
||||
/// The file is shorter than a mandatory fixed-size section.
|
||||
FileTooSmall { len: u64, needed: u64 },
|
||||
|
||||
/// The preamble's declared size does not match the real file length.
|
||||
FileSizeMismatch { declared: u64, actual: u64 },
|
||||
|
||||
/// `header_size` is below the minimum.
|
||||
HeaderTooSmall { header_size: u32 },
|
||||
|
||||
/// The header extends past the end of the file.
|
||||
HeaderOutOfBounds { header_size: u32, file_len: u64 },
|
||||
|
||||
/// `tree_arity` is below 2.
|
||||
ArityTooSmall { arity: u32 },
|
||||
|
||||
/// The file's arity does not match the requested `N`.
|
||||
ArityMismatch { file: u32, requested: u32 },
|
||||
|
||||
/// `tree_depth` exceeds what `TreeLocator` can address for this arity.
|
||||
DepthTooLarge { depth: u32, max: u32 },
|
||||
|
||||
/// The attribute layout has no attributes.
|
||||
EmptyLayout,
|
||||
|
||||
/// An attribute declares zero words per voxel.
|
||||
InvalidWordCount { index: usize, word_count: u32 },
|
||||
|
||||
/// The layout's word count does not match `size_of::<T>()`.
|
||||
LayoutSizeMismatch {
|
||||
layout_words: u64,
|
||||
payload_words: u64,
|
||||
},
|
||||
|
||||
/// `size_of::<T>()` is not a whole number of 32-bit words.
|
||||
PayloadNotWordAligned { size: usize },
|
||||
|
||||
/// The file's attribute word counts differ from the expected layout.
|
||||
LayoutMismatch { expected: Vec<u32>, found: Vec<u32> },
|
||||
|
||||
/// The offset table size is not a multiple of the entry size.
|
||||
OffsetTableNotAligned { size: u32 },
|
||||
|
||||
/// The offset table extends past the end of the file.
|
||||
OffsetTableOutOfBounds { end: u64, file_len: u64 },
|
||||
|
||||
/// Offset-table entries are not ordered by file offset.
|
||||
OffsetTableNotSorted,
|
||||
|
||||
/// A chunk offset is not 8-byte aligned.
|
||||
MisalignedOffset { offset: u64 },
|
||||
|
||||
/// A chunk does not start where the previous chunk and the alignment rule say.
|
||||
ChunkOffsetMismatch { tag: u32, expected: u64, found: u64 },
|
||||
|
||||
/// Padding between chunks contains a non-zero byte.
|
||||
NonZeroPadding { offset: u64, value: u8 },
|
||||
|
||||
/// A chunk extends past the end of the file.
|
||||
ChunkOutOfBounds { tag: u32, offset: u64, size: u64 },
|
||||
|
||||
/// A chunk declares a size smaller than the 12-byte frame.
|
||||
ChunkSizeTooSmall { tag: u32, size: u64 },
|
||||
|
||||
/// A chunk's declared size does not match the bytes its body consumed.
|
||||
ChunkSizeMismatch {
|
||||
tag: u32,
|
||||
declared: u64,
|
||||
consumed: u64,
|
||||
},
|
||||
|
||||
/// The size in the offset table differs from the size in the chunk frame.
|
||||
EntrySizeMismatch { tag: u32, entry: u64, frame: u64 },
|
||||
|
||||
/// The tag in the offset table differs from the tag in the chunk frame.
|
||||
ChunkTagMismatch { entry: u32, frame: u32 },
|
||||
|
||||
/// The same chunk tag appears more than once.
|
||||
DuplicateChunk { tag: u32 },
|
||||
|
||||
/// The file contains an undefined tag.
|
||||
UnexpectedTag { tag: u32 },
|
||||
|
||||
/// The mandatory attributes chunk is missing.
|
||||
MissingAttributesChunk,
|
||||
|
||||
/// A tree level has no chunk.
|
||||
MissingLevelChunk { level: u32 },
|
||||
|
||||
/// A tree level chunk is beyond `tree_depth`.
|
||||
LevelOutOfRange { level: u32, tree_depth: u32 },
|
||||
|
||||
/// A level declares a different number of nodes than its parents imply.
|
||||
NodeCountMismatch {
|
||||
level: u32,
|
||||
declared: u32,
|
||||
expected: u64,
|
||||
},
|
||||
|
||||
/// The unused bits of a level's subdivision flags are not zero.
|
||||
TrailingFlagBits { level: u32 },
|
||||
|
||||
/// The deepest level contains a subdivided node.
|
||||
SubdividedAtDeepestLevel { level: u32 },
|
||||
|
||||
/// The tree contains nodes that cannot be reached from the root, or vice versa.
|
||||
UnreachableNodes { reachable: usize, stored: usize },
|
||||
|
||||
/// The in-memory tree cannot be represented by the format.
|
||||
InconsistentTree { reason: &'static str },
|
||||
|
||||
/// An arithmetic operation overflowed while sizing the file.
|
||||
Overflow { what: &'static str },
|
||||
|
||||
/// A chunk's CRC does not match its contents.
|
||||
CrcMismatch {
|
||||
tag: u32,
|
||||
offset: u64,
|
||||
expected: u32,
|
||||
found: u32,
|
||||
},
|
||||
|
||||
/// Bytes remain after the last chunk.
|
||||
TrailingBytes { end: u64, file_len: u64 },
|
||||
}
|
||||
|
||||
impl fmt::Display for TreeFileError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Io(error) => write!(f, "I/O error: {error}"),
|
||||
Self::Binrw(error) => write!(f, "parse error: {error}"),
|
||||
Self::BadMagic { found } => {
|
||||
write!(f, "bad magic {found:02X?}, expected b\"VXLS\"")
|
||||
}
|
||||
Self::BadFileType { found } => {
|
||||
write!(f, "bad file type {found:02X?}, expected b\"ST\\0\\0\"")
|
||||
}
|
||||
Self::UnsupportedVersion { major, minor } => {
|
||||
write!(f, "unsupported file version {major}.{minor}")
|
||||
}
|
||||
Self::FileTooSmall { len, needed } => {
|
||||
write!(f, "file is {len} bytes, at least {needed} are needed")
|
||||
}
|
||||
Self::FileSizeMismatch { declared, actual } => {
|
||||
write!(
|
||||
f,
|
||||
"file declares {declared} bytes but is {actual} bytes long"
|
||||
)
|
||||
}
|
||||
Self::HeaderTooSmall { header_size } => {
|
||||
write!(
|
||||
f,
|
||||
"header_size {header_size} is smaller than the 12-byte header"
|
||||
)
|
||||
}
|
||||
Self::HeaderOutOfBounds {
|
||||
header_size,
|
||||
file_len,
|
||||
} => write!(
|
||||
f,
|
||||
"header_size {header_size} extends past the {file_len}-byte file"
|
||||
),
|
||||
Self::ArityTooSmall { arity } => write!(f, "tree_arity {arity} is below 2"),
|
||||
Self::ArityMismatch { file, requested } => {
|
||||
write!(
|
||||
f,
|
||||
"file arity {file} does not match requested arity {requested}"
|
||||
)
|
||||
}
|
||||
Self::DepthTooLarge { depth, max } => {
|
||||
write!(f, "tree_depth {depth} exceeds the maximum {max}")
|
||||
}
|
||||
Self::EmptyLayout => write!(f, "the attribute layout is empty"),
|
||||
Self::InvalidWordCount { index, word_count } => write!(
|
||||
f,
|
||||
"attribute {index} has word_count {word_count}, expected at least 1"
|
||||
),
|
||||
Self::LayoutSizeMismatch {
|
||||
layout_words,
|
||||
payload_words,
|
||||
} => write!(
|
||||
f,
|
||||
"layout totals {layout_words} words but the payload is {payload_words} words"
|
||||
),
|
||||
Self::PayloadNotWordAligned { size } => {
|
||||
write!(f, "payload size {size} is not a multiple of 4 bytes")
|
||||
}
|
||||
Self::LayoutMismatch { expected, found } => {
|
||||
write!(
|
||||
f,
|
||||
"attribute layout mismatch: expected {expected:?}, file has {found:?}"
|
||||
)
|
||||
}
|
||||
Self::OffsetTableNotAligned { size } => {
|
||||
write!(f, "offset table size {size} is not a multiple of 24")
|
||||
}
|
||||
Self::OffsetTableOutOfBounds { end, file_len } => {
|
||||
write!(
|
||||
f,
|
||||
"offset table ends at {end}, past the {file_len}-byte file"
|
||||
)
|
||||
}
|
||||
Self::OffsetTableNotSorted => {
|
||||
write!(f, "offset table entries are not ordered by file_offset")
|
||||
}
|
||||
Self::MisalignedOffset { offset } => {
|
||||
write!(f, "chunk offset {offset} is not 8-byte aligned")
|
||||
}
|
||||
Self::ChunkOffsetMismatch {
|
||||
tag,
|
||||
expected,
|
||||
found,
|
||||
} => write!(
|
||||
f,
|
||||
"chunk {tag:#010X} starts at {found}, expected {expected}"
|
||||
),
|
||||
Self::NonZeroPadding { offset, value } => {
|
||||
write!(f, "padding byte at {offset} is {value}, expected 0")
|
||||
}
|
||||
Self::ChunkOutOfBounds { tag, offset, size } => write!(
|
||||
f,
|
||||
"chunk {tag:#010X} at {offset} with size {size} extends past the file"
|
||||
),
|
||||
Self::ChunkSizeTooSmall { tag, size } => {
|
||||
write!(f, "chunk {tag:#010X} size {size} is smaller than 12")
|
||||
}
|
||||
Self::ChunkSizeMismatch {
|
||||
tag,
|
||||
declared,
|
||||
consumed,
|
||||
} => write!(
|
||||
f,
|
||||
"chunk {tag:#010X} declares {declared} body bytes but consumed {consumed}"
|
||||
),
|
||||
Self::EntrySizeMismatch { tag, entry, frame } => write!(
|
||||
f,
|
||||
"chunk {tag:#010X} size {frame} in the frame differs from {entry} in the offset table"
|
||||
),
|
||||
Self::ChunkTagMismatch { entry, frame } => write!(
|
||||
f,
|
||||
"chunk tag {frame:#010X} in the frame differs from {entry:#010X} in the offset table"
|
||||
),
|
||||
Self::DuplicateChunk { tag } => write!(f, "chunk tag {tag:#010X} appears twice"),
|
||||
Self::UnexpectedTag { tag } => write!(f, "undefined chunk tag {tag:#010X}"),
|
||||
Self::MissingAttributesChunk => write!(f, "the attributes chunk is missing"),
|
||||
Self::MissingLevelChunk { level } => {
|
||||
write!(f, "the chunk for tree level {level} is missing")
|
||||
}
|
||||
Self::LevelOutOfRange { level, tree_depth } => {
|
||||
write!(f, "level chunk {level} is beyond tree_depth {tree_depth}")
|
||||
}
|
||||
Self::NodeCountMismatch {
|
||||
level,
|
||||
declared,
|
||||
expected,
|
||||
} => write!(
|
||||
f,
|
||||
"level {level} declares {declared} nodes but its parents imply {expected}"
|
||||
),
|
||||
Self::TrailingFlagBits { level } => {
|
||||
write!(f, "level {level} has non-zero unused subdivision bits")
|
||||
}
|
||||
Self::SubdividedAtDeepestLevel { level } => {
|
||||
write!(
|
||||
f,
|
||||
"level {level} is the deepest level but has subdivided nodes"
|
||||
)
|
||||
}
|
||||
Self::UnreachableNodes { reachable, stored } => write!(
|
||||
f,
|
||||
"{reachable} nodes are reachable from the root but the tree stores {stored}"
|
||||
),
|
||||
Self::InconsistentTree { reason } => write!(f, "inconsistent tree: {reason}"),
|
||||
Self::Overflow { what } => write!(f, "integer overflow while computing {what}"),
|
||||
Self::CrcMismatch {
|
||||
tag,
|
||||
offset,
|
||||
expected,
|
||||
found,
|
||||
} => write!(
|
||||
f,
|
||||
"chunk {tag:#010X} at {offset} has CRC {found:#010X}, expected {expected:#010X}"
|
||||
),
|
||||
Self::TrailingBytes { end, file_len } => write!(
|
||||
f,
|
||||
"the last chunk ends at {end} but the file is {file_len} bytes long"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for TreeFileError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
match self {
|
||||
Self::Io(error) => Some(error),
|
||||
Self::Binrw(error) => Some(error),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<io::Error> for TreeFileError {
|
||||
fn from(value: io::Error) -> Self {
|
||||
Self::Io(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<binrw::Error> for TreeFileError {
|
||||
fn from(value: binrw::Error) -> Self {
|
||||
Self::Binrw(value)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
//! On-disk wire types of the VXLS sparse-tree format.
|
||||
//!
|
||||
//! Fixed-shape sections derive [`BinRead`]/[`BinWrite`]. The two variable
|
||||
//! sections (attributes and tree levels) are implemented by hand because they
|
||||
//! are structure-of-arrays with counts taken from the stream and from the
|
||||
//! attribute layout.
|
||||
|
||||
use std::io::Read;
|
||||
use std::io::Seek;
|
||||
use std::io::SeekFrom;
|
||||
use std::io::Write;
|
||||
|
||||
use binrw::BinRead;
|
||||
use binrw::BinResult;
|
||||
use binrw::BinWrite;
|
||||
use binrw::Endian;
|
||||
|
||||
/// File magic.
|
||||
pub const MAGIC: [u8; 4] = *b"VXLS";
|
||||
|
||||
/// File-type word for a sparse tree.
|
||||
pub const FILE_TYPE_SPARSE_TREE: [u8; 4] = *b"ST\0\0";
|
||||
|
||||
/// Size of [`Preamble`] in bytes.
|
||||
pub const PREAMBLE_SIZE: u64 = 24;
|
||||
|
||||
/// Size of [`Header`] in bytes.
|
||||
pub const HEADER_SIZE: u32 = 12;
|
||||
|
||||
/// Size of the fixed part of a chunk frame (`tag` + `chunk_size`).
|
||||
pub const CHUNK_FRAME_SIZE: u64 = 12;
|
||||
|
||||
/// Size of one offset-table entry.
|
||||
pub const OFFSET_ENTRY_SIZE: u64 = 24;
|
||||
|
||||
/// Chunk tag of the attributes section.
|
||||
pub const TAG_ATTRIBUTES: u32 = 1;
|
||||
|
||||
/// High bit of a tree-level chunk tag.
|
||||
pub const TAG_LEVEL_FLAG: u32 = 0x8000_0000;
|
||||
|
||||
/// Version written by this implementation.
|
||||
pub const CURRENT_MAJOR: u32 = 1;
|
||||
|
||||
/// Minor version written by this implementation.
|
||||
pub const CURRENT_MINOR: u32 = 0;
|
||||
|
||||
/// Builds the chunk tag for a tree level, 0 being the root.
|
||||
pub const fn level_tag(level: u32) -> u32 {
|
||||
TAG_LEVEL_FLAG | level
|
||||
}
|
||||
|
||||
/// Extracts the level from a chunk tag, or `None` for a non-level chunk.
|
||||
pub const fn level_of(tag: u32) -> Option<u32> {
|
||||
if tag & TAG_LEVEL_FLAG != 0 {
|
||||
Some(tag & !TAG_LEVEL_FLAG)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of `u32` words needed for `node_count` subdivision flags.
|
||||
pub const fn mask_words(node_count: u32) -> usize {
|
||||
(node_count as usize).div_ceil(32)
|
||||
}
|
||||
/// File preamble.
|
||||
#[derive(BinRead, BinWrite, Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[brw(little)]
|
||||
pub struct Preamble {
|
||||
pub magic: [u8; 4],
|
||||
pub file_type: [u8; 4],
|
||||
pub major_version: u32,
|
||||
pub minor_version: u32,
|
||||
pub total_file_size: u64,
|
||||
}
|
||||
|
||||
/// Fixed header following the preamble.
|
||||
#[derive(BinRead, BinWrite, Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[brw(little)]
|
||||
pub struct Header {
|
||||
pub header_size: u32,
|
||||
pub tree_arity: u32,
|
||||
pub tree_depth: u32,
|
||||
}
|
||||
|
||||
/// The fixed part of a chunk frame.
|
||||
#[derive(BinRead, BinWrite, Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[brw(little)]
|
||||
pub struct ChunkFrame {
|
||||
pub chunk_type_tag: u32,
|
||||
pub chunk_size: u64,
|
||||
}
|
||||
|
||||
/// One entry of the offset table.
|
||||
#[derive(BinRead, BinWrite, Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[brw(little)]
|
||||
pub struct OffsetEntry {
|
||||
pub chunk_type_tag: u32,
|
||||
pub reserved: u32,
|
||||
pub file_offset: u64,
|
||||
pub chunk_size: u64,
|
||||
}
|
||||
|
||||
/// One attribute as recorded in the attributes chunk.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FileAttribute {
|
||||
/// Human-readable name. The format does not interpret it.
|
||||
pub label: String,
|
||||
|
||||
/// Size of the attribute in 32-bit words.
|
||||
pub word_count: u32,
|
||||
}
|
||||
|
||||
/// The attributes chunk body.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AttributesBody {
|
||||
pub attributes: Vec<FileAttribute>,
|
||||
}
|
||||
|
||||
impl BinRead for AttributesBody {
|
||||
type Args<'a> = ();
|
||||
|
||||
fn read_options<R: Read + Seek>(
|
||||
reader: &mut R,
|
||||
endian: Endian,
|
||||
_args: Self::Args<'_>,
|
||||
) -> BinResult<Self> {
|
||||
let start = reader.stream_position()?;
|
||||
let remaining = remaining_bytes(reader)?;
|
||||
let count = u32::read_options(reader, endian, ())?;
|
||||
|
||||
// Every entry needs at least word_count + label_size.
|
||||
if count as u64 > remaining / 8 {
|
||||
return Err(binrw::Error::AssertFail {
|
||||
pos: start,
|
||||
message: format!(
|
||||
"attributes chunk declares {count} entries, which cannot fit in {remaining} bytes"
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
let mut attributes = Vec::with_capacity(count as usize);
|
||||
|
||||
for index in 0..count {
|
||||
let word_count = u32::read_options(reader, endian, ())?;
|
||||
let label_size = u32::read_options(reader, endian, ())?;
|
||||
let position = reader.stream_position()?;
|
||||
|
||||
if label_size as u64 > remaining_bytes(reader)? {
|
||||
return Err(binrw::Error::AssertFail {
|
||||
pos: position,
|
||||
message: format!(
|
||||
"attribute {index} label length {label_size} exceeds the chunk body"
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
let mut bytes = vec![0u8; label_size as usize];
|
||||
reader.read_exact(&mut bytes)?;
|
||||
|
||||
let label = String::from_utf8(bytes).map_err(|_| binrw::Error::AssertFail {
|
||||
pos: position,
|
||||
message: format!("attribute {index} label is not valid UTF-8"),
|
||||
})?;
|
||||
|
||||
attributes.push(FileAttribute { label, word_count });
|
||||
}
|
||||
|
||||
Ok(Self { attributes })
|
||||
}
|
||||
}
|
||||
|
||||
impl BinWrite for AttributesBody {
|
||||
type Args<'a> = ();
|
||||
|
||||
fn write_options<W: Write + Seek>(
|
||||
&self,
|
||||
writer: &mut W,
|
||||
endian: Endian,
|
||||
_args: Self::Args<'_>,
|
||||
) -> BinResult<()> {
|
||||
let count = u32::try_from(self.attributes.len()).map_err(|_| binrw::Error::AssertFail {
|
||||
pos: writer.stream_position().unwrap_or(0),
|
||||
message: "attribute count does not fit in a u32".to_string(),
|
||||
})?;
|
||||
count.write_options(writer, endian, ())?;
|
||||
|
||||
for attribute in &self.attributes {
|
||||
let label_size =
|
||||
u32::try_from(attribute.label.len()).map_err(|_| binrw::Error::AssertFail {
|
||||
pos: writer.stream_position().unwrap_or(0),
|
||||
message: "attribute label does not fit in a u32".to_string(),
|
||||
})?;
|
||||
|
||||
attribute.word_count.write_options(writer, endian, ())?;
|
||||
label_size.write_options(writer, endian, ())?;
|
||||
writer.write_all(attribute.label.as_bytes())?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// One tree level, stored as a structure of arrays.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LevelBody {
|
||||
/// Number of nodes at this level.
|
||||
pub node_count: u32,
|
||||
|
||||
/// One `subdivided` bit per node, packed least-significant bit first.
|
||||
pub subdivided: Vec<u32>,
|
||||
|
||||
/// One word array per attribute, `node_count * word_count` words each.
|
||||
pub attributes: Vec<Vec<u32>>,
|
||||
}
|
||||
|
||||
/// Arguments of [`LevelBody::read_options`].
|
||||
pub struct LevelArgs<'a> {
|
||||
/// Word count of every attribute, in binding order.
|
||||
pub word_counts: &'a [u32],
|
||||
}
|
||||
|
||||
impl BinRead for LevelBody {
|
||||
type Args<'a> = LevelArgs<'a>;
|
||||
|
||||
fn read_options<R: Read + Seek>(
|
||||
reader: &mut R,
|
||||
endian: Endian,
|
||||
args: Self::Args<'_>,
|
||||
) -> BinResult<Self> {
|
||||
let start = reader.stream_position()?;
|
||||
let node_count = u32::read_options(reader, endian, ())?;
|
||||
|
||||
let words = mask_words(node_count);
|
||||
let mask_bytes = words as u64 * 4;
|
||||
|
||||
if mask_bytes > remaining_bytes(reader)? {
|
||||
return Err(binrw::Error::AssertFail {
|
||||
pos: start,
|
||||
message: format!(
|
||||
"level with {node_count} nodes needs {mask_bytes} mask bytes, more than the chunk holds"
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
let mut subdivided = Vec::with_capacity(words);
|
||||
|
||||
for _ in 0..words {
|
||||
subdivided.push(u32::read_options(reader, endian, ())?);
|
||||
}
|
||||
|
||||
let mut attributes = Vec::with_capacity(args.word_counts.len());
|
||||
|
||||
for (index, &word_count) in args.word_counts.iter().enumerate() {
|
||||
let count = (node_count as u64)
|
||||
.checked_mul(word_count as u64)
|
||||
.ok_or_else(|| binrw::Error::AssertFail {
|
||||
pos: start,
|
||||
message: format!(
|
||||
"attribute {index} needs {node_count} * {word_count} words, which overflows"
|
||||
),
|
||||
})?;
|
||||
|
||||
if count.saturating_mul(4) > remaining_bytes(reader)? {
|
||||
return Err(binrw::Error::AssertFail {
|
||||
pos: start,
|
||||
message: format!(
|
||||
"attribute {index} needs {count} words, more than the chunk holds"
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
let count = count as usize;
|
||||
let mut attribute = Vec::with_capacity(count);
|
||||
|
||||
for _ in 0..count {
|
||||
attribute.push(u32::read_options(reader, endian, ())?);
|
||||
}
|
||||
|
||||
attributes.push(attribute);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
node_count,
|
||||
subdivided,
|
||||
attributes,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl BinWrite for LevelBody {
|
||||
type Args<'a> = ();
|
||||
|
||||
fn write_options<W: Write + Seek>(
|
||||
&self,
|
||||
writer: &mut W,
|
||||
endian: Endian,
|
||||
_args: Self::Args<'_>,
|
||||
) -> BinResult<()> {
|
||||
self.node_count.write_options(writer, endian, ())?;
|
||||
|
||||
for word in &self.subdivided {
|
||||
word.write_options(writer, endian, ())?;
|
||||
}
|
||||
|
||||
for attribute in &self.attributes {
|
||||
for word in attribute {
|
||||
word.write_options(writer, endian, ())?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn remaining_bytes<R: Read + Seek>(reader: &mut R) -> BinResult<u64> {
|
||||
let position = reader.stream_position()?;
|
||||
let end = reader.seek(SeekFrom::End(0))?;
|
||||
reader.seek(SeekFrom::Start(position))?;
|
||||
Ok(end.saturating_sub(position))
|
||||
}
|
||||
@@ -0,0 +1,591 @@
|
||||
//! Reading and validating VXLS sparse-tree files.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::fs::File;
|
||||
use std::io::Cursor;
|
||||
use std::io::Read;
|
||||
use std::io::Seek;
|
||||
use std::io::SeekFrom;
|
||||
use std::mem::size_of;
|
||||
use std::path::Path;
|
||||
|
||||
use binrw::BinRead;
|
||||
use binrw::Endian;
|
||||
|
||||
use super::chunk::CHUNK_ALIGNMENT;
|
||||
use super::chunk::Chunk;
|
||||
use super::chunk::align_up;
|
||||
use super::chunk::read_chunk;
|
||||
use super::chunk::read_padding;
|
||||
use super::error::TreeFileError;
|
||||
use super::format::AttributesBody;
|
||||
use super::format::CHUNK_FRAME_SIZE;
|
||||
use super::format::CURRENT_MAJOR;
|
||||
use super::format::FILE_TYPE_SPARSE_TREE;
|
||||
use super::format::FileAttribute;
|
||||
use super::format::HEADER_SIZE;
|
||||
use super::format::Header;
|
||||
use super::format::LevelArgs;
|
||||
use super::format::LevelBody;
|
||||
use super::format::MAGIC;
|
||||
use super::format::OFFSET_ENTRY_SIZE;
|
||||
use super::format::OffsetEntry;
|
||||
use super::format::PREAMBLE_SIZE;
|
||||
use super::format::Preamble;
|
||||
use super::format::TAG_ATTRIBUTES;
|
||||
use super::format::level_of;
|
||||
use super::format::mask_words;
|
||||
use crate::Attribute;
|
||||
use crate::AttributesLayout;
|
||||
use crate::sparse_tree::NTree;
|
||||
use crate::sparse_tree::NTreeNode;
|
||||
use crate::tree_locator::TreeLocator;
|
||||
|
||||
/// The attribute layout read from a file.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct FileLayout {
|
||||
pub attributes: Vec<FileAttribute>,
|
||||
}
|
||||
|
||||
impl FileLayout {
|
||||
/// Total number of 32-bit words per voxel.
|
||||
pub fn total_word_count(&self) -> u64 {
|
||||
self.attributes
|
||||
.iter()
|
||||
.map(|attribute| attribute.word_count as u64)
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Index of the first attribute with this label.
|
||||
pub fn by_label(&self, label: &str) -> Option<usize> {
|
||||
self.attributes
|
||||
.iter()
|
||||
.position(|attribute| attribute.label == label)
|
||||
}
|
||||
}
|
||||
|
||||
/// A tree and its attribute layout, as read from a file.
|
||||
pub struct TreeFile<const N: usize, T: Attribute> {
|
||||
/// The parsed tree.
|
||||
pub tree: NTree<N, T>,
|
||||
|
||||
/// The attribute split recorded in the file, in binding order.
|
||||
pub layout: FileLayout,
|
||||
|
||||
/// Major version of the file.
|
||||
pub major_version: u32,
|
||||
|
||||
/// Minor version of the file.
|
||||
pub minor_version: u32,
|
||||
}
|
||||
|
||||
impl<const N: usize, T: Attribute> std::fmt::Debug for TreeFile<N, T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("TreeFile")
|
||||
.field("depth", &self.tree.depth())
|
||||
.field("nodes", &self.tree.node_count())
|
||||
.field("layout", &self.layout)
|
||||
.field("major_version", &self.major_version)
|
||||
.field("minor_version", &self.minor_version)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a sparse-tree file.
|
||||
///
|
||||
/// When `expected` is `Some`, the file's attribute count and word counts must
|
||||
/// match it exactly. Labels are treated as hints and are not compared.
|
||||
pub fn read_tree<R, const N: usize, T>(
|
||||
reader: &mut R,
|
||||
expected: Option<AttributesLayout>,
|
||||
) -> Result<TreeFile<N, T>, TreeFileError>
|
||||
where
|
||||
R: Read + Seek,
|
||||
T: Attribute,
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
if N < 2 {
|
||||
return Err(TreeFileError::ArityTooSmall { arity: N as u32 });
|
||||
}
|
||||
|
||||
let file_len = reader.seek(SeekFrom::End(0))?;
|
||||
reader.seek(SeekFrom::Start(0))?;
|
||||
|
||||
if file_len < PREAMBLE_SIZE {
|
||||
return Err(TreeFileError::FileTooSmall {
|
||||
len: file_len,
|
||||
needed: PREAMBLE_SIZE,
|
||||
});
|
||||
}
|
||||
|
||||
let preamble = Preamble::read_options(reader, Endian::Little, ())?;
|
||||
|
||||
if preamble.magic != MAGIC {
|
||||
return Err(TreeFileError::BadMagic {
|
||||
found: preamble.magic,
|
||||
});
|
||||
}
|
||||
|
||||
if preamble.file_type != FILE_TYPE_SPARSE_TREE {
|
||||
return Err(TreeFileError::BadFileType {
|
||||
found: preamble.file_type,
|
||||
});
|
||||
}
|
||||
|
||||
if preamble.major_version != CURRENT_MAJOR {
|
||||
return Err(TreeFileError::UnsupportedVersion {
|
||||
major: preamble.major_version,
|
||||
minor: preamble.minor_version,
|
||||
});
|
||||
}
|
||||
|
||||
// A newer minor is accepted: unknown chunks are skipped while walking the
|
||||
// offset table.
|
||||
|
||||
if preamble.total_file_size != file_len {
|
||||
return Err(TreeFileError::FileSizeMismatch {
|
||||
declared: preamble.total_file_size,
|
||||
actual: file_len,
|
||||
});
|
||||
}
|
||||
|
||||
let minimum_header_end = PREAMBLE_SIZE + HEADER_SIZE as u64;
|
||||
|
||||
if file_len < minimum_header_end {
|
||||
return Err(TreeFileError::FileTooSmall {
|
||||
len: file_len,
|
||||
needed: minimum_header_end,
|
||||
});
|
||||
}
|
||||
|
||||
let header = Header::read_options(reader, Endian::Little, ())?;
|
||||
|
||||
if header.header_size < HEADER_SIZE {
|
||||
return Err(TreeFileError::HeaderTooSmall {
|
||||
header_size: header.header_size,
|
||||
});
|
||||
}
|
||||
|
||||
let header_end = PREAMBLE_SIZE + header.header_size as u64;
|
||||
|
||||
if header_end > file_len {
|
||||
return Err(TreeFileError::HeaderOutOfBounds {
|
||||
header_size: header.header_size,
|
||||
file_len,
|
||||
});
|
||||
}
|
||||
|
||||
reader.seek(SeekFrom::Start(header_end))?;
|
||||
|
||||
if header.tree_arity < 2 {
|
||||
return Err(TreeFileError::ArityTooSmall {
|
||||
arity: header.tree_arity,
|
||||
});
|
||||
}
|
||||
|
||||
if header.tree_arity != N as u32 {
|
||||
return Err(TreeFileError::ArityMismatch {
|
||||
file: header.tree_arity,
|
||||
requested: N as u32,
|
||||
});
|
||||
}
|
||||
|
||||
if header.tree_depth > TreeLocator::<N>::max_depth() {
|
||||
return Err(TreeFileError::DepthTooLarge {
|
||||
depth: header.tree_depth,
|
||||
max: TreeLocator::<N>::max_depth(),
|
||||
});
|
||||
}
|
||||
|
||||
let table_size = u32::read_options(reader, Endian::Little, ())?;
|
||||
|
||||
if !(table_size as u64).is_multiple_of(OFFSET_ENTRY_SIZE) {
|
||||
return Err(TreeFileError::OffsetTableNotAligned { size: table_size });
|
||||
}
|
||||
|
||||
let table_end = header_end + 4 + table_size as u64;
|
||||
|
||||
if table_end > file_len {
|
||||
return Err(TreeFileError::OffsetTableOutOfBounds {
|
||||
end: table_end,
|
||||
file_len,
|
||||
});
|
||||
}
|
||||
|
||||
let entry_count = table_size as usize / OFFSET_ENTRY_SIZE as usize;
|
||||
let mut entries = Vec::with_capacity(entry_count);
|
||||
let mut tags = HashSet::with_capacity(entry_count);
|
||||
let mut previous_offset = None;
|
||||
|
||||
for _ in 0..entry_count {
|
||||
let entry = OffsetEntry::read_options(reader, Endian::Little, ())?;
|
||||
|
||||
if !tags.insert(entry.chunk_type_tag) {
|
||||
return Err(TreeFileError::DuplicateChunk {
|
||||
tag: entry.chunk_type_tag,
|
||||
});
|
||||
}
|
||||
|
||||
if entry.file_offset % CHUNK_ALIGNMENT != 0 {
|
||||
return Err(TreeFileError::MisalignedOffset {
|
||||
offset: entry.file_offset,
|
||||
});
|
||||
}
|
||||
|
||||
if entry.chunk_size < CHUNK_FRAME_SIZE {
|
||||
return Err(TreeFileError::ChunkSizeTooSmall {
|
||||
tag: entry.chunk_type_tag,
|
||||
size: entry.chunk_size,
|
||||
});
|
||||
}
|
||||
|
||||
let end = entry
|
||||
.file_offset
|
||||
.checked_add(entry.chunk_size)
|
||||
.and_then(|value| value.checked_add(4))
|
||||
.ok_or(TreeFileError::Overflow { what: "chunk end" })?;
|
||||
|
||||
if end > file_len {
|
||||
return Err(TreeFileError::ChunkOutOfBounds {
|
||||
tag: entry.chunk_type_tag,
|
||||
offset: entry.file_offset,
|
||||
size: entry.chunk_size,
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(previous) = previous_offset
|
||||
&& entry.file_offset <= previous
|
||||
{
|
||||
return Err(TreeFileError::OffsetTableNotSorted);
|
||||
}
|
||||
|
||||
previous_offset = Some(entry.file_offset);
|
||||
entries.push(entry);
|
||||
}
|
||||
|
||||
if entry_count == 0 {
|
||||
return Err(TreeFileError::MissingAttributesChunk);
|
||||
}
|
||||
|
||||
// The writer emits chunks back to back; the reader enforces that packing.
|
||||
let mut previous_end = table_end;
|
||||
|
||||
for entry in &entries {
|
||||
let expected = align_up(previous_end, CHUNK_ALIGNMENT);
|
||||
|
||||
if entry.file_offset != expected {
|
||||
return Err(TreeFileError::ChunkOffsetMismatch {
|
||||
tag: entry.chunk_type_tag,
|
||||
expected,
|
||||
found: entry.file_offset,
|
||||
});
|
||||
}
|
||||
|
||||
reader.seek(SeekFrom::Start(previous_end))?;
|
||||
read_padding(reader, entry.file_offset)?;
|
||||
|
||||
previous_end = entry.file_offset + entry.chunk_size + 4;
|
||||
}
|
||||
|
||||
if previous_end != file_len {
|
||||
return Err(TreeFileError::TrailingBytes {
|
||||
end: previous_end,
|
||||
file_len,
|
||||
});
|
||||
}
|
||||
|
||||
let mut attributes_entry = None;
|
||||
let mut level_entries = HashMap::new();
|
||||
|
||||
for entry in &entries {
|
||||
if entry.chunk_type_tag == TAG_ATTRIBUTES {
|
||||
attributes_entry = Some(*entry);
|
||||
} else if let Some(level) = level_of(entry.chunk_type_tag) {
|
||||
if level > header.tree_depth {
|
||||
return Err(TreeFileError::LevelOutOfRange {
|
||||
level,
|
||||
tree_depth: header.tree_depth,
|
||||
});
|
||||
}
|
||||
|
||||
level_entries.insert(level, *entry);
|
||||
} else if entry.chunk_type_tag == 0 {
|
||||
return Err(TreeFileError::UnexpectedTag {
|
||||
tag: entry.chunk_type_tag,
|
||||
});
|
||||
}
|
||||
// Unknown non-level chunks are skipped for minor-version compatibility.
|
||||
}
|
||||
|
||||
let attributes_entry = attributes_entry.ok_or(TreeFileError::MissingAttributesChunk)?;
|
||||
|
||||
let level_count = level_entries.len();
|
||||
|
||||
if level_count == 0 {
|
||||
return Err(TreeFileError::MissingLevelChunk { level: 0 });
|
||||
}
|
||||
|
||||
for level in 0..level_count as u32 {
|
||||
if !level_entries.contains_key(&level) {
|
||||
return Err(TreeFileError::MissingLevelChunk { level });
|
||||
}
|
||||
}
|
||||
|
||||
let deepest = level_count as u32 - 1;
|
||||
|
||||
let layout = read_attributes(reader, &attributes_entry, file_len)?;
|
||||
|
||||
if let Some(expected) = expected {
|
||||
let expected_words: Vec<u32> = expected
|
||||
.attributes
|
||||
.iter()
|
||||
.map(|attribute| attribute.word_count)
|
||||
.collect();
|
||||
let found_words: Vec<u32> = layout
|
||||
.attributes
|
||||
.iter()
|
||||
.map(|attribute| attribute.word_count)
|
||||
.collect();
|
||||
|
||||
if expected_words != found_words {
|
||||
return Err(TreeFileError::LayoutMismatch {
|
||||
expected: expected_words,
|
||||
found: found_words,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (index, attribute) in layout.attributes.iter().enumerate() {
|
||||
if attribute.word_count == 0 {
|
||||
return Err(TreeFileError::InvalidWordCount {
|
||||
index,
|
||||
word_count: attribute.word_count,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if !size_of::<T>().is_multiple_of(4) {
|
||||
return Err(TreeFileError::PayloadNotWordAligned {
|
||||
size: size_of::<T>(),
|
||||
});
|
||||
}
|
||||
|
||||
let layout_words = layout.total_word_count();
|
||||
let payload_words = (size_of::<T>() / 4) as u64;
|
||||
|
||||
if layout_words != payload_words {
|
||||
return Err(TreeFileError::LayoutSizeMismatch {
|
||||
layout_words,
|
||||
payload_words,
|
||||
});
|
||||
}
|
||||
|
||||
let word_counts: Vec<u32> = layout
|
||||
.attributes
|
||||
.iter()
|
||||
.map(|attribute| attribute.word_count)
|
||||
.collect();
|
||||
|
||||
let tree = read_tree_body::<N, T>(
|
||||
reader,
|
||||
file_len,
|
||||
header.tree_depth,
|
||||
deepest,
|
||||
&level_entries,
|
||||
&word_counts,
|
||||
)?;
|
||||
|
||||
Ok(TreeFile {
|
||||
tree,
|
||||
layout,
|
||||
major_version: preamble.major_version,
|
||||
minor_version: preamble.minor_version,
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads `path` as a sparse-tree file.
|
||||
pub fn read_tree_from_path<P, const N: usize, T>(
|
||||
path: P,
|
||||
expected: Option<AttributesLayout>,
|
||||
) -> Result<TreeFile<N, T>, TreeFileError>
|
||||
where
|
||||
P: AsRef<Path>,
|
||||
T: Attribute,
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
let mut file = File::open(path)?;
|
||||
read_tree(&mut file, expected)
|
||||
}
|
||||
|
||||
fn read_attributes<R: Read + Seek>(
|
||||
reader: &mut R,
|
||||
entry: &OffsetEntry,
|
||||
file_len: u64,
|
||||
) -> Result<FileLayout, TreeFileError> {
|
||||
let chunk = read_chunk_at(reader, entry, file_len)?;
|
||||
|
||||
if chunk.tag != TAG_ATTRIBUTES {
|
||||
return Err(TreeFileError::ChunkTagMismatch {
|
||||
entry: TAG_ATTRIBUTES,
|
||||
frame: chunk.tag,
|
||||
});
|
||||
}
|
||||
|
||||
let mut cursor = Cursor::new(&chunk.body);
|
||||
let body = AttributesBody::read_options(&mut cursor, Endian::Little, ())?;
|
||||
|
||||
if cursor.position() != chunk.body.len() as u64 {
|
||||
return Err(TreeFileError::ChunkSizeMismatch {
|
||||
tag: chunk.tag,
|
||||
declared: chunk.body.len() as u64,
|
||||
consumed: cursor.position(),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(FileLayout {
|
||||
attributes: body.attributes,
|
||||
})
|
||||
}
|
||||
|
||||
fn read_tree_body<const N: usize, T: Attribute>(
|
||||
reader: &mut (impl Read + Seek),
|
||||
file_len: u64,
|
||||
tree_depth: u32,
|
||||
deepest: u32,
|
||||
level_entries: &HashMap<u32, OffsetEntry>,
|
||||
word_counts: &[u32],
|
||||
) -> Result<NTree<N, T>, TreeFileError>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
let mut map: HashMap<TreeLocator<N>, NTreeNode<T>> = HashMap::new();
|
||||
let mut parents = vec![TreeLocator::<N>::root()];
|
||||
let mut scratch = vec![0u8; size_of::<T>()];
|
||||
|
||||
for level in 0..=deepest {
|
||||
let entry = level_entries
|
||||
.get(&level)
|
||||
.ok_or(TreeFileError::MissingLevelChunk { level })?;
|
||||
let chunk = read_chunk_at(reader, entry, file_len)?;
|
||||
|
||||
if level_of(chunk.tag) != Some(level) {
|
||||
return Err(TreeFileError::ChunkTagMismatch {
|
||||
entry: entry.chunk_type_tag,
|
||||
frame: chunk.tag,
|
||||
});
|
||||
}
|
||||
|
||||
let mut cursor = Cursor::new(&chunk.body);
|
||||
let body = LevelBody::read_options(&mut cursor, Endian::Little, LevelArgs { word_counts })?;
|
||||
|
||||
if cursor.position() != chunk.body.len() as u64 {
|
||||
return Err(TreeFileError::ChunkSizeMismatch {
|
||||
tag: chunk.tag,
|
||||
declared: chunk.body.len() as u64,
|
||||
consumed: cursor.position(),
|
||||
});
|
||||
}
|
||||
|
||||
let node_count = body.node_count as usize;
|
||||
|
||||
if node_count as u64 != parents.len() as u64 {
|
||||
return Err(TreeFileError::NodeCountMismatch {
|
||||
level,
|
||||
declared: body.node_count,
|
||||
expected: parents.len() as u64,
|
||||
});
|
||||
}
|
||||
|
||||
if body.subdivided.len() != mask_words(body.node_count) {
|
||||
return Err(TreeFileError::InconsistentTree {
|
||||
reason: "level mask length does not match its node count",
|
||||
});
|
||||
}
|
||||
|
||||
if body.node_count % 32 != 0 {
|
||||
let used = body.node_count % 32;
|
||||
let last = *body.subdivided.last().unwrap_or(&0);
|
||||
|
||||
if last >> used != 0 {
|
||||
return Err(TreeFileError::TrailingFlagBits { level });
|
||||
}
|
||||
}
|
||||
|
||||
let mut next = Vec::new();
|
||||
|
||||
for (index, parent) in parents.iter().enumerate() {
|
||||
let subdivided = body.subdivided[index / 32] & (1 << (index % 32)) != 0;
|
||||
|
||||
let mut byte_offset = 0usize;
|
||||
|
||||
for (attribute_index, &word_count) in word_counts.iter().enumerate() {
|
||||
let word_count = word_count as usize;
|
||||
let start = index * word_count;
|
||||
let end = start + word_count;
|
||||
let words = &body.attributes[attribute_index][start..end];
|
||||
|
||||
for word in words {
|
||||
scratch[byte_offset..byte_offset + 4].copy_from_slice(&word.to_ne_bytes());
|
||||
byte_offset += 4;
|
||||
}
|
||||
}
|
||||
|
||||
let attribute = bytemuck::pod_read_unaligned::<T>(&scratch);
|
||||
|
||||
map.insert(
|
||||
*parent,
|
||||
NTreeNode {
|
||||
attribute,
|
||||
subdivided,
|
||||
},
|
||||
);
|
||||
|
||||
if subdivided {
|
||||
next.extend(parent.children());
|
||||
}
|
||||
}
|
||||
|
||||
if level == deepest && !next.is_empty() {
|
||||
return Err(TreeFileError::SubdividedAtDeepestLevel { level });
|
||||
}
|
||||
|
||||
parents = next;
|
||||
}
|
||||
|
||||
if !parents.is_empty() {
|
||||
return Err(TreeFileError::NodeCountMismatch {
|
||||
level: deepest,
|
||||
declared: 0,
|
||||
expected: parents.len() as u64,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(NTree::from_nodes(map, tree_depth as usize))
|
||||
}
|
||||
|
||||
fn read_chunk_at<R: Read + Seek>(
|
||||
reader: &mut R,
|
||||
entry: &OffsetEntry,
|
||||
file_len: u64,
|
||||
) -> Result<Chunk, TreeFileError> {
|
||||
reader.seek(SeekFrom::Start(entry.file_offset))?;
|
||||
let chunk = read_chunk(reader, file_len)?;
|
||||
|
||||
if chunk.tag != entry.chunk_type_tag {
|
||||
return Err(TreeFileError::ChunkTagMismatch {
|
||||
entry: entry.chunk_type_tag,
|
||||
frame: chunk.tag,
|
||||
});
|
||||
}
|
||||
|
||||
if chunk.size != entry.chunk_size {
|
||||
return Err(TreeFileError::EntrySizeMismatch {
|
||||
tag: chunk.tag,
|
||||
entry: entry.chunk_size,
|
||||
frame: chunk.size,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(chunk)
|
||||
}
|
||||
@@ -0,0 +1,643 @@
|
||||
//! Writing VXLS sparse-tree files.
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::Cursor;
|
||||
use std::io::Write;
|
||||
use std::mem::size_of;
|
||||
use std::path::Path;
|
||||
|
||||
use binrw::BinWrite;
|
||||
use binrw::Endian;
|
||||
|
||||
use super::chunk::CHUNK_ALIGNMENT;
|
||||
use super::chunk::align_up;
|
||||
use super::chunk::write_chunk;
|
||||
use super::chunk::write_padding_to_alignment;
|
||||
use super::error::TreeFileError;
|
||||
use super::format::AttributesBody;
|
||||
use super::format::CURRENT_MAJOR;
|
||||
use super::format::CURRENT_MINOR;
|
||||
use super::format::FILE_TYPE_SPARSE_TREE;
|
||||
use super::format::FileAttribute;
|
||||
use super::format::HEADER_SIZE;
|
||||
use super::format::Header;
|
||||
use super::format::LevelBody;
|
||||
use super::format::MAGIC;
|
||||
use super::format::OFFSET_ENTRY_SIZE;
|
||||
use super::format::OffsetEntry;
|
||||
use super::format::PREAMBLE_SIZE;
|
||||
use super::format::Preamble;
|
||||
use super::format::TAG_ATTRIBUTES;
|
||||
use super::format::level_tag;
|
||||
use super::format::mask_words;
|
||||
use crate::Attribute;
|
||||
use crate::AttributesLayout;
|
||||
use crate::sparse_tree::NTree;
|
||||
use crate::tree_locator::TreeLocator;
|
||||
|
||||
/// One level of the tree, as planned for writing.
|
||||
struct LevelPlan<const N: usize> {
|
||||
locators: Vec<TreeLocator<N>>,
|
||||
subdivided: Vec<bool>,
|
||||
}
|
||||
|
||||
impl<const N: usize> LevelPlan<N> {
|
||||
fn node_count(&self) -> u64 {
|
||||
self.locators.len() as u64
|
||||
}
|
||||
|
||||
fn body_len(&self, total_words: u64) -> u64 {
|
||||
let flags = mask_words(self.locators.len() as u32) as u64 * 4;
|
||||
let attribute_bytes = self.node_count() * total_words * 4;
|
||||
|
||||
4 + flags + attribute_bytes
|
||||
}
|
||||
}
|
||||
|
||||
struct ChunkPlan {
|
||||
tag: u32,
|
||||
offset: u64,
|
||||
chunk_size: u64,
|
||||
}
|
||||
|
||||
/// Serialises `tree` with the attribute split described by `layout`.
|
||||
///
|
||||
/// The layout must have at least one attribute, every `word_count` must be
|
||||
/// non-zero, and `sum(word_count) * 4` must equal `size_of::<T>()`.
|
||||
pub fn write_tree<W, const N: usize, T>(
|
||||
writer: &mut W,
|
||||
tree: &NTree<N, T>,
|
||||
layout: AttributesLayout,
|
||||
) -> Result<(), TreeFileError>
|
||||
where
|
||||
W: Write + std::io::Seek,
|
||||
T: Attribute,
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
if N < 2 {
|
||||
return Err(TreeFileError::ArityTooSmall { arity: N as u32 });
|
||||
}
|
||||
|
||||
let children_per_node = (N as u64)
|
||||
.checked_mul(N as u64)
|
||||
.and_then(|value| value.checked_mul(N as u64))
|
||||
.ok_or(TreeFileError::Overflow { what: "N^3" })?;
|
||||
|
||||
if children_per_node > u32::MAX as u64 {
|
||||
return Err(TreeFileError::Overflow {
|
||||
what: "N^3 does not fit in the u32 node count",
|
||||
});
|
||||
}
|
||||
|
||||
if !size_of::<T>().is_multiple_of(4) {
|
||||
return Err(TreeFileError::PayloadNotWordAligned {
|
||||
size: size_of::<T>(),
|
||||
});
|
||||
}
|
||||
|
||||
if layout.attributes.is_empty() {
|
||||
return Err(TreeFileError::EmptyLayout);
|
||||
}
|
||||
|
||||
let mut layout_words = 0u64;
|
||||
|
||||
for (index, attribute) in layout.attributes.iter().enumerate() {
|
||||
if attribute.word_count == 0 {
|
||||
return Err(TreeFileError::InvalidWordCount {
|
||||
index,
|
||||
word_count: attribute.word_count,
|
||||
});
|
||||
}
|
||||
|
||||
layout_words = layout_words
|
||||
.checked_add(attribute.word_count as u64)
|
||||
.ok_or(TreeFileError::Overflow {
|
||||
what: "attribute word count",
|
||||
})?;
|
||||
}
|
||||
|
||||
let payload_words = (size_of::<T>() / 4) as u64;
|
||||
|
||||
if layout_words != payload_words {
|
||||
return Err(TreeFileError::LayoutSizeMismatch {
|
||||
layout_words,
|
||||
payload_words,
|
||||
});
|
||||
}
|
||||
|
||||
let tree_depth = u32::try_from(tree.depth()).map_err(|_| TreeFileError::DepthTooLarge {
|
||||
depth: u32::MAX,
|
||||
max: TreeLocator::<N>::max_depth(),
|
||||
})?;
|
||||
|
||||
if tree_depth > TreeLocator::<N>::max_depth() {
|
||||
return Err(TreeFileError::DepthTooLarge {
|
||||
depth: tree_depth,
|
||||
max: TreeLocator::<N>::max_depth(),
|
||||
});
|
||||
}
|
||||
|
||||
let levels = plan_levels::<N, T>(tree, tree_depth)?;
|
||||
|
||||
// Reachability check: the file can only describe the part of the map that
|
||||
// is reachable from the root.
|
||||
let reachable = levels
|
||||
.iter()
|
||||
.map(|level| level.node_count())
|
||||
.sum::<u64>()
|
||||
.try_into()
|
||||
.unwrap_or(usize::MAX);
|
||||
|
||||
if reachable != tree.node_count() {
|
||||
return Err(TreeFileError::UnreachableNodes {
|
||||
reachable,
|
||||
stored: tree.node_count(),
|
||||
});
|
||||
}
|
||||
|
||||
let word_offsets = attribute_word_offsets(layout);
|
||||
|
||||
// Plan every chunk size and offset before writing anything. All sizes are
|
||||
// derivable from the node counts and the layout, so no backpatching.
|
||||
let attributes_body_len = attributes_body_len(layout)?;
|
||||
|
||||
let mut plans: Vec<ChunkPlan> = Vec::with_capacity(levels.len() + 1);
|
||||
plans.push(ChunkPlan {
|
||||
tag: TAG_ATTRIBUTES,
|
||||
offset: 0,
|
||||
chunk_size: chunk_size_for(attributes_body_len)?,
|
||||
});
|
||||
|
||||
for (level, plan) in levels.iter().enumerate() {
|
||||
plans.push(ChunkPlan {
|
||||
tag: level_tag(level as u32),
|
||||
offset: 0,
|
||||
chunk_size: chunk_size_for(plan.body_len(layout_words))?,
|
||||
});
|
||||
}
|
||||
|
||||
let header_end = PREAMBLE_SIZE + HEADER_SIZE as u64;
|
||||
let table_size =
|
||||
(plans.len() as u64)
|
||||
.checked_mul(OFFSET_ENTRY_SIZE)
|
||||
.ok_or(TreeFileError::Overflow {
|
||||
what: "offset table size",
|
||||
})?;
|
||||
let table_end = header_end + 4 + table_size;
|
||||
|
||||
let mut cursor = align_up(table_end, CHUNK_ALIGNMENT);
|
||||
|
||||
for plan in &mut plans {
|
||||
plan.offset = cursor;
|
||||
cursor = align_up(cursor + plan.chunk_size + 4, CHUNK_ALIGNMENT);
|
||||
}
|
||||
|
||||
let last = plans.last().ok_or(TreeFileError::InconsistentTree {
|
||||
reason: "no chunks to write",
|
||||
})?;
|
||||
let total_file_size = last.offset + last.chunk_size + 4;
|
||||
|
||||
Preamble {
|
||||
magic: MAGIC,
|
||||
file_type: FILE_TYPE_SPARSE_TREE,
|
||||
major_version: CURRENT_MAJOR,
|
||||
minor_version: CURRENT_MINOR,
|
||||
total_file_size,
|
||||
}
|
||||
.write_options(writer, Endian::Little, ())?;
|
||||
|
||||
Header {
|
||||
header_size: HEADER_SIZE,
|
||||
tree_arity: N as u32,
|
||||
tree_depth,
|
||||
}
|
||||
.write_options(writer, Endian::Little, ())?;
|
||||
|
||||
u32::try_from(table_size)
|
||||
.map_err(|_| TreeFileError::Overflow {
|
||||
what: "offset table size does not fit in a u32",
|
||||
})?
|
||||
.write_options(writer, Endian::Little, ())?;
|
||||
|
||||
for plan in &plans {
|
||||
OffsetEntry {
|
||||
chunk_type_tag: plan.tag,
|
||||
reserved: 0,
|
||||
file_offset: plan.offset,
|
||||
chunk_size: plan.chunk_size,
|
||||
}
|
||||
.write_options(writer, Endian::Little, ())?;
|
||||
}
|
||||
|
||||
for (index, plan) in plans.iter().enumerate() {
|
||||
write_padding_to_alignment(writer)?;
|
||||
|
||||
let position = writer.stream_position()?;
|
||||
|
||||
if position != plan.offset {
|
||||
return Err(TreeFileError::ChunkOffsetMismatch {
|
||||
tag: plan.tag,
|
||||
expected: plan.offset,
|
||||
found: position,
|
||||
});
|
||||
}
|
||||
|
||||
let body = if index == 0 {
|
||||
build_attributes_body(layout)?
|
||||
} else {
|
||||
build_level_body(tree, &levels[index - 1], layout, &word_offsets)?
|
||||
};
|
||||
|
||||
write_chunk(writer, plan.tag, &body)?;
|
||||
}
|
||||
|
||||
let position = writer.stream_position()?;
|
||||
|
||||
if position != total_file_size {
|
||||
return Err(TreeFileError::FileSizeMismatch {
|
||||
declared: total_file_size,
|
||||
actual: position,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes `tree` to a new file at `path`.
|
||||
pub fn write_tree_to_path<P, const N: usize, T>(
|
||||
path: P,
|
||||
tree: &NTree<N, T>,
|
||||
layout: AttributesLayout,
|
||||
) -> Result<(), TreeFileError>
|
||||
where
|
||||
P: AsRef<Path>,
|
||||
T: Attribute,
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
let mut file = File::create(path)?;
|
||||
write_tree(&mut file, tree, layout)
|
||||
}
|
||||
|
||||
fn plan_levels<const N: usize, T: Attribute>(
|
||||
tree: &NTree<N, T>,
|
||||
capacity: u32,
|
||||
) -> Result<Vec<LevelPlan<N>>, TreeFileError>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
let mut levels = Vec::new();
|
||||
let mut current = vec![TreeLocator::<N>::root()];
|
||||
let mut level = 0u32;
|
||||
|
||||
loop {
|
||||
let mut subdivided = Vec::with_capacity(current.len());
|
||||
|
||||
for locator in ¤t {
|
||||
let node = tree
|
||||
.get_by_loc(*locator)
|
||||
.ok_or(TreeFileError::InconsistentTree {
|
||||
reason: "a node reachable from the root is missing from the map",
|
||||
})?;
|
||||
subdivided.push(node.subdivided);
|
||||
}
|
||||
|
||||
let subdivided_count = subdivided.iter().filter(|flag| **flag).count();
|
||||
|
||||
if subdivided_count > 0 && level == capacity {
|
||||
return Err(TreeFileError::InconsistentTree {
|
||||
reason: "a node at the maximum depth is subdivided",
|
||||
});
|
||||
}
|
||||
|
||||
let mut next = Vec::new();
|
||||
|
||||
if subdivided_count > 0 {
|
||||
let children = (N as u64)
|
||||
.checked_mul(N as u64)
|
||||
.and_then(|value| value.checked_mul(N as u64))
|
||||
.ok_or(TreeFileError::Overflow { what: "N^3" })?;
|
||||
let reserve =
|
||||
(subdivided_count as u64)
|
||||
.checked_mul(children)
|
||||
.ok_or(TreeFileError::Overflow {
|
||||
what: "next level node count",
|
||||
})?;
|
||||
let reserve = usize::try_from(reserve).map_err(|_| TreeFileError::Overflow {
|
||||
what: "next level node count does not fit in usize",
|
||||
})?;
|
||||
next.reserve(reserve);
|
||||
|
||||
for (locator, is_subdivided) in current.iter().zip(&subdivided) {
|
||||
if *is_subdivided {
|
||||
next.extend(locator.children());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let plan = LevelPlan {
|
||||
locators: current,
|
||||
subdivided,
|
||||
};
|
||||
|
||||
if u32::try_from(plan.locators.len()).is_err() {
|
||||
return Err(TreeFileError::Overflow {
|
||||
what: "level node count does not fit in a u32",
|
||||
});
|
||||
}
|
||||
|
||||
levels.push(plan);
|
||||
|
||||
if next.is_empty() {
|
||||
break;
|
||||
}
|
||||
|
||||
current = next;
|
||||
level += 1;
|
||||
}
|
||||
|
||||
Ok(levels)
|
||||
}
|
||||
|
||||
fn attribute_word_offsets(layout: AttributesLayout) -> Vec<usize> {
|
||||
let mut offsets = Vec::with_capacity(layout.attributes.len());
|
||||
let mut offset = 0usize;
|
||||
|
||||
for attribute in layout.attributes {
|
||||
offsets.push(offset);
|
||||
offset += attribute.word_count as usize;
|
||||
}
|
||||
|
||||
offsets
|
||||
}
|
||||
|
||||
fn attributes_body_len(layout: AttributesLayout) -> Result<u64, TreeFileError> {
|
||||
let mut length = 4u64;
|
||||
|
||||
for attribute in layout.attributes {
|
||||
length = length
|
||||
.checked_add(8)
|
||||
.and_then(|value| value.checked_add(attribute.label.len() as u64))
|
||||
.ok_or(TreeFileError::Overflow {
|
||||
what: "attributes chunk length",
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(length)
|
||||
}
|
||||
|
||||
fn build_attributes_body(layout: AttributesLayout) -> Result<Vec<u8>, TreeFileError> {
|
||||
let body = AttributesBody {
|
||||
attributes: layout
|
||||
.attributes
|
||||
.iter()
|
||||
.map(|attribute| FileAttribute {
|
||||
label: attribute.label.to_string(),
|
||||
word_count: attribute.word_count,
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
|
||||
let mut cursor = Cursor::new(Vec::new());
|
||||
body.write_options(&mut cursor, Endian::Little, ())?;
|
||||
Ok(cursor.into_inner())
|
||||
}
|
||||
|
||||
fn build_level_body<const N: usize, T: Attribute>(
|
||||
tree: &NTree<N, T>,
|
||||
plan: &LevelPlan<N>,
|
||||
layout: AttributesLayout,
|
||||
word_offsets: &[usize],
|
||||
) -> Result<Vec<u8>, TreeFileError>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
let node_count = u32::try_from(plan.locators.len()).map_err(|_| TreeFileError::Overflow {
|
||||
what: "level node count does not fit in a u32",
|
||||
})?;
|
||||
|
||||
let mut flags = vec![0u32; mask_words(node_count)];
|
||||
|
||||
for (index, subdivided) in plan.subdivided.iter().enumerate() {
|
||||
if *subdivided {
|
||||
flags[index / 32] |= 1 << (index % 32);
|
||||
}
|
||||
}
|
||||
|
||||
let mut attributes: Vec<Vec<u32>> = layout
|
||||
.attributes
|
||||
.iter()
|
||||
.map(|attribute| Vec::with_capacity(node_count as usize * attribute.word_count as usize))
|
||||
.collect();
|
||||
|
||||
for locator in &plan.locators {
|
||||
let node = tree
|
||||
.get_by_loc(*locator)
|
||||
.ok_or(TreeFileError::InconsistentTree {
|
||||
reason: "a planned node disappeared from the map",
|
||||
})?;
|
||||
|
||||
let bytes = bytemuck::bytes_of(&node.attribute);
|
||||
|
||||
for (index, attribute) in layout.attributes.iter().enumerate() {
|
||||
let start = word_offsets[index] * 4;
|
||||
let end = start + attribute.word_count as usize * 4;
|
||||
let slice = &bytes[start..end];
|
||||
|
||||
for word in slice.chunks_exact(4) {
|
||||
let value =
|
||||
u32::from_ne_bytes(word.try_into().expect("chunks_exact yields 4-byte slices"));
|
||||
attributes[index].push(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let body = LevelBody {
|
||||
node_count,
|
||||
subdivided: flags,
|
||||
attributes,
|
||||
};
|
||||
|
||||
let mut cursor = Cursor::new(Vec::new());
|
||||
body.write_options(&mut cursor, Endian::Little, ())?;
|
||||
Ok(cursor.into_inner())
|
||||
}
|
||||
|
||||
fn chunk_size_for(body_len: u64) -> Result<u64, TreeFileError> {
|
||||
super::format::CHUNK_FRAME_SIZE
|
||||
.checked_add(body_len)
|
||||
.ok_or(TreeFileError::Overflow { what: "chunk size" })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io::Cursor;
|
||||
use std::io::Seek;
|
||||
use std::io::SeekFrom;
|
||||
|
||||
use super::*;
|
||||
use crate::io::chunk::read_chunk;
|
||||
use crate::io::format::AttributesBody;
|
||||
use crate::io::format::Header;
|
||||
use crate::io::format::LevelArgs;
|
||||
use crate::io::format::LevelBody;
|
||||
use crate::io::format::OffsetEntry;
|
||||
use crate::io::format::PREAMBLE_SIZE;
|
||||
use crate::io::format::level_of;
|
||||
use binrw::BinRead;
|
||||
use binrw::BinWrite;
|
||||
|
||||
const U32_LAYOUT: AttributesLayout =
|
||||
AttributesLayout::new(&[crate::AttributeDescriptor::new("value", 1)]);
|
||||
|
||||
fn write(tree: &NTree<2, u32>) -> Vec<u8> {
|
||||
let mut cursor = Cursor::new(Vec::new());
|
||||
write_tree(&mut cursor, tree, U32_LAYOUT).unwrap();
|
||||
cursor.into_inner()
|
||||
}
|
||||
|
||||
fn entries(bytes: &[u8]) -> Vec<OffsetEntry> {
|
||||
let mut cursor = Cursor::new(bytes);
|
||||
cursor.seek(SeekFrom::Start(PREAMBLE_SIZE)).unwrap();
|
||||
let header = Header::read_options(&mut cursor, Endian::Little, ()).unwrap();
|
||||
cursor
|
||||
.seek(SeekFrom::Start(PREAMBLE_SIZE + header.header_size as u64))
|
||||
.unwrap();
|
||||
let table_size = u32::read_options(&mut cursor, Endian::Little, ()).unwrap();
|
||||
|
||||
(0..table_size as usize / 24)
|
||||
.map(|_| OffsetEntry::read_options(&mut cursor, Endian::Little, ()).unwrap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn bodies(bytes: &[u8]) -> Vec<(u32, Vec<u8>)> {
|
||||
let mut cursor = Cursor::new(bytes);
|
||||
entries(bytes)
|
||||
.into_iter()
|
||||
.map(|entry| {
|
||||
cursor.seek(SeekFrom::Start(entry.file_offset)).unwrap();
|
||||
let chunk = read_chunk(&mut cursor, bytes.len() as u64).unwrap();
|
||||
assert_eq!(chunk.tag, entry.chunk_type_tag);
|
||||
(chunk.tag, chunk.body)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn child_order_is_x_fastest() {
|
||||
let mut tree = NTree::<2, u32>::constant(0, 1);
|
||||
tree.set(1, 0, 0, 9);
|
||||
|
||||
let bytes = write(&tree);
|
||||
let chunks = bodies(&bytes);
|
||||
|
||||
assert_eq!(chunks[0].0, TAG_ATTRIBUTES);
|
||||
assert_eq!(level_of(chunks[1].0), Some(0));
|
||||
assert_eq!(level_of(chunks[2].0), Some(1));
|
||||
|
||||
let root = LevelBody::read_options(
|
||||
&mut Cursor::new(&chunks[1].1),
|
||||
Endian::Little,
|
||||
LevelArgs { word_counts: &[1] },
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(root.node_count, 1);
|
||||
assert_eq!(root.subdivided, vec![1]);
|
||||
assert_eq!(root.attributes[0], vec![9 / 8]);
|
||||
|
||||
let level = LevelBody::read_options(
|
||||
&mut Cursor::new(&chunks[2].1),
|
||||
Endian::Little,
|
||||
LevelArgs { word_counts: &[1] },
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(level.node_count, 8);
|
||||
assert_eq!(level.subdivided, vec![0]);
|
||||
assert_eq!(level.attributes[0], vec![0, 9, 0, 0, 0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunks_are_aligned_and_packed() {
|
||||
let tree = NTree::<2, u32>::constant(3, 2);
|
||||
let bytes = write(&tree);
|
||||
let entries = entries(&bytes);
|
||||
|
||||
let header_end = PREAMBLE_SIZE + 12;
|
||||
let table_end = header_end + 4 + entries.len() as u64 * 24;
|
||||
|
||||
let mut previous_end = table_end;
|
||||
|
||||
for entry in &entries {
|
||||
let expected = crate::io::chunk::align_up(previous_end, 8);
|
||||
assert_eq!(entry.file_offset, expected);
|
||||
assert_eq!(entry.file_offset % 8, 0);
|
||||
previous_end = entry.file_offset + entry.chunk_size + 4;
|
||||
}
|
||||
|
||||
assert_eq!(previous_end, bytes.len() as u64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attributes_chunk_roundtrip() {
|
||||
let body = AttributesBody {
|
||||
attributes: vec![
|
||||
FileAttribute {
|
||||
label: "color".to_string(),
|
||||
word_count: 1,
|
||||
},
|
||||
FileAttribute {
|
||||
label: "normal".to_string(),
|
||||
word_count: 3,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
let mut cursor = Cursor::new(Vec::new());
|
||||
body.write_options(&mut cursor, Endian::Little, ()).unwrap();
|
||||
|
||||
cursor.seek(SeekFrom::Start(0)).unwrap();
|
||||
let parsed = AttributesBody::read_options(&mut cursor, Endian::Little, ()).unwrap();
|
||||
|
||||
assert_eq!(parsed, body);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shallow_tree_keeps_capacity_in_the_header() {
|
||||
// A tree that bottoms out at level 1 while declaring a capacity of 4.
|
||||
let mut map = std::collections::HashMap::new();
|
||||
map.insert(
|
||||
TreeLocator::<2>::root(),
|
||||
crate::sparse_tree::NTreeNode {
|
||||
attribute: 1u32,
|
||||
subdivided: true,
|
||||
},
|
||||
);
|
||||
|
||||
for child in TreeLocator::<2>::root().children() {
|
||||
map.insert(
|
||||
child,
|
||||
crate::sparse_tree::NTreeNode {
|
||||
attribute: 2u32,
|
||||
subdivided: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let tree = NTree::<2, u32>::from_nodes(map, 4);
|
||||
let mut cursor = Cursor::new(Vec::new());
|
||||
write_tree(&mut cursor, &tree, U32_LAYOUT).unwrap();
|
||||
|
||||
let bytes = cursor.into_inner();
|
||||
let chunks = bodies(&bytes);
|
||||
|
||||
// Attributes, level 0 and level 1 only.
|
||||
assert_eq!(chunks.len(), 3);
|
||||
|
||||
let mut cursor = Cursor::new(&bytes);
|
||||
let file = crate::io::read::read_tree::<_, 2, u32>(&mut cursor, Some(U32_LAYOUT)).unwrap();
|
||||
|
||||
assert_eq!(file.tree.depth(), 4);
|
||||
assert_eq!(file.tree.node_count(), 9);
|
||||
assert_eq!(file.tree.get(0, 0, 0), 2);
|
||||
assert_eq!(file.tree.get(15, 15, 15), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
#![allow(incomplete_features)]
|
||||
#![feature(generic_const_exprs)]
|
||||
|
||||
//! Producer-side API: produced nodes, producers, and the attribute vocabulary
|
||||
//! re-exported from `vxls-attributes`.
|
||||
//!
|
||||
//! A voxel payload is described by a type implementing [`Attributes`]. Each
|
||||
//! non-skipped field of that type becomes one cache attribute, stored in its
|
||||
//! own GPU buffer (`word_count` 32-bit words per voxel). The order of the
|
||||
//! fields is the order of the attribute bindings, so it is the same order the
|
||||
//! shaders index.
|
||||
//!
|
||||
//! [`Attributes`] is a sub-trait of [`Attribute`], which means a payload struct
|
||||
//! can be used everywhere a single attribute used to be: sparse trees, produced
|
||||
//! nodes and producers.
|
||||
//!
|
||||
//! ```ignore
|
||||
//! #[derive(Clone, Copy, PartialEq, Default, Pod, Zeroable, Attributes)]
|
||||
//! #[repr(C)]
|
||||
//! struct MyAttributes
|
||||
//! {
|
||||
//! #[attribute(label = "color", semantic = "color")]
|
||||
//! color: u32,
|
||||
//! #[attribute(label = "normal", semantic = "normal")]
|
||||
//! normal: [f32; 3],
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
pub use bytemuck;
|
||||
pub use vxls_attributes::*;
|
||||
pub use vxls_voxel_cache::schema::StructureAnchor;
|
||||
|
||||
mod producer;
|
||||
|
||||
pub use producer::*;
|
||||
|
||||
/// A structure locator format to locate node within an ntree
|
||||
pub mod tree_locator;
|
||||
|
||||
/// Sparse NTree to store voxel data
|
||||
pub mod sparse_tree;
|
||||
|
||||
/// Bounded, deduplicating, priority-ordered cache request queue
|
||||
pub mod request_queue;
|
||||
|
||||
/// Routing voxel production to different producers
|
||||
pub mod production_router;
|
||||
|
||||
pub mod io;
|
||||
@@ -0,0 +1,305 @@
|
||||
#![allow(incomplete_features)]
|
||||
#![feature(generic_const_exprs)]
|
||||
use std::fs::File;
|
||||
|
||||
use bytemuck::Zeroable;
|
||||
use vxls_attributes::Attributes;
|
||||
use vxls_production::io::write_tree;
|
||||
use vxls_production::sparse_tree::Color;
|
||||
use vxls_production::sparse_tree::ColorByte;
|
||||
use vxls_production::sparse_tree::NTree;
|
||||
|
||||
/// Side length of the dense voxel grid.
|
||||
const GRID: usize = 256;
|
||||
const GRID_SQ: usize = GRID * GRID;
|
||||
const VOXEL_COUNT: usize = GRID * GRID * GRID;
|
||||
|
||||
/// Number of smoothing passes. Each pass applies a 3D Gaussian approximation
|
||||
/// with a support of 5 voxels, so two passes give a smooth normal field.
|
||||
const BLUR_PASSES: usize = 2;
|
||||
|
||||
/// Voxel coordinates are stored as `x + z * GRID + y * GRID^2`, matching the
|
||||
/// order used by `dragon.txt`.
|
||||
#[inline]
|
||||
fn voxel_index(x: usize, y: usize, z: usize) -> usize {
|
||||
x + z * GRID + y * GRID_SQ
|
||||
}
|
||||
|
||||
/// Pushes `(x, y, z)` onto the flood fill stack if it is empty and not yet
|
||||
/// marked as exterior.
|
||||
#[inline]
|
||||
fn seed_exterior(
|
||||
exterior: &mut [bool],
|
||||
stack: &mut Vec<u32>,
|
||||
occupied: &[bool],
|
||||
x: usize,
|
||||
y: usize,
|
||||
z: usize,
|
||||
) {
|
||||
let index = voxel_index(x, y, z);
|
||||
if !occupied[index] && !exterior[index] {
|
||||
exterior[index] = true;
|
||||
stack.push(index as u32);
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks every empty voxel reachable from the grid border.
|
||||
fn exterior_mask(occupied: &[bool]) -> Vec<bool> {
|
||||
let mut exterior = vec![false; VOXEL_COUNT];
|
||||
let mut stack = Vec::new();
|
||||
|
||||
// Seed from the six grid faces. Every air region connected to the outside
|
||||
// is reachable from one of them.
|
||||
for z in 0..GRID {
|
||||
for y in 0..GRID {
|
||||
seed_exterior(&mut exterior, &mut stack, occupied, 0, y, z);
|
||||
seed_exterior(&mut exterior, &mut stack, occupied, GRID - 1, y, z);
|
||||
}
|
||||
}
|
||||
for z in 0..GRID {
|
||||
for x in 0..GRID {
|
||||
seed_exterior(&mut exterior, &mut stack, occupied, x, 0, z);
|
||||
seed_exterior(&mut exterior, &mut stack, occupied, x, GRID - 1, z);
|
||||
}
|
||||
}
|
||||
for y in 0..GRID {
|
||||
for x in 0..GRID {
|
||||
seed_exterior(&mut exterior, &mut stack, occupied, x, y, 0);
|
||||
seed_exterior(&mut exterior, &mut stack, occupied, x, y, GRID - 1);
|
||||
}
|
||||
}
|
||||
|
||||
while let Some(index) = stack.pop() {
|
||||
let index = index as usize;
|
||||
let x = index % GRID;
|
||||
let z = (index / GRID) % GRID;
|
||||
let y = index / GRID_SQ;
|
||||
|
||||
if x > 0 {
|
||||
seed_exterior(&mut exterior, &mut stack, occupied, x - 1, y, z);
|
||||
}
|
||||
if x + 1 < GRID {
|
||||
seed_exterior(&mut exterior, &mut stack, occupied, x + 1, y, z);
|
||||
}
|
||||
if y > 0 {
|
||||
seed_exterior(&mut exterior, &mut stack, occupied, x, y - 1, z);
|
||||
}
|
||||
if y + 1 < GRID {
|
||||
seed_exterior(&mut exterior, &mut stack, occupied, x, y + 1, z);
|
||||
}
|
||||
if z > 0 {
|
||||
seed_exterior(&mut exterior, &mut stack, occupied, x, y, z - 1);
|
||||
}
|
||||
if z + 1 < GRID {
|
||||
seed_exterior(&mut exterior, &mut stack, occupied, x, y, z + 1);
|
||||
}
|
||||
}
|
||||
|
||||
exterior
|
||||
}
|
||||
|
||||
/// Builds a smoothable field that is `1` inside the dragon and `0` outside.
|
||||
///
|
||||
/// `dragon.txt` only samples the surface, so the occupied voxels form a thin
|
||||
/// shell. Blurring that shell directly produces a density that peaks on the
|
||||
/// shell, where the gradient is close to zero. Filling the enclosed volume
|
||||
/// first makes the blurred field ramp across the surface, so its gradient is
|
||||
/// well defined there.
|
||||
fn solid_field(occupied: &[bool]) -> Vec<f32> {
|
||||
let exterior = exterior_mask(occupied);
|
||||
|
||||
(0..VOXEL_COUNT)
|
||||
.map(|index| {
|
||||
// Anything occupied, or empty but not connected to the outside,
|
||||
// belongs to the solid.
|
||||
if occupied[index] || !exterior[index] {
|
||||
1.0
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Separable [`1, 4, 6, 4, 1`] / 16 blur along `x` (clamped at the borders).
|
||||
fn blur_x(src: &[f32], dst: &mut [f32]) {
|
||||
for y in 0..GRID {
|
||||
for z in 0..GRID {
|
||||
let base = z * GRID + y * GRID_SQ;
|
||||
for x in 0..GRID {
|
||||
let xm2 = x.saturating_sub(2);
|
||||
let xm1 = x.saturating_sub(1);
|
||||
let xp1 = (x + 1).min(GRID - 1);
|
||||
let xp2 = (x + 2).min(GRID - 1);
|
||||
|
||||
dst[base + x] = (src[base + xm2]
|
||||
+ 4.0 * src[base + xm1]
|
||||
+ 6.0 * src[base + x]
|
||||
+ 4.0 * src[base + xp1]
|
||||
+ src[base + xp2])
|
||||
* (1.0 / 16.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Separable [`1, 4, 6, 4, 1`] / 16 blur along `y` (clamped at the borders).
|
||||
fn blur_y(src: &[f32], dst: &mut [f32]) {
|
||||
for z in 0..GRID {
|
||||
for x in 0..GRID {
|
||||
let base = z * GRID + x;
|
||||
for y in 0..GRID {
|
||||
let ym2 = y.saturating_sub(2);
|
||||
let ym1 = y.saturating_sub(1);
|
||||
let yp1 = (y + 1).min(GRID - 1);
|
||||
let yp2 = (y + 2).min(GRID - 1);
|
||||
|
||||
dst[base + y * GRID_SQ] = (src[base + ym2 * GRID_SQ]
|
||||
+ 4.0 * src[base + ym1 * GRID_SQ]
|
||||
+ 6.0 * src[base + y * GRID_SQ]
|
||||
+ 4.0 * src[base + yp1 * GRID_SQ]
|
||||
+ src[base + yp2 * GRID_SQ])
|
||||
* (1.0 / 16.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Separable [`1, 4, 6, 4, 1`] / 16 blur along `z` (clamped at the borders).
|
||||
fn blur_z(src: &[f32], dst: &mut [f32]) {
|
||||
for y in 0..GRID {
|
||||
for x in 0..GRID {
|
||||
let base = y * GRID_SQ + x;
|
||||
for z in 0..GRID {
|
||||
let zm2 = z.saturating_sub(2);
|
||||
let zm1 = z.saturating_sub(1);
|
||||
let zp1 = (z + 1).min(GRID - 1);
|
||||
let zp2 = (z + 2).min(GRID - 1);
|
||||
|
||||
dst[base + z * GRID] = (src[base + zm2 * GRID]
|
||||
+ 4.0 * src[base + zm1 * GRID]
|
||||
+ 6.0 * src[base + z * GRID]
|
||||
+ 4.0 * src[base + zp1 * GRID]
|
||||
+ src[base + zp2 * GRID])
|
||||
* (1.0 / 16.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes an outward unit normal for every occupied voxel from the smoothed
|
||||
/// solid field.
|
||||
///
|
||||
/// The field is `1` inside and `0` outside, so its gradient points inwards;
|
||||
/// the outward normal is the negated, normalised gradient.
|
||||
fn compute_normals(occupied: &[bool], field: &[f32], normals: &mut [[f32; 3]]) {
|
||||
for z in 0..GRID {
|
||||
for y in 0..GRID {
|
||||
for x in 0..GRID {
|
||||
let index = voxel_index(x, y, z);
|
||||
if !occupied[index] {
|
||||
continue;
|
||||
}
|
||||
|
||||
let xm = voxel_index(x.saturating_sub(1), y, z);
|
||||
let xp = voxel_index((x + 1).min(GRID - 1), y, z);
|
||||
let ym = voxel_index(x, y.saturating_sub(1), z);
|
||||
let yp = voxel_index(x, (y + 1).min(GRID - 1), z);
|
||||
let zm = voxel_index(x, y, z.saturating_sub(1));
|
||||
let zp = voxel_index(x, y, (z + 1).min(GRID - 1));
|
||||
|
||||
let gx = field[xp] - field[xm];
|
||||
let gy = field[yp] - field[ym];
|
||||
let gz = field[zp] - field[zm];
|
||||
|
||||
let (nx, ny, nz) = (-gx, -gy, -gz);
|
||||
let length = (nx * nx + ny * ny + nz * nz).sqrt();
|
||||
|
||||
normals[index] = if length > 1e-6 {
|
||||
[nx / length, ny / length, nz / length]
|
||||
} else {
|
||||
// Degenerate gradient (for example a voxel fully enclosed
|
||||
// by the solid): keep a sane unit normal.
|
||||
[0.0, 1.0, 0.0]
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Attributes, PartialEq, Clone, Copy, Default, bytemuck::Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
struct VoxelPayload {
|
||||
#[attribute(label = "color", semantic = "color")]
|
||||
color_byte: ColorByte,
|
||||
|
||||
#[attribute(label = "normal", semantic = "normal")]
|
||||
normal: [f32; 3],
|
||||
}
|
||||
|
||||
// impl Attribute for VoxelPayload
|
||||
// {
|
||||
// fn average(attributes: &[Self]) -> Self {
|
||||
// let colors: Vec<ColorByte> = attributes.iter().map(|a| a.color_byte).collect();
|
||||
// let normals: Vec<[f32; 3]> = attributes.iter().map(|a| a.normal).collect();
|
||||
//
|
||||
// Self
|
||||
// {
|
||||
// color_byte: ColorByte::average(&colors),
|
||||
// normal: <[f32; 3] as Attribute>::average(&normals),
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
fn main() {
|
||||
let file = std::fs::read_to_string("../../dragon.txt").unwrap();
|
||||
|
||||
let mut colors = vec![Color::default(); VOXEL_COUNT];
|
||||
let mut normals = vec![[0.0f32; 3]; VOXEL_COUNT];
|
||||
|
||||
// Load file
|
||||
for line in file.lines() {
|
||||
let coords = line
|
||||
.split(',')
|
||||
.take(3)
|
||||
.map(|s| s.trim_end().trim_start().parse::<u32>().unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
let (x, y, z) = (coords[0] as usize, coords[1] as usize, coords[2] as usize);
|
||||
let index = voxel_index(x, y, z);
|
||||
colors[index] = Color(1., 1., 1., 1.);
|
||||
}
|
||||
|
||||
// Occupancy comes straight from the loaded colors (alpha > 0).
|
||||
let occupied: Vec<bool> = colors.iter().map(|color| color.3 != 0.0).collect();
|
||||
|
||||
// Smooth a solid version of the occupancy, then read the surface normal
|
||||
// from the gradient of the smoothed field.
|
||||
let mut field = solid_field(&occupied);
|
||||
let mut scratch = vec![0.0f32; VOXEL_COUNT];
|
||||
|
||||
for _ in 0..BLUR_PASSES {
|
||||
blur_x(&field, &mut scratch);
|
||||
blur_y(&scratch, &mut field);
|
||||
blur_z(&field, &mut scratch);
|
||||
std::mem::swap(&mut field, &mut scratch);
|
||||
}
|
||||
|
||||
compute_normals(&occupied, &field, &mut normals);
|
||||
|
||||
let bundled: Vec<_> = colors
|
||||
.iter()
|
||||
.zip(normals.iter())
|
||||
.map(|(color, normal)| VoxelPayload {
|
||||
color_byte: color.as_color_byte(),
|
||||
normal: *normal,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let tree: NTree<4, _> = NTree::from_array(&bundled, 4);
|
||||
write_tree(
|
||||
&mut File::create("../../dragon.vxls").unwrap(),
|
||||
&tree,
|
||||
VoxelPayload::LAYOUT,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
//! Producers and the nodes they produce.
|
||||
|
||||
use vxls_voxel_cache::insertion::CacheInsertionData;
|
||||
use vxls_voxel_cache::schema::InsertionInformation;
|
||||
|
||||
pub use vxls_voxel_cache::insertion::AttributeUploadError;
|
||||
pub use vxls_voxel_cache::schema::ProducerId;
|
||||
pub use vxls_voxel_cache::schema::StructureLocator;
|
||||
|
||||
use crate::Attributes;
|
||||
use crate::StructureAnchor;
|
||||
|
||||
/// A node produced by a [`Producer`], ready to be inserted into the cache.
|
||||
///
|
||||
/// The producer only provides the structure of the page ([`InsertionInformation`])
|
||||
/// and its voxels. Cache-owned identity (node id, producer id, anchor, depth)
|
||||
/// is attached by the host from the request, so producers cannot forge it.
|
||||
pub struct ProducedNode<const N: usize, A: Attributes>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
/// Structure of the produced page
|
||||
pub insertion: InsertionInformation<N>,
|
||||
|
||||
/// The voxels of the page, in child-major order (`x + 4*y + 16*z`)
|
||||
pub attributes: [A; N * N * N],
|
||||
}
|
||||
|
||||
impl<const N: usize, A: Attributes> ProducedNode<N, A>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
/// Creates a produced node
|
||||
pub fn new(insertion: InsertionInformation<N>, attributes: [A; N * N * N]) -> Self {
|
||||
Self {
|
||||
insertion,
|
||||
attributes,
|
||||
}
|
||||
}
|
||||
|
||||
/// The produced voxels
|
||||
pub fn attributes(&self) -> &[A] {
|
||||
&self.attributes
|
||||
}
|
||||
|
||||
/// The produced voxels, mutably
|
||||
pub fn attributes_mut(&mut self) -> &mut [A] {
|
||||
&mut self.attributes
|
||||
}
|
||||
|
||||
/// Uploads this node's voxels into an insertion batch.
|
||||
///
|
||||
/// Returns the number of entries the batch now describes, which is `1`
|
||||
/// for a single produced node.
|
||||
pub fn write_attributes_into(
|
||||
&self,
|
||||
queue: &wgpu::Queue,
|
||||
insertion: &CacheInsertionData<N>,
|
||||
) -> Result<usize, AttributeUploadError> {
|
||||
insertion.write_attributes(queue, &self.attributes)
|
||||
}
|
||||
|
||||
/// Writes attribute `index` of every child to `out`, in the
|
||||
/// `[child][word]` order expected by the cache insertion buffer.
|
||||
///
|
||||
/// This transposes the CPU-side array-of-structs into the per-attribute
|
||||
/// buffer layout. `out` is cleared first.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `index` is not a valid attribute index.
|
||||
pub fn write_attribute_words(&self, index: usize, out: &mut Vec<u32>) {
|
||||
let word_count = A::LAYOUT.attributes[index].word_count as usize;
|
||||
|
||||
out.clear();
|
||||
out.reserve(self.attributes.len() * word_count);
|
||||
|
||||
for node in &self.attributes {
|
||||
let bytes = node.get_attr(index);
|
||||
debug_assert_eq!(
|
||||
bytes.len(),
|
||||
word_count * size_of::<u32>(),
|
||||
"attribute size does not match its declared word count",
|
||||
);
|
||||
|
||||
for word in bytes.chunks_exact(size_of::<u32>()) {
|
||||
out.push(u32::from_ne_bytes(
|
||||
word.try_into().expect("chunks_exact yields 4-byte slices"),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Produces cache pages on demand
|
||||
pub trait Producer<const N: usize, A: Attributes>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
/// Produces the node requested by `locator`, inside `anchor`.
|
||||
///
|
||||
/// `locator` is the content-local path of the requested node; use
|
||||
/// [`crate::tree_locator::TreeLocator`] (and its `From<StructureLocator>`
|
||||
/// impl) to decode it into coordinates.
|
||||
fn produce(&self, anchor: StructureAnchor, locator: StructureLocator) -> ProducedNode<N, A>;
|
||||
}
|
||||
|
||||
pub struct FnProducer<T, A, const N: usize>
|
||||
where
|
||||
T: Fn(StructureAnchor, StructureLocator) -> ProducedNode<N, A>,
|
||||
A: Attributes,
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
f: T,
|
||||
}
|
||||
|
||||
impl<T, A, const N: usize> FnProducer<T, A, N>
|
||||
where
|
||||
T: Fn(StructureAnchor, StructureLocator) -> ProducedNode<N, A>,
|
||||
A: Attributes,
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(f: T) -> Self {
|
||||
Self { f }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, A, const N: usize> Producer<N, A> for FnProducer<T, A, N>
|
||||
where
|
||||
T: Fn(StructureAnchor, StructureLocator) -> ProducedNode<N, A>,
|
||||
A: Attributes,
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
fn produce(&self, anchor: StructureAnchor, locator: StructureLocator) -> ProducedNode<N, A> {
|
||||
(self.f)(anchor, locator)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,506 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
use itertools::Itertools;
|
||||
|
||||
use super::tree_locator::TreeLocator;
|
||||
|
||||
use crate::Attribute;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct Color(pub f32, pub f32, pub f32, pub f32);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct ColorByte(pub u32);
|
||||
|
||||
// `Attribute` requires `Eq`. `Color` is only ever constructed from finite,
|
||||
// non-NaN values in this crate, so equality is well-behaved here.
|
||||
impl Eq for Color {}
|
||||
|
||||
impl Attribute for Color {
|
||||
fn average(attributes: &[Self]) -> Self {
|
||||
if attributes.is_empty() {
|
||||
return Self::default();
|
||||
}
|
||||
|
||||
let mut c = Self::default();
|
||||
for color in attributes {
|
||||
c.0 += color.0;
|
||||
c.1 += color.1;
|
||||
c.2 += color.2;
|
||||
c.3 += color.3;
|
||||
}
|
||||
|
||||
//let count = attributes.len() as f32;
|
||||
let count = c.3;
|
||||
c.0 /= count;
|
||||
c.1 /= count;
|
||||
c.2 /= count;
|
||||
c.3 /= count;
|
||||
c
|
||||
}
|
||||
}
|
||||
|
||||
impl Attribute for ColorByte {
|
||||
fn average(attributes: &[Self]) -> Self {
|
||||
if attributes.is_empty() {
|
||||
return Self::default();
|
||||
}
|
||||
|
||||
let mut c = Color::default();
|
||||
for color in attributes {
|
||||
let color = color.as_color();
|
||||
c.0 += color.0;
|
||||
c.1 += color.1;
|
||||
c.2 += color.2;
|
||||
c.3 += color.3;
|
||||
}
|
||||
|
||||
//let count = attributes.len() as f32;
|
||||
let count = c.3;
|
||||
c.0 /= count;
|
||||
c.1 /= count;
|
||||
c.2 /= count;
|
||||
c.3 /= count;
|
||||
ColorByte(c.as_packed_u32())
|
||||
}
|
||||
}
|
||||
|
||||
impl Color {
|
||||
pub fn as_packed_u32(&self) -> u32 {
|
||||
let mapped_r = (self.0 * 255.0).clamp(0., 255.0) as u32;
|
||||
let mapped_g = (self.1 * 255.0).clamp(0., 255.0) as u32;
|
||||
let mapped_b = (self.2 * 255.0).clamp(0., 255.0) as u32;
|
||||
let mapped_a = (self.3 * 255.0).clamp(0., 255.0) as u32;
|
||||
mapped_r | (mapped_g << 8) | (mapped_b << 16) | (mapped_a << 24)
|
||||
}
|
||||
|
||||
pub fn as_color_byte(&self) -> ColorByte {
|
||||
ColorByte(self.as_packed_u32())
|
||||
}
|
||||
}
|
||||
|
||||
impl ColorByte {
|
||||
pub fn as_color(&self) -> Color {
|
||||
let r = (self.0 & 0xFF) as f32 / 255.0;
|
||||
let g = ((self.0 >> 8) & 0xFF) as f32 / 255.0;
|
||||
let b = ((self.0 >> 16) & 0xFF) as f32 / 255.0;
|
||||
let a = ((self.0 >> 24) & 0xFF) as f32 / 255.0;
|
||||
Color(r, g, b, a)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NTree<const N: usize, T: Attribute> {
|
||||
map: HashMap<TreeLocator<N>, NTreeNode<T>>,
|
||||
|
||||
// Depth is the parameter such that
|
||||
// N^depth == max_number_of_voxels
|
||||
// one root => depth = 1
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct NTreeNode<T: Attribute> {
|
||||
pub attribute: T,
|
||||
pub subdivided: bool,
|
||||
}
|
||||
|
||||
impl<const N: usize, T: Attribute> NTree<N, T> {
|
||||
/// Maximum voxel depth: the tree spans `N.pow(depth)` voxels per axis.
|
||||
pub fn depth(&self) -> usize {
|
||||
self.depth
|
||||
}
|
||||
|
||||
/// Number of nodes currently stored, reachable from the root or not.
|
||||
pub fn node_count(&self) -> usize {
|
||||
self.map.len()
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize, T> NTree<N, T>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
T: Attribute,
|
||||
{
|
||||
pub fn constant(value: T, depth: usize) -> Self {
|
||||
let mut map = HashMap::new();
|
||||
let root = NTreeNode {
|
||||
attribute: value,
|
||||
subdivided: false,
|
||||
};
|
||||
map.insert(TreeLocator::<N>::root(), root);
|
||||
Self { map, depth }
|
||||
}
|
||||
|
||||
pub fn set(&mut self, x: usize, y: usize, z: usize, value: T) {
|
||||
self.set_at_depth(x, y, z, self.depth, value);
|
||||
}
|
||||
|
||||
pub fn mapped<D: Attribute, F: FnMut(&T) -> D>(&self, mut map: F) -> NTree<N, D> {
|
||||
NTree::<N, D> {
|
||||
map: self
|
||||
.map
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
(
|
||||
*k,
|
||||
NTreeNode {
|
||||
attribute: map(&v.attribute),
|
||||
subdivided: v.subdivided,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
depth: self.depth,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get(&self, x: usize, y: usize, z: usize) -> T {
|
||||
assert!(x < N.pow(self.depth as u32));
|
||||
assert!(y < N.pow(self.depth as u32));
|
||||
assert!(z < N.pow(self.depth as u32));
|
||||
|
||||
// Try to walk down the tree, and create necessary nodes
|
||||
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();
|
||||
|
||||
loop {
|
||||
if !current_node.subdivided {
|
||||
return current_node.attribute;
|
||||
}
|
||||
|
||||
// Descend to relevant node,
|
||||
let child_node_size = current_node_size / N;
|
||||
let child_x = (x % current_node_size) / child_node_size;
|
||||
let child_y = (y % current_node_size) / child_node_size;
|
||||
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 as u32, child_y as u32, child_z as u32);
|
||||
current_node = self.map.get(¤t_node_loc).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_at_depth(&mut self, x: usize, y: usize, z: usize, depth: usize, value: T) {
|
||||
assert!(x < N.pow(depth as u32));
|
||||
assert!(y < N.pow(depth as u32));
|
||||
assert!(z < N.pow(depth as u32));
|
||||
|
||||
// Try to walk down the tree, and create necessary nodes
|
||||
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();
|
||||
|
||||
while current_depth != depth {
|
||||
if current_node.attribute == value {
|
||||
// Attribute is already correct, work is finished
|
||||
return;
|
||||
}
|
||||
|
||||
// Current is not subdivided, and attribute is different => subdivide
|
||||
if !current_node.subdivided {
|
||||
current_node.subdivided = true;
|
||||
let new_nodes = NTreeNode {
|
||||
attribute: current_node.attribute,
|
||||
subdivided: false,
|
||||
};
|
||||
current_node_loc.children().for_each(|child| {
|
||||
self.map.insert(child, new_nodes);
|
||||
});
|
||||
}
|
||||
|
||||
// Descend to relevant node,
|
||||
let child_node_size = current_node_size / N;
|
||||
let child_x = (x % current_node_size) / child_node_size;
|
||||
let child_y = (y % current_node_size) / child_node_size;
|
||||
let child_z = (z % current_node_size) / child_node_size;
|
||||
current_node_size = child_node_size;
|
||||
current_depth += 1;
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
if current_node.subdivided {
|
||||
self.make_constant(current_node_loc, value);
|
||||
} else {
|
||||
current_node.attribute = value;
|
||||
}
|
||||
|
||||
// We need to go back up the hierarchy to combine nodes
|
||||
// current_node is the modified node, go one up
|
||||
|
||||
loop {
|
||||
// Go one node up
|
||||
current_depth -= 1;
|
||||
current_node_loc = current_node_loc.parent().unwrap();
|
||||
//current_node_size *= N;
|
||||
|
||||
// Access all children's attributes
|
||||
let children_attributes = current_node_loc
|
||||
.children()
|
||||
.map(|child_loc| self.map.get(&child_loc).unwrap().attribute)
|
||||
.collect::<Vec<_>>();
|
||||
let children_attribute_avg = T::average(&children_attributes);
|
||||
|
||||
current_node = self.map.get_mut(¤t_node_loc).unwrap();
|
||||
current_node.attribute = children_attribute_avg;
|
||||
|
||||
if current_depth == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn make_constant(&mut self, locator: TreeLocator<N>, value: T) {
|
||||
let mut dfs_stack = Vec::new();
|
||||
dfs_stack.push(locator);
|
||||
|
||||
while let Some(current) = dfs_stack.pop() {
|
||||
// Remove element
|
||||
let removed = self.map.remove(¤t);
|
||||
let handle_children = removed.is_some_and(|x| x.subdivided);
|
||||
|
||||
// If children have to be handled, push on stack
|
||||
if handle_children {
|
||||
dfs_stack.extend(current.children());
|
||||
}
|
||||
}
|
||||
|
||||
self.map.insert(
|
||||
locator,
|
||||
NTreeNode {
|
||||
attribute: value,
|
||||
subdivided: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
pub fn from_array(array: &[T], depth: usize) -> Self {
|
||||
let mut structure = HashMap::new();
|
||||
// Per voxel in the array :
|
||||
// 0 -> Voxel not merged yet
|
||||
// _ -> size of the block in which the voxel was merged
|
||||
let mut merged_size = vec![0; array.len()];
|
||||
let width = N.pow(depth as u32);
|
||||
|
||||
for (z, y) in (0..width).cartesian_product(0..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
|
||||
x += merged_size[x + y * width + z * width * width];
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check smallest depth aligned with current position
|
||||
let x_trailing = base_trailing_zeroes::<N>(x).unwrap_or(depth as u32);
|
||||
let y_trailing = base_trailing_zeroes::<N>(y).unwrap_or(depth as u32);
|
||||
let z_trailing = base_trailing_zeroes::<N>(z).unwrap_or(depth as u32);
|
||||
|
||||
// Biggest block size power of which this voxel can be a lower corner
|
||||
let block_power = x_trailing.min(y_trailing.min(z_trailing));
|
||||
|
||||
// Try to merge for each depth
|
||||
let mut max_power_merge = 0; // Single voxel can always be merged
|
||||
let attribute = array[x + y * width + z * width * width];
|
||||
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 attribute
|
||||
for ((merge_z, merge_y), merge_x) in (0..block_size)
|
||||
.cartesian_product(0..block_size)
|
||||
.cartesian_product(0..block_size)
|
||||
{
|
||||
if array
|
||||
[(x + merge_x) + (y + merge_y) * width + (z + merge_z) * width * width]
|
||||
!= attribute
|
||||
{
|
||||
break 'power_search;
|
||||
}
|
||||
}
|
||||
|
||||
// Update biggest candidate block
|
||||
locator = locator.parent().unwrap();
|
||||
max_power_merge = power;
|
||||
}
|
||||
|
||||
// We know which size we can know merge
|
||||
// Say we accounted for those voxels :
|
||||
let block_size = N.pow(max_power_merge);
|
||||
for ((merge_z, merge_y), merge_x) in (0..block_size)
|
||||
.cartesian_product(0..block_size)
|
||||
.cartesian_product(0..block_size)
|
||||
{
|
||||
merged_size
|
||||
[(x + merge_x) + (y + merge_y) * width + (z + merge_z) * width * width] =
|
||||
block_size;
|
||||
}
|
||||
|
||||
// Add new found block in our structure
|
||||
// If power is depth, this is the whole structure, thus depth is 0
|
||||
let node = NTreeNode {
|
||||
attribute,
|
||||
subdivided: false,
|
||||
};
|
||||
structure.insert(locator, node);
|
||||
x += block_size;
|
||||
}
|
||||
}
|
||||
|
||||
// The structure now consists of the leaf most nodes, we need to rebuild the hierarchy
|
||||
// bottom up
|
||||
for current_power in 1..=depth {
|
||||
// Iterate on the blocks of this size
|
||||
let block_size = N.pow(current_power as u32);
|
||||
let block_count = width / block_size;
|
||||
|
||||
for ((block_x, block_y), block_z) in (0..block_count)
|
||||
.cartesian_product(0..block_count)
|
||||
.cartesian_product(0..block_count)
|
||||
{
|
||||
// Check the lower corner of this block
|
||||
let corner = merged_size[(block_x * block_size)
|
||||
+ (block_y * block_size) * width
|
||||
+ (block_z * block_size) * width * width];
|
||||
if corner >= block_size {
|
||||
// Children are merged in bigger block
|
||||
continue;
|
||||
}
|
||||
|
||||
// Add hierarchy node
|
||||
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 attribute of children
|
||||
let children = locator
|
||||
.children()
|
||||
.map(|child_loc| structure.get(&child_loc).unwrap().attribute)
|
||||
.collect::<Vec<_>>();
|
||||
let attribute = T::average(&children);
|
||||
|
||||
let hierarchy_node = NTreeNode {
|
||||
attribute,
|
||||
subdivided: true,
|
||||
};
|
||||
structure.insert(locator, hierarchy_node);
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
map: structure,
|
||||
depth,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_by_loc(&self, locator: TreeLocator<N>) -> Option<NTreeNode<T>> {
|
||||
self.map.get(&locator).copied()
|
||||
}
|
||||
|
||||
/// Rebuilds a tree from raw nodes.
|
||||
///
|
||||
/// Crate-private: the file reader is the only caller, and it is responsible
|
||||
/// for maintaining the invariant that a subdivided node has all `N * N * N`
|
||||
/// children.
|
||||
pub(crate) fn from_nodes(map: HashMap<TreeLocator<N>, NTreeNode<T>>, depth: usize) -> Self {
|
||||
Self { map, depth }
|
||||
}
|
||||
}
|
||||
|
||||
fn base_trailing_zeroes<const N: usize>(mut number: usize) -> Option<u32> {
|
||||
if number == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut trailing_zeroes = 0;
|
||||
while number.is_multiple_of(N) {
|
||||
number /= N;
|
||||
trailing_zeroes += 1;
|
||||
}
|
||||
|
||||
Some(trailing_zeroes)
|
||||
}
|
||||
|
||||
pub fn load_ply<P: AsRef<std::path::Path>, const N: usize>(path: P) -> NTree<N, Color>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
let file = std::fs::read_to_string(path).unwrap();
|
||||
|
||||
let mut colors = vec![Color::default(); 256 * 256 * 256];
|
||||
for line in file.lines() {
|
||||
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.);
|
||||
}
|
||||
|
||||
NTree::<N, Color>::from_array(&colors, 4)
|
||||
}
|
||||
|
||||
mod test {
|
||||
#[allow(unused_imports)]
|
||||
use crate::sparse_tree::Color;
|
||||
#[allow(unused_imports)]
|
||||
use crate::sparse_tree::NTree;
|
||||
|
||||
#[test]
|
||||
fn constant_set() {
|
||||
let mut tree = NTree::<4, Color>::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.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_read_same() {
|
||||
let file =
|
||||
std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../dragon.txt"))
|
||||
.unwrap();
|
||||
|
||||
let mut colors = vec![Color(0., 0., 0., 0.); 256 * 256 * 256];
|
||||
for line in file.lines() {
|
||||
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.);
|
||||
}
|
||||
|
||||
println!("building tree");
|
||||
let tree = NTree::<4, Color>::from_array(&colors, 4);
|
||||
println!("ok");
|
||||
|
||||
for x in 0..256 {
|
||||
for y in 0..256 {
|
||||
for z in 0..256 {
|
||||
let index = x + y * 256 + z * 256 * 256;
|
||||
let color = colors[index];
|
||||
let t = tree.get(x, y, z);
|
||||
assert!(t == color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
use itertools::Itertools;
|
||||
|
||||
use crate::StructureLocator;
|
||||
|
||||
/// Compact location of a specific node within a Voxel tree data strcutrure : depth + location
|
||||
///
|
||||
/// The location is encoded as one number per coordinate.
|
||||
/// A coordinate is interpreted as base `N` number.
|
||||
/// The base `N` digits represent the path take from the root down to the node, therminated by a
|
||||
/// `1` digit.
|
||||
///
|
||||
/// Thus a encoded location of `1` refers to the root : Only node of depth 0
|
||||
///
|
||||
/// 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, Hash, PartialEq, Eq, Debug)]
|
||||
pub struct TreeLocator<const N: usize> {
|
||||
x: u32,
|
||||
y: u32,
|
||||
z: u32,
|
||||
}
|
||||
|
||||
impl<const N: usize> From<StructureLocator> for TreeLocator<N> {
|
||||
fn from(value: StructureLocator) -> Self {
|
||||
let mut value = value.0;
|
||||
let mut locator = Self::root();
|
||||
let n = N as u32;
|
||||
|
||||
while value != 1 {
|
||||
let z = value % n;
|
||||
value /= n;
|
||||
let y = value % n;
|
||||
value /= n;
|
||||
let x = value % n;
|
||||
value /= n;
|
||||
|
||||
locator = locator.child(x, y, z)
|
||||
}
|
||||
locator
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> From<TreeLocator<N>> for StructureLocator {
|
||||
fn from(mut value: TreeLocator<N>) -> StructureLocator {
|
||||
let mut locator = 1u32;
|
||||
while !value.is_root() {
|
||||
let (x, y, z) = value.local_coords();
|
||||
value = value.parent().unwrap();
|
||||
|
||||
locator *= N as u32;
|
||||
locator += x;
|
||||
|
||||
locator *= N as u32;
|
||||
locator += y;
|
||||
|
||||
locator *= N as u32;
|
||||
locator += z;
|
||||
}
|
||||
|
||||
StructureLocator(locator)
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> TreeLocator<N> {
|
||||
pub const ROOT: TreeLocator<N> = TreeLocator { x: 1, y: 1, z: 1 };
|
||||
|
||||
pub fn root() -> Self {
|
||||
Self::ROOT
|
||||
}
|
||||
|
||||
/// Returns the locator of node at `depth`, with coordinates, in that depth coordinate space,
|
||||
/// `node_x` `node_y` `node_z`.
|
||||
///
|
||||
/// The `node_*` must be in the `0..N^depth` range.
|
||||
pub fn from_node_coords(depth: u32, node_x: u32, node_y: u32, node_z: u32) -> Self {
|
||||
// Check coordinate bounds
|
||||
assert!(
|
||||
node_x < N.pow(depth) as u32,
|
||||
"Node coordinates out of bounds."
|
||||
);
|
||||
assert!(
|
||||
node_y < N.pow(depth) as u32,
|
||||
"Node coordinates out of bounds."
|
||||
);
|
||||
assert!(
|
||||
node_z < N.pow(depth) as u32,
|
||||
"Node coordinates out of bounds."
|
||||
);
|
||||
|
||||
if depth == 0 {
|
||||
return Self::ROOT;
|
||||
}
|
||||
|
||||
// Puts a one in base-N on the Nth digit
|
||||
let one = N.pow(depth) as u32;
|
||||
Self {
|
||||
x: one + node_x,
|
||||
y: one + node_y,
|
||||
z: one + node_z,
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes the maximum depth supported for this tree arity
|
||||
pub fn max_depth() -> u32 {
|
||||
(u32::MAX as usize).ilog(N) - 1
|
||||
}
|
||||
|
||||
pub fn is_root(&self) -> bool {
|
||||
self.x == 1 && self.y == 1 && self.z == 1
|
||||
}
|
||||
|
||||
/// Returns the depth of the node located by `self`, 0 being the root
|
||||
pub fn depth(&self) -> u32 {
|
||||
// A number k takes floor(log_n(k)) + 1 digits in base n
|
||||
|
||||
// This is digits - 1 as the locator contains a 1 on the front
|
||||
self.x.ilog(N as u32)
|
||||
}
|
||||
|
||||
/// Returns the size in voxels of this node considering that a node at `max_depth` represents 1
|
||||
/// voxel
|
||||
pub fn node_size(&self, max_depth: u32) -> u32 {
|
||||
let depth = self.depth();
|
||||
|
||||
// 0 if voxel, max_depth if root
|
||||
let height = max_depth - depth;
|
||||
|
||||
N.pow(height) as u32
|
||||
}
|
||||
|
||||
/// Returns the locator of this node's parent, `None` if `self` is the root
|
||||
pub fn parent(&self) -> Option<Self> {
|
||||
if self.is_root() {
|
||||
None
|
||||
} else {
|
||||
Some(Self {
|
||||
x: self.x / N as u32,
|
||||
y: self.y / N as u32,
|
||||
z: self.z / N as u32,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the [`TreeLocator`] of the children of this node with coordinates `child_x`,
|
||||
/// `child_y`, `child_z` within this node.
|
||||
///
|
||||
/// The `child_*` coordinates must be in the `0..N` range.
|
||||
pub fn child(&self, child_x: u32, child_y: u32, child_z: u32) -> Self {
|
||||
// Check children bounds
|
||||
assert!(child_x < N as u32, "Out of bounds child coordinate.");
|
||||
assert!(child_y < N as u32, "Out of bounds child coordinate.");
|
||||
assert!(child_z < N as u32, "Out of bounds child coordinate.");
|
||||
|
||||
// Check depth bounds
|
||||
assert!(
|
||||
self.x.checked_mul(N as u32).is_some(),
|
||||
"TreeLocator too deep"
|
||||
);
|
||||
assert!(
|
||||
self.y.checked_mul(N as u32).is_some(),
|
||||
"TreeLocator too deep"
|
||||
);
|
||||
assert!(
|
||||
self.z.checked_mul(N as u32).is_some(),
|
||||
"TreeLocator too deep"
|
||||
);
|
||||
|
||||
let n = N as u32;
|
||||
Self {
|
||||
x: self.x * n + child_x,
|
||||
y: self.y * n + child_y,
|
||||
z: self.z * n + child_z,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an iterator on the children of this node
|
||||
pub fn children(&self) -> impl Iterator<Item = Self> {
|
||||
(0..N as u32)
|
||||
.cartesian_product(0..N as u32)
|
||||
.cartesian_product(0..N as u32)
|
||||
.map(|((z, y), x)| self.child(x, y, z))
|
||||
}
|
||||
|
||||
/// Returns the coordinate of this node inside its parent.
|
||||
/// The returned coordinate are in `0..N`
|
||||
pub fn local_coords(&self) -> (u32, u32, u32) {
|
||||
if self.is_root() {
|
||||
return (0, 0, 0);
|
||||
}
|
||||
|
||||
let x = self.x % N as u32;
|
||||
let y = self.y % N as u32;
|
||||
let z = self.z % N as u32;
|
||||
|
||||
(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)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn raw<const N: usize>(l: TreeLocator<N>) -> (u32, u32, u32) {
|
||||
(l.x, l.y, l.z)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_is_depth_zero() {
|
||||
let r = TreeLocator::<4>::root();
|
||||
assert!(r.is_root());
|
||||
assert_eq!(r.depth(), 0);
|
||||
assert_eq!(raw(r), (1, 1, 1));
|
||||
assert!(r.parent().is_none());
|
||||
assert_eq!(r.local_coords(), (0, 0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn child_encoding_matches_doc_example() {
|
||||
// Doc: `1032` in base 4 => child 0, then 3, then 2 => depth 3.
|
||||
let l = TreeLocator::<4>::root()
|
||||
.child(0, 0, 0)
|
||||
.child(3, 3, 3)
|
||||
.child(2, 2, 2);
|
||||
|
||||
// 0b1032 in base 4 = 1*64 + 0*16 + 3*4 + 2 = 78
|
||||
assert_eq!(raw(l), (78, 78, 78));
|
||||
assert_eq!(l.depth(), 3);
|
||||
assert!(!l.is_root());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn child_uses_independent_coordinates() {
|
||||
let c = TreeLocator::<4>::root().child(1, 2, 3);
|
||||
assert_eq!(raw(c), (4 + 1, 4 + 2, 4 + 3));
|
||||
assert_eq!(c.depth(), 1);
|
||||
assert_eq!(c.local_coords(), (1, 2, 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parent_undoes_child() {
|
||||
let root = TreeLocator::<4>::root();
|
||||
let c = root.child(3, 0, 2);
|
||||
let gc = c.child(1, 1, 0);
|
||||
|
||||
assert_eq!(raw(gc.parent().unwrap()), raw(c));
|
||||
assert_eq!(raw(c.parent().unwrap()), raw(root));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_node_coords_depth_zero_is_root() {
|
||||
let l = TreeLocator::<4>::from_node_coords(0, 0, 0, 0);
|
||||
assert!(l.is_root());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_node_coords_matches_child_walk() {
|
||||
// Node (5, 2, 7) at depth 2 in a 4-tree (coords in 0..16).
|
||||
// Base 4: x = 11, y = 02, z = 13.
|
||||
let direct = TreeLocator::<4>::from_node_coords(2, 5, 2, 7);
|
||||
let walked = TreeLocator::<4>::root().child(1, 0, 1).child(1, 2, 3);
|
||||
|
||||
assert_eq!(raw(direct), raw(walked));
|
||||
assert_eq!(direct.depth(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_node_coords_parent_is_coarser_node() {
|
||||
let l = TreeLocator::<4>::from_node_coords(3, 37, 12, 63);
|
||||
let p = TreeLocator::<4>::from_node_coords(2, 37 / 4, 12 / 4, 63 / 4);
|
||||
assert_eq!(raw(l.parent().unwrap()), raw(p));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_via_local_coords() {
|
||||
let original = TreeLocator::<3>::from_node_coords(4, 50, 7, 80);
|
||||
|
||||
// Walk up to the root, collecting local coords at each level.
|
||||
let mut path = Vec::new();
|
||||
let mut cur = original;
|
||||
while let Some(parent) = cur.parent() {
|
||||
path.push(cur.local_coords());
|
||||
cur = parent;
|
||||
}
|
||||
assert!(cur.is_root());
|
||||
assert_eq!(path.len() as u32, original.depth());
|
||||
|
||||
// Walk back down and rebuild.
|
||||
let mut rebuilt = TreeLocator::<3>::root();
|
||||
for (x, y, z) in path.into_iter().rev() {
|
||||
rebuilt = rebuilt.child(x, y, z);
|
||||
}
|
||||
assert_eq!(raw(rebuilt), raw(original));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn children_are_complete_distinct_and_valid() {
|
||||
let parent = TreeLocator::<3>::root().child(2, 1, 0);
|
||||
let kids: Vec<_> = parent.children().collect();
|
||||
|
||||
assert_eq!(kids.len(), 27);
|
||||
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut locals = std::collections::HashSet::new();
|
||||
for k in &kids {
|
||||
assert_eq!(k.depth(), parent.depth() + 1);
|
||||
assert_eq!(raw(k.parent().unwrap()), raw(parent));
|
||||
assert!(seen.insert(raw(*k)), "duplicate child");
|
||||
locals.insert(k.local_coords());
|
||||
}
|
||||
// Every (x, y, z) in 0..3 appears exactly once as a local coordinate.
|
||||
assert_eq!(locals.len(), 27);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_size_scales_with_depth() {
|
||||
let max_depth = 3;
|
||||
let root = TreeLocator::<4>::root();
|
||||
assert_eq!(root.node_size(max_depth), 64); // 4^3
|
||||
assert_eq!(root.child(0, 0, 0).node_size(max_depth), 16); // 4^2
|
||||
assert_eq!(root.child(0, 0, 0).child(1, 1, 1).node_size(max_depth), 4);
|
||||
assert_eq!(
|
||||
root.child(0, 0, 0)
|
||||
.child(1, 1, 1)
|
||||
.child(2, 2, 2)
|
||||
.node_size(max_depth),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_depth_is_reachable_without_overflow() {
|
||||
// `max_depth` may be conservative, but it must always be safe to reach.
|
||||
fn check<const N: usize>() {
|
||||
let max = TreeLocator::<N>::max_depth();
|
||||
let last = N as u32 - 1;
|
||||
|
||||
let mut l = TreeLocator::<N>::root();
|
||||
for _ in 0..max {
|
||||
l = l.child(last, last, last);
|
||||
}
|
||||
assert_eq!(l.depth(), max);
|
||||
|
||||
// Largest coordinates at that depth must also be constructible.
|
||||
let top = (N as u32).pow(max) - 1;
|
||||
let direct = TreeLocator::<N>::from_node_coords(max, top, top, top);
|
||||
assert_eq!(raw(direct), raw(l));
|
||||
}
|
||||
|
||||
check::<2>();
|
||||
check::<3>();
|
||||
check::<4>();
|
||||
check::<8>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "Out of bounds child coordinate.")]
|
||||
fn child_rejects_out_of_range_coordinate() {
|
||||
TreeLocator::<4>::root().child(0, 4, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "Node coordinates out of bounds.")]
|
||||
fn from_node_coords_rejects_out_of_range_coordinate() {
|
||||
// Depth 2 in a 4-tree allows 0..16.
|
||||
TreeLocator::<4>::from_node_coords(2, 0, 16, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "TreeLocator too deep")]
|
||||
fn child_rejects_overflowing_depth() {
|
||||
let mut l = TreeLocator::<2>::root();
|
||||
for _ in 0..40 {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
#![allow(incomplete_features)]
|
||||
#![feature(generic_const_exprs)]
|
||||
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
use vxls_production::Attribute;
|
||||
use vxls_production::AttributeDescriptor;
|
||||
use vxls_production::Attributes;
|
||||
use vxls_production::AttributesLayout;
|
||||
use vxls_production::LayoutError;
|
||||
use vxls_production::ProducedNode;
|
||||
use vxls_voxel_cache::schema::ChildInformation;
|
||||
use vxls_voxel_cache::schema::InsertionInformation;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Default, Pod, Zeroable, Attributes, Debug)]
|
||||
#[repr(C)]
|
||||
struct TestAttributes {
|
||||
#[attribute(label = "color", semantic = "color")]
|
||||
color: u32,
|
||||
|
||||
#[attribute(label = "normal", semantic = "normal")]
|
||||
normal: [f32; 3],
|
||||
|
||||
#[attribute(skip)]
|
||||
reserved: u32,
|
||||
}
|
||||
|
||||
fn sample(color: u32, normal: [f32; 3]) -> TestAttributes {
|
||||
TestAttributes {
|
||||
color,
|
||||
normal,
|
||||
reserved: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout_matches_the_declared_fields() {
|
||||
let layout = TestAttributes::LAYOUT;
|
||||
|
||||
assert_eq!(layout.len(), 2);
|
||||
assert!(!layout.is_empty());
|
||||
|
||||
assert_eq!(layout.attributes[0].label, "color");
|
||||
assert_eq!(layout.attributes[0].semantic, Some("color"));
|
||||
assert_eq!(layout.attributes[0].word_count, 1);
|
||||
|
||||
assert_eq!(layout.attributes[1].label, "normal");
|
||||
assert_eq!(layout.attributes[1].semantic, Some("normal"));
|
||||
assert_eq!(layout.attributes[1].word_count, 3);
|
||||
|
||||
assert_eq!(layout.total_word_count(), 4);
|
||||
assert!(layout.validate().is_ok());
|
||||
|
||||
assert_eq!(layout.by_label("normal").map(|(index, _)| index), Some(1));
|
||||
assert_eq!(layout.by_semantic("color").map(|(index, _)| index), Some(0));
|
||||
assert!(layout.by_label("reserved").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_attr_returns_the_field_bytes() {
|
||||
let value = sample(0x1122_3344, [1.0, 2.0, 3.0]);
|
||||
|
||||
assert_eq!(value.get_attr(0), bytemuck::bytes_of(&value.color));
|
||||
assert_eq!(value.get_attr(1), bytemuck::bytes_of(&value.normal));
|
||||
assert!(value.try_get_attr(2).is_none());
|
||||
|
||||
let mut value = value;
|
||||
value
|
||||
.get_attr_mut(0)
|
||||
.copy_from_slice(&0xAABB_CCDDu32.to_ne_bytes());
|
||||
assert_eq!(value.color, 0xAABB_CCDD);
|
||||
assert!(value.try_get_attr_mut(2).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn average_is_component_wise_and_skips_the_reserved_field() {
|
||||
let first = TestAttributes {
|
||||
color: 2,
|
||||
normal: [1.0, 2.0, 3.0],
|
||||
reserved: 7,
|
||||
};
|
||||
let second = TestAttributes {
|
||||
color: 4,
|
||||
normal: [3.0, 4.0, 5.0],
|
||||
reserved: 9,
|
||||
};
|
||||
|
||||
let average = TestAttributes::average(&[first, second]);
|
||||
|
||||
assert_eq!(average.color, 3);
|
||||
assert_eq!(average.normal, [2.0, 3.0, 4.0]);
|
||||
assert_eq!(average.reserved, 0);
|
||||
|
||||
assert_eq!(TestAttributes::average(&[]), TestAttributes::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_rejects_duplicate_labels_and_semantics() {
|
||||
const DUPLICATE_LABELS: AttributesLayout = AttributesLayout {
|
||||
attributes: &[
|
||||
AttributeDescriptor {
|
||||
label: "a",
|
||||
word_count: 1,
|
||||
semantic: None,
|
||||
},
|
||||
AttributeDescriptor {
|
||||
label: "a",
|
||||
word_count: 1,
|
||||
semantic: None,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
DUPLICATE_LABELS.validate(),
|
||||
Err(LayoutError::DuplicateLabel {
|
||||
first: 0,
|
||||
second: 1
|
||||
})
|
||||
);
|
||||
|
||||
const DUPLICATE_SEMANTICS: AttributesLayout = AttributesLayout {
|
||||
attributes: &[
|
||||
AttributeDescriptor::new("a", 1).with_semantic("color"),
|
||||
AttributeDescriptor::new("b", 1).with_semantic("color"),
|
||||
],
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
DUPLICATE_SEMANTICS.validate(),
|
||||
Err(LayoutError::DuplicateSemantic {
|
||||
first: 0,
|
||||
second: 1
|
||||
})
|
||||
);
|
||||
|
||||
assert_eq!(AttributesLayout::EMPTY.validate(), Err(LayoutError::Empty));
|
||||
|
||||
assert_ne!(
|
||||
TestAttributes::LAYOUT.fingerprint(),
|
||||
DUPLICATE_LABELS.fingerprint()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn produced_node_transposes_attributes_for_the_insertion_buffer() {
|
||||
let value = sample(0x0102_0304, [1.0, 2.0, 3.0]);
|
||||
|
||||
let insertion = InsertionInformation::<4> {
|
||||
children: [ChildInformation::NONE; 4 * 4 * 4],
|
||||
};
|
||||
|
||||
let node = ProducedNode::new(insertion, [value; 4 * 4 * 4]);
|
||||
|
||||
let mut words = Vec::new();
|
||||
node.write_attribute_words(1, &mut words);
|
||||
|
||||
assert_eq!(words.len(), 64 * 3);
|
||||
assert_eq!(&words[..3], bytemuck::cast_slice::<f32, u32>(&value.normal));
|
||||
|
||||
node.write_attribute_words(0, &mut words);
|
||||
assert_eq!(words.len(), 64);
|
||||
assert!(words.iter().all(|word| *word == 0x0102_0304));
|
||||
}
|
||||
@@ -0,0 +1,613 @@
|
||||
//! End-to-end tests of the VXLS sparse-tree file format.
|
||||
|
||||
#![feature(generic_const_exprs)]
|
||||
#![allow(incomplete_features)]
|
||||
|
||||
use std::io::Cursor;
|
||||
use std::ops::Range;
|
||||
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
use vxls_production::Attribute;
|
||||
use vxls_production::AttributeDescriptor;
|
||||
use vxls_production::Attributes;
|
||||
use vxls_production::AttributesLayout;
|
||||
use vxls_production::io::TreeFileError;
|
||||
use vxls_production::io::read_tree;
|
||||
use vxls_production::io::write_tree;
|
||||
use vxls_production::sparse_tree::NTree;
|
||||
|
||||
const U32_LAYOUT: AttributesLayout = AttributesLayout::new(&[AttributeDescriptor::new("value", 1)]);
|
||||
const PAIR_LAYOUT: AttributesLayout = AttributesLayout::new(&[AttributeDescriptor::new("pair", 2)]);
|
||||
const WRONG_LAYOUT: AttributesLayout =
|
||||
AttributesLayout::new(&[AttributeDescriptor::new("wrong", 2)]);
|
||||
|
||||
fn encode<const N: usize, T: Attribute>(tree: &NTree<N, T>, layout: AttributesLayout) -> Vec<u8>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
let mut cursor = Cursor::new(Vec::new());
|
||||
write_tree(&mut cursor, tree, layout).expect("write succeeds");
|
||||
cursor.into_inner()
|
||||
}
|
||||
|
||||
fn decode<const N: usize, T: Attribute>(
|
||||
bytes: &[u8],
|
||||
expected: Option<AttributesLayout>,
|
||||
) -> Result<NTree<N, T>, TreeFileError>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
let mut cursor = Cursor::new(bytes);
|
||||
read_tree::<_, N, T>(&mut cursor, expected).map(|file| file.tree)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Entry {
|
||||
tag: u32,
|
||||
offset: usize,
|
||||
size: usize,
|
||||
table_position: usize,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
fn body(&self) -> Range<usize> {
|
||||
self.offset + 12..self.offset + self.size
|
||||
}
|
||||
}
|
||||
|
||||
fn header_size(bytes: &[u8]) -> usize {
|
||||
u32::from_le_bytes(bytes[24..28].try_into().unwrap()) as usize
|
||||
}
|
||||
|
||||
fn entries(bytes: &[u8]) -> Vec<Entry> {
|
||||
let header_size = header_size(bytes);
|
||||
let table_position = 24 + header_size;
|
||||
let table_size = u32::from_le_bytes(
|
||||
bytes[table_position..table_position + 4]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
) as usize;
|
||||
let start = table_position + 4;
|
||||
|
||||
(0..table_size / 24)
|
||||
.map(|index| {
|
||||
let base = start + index * 24;
|
||||
Entry {
|
||||
tag: u32::from_le_bytes(bytes[base..base + 4].try_into().unwrap()),
|
||||
offset: u64::from_le_bytes(bytes[base + 8..base + 16].try_into().unwrap()) as usize,
|
||||
size: u64::from_le_bytes(bytes[base + 16..base + 24].try_into().unwrap()) as usize,
|
||||
table_position: base,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn find_level(bytes: &[u8], level: u32) -> Entry {
|
||||
entries(bytes)
|
||||
.into_iter()
|
||||
.find(|entry| entry.tag == 0x8000_0000 | level)
|
||||
.expect("level chunk exists")
|
||||
}
|
||||
|
||||
fn patch_u32(bytes: &mut [u8], position: usize, value: u32) {
|
||||
bytes[position..position + 4].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
|
||||
fn recompute_crc(bytes: &mut [u8], entry: &Entry) {
|
||||
let crc = crc32fast::hash(&bytes[entry.offset..entry.offset + entry.size]);
|
||||
bytes[entry.offset + entry.size..entry.offset + entry.size + 4]
|
||||
.copy_from_slice(&crc.to_le_bytes());
|
||||
}
|
||||
|
||||
/// Renames a chunk in both the offset table and the frame, keeping the CRC valid.
|
||||
fn rename_chunk(bytes: &mut [u8], entry: &Entry, tag: u32) {
|
||||
patch_u32(bytes, entry.table_position, tag);
|
||||
patch_u32(bytes, entry.offset, tag);
|
||||
recompute_crc(bytes, &Entry { tag, ..*entry });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_tree_roundtrip() {
|
||||
let tree = NTree::<2, u32>::constant(7, 3);
|
||||
let read = decode::<2, u32>(&encode(&tree, U32_LAYOUT), Some(U32_LAYOUT)).unwrap();
|
||||
|
||||
assert_eq!(read.depth(), 3);
|
||||
assert_eq!(read.node_count(), 1);
|
||||
assert_eq!(read.get(0, 0, 0), 7);
|
||||
assert_eq!(read.get(7, 7, 7), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_voxel_roundtrip_matches_every_position() {
|
||||
let mut tree = NTree::<2, u32>::constant(0, 1);
|
||||
|
||||
for z in 0..2 {
|
||||
for y in 0..2 {
|
||||
for x in 0..2 {
|
||||
tree.set(x, y, z, 1 + (x + 2 * y + 4 * z) as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let read = decode::<2, u32>(&encode(&tree, U32_LAYOUT), Some(U32_LAYOUT)).unwrap();
|
||||
|
||||
for z in 0..2 {
|
||||
for y in 0..2 {
|
||||
for x in 0..2 {
|
||||
assert_eq!(read.get(x, y, z), tree.get(x, y, z), "voxel {x},{y},{z}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_tree_roundtrip() {
|
||||
let mut tree = NTree::<2, u32>::constant(0, 4);
|
||||
|
||||
for z in 0..16 {
|
||||
for y in 0..16 {
|
||||
for x in 0..16 {
|
||||
tree.set(x, y, z, (x * 31 + y * 17 + z * 7) as u32 % 23);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let read = decode::<2, u32>(&encode(&tree, U32_LAYOUT), Some(U32_LAYOUT)).unwrap();
|
||||
|
||||
for z in 0..16 {
|
||||
for y in 0..16 {
|
||||
for x in 0..16 {
|
||||
assert_eq!(read.get(x, y, z), tree.get(x, y, z), "voxel {x},{y},{z}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arity_three_roundtrip() {
|
||||
let mut tree = NTree::<3, u32>::constant(0, 2);
|
||||
|
||||
for z in 0..9 {
|
||||
for y in 0..9 {
|
||||
for x in 0..9 {
|
||||
tree.set(x, y, z, ((x + y + z) % 5) as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let read = decode::<3, u32>(&encode(&tree, U32_LAYOUT), Some(U32_LAYOUT)).unwrap();
|
||||
|
||||
for z in 0..9 {
|
||||
for y in 0..9 {
|
||||
for x in 0..9 {
|
||||
assert_eq!(read.get(x, y, z), tree.get(x, y, z), "voxel {x},{y},{z}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shallow_tree_keeps_capacity_in_header() {
|
||||
let tree = NTree::<2, u32>::constant(5, 4);
|
||||
let read = decode::<2, u32>(&encode(&tree, U32_LAYOUT), None).unwrap();
|
||||
|
||||
assert_eq!(read.depth(), 4);
|
||||
assert_eq!(read.node_count(), 1);
|
||||
assert_eq!(read.get(15, 15, 15), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_array_roundtrip() {
|
||||
let values: Vec<u32> = (0..64).map(|index| (index * 13 % 29) as u32).collect();
|
||||
let tree = NTree::<2, u32>::from_array(&values, 2);
|
||||
let read = decode::<2, u32>(&encode(&tree, U32_LAYOUT), Some(U32_LAYOUT)).unwrap();
|
||||
|
||||
for z in 0..4 {
|
||||
for y in 0..4 {
|
||||
for x in 0..4 {
|
||||
assert_eq!(read.get(x, y, z), tree.get(x, y, z), "voxel {x},{y},{z}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable, Attributes)]
|
||||
#[repr(C)]
|
||||
struct Payload {
|
||||
#[attribute(label = "color", semantic = "color")]
|
||||
color: u32,
|
||||
|
||||
#[attribute(label = "normal", semantic = "normal")]
|
||||
normal: [f32; 3],
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_attribute_roundtrip() {
|
||||
let mut tree = NTree::<2, Payload>::constant(Payload::default(), 2);
|
||||
|
||||
for z in 0..4 {
|
||||
for y in 0..4 {
|
||||
for x in 0..4 {
|
||||
tree.set(
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
Payload {
|
||||
color: (x + 4 * y + 16 * z) as u32,
|
||||
normal: [x as f32, y as f32, z as f32],
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let bytes = encode(&tree, Payload::LAYOUT);
|
||||
let mut cursor = Cursor::new(&bytes);
|
||||
let file = read_tree::<_, 2, Payload>(&mut cursor, Some(Payload::LAYOUT)).unwrap();
|
||||
|
||||
assert_eq!(file.layout.attributes.len(), 2);
|
||||
assert_eq!(file.layout.attributes[0].label, "color");
|
||||
assert_eq!(file.layout.attributes[0].word_count, 1);
|
||||
assert_eq!(file.layout.attributes[1].label, "normal");
|
||||
assert_eq!(file.layout.attributes[1].word_count, 3);
|
||||
|
||||
for z in 0..4 {
|
||||
for y in 0..4 {
|
||||
for x in 0..4 {
|
||||
assert_eq!(file.tree.get(x, y, z), tree.get(x, y, z));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_rejects_layout_size_mismatch() {
|
||||
let tree = NTree::<2, u32>::constant(0, 1);
|
||||
let mut cursor = Cursor::new(Vec::new());
|
||||
|
||||
assert!(matches!(
|
||||
write_tree(&mut cursor, &tree, PAIR_LAYOUT),
|
||||
Err(TreeFileError::LayoutSizeMismatch { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_rejects_empty_layout() {
|
||||
let tree = NTree::<2, u32>::constant(0, 1);
|
||||
let mut cursor = Cursor::new(Vec::new());
|
||||
|
||||
assert!(matches!(
|
||||
write_tree(&mut cursor, &tree, AttributesLayout::EMPTY),
|
||||
Err(TreeFileError::EmptyLayout)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_rejects_zero_word_count() {
|
||||
const ZERO: AttributesLayout = AttributesLayout::new(&[AttributeDescriptor::new("zero", 0)]);
|
||||
|
||||
let tree = NTree::<2, u32>::constant(0, 1);
|
||||
let mut cursor = Cursor::new(Vec::new());
|
||||
|
||||
assert!(matches!(
|
||||
write_tree(&mut cursor, &tree, ZERO),
|
||||
Err(TreeFileError::InvalidWordCount { index: 0, .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_magic() {
|
||||
let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT);
|
||||
bytes[0] = b'X';
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::BadMagic { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_file_type() {
|
||||
let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT);
|
||||
bytes[4] = b'X';
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::BadFileType { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unsupported_major_version() {
|
||||
let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT);
|
||||
patch_u32(&mut bytes, 8, 99);
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::UnsupportedVersion { major: 99, .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_newer_minor_version() {
|
||||
let mut bytes = encode(&NTree::<2, u32>::constant(3, 1), U32_LAYOUT);
|
||||
patch_u32(&mut bytes, 12, 7);
|
||||
|
||||
let tree = decode::<2, u32>(&bytes, None).unwrap();
|
||||
assert_eq!(tree.get(0, 0, 0), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_file_size_mismatch() {
|
||||
let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT);
|
||||
bytes.pop();
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::FileSizeMismatch { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_arity_mismatch() {
|
||||
let bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT);
|
||||
|
||||
assert!(matches!(
|
||||
decode::<3, u32>(&bytes, None),
|
||||
Err(TreeFileError::ArityMismatch {
|
||||
file: 2,
|
||||
requested: 3
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_small_header() {
|
||||
let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT);
|
||||
patch_u32(&mut bytes, 24, 4);
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::HeaderTooSmall { header_size: 4 })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_excessive_depth() {
|
||||
let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT);
|
||||
patch_u32(&mut bytes, 32, 31);
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::DepthTooLarge { depth: 31, .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_misaligned_offset_table_entry() {
|
||||
let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT);
|
||||
let entry = entries(&bytes)[0];
|
||||
patch_u32(
|
||||
&mut bytes,
|
||||
entry.table_position + 8,
|
||||
entry.offset as u32 + 1,
|
||||
);
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::MisalignedOffset { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_duplicate_chunk_tag() {
|
||||
let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT);
|
||||
let first = entries(&bytes)[0];
|
||||
let second = entries(&bytes)[1];
|
||||
patch_u32(&mut bytes, second.table_position, first.tag);
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::DuplicateChunk { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_zero_padding() {
|
||||
let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT);
|
||||
let entries = entries(&bytes);
|
||||
|
||||
let gap = entries
|
||||
.windows(2)
|
||||
.find_map(|pair| {
|
||||
let end = pair[0].offset + pair[0].size + 4;
|
||||
(end < pair[1].offset).then_some(end)
|
||||
})
|
||||
.expect("the writer leaves at least one padding byte");
|
||||
|
||||
bytes[gap] = 1;
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::NonZeroPadding { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wrong_frame_tag() {
|
||||
let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT);
|
||||
let entry = entries(&bytes)[0];
|
||||
patch_u32(&mut bytes, entry.offset, entry.tag + 100);
|
||||
recompute_crc(&mut bytes, &entry);
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::ChunkTagMismatch { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_crc() {
|
||||
let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT);
|
||||
let entry = find_level(&bytes, 0);
|
||||
let body = entry.body();
|
||||
bytes[body.start + 4] ^= 0xFF;
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::CrcMismatch { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_utf8_label() {
|
||||
let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT);
|
||||
let entry = entries(&bytes)[0];
|
||||
let body = entry.body();
|
||||
// count, word_count, label_size, then the label bytes.
|
||||
bytes[body.start + 12] = 0xFF;
|
||||
recompute_crc(&mut bytes, &entry);
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::Binrw(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_layout_mismatch() {
|
||||
let bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT);
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, Some(WRONG_LAYOUT)),
|
||||
Err(TreeFileError::LayoutMismatch { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_layout_size_mismatch() {
|
||||
let tree = NTree::<2, [u32; 2]>::constant([1, 2], 1);
|
||||
let bytes = encode(&tree, PAIR_LAYOUT);
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::LayoutSizeMismatch { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_trailing_bytes() {
|
||||
let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT);
|
||||
bytes.push(0);
|
||||
let length = bytes.len() as u64;
|
||||
bytes[16..24].copy_from_slice(&length.to_le_bytes());
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::TrailingBytes { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_level_chunk() {
|
||||
let mut tree = NTree::<2, u32>::constant(0, 2);
|
||||
tree.set(0, 0, 0, 1);
|
||||
tree.set(2, 0, 0, 2);
|
||||
|
||||
let mut bytes = encode(&tree, U32_LAYOUT);
|
||||
|
||||
assert_eq!(find_level(&bytes, 2).tag, 0x8000_0002);
|
||||
|
||||
let entry = find_level(&bytes, 1);
|
||||
rename_chunk(&mut bytes, &entry, 2);
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::MissingLevelChunk { level: 1 })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_node_count_mismatch() {
|
||||
let mut tree = NTree::<2, u32>::constant(0, 2);
|
||||
tree.set(0, 0, 0, 1);
|
||||
tree.set(2, 0, 0, 2);
|
||||
|
||||
let mut bytes = encode(&tree, U32_LAYOUT);
|
||||
let level_one = find_level(&bytes, 1);
|
||||
let level_two = find_level(&bytes, 2);
|
||||
|
||||
// Swap the two tags: level 1 now points at a body declaring 16 nodes while
|
||||
// its parents imply only 8.
|
||||
rename_chunk(&mut bytes, &level_one, 0x8000_0002);
|
||||
rename_chunk(&mut bytes, &level_two, 0x8000_0001);
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::NodeCountMismatch { level: 1, .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_subdivision_at_deepest_level() {
|
||||
let mut tree = NTree::<2, u32>::constant(0, 1);
|
||||
tree.set(0, 0, 0, 1);
|
||||
|
||||
let mut bytes = encode(&tree, U32_LAYOUT);
|
||||
let entry = find_level(&bytes, 1);
|
||||
let body = entry.body();
|
||||
|
||||
// First body word is node_count; the mask follows.
|
||||
bytes[body.start + 4] |= 1;
|
||||
recompute_crc(&mut bytes, &entry);
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::SubdividedAtDeepestLevel { level: 1 })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_zero_unused_flag_bits() {
|
||||
let mut tree = NTree::<2, u32>::constant(0, 1);
|
||||
tree.set(0, 0, 0, 1);
|
||||
|
||||
let mut bytes = encode(&tree, U32_LAYOUT);
|
||||
let entry = find_level(&bytes, 1);
|
||||
let body = entry.body();
|
||||
|
||||
// 8 nodes use the low 8 bits; bit 9 is unused and must stay clear.
|
||||
bytes[body.start + 5] |= 1 << 1;
|
||||
recompute_crc(&mut bytes, &entry);
|
||||
|
||||
assert!(matches!(
|
||||
decode::<2, u32>(&bytes, None),
|
||||
Err(TreeFileError::TrailingFlagBits { level: 1 })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_path_helpers_roundtrip() {
|
||||
let directory = std::env::temp_dir().join(format!(
|
||||
"vxls-io-test-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
std::fs::create_dir_all(&directory).unwrap();
|
||||
let path = directory.join("tree.vxls");
|
||||
|
||||
let mut tree = NTree::<2, u32>::constant(0, 2);
|
||||
tree.set(1, 2, 3, 42);
|
||||
|
||||
vxls_production::io::write_tree_to_path(&path, &tree, U32_LAYOUT).unwrap();
|
||||
let file =
|
||||
vxls_production::io::read_tree_from_path::<_, 2, u32>(&path, Some(U32_LAYOUT)).unwrap();
|
||||
|
||||
assert_eq!(file.tree.get(1, 2, 3), 42);
|
||||
|
||||
std::fs::remove_dir_all(&directory).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "vxls-profiler"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
bytemuck.workspace = true
|
||||
egui.workspace = true
|
||||
wgpu.workspace = true
|
||||
@@ -14,6 +14,7 @@ use wgpu::Queue;
|
||||
|
||||
pub mod memory_profiler;
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! begin_frame {
|
||||
($encoder:ident) => {
|
||||
let mut $encoder = $encoder.begin_frame(None);
|
||||
@@ -24,32 +25,27 @@ macro_rules! begin_frame {
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! begin_scope {
|
||||
($scope:ident, $name:literal) => {
|
||||
let mut $scope = $scope.begin_scope($name);
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use begin_frame;
|
||||
pub(crate) use begin_scope;
|
||||
|
||||
pub struct ScopeEncoder<'enc, 'prof_enc, T>
|
||||
{
|
||||
pub struct ScopeEncoder<'enc, 'prof_enc, T> {
|
||||
encoder: &'prof_enc mut ProfilingEncoder<'enc>,
|
||||
scope_index: usize,
|
||||
_phantom: PhantomData<T>,
|
||||
}
|
||||
|
||||
pub struct Scope
|
||||
{
|
||||
pub struct Scope {
|
||||
name: &'static str,
|
||||
start_index: QuerySetHandle,
|
||||
end_index: Option<QuerySetHandle>,
|
||||
children: Vec<usize>,
|
||||
}
|
||||
|
||||
pub struct ProfilingEncoder<'enc>
|
||||
{
|
||||
pub struct ProfilingEncoder<'enc> {
|
||||
device: Device,
|
||||
encoder: &'enc mut CommandEncoder,
|
||||
query_set_allocator: QuerySetAllocator,
|
||||
@@ -60,14 +56,12 @@ pub struct ProfilingEncoder<'enc>
|
||||
compute_pass: Option<(usize, ComputePass<'static>)>,
|
||||
}
|
||||
|
||||
pub struct GpuProfile
|
||||
{
|
||||
pub struct GpuProfile {
|
||||
scopes: Vec<Scope>,
|
||||
timestamps: Buffer,
|
||||
}
|
||||
|
||||
pub struct Frame
|
||||
{
|
||||
pub struct Frame {
|
||||
pub name: &'static str,
|
||||
pub children: Vec<usize>,
|
||||
|
||||
@@ -76,15 +70,12 @@ pub struct Frame
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Profile
|
||||
{
|
||||
pub struct Profile {
|
||||
pub frames: Vec<Frame>,
|
||||
}
|
||||
|
||||
impl<'enc> ProfilingEncoder<'enc>
|
||||
{
|
||||
pub fn new(device: &Device, encoder: &'enc mut CommandEncoder) -> Self
|
||||
{
|
||||
impl<'enc> ProfilingEncoder<'enc> {
|
||||
pub fn new(device: &Device, encoder: &'enc mut CommandEncoder) -> Self {
|
||||
Self {
|
||||
encoder,
|
||||
query_set_allocator: QuerySetAllocator::new(device),
|
||||
@@ -98,8 +89,7 @@ impl<'enc> ProfilingEncoder<'enc>
|
||||
pub fn begin_frame<'prof_enc>(
|
||||
&'prof_enc mut self,
|
||||
frame_name: Option<&'static str>,
|
||||
) -> ScopeEncoder<'enc, 'prof_enc, CommandEncoder>
|
||||
{
|
||||
) -> ScopeEncoder<'enc, 'prof_enc, CommandEncoder> {
|
||||
let scope_index = self.begin_scope(None, frame_name.unwrap_or("Frame"));
|
||||
self.index_stack.push(scope_index);
|
||||
ScopeEncoder {
|
||||
@@ -109,17 +99,13 @@ impl<'enc> ProfilingEncoder<'enc>
|
||||
}
|
||||
}
|
||||
|
||||
fn begin_scope(&mut self, scope_index: Option<usize>, name: &'static str) -> usize
|
||||
{
|
||||
fn begin_scope(&mut self, scope_index: Option<usize>, name: &'static str) -> usize {
|
||||
let begin_query = self.query_set_allocator.allocate();
|
||||
|
||||
if let Some((_, pass)) = &mut self.compute_pass
|
||||
{
|
||||
if let Some((_, pass)) = &mut self.compute_pass {
|
||||
self.query_set_allocator
|
||||
.write_compute_timestamp(pass, &begin_query);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
self.query_set_allocator
|
||||
.write_timestamp(self.encoder, &begin_query);
|
||||
}
|
||||
@@ -136,24 +122,19 @@ impl<'enc> ProfilingEncoder<'enc>
|
||||
self.index_stack.push(new_scope_index);
|
||||
|
||||
// Add this new stack to parent
|
||||
if let Some(scope_index) = scope_index
|
||||
{
|
||||
if let Some(scope_index) = scope_index {
|
||||
self.scopes[scope_index].children.push(new_scope_index);
|
||||
}
|
||||
|
||||
new_scope_index
|
||||
}
|
||||
|
||||
fn end_scope(&mut self, scope_index: usize)
|
||||
{
|
||||
fn end_scope(&mut self, scope_index: usize) {
|
||||
let end_query = self.query_set_allocator.allocate();
|
||||
if let Some((_, pass)) = &mut self.compute_pass
|
||||
{
|
||||
if let Some((_, pass)) = &mut self.compute_pass {
|
||||
self.query_set_allocator
|
||||
.write_compute_timestamp(pass, &end_query);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
self.query_set_allocator
|
||||
.write_timestamp(self.encoder, &end_query);
|
||||
}
|
||||
@@ -168,8 +149,7 @@ impl<'enc> ProfilingEncoder<'enc>
|
||||
scope.end_index = Some(end_query);
|
||||
}
|
||||
|
||||
pub fn finish_profiler(self) -> GpuProfile
|
||||
{
|
||||
pub fn finish_profiler(self) -> GpuProfile {
|
||||
let timestamp_count = self.query_set_allocator.allocated_count();
|
||||
let resolve_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("ProfilingEncoder::resolve_buffer"),
|
||||
@@ -188,13 +168,11 @@ impl<'enc> ProfilingEncoder<'enc>
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc, CommandEncoder>
|
||||
{
|
||||
impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc, CommandEncoder> {
|
||||
pub fn begin_profiled_compute_pass<'scope>(
|
||||
&'scope mut self,
|
||||
label: &'static str,
|
||||
) -> ScopeEncoder<'enc, 'scope, ComputePass<'static>>
|
||||
{
|
||||
) -> ScopeEncoder<'enc, 'scope, ComputePass<'static>> {
|
||||
let new_scope = self.encoder.begin_scope(Some(self.scope_index), label);
|
||||
let compute_pass = self
|
||||
.encoder
|
||||
@@ -228,14 +206,12 @@ impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc, CommandEncoder>
|
||||
}
|
||||
}
|
||||
|
||||
pub fn end_scope(self)
|
||||
{
|
||||
pub fn end_scope(self) {
|
||||
drop(self);
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc, ComputePass<'static>>
|
||||
{
|
||||
impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc, ComputePass<'static>> {
|
||||
pub fn begin_scope<'scope>(
|
||||
&'scope mut self,
|
||||
name: &'static str,
|
||||
@@ -251,16 +227,13 @@ impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc, ComputePass<'static>>
|
||||
}
|
||||
}
|
||||
|
||||
pub fn end_scope(self)
|
||||
{
|
||||
pub fn end_scope(self) {
|
||||
drop(self);
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc, 'prof_enc, T> Drop for ScopeEncoder<'enc, 'prof_enc, T>
|
||||
{
|
||||
fn drop(&mut self)
|
||||
{
|
||||
impl<'enc, 'prof_enc, T> Drop for ScopeEncoder<'enc, 'prof_enc, T> {
|
||||
fn drop(&mut self) {
|
||||
if let Some((parent_scope, _)) = self.encoder.compute_pass
|
||||
&& parent_scope == self.scope_index
|
||||
{
|
||||
@@ -271,59 +244,46 @@ impl<'enc, 'prof_enc, T> Drop for ScopeEncoder<'enc, 'prof_enc, T>
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc, 'prof_enc> DerefMut for ScopeEncoder<'enc, 'prof_enc, CommandEncoder>
|
||||
{
|
||||
fn deref_mut(&mut self) -> &mut Self::Target
|
||||
{
|
||||
impl<'enc, 'prof_enc> DerefMut for ScopeEncoder<'enc, 'prof_enc, CommandEncoder> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut *self.encoder
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc, 'prof_enc> Deref for ScopeEncoder<'enc, 'prof_enc, CommandEncoder>
|
||||
{
|
||||
impl<'enc, 'prof_enc> Deref for ScopeEncoder<'enc, 'prof_enc, CommandEncoder> {
|
||||
type Target = CommandEncoder;
|
||||
fn deref(&self) -> &Self::Target
|
||||
{
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&*self.encoder
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc, 'prof_enc> DerefMut for ScopeEncoder<'enc, 'prof_enc, ComputePass<'static>>
|
||||
{
|
||||
fn deref_mut(&mut self) -> &mut Self::Target
|
||||
{
|
||||
impl<'enc, 'prof_enc> DerefMut for ScopeEncoder<'enc, 'prof_enc, ComputePass<'static>> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.encoder.compute_pass.as_mut().unwrap().1
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc, 'prof_enc> Deref for ScopeEncoder<'enc, 'prof_enc, ComputePass<'static>>
|
||||
{
|
||||
impl<'enc, 'prof_enc> Deref for ScopeEncoder<'enc, 'prof_enc, ComputePass<'static>> {
|
||||
type Target = ComputePass<'static>;
|
||||
fn deref(&self) -> &Self::Target
|
||||
{
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.encoder.compute_pass.as_ref().unwrap().1
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc> DerefMut for ProfilingEncoder<'enc>
|
||||
{
|
||||
fn deref_mut(&mut self) -> &mut Self::Target
|
||||
{
|
||||
impl<'enc> DerefMut for ProfilingEncoder<'enc> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
self.encoder
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc> Deref for ProfilingEncoder<'enc>
|
||||
{
|
||||
impl<'enc> Deref for ProfilingEncoder<'enc> {
|
||||
type Target = CommandEncoder;
|
||||
fn deref(&self) -> &Self::Target
|
||||
{
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.encoder
|
||||
}
|
||||
}
|
||||
|
||||
struct QuerySetAllocator
|
||||
{
|
||||
struct QuerySetAllocator {
|
||||
device: Device,
|
||||
current_size: u32,
|
||||
current_id: u32,
|
||||
@@ -333,40 +293,30 @@ struct QuerySetAllocator
|
||||
#[derive(PartialEq, Eq)]
|
||||
struct QuerySetHandle(usize, u32, u32);
|
||||
|
||||
impl QuerySetHandle
|
||||
{
|
||||
pub fn index(&self) -> usize
|
||||
{
|
||||
impl QuerySetHandle {
|
||||
pub fn index(&self) -> usize {
|
||||
self.2 as usize
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for QuerySetHandle
|
||||
{
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering>
|
||||
{
|
||||
impl PartialOrd for QuerySetHandle {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for QuerySetHandle
|
||||
{
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering
|
||||
{
|
||||
match self.0.cmp(&other.0)
|
||||
{
|
||||
core::cmp::Ordering::Equal =>
|
||||
{}
|
||||
impl Ord for QuerySetHandle {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
match self.0.cmp(&other.0) {
|
||||
core::cmp::Ordering::Equal => {}
|
||||
ord => return ord,
|
||||
}
|
||||
self.1.cmp(&other.1)
|
||||
}
|
||||
}
|
||||
|
||||
impl QuerySetAllocator
|
||||
{
|
||||
pub fn new(device: &Device) -> Self
|
||||
{
|
||||
impl QuerySetAllocator {
|
||||
pub fn new(device: &Device) -> Self {
|
||||
let current_size = 32;
|
||||
let query_sets = vec![(
|
||||
0,
|
||||
@@ -381,27 +331,23 @@ impl QuerySetAllocator
|
||||
}
|
||||
}
|
||||
|
||||
pub fn allocated_count(&self) -> u32
|
||||
{
|
||||
pub fn allocated_count(&self) -> u32 {
|
||||
self.query_sets
|
||||
.iter()
|
||||
.map(|(allocated, _, _)| *allocated)
|
||||
.sum()
|
||||
}
|
||||
|
||||
pub fn resolve_all(&self, encoder: &mut CommandEncoder, target: &Buffer)
|
||||
{
|
||||
pub fn resolve_all(&self, encoder: &mut CommandEncoder, target: &Buffer) {
|
||||
let mut offset = 0;
|
||||
for (allocated, _, query_set) in self.query_sets.iter()
|
||||
{
|
||||
for (allocated, _, query_set) in self.query_sets.iter() {
|
||||
encoder.resolve_query_set(query_set, 0..*allocated, target, offset);
|
||||
|
||||
offset += *allocated as u64 * size_of::<u64>() as u64;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn allocate(&mut self) -> QuerySetHandle
|
||||
{
|
||||
pub fn allocate(&mut self) -> QuerySetHandle {
|
||||
// Check if allocation is possible
|
||||
if self
|
||||
.query_sets
|
||||
@@ -431,8 +377,7 @@ impl QuerySetAllocator
|
||||
QuerySetHandle(query_set_index, query_index, id)
|
||||
}
|
||||
|
||||
fn new_query_set(device: &Device, size: u32, index: usize) -> QuerySet
|
||||
{
|
||||
fn new_query_set(device: &Device, size: u32, index: usize) -> QuerySet {
|
||||
device.create_query_set(&wgpu::QuerySetDescriptor {
|
||||
label: Some(format!("QuerySetAllocator::query_set_{index}").as_str()),
|
||||
ty: wgpu::QueryType::Timestamp,
|
||||
@@ -440,28 +385,24 @@ impl QuerySetAllocator
|
||||
})
|
||||
}
|
||||
|
||||
fn write_timestamp(&mut self, encoder: &mut CommandEncoder, handle: &QuerySetHandle)
|
||||
{
|
||||
fn write_timestamp(&mut self, encoder: &mut CommandEncoder, handle: &QuerySetHandle) {
|
||||
let query_set = &self.query_sets[handle.0].2;
|
||||
encoder.write_timestamp(query_set, handle.1);
|
||||
}
|
||||
|
||||
fn write_compute_timestamp(&mut self, pass: &mut ComputePass, handle: &QuerySetHandle)
|
||||
{
|
||||
fn write_compute_timestamp(&mut self, pass: &mut ComputePass, handle: &QuerySetHandle) {
|
||||
let query_set = &self.query_sets[handle.0].2;
|
||||
pass.write_timestamp(query_set, handle.1);
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuProfile
|
||||
{
|
||||
impl GpuProfile {
|
||||
pub fn read_back(
|
||||
self,
|
||||
device: &Device,
|
||||
queue: &Queue,
|
||||
mut callback: impl FnMut(Profile) + Send + Sync + 'static,
|
||||
)
|
||||
{
|
||||
) {
|
||||
// Readback timestamps
|
||||
wgpu::util::DownloadBuffer::read_buffer(
|
||||
device,
|
||||
@@ -488,43 +429,34 @@ impl GpuProfile
|
||||
}
|
||||
}
|
||||
|
||||
impl Profile
|
||||
{
|
||||
pub fn to_display_string(&self, q: f32) -> String
|
||||
{
|
||||
impl Profile {
|
||||
pub fn to_display_string(&self, q: f32) -> String {
|
||||
let mut str = String::new();
|
||||
self.frames[0].build_string(&self.frames, 0, q, &mut str);
|
||||
str
|
||||
}
|
||||
|
||||
pub fn show(&self, ui: &mut Ui, q: f32)
|
||||
{
|
||||
if !self.frames.is_empty()
|
||||
{
|
||||
pub fn show(&self, ui: &mut Ui, q: f32) {
|
||||
if !self.frames.is_empty() {
|
||||
self.frames[0].show(ui, q, &self.frames);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Frame
|
||||
{
|
||||
fn time(&self, q: f32) -> f32
|
||||
{
|
||||
impl Frame {
|
||||
fn time(&self, q: f32) -> f32 {
|
||||
(self.end_timestamp - self.start_timestamp) as f32 * q
|
||||
}
|
||||
|
||||
fn start(&self, q: f32) -> f32
|
||||
{
|
||||
fn start(&self, q: f32) -> f32 {
|
||||
self.start_timestamp as f32 * q
|
||||
}
|
||||
|
||||
fn end(&self, q: f32) -> f32
|
||||
{
|
||||
fn end(&self, q: f32) -> f32 {
|
||||
self.end_timestamp as f32 * q
|
||||
}
|
||||
|
||||
fn build_string(&self, frames: &Vec<Frame>, depth: usize, q: f32, str: &mut String)
|
||||
{
|
||||
fn build_string(&self, frames: &Vec<Frame>, depth: usize, q: f32, str: &mut String) {
|
||||
let mut depth_string = String::new();
|
||||
(0..depth).for_each(|_| depth_string.push_str(" "));
|
||||
|
||||
@@ -536,8 +468,7 @@ impl Frame
|
||||
.for_each(|c| frames[*c].build_string(frames, depth + 1, q, str));
|
||||
}
|
||||
|
||||
pub fn show(&self, ui: &mut Ui, q: f32, frames: &Vec<Frame>)
|
||||
{
|
||||
pub fn show(&self, ui: &mut Ui, q: f32, frames: &Vec<Frame>) {
|
||||
let id = ui.make_persistent_id(self.name);
|
||||
egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true)
|
||||
.show_header(ui, |ui| {
|
||||
@@ -568,13 +499,10 @@ impl Frame
|
||||
}
|
||||
}
|
||||
|
||||
impl Profile
|
||||
{
|
||||
impl Profile {
|
||||
// Clauderies
|
||||
pub fn show_flamegraph(&self, id: egui::Id, q: f32, ui: &mut Ui) -> egui::Response
|
||||
{
|
||||
if self.frames.is_empty()
|
||||
{
|
||||
pub fn show_flamegraph(&self, id: egui::Id, q: f32, ui: &mut Ui) -> egui::Response {
|
||||
if self.frames.is_empty() {
|
||||
return ui.label("empty");
|
||||
}
|
||||
let row_height = 20.;
|
||||
@@ -582,15 +510,13 @@ impl Profile
|
||||
let mut full = (f64::INFINITY, f64::NEG_INFINITY);
|
||||
let mut max_depth = 0usize;
|
||||
let mut stack: Vec<(usize, usize)> = [0].iter().map(|&r| (r, 0)).collect();
|
||||
while let Some((i, d)) = stack.pop()
|
||||
{
|
||||
while let Some((i, d)) = stack.pop() {
|
||||
let s = &self.frames[i];
|
||||
full = (full.0.min(s.start(q) as f64), full.1.max(s.end(q) as f64));
|
||||
max_depth = max_depth.max(d);
|
||||
stack.extend(s.children.iter().map(|&c| (c, d + 1)));
|
||||
}
|
||||
if full.0 >= full.1
|
||||
{
|
||||
if full.0 >= full.1 {
|
||||
full = (0.0, 1.0); // empty or degenerate input
|
||||
}
|
||||
|
||||
@@ -599,7 +525,9 @@ impl Profile
|
||||
let fspan = full.1 - full.0;
|
||||
let norm: (f64, f64) = ui.data_mut(|d| d.get_temp(id)).unwrap_or((0.0, 1.0));
|
||||
let mut view = (full.0 + norm.0 * fspan, full.0 + norm.1 * fspan);
|
||||
if !(view.1 > view.0) || !view.0.is_finite() || !view.1.is_finite()
|
||||
if !(egui::emath::OrderedFloat(view.1) > egui::emath::OrderedFloat(view.0))
|
||||
|| !view.0.is_finite()
|
||||
|| !view.1.is_finite()
|
||||
{
|
||||
view = full;
|
||||
}
|
||||
@@ -611,25 +539,21 @@ impl Profile
|
||||
|
||||
// --- interaction ---
|
||||
let mut span = view.1 - view.0;
|
||||
if resp.dragged()
|
||||
{
|
||||
if resp.dragged() {
|
||||
let dt = -(resp.drag_delta().x as f64) / w * span;
|
||||
view = (view.0 + dt, view.1 + dt);
|
||||
}
|
||||
if let Some(p) = resp.hover_pos()
|
||||
{
|
||||
if let Some(p) = resp.hover_pos() {
|
||||
let (zoom, scroll) = ui.input(|i| (i.zoom_delta(), i.smooth_scroll_delta.y));
|
||||
let z = zoom as f64 * (scroll as f64 * 0.005).exp();
|
||||
if (z - 1.0).abs() > 1e-6
|
||||
{
|
||||
if (z - 1.0).abs() > 1e-6 {
|
||||
let frac = ((p.x - rect.left()) as f64 / w).clamp(0.0, 1.0);
|
||||
let t_cursor = view.0 + frac * span;
|
||||
span = (span / z).clamp((full.1 - full.0) * 1e-6, (full.1 - full.0) * 10.0);
|
||||
view = (t_cursor - frac * span, t_cursor + (1.0 - frac) * span);
|
||||
}
|
||||
}
|
||||
if resp.double_clicked()
|
||||
{
|
||||
if resp.double_clicked() {
|
||||
view = full;
|
||||
}
|
||||
//ui.data_mut(|d| d.insert_temp(id, view));
|
||||
@@ -646,18 +570,15 @@ impl Profile
|
||||
let mut hovered: Option<usize> = None;
|
||||
|
||||
let mut stack: Vec<(usize, usize)> = [0].iter().map(|&r| (r, 0)).collect();
|
||||
while let Some((i, depth)) = stack.pop()
|
||||
{
|
||||
while let Some((i, depth)) = stack.pop() {
|
||||
let s = &self.frames[i];
|
||||
let start = s.start(q) as f64;
|
||||
let end = s.end(q) as f64;
|
||||
if end < view.0 || start > view.1
|
||||
{
|
||||
if end < view.0 || start > view.1 {
|
||||
continue; // off-screen: children are inside the parent, skip them too
|
||||
}
|
||||
let (x0, x1) = (to_x(start).max(rect.left()), to_x(end).min(rect.right()));
|
||||
if x1 - x0 < 0.5
|
||||
{
|
||||
if x1 - x0 < 0.5 {
|
||||
continue; // too thin to see
|
||||
}
|
||||
let y = rect.top() + depth as f32 * row_height;
|
||||
@@ -665,22 +586,19 @@ impl Profile
|
||||
.shrink2(vec2(0.5, 0.5));
|
||||
|
||||
let is_hovered = hover.is_some_and(|p| r.contains(p));
|
||||
if is_hovered
|
||||
{
|
||||
if is_hovered {
|
||||
hovered = Some(i);
|
||||
}
|
||||
let mut color = color_for(&s.name);
|
||||
if is_hovered
|
||||
{
|
||||
let mut color = color_for(s.name);
|
||||
if is_hovered {
|
||||
color = color.gamma_multiply(1.15);
|
||||
}
|
||||
painter.rect_filled(r, 2.0, color);
|
||||
if r.width() > 24.0
|
||||
{
|
||||
if r.width() > 24.0 {
|
||||
painter.with_clip_rect(r).text(
|
||||
r.left_center() + vec2(3.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
&s.name,
|
||||
s.name,
|
||||
font.clone(),
|
||||
egui::Color32::BLACK,
|
||||
);
|
||||
@@ -688,8 +606,7 @@ impl Profile
|
||||
stack.extend(s.children.iter().map(|&c| (c, depth + 1)));
|
||||
}
|
||||
|
||||
if let Some(i) = hovered
|
||||
{
|
||||
if let Some(i) = hovered {
|
||||
let s = &self.frames[i];
|
||||
let start = s.start(q) as f64;
|
||||
let end = s.end(q) as f64;
|
||||
@@ -704,11 +621,9 @@ impl Profile
|
||||
}
|
||||
|
||||
/// Stable pastel color derived from the scope name.
|
||||
fn color_for(name: &str) -> egui::Color32
|
||||
{
|
||||
fn color_for(name: &str) -> egui::Color32 {
|
||||
let mut h: u32 = 2166136261; // FNV-1a
|
||||
for b in name.bytes()
|
||||
{
|
||||
for b in name.bytes() {
|
||||
h = (h ^ b as u32).wrapping_mul(16777619);
|
||||
}
|
||||
egui::ecolor::Hsva::new((h % 360) as f32 / 360.0, 0.45, 0.9, 1.0).into()
|
||||
@@ -1,24 +1,20 @@
|
||||
use std::ops::Deref;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
pub struct Buffer
|
||||
{
|
||||
pub struct Buffer {
|
||||
pub label: String,
|
||||
pub size: usize,
|
||||
}
|
||||
|
||||
pub struct Group
|
||||
{
|
||||
pub struct Group {
|
||||
pub label: &'static str,
|
||||
size: Option<usize>,
|
||||
pub buffers: Vec<Buffer>,
|
||||
pub sub_groups: Vec<Group>,
|
||||
}
|
||||
|
||||
impl Group
|
||||
{
|
||||
pub fn new(label: &'static str) -> Self
|
||||
{
|
||||
impl Group {
|
||||
pub fn new(label: &'static str) -> Self {
|
||||
Self {
|
||||
label,
|
||||
size: None,
|
||||
@@ -27,16 +23,14 @@ impl Group
|
||||
}
|
||||
}
|
||||
|
||||
pub fn size(&self) -> usize
|
||||
{
|
||||
pub fn size(&self) -> usize {
|
||||
self.size.unwrap_or_else(|| {
|
||||
self.buffers.iter().map(|b| b.size).sum::<usize>()
|
||||
+ self.sub_groups.iter().map(Self::size).sum::<usize>()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn size_mut(&mut self) -> usize
|
||||
{
|
||||
pub fn size_mut(&mut self) -> usize {
|
||||
*self.size.get_or_insert_with(|| {
|
||||
self.buffers.iter().map(|b| b.size).sum::<usize>()
|
||||
+ self
|
||||
@@ -48,21 +42,17 @@ impl Group
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MemoryProfile
|
||||
{
|
||||
pub struct MemoryProfile {
|
||||
stack: Vec<Group>,
|
||||
}
|
||||
|
||||
pub struct Device<'a>
|
||||
{
|
||||
pub struct Device<'a> {
|
||||
device: wgpu::Device,
|
||||
profile: &'a mut MemoryProfile,
|
||||
}
|
||||
|
||||
impl<'a> Device<'a>
|
||||
{
|
||||
pub fn create_buffer(&mut self, desc: &wgpu::BufferDescriptor) -> wgpu::Buffer
|
||||
{
|
||||
impl<'a> Device<'a> {
|
||||
pub fn create_buffer(&mut self, desc: &wgpu::BufferDescriptor) -> wgpu::Buffer {
|
||||
let buffer = self.device.create_buffer(desc);
|
||||
self.profile.add_buffer(Buffer {
|
||||
label: desc.label.unwrap_or("Unnamed").into(),
|
||||
@@ -71,8 +61,7 @@ impl<'a> Device<'a>
|
||||
buffer
|
||||
}
|
||||
|
||||
pub fn create_buffer_init(&mut self, desc: &wgpu::util::BufferInitDescriptor) -> wgpu::Buffer
|
||||
{
|
||||
pub fn create_buffer_init(&mut self, desc: &wgpu::util::BufferInitDescriptor) -> wgpu::Buffer {
|
||||
let buffer = self.device.create_buffer_init(desc);
|
||||
self.profile.add_buffer(Buffer {
|
||||
label: desc.label.unwrap_or("Unnamed").into(),
|
||||
@@ -93,87 +82,69 @@ impl<'a> Device<'a>
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Drop for Device<'a>
|
||||
{
|
||||
fn drop(&mut self)
|
||||
{
|
||||
impl<'a> Drop for Device<'a> {
|
||||
fn drop(&mut self) {
|
||||
self.profile.close_group();
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Device<'_>
|
||||
{
|
||||
impl Deref for Device<'_> {
|
||||
type Target = wgpu::Device;
|
||||
|
||||
fn deref(&self) -> &Self::Target
|
||||
{
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.device
|
||||
}
|
||||
}
|
||||
|
||||
impl MemoryProfile
|
||||
{
|
||||
pub fn new(label: &'static str) -> Self
|
||||
{
|
||||
impl MemoryProfile {
|
||||
pub fn new(label: &'static str) -> Self {
|
||||
Self {
|
||||
stack: vec![Group::new(label)],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn begin(&mut self, device: &wgpu::Device) -> Device
|
||||
{
|
||||
pub fn begin(&mut self, device: &wgpu::Device) -> Device<'_> {
|
||||
Device {
|
||||
device: device.clone(),
|
||||
profile: self,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn terminate(mut self) -> Group
|
||||
{
|
||||
pub fn terminate(mut self) -> Group {
|
||||
self.stack.pop().unwrap()
|
||||
}
|
||||
|
||||
fn open_group(&mut self, label: &'static str)
|
||||
{
|
||||
fn open_group(&mut self, label: &'static str) {
|
||||
self.stack.push(Group::new(label));
|
||||
}
|
||||
|
||||
fn close_group(&mut self)
|
||||
{
|
||||
fn close_group(&mut self) {
|
||||
let mut group = self.stack.pop().unwrap();
|
||||
let _ = group.size_mut();
|
||||
|
||||
// Add it to parent if it exists
|
||||
if let Some(parent) = self.stack.last_mut()
|
||||
{
|
||||
if let Some(parent) = self.stack.last_mut() {
|
||||
parent.sub_groups.push(group);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
self.stack.push(group);
|
||||
}
|
||||
}
|
||||
|
||||
fn add_buffer(&mut self, buffer: Buffer)
|
||||
{
|
||||
fn add_buffer(&mut self, buffer: Buffer) {
|
||||
self.stack.last_mut().unwrap().buffers.push(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
use std::fmt;
|
||||
|
||||
impl fmt::Display for Group
|
||||
{
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
|
||||
{
|
||||
impl fmt::Display for Group {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
self.fmt_with_indent(f, 0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Group
|
||||
{
|
||||
fn fmt_with_indent(&self, f: &mut fmt::Formatter<'_>, indent: usize) -> fmt::Result
|
||||
{
|
||||
impl Group {
|
||||
fn fmt_with_indent(&self, f: &mut fmt::Formatter<'_>, indent: usize) -> fmt::Result {
|
||||
let prefix = " ".repeat(indent);
|
||||
|
||||
writeln!(
|
||||
@@ -185,8 +156,7 @@ impl Group
|
||||
)?;
|
||||
|
||||
// Print buffers
|
||||
for buffer in &self.buffers
|
||||
{
|
||||
for buffer in &self.buffers {
|
||||
writeln!(
|
||||
f,
|
||||
"{} ├── {} ({} bytes)",
|
||||
@@ -195,8 +165,7 @@ impl Group
|
||||
}
|
||||
|
||||
// Print subgroups
|
||||
for (i, group) in self.sub_groups.iter().enumerate()
|
||||
{
|
||||
for group in self.sub_groups.iter() {
|
||||
group.fmt_with_indent(f, indent + 1)?;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "vxls-terrain"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
bytemuck.workspace = true
|
||||
glam.workspace = true
|
||||
wgpu.workspace = true
|
||||
vxls-gpu = { path = "../vxls-gpu" }
|
||||
vxls-profiler = { path = "../vxls-profiler" }
|
||||
vxls-voxel-cache = { path = "../vxls-voxel-cache" }
|
||||
@@ -0,0 +1,284 @@
|
||||
#![allow(incomplete_features)]
|
||||
#![feature(generic_const_exprs)]
|
||||
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
use glam::Vec3;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::include_wgsl;
|
||||
|
||||
use vxls_gpu::create_multi_buffers_bind_group_layout;
|
||||
use vxls_voxel_cache::schema::StructureAnchor;
|
||||
use vxls_voxel_cache::tables::FixedStructureTable;
|
||||
|
||||
/// A torroidal structure table for "infinite" world purposes.
|
||||
/// Allows rendering a X*Y*Z block of chunks arround a position, like for example arround a player.
|
||||
///
|
||||
/// When the player moves, crossing a chunk boundary, chunks behind disapear, chunks in front
|
||||
/// appear. The torroidal nature of the table (modulo on the coordinates) allows reusing the
|
||||
/// disapearing chunks for the new chunks appearing in front.
|
||||
pub struct ToroidalStructureTable {
|
||||
/// Size of the torroidal structure : how many chunks in each direction can be rendered at once
|
||||
extent: (usize, usize, usize),
|
||||
|
||||
fixed_structure_table: FixedStructureTable,
|
||||
position: Vec3,
|
||||
current_offset: (isize, isize, isize),
|
||||
|
||||
invalidation_pass: wgpu::ComputePipeline,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
struct ToroidalInvalidationImmediates {
|
||||
extent: [u32; 3],
|
||||
_pad1: u32,
|
||||
previous_offset: [i32; 3],
|
||||
_pad2: u32,
|
||||
offset: [i32; 3],
|
||||
_pad3: u32,
|
||||
}
|
||||
|
||||
impl ToroidalStructureTable {
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
extent: (usize, usize, usize),
|
||||
initial_position: Vec3,
|
||||
max_requests: usize,
|
||||
producer_id: u32,
|
||||
) -> Self {
|
||||
let size = extent.0 * extent.1 * extent.2;
|
||||
assert!(size <= (u32::MAX as usize));
|
||||
|
||||
let current_offset = Self::offset_from_center(extent, initial_position);
|
||||
|
||||
// Initial anchor of every slot is its world position in the starting
|
||||
// window. Structure ids are table-internal and start at `0..size`.
|
||||
let anchors = (0..size)
|
||||
.map(|slot| {
|
||||
let (x, y, z) = Self::position_for_offset(extent, slot, current_offset);
|
||||
StructureAnchor::from_world(x as i32, y as i32, z as i32, 0)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let bind_group_layout = create_multi_buffers_bind_group_layout(
|
||||
device,
|
||||
1,
|
||||
Some("ToroidalStructureTable::bind_group_layout"),
|
||||
);
|
||||
|
||||
let invalidation_pipeline_layout =
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("ToroidalStructureTable::invalidation_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&bind_group_layout)],
|
||||
immediate_size: size_of::<ToroidalInvalidationImmediates>() as u32,
|
||||
});
|
||||
|
||||
let shader_module =
|
||||
device.create_shader_module(include_wgsl!("./shaders/toroidal_structure.wgsl"));
|
||||
|
||||
let invalidation_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("ToroidalStructureTable::invalidation_pass"),
|
||||
layout: Some(&invalidation_pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("invalidate_new"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
ToroidalStructureTable {
|
||||
extent,
|
||||
fixed_structure_table: FixedStructureTable::new_with_anchors(
|
||||
device,
|
||||
size,
|
||||
max_requests,
|
||||
producer_id,
|
||||
anchors,
|
||||
),
|
||||
position: initial_position,
|
||||
current_offset,
|
||||
invalidation_pass,
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the center position to `new_position`.
|
||||
/// 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 identity; anchors that leave are retired. The
|
||||
/// invalidation pass resets the pointers of moved slots so their roots are
|
||||
/// requested again.
|
||||
///
|
||||
/// 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<StructureAnchor> {
|
||||
let previous_offset = self.current_offset;
|
||||
let new_offset = Self::offset_from_center(self.extent, new_position);
|
||||
self.current_offset = new_offset;
|
||||
self.position = new_position;
|
||||
|
||||
let mut retired = Vec::new();
|
||||
if previous_offset != new_offset {
|
||||
let size = self.extent.0 * self.extent.1 * self.extent.2;
|
||||
let new_anchors: Vec<StructureAnchor> = (0..size)
|
||||
.map(|slot| {
|
||||
let (x, y, z) = Self::position_for_offset(self.extent, slot, new_offset);
|
||||
StructureAnchor::from_world(x as i32, y as i32, z as i32, 0)
|
||||
})
|
||||
.collect();
|
||||
|
||||
retired = self
|
||||
.fixed_structure_table
|
||||
.reassign_slots(queue, &new_anchors);
|
||||
}
|
||||
|
||||
let invalidation_parameters = ToroidalInvalidationImmediates {
|
||||
extent: [
|
||||
self.extent.0 as u32,
|
||||
self.extent.1 as u32,
|
||||
self.extent.2 as u32,
|
||||
],
|
||||
_pad1: 0,
|
||||
previous_offset: [
|
||||
previous_offset.0 as i32,
|
||||
previous_offset.1 as i32,
|
||||
previous_offset.2 as i32,
|
||||
],
|
||||
_pad2: 0,
|
||||
offset: [
|
||||
self.current_offset.0 as i32,
|
||||
self.current_offset.1 as i32,
|
||||
self.current_offset.2 as i32,
|
||||
],
|
||||
_pad3: 0,
|
||||
};
|
||||
|
||||
let mut invalidation_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("ToroidalStructureTable::invalidation_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
invalidation_pass.set_pipeline(&self.invalidation_pass);
|
||||
invalidation_pass.set_bind_group(0, self.fixed_structure_table.pointers_bind_group(), &[]);
|
||||
invalidation_pass.set_immediates(0, bytemuck::bytes_of(&invalidation_parameters));
|
||||
invalidation_pass.dispatch_workgroups(
|
||||
self.extent.0.div_ceil(4) as u32,
|
||||
self.extent.1.div_ceil(4) as u32,
|
||||
self.extent.2.div_ceil(4) as u32,
|
||||
);
|
||||
|
||||
retired
|
||||
}
|
||||
|
||||
/// Returns the world position encoded in a table anchor.
|
||||
pub fn position_for_anchor(&self, anchor: StructureAnchor) -> (isize, isize, isize) {
|
||||
let (x, y, z, _version) = anchor.world();
|
||||
(x as isize, y as isize, z as isize)
|
||||
}
|
||||
|
||||
/// Canonical table slot of the visible block's minimum corner.
|
||||
///
|
||||
/// The render shader uses this to advance its table slot incrementally, so
|
||||
/// the ray traversal does not have to perform an integer modulo per chunk.
|
||||
pub fn base_slot(&self) -> [u32; 3] {
|
||||
let (ox, oy, oz) = self.current_offset;
|
||||
let (ex, ey, ez) = self.extent;
|
||||
[
|
||||
ox.rem_euclid(ex as isize) as u32,
|
||||
oy.rem_euclid(ey as isize) as u32,
|
||||
oz.rem_euclid(ez as isize) as u32,
|
||||
]
|
||||
}
|
||||
|
||||
fn position_for_offset(
|
||||
extent: (usize, usize, 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 = slot as isize;
|
||||
|
||||
let sx = id % ex;
|
||||
let sz = (id / ex) % ez;
|
||||
let sy = id / (ex * ez);
|
||||
|
||||
let (ox, oy, oz) = offset;
|
||||
|
||||
(
|
||||
ox + (sx - ox).rem_euclid(ex),
|
||||
oy + (sy - oy).rem_euclid(ey),
|
||||
oz + (sz - oz).rem_euclid(ez),
|
||||
)
|
||||
}
|
||||
|
||||
fn offset_from_center(extent: (usize, usize, usize), position: Vec3) -> (isize, isize, isize) {
|
||||
(
|
||||
position.x.floor() as isize - (extent.0 as isize / 2),
|
||||
position.y.floor() as isize - (extent.1 as isize / 2),
|
||||
position.z.floor() as isize - (extent.2 as isize / 2),
|
||||
)
|
||||
}
|
||||
|
||||
// Function calls through to fixed_structure_table
|
||||
|
||||
pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup {
|
||||
self.fixed_structure_table.raytrace_bind_group()
|
||||
}
|
||||
|
||||
pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout {
|
||||
self.fixed_structure_table.raytrace_bind_group_layout()
|
||||
}
|
||||
|
||||
pub fn insert<const N: usize>(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut vxls_profiler::ScopeEncoder<wgpu::CommandEncoder>,
|
||||
insertion: &vxls_voxel_cache::insertion::CacheInsertionData<N>,
|
||||
) where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
self.fixed_structure_table
|
||||
.insert(device, encoder, insertion);
|
||||
}
|
||||
|
||||
pub fn gather_requests(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut vxls_profiler::ScopeEncoder<wgpu::CommandEncoder>,
|
||||
request_buffer: &vxls_voxel_cache::requests::CacheRequestBuffer,
|
||||
) {
|
||||
self.fixed_structure_table
|
||||
.gather_requests(device, encoder, request_buffer);
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> vxls_voxel_cache::CacheInvalidable<N> for ToroidalStructureTable
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
fn validate_insertion(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut vxls_profiler::ScopeEncoder<CommandEncoder>,
|
||||
insertion: &vxls_voxel_cache::insertion::CacheInsertionData<N>,
|
||||
) {
|
||||
self.fixed_structure_table
|
||||
.validate_insertion(device, encoder, insertion);
|
||||
}
|
||||
|
||||
fn invalidate(
|
||||
&mut self,
|
||||
encoder: &mut vxls_profiler::ScopeEncoder<CommandEncoder>,
|
||||
cache_evictor: &vxls_voxel_cache::eviction::CacheEvictor,
|
||||
invalid_timestamp: u32,
|
||||
) {
|
||||
self.fixed_structure_table
|
||||
.invalidate(encoder, cache_evictor, invalid_timestamp);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
@group(0) @binding(0) var<storage, read_write> table_pointers: array<u32>;
|
||||
|
||||
struct InvalidationImmediates
|
||||
{
|
||||
extent: vec3<u32>,
|
||||
pevious_offset: vec3<i32>,
|
||||
offset: vec3<i32>,
|
||||
}
|
||||
|
||||
var<immediate> immediates: InvalidationImmediates;
|
||||
|
||||
|
||||
@compute
|
||||
@workgroup_size(4, 4, 4)
|
||||
fn invalidate_new(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
if(any(gid >= immediates.extent))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Check whether this invocation lies within a pointer to be renewed
|
||||
let igid = vec3<i32>(gid);
|
||||
let previous_pos = get_position(igid, immediates.pevious_offset);
|
||||
let pos = get_position(igid, immediates.offset);
|
||||
|
||||
if(any(previous_pos != pos))
|
||||
{
|
||||
// Invalidate pointer
|
||||
let index = gid.x + gid.z * immediates.extent.x + gid.y * immediates.extent.x * immediates.extent.z;
|
||||
table_pointers[index] = u32(1) << 31;
|
||||
}
|
||||
}
|
||||
|
||||
fn get_position(block_position: vec3<i32>, offset: vec3<i32>) -> vec3<i32>
|
||||
{
|
||||
return offset + imodv((block_position - offset), vec3<i32>(immediates.extent));
|
||||
}
|
||||
|
||||
fn imod(x: i32, n: i32) -> i32 {
|
||||
return ((x % n) + n) % n;
|
||||
}
|
||||
|
||||
fn imodv(x: vec3<i32>, n: vec3<i32>) -> vec3<i32> {
|
||||
return vec3<i32>(imod(x.x, n.x), imod(x.y, n.y), imod(x.z, n.z));
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "vxls-voxel-cache"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
bytemuck.workspace = true
|
||||
wgpu.workspace = true
|
||||
vxls-attributes = { path = "../vxls-attributes" }
|
||||
vxls-gpu = { path = "../vxls-gpu" }
|
||||
vxls-profiler = { path = "../vxls-profiler" }
|
||||
@@ -1,36 +1,33 @@
|
||||
use vxls_attributes::AttributeDescriptor;
|
||||
use vxls_attributes::AttributesLayout;
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
|
||||
use crate::gpu_profiler::memory_profiler;
|
||||
use crate::voxel_cache::layout::CacheLayout;
|
||||
use vxls_profiler::memory_profiler;
|
||||
|
||||
/// Contains instanciated gpu buffers to hold data for cache attributes
|
||||
pub struct CacheAttributes<const N: usize>
|
||||
{
|
||||
pub struct CacheAttributes<const N: usize> {
|
||||
attribute_buffers: Vec<wgpu::Buffer>,
|
||||
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
bind_group: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheAttributes<N>
|
||||
{
|
||||
pub fn from_cache_layout(
|
||||
impl<const N: usize> CacheAttributes<N> {
|
||||
pub fn from_attribute_layout(
|
||||
device: &mut memory_profiler::Device,
|
||||
layout: &CacheLayout,
|
||||
layout: &AttributesLayout,
|
||||
page_count: usize,
|
||||
) -> Self
|
||||
{
|
||||
) -> Self {
|
||||
let attribute_buffers = layout
|
||||
.attributes
|
||||
.iter()
|
||||
.map(|attribute| {
|
||||
attribute.create_buffer_profiled(
|
||||
create_attributes_buffer_profiled::<N>(
|
||||
device,
|
||||
N * N * N,
|
||||
attribute,
|
||||
page_count,
|
||||
BufferUsages::STORAGE,
|
||||
wgpu::BufferUsages::STORAGE,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -58,9 +55,10 @@ impl<const N: usize> CacheAttributes<N>
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_bind_group_layout(device: &wgpu::Device, layout: &CacheLayout)
|
||||
-> BindGroupLayout
|
||||
{
|
||||
pub fn create_bind_group_layout(
|
||||
device: &wgpu::Device,
|
||||
layout: &AttributesLayout,
|
||||
) -> BindGroupLayout {
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("CacheAttributes::bind_group_layout"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
@@ -79,18 +77,57 @@ impl<const N: usize> CacheAttributes<N>
|
||||
})
|
||||
}
|
||||
|
||||
pub fn bind_group_layout(&self) -> &wgpu::BindGroupLayout
|
||||
{
|
||||
pub fn bind_group_layout(&self) -> &wgpu::BindGroupLayout {
|
||||
&self.bind_group_layout
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &wgpu::BindGroup
|
||||
{
|
||||
pub fn bind_group(&self) -> &wgpu::BindGroup {
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
pub fn attribute_buffers(&self) -> &[Buffer]
|
||||
{
|
||||
pub fn attribute_buffers(&self) -> &[Buffer] {
|
||||
&self.attribute_buffers
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_attributes_buffer_profiled<const N: usize>(
|
||||
device: &mut memory_profiler::Device,
|
||||
attribute_descriptor: &AttributeDescriptor,
|
||||
page_count: usize,
|
||||
usage: wgpu::BufferUsages,
|
||||
) -> wgpu::Buffer {
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(
|
||||
format!(
|
||||
"VoxelCacheAttribute ({}) {} word(s)",
|
||||
attribute_descriptor.label, attribute_descriptor.word_count
|
||||
)
|
||||
.as_str(),
|
||||
),
|
||||
size: (page_count * attribute_descriptor.word_count as usize * N * N * N * size_of::<u32>())
|
||||
as u64,
|
||||
usage,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn create_attributes_buffer<const N: usize>(
|
||||
device: &wgpu::Device,
|
||||
attribute_descriptor: &AttributeDescriptor,
|
||||
page_count: usize,
|
||||
usage: wgpu::BufferUsages,
|
||||
) -> wgpu::Buffer {
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(
|
||||
format!(
|
||||
"VoxelCacheAttribute ({}) {} word(s)",
|
||||
attribute_descriptor.label, attribute_descriptor.word_count
|
||||
)
|
||||
.as_str(),
|
||||
),
|
||||
size: (page_count * attribute_descriptor.word_count as usize * N * N * N * size_of::<u32>())
|
||||
as u64,
|
||||
usage,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
}
|
||||
@@ -2,54 +2,57 @@
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::include_wgsl;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::gpu::create_multi_buffers_bind_group;
|
||||
use crate::gpu::radix_sort;
|
||||
use crate::gpu_profiler::ScopeEncoder;
|
||||
use crate::gpu_profiler::memory_profiler;
|
||||
use crate::gpu_profiler::{self};
|
||||
use crate::voxel_cache::CacheRessources;
|
||||
use crate::voxel_cache::create_multi_buffers_bind_group_layout;
|
||||
use crate::voxel_cache::structure::CacheStructure;
|
||||
use crate::CacheRessources;
|
||||
use crate::create_multi_buffers_bind_group_layout;
|
||||
use crate::structure::CacheStructure;
|
||||
use vxls_gpu::create_multi_buffers_bind_group;
|
||||
use vxls_gpu::radix_sort;
|
||||
use vxls_profiler::ScopeEncoder;
|
||||
use vxls_profiler::memory_profiler;
|
||||
use vxls_profiler::{self};
|
||||
|
||||
/// Retains usage information about pages in the cache under the form of timestamps.
|
||||
/// Produces a list of LRU eviction order, from which the cache can pull pages to recycle
|
||||
pub struct CacheEvictor
|
||||
{
|
||||
/// Produces an eviction order from which the cache can pull pages to recycle.
|
||||
///
|
||||
/// The list is ordered by timestamp first (least recently used first). Ties are
|
||||
/// broken by depth, deepest first. This works because the timestamp pass is a
|
||||
/// stable radix sort applied after a descending depth sort: pages that share a
|
||||
/// timestamp keep the deepest-first order established by the depth pass.
|
||||
pub struct CacheEvictor {
|
||||
page_count: usize,
|
||||
|
||||
/// Contains a u32 timestamp per page, so that we know when a page was last used
|
||||
timestamp_pages: wgpu::Buffer,
|
||||
|
||||
/// Contains indices in LRU order, after sorting
|
||||
/// Contains page indices in eviction order: least recently used first.
|
||||
/// Among pages with equal timestamps, deeper pages come first.
|
||||
lru_list: wgpu::Buffer,
|
||||
|
||||
/// When reusing pages, count of lru pages consumed
|
||||
#[allow(unused)]
|
||||
consumed_count: wgpu::Buffer,
|
||||
|
||||
/// To reset lru indices between insertions
|
||||
reset_lru_pass: wgpu::ComputePipeline,
|
||||
|
||||
/// To copy corresponding timestamp values after first depth sort
|
||||
/// To copy corresponding timestamp values after the descending depth sort
|
||||
indirect_copy_pass: wgpu::ComputePipeline,
|
||||
pipelines_dispatch_count: u32,
|
||||
|
||||
// For external passes
|
||||
#[allow(unused)]
|
||||
bind_group_layout: BindGroupLayout,
|
||||
bind_group: BindGroup,
|
||||
}
|
||||
|
||||
impl CacheEvictor
|
||||
{
|
||||
impl CacheEvictor {
|
||||
pub fn new(
|
||||
device: &mut memory_profiler::Device,
|
||||
page_count: usize,
|
||||
initial_timestamp: u32,
|
||||
) -> Self
|
||||
{
|
||||
) -> Self {
|
||||
let timestamp_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheUsage::timestamp_pages"),
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
|
||||
@@ -122,7 +125,7 @@ impl CacheEvictor
|
||||
}
|
||||
}
|
||||
|
||||
pub fn prepare_eviction_list<const N: usize>(
|
||||
pub(crate) fn prepare_eviction_list<const N: usize>(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
ressources: &CacheRessources<N>,
|
||||
@@ -131,7 +134,7 @@ impl CacheEvictor
|
||||
) where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "CacheEvictor::prepare_eviction_list");
|
||||
vxls_profiler::begin_scope!(encoder, "CacheEvictor::prepare_eviction_list");
|
||||
// Reset lru list
|
||||
{
|
||||
let mut reset_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
@@ -146,9 +149,17 @@ impl CacheEvictor
|
||||
reset_pass.dispatch_workgroups(self.pipelines_dispatch_count, 1, 1);
|
||||
}
|
||||
|
||||
// First sort nodes per depth
|
||||
// First sort nodes by depth, deepest first. This is the tie-breaker:
|
||||
// the timestamp sort below is stable, so it preserves this order for
|
||||
// pages that share a timestamp.
|
||||
//
|
||||
// Consuming the list in order then reuses the deepest pages first among
|
||||
// equal timestamps. Since a page's resident children are deeper, they
|
||||
// appear earlier in the list and are reused first (provided their
|
||||
// timestamp is equal or older), instead of being orphaned when the
|
||||
// parent is recycled.
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "depth radix");
|
||||
vxls_profiler::begin_scope!(encoder, "depth radix");
|
||||
encoder.copy_buffer_to_buffer(
|
||||
structure.depth_pages(),
|
||||
0,
|
||||
@@ -164,12 +175,12 @@ impl CacheEvictor
|
||||
None,
|
||||
Some(self.page_count),
|
||||
&mut encoder,
|
||||
radix_sort::RadixSortDirection::Ascending,
|
||||
radix_sort::RadixSortDirection::Descending,
|
||||
);
|
||||
}
|
||||
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "indirect copy");
|
||||
vxls_profiler::begin_scope!(encoder, "indirect copy");
|
||||
let mut indirect_copy_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("CacheEvictor::indirect_copy_pass"),
|
||||
timestamp_writes: None,
|
||||
@@ -182,8 +193,11 @@ impl CacheEvictor
|
||||
indirect_copy_pass.dispatch_workgroups(self.pipelines_dispatch_count, 1, 1);
|
||||
}
|
||||
|
||||
// Then sort by timestamp, oldest first. The radix sort is stable, so
|
||||
// equal timestamps retain the deepest-first order from the depth sort.
|
||||
// The resulting list is LRU-first with deepest-first ties.
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "timestamp radix");
|
||||
vxls_profiler::begin_scope!(encoder, "timestamp radix");
|
||||
ressources.radix_sorter.sort(
|
||||
device,
|
||||
&ressources.scratch_buffer,
|
||||
@@ -196,18 +210,15 @@ impl CacheEvictor
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &BindGroup
|
||||
{
|
||||
pub fn bind_group(&self) -> &BindGroup {
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout
|
||||
{
|
||||
pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout {
|
||||
create_multi_buffers_bind_group_layout(device, 3, Some("CacheEvictor::bind_group_layout"))
|
||||
}
|
||||
|
||||
pub fn timestamp_pages_buffer(&self) -> &wgpu::Buffer
|
||||
{
|
||||
pub fn timestamp_pages_buffer(&self) -> &wgpu::Buffer {
|
||||
&self.timestamp_pages
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,699 @@
|
||||
use std::num::NonZero;
|
||||
|
||||
use vxls_attributes::AttributesLayout;
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::ShaderStages;
|
||||
|
||||
use vxls_attributes::Attributes;
|
||||
|
||||
use crate::schema::InsertionInformation;
|
||||
use crate::schema::InsertionParent;
|
||||
use crate::schema::LocationPage;
|
||||
|
||||
/// Data to be inserted in a cache insertion operation
|
||||
pub struct CacheInsertionData<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
/// The amount of pages to insert this structure can hold
|
||||
max_page_count: usize,
|
||||
|
||||
/// Amount of pages that the structure actually contains
|
||||
page_count_buffer: wgpu::Buffer,
|
||||
|
||||
/// Information about inserted pages : dense array of [`InsertionInformation<N>`] structs
|
||||
insertion_information: wgpu::Buffer,
|
||||
|
||||
/// Location of the new nodes : dense array of [`LocationPage`] structs
|
||||
location_pages: wgpu::Buffer,
|
||||
|
||||
/// Contains the attributes to import in the cache.
|
||||
attributes: Vec<wgpu::Buffer>,
|
||||
|
||||
/// Layout the attribute buffers were created from. Kept so attribute
|
||||
/// uploads can validate producer layouts against the cache layout.
|
||||
layout: AttributesLayout,
|
||||
|
||||
/// Contains the indicies of the page in which the data was written
|
||||
destination_indices: wgpu::Buffer,
|
||||
|
||||
/// Parent/attachment information for every entry : dense array of [`InsertionParent`]
|
||||
insertion_parents: wgpu::Buffer,
|
||||
|
||||
/// Indices of the entries that passed validation, written by the validation pass
|
||||
valid_indices: wgpu::Buffer,
|
||||
|
||||
/// Amount of entries written to [`Self::valid_indices`]
|
||||
valid_count: wgpu::Buffer,
|
||||
|
||||
#[allow(unused)]
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
bind_group: wgpu::BindGroup,
|
||||
bind_group_no_attributes: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
/// One entry of an insertion batch.
|
||||
///
|
||||
/// The cache owns page identity, so the host supplies the structure of the
|
||||
/// produced page together with the parent it attaches to and the location it
|
||||
/// should be recorded at. The cache does not depend on the producer crate, so
|
||||
/// this is the primitive form produced by `ReadyItem::insertion_entry`.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct InsertionEntry<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
/// Structure of the produced page.
|
||||
pub information: InsertionInformation<N>,
|
||||
|
||||
/// Attachment point of the produced page.
|
||||
pub parent: InsertionParent,
|
||||
|
||||
/// Identity recorded for the produced page.
|
||||
pub location: LocationPage,
|
||||
}
|
||||
|
||||
/// Errors reported while uploading a full insertion batch.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum InsertionUploadError {
|
||||
/// The batch has more entries than the insertion data can hold.
|
||||
TooManyEntries { provided: usize, capacity: usize },
|
||||
|
||||
/// The voxel slice does not contain exactly one page per entry.
|
||||
VoxelCountMismatch { provided: usize, expected: usize },
|
||||
|
||||
/// The producer attribute layout does not match the cache layout.
|
||||
LayoutMismatch {
|
||||
producer: AttributesLayout,
|
||||
cache: AttributesLayout,
|
||||
},
|
||||
|
||||
/// The attribute payload was rejected by [`CacheInsertionData::write_attributes`].
|
||||
Attributes(AttributeUploadError),
|
||||
}
|
||||
|
||||
impl From<AttributeUploadError> for InsertionUploadError {
|
||||
fn from(error: AttributeUploadError) -> Self {
|
||||
Self::Attributes(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for InsertionUploadError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::TooManyEntries { provided, capacity } => write!(
|
||||
formatter,
|
||||
"insertion batch has {provided} entries but capacity is {capacity}"
|
||||
),
|
||||
Self::VoxelCountMismatch { provided, expected } => write!(
|
||||
formatter,
|
||||
"insertion batch has {provided} voxels but expected {expected}"
|
||||
),
|
||||
Self::LayoutMismatch { producer, cache } => write!(
|
||||
formatter,
|
||||
"producer attribute layout {producer:?} does not match cache layout {cache:?}"
|
||||
),
|
||||
Self::Attributes(error) => write!(formatter, "attribute upload failed: {error:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for InsertionUploadError {}
|
||||
|
||||
/// Errors reported while uploading a producer attribute slice into
|
||||
/// [`CacheInsertionData`].
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum AttributeUploadError {
|
||||
/// The slice is not a whole number of pages.
|
||||
NotWholePages { voxel_count: usize, children: usize },
|
||||
|
||||
/// The slice does not fit in this insertion batch.
|
||||
TooManyVoxels { voxel_count: usize, capacity: usize },
|
||||
|
||||
/// The producer declares more attributes than the cache layout has.
|
||||
MissingCacheAttribute { index: usize },
|
||||
|
||||
/// The producer attribute index is out of bounds.
|
||||
AttributeIndexOutOfBounds { index: usize },
|
||||
|
||||
/// The cache attribute is not `External`, so insertion will not copy it.
|
||||
NotExternal { index: usize },
|
||||
|
||||
/// Declared word counts disagree.
|
||||
WordCountMismatch {
|
||||
index: usize,
|
||||
producer: u32,
|
||||
cache: u32,
|
||||
},
|
||||
|
||||
/// Declared labels disagree (only checked when the cache label is present).
|
||||
LabelMismatch {
|
||||
index: usize,
|
||||
producer: &'static str,
|
||||
cache: Option<&'static str>,
|
||||
},
|
||||
|
||||
/// A `get_attr` implementation returned the wrong number of bytes.
|
||||
BadAttributeBytes {
|
||||
index: usize,
|
||||
expected: usize,
|
||||
actual: usize,
|
||||
},
|
||||
}
|
||||
|
||||
/// Checks that a voxel slice is a whole number of pages and fits the batch.
|
||||
pub fn validate_voxel_count(
|
||||
voxel_count: usize,
|
||||
children: usize,
|
||||
capacity: usize,
|
||||
) -> Result<(), AttributeUploadError> {
|
||||
if !voxel_count.is_multiple_of(children) {
|
||||
return Err(AttributeUploadError::NotWholePages {
|
||||
voxel_count,
|
||||
children,
|
||||
});
|
||||
}
|
||||
|
||||
if voxel_count > capacity {
|
||||
return Err(AttributeUploadError::TooManyVoxels {
|
||||
voxel_count,
|
||||
capacity,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Collects attribute `index` of every voxel into `[voxel][word]` bytes.
|
||||
///
|
||||
/// The resulting byte slice is exactly what the insertion attribute buffer
|
||||
/// expects for one entry-major attribute page.
|
||||
pub fn collect_attribute_bytes<A: Attributes>(
|
||||
voxels: &[A],
|
||||
index: usize,
|
||||
) -> Result<Vec<u8>, AttributeUploadError> {
|
||||
let Some(descriptor) = A::LAYOUT.attributes.get(index) else {
|
||||
return Err(AttributeUploadError::AttributeIndexOutOfBounds { index });
|
||||
};
|
||||
|
||||
let expected = descriptor.word_count as usize * size_of::<u32>();
|
||||
let mut bytes = Vec::with_capacity(voxels.len() * expected);
|
||||
|
||||
for voxel in voxels {
|
||||
let attribute = voxel.get_attr(index);
|
||||
|
||||
if attribute.len() != expected {
|
||||
return Err(AttributeUploadError::BadAttributeBytes {
|
||||
index,
|
||||
expected,
|
||||
actual: attribute.len(),
|
||||
});
|
||||
}
|
||||
|
||||
bytes.extend_from_slice(attribute);
|
||||
}
|
||||
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheInsertionData<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &wgpu::Device, max_page_count: usize, layout: &AttributesLayout) -> Self {
|
||||
let page_count_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheInsertionData::page_count_buffer"),
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
size: size_of::<u32>() as u64,
|
||||
});
|
||||
|
||||
let insertion_information = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheInsertionData::insertion_information"),
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
size: (size_of::<InsertionInformation<N>>() * max_page_count) as u64,
|
||||
});
|
||||
|
||||
let location_pages = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheInsertionData::location_pages"),
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
size: (size_of::<LocationPage>() * max_page_count) as u64,
|
||||
});
|
||||
|
||||
let destination_indices = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheInsertionData::destination_indices"),
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
size: (size_of::<u32>() * max_page_count) as u64,
|
||||
});
|
||||
|
||||
let insertion_parents = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheInsertionData::insertion_parents"),
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
size: (size_of::<InsertionParent>() * max_page_count) as u64,
|
||||
});
|
||||
|
||||
let valid_indices = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheInsertionData::valid_indices"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
mapped_at_creation: false,
|
||||
size: (size_of::<u32>() * max_page_count) as u64,
|
||||
});
|
||||
|
||||
let valid_count = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheInsertionData::valid_count"),
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
size: size_of::<u32>() as u64,
|
||||
});
|
||||
|
||||
let attributes = layout
|
||||
.attributes
|
||||
.iter()
|
||||
.map(|attribute| {
|
||||
crate::attributes::create_attributes_buffer::<N>(
|
||||
device,
|
||||
attribute,
|
||||
max_page_count,
|
||||
BufferUsages::STORAGE | BufferUsages::COPY_DST,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let bind_group_bindings = attributes
|
||||
.iter()
|
||||
.map(|buffer| buffer.as_entire_buffer_binding())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let mut entries = vec![
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: page_count_buffer.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: insertion_information.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: location_pages.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: destination_indices.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: insertion_parents.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 5,
|
||||
resource: valid_indices.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 6,
|
||||
resource: valid_count.as_entire_binding(),
|
||||
},
|
||||
];
|
||||
|
||||
let bind_group_layout_no_attributes = Self::create_bind_group_layout(device, None);
|
||||
let bind_group_no_attributes = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("CacheInsertionData::bind_group_no_attributes"),
|
||||
layout: &bind_group_layout_no_attributes,
|
||||
entries: &entries,
|
||||
});
|
||||
entries.push(wgpu::BindGroupEntry {
|
||||
binding: 7,
|
||||
resource: wgpu::BindingResource::BufferArray(&bind_group_bindings),
|
||||
});
|
||||
|
||||
let bind_group_layout = Self::create_bind_group_layout(device, Some(layout));
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("CacheInsertionData::bind_group"),
|
||||
layout: &bind_group_layout,
|
||||
entries: &entries,
|
||||
});
|
||||
|
||||
Self {
|
||||
page_count_buffer,
|
||||
max_page_count,
|
||||
insertion_information,
|
||||
location_pages,
|
||||
destination_indices,
|
||||
insertion_parents,
|
||||
valid_indices,
|
||||
valid_count,
|
||||
attributes,
|
||||
layout: *layout,
|
||||
|
||||
bind_group_layout,
|
||||
bind_group,
|
||||
bind_group_no_attributes,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a bindgroup layout to bind the insertion data :
|
||||
/// - Page count buffer (u32)
|
||||
/// - Insertion information
|
||||
/// - Location pages
|
||||
/// - Destination indicies
|
||||
/// - (Optional) attributes
|
||||
///
|
||||
/// An applcation that does not need the the attributes can pass `None` to layout.
|
||||
/// It can then use [`CacheInsertionData::<_>::bind_group_no_attributes(...)`] to get the
|
||||
/// corresponding bind group, otherwise use [`CacheInsertionData::<_>::bind_group(...)`]
|
||||
///
|
||||
pub fn create_bind_group_layout(
|
||||
device: &wgpu::Device,
|
||||
layout: Option<&AttributesLayout>,
|
||||
) -> BindGroupLayout {
|
||||
let storage_entry = |binding: u32| wgpu::BindGroupLayoutEntry {
|
||||
binding,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
};
|
||||
|
||||
let mut entries = vec![
|
||||
storage_entry(0), // page count
|
||||
storage_entry(1), // insertion information
|
||||
storage_entry(2), // location pages
|
||||
storage_entry(3), // destination indices
|
||||
storage_entry(4), // insertion parents
|
||||
storage_entry(5), // valid indices
|
||||
storage_entry(6), // valid count
|
||||
];
|
||||
|
||||
if let Some(layout) = layout {
|
||||
entries.push(wgpu::BindGroupLayoutEntry {
|
||||
binding: 7,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: Some(NonZero::new(layout.attributes.len() as u32).unwrap()),
|
||||
});
|
||||
}
|
||||
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("CacheInsertionData::bind_group_layout"),
|
||||
entries: &entries,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &wgpu::BindGroup {
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
pub fn bind_group_no_attributes(&self) -> &wgpu::BindGroup {
|
||||
&self.bind_group_no_attributes
|
||||
}
|
||||
|
||||
pub fn page_count(&self) -> usize {
|
||||
self.max_page_count
|
||||
}
|
||||
|
||||
/// Maximum number of entries a batch can hold.
|
||||
pub fn capacity(&self) -> usize {
|
||||
self.max_page_count
|
||||
}
|
||||
|
||||
pub fn page_count_buffer(&self) -> &wgpu::Buffer {
|
||||
&self.page_count_buffer
|
||||
}
|
||||
|
||||
pub fn insertion_information_buffer(&self) -> &wgpu::Buffer {
|
||||
&self.insertion_information
|
||||
}
|
||||
|
||||
pub fn location_pages_buffer(&self) -> &wgpu::Buffer {
|
||||
&self.location_pages
|
||||
}
|
||||
|
||||
pub fn destination_indices_buffer(&self) -> &wgpu::Buffer {
|
||||
&self.destination_indices
|
||||
}
|
||||
|
||||
pub fn insertion_parents_buffer(&self) -> &wgpu::Buffer {
|
||||
&self.insertion_parents
|
||||
}
|
||||
|
||||
pub fn valid_indices_buffer(&self) -> &wgpu::Buffer {
|
||||
&self.valid_indices
|
||||
}
|
||||
|
||||
pub fn valid_count_buffer(&self) -> &wgpu::Buffer {
|
||||
&self.valid_count
|
||||
}
|
||||
|
||||
pub fn attributes_buffers(&self) -> &[wgpu::Buffer] {
|
||||
&self.attributes
|
||||
}
|
||||
|
||||
/// The layout this insertion data was created from.
|
||||
pub fn layout(&self) -> &AttributesLayout {
|
||||
&self.layout
|
||||
}
|
||||
|
||||
/// Number of attribute buffers in this insertion batch.
|
||||
pub fn attribute_count(&self) -> usize {
|
||||
self.attributes.len()
|
||||
}
|
||||
|
||||
/// The attribute buffer for `index`, if it exists.
|
||||
pub fn attribute_buffer(&self, index: usize) -> Option<&wgpu::Buffer> {
|
||||
self.attributes.get(index)
|
||||
}
|
||||
|
||||
/// Maximum number of voxels this insertion batch can hold.
|
||||
pub fn attribute_capacity(&self) -> usize {
|
||||
self.max_page_count * N * N * N
|
||||
}
|
||||
|
||||
/// Uploads `[entry][child]` voxel attributes into the insertion buffers.
|
||||
///
|
||||
/// `voxels` must contain `entry_count * N^3` elements in child-major order
|
||||
/// (`x + 4*y + 16*z`). Returns `entry_count`, which the caller should write
|
||||
/// to [`Self::page_count_buffer`] before insertion.
|
||||
///
|
||||
/// Only the producer attributes (`A::LAYOUT`) are written. `DontTouch`
|
||||
/// attributes appended to the cache layout are left untouched.
|
||||
pub fn write_attributes<A: Attributes>(
|
||||
&self,
|
||||
queue: &wgpu::Queue,
|
||||
voxels: &[A],
|
||||
) -> Result<usize, AttributeUploadError> {
|
||||
if A::LAYOUT != self.layout {
|
||||
return Err(AttributeUploadError::LabelMismatch {
|
||||
index: 0,
|
||||
producer: "..",
|
||||
cache: None,
|
||||
});
|
||||
}
|
||||
validate_voxel_count(voxels.len(), N * N * N, self.attribute_capacity())?;
|
||||
|
||||
if voxels.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
for index in 0..A::LAYOUT.len() {
|
||||
let bytes = collect_attribute_bytes(voxels, index)?;
|
||||
queue.write_buffer(&self.attributes[index], 0, &bytes);
|
||||
}
|
||||
|
||||
Ok(voxels.len() / (N * N * N))
|
||||
}
|
||||
|
||||
/// Uploads a complete insertion batch.
|
||||
///
|
||||
/// `entries` and `voxels` must agree: `voxels` contains one page of
|
||||
/// [`Attributes`] per entry, in entry-major order. This writes the
|
||||
/// structure, location and parent arrays, resets `valid_count`, sets
|
||||
/// `page_count` to the number of entries, and uploads the attributes.
|
||||
///
|
||||
/// `destination_indices` is intentionally not written here: the internal
|
||||
/// and external validation passes reset every entry they process, so a
|
||||
/// stale destination can never survive a batch.
|
||||
///
|
||||
/// Returns the number of entries written.
|
||||
pub fn upload<A: Attributes>(
|
||||
&self,
|
||||
queue: &wgpu::Queue,
|
||||
entries: &[InsertionEntry<N>],
|
||||
voxels: &[A],
|
||||
) -> Result<usize, InsertionUploadError> {
|
||||
if A::LAYOUT != self.layout {
|
||||
return Err(InsertionUploadError::LayoutMismatch {
|
||||
producer: A::LAYOUT,
|
||||
cache: self.layout,
|
||||
});
|
||||
}
|
||||
|
||||
if entries.len() > self.capacity() {
|
||||
return Err(InsertionUploadError::TooManyEntries {
|
||||
provided: entries.len(),
|
||||
capacity: self.capacity(),
|
||||
});
|
||||
}
|
||||
|
||||
let expected_voxels = entries.len() * N * N * N;
|
||||
if voxels.len() != expected_voxels {
|
||||
return Err(InsertionUploadError::VoxelCountMismatch {
|
||||
provided: voxels.len(),
|
||||
expected: expected_voxels,
|
||||
});
|
||||
}
|
||||
|
||||
// Disable the batch until every buffer has been written successfully.
|
||||
// This prevents a partially-uploaded batch from being encoded if an
|
||||
// attribute upload fails after the structure buffers were written.
|
||||
queue.write_buffer(&self.page_count_buffer, 0, bytemuck::bytes_of(&0u32));
|
||||
queue.write_buffer(&self.valid_count, 0, bytemuck::bytes_of(&0u32));
|
||||
|
||||
if entries.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let informations: Vec<InsertionInformation<N>> =
|
||||
entries.iter().map(|entry| entry.information).collect();
|
||||
let locations: Vec<LocationPage> = entries.iter().map(|entry| entry.location).collect();
|
||||
let parents: Vec<InsertionParent> = entries.iter().map(|entry| entry.parent).collect();
|
||||
|
||||
queue.write_buffer(
|
||||
&self.insertion_information,
|
||||
0,
|
||||
bytemuck::cast_slice(&informations),
|
||||
);
|
||||
queue.write_buffer(&self.location_pages, 0, bytemuck::cast_slice(&locations));
|
||||
queue.write_buffer(&self.insertion_parents, 0, bytemuck::cast_slice(&parents));
|
||||
|
||||
self.write_attributes(queue, voxels)?;
|
||||
|
||||
// Only now is the batch complete and safe to process.
|
||||
let entry_count = entries.len() as u32;
|
||||
queue.write_buffer(&self.page_count_buffer, 0, bytemuck::bytes_of(&entry_count));
|
||||
|
||||
Ok(entries.len())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use vxls_attributes::Attribute;
|
||||
use vxls_attributes::AttributeDescriptor;
|
||||
use vxls_attributes::AttributesLayout;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
#[repr(C)]
|
||||
struct TestAttributes {
|
||||
color: u32,
|
||||
normal: [f32; 3],
|
||||
}
|
||||
|
||||
impl Attribute for TestAttributes {
|
||||
fn average(attributes: &[Self]) -> Self {
|
||||
if attributes.is_empty() {
|
||||
return Self::default();
|
||||
}
|
||||
|
||||
let count = attributes.len() as f32;
|
||||
|
||||
Self {
|
||||
color: (attributes
|
||||
.iter()
|
||||
.map(|value| value.color as u64)
|
||||
.sum::<u64>()
|
||||
/ attributes.len() as u64) as u32,
|
||||
normal: std::array::from_fn(|index| {
|
||||
attributes
|
||||
.iter()
|
||||
.map(|value| value.normal[index])
|
||||
.sum::<f32>()
|
||||
/ count
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Attributes for TestAttributes {
|
||||
const LAYOUT: AttributesLayout = AttributesLayout::new(&[
|
||||
AttributeDescriptor::new("color", 1),
|
||||
AttributeDescriptor::new("normal", 3),
|
||||
]);
|
||||
|
||||
fn get_attr(&self, index: usize) -> &[u8] {
|
||||
match index {
|
||||
0 => bytemuck::bytes_of(&self.color),
|
||||
1 => bytemuck::bytes_of(&self.normal),
|
||||
_ => panic!("attribute index out of bounds"),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_attr_mut(&mut self, index: usize) -> &mut [u8] {
|
||||
match index {
|
||||
0 => bytemuck::bytes_of_mut(&mut self.color),
|
||||
1 => bytemuck::bytes_of_mut(&mut self.normal),
|
||||
_ => panic!("attribute index out of bounds"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_attribute_bytes_orders_by_voxel() {
|
||||
let voxels = [
|
||||
TestAttributes {
|
||||
color: 1,
|
||||
normal: [1., 2., 3.],
|
||||
},
|
||||
TestAttributes {
|
||||
color: 2,
|
||||
normal: [4., 5., 6.],
|
||||
},
|
||||
];
|
||||
|
||||
let colors = collect_attribute_bytes(&voxels, 0).unwrap();
|
||||
assert_eq!(colors, bytemuck::cast_slice::<u32, u8>(&[1, 2]));
|
||||
|
||||
let normals = collect_attribute_bytes(&voxels, 1).unwrap();
|
||||
assert_eq!(
|
||||
normals,
|
||||
bytemuck::cast_slice::<f32, u8>(&[1., 2., 3., 4., 5., 6.])
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
collect_attribute_bytes(&voxels, 2).unwrap_err(),
|
||||
AttributeUploadError::AttributeIndexOutOfBounds { index: 2 }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn voxel_counts_must_be_whole_pages_within_capacity() {
|
||||
assert_eq!(validate_voxel_count(64, 64, 128), Ok(()));
|
||||
assert_eq!(
|
||||
validate_voxel_count(65, 64, 128),
|
||||
Err(AttributeUploadError::NotWholePages {
|
||||
voxel_count: 65,
|
||||
children: 64,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
validate_voxel_count(128, 64, 64),
|
||||
Err(AttributeUploadError::TooManyVoxels {
|
||||
voxel_count: 128,
|
||||
capacity: 64,
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,52 +1,48 @@
|
||||
#![allow(incomplete_features)]
|
||||
#![feature(generic_const_exprs)]
|
||||
|
||||
use std::num::NonZero;
|
||||
|
||||
use vxls_attributes::AttributesLayout;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::Device;
|
||||
|
||||
use crate::gpu::create_multi_buffers_bg_bg_layout;
|
||||
use crate::gpu::create_multi_buffers_bind_group_layout;
|
||||
use crate::gpu::radix_sort::RadixSorter;
|
||||
use crate::gpu_profiler;
|
||||
use crate::gpu_profiler::ScopeEncoder;
|
||||
use crate::gpu_profiler::memory_profiler;
|
||||
use crate::gpu_profiler::memory_profiler::MemoryProfile;
|
||||
use crate::voxel_cache::attributes::CacheAttributes;
|
||||
use crate::voxel_cache::eviction::CacheEvictor;
|
||||
use crate::voxel_cache::insertion::CacheInsertionData;
|
||||
use crate::voxel_cache::pipelines::CacheInsertionPass;
|
||||
use crate::voxel_cache::pipelines::CacheInvalidationPass;
|
||||
use crate::voxel_cache::pipelines::WritePointersPass;
|
||||
use crate::voxel_cache::pipelines::WriteRequestsPass;
|
||||
use crate::voxel_cache::requests::CacheRequestBuffer;
|
||||
use crate::voxel_cache::requests::CacheRequestHandler;
|
||||
use crate::voxel_cache::structure::CacheStructure;
|
||||
use crate::attributes::CacheAttributes;
|
||||
use crate::eviction::CacheEvictor;
|
||||
use crate::insertion::CacheInsertionData;
|
||||
use crate::pipelines::CacheInsertionPass;
|
||||
use crate::pipelines::CacheInvalidationPass;
|
||||
use crate::pipelines::WritePointersPass;
|
||||
use crate::pipelines::WriteRequestsPass;
|
||||
use crate::requests::CacheRequestBuffer;
|
||||
use crate::requests::CacheRequestHandler;
|
||||
use crate::structure::CacheStructure;
|
||||
use vxls_gpu::create_multi_buffers_bg_bg_layout;
|
||||
use vxls_gpu::create_multi_buffers_bind_group_layout;
|
||||
use vxls_gpu::radix_sort::RadixSorter;
|
||||
use vxls_profiler::ScopeEncoder;
|
||||
use vxls_profiler::memory_profiler;
|
||||
use vxls_profiler::memory_profiler::MemoryProfile;
|
||||
|
||||
pub mod attributes;
|
||||
pub mod eviction;
|
||||
pub mod insertion;
|
||||
pub mod layout;
|
||||
//pub mod layout;
|
||||
pub mod pipelines;
|
||||
pub mod requests;
|
||||
pub mod schema;
|
||||
pub mod structure;
|
||||
pub mod tables;
|
||||
|
||||
pub use layout::CacheAttribute;
|
||||
pub use layout::CacheAttributeInit;
|
||||
pub use layout::CacheLayout;
|
||||
|
||||
/// Stores some ressources that can be reused throughout the modules of the cache
|
||||
struct CacheRessources<const N: usize>
|
||||
{
|
||||
struct CacheRessources<const N: usize> {
|
||||
scratch_buffer: wgpu::Buffer,
|
||||
scratch_buffer_bind_group: wgpu::BindGroup,
|
||||
radix_sorter: RadixSorter,
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheRessources<N>
|
||||
{
|
||||
pub fn new(device: &mut memory_profiler::Device, page_count: usize) -> Self
|
||||
{
|
||||
impl<const N: usize> CacheRessources<N> {
|
||||
pub fn new(device: &mut memory_profiler::Device, page_count: usize) -> Self {
|
||||
let scratch_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheRessources::scratch_buffer"),
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
@@ -68,8 +64,7 @@ impl<const N: usize> CacheRessources<N>
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_scratch_buffer_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout
|
||||
{
|
||||
pub fn create_scratch_buffer_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
|
||||
create_multi_buffers_bind_group_layout(
|
||||
device,
|
||||
1,
|
||||
@@ -77,8 +72,7 @@ impl<const N: usize> CacheRessources<N>
|
||||
)
|
||||
}
|
||||
|
||||
pub fn scratch_buffer_bind_group(&self) -> &wgpu::BindGroup
|
||||
{
|
||||
pub fn scratch_buffer_bind_group(&self) -> &wgpu::BindGroup {
|
||||
&self.scratch_buffer_bind_group
|
||||
}
|
||||
}
|
||||
@@ -108,7 +102,9 @@ where
|
||||
frame_timestamp: u32,
|
||||
}
|
||||
|
||||
pub trait CacheInvalidable
|
||||
pub trait CacheInvalidable<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
fn invalidate(
|
||||
&mut self,
|
||||
@@ -116,41 +112,58 @@ pub trait CacheInvalidable
|
||||
cache_evictor: &CacheEvictor,
|
||||
invalid_timestamp: u32,
|
||||
);
|
||||
|
||||
/// Validates an external insertion batch against the structure table and
|
||||
/// compacts the valid entries before the cache allocates pages for them.
|
||||
fn validate_insertion(
|
||||
&mut self,
|
||||
device: &Device,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
insertion: &CacheInsertionData<N>,
|
||||
);
|
||||
}
|
||||
|
||||
pub enum VoxelCacheInsertion<'a, const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
ExternalRequest(&'a CacheInsertionData<N>, &'a mut dyn CacheInvalidable),
|
||||
InternalRequest(&'a CacheInsertionData<N>, &'a CacheRequestBuffer),
|
||||
ExternalRequest(&'a CacheInsertionData<N>, &'a mut dyn CacheInvalidable<N>),
|
||||
InternalRequest(&'a CacheInsertionData<N>),
|
||||
}
|
||||
|
||||
impl<const N: usize> VoxelCache<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self
|
||||
{
|
||||
pub fn new(
|
||||
device: &Device,
|
||||
page_count: usize,
|
||||
max_requests: usize,
|
||||
attributes_layout: &AttributesLayout,
|
||||
) -> Self {
|
||||
let mut cache_memory_profile = MemoryProfile::new("VoxelCache");
|
||||
let mut mem_device = cache_memory_profile.begin(device);
|
||||
|
||||
let structure = CacheStructure::new(&mut mem_device.group("CacheStructure"), page_count);
|
||||
let attributes = CacheAttributes::from_cache_layout(
|
||||
let attributes = CacheAttributes::from_attribute_layout(
|
||||
&mut mem_device.group("CacheAttributes"),
|
||||
layout,
|
||||
attributes_layout,
|
||||
page_count,
|
||||
);
|
||||
let request_handler =
|
||||
CacheRequestHandler::new(&mut mem_device.group("CacheRequestHandler"), page_count);
|
||||
let request_handler = CacheRequestHandler::new(
|
||||
&mut mem_device.group("CacheRequestHandler"),
|
||||
page_count,
|
||||
max_requests as u32,
|
||||
);
|
||||
let evictor = CacheEvictor::new(&mut mem_device.group("CacheEvictor"), page_count, 0u32);
|
||||
let common_ressources =
|
||||
CacheRessources::new(&mut mem_device.group("CacheRessources"), page_count);
|
||||
|
||||
let write_requests_pass = WriteRequestsPass::new(device, page_count, layout);
|
||||
let cache_insertion_pass = CacheInsertionPass::new(device, page_count, layout);
|
||||
let cache_invalidation_pass = CacheInvalidationPass::new(device, page_count, layout);
|
||||
let write_pointers_pass = WritePointersPass::new(device, page_count, layout);
|
||||
let write_requests_pass = WriteRequestsPass::new(device, page_count, attributes_layout);
|
||||
let cache_insertion_pass = CacheInsertionPass::new(device, page_count, attributes_layout);
|
||||
let cache_invalidation_pass =
|
||||
CacheInvalidationPass::new(device, page_count, attributes_layout);
|
||||
let write_pointers_pass = WritePointersPass::new(device, page_count, attributes_layout);
|
||||
|
||||
let (raytrace_bind_group_layout, raytrace_bind_group) = Self::create_raytrace_bind_group(
|
||||
device,
|
||||
@@ -161,7 +174,7 @@ where
|
||||
);
|
||||
|
||||
drop(mem_device);
|
||||
let mut root_group = cache_memory_profile.terminate();
|
||||
let root_group = cache_memory_profile.terminate();
|
||||
println!("{}", root_group);
|
||||
|
||||
Self {
|
||||
@@ -189,12 +202,15 @@ where
|
||||
device: &Device,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
request_buffer: &CacheRequestBuffer,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "gather_requests");
|
||||
) {
|
||||
vxls_profiler::begin_scope!(encoder, "gather_requests");
|
||||
|
||||
self.request_handler
|
||||
.sort_requests(device, &self.common_ressources, &mut encoder);
|
||||
self.request_handler.sort_requests(
|
||||
device,
|
||||
&self.common_ressources,
|
||||
&mut encoder,
|
||||
request_buffer.max_requests as u32,
|
||||
);
|
||||
|
||||
self.write_requests_pass.encode(
|
||||
&mut encoder,
|
||||
@@ -219,9 +235,8 @@ where
|
||||
device: &Device,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
insertions: &mut [&mut VoxelCacheInsertion<N>],
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "insertion");
|
||||
) {
|
||||
vxls_profiler::begin_scope!(encoder, "insertion");
|
||||
let new_timestamp = self.frame_timestamp + 1;
|
||||
|
||||
self.evictor.prepare_eviction_list(
|
||||
@@ -231,13 +246,30 @@ where
|
||||
&mut encoder,
|
||||
);
|
||||
|
||||
for insertion in insertions.iter()
|
||||
{
|
||||
match insertion
|
||||
{
|
||||
// Validate everything before allocating any page, so stale insertions
|
||||
// can never consume a recycled page.
|
||||
for insertion in insertions.iter_mut() {
|
||||
match insertion {
|
||||
VoxelCacheInsertion::ExternalRequest(cache_insertion_data, invalidable) => {
|
||||
invalidable.validate_insertion(device, &mut encoder, cache_insertion_data);
|
||||
}
|
||||
VoxelCacheInsertion::InternalRequest(cache_insertion_data) => {
|
||||
self.cache_insertion_pass.encode_validation(
|
||||
device,
|
||||
&mut encoder,
|
||||
&self.attributes,
|
||||
&self.structure,
|
||||
cache_insertion_data,
|
||||
&self.evictor,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for insertion in insertions.iter() {
|
||||
match insertion {
|
||||
VoxelCacheInsertion::ExternalRequest(cache_insertion_data, _)
|
||||
| VoxelCacheInsertion::InternalRequest(cache_insertion_data, _) =>
|
||||
{
|
||||
| VoxelCacheInsertion::InternalRequest(cache_insertion_data) => {
|
||||
self.cache_insertion_pass.encode(
|
||||
device,
|
||||
&mut encoder,
|
||||
@@ -252,10 +284,8 @@ where
|
||||
}
|
||||
|
||||
// Invalidate external structures pointing inside the cache
|
||||
for insertion in insertions.iter_mut()
|
||||
{
|
||||
if let VoxelCacheInsertion::ExternalRequest(_, invalidable) = insertion
|
||||
{
|
||||
for insertion in insertions.iter_mut() {
|
||||
if let VoxelCacheInsertion::ExternalRequest(_, invalidable) = insertion {
|
||||
invalidable.invalidate(&mut encoder, &self.evictor, new_timestamp);
|
||||
}
|
||||
}
|
||||
@@ -269,17 +299,10 @@ where
|
||||
);
|
||||
|
||||
// Write internal requests pointers
|
||||
for insertion in insertions.iter_mut()
|
||||
{
|
||||
if let VoxelCacheInsertion::InternalRequest(insertion, request) = insertion
|
||||
{
|
||||
self.write_pointers_pass.encode(
|
||||
&mut encoder,
|
||||
device,
|
||||
&self.structure,
|
||||
request,
|
||||
insertion,
|
||||
);
|
||||
for insertion in insertions.iter_mut() {
|
||||
if let VoxelCacheInsertion::InternalRequest(insertion) = insertion {
|
||||
self.write_pointers_pass
|
||||
.encode(&mut encoder, device, &self.structure, insertion);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,8 +310,7 @@ where
|
||||
self.frame_timestamp = new_timestamp;
|
||||
}
|
||||
|
||||
pub fn current_timestamp(&self) -> u32
|
||||
{
|
||||
pub fn current_timestamp(&self) -> u32 {
|
||||
self.frame_timestamp
|
||||
}
|
||||
|
||||
@@ -298,8 +320,7 @@ where
|
||||
attributes: &CacheAttributes<N>,
|
||||
request_handler: &CacheRequestHandler<N>,
|
||||
evictor: &CacheEvictor,
|
||||
) -> (wgpu::BindGroupLayout, wgpu::BindGroup)
|
||||
{
|
||||
) -> (wgpu::BindGroupLayout, wgpu::BindGroup) {
|
||||
let attribute_count = attributes.attribute_buffers().len();
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("VoxelCache::raytrace_bind_group_layout"),
|
||||
@@ -315,23 +336,9 @@ where
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Attributes
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: Some(
|
||||
NonZero::new(attribute_count as u32)
|
||||
.expect("Null amount of cache attributes."),
|
||||
),
|
||||
},
|
||||
// Request pages
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
@@ -342,7 +349,7 @@ where
|
||||
},
|
||||
// Usage pages
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 3,
|
||||
binding: 2,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
@@ -351,6 +358,20 @@ where
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Attributes
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 3,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: Some(
|
||||
NonZero::new(attribute_count as u32)
|
||||
.expect("Null amount of cache attributes."),
|
||||
),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -369,35 +390,36 @@ where
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::BufferArray(&attributes_bindings),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: request_handler.request_pages_buffer().as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 3,
|
||||
binding: 2,
|
||||
resource: evictor.timestamp_pages_buffer().as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: wgpu::BindingResource::BufferArray(&attributes_bindings),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
(bind_group_layout, bind_group)
|
||||
}
|
||||
|
||||
pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout
|
||||
{
|
||||
pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout {
|
||||
&self.raytrace_bind_group_layout
|
||||
}
|
||||
|
||||
pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup
|
||||
{
|
||||
pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup {
|
||||
&self.raytrace_bind_group
|
||||
}
|
||||
|
||||
// For debugging
|
||||
pub fn usage_timestamps(&self) -> &wgpu::Buffer
|
||||
{
|
||||
pub fn usage_timestamps(&self) -> &wgpu::Buffer {
|
||||
self.evictor.timestamp_pages_buffer()
|
||||
}
|
||||
|
||||
pub fn size(&self) -> usize {
|
||||
self.page_count
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,20 @@
|
||||
use vxls_attributes::AttributesLayout;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::Device;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::gpu::indirect_buffer::IndirectBuffer1D;
|
||||
use crate::gpu_profiler;
|
||||
use crate::gpu_profiler::ScopeEncoder;
|
||||
use crate::voxel_cache::attributes::CacheAttributes;
|
||||
use crate::voxel_cache::create_multi_buffers_bg_bg_layout;
|
||||
use crate::voxel_cache::eviction::CacheEvictor;
|
||||
use crate::voxel_cache::insertion::CacheInsertionData;
|
||||
use crate::voxel_cache::layout::CacheLayout;
|
||||
use crate::voxel_cache::requests::CacheRequestBuffer;
|
||||
use crate::voxel_cache::requests::CacheRequestHandler;
|
||||
use crate::voxel_cache::structure::CacheStructure;
|
||||
use crate::attributes::CacheAttributes;
|
||||
use crate::create_multi_buffers_bg_bg_layout;
|
||||
use crate::eviction::CacheEvictor;
|
||||
use crate::insertion::CacheInsertionData;
|
||||
use crate::requests::CacheRequestBuffer;
|
||||
use crate::requests::CacheRequestHandler;
|
||||
use crate::structure::CacheStructure;
|
||||
use vxls_gpu::indirect_buffer::IndirectBuffer1D;
|
||||
use vxls_profiler;
|
||||
use vxls_profiler::ScopeEncoder;
|
||||
|
||||
macro_rules! programmatic_common_wgsl {
|
||||
($children_count:ident, $page_count:ident, $cache_layout:ident) => {
|
||||
@@ -54,8 +54,6 @@ macro_rules! include_cache_wgsl {
|
||||
}};
|
||||
}
|
||||
|
||||
pub(super) use include_cache_wgsl;
|
||||
|
||||
pub struct WriteRequestsPass<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
@@ -69,8 +67,7 @@ impl<const N: usize> WriteRequestsPass<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, cache_layout: &CacheLayout) -> Self
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, cache_layout: &AttributesLayout) -> Self {
|
||||
// Binds
|
||||
// - structure
|
||||
// - request buffer
|
||||
@@ -119,9 +116,8 @@ where
|
||||
cache_structure: &CacheStructure<N>,
|
||||
cache_request_handler: &CacheRequestHandler<N>,
|
||||
target_request_buffer: &CacheRequestBuffer,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "WriteRequests");
|
||||
) {
|
||||
vxls_profiler::begin_scope!(encoder, "WriteRequests");
|
||||
|
||||
let indirect_dispatch_buffer = self.indirect_buffer.workgroup_count(
|
||||
device,
|
||||
@@ -160,7 +156,11 @@ where
|
||||
/// Copies new pages into cache using LRU order
|
||||
write_pipeline: ComputePipeline,
|
||||
|
||||
/// Validates internal insertions and compacts their indices
|
||||
validate_internal_pipeline: ComputePipeline,
|
||||
|
||||
/// u32 buffer containing amount of inserted data of current pass
|
||||
#[allow(unused)]
|
||||
inserted_count: wgpu::Buffer,
|
||||
inserted_count_bind_group: wgpu::BindGroup,
|
||||
|
||||
@@ -175,8 +175,7 @@ impl<const N: usize> CacheInsertionPass<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, layout: &AttributesLayout) -> Self {
|
||||
// Binds
|
||||
// - structure
|
||||
// - request buffer
|
||||
@@ -203,7 +202,8 @@ where
|
||||
Some(&CacheStructure::<N>::create_bind_group_layout(device)),
|
||||
// New incoming attributes
|
||||
Some(&CacheInsertionData::<N>::create_bind_group_layout(
|
||||
device, layout,
|
||||
device,
|
||||
Some(layout),
|
||||
)),
|
||||
// To get recyclable pages, and mark pages dirty
|
||||
Some(&CacheEvictor::create_bind_group_layout(device)),
|
||||
@@ -243,8 +243,19 @@ where
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let validate_internal_pipeline =
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("CacheInsertionPass::validate_internal_pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("validate_internal"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
write_pipeline,
|
||||
validate_internal_pipeline,
|
||||
consume_pipeline,
|
||||
inserted_count,
|
||||
inserted_count_bind_group,
|
||||
@@ -252,6 +263,44 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates internal insertions and compacts them into the insertion data's
|
||||
/// `valid_indices` buffer.
|
||||
///
|
||||
/// External roots are validated by the structure table that requested them.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn encode_validation(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
cache_attributes: &CacheAttributes<N>,
|
||||
cache_structure: &CacheStructure<N>,
|
||||
insertion_data: &CacheInsertionData<N>,
|
||||
cache_evictor: &CacheEvictor,
|
||||
) {
|
||||
vxls_profiler::begin_scope!(encoder, "PageInsertionValidation");
|
||||
|
||||
let indirect_write_dispatch = self.indirect_dispatcher.workgroup_count(
|
||||
device,
|
||||
&mut encoder,
|
||||
insertion_data.page_count_buffer(),
|
||||
256,
|
||||
);
|
||||
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("CacheInsertionPass::validation_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
pass.set_bind_group(0, cache_attributes.bind_group(), &[]);
|
||||
pass.set_bind_group(1, cache_structure.bind_group(), &[]);
|
||||
pass.set_bind_group(2, insertion_data.bind_group(), &[]);
|
||||
pass.set_bind_group(3, cache_evictor.bind_group(), &[]);
|
||||
pass.set_bind_group(4, &self.inserted_count_bind_group, &[]);
|
||||
|
||||
pass.set_pipeline(&self.validate_internal_pipeline);
|
||||
pass.dispatch_workgroups_indirect(indirect_write_dispatch, 0);
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn encode(
|
||||
&self,
|
||||
@@ -262,9 +311,8 @@ where
|
||||
insertion_data: &CacheInsertionData<N>,
|
||||
cache_evictor: &CacheEvictor,
|
||||
timestamp: u32,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "PageInsertion");
|
||||
) {
|
||||
vxls_profiler::begin_scope!(encoder, "PageInsertion");
|
||||
|
||||
let indirect_write_dispatch = self.indirect_dispatcher.workgroup_count(
|
||||
device,
|
||||
@@ -309,8 +357,7 @@ impl<const N: usize> CacheInvalidationPass<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, layout: &AttributesLayout) -> Self {
|
||||
// Binds
|
||||
// - structure
|
||||
// - request buffer
|
||||
@@ -358,9 +405,8 @@ where
|
||||
cache_structure: &CacheStructure<N>,
|
||||
cache_evictor: &CacheEvictor,
|
||||
timestamp: u32,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "CacheInvalidation");
|
||||
) {
|
||||
vxls_profiler::begin_scope!(encoder, "CacheInvalidation");
|
||||
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("CacheInvalidationPass::pass"),
|
||||
@@ -390,16 +436,14 @@ impl<const N: usize> WritePointersPass<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, layout: &AttributesLayout) -> Self {
|
||||
let bindings = [
|
||||
// To find where pages are pointing
|
||||
Some(&CacheStructure::<N>::create_bind_group_layout(device)),
|
||||
// To find where the requests came from
|
||||
Some(&CacheRequestBuffer::create_bind_group_layout(device)),
|
||||
// To find where the request's response went
|
||||
Some(&CacheInsertionData::<N>::create_bind_group_layout(
|
||||
device, layout,
|
||||
device,
|
||||
Some(layout),
|
||||
)),
|
||||
];
|
||||
|
||||
@@ -436,11 +480,9 @@ where
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
device: &Device,
|
||||
cache_structure: &CacheStructure<N>,
|
||||
request_buffer: &CacheRequestBuffer,
|
||||
cache_insertion_data: &CacheInsertionData<N>,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "WritePointers");
|
||||
) {
|
||||
vxls_profiler::begin_scope!(encoder, "WritePointers");
|
||||
|
||||
let indirect_buffer = self.indirect_buffer.workgroup_count(
|
||||
device,
|
||||
@@ -456,8 +498,7 @@ where
|
||||
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_bind_group(0, cache_structure.bind_group(), &[]);
|
||||
pass.set_bind_group(1, request_buffer.bind_group(), &[]);
|
||||
pass.set_bind_group(2, cache_insertion_data.bind_group(), &[]);
|
||||
pass.set_bind_group(1, cache_insertion_data.bind_group(), &[]);
|
||||
|
||||
pass.dispatch_workgroups_indirect(indirect_buffer, 0);
|
||||
}
|
||||
@@ -9,21 +9,21 @@ use wgpu::Device;
|
||||
use wgpu::include_wgsl;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::gpu::buffer_compactor::NonZeroBufferCompactor;
|
||||
use crate::gpu::create_multi_buffers_bind_group;
|
||||
use crate::gpu::radix_sort::{self};
|
||||
use crate::gpu_profiler::ScopeEncoder;
|
||||
use crate::gpu_profiler::memory_profiler;
|
||||
use crate::gpu_profiler::{self};
|
||||
use crate::voxel_cache::CacheRessources;
|
||||
use crate::voxel_cache::create_multi_buffers_bg_bg_layout;
|
||||
use crate::voxel_cache::create_multi_buffers_bind_group_layout;
|
||||
use crate::voxel_cache::schema::RequestInformation;
|
||||
use crate::voxel_cache::schema::RequestMeta;
|
||||
use crate::CacheRessources;
|
||||
use crate::create_multi_buffers_bg_bg_layout;
|
||||
use crate::create_multi_buffers_bind_group_layout;
|
||||
use crate::schema::RequestInformation;
|
||||
use crate::schema::RequestMeta;
|
||||
use vxls_gpu::create_multi_buffers_bind_group;
|
||||
use vxls_gpu::indirect_buffer::IndirectBuffer1D;
|
||||
use vxls_gpu::radix_sort::{self};
|
||||
use vxls_gpu::top_k::TopKSelector;
|
||||
use vxls_profiler::ScopeEncoder;
|
||||
use vxls_profiler::memory_profiler;
|
||||
use vxls_profiler::{self};
|
||||
|
||||
/// Records, handles, and produces a list of requested data inside the cache
|
||||
pub struct CacheRequestHandler<const N: usize>
|
||||
{
|
||||
pub struct CacheRequestHandler<const N: usize> {
|
||||
/// Contains a u32 per pointer of the cache, that records an amount of request by the cache user.
|
||||
/// This can then be used to prioritize request based on demand
|
||||
request_counts_pages: wgpu::Buffer,
|
||||
@@ -34,7 +34,16 @@ pub struct CacheRequestHandler<const N: usize>
|
||||
/// Number of requests
|
||||
request_count: wgpu::Buffer,
|
||||
|
||||
compactor: NonZeroBufferCompactor,
|
||||
/// Number of request counts in `request_counts_pages`
|
||||
element_count: u32,
|
||||
|
||||
/// Selects the most requested pages
|
||||
top_k: TopKSelector,
|
||||
|
||||
/// Gathers the selected counts and indices into contiguous sort buffers
|
||||
gather_pass: ComputePipeline,
|
||||
gather_pass_bind_group_layout: BindGroupLayout,
|
||||
gather_indirect_buffer: IndirectBuffer1D,
|
||||
|
||||
// Pass to reset the requests
|
||||
reset_pass_bind_group: BindGroup,
|
||||
@@ -42,13 +51,13 @@ pub struct CacheRequestHandler<const N: usize>
|
||||
reset_pass_dispatch: u32,
|
||||
|
||||
// External bind group
|
||||
#[allow(unused)]
|
||||
bind_group_layout: BindGroupLayout,
|
||||
bind_group: BindGroup,
|
||||
}
|
||||
|
||||
/// Records requests made by the cache
|
||||
pub struct CacheRequestBuffer
|
||||
{
|
||||
pub struct CacheRequestBuffer {
|
||||
pub max_requests: usize,
|
||||
|
||||
/// Buffer containing the amount of requests made by the cache, under max requsets
|
||||
@@ -60,24 +69,30 @@ pub struct CacheRequestBuffer
|
||||
/// Buffer containing the meta information about the requests, a dense array of [`voxel_cache::schema::RequestMeta`]
|
||||
request_meta: wgpu::Buffer,
|
||||
|
||||
#[allow(unused)]
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
bind_group: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheRequestHandler<N>
|
||||
{
|
||||
pub fn new(device: &mut memory_profiler::Device, page_count: usize) -> Self
|
||||
{
|
||||
impl<const N: usize> CacheRequestHandler<N> {
|
||||
pub fn new(device: &mut memory_profiler::Device, page_count: usize, max_selected: u32) -> Self {
|
||||
let element_count = page_count * N * N * N;
|
||||
assert!(
|
||||
element_count <= u32::MAX as usize,
|
||||
"CacheRequestHandler: too many request pages ({element_count})"
|
||||
);
|
||||
let element_count = element_count as u32;
|
||||
|
||||
let request_counts_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheRequestHandler::request_counts_pages"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
contents: bytemuck::cast_slice(&vec![0u32; page_count * N * N * N]),
|
||||
contents: bytemuck::cast_slice(&vec![0u32; element_count as usize]),
|
||||
});
|
||||
|
||||
let sorted_requests = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheRequestHandler::sorted_requests"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
contents: bytemuck::cast_slice(&vec![0u32; page_count * N * N * N]),
|
||||
contents: bytemuck::cast_slice(&vec![0u32; element_count as usize]),
|
||||
});
|
||||
|
||||
let request_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
@@ -88,6 +103,25 @@ impl<const N: usize> CacheRequestHandler<N>
|
||||
contents: bytemuck::bytes_of(&0u32),
|
||||
});
|
||||
|
||||
let top_k = TopKSelector::new(device, max_selected);
|
||||
|
||||
let gather_pass_bind_group_layout = Self::create_gather_bind_group_layout(device);
|
||||
let gather_pass_pipeline_layout =
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("CacheRequestHandler::gather_pass_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&gather_pass_bind_group_layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let gather_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("CacheRequestHandler::gather_pass"),
|
||||
layout: Some(&gather_pass_pipeline_layout),
|
||||
module: &device.create_shader_module(include_wgsl!("./shaders/gather_requests.wgsl")),
|
||||
entry_point: Some("gather_requests"),
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let (reset_pass_bg_layout, reset_pass_bind_group) = create_multi_buffers_bg_bg_layout(
|
||||
device,
|
||||
&[&request_counts_pages],
|
||||
@@ -114,7 +148,7 @@ impl<const N: usize> CacheRequestHandler<N>
|
||||
let bind_group = create_multi_buffers_bind_group(
|
||||
device,
|
||||
&bind_group_layout,
|
||||
&[&request_count, &sorted_requests],
|
||||
&[&request_count, &sorted_requests, &request_counts_pages],
|
||||
Some("CacheRequestHandler::bind_group"),
|
||||
);
|
||||
|
||||
@@ -122,96 +156,163 @@ impl<const N: usize> CacheRequestHandler<N>
|
||||
request_counts_pages,
|
||||
sorted_requests,
|
||||
request_count,
|
||||
compactor: NonZeroBufferCompactor::new(device, page_count * N * N * N),
|
||||
element_count,
|
||||
top_k,
|
||||
gather_pass,
|
||||
gather_pass_bind_group_layout,
|
||||
gather_indirect_buffer: IndirectBuffer1D::new(device),
|
||||
|
||||
reset_pass_bind_group,
|
||||
reset_pass,
|
||||
reset_pass_dispatch: ((page_count * N * N * N) as u32).div_ceil(256),
|
||||
reset_pass_dispatch: element_count.div_ceil(256),
|
||||
|
||||
bind_group_layout,
|
||||
bind_group,
|
||||
}
|
||||
}
|
||||
|
||||
fn create_gather_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout {
|
||||
let entry = |binding: u32, read_only: bool| wgpu::BindGroupLayoutEntry {
|
||||
binding,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
};
|
||||
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("CacheRequestHandler::gather_pass_bind_group_layout"),
|
||||
entries: &[
|
||||
entry(0, true), // requests
|
||||
entry(1, true), // selected_indices
|
||||
entry(2, true), // selected_count
|
||||
entry(3, false), // keys
|
||||
entry(4, false), // values
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
/// Sorts the requests currently held by the request handler in order to process them.
|
||||
///
|
||||
/// Uses both the sorter and the scratch buffer in the ressources
|
||||
///
|
||||
/// The `request_count` buffer will contain the amount of request produced this time.
|
||||
pub fn sort_requests(
|
||||
pub(crate) fn sort_requests(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
ressources: &CacheRessources<N>,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "RequestHandler::sort_requests");
|
||||
k: u32,
|
||||
) {
|
||||
vxls_profiler::begin_scope!(encoder, "RequestHandler::sort_requests");
|
||||
|
||||
// First perform a fast compaction sort
|
||||
// Select the most requested pages.
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "compaction");
|
||||
self.compactor.compact_buffer(
|
||||
vxls_profiler::begin_scope!(encoder, "top_k");
|
||||
self.top_k.select(
|
||||
device,
|
||||
&mut encoder,
|
||||
&self.request_counts_pages,
|
||||
&self.sorted_requests,
|
||||
Some(&ressources.scratch_buffer),
|
||||
self.element_count,
|
||||
k,
|
||||
);
|
||||
}
|
||||
|
||||
self.compactor
|
||||
.copy_count_to_buffer(&mut encoder, &self.request_count);
|
||||
|
||||
// State:
|
||||
// At this point the `sorted_requests` buffer contains the compacted indices of the request counts
|
||||
// and the scratch buffer contains the associated values
|
||||
|
||||
// The indices can now be sorted using `sorted_requests` as values and
|
||||
// `ressources.scratch_buffer` as keys for a sort operation
|
||||
|
||||
// We use the amount of non zero request as the indirect count so that we can sort only the
|
||||
// compacted, non-null requests
|
||||
// Gather the selected counts and indices into contiguous sort buffers.
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "radix");
|
||||
vxls_profiler::begin_scope!(encoder, "gather");
|
||||
|
||||
let gather_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("CacheRequestHandler::gather_bind_group"),
|
||||
layout: &self.gather_pass_bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: self.request_counts_pages.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: self.top_k.selected_indices_buffer().as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: self.top_k.selected_count_buffer().as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: ressources.scratch_buffer.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: self.sorted_requests.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let gather_dispatch = self.gather_indirect_buffer.workgroup_count(
|
||||
device,
|
||||
&mut encoder,
|
||||
self.top_k.selected_count_buffer(),
|
||||
256,
|
||||
);
|
||||
|
||||
let mut compute_pass = encoder.begin_profiled_compute_pass("gather");
|
||||
compute_pass.set_pipeline(&self.gather_pass);
|
||||
compute_pass.set_bind_group(0, &gather_bind_group, &[]);
|
||||
compute_pass.dispatch_workgroups_indirect(gather_dispatch, 0);
|
||||
}
|
||||
|
||||
// Sort the selected requests by descending request count. The scratch
|
||||
// buffer holds the keys (counts) and `sorted_requests` the values
|
||||
// (indices). `selected_count` is the indirect element count.
|
||||
{
|
||||
vxls_profiler::begin_scope!(encoder, "radix");
|
||||
ressources.radix_sorter.sort(
|
||||
device,
|
||||
&ressources.scratch_buffer,
|
||||
&self.sorted_requests,
|
||||
Some(&self.request_count),
|
||||
Some(self.top_k.selected_count_buffer()),
|
||||
None,
|
||||
&mut encoder,
|
||||
radix_sort::RadixSortDirection::Descending,
|
||||
);
|
||||
}
|
||||
|
||||
// Publish the amount of selected requests for downstream passes.
|
||||
encoder.copy_buffer_to_buffer(
|
||||
self.top_k.selected_count_buffer(),
|
||||
0,
|
||||
&self.request_count,
|
||||
0,
|
||||
size_of::<u32>() as u64,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout
|
||||
{
|
||||
pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout {
|
||||
create_multi_buffers_bind_group_layout(
|
||||
device,
|
||||
2,
|
||||
3,
|
||||
Some("CacheRequestHandler::bind_group_layout"),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &BindGroup
|
||||
{
|
||||
pub fn bind_group(&self) -> &BindGroup {
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
pub fn request_count_buffer(&self) -> &wgpu::Buffer
|
||||
{
|
||||
pub fn request_count_buffer(&self) -> &wgpu::Buffer {
|
||||
&self.request_count
|
||||
}
|
||||
|
||||
pub fn request_pages_buffer(&self) -> &wgpu::Buffer
|
||||
{
|
||||
pub fn request_pages_buffer(&self) -> &wgpu::Buffer {
|
||||
&self.request_counts_pages
|
||||
}
|
||||
|
||||
/// Resets the RequestHandlers request buffer for a next cache usage.
|
||||
pub fn reset(&self, encoder: &mut ScopeEncoder<CommandEncoder>)
|
||||
{
|
||||
pub fn reset(&self, encoder: &mut ScopeEncoder<CommandEncoder>) {
|
||||
let mut compute_pass = encoder.begin_profiled_compute_pass("CacheRequestHandler::reset");
|
||||
|
||||
compute_pass.set_pipeline(&self.reset_pass);
|
||||
@@ -220,11 +321,9 @@ impl<const N: usize> CacheRequestHandler<N>
|
||||
}
|
||||
}
|
||||
|
||||
impl CacheRequestBuffer
|
||||
{
|
||||
impl CacheRequestBuffer {
|
||||
/// Creates a request buffer that can contain at most `max_amount` requests
|
||||
pub fn new(device: &Device, max_requests: usize) -> Self
|
||||
{
|
||||
pub fn new(device: &Device, max_requests: usize) -> Self {
|
||||
let request_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheRequestBuffer::request_count"),
|
||||
usage: wgpu::BufferUsages::STORAGE
|
||||
@@ -266,8 +365,7 @@ impl CacheRequestBuffer
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_bind_group_layout(device: &Device) -> BindGroupLayout
|
||||
{
|
||||
pub fn create_bind_group_layout(device: &Device) -> BindGroupLayout {
|
||||
create_multi_buffers_bind_group_layout(
|
||||
device,
|
||||
3,
|
||||
@@ -275,19 +373,19 @@ impl CacheRequestBuffer
|
||||
)
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &BindGroup
|
||||
{
|
||||
pub fn bind_group(&self) -> &BindGroup {
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
pub fn host_download_requests<F: FnMut(&[RequestInformation]) + Send + Sync + 'static>(
|
||||
pub fn host_download_requests<
|
||||
F: FnMut(&[RequestInformation], &[RequestMeta]) + Send + Sync + 'static,
|
||||
>(
|
||||
&self,
|
||||
device: &Device,
|
||||
queue: &wgpu::Queue,
|
||||
callback: F,
|
||||
)
|
||||
{
|
||||
// Once the two required buffer have been mapped, the requestMapState will automatically
|
||||
) {
|
||||
// Once the three required buffers have been mapped, the requestMapState will automatically
|
||||
// fire the callback
|
||||
let request_map_state = Arc::new(Mutex::new(RequestMapState::new(callback)));
|
||||
|
||||
@@ -323,45 +421,65 @@ impl CacheRequestBuffer
|
||||
.set_request_infos(request_infos);
|
||||
},
|
||||
);
|
||||
|
||||
let request_map_state_3 = request_map_state.clone();
|
||||
wgpu::util::DownloadBuffer::read_buffer(
|
||||
device,
|
||||
queue,
|
||||
&self.request_meta.slice(..),
|
||||
move |buffer| {
|
||||
let mapped_buffer = buffer.expect("Could not map request buffer (meta).");
|
||||
let request_metas: Vec<RequestMeta> = bytemuck::pod_collect_to_vec(&mapped_buffer);
|
||||
|
||||
request_map_state_3
|
||||
.lock()
|
||||
.unwrap()
|
||||
.set_request_metas(request_metas);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
struct RequestMapState<F: FnMut(&[RequestInformation]) -> () + Send + Sync + 'static>
|
||||
{
|
||||
struct RequestMapState<F: FnMut(&[RequestInformation], &[RequestMeta]) + Send + Sync + 'static> {
|
||||
request_count: Option<usize>,
|
||||
request_infos: Option<Vec<RequestInformation>>,
|
||||
request_metas: Option<Vec<RequestMeta>>,
|
||||
callback: F,
|
||||
}
|
||||
|
||||
impl<F: FnMut(&[RequestInformation]) -> () + Send + Sync + 'static> RequestMapState<F>
|
||||
{
|
||||
pub fn new(callback: F) -> Self
|
||||
{
|
||||
impl<F: FnMut(&[RequestInformation], &[RequestMeta]) + Send + Sync + 'static> RequestMapState<F> {
|
||||
pub fn new(callback: F) -> Self {
|
||||
Self {
|
||||
request_count: None,
|
||||
request_infos: None,
|
||||
request_metas: None,
|
||||
callback,
|
||||
}
|
||||
}
|
||||
|
||||
fn try_callback(&mut self)
|
||||
{
|
||||
if let (Some(request_count), Some(request_infos)) =
|
||||
(self.request_count, &self.request_infos)
|
||||
fn try_callback(&mut self) {
|
||||
if let (Some(request_count), Some(request_infos), Some(request_metas)) =
|
||||
(self.request_count, &self.request_infos, &self.request_metas)
|
||||
{
|
||||
(self.callback)(&request_infos[0..request_count])
|
||||
(self.callback)(
|
||||
&request_infos[0..request_count],
|
||||
&request_metas[0..request_count],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_request_count(&mut self, request_count: usize)
|
||||
{
|
||||
pub fn set_request_count(&mut self, request_count: usize) {
|
||||
self.request_count = Some(request_count);
|
||||
self.try_callback();
|
||||
}
|
||||
|
||||
pub fn set_request_infos(&mut self, request_infos: Vec<RequestInformation>)
|
||||
{
|
||||
pub fn set_request_infos(&mut self, request_infos: Vec<RequestInformation>) {
|
||||
self.request_infos = Some(request_infos);
|
||||
self.try_callback();
|
||||
}
|
||||
|
||||
pub fn set_request_metas(&mut self, request_metas: Vec<RequestMeta>) {
|
||||
self.request_metas = Some(request_metas);
|
||||
self.try_callback();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
/// Contains definitions of the data layouts for the cache
|
||||
use std::ops::BitOr;
|
||||
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
|
||||
/// CachePointer represents a pointer in the [`VoxelCache`]
|
||||
///
|
||||
/// Pointers are used in the structure pool of the cache and encodes the N-tree itself
|
||||
///
|
||||
/// Three states are possible :
|
||||
///
|
||||
/// - unsubdivisable: This children of the node cannot be subdivided further
|
||||
/// - subdivisable: This children of the node can be subdivided further ...
|
||||
/// - unavailable: ... but is not currently available in the cache
|
||||
/// - available: ... is currently available in the cache and the pointer is valid
|
||||
///
|
||||
///
|
||||
/// The layout is the following
|
||||
///
|
||||
/// - bit 31: subdivisable?
|
||||
/// - bit 30: available?
|
||||
/// - bit 0..29: pointer (only relevant if available is 1)
|
||||
///
|
||||
#[derive(Clone, Copy, Debug, Zeroable, Pod)]
|
||||
#[repr(transparent)]
|
||||
pub struct CachePointer(u32);
|
||||
|
||||
impl CachePointer {
|
||||
/// First option represents subdivisability
|
||||
/// Second option represents availability
|
||||
///
|
||||
/// None -> unsubdivisable
|
||||
/// Some(None) -> subdivisable not available
|
||||
/// Some(Some(ptr)) -> subdivisable, available a pointer ptr
|
||||
pub fn new(value: Option<Option<u32>>) -> Self {
|
||||
CachePointer(match value {
|
||||
Some(available) => match available {
|
||||
Some(pointer) => {
|
||||
assert_eq!(
|
||||
pointer >> 30,
|
||||
0,
|
||||
"Provided pointer is to big and does not fit in CachePointer. Last two bits must be null."
|
||||
);
|
||||
(1 << 31) | (1 << 30) | pointer
|
||||
}
|
||||
None => 1 << 31,
|
||||
},
|
||||
None => 0,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn as_option(&self) -> Option<Option<u32>> {
|
||||
let subdivisable = (self.0 >> 31) != 0;
|
||||
let available = ((self.0 >> 30) & 1) != 0;
|
||||
let pointer = self.0 & 0x3FFFFFFF;
|
||||
|
||||
match (subdivisable, available) {
|
||||
(false, true) => panic!("Invalid cache pointer. (not subdivisable and available)"),
|
||||
(false, _) if pointer != 0 => {
|
||||
panic!("Invalid cache pointer. (non null unsubdivisable pointer)")
|
||||
}
|
||||
(false, _) => None,
|
||||
(true, false) => Some(None),
|
||||
(true, true) => Some(Some(pointer)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u32> for CachePointer {
|
||||
fn from(value: u32) -> Self {
|
||||
CachePointer(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Pages encoding the structure of the trees in the cache.
|
||||
/// Occupancy mask is a mask containing a bit per children, based on whether it can be skipped
|
||||
/// during raytracing. This can help faster tracing, and coalesce skips.
|
||||
#[derive(Debug, Clone, Copy, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct StructurePage<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub occupancy_mask: u64,
|
||||
pub pointers: [CachePointer; N * N * N],
|
||||
}
|
||||
|
||||
// SAFETY: u64, then packed u32s ([`CachePointer`]s), so no padding, all bit patterns are allowed
|
||||
unsafe impl<const N: usize> Pod for StructurePage<N> where [(); N * N * N]: {}
|
||||
|
||||
/// Number of `u32` words in a [`StructureAnchor`].
|
||||
pub const ANCHOR_WORDS: usize = 4;
|
||||
|
||||
/// Sentinel used in [`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;
|
||||
|
||||
/// Opaque, table-defined identity of a structure's *content*.
|
||||
///
|
||||
/// The cache and the request queue never interpret these words. A table decides
|
||||
/// what an anchor means (for example a world position plus a version) and is
|
||||
/// responsible for never exposing two live slots with the same anchor. The
|
||||
/// anchor travels on the wire so producers stay stateless and so stale
|
||||
/// insertions can be rejected against the current table state.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct StructureAnchor {
|
||||
pub words: [u32; ANCHOR_WORDS],
|
||||
}
|
||||
|
||||
impl StructureAnchor {
|
||||
/// Convenience anchor used by tests and by tables that do not need a
|
||||
/// distinguishable identity at startup.
|
||||
#[allow(dead_code)]
|
||||
pub const ZERO: Self = Self {
|
||||
words: [0; ANCHOR_WORDS],
|
||||
};
|
||||
|
||||
/// Table-defined helper for world-position anchors: `(x, y, z, version)`.
|
||||
pub fn from_world(x: i32, y: i32, z: i32, version: u32) -> Self {
|
||||
Self {
|
||||
words: [x as u32, y as u32, z as u32, version],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn world(self) -> (i32, i32, i32, u32) {
|
||||
(
|
||||
self.words[0] as i32,
|
||||
self.words[1] as i32,
|
||||
self.words[2] as i32,
|
||||
self.words[3],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A cache might hold data owned by multiple different producers. To discriminate where to route the
|
||||
/// request, a node is always tagged by a [`ProducerId`].
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)]
|
||||
#[repr(transparent)]
|
||||
pub struct ProducerId(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)]
|
||||
#[repr(transparent)]
|
||||
pub struct StructureLocator(pub u32);
|
||||
|
||||
/// Data stored alongside cache structure so that application can locate a
|
||||
/// particular request
|
||||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct LocationPage {
|
||||
/// Identifier for locating this particular node within the structure
|
||||
pub node_id: StructureLocator,
|
||||
|
||||
/// Identifier of the producer that owns this node
|
||||
pub producer_id: ProducerId,
|
||||
|
||||
/// Opaque content identity inherited from the root request.
|
||||
pub anchor: StructureAnchor,
|
||||
}
|
||||
|
||||
/// Page storing the depth of the current node related to its root.
|
||||
/// - 0xFFFFFFFF: Page unused
|
||||
/// - 0..0xFFFFFFFF(excl): Depth
|
||||
///
|
||||
/// An external insertion gets the 0 depth.
|
||||
/// Internal insertions get the parent's depth plus one.
|
||||
///
|
||||
/// As such, when inserting pages in the cache, we first sort the lru pages by
|
||||
/// depth, deepest first, then apply a stable radix sort by timestamp. The final
|
||||
/// order is least-recently-used first, with deepest pages first among equal
|
||||
/// timestamps. Reusing deepest pages first means that a page's resident children
|
||||
/// are deeper, so they appear earlier in the list and are reused first (provided
|
||||
/// their timestamp is equal or older) instead of being orphaned when their
|
||||
/// parent is recycled.
|
||||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct DepthPage(pub u32);
|
||||
|
||||
impl DepthPage {
|
||||
pub const PAGE_UNUSED: Self = DepthPage(u32::MAX);
|
||||
}
|
||||
|
||||
/// When the cache requests some information, it produces this structure,
|
||||
/// which contains the node on which a subdivision is requested, as well which particular
|
||||
/// children is needed
|
||||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct RequestInformation {
|
||||
/// Identifier for locating this particular node within the structure
|
||||
pub node_id: StructureLocator,
|
||||
|
||||
/// The index of the children on which the request was issued
|
||||
pub children_index: u32,
|
||||
|
||||
/// Identifier of the producer that owns the requesting node
|
||||
pub producer_id: ProducerId,
|
||||
|
||||
/// The amount of times this request was emitted this frame. Higher means more urgent.
|
||||
pub demand: u32,
|
||||
|
||||
/// Opaque content identity of the structure this request belongs to.
|
||||
pub anchor: StructureAnchor,
|
||||
}
|
||||
|
||||
/// Metainformation kept along each request, to know which node made the demand
|
||||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct RequestMeta {
|
||||
/// The page on which the request was issued, with the special value 0xFFFFFFFF if the request
|
||||
/// is external
|
||||
pub page_index: u32,
|
||||
|
||||
/// The children on which the request was issued
|
||||
pub children_index: u32,
|
||||
|
||||
/// 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
|
||||
/// request/insertion that has no cache parent (an external root requested by a structure table).
|
||||
pub const NO_PARENT_PAGE: u32 = u32::MAX;
|
||||
|
||||
/// Kind of parent an insertion is attached to.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Zeroable, Pod)]
|
||||
#[repr(transparent)]
|
||||
pub struct InsertionParentKind(u32);
|
||||
|
||||
impl InsertionParentKind {
|
||||
/// The new page is a child of a resident cache page.
|
||||
pub const INTERNAL: Self = Self(0);
|
||||
|
||||
/// The new page is the root of a structure owned by a structure table.
|
||||
pub const EXTERNAL: Self = Self(1);
|
||||
|
||||
pub fn raw(self) -> u32 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Identity and attachment point of the page being inserted.
|
||||
///
|
||||
/// This makes an insertion batch self-describing: the GPU can validate that the parent is still
|
||||
/// the node the request was issued on, and link the new page without reading the request buffer.
|
||||
#[derive(Clone, Copy, Debug, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct InsertionParent {
|
||||
/// [`InsertionParentKind`].
|
||||
pub kind: u32,
|
||||
|
||||
/// Cache page of the parent. [`NO_PARENT_PAGE`] for external roots.
|
||||
pub page_index: u32,
|
||||
|
||||
/// Child slot inside the parent. `0` for external roots.
|
||||
pub children_index: u32,
|
||||
|
||||
/// Depth of the parent. [`NO_PARENT_PAGE`] for external roots.
|
||||
pub depth: u32,
|
||||
|
||||
/// Locator of the parent inside the structure. `StructureLocator(0)` for external roots.
|
||||
pub node_id: StructureLocator,
|
||||
|
||||
/// Producer that owns the parent.
|
||||
pub producer_id: ProducerId,
|
||||
|
||||
/// Opaque content identity of the structure the parent belongs to.
|
||||
pub anchor: StructureAnchor,
|
||||
|
||||
/// Table slot of an external root; [`NO_TABLE_SLOT`] for internal
|
||||
/// insertions.
|
||||
pub table_slot: u32,
|
||||
}
|
||||
|
||||
impl InsertionParent {
|
||||
/// Parent information for a child of a resident cache page.
|
||||
pub fn internal(
|
||||
meta: &RequestMeta,
|
||||
node_id: StructureLocator,
|
||||
producer_id: ProducerId,
|
||||
anchor: StructureAnchor,
|
||||
) -> Self {
|
||||
Self {
|
||||
kind: InsertionParentKind::INTERNAL.raw(),
|
||||
page_index: meta.page_index,
|
||||
children_index: meta.children_index,
|
||||
depth: meta.depth,
|
||||
node_id,
|
||||
producer_id,
|
||||
anchor,
|
||||
table_slot: NO_TABLE_SLOT,
|
||||
}
|
||||
}
|
||||
|
||||
/// Parent information for the root of an external structure.
|
||||
pub fn external(producer_id: ProducerId, anchor: StructureAnchor, table_slot: u32) -> Self {
|
||||
Self {
|
||||
kind: InsertionParentKind::EXTERNAL.raw(),
|
||||
page_index: NO_PARENT_PAGE,
|
||||
children_index: 0,
|
||||
depth: NO_PARENT_PAGE,
|
||||
node_id: StructureLocator(0),
|
||||
producer_id,
|
||||
anchor,
|
||||
table_slot,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_external(&self) -> bool {
|
||||
self.kind == InsertionParentKind::EXTERNAL.raw()
|
||||
}
|
||||
|
||||
pub fn is_internal(&self) -> bool {
|
||||
self.kind == InsertionParentKind::INTERNAL.raw()
|
||||
}
|
||||
}
|
||||
|
||||
/// Structure information about the children of a node.
|
||||
/// Used when inserting data in the cache, to setup structure pointers
|
||||
///
|
||||
/// A specific child of a node being inserted can be in four state by
|
||||
///
|
||||
/// Whether it can be subdivided further or not
|
||||
/// Whether it is considered occupied or not
|
||||
/// 31st bit : subdivisable?
|
||||
/// 30th bit : occupied?
|
||||
#[derive(Clone, Copy, Debug, Zeroable, Pod)]
|
||||
#[repr(transparent)]
|
||||
pub struct ChildInformation(u32);
|
||||
|
||||
impl ChildInformation {
|
||||
pub const NONE: Self = Self(0);
|
||||
pub const SUBDIVISABLE: Self = Self(1 << 31);
|
||||
pub const OCCUPIED: Self = Self(1 << 30);
|
||||
|
||||
pub fn new(subdivisable: bool, occupied: bool) -> Self {
|
||||
let mut n = Self::NONE;
|
||||
if subdivisable {
|
||||
n = n | Self::SUBDIVISABLE;
|
||||
}
|
||||
|
||||
if occupied {
|
||||
n = n | Self::OCCUPIED;
|
||||
}
|
||||
|
||||
n
|
||||
}
|
||||
}
|
||||
|
||||
impl BitOr for ChildInformation {
|
||||
type Output = Self;
|
||||
|
||||
fn bitor(self, rhs: Self) -> Self::Output {
|
||||
Self(self.0 | rhs.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Information given for an page insertion operation
|
||||
#[derive(Debug, Clone, Copy, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct InsertionInformation<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
/// Information to setup structure pointers
|
||||
pub children: [ChildInformation; N * N * N],
|
||||
}
|
||||
|
||||
// SAFETY: Packed array of u32, no padding, all bit patterns allowed
|
||||
unsafe impl<const N: usize> Pod for InsertionInformation<N> where [(); N * N * N]: {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn wire_layout_sizes_are_stable() {
|
||||
assert_eq!(size_of::<StructureAnchor>(), 16);
|
||||
assert_eq!(size_of::<RequestInformation>(), 32);
|
||||
assert_eq!(size_of::<LocationPage>(), 24);
|
||||
assert_eq!(size_of::<InsertionParent>(), 44);
|
||||
assert_eq!(size_of::<RequestMeta>(), 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anchor_world_round_trips_negative_coordinates() {
|
||||
let anchor = StructureAnchor::from_world(-17, 42, -3, 7);
|
||||
assert_eq!(anchor.world(), (-17, 42, -3, 7));
|
||||
}
|
||||
}
|
||||
+47
-4
@@ -5,18 +5,60 @@ struct CacheIndex
|
||||
page_index: u32,
|
||||
children_index: u32,
|
||||
}
|
||||
|
||||
const ANCHOR_WORDS: u32 = 4u;
|
||||
|
||||
struct StructureAnchor
|
||||
{
|
||||
words: array<u32, 4>
|
||||
}
|
||||
|
||||
fn anchor_eq(a: StructureAnchor, b: StructureAnchor) -> bool
|
||||
{
|
||||
for(var i = 0u; i < ANCHOR_WORDS; i++)
|
||||
{
|
||||
if(a.words[i] != b.words[i])
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
struct RequestInformation
|
||||
{
|
||||
structure_id: u32,
|
||||
node_id: u32,
|
||||
children_index: u32
|
||||
children_index: u32,
|
||||
producer_id: u32,
|
||||
demand: u32,
|
||||
anchor: StructureAnchor
|
||||
}
|
||||
|
||||
struct RequestMeta
|
||||
{
|
||||
page_index: u32,
|
||||
children_index: u32,
|
||||
depth: u32
|
||||
depth: u32,
|
||||
table_slot: u32
|
||||
}
|
||||
|
||||
// No cache parent (external root insertion).
|
||||
const NO_PARENT_PAGE: u32 = 0xFFFFFFFFu;
|
||||
const INSERTION_PARENT_INTERNAL: u32 = 0u;
|
||||
const INSERTION_PARENT_EXTERNAL: u32 = 1u;
|
||||
// No structure-table slot (internal request/insertion).
|
||||
const NO_TABLE_SLOT: u32 = 0xFFFFFFFFu;
|
||||
|
||||
struct InsertionParent
|
||||
{
|
||||
kind: u32,
|
||||
page_index: u32,
|
||||
children_index: u32,
|
||||
depth: u32,
|
||||
node_id: u32,
|
||||
producer_id: u32,
|
||||
anchor: StructureAnchor,
|
||||
table_slot: u32
|
||||
}
|
||||
|
||||
struct AttributeArray
|
||||
@@ -26,8 +68,9 @@ struct AttributeArray
|
||||
|
||||
struct LocationPage
|
||||
{
|
||||
structure_id: u32,
|
||||
node_id: u32,
|
||||
producer_id: u32,
|
||||
anchor: StructureAnchor
|
||||
}
|
||||
|
||||
fn child_information_occupied(info: u32) -> bool
|
||||
+8
-2
@@ -11,7 +11,8 @@
|
||||
/// Group 2: Scratch buffer
|
||||
@group(2) @binding(0) var<storage, read_write> scratch_buffer: array<u32>;
|
||||
|
||||
/// Resets the lru list
|
||||
/// Resets the lru list to identity order before the depth sort, and clears the
|
||||
/// number of pages consumed by previous insertions.
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn reset_lru_list(@builtin(global_invocation_id) global_invocation_id: vec3<u32>)
|
||||
@@ -28,7 +29,12 @@ fn reset_lru_list(@builtin(global_invocation_id) global_invocation_id: vec3<u32>
|
||||
consumed_count = 0;
|
||||
}
|
||||
|
||||
/// Indirect copy, in between the depth sort and the timestamp sort
|
||||
/// Rearranges timestamps into depth order, in between the descending depth sort
|
||||
/// and the stable timestamp sort.
|
||||
///
|
||||
/// `lru_list` currently holds page indices sorted deepest first. Writing each
|
||||
/// page's timestamp to the same position gives the next (stable) radix sort an
|
||||
/// input where equal timestamps preserve the deepest-first depth order.
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn indirect_copy(@builtin(global_invocation_id) global_invocation_id: vec3<u32>)
|
||||
@@ -0,0 +1,73 @@
|
||||
// Group 0: Table pointers
|
||||
@group(0) @binding(0) var<storage, read_write> fixed_table_pointers: array<u32>; // Request count
|
||||
|
||||
// Group 1: Cache insertion data
|
||||
@group(1) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
|
||||
@group(1) @binding(1) var<storage, read_write> insertion_data_information: array<u32>; // UNUSED
|
||||
@group(1) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
|
||||
@group(1) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
|
||||
@group(1) @binding(4) var<storage, read_write> insertion_data_parents: array<InsertionParent>;
|
||||
@group(1) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
|
||||
@group(1) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
|
||||
|
||||
// Group 2: Slot metadata
|
||||
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
|
||||
|
||||
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
|
||||
|
||||
fn slot_matches(parent: InsertionParent) -> bool
|
||||
{
|
||||
let slot = parent.table_slot;
|
||||
if(slot == NO_TABLE_SLOT || slot >= arrayLength(&fixed_table_anchors))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return anchor_eq(parent.anchor, fixed_table_anchors[slot]);
|
||||
}
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn insertion(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let index = gid.x;
|
||||
let entry_count = min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents));
|
||||
if(index >= entry_count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let parent = insertion_data_parents[index];
|
||||
if(parent.kind != INSERTION_PARENT_EXTERNAL)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let destination = insertion_data_destination_indices[index];
|
||||
if(destination == DESTINATION_NONE)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Re-check identity and pointer state after allocation. A slot move between
|
||||
// validation and insertion must not link the wrong tree.
|
||||
if(!slot_matches(parent))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let slot = parent.table_slot;
|
||||
if(slot >= arrayLength(&fixed_table_pointers))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Re-check that the slot is still waiting for this root.
|
||||
let pointer = fixed_table_pointers[slot];
|
||||
if(!child_pointer_subdivided(pointer) || child_pointer_available(pointer))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
fixed_table_pointers[slot] = child_pointer_make_available(destination);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Group 0: Table pointers
|
||||
@group(0) @binding(0) var<storage, read_write> fixed_table_pointers: array<u32>;
|
||||
|
||||
// Group 1: Cache insertion data
|
||||
@group(1) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
|
||||
@group(1) @binding(1) var<storage, read_write> insertion_data_information: array<u32>; // UNUSED
|
||||
@group(1) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
|
||||
@group(1) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
|
||||
@group(1) @binding(4) var<storage, read_write> insertion_data_parents: array<InsertionParent>;
|
||||
@group(1) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
|
||||
@group(1) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
|
||||
|
||||
// Group 2: Slot metadata
|
||||
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
|
||||
|
||||
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
|
||||
|
||||
/// 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;
|
||||
if(slot == NO_TABLE_SLOT || slot >= arrayLength(&fixed_table_anchors))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return anchor_eq(parent.anchor, fixed_table_anchors[slot]);
|
||||
}
|
||||
|
||||
/// Validates external root insertions against the structure table.
|
||||
///
|
||||
/// A root is still wanted while its table slot is subdivisible but not yet
|
||||
/// available. Slots that were already satisfied (or whose structure was
|
||||
/// invalidated before the request was dispatched) are dropped here, before the
|
||||
/// cache allocates any page for them.
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn validate_external(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let index = gid.x;
|
||||
let entry_count = min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents));
|
||||
if(index >= entry_count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let parent = insertion_data_parents[index];
|
||||
|
||||
// Reset every destination; only validated entries that are allocated get a
|
||||
// page written back by the cache insertion pass.
|
||||
insertion_data_destination_indices[index] = DESTINATION_NONE;
|
||||
|
||||
if(parent.kind != INSERTION_PARENT_EXTERNAL)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if(!slot_matches(parent))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let slot = parent.table_slot;
|
||||
if(slot >= arrayLength(&fixed_table_pointers))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let pointer = fixed_table_pointers[slot];
|
||||
if(!child_pointer_subdivided(pointer) || child_pointer_available(pointer))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let valid_slot = atomicAdd(&insertion_data_valid_count, 1u);
|
||||
insertion_data_valid_indices[valid_slot] = index;
|
||||
}
|
||||
+20
-2
@@ -1,12 +1,18 @@
|
||||
/// Group 0: Cache request handler
|
||||
@group(0) @binding(0) var<storage, read_write> request_handler_count: u32; // Request count
|
||||
@group(0) @binding(1) var<storage, read_write> request_handler_requests: array<u32>;
|
||||
@group(0) @binding(2) var<storage, read_write> request_handler_counts: array<u32>;
|
||||
|
||||
/// Group 1: Request buffer
|
||||
@group(1) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
|
||||
@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 assignment)
|
||||
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
|
||||
|
||||
var<immediate> table_producer_id: u32;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
@@ -18,16 +24,28 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
return;
|
||||
}
|
||||
|
||||
// The request handler emits a slot index; resolve its current assignment so
|
||||
// the request carries stable identity plus the current placement.
|
||||
let slot = request_handler_requests[index];
|
||||
if(slot >= arrayLength(&fixed_table_anchors))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var request_info: RequestInformation;
|
||||
request_info.structure_id = request_handler_requests[index];
|
||||
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];
|
||||
|
||||
var request_meta: RequestMeta;
|
||||
request_meta.page_index = 0;
|
||||
// External requests have no parent page.
|
||||
request_meta.page_index = 0xFFFFFFFF;
|
||||
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;
|
||||
@@ -0,0 +1,25 @@
|
||||
// Gathers the selected (count, index) pairs into contiguous buffers so they can
|
||||
// be sorted by the radix sorter.
|
||||
//
|
||||
// `keys` receives the request counts and `values` receives the request indices.
|
||||
|
||||
@group(0) @binding(0) var<storage, read> requests: array<u32>;
|
||||
@group(0) @binding(1) var<storage, read> selected_indices: array<u32>;
|
||||
@group(0) @binding(2) var<storage, read> selected_count: u32;
|
||||
@group(0) @binding(3) var<storage, read_write> keys: array<u32>;
|
||||
@group(0) @binding(4) var<storage, read_write> values: array<u32>;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn gather_requests(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let i = gid.x;
|
||||
if (i >= selected_count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let index = selected_indices[i];
|
||||
keys[i] = requests[index];
|
||||
values[i] = index;
|
||||
}
|
||||
+103
-30
@@ -12,7 +12,10 @@
|
||||
@group(2) @binding(1) var<storage, read_write> insertion_data_information: array<InsertionInformation>;
|
||||
@group(2) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
|
||||
@group(2) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
|
||||
@group(2) @binding(4) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
|
||||
@group(2) @binding(4) var<storage, read_write> insertion_data_parents: array<InsertionParent>;
|
||||
@group(2) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
|
||||
@group(2) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
|
||||
@group(2) @binding(7) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
|
||||
|
||||
// Group 3: Cache evictor
|
||||
@group(3) @binding(0) var<storage, read_write> cache_evictor_timestamps: array<u32>;
|
||||
@@ -24,13 +27,79 @@
|
||||
|
||||
var<immediate> new_timestamp: u32;
|
||||
|
||||
// Computes amount of available LRU pages
|
||||
fn available_amount() -> u32
|
||||
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
|
||||
|
||||
fn insertion_entry_count() -> u32
|
||||
{
|
||||
return min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents));
|
||||
}
|
||||
|
||||
/// Checks that the parent page still holds the node the request was issued on,
|
||||
/// and that the requested child slot is still waiting for a page.
|
||||
fn internal_parent_is_valid(parent: InsertionParent) -> bool
|
||||
{
|
||||
if(parent.page_index >= PAGE_COUNT)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let location = structure_location_pages[parent.page_index];
|
||||
if(location.node_id != parent.node_id ||
|
||||
location.producer_id != parent.producer_id ||
|
||||
!anchor_eq(location.anchor, parent.anchor))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if(structure_depth_pages[parent.page_index] != parent.depth)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let pointer = structure_pointer_pages[parent.page_index].pointers[parent.children_index];
|
||||
return child_pointer_subdivided(pointer) && !child_pointer_available(pointer);
|
||||
}
|
||||
|
||||
/// Validates a batch of internal insertions and compacts the valid ones into
|
||||
/// `insertion_data_valid_indices`.
|
||||
///
|
||||
/// This must run before page allocation so that stale insertions never consume
|
||||
/// an evicted page. External roots are validated by the structure table that
|
||||
/// requested them (see `fixed_table/validate_insertion.wgsl`).
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn validate_internal(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let index = gid.x;
|
||||
if(index >= insertion_entry_count())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let parent = insertion_data_parents[index];
|
||||
|
||||
// Reset the destination of every entry. Only entries compacted into
|
||||
// `valid_indices` and actually allocated by the insertion pass get a page;
|
||||
// this keeps invalid/stale insertions from reusing a previous batch's
|
||||
// destination if the host did not pre-fill the buffer.
|
||||
insertion_data_destination_indices[index] = DESTINATION_NONE;
|
||||
|
||||
if(parent.kind != INSERTION_PARENT_INTERNAL)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if(internal_parent_is_valid(parent))
|
||||
{
|
||||
let slot = atomicAdd(&insertion_data_valid_count, 1u);
|
||||
insertion_data_valid_indices[slot] = index;
|
||||
}
|
||||
}
|
||||
|
||||
fn available_amount(valid_count: u32) -> u32
|
||||
{
|
||||
let lru_remaining = arrayLength(&cache_evictor_timestamps) - cache_evictor_consumed_count;
|
||||
let available_amount = min(lru_remaining, insertion_data_page_count_buffer);
|
||||
|
||||
return available_amount;
|
||||
return min(lru_remaining, valid_count);
|
||||
}
|
||||
|
||||
@compute
|
||||
@@ -38,7 +107,7 @@ fn available_amount() -> u32
|
||||
fn consume(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
// Report consumed amount of LRU pages to cache evictor
|
||||
// So that subsequent insertions can can continue to use new pages
|
||||
// So that subsequent insertions can can continue to use new pages
|
||||
cache_evictor_consumed_count += atomicLoad(&pass_inserted_count);
|
||||
atomicStore(&pass_inserted_count, 0);
|
||||
}
|
||||
@@ -47,57 +116,61 @@ fn consume(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn insertion(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let index = gid.x;
|
||||
//let insertion_count = min(array_length(&insertion_data_information), insertion_data_page_count_buffer);
|
||||
let insertion_count = available_amount();
|
||||
|
||||
if(index >= insertion_data_page_count_buffer)
|
||||
let slot = gid.x;
|
||||
let entry_count = insertion_entry_count();
|
||||
if(slot >= entry_count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if(index >= insertion_count)
|
||||
{
|
||||
// Report that page was not written
|
||||
insertion_data_destination_indices[index] = 0xFFFFFFFF;
|
||||
return;
|
||||
let valid_count = atomicLoad(&insertion_data_valid_count);
|
||||
if(slot >= valid_count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Compacted entry index in the host-provided arrays.
|
||||
let index = insertion_data_valid_indices[slot];
|
||||
let insertion_count = available_amount(valid_count);
|
||||
|
||||
if(slot >= insertion_count)
|
||||
{
|
||||
// Report that page was not written. The host also pre-fills the whole
|
||||
// destination array with DESTINATION_NONE, so this is defensive.
|
||||
insertion_data_destination_indices[index] = DESTINATION_NONE;
|
||||
return;
|
||||
}
|
||||
|
||||
// Get a page to evict
|
||||
let page_index = cache_evictor_lru_pages[index + cache_evictor_consumed_count];
|
||||
let page_index = cache_evictor_lru_pages[slot + cache_evictor_consumed_count];
|
||||
let page_timestamp = cache_evictor_timestamps[page_index];
|
||||
|
||||
if(page_timestamp >= new_timestamp - 1)
|
||||
{
|
||||
// Do not insert page
|
||||
insertion_data_destination_indices[index] = 0xFFFFFFFF;
|
||||
return;
|
||||
insertion_data_destination_indices[index] = DESTINATION_NONE;
|
||||
return;
|
||||
}
|
||||
|
||||
atomicAdd(&pass_inserted_count, 1);
|
||||
insertion_data_destination_indices[index] = page_index;
|
||||
|
||||
// Copy new location
|
||||
structure_location_pages[page_index] = insertion_data_location_pages[index];
|
||||
structure_location_pages[page_index] = insertion_data_location_pages[index];
|
||||
|
||||
// Copy new pointers
|
||||
let new_pointers = insertion_info_to_pointer_page(insertion_data_information[index]);
|
||||
structure_pointer_pages[page_index] = new_pointers;
|
||||
structure_pointer_pages[page_index] = new_pointers;
|
||||
|
||||
// Mark page as dirty for invalidation
|
||||
cache_evictor_timestamps[page_index] = new_timestamp;
|
||||
|
||||
// Set default depth
|
||||
structure_depth_pages[page_index] = 0;
|
||||
// Set default depth. `write_pointers` refines it for internal insertions.
|
||||
structure_depth_pages[page_index] = 0;
|
||||
|
||||
// Copy attributes
|
||||
for(var attribute_index = u32(0); attribute_index < ATTRIBUTE_COUNT; attribute_index ++)
|
||||
{
|
||||
if(!ATTRIBUTE_COPY[attribute_index])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var page_stride = CHILDREN_COUNT * ATTRIBUTE_WORD_COUNTS[attribute_index];
|
||||
var dest_offset = page_stride * page_index;
|
||||
var src_offset = page_stride * index;
|
||||
@@ -116,7 +189,7 @@ fn insertion_info_to_pointer_page(info: InsertionInformation) -> PointerPage
|
||||
|
||||
var occupancy_low = u32(0);
|
||||
var occupancy_high = u32(0);
|
||||
for(var i = u32(0); i < CHILDREN_COUNT; i++)
|
||||
for(var i = u32(0); i < CHILDREN_COUNT; i++)
|
||||
{
|
||||
let insert_info = info.children[i];
|
||||
|
||||
+3
-2
@@ -19,9 +19,10 @@ fn invalidation(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
|
||||
for(var i = u32(0); i < CHILDREN_COUNT; i++)
|
||||
{
|
||||
if(pointer_invalid(structure_pointer_pages[index].pointers[i]))
|
||||
let pointer = structure_pointer_pages[index].pointers[i];
|
||||
if(child_pointer_available(pointer) && cache_evictor_timestamps[child_pointer_pointer(pointer)] == new_timestamp)
|
||||
{
|
||||
pointer_invalidate(index, i);
|
||||
structure_pointer_pages[index].pointers[i] = child_pointer_empty(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/// Group 0: Cache structure
|
||||
@group(0) @binding(0) var<storage, read_write> structure_pointer_pages: array<PointerPage>;
|
||||
@group(0) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
|
||||
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
|
||||
|
||||
// Group 1: Cache insertion data
|
||||
@group(1) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
|
||||
@group(1) @binding(1) var<storage, read_write> insertion_data_information: array<InsertionInformation>;
|
||||
@group(1) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
|
||||
@group(1) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
|
||||
@group(1) @binding(4) var<storage, read_write> insertion_data_parents: array<InsertionParent>;
|
||||
@group(1) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
|
||||
@group(1) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
|
||||
@group(1) @binding(7) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
|
||||
|
||||
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
|
||||
|
||||
/// Links inserted pages into their parent, using only the insertion batch's own
|
||||
/// parent description. No request buffer is involved, so a batch may be
|
||||
/// produced on a different frame than the one that emitted the requests.
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn write_pointers(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let index = gid.x;
|
||||
let entry_count = min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents));
|
||||
if(index >= entry_count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let parent = insertion_data_parents[index];
|
||||
if(parent.kind != INSERTION_PARENT_INTERNAL)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let page_index = insertion_data_destination_indices[index];
|
||||
if(page_index == DESTINATION_NONE)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// The parent page may have been recycled while this insertion batch was in
|
||||
// flight. Only link if it still describes the same node, and never link a
|
||||
// page to itself.
|
||||
if(parent.page_index >= PAGE_COUNT || parent.page_index == page_index)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let location = structure_location_pages[parent.page_index];
|
||||
if(location.node_id != parent.node_id ||
|
||||
location.producer_id != parent.producer_id ||
|
||||
!anchor_eq(location.anchor, parent.anchor))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
structure_pointer_pages[parent.page_index].pointers[parent.children_index]
|
||||
= child_pointer_make_available(page_index);
|
||||
structure_depth_pages[page_index] = parent.depth + 1;
|
||||
}
|
||||
+5
-1
@@ -8,6 +8,7 @@
|
||||
/// Group 1: Cache request handler
|
||||
@group(1) @binding(0) var<storage, read_write> request_handler_count: u32; // Request count
|
||||
@group(1) @binding(1) var<storage, read_write> request_handler_requests: array<u32>;
|
||||
@group(1) @binding(2) var<storage, read_write> request_handler_counts: array<u32>;
|
||||
|
||||
/// Group 3: Request buffer
|
||||
@group(2) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
|
||||
@@ -32,15 +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;
|
||||
|
||||
// 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;
|
||||
@@ -3,11 +3,11 @@ use wgpu::BindGroupLayout;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
|
||||
use crate::gpu::create_multi_buffers_bind_group;
|
||||
use crate::gpu::create_multi_buffers_bind_group_layout;
|
||||
use crate::gpu_profiler::memory_profiler;
|
||||
use crate::voxel_cache::schema::DepthPage;
|
||||
use crate::voxel_cache::schema::StructurePage;
|
||||
use crate::schema::DepthPage;
|
||||
use crate::schema::StructurePage;
|
||||
use vxls_gpu::create_multi_buffers_bind_group;
|
||||
use vxls_gpu::create_multi_buffers_bind_group_layout;
|
||||
use vxls_profiler::memory_profiler;
|
||||
|
||||
/// Contains the instanciated buffers relevant to the structure of the trees
|
||||
pub struct CacheStructure<const N: usize>
|
||||
@@ -15,6 +15,7 @@ where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pointer_pages: Buffer,
|
||||
#[allow(unused)]
|
||||
location_pages: Buffer,
|
||||
depth_pages: Buffer,
|
||||
|
||||
@@ -30,8 +31,7 @@ where
|
||||
pub const LOCATION_PAGES_BINDING: u32 = 1;
|
||||
pub const DEPTH_PAGES_BINDING: u32 = 2;
|
||||
|
||||
pub fn new(device: &mut memory_profiler::Device, page_count: usize) -> Self
|
||||
{
|
||||
pub fn new(device: &mut memory_profiler::Device, page_count: usize) -> Self {
|
||||
let pointer_pages = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheStructure::pointer_pages"),
|
||||
size: (size_of::<StructurePage<N>>() * page_count) as u64,
|
||||
@@ -46,8 +46,9 @@ where
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
// Depth pages need to be initialized to unused, this prioritizes them in the
|
||||
// depth sort used in the eviction pass
|
||||
// Unused pages get the maximum depth so they lead the deepest-first
|
||||
// depth sort used by the eviction pass. Combined with their initial
|
||||
// timestamp of 0, this makes them the first pages reused.
|
||||
let depth_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheStructure::depth_pages"),
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
@@ -72,28 +73,23 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout
|
||||
{
|
||||
pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout {
|
||||
create_multi_buffers_bind_group_layout(device, 3, Some("CacheStructure::bind_group_layout"))
|
||||
}
|
||||
|
||||
pub fn bind_group_layout(&self) -> &BindGroupLayout
|
||||
{
|
||||
pub fn bind_group_layout(&self) -> &BindGroupLayout {
|
||||
&self.bind_group_layout
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &BindGroup
|
||||
{
|
||||
pub fn bind_group(&self) -> &BindGroup {
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
pub fn pointer_pages(&self) -> &Buffer
|
||||
{
|
||||
pub fn pointer_pages(&self) -> &Buffer {
|
||||
&self.pointer_pages
|
||||
}
|
||||
|
||||
pub fn depth_pages(&self) -> &Buffer
|
||||
{
|
||||
pub fn depth_pages(&self) -> &Buffer {
|
||||
&self.depth_pages
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,34 @@
|
||||
[package]
|
||||
name = "vxls"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
vxls-attributes = { path = "../vxls-attributes" }
|
||||
vxls-bvh = { path = "../vxls-bvh" }
|
||||
vxls-gpu = { path = "../vxls-gpu" }
|
||||
vxls-production = { path = "../vxls-production" }
|
||||
vxls-profiler = { path = "../vxls-profiler" }
|
||||
vxls-terrain = { path = "../vxls-terrain" }
|
||||
vxls-voxel-cache = { path = "../vxls-voxel-cache" }
|
||||
|
||||
bytemuck.workspace = true
|
||||
crevice.workspace = true
|
||||
egui.workspace = true
|
||||
egui-wgpu.workspace = true
|
||||
egui-winit.workspace = true
|
||||
egui_ltreeview.workspace = true
|
||||
egui_plot.workspace = true
|
||||
env_logger.workspace = true
|
||||
fastapprox.workspace = true
|
||||
glam.workspace = true
|
||||
image.workspace = true
|
||||
indicatif.workspace = true
|
||||
itertools.workspace = true
|
||||
noise.workspace = true
|
||||
pollster.workspace = true
|
||||
rand.workspace = true
|
||||
rayon.workspace = true
|
||||
tiff.workspace = true
|
||||
wgpu.workspace = true
|
||||
winit.workspace = true
|
||||
@@ -7,8 +7,7 @@ use glam::Vec3;
|
||||
use winit::event::WindowEvent;
|
||||
use winit::keyboard::KeyCode;
|
||||
|
||||
pub struct Camera
|
||||
{
|
||||
pub struct Camera {
|
||||
pub position: Vec3,
|
||||
pitch: f32,
|
||||
yaw: f32,
|
||||
@@ -22,10 +21,8 @@ pub struct Camera
|
||||
pub pressed_keyset: HashSet<KeyCode>,
|
||||
}
|
||||
|
||||
impl Default for Camera
|
||||
{
|
||||
fn default() -> Self
|
||||
{
|
||||
impl Default for Camera {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
position: Vec3::new(0., 0., 0.),
|
||||
pitch: Default::default(),
|
||||
@@ -41,47 +38,35 @@ impl Default for Camera
|
||||
}
|
||||
}
|
||||
|
||||
impl Camera
|
||||
{
|
||||
pub fn handle_input(&mut self, event: &WindowEvent)
|
||||
{
|
||||
if let WindowEvent::KeyboardInput { event, .. } = event
|
||||
{
|
||||
match (event.state, event.physical_key)
|
||||
{
|
||||
(winit::event::ElementState::Pressed, winit::keyboard::PhysicalKey::Code(c)) =>
|
||||
{
|
||||
impl Camera {
|
||||
pub fn handle_input(&mut self, event: &WindowEvent) {
|
||||
if let WindowEvent::KeyboardInput { event, .. } = event {
|
||||
match (event.state, event.physical_key) {
|
||||
(winit::event::ElementState::Pressed, winit::keyboard::PhysicalKey::Code(c)) => {
|
||||
self.pressed_keyset.insert(c);
|
||||
}
|
||||
(winit::event::ElementState::Released, winit::keyboard::PhysicalKey::Code(c)) =>
|
||||
{
|
||||
(winit::event::ElementState::Released, winit::keyboard::PhysicalKey::Code(c)) => {
|
||||
self.pressed_keyset.remove(&c);
|
||||
}
|
||||
_ =>
|
||||
{}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(&mut self)
|
||||
{
|
||||
pub fn update(&mut self) {
|
||||
let mut movement = Vec3::new(0., 0., 0.);
|
||||
if self.pressed_keyset.contains(&KeyCode::KeyW)
|
||||
{
|
||||
if self.pressed_keyset.contains(&KeyCode::KeyW) {
|
||||
movement.z += self.speed;
|
||||
}
|
||||
if self.pressed_keyset.contains(&KeyCode::KeyS)
|
||||
{
|
||||
if self.pressed_keyset.contains(&KeyCode::KeyS) {
|
||||
movement.z -= self.speed;
|
||||
}
|
||||
|
||||
// Left right
|
||||
if self.pressed_keyset.contains(&KeyCode::KeyA)
|
||||
{
|
||||
if self.pressed_keyset.contains(&KeyCode::KeyA) {
|
||||
movement.x += self.speed;
|
||||
}
|
||||
if self.pressed_keyset.contains(&KeyCode::KeyD)
|
||||
{
|
||||
if self.pressed_keyset.contains(&KeyCode::KeyD) {
|
||||
movement.x -= self.speed;
|
||||
}
|
||||
|
||||
@@ -91,8 +76,7 @@ impl Camera
|
||||
self.position -= rot_movement;
|
||||
}
|
||||
|
||||
pub fn cursor_moved(&mut self, x: f32, y: f32)
|
||||
{
|
||||
pub fn cursor_moved(&mut self, x: f32, y: f32) {
|
||||
const SENSITIVITY: f32 = 0.0004;
|
||||
let position = Vec2::new(x, y);
|
||||
let offset = position * SENSITIVITY;
|
||||
@@ -101,8 +85,7 @@ impl Camera
|
||||
self.pitch += offset.y;
|
||||
}
|
||||
|
||||
pub fn view_proj(&self) -> Mat4
|
||||
{
|
||||
pub fn view_proj(&self) -> Mat4 {
|
||||
let view = glam::Mat4::from_translation(self.position)
|
||||
* glam::Mat4::from_rotation_y(-self.yaw)
|
||||
* glam::Mat4::from_rotation_x(-self.pitch);
|
||||
@@ -12,23 +12,22 @@ use wgpu::TextureView;
|
||||
use winit::event::WindowEvent;
|
||||
use winit::window::Window;
|
||||
|
||||
pub struct EguiRenderer
|
||||
{
|
||||
pub struct EguiRenderer {
|
||||
state: State,
|
||||
pub renderer: Renderer,
|
||||
frame_started: bool,
|
||||
}
|
||||
|
||||
impl EguiRenderer
|
||||
{
|
||||
pub fn context(&self) -> &Context
|
||||
{
|
||||
impl EguiRenderer {
|
||||
pub fn context(&self) -> &Context {
|
||||
self.state.egui_ctx()
|
||||
}
|
||||
|
||||
pub fn new(device: &Device, output_color_format: TextureFormat, window: &Window)
|
||||
-> EguiRenderer
|
||||
{
|
||||
pub fn new(
|
||||
device: &Device,
|
||||
output_color_format: TextureFormat,
|
||||
window: &Window,
|
||||
) -> EguiRenderer {
|
||||
let egui_context = Context::default();
|
||||
|
||||
let egui_state = State::new(
|
||||
@@ -49,18 +48,15 @@ impl EguiRenderer
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle_input(&mut self, window: &Window, event: &WindowEvent)
|
||||
{
|
||||
pub fn handle_input(&mut self, window: &Window, event: &WindowEvent) {
|
||||
let _ = self.state.on_window_event(window, event);
|
||||
}
|
||||
|
||||
pub fn ppp(&mut self, v: f32)
|
||||
{
|
||||
pub fn ppp(&mut self, v: f32) {
|
||||
self.context().set_pixels_per_point(v);
|
||||
}
|
||||
|
||||
pub fn begin_frame(&mut self, window: &Window)
|
||||
{
|
||||
pub fn begin_frame(&mut self, window: &Window) {
|
||||
let raw_input = self.state.take_egui_input(window);
|
||||
self.state.egui_ctx().begin_pass(raw_input);
|
||||
self.frame_started = true;
|
||||
@@ -74,10 +70,8 @@ impl EguiRenderer
|
||||
window: &Window,
|
||||
window_surface_view: &TextureView,
|
||||
screen_descriptor: ScreenDescriptor,
|
||||
)
|
||||
{
|
||||
if !self.frame_started
|
||||
{
|
||||
) {
|
||||
if !self.frame_started {
|
||||
panic!("begin_frame must be called before.");
|
||||
}
|
||||
|
||||
@@ -92,8 +86,7 @@ impl EguiRenderer
|
||||
.egui_ctx()
|
||||
.tessellate(full_output.shapes, self.state.egui_ctx().pixels_per_point());
|
||||
|
||||
for (id, image_delta) in &full_output.textures_delta.set
|
||||
{
|
||||
for (id, image_delta) in &full_output.textures_delta.set {
|
||||
self.renderer
|
||||
.update_texture(device, queue, *id, &image_delta[0]);
|
||||
}
|
||||
@@ -121,8 +114,7 @@ impl EguiRenderer
|
||||
|
||||
self.renderer
|
||||
.render(&mut rpass.forget_lifetime(), &tris, &screen_descriptor);
|
||||
for x in &full_output.textures_delta.free
|
||||
{
|
||||
for x in &full_output.textures_delta.free {
|
||||
self.renderer.free_texture(x);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::gpu::create_multi_buffers_bind_group;
|
||||
use crate::gpu::create_multi_buffers_bind_group_layout;
|
||||
use vxls_gpu::create_multi_buffers_bind_group;
|
||||
use vxls_gpu::create_multi_buffers_bind_group_layout;
|
||||
|
||||
/// To keep a set of voxel nodes in the cache
|
||||
pub struct GpuSparseSet
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,22 +1,47 @@
|
||||
use std::fs::File;
|
||||
use std::path::Path;
|
||||
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
use glam::Vec3;
|
||||
use itertools::Itertools;
|
||||
use noise::Cylinders;
|
||||
use noise::Fbm;
|
||||
use noise::NoiseFn;
|
||||
use noise::Simplex;
|
||||
use rand::random;
|
||||
|
||||
use crate::sparse_tree::Color;
|
||||
use crate::voxel_cache::schema::ChildInformation;
|
||||
use vxls_production::ProducedNode;
|
||||
use vxls_production::Producer as VoxelProducer;
|
||||
use vxls_production::StructureAnchor;
|
||||
use vxls_production::StructureLocator;
|
||||
use vxls_production::sparse_tree::Color;
|
||||
use vxls_production::sparse_tree::ColorByte;
|
||||
use vxls_production::sparse_tree::NTree;
|
||||
use vxls_production::tree_locator::TreeLocator;
|
||||
use vxls_voxel_cache::schema::ChildInformation;
|
||||
use vxls_voxel_cache::schema::InsertionInformation;
|
||||
|
||||
pub struct BallGenerator<const N: usize>
|
||||
{
|
||||
/// The voxel attributes used by the demo cache.
|
||||
///
|
||||
/// The field order is load-bearing: attribute 0 is a packed RGBA color and
|
||||
/// attribute 1 is a 3-word normal, matching `fetch_color` / `fetch_normal` in
|
||||
/// `shaders/voxel.slang`.
|
||||
#[derive(Clone, Copy, PartialEq, Default, Pod, Zeroable, vxls_production::Attributes, Debug)]
|
||||
#[repr(C)]
|
||||
pub struct VoxelAttributes {
|
||||
#[attribute(label = "color", semantic = "color")]
|
||||
pub color: u32,
|
||||
|
||||
#[attribute(label = "normal", semantic = "normal")]
|
||||
pub normal: [f32; 3],
|
||||
}
|
||||
|
||||
pub struct BallGenerator<const N: usize> {
|
||||
chunk_power: usize,
|
||||
}
|
||||
|
||||
pub fn map(x: f32, x_min: f32, x_max: f32, y_min: f32, y_max: f32) -> f32
|
||||
{
|
||||
pub fn map(x: f32, x_min: f32, x_max: f32, y_min: f32, y_max: f32) -> f32 {
|
||||
//((x - x_min) / (x_max - x_min)) * (y_max - y_min) + y_min
|
||||
let input_range = x_max.algebraic_sub(x_min);
|
||||
let output_range = y_max.algebraic_sub(y_min);
|
||||
@@ -37,8 +62,7 @@ impl<const N: usize> BallGenerator<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(chunk_power: usize) -> Self
|
||||
{
|
||||
pub fn new(chunk_power: usize) -> Self {
|
||||
BallGenerator { chunk_power }
|
||||
}
|
||||
}
|
||||
@@ -47,8 +71,7 @@ impl<const N: usize> Producer<N> for BallGenerator<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ProducedChunk<N>
|
||||
{
|
||||
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ProducedChunk<N> {
|
||||
let node_size = N.pow((self.chunk_power - depth) as u32);
|
||||
let child_size = node_size / N;
|
||||
let global_size = N.pow(self.chunk_power as u32);
|
||||
@@ -61,8 +84,7 @@ where
|
||||
let gny = ny * node_size;
|
||||
let gnz = nz * node_size;
|
||||
// Iterate on children of this node
|
||||
for ((cx, cy), cz) in (0..N).cartesian_product(0..N).cartesian_product(0..N)
|
||||
{
|
||||
for ((cx, cy), cz) in (0..N).cartesian_product(0..N).cartesian_product(0..N) {
|
||||
let gvx = gnx + cx * child_size + (child_size / 2);
|
||||
let gvy = gny + cy * child_size + (child_size / 2);
|
||||
let gvz = gnz + cz * child_size + (child_size / 2);
|
||||
@@ -77,19 +99,14 @@ where
|
||||
|
||||
let alpha;
|
||||
let subdivided;
|
||||
if (dist - (global_size as f32 / 2.)).abs() <= child_diagonal_length
|
||||
{
|
||||
if (dist - (global_size as f32 / 2.)).abs() <= child_diagonal_length {
|
||||
//children.push(StructurePointer::new(depth <= 3, false, 0));
|
||||
subdivided = depth < (self.chunk_power - 1);
|
||||
alpha = if dist > 128. { 0. } else { 1. };
|
||||
}
|
||||
else if dist > (global_size as f32 / 2.)
|
||||
{
|
||||
} else if dist > (global_size as f32 / 2.) {
|
||||
subdivided = false;
|
||||
alpha = 0.;
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
subdivided = false;
|
||||
alpha = 1.;
|
||||
}
|
||||
@@ -149,8 +166,7 @@ where
|
||||
height_path: P,
|
||||
height_factor: f32,
|
||||
color_path: P,
|
||||
) -> Self
|
||||
{
|
||||
) -> Self {
|
||||
println!("Starting terrain producer");
|
||||
println!("Loading height map.");
|
||||
let mut tiff_dec = tiff::decoder::Decoder::new(File::open(height_path).unwrap()).unwrap();
|
||||
@@ -158,8 +174,7 @@ where
|
||||
let (heightmap_width, heightmap_height) =
|
||||
(heightmap_width as usize, heightmap_height as usize);
|
||||
|
||||
let mut heightmap = match tiff_dec.read_image().unwrap()
|
||||
{
|
||||
let mut heightmap = match tiff_dec.read_image().unwrap() {
|
||||
tiff::decoder::DecodingResult::F32(vec) => vec,
|
||||
_ => panic!("Unsupported format"),
|
||||
};
|
||||
@@ -209,16 +224,12 @@ where
|
||||
|
||||
let mut heightmap_low = vec![(0., 0.); heightmap_low_height * heightmap_low_width];
|
||||
|
||||
for y in 0..heightmap_low_height
|
||||
{
|
||||
for x in 0..heightmap_low_width
|
||||
{
|
||||
for y in 0..heightmap_low_height {
|
||||
for x in 0..heightmap_low_width {
|
||||
let mut min = heightmap_max;
|
||||
let mut max = heightmap_min;
|
||||
for sy in (y * 8)..(y * 8 + 8)
|
||||
{
|
||||
for sx in (x * 8)..(x * 8 + 8)
|
||||
{
|
||||
for sy in (y * 8)..(y * 8 + 8) {
|
||||
for sx in (x * 8)..(x * 8 + 8) {
|
||||
min = min.min(heightmap[sx + sy * heightmap_width]);
|
||||
max = max.max(heightmap[sx + sy * heightmap_width]);
|
||||
}
|
||||
@@ -234,17 +245,13 @@ where
|
||||
|
||||
let mut colormap_mip = vec![0u8; colormap_low_width * colormap_low_height * 3];
|
||||
|
||||
for y in 0..colormap_low_height
|
||||
{
|
||||
for x in 0..colormap_low_width
|
||||
{
|
||||
for y in 0..colormap_low_height {
|
||||
for x in 0..colormap_low_width {
|
||||
let mut r = 0u32;
|
||||
let mut g = 0u32;
|
||||
let mut b = 0u32;
|
||||
for sy in (y * 8)..(y * 8 + 8)
|
||||
{
|
||||
for sx in (x * 8)..(x * 8 + 8)
|
||||
{
|
||||
for sy in (y * 8)..(y * 8 + 8) {
|
||||
for sx in (x * 8)..(x * 8 + 8) {
|
||||
r += colormap[(sx + sy * terrain_width) * 3] as u32;
|
||||
g += colormap[(sx + sy * terrain_width) * 3 + 1] as u32;
|
||||
b += colormap[(sx + sy * terrain_width) * 3 + 2] as u32;
|
||||
@@ -298,8 +305,7 @@ where
|
||||
ny: usize,
|
||||
nz: usize,
|
||||
chunk_pos: (usize, usize, usize),
|
||||
) -> ProducedChunk<N>
|
||||
{
|
||||
) -> ProducedChunk<N> {
|
||||
let node_size = N.pow((self.chunk_power - depth) as u32);
|
||||
let child_size = node_size / N;
|
||||
let global_size = N.pow(self.chunk_power as u32);
|
||||
@@ -312,8 +318,7 @@ where
|
||||
let gny = chunk_pos.1 * global_size + ny * node_size;
|
||||
let gnz = chunk_pos.2 * global_size + nz * node_size;
|
||||
// Iterate on children of this node
|
||||
for (cx, cz) in (0..N).cartesian_product(0..N)
|
||||
{
|
||||
for (cx, cz) in (0..N).cartesian_product(0..N) {
|
||||
let gcx = gnx + cx * child_size;
|
||||
let gcz = gnz + cz * child_size;
|
||||
|
||||
@@ -325,14 +330,11 @@ where
|
||||
let mut color_avg = Color(0., 0., 0., 0.);
|
||||
let mut count = 0;
|
||||
|
||||
if depth <= 2
|
||||
{
|
||||
for (z, x) in (0..(child_size / 8)).cartesian_product(0..(child_size / 8))
|
||||
{
|
||||
if depth <= 2 {
|
||||
for (z, x) in (0..(child_size / 8)).cartesian_product(0..(child_size / 8)) {
|
||||
let gvx = (gcx + x * 8) / 8;
|
||||
let gvz = (gcz + z * 8) / 8;
|
||||
if gvx < self.colormap_low_width && gvz < self.colormap_low_height
|
||||
{
|
||||
if gvx < self.colormap_low_width && gvz < self.colormap_low_height {
|
||||
// Height sample
|
||||
let height_x = (gvx * self.heightmap_low_width) / self.colormap_low_width;
|
||||
let height_z = (gvz * self.heightmap_low_height) / self.colormap_low_height;
|
||||
@@ -356,15 +358,11 @@ where
|
||||
}
|
||||
//let gvy = gcy;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (z, x) in (0..child_size).cartesian_product(0..child_size)
|
||||
{
|
||||
} else {
|
||||
for (z, x) in (0..child_size).cartesian_product(0..child_size) {
|
||||
let gvx = gcx + x;
|
||||
let gvz = gcz + z;
|
||||
if gvx < self.terrain_width && gvz < self.terrain_height
|
||||
{
|
||||
if gvx < self.terrain_width && gvz < self.terrain_height {
|
||||
// Height sample
|
||||
let height_x = (gvx * self.heightmap_width) / self.terrain_width;
|
||||
let height_z = (gvz * self.heightmap_height) / self.terrain_height;
|
||||
@@ -407,32 +405,23 @@ where
|
||||
(self.chunk_alt * global_size) as f32,
|
||||
) as usize;
|
||||
|
||||
for cy in 0..N
|
||||
{
|
||||
for cy in 0..N {
|
||||
let gcy = gny + cy * child_size;
|
||||
let index = cz * N * N + cy * N + cx;
|
||||
let alpha;
|
||||
let subdivided;
|
||||
if gcy > sample_max
|
||||
{
|
||||
if gcy > sample_max {
|
||||
subdivided = false;
|
||||
alpha = 0.;
|
||||
}
|
||||
else if gcy + child_size < sample_min
|
||||
{
|
||||
} else if gcy + child_size < sample_min {
|
||||
subdivided = false;
|
||||
alpha = 1.;
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
subdivided = depth < (self.chunk_power - 1);
|
||||
//children.push(StructurePointer(0));
|
||||
alpha = if (sample_max + sample_min / 2) > gcy + (child_size / 2)
|
||||
{
|
||||
alpha = if (sample_max + sample_min / 2) > gcy + (child_size / 2) {
|
||||
1.
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
0.
|
||||
};
|
||||
}
|
||||
@@ -475,21 +464,18 @@ where
|
||||
) -> ProducedChunk<N>;
|
||||
}
|
||||
|
||||
pub struct SdfGenerator<const N: usize>
|
||||
{
|
||||
pub struct SdfGenerator<const N: usize> {
|
||||
chunk_power: usize,
|
||||
//perlin: Fbm<Simplex>,
|
||||
perlin: Simplex,
|
||||
perlin: Fbm<Simplex>,
|
||||
//perlin: Cylinders,
|
||||
}
|
||||
|
||||
impl<const N: usize> SdfGenerator<N>
|
||||
{
|
||||
pub fn new(chunk_power: usize) -> Self
|
||||
{
|
||||
impl<const N: usize> SdfGenerator<N> {
|
||||
pub fn new(chunk_power: usize) -> Self {
|
||||
Self {
|
||||
chunk_power,
|
||||
//perlin: Fbm::new(67),
|
||||
perlin: Simplex::new(67),
|
||||
perlin: Fbm::new(67),
|
||||
//perlin: Cylinders::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -505,21 +491,28 @@ where
|
||||
ny: usize,
|
||||
nz: usize,
|
||||
chunk_pos: (usize, usize, usize),
|
||||
) -> ProducedChunk<N>
|
||||
{
|
||||
) -> ProducedChunk<N> {
|
||||
fn hash(mut p: [f32; 3]) -> f32 {
|
||||
p[0] = (p[0] * 127.1 + p[1] * 311.7 + p[2] * 74.7).sin() * 43758.5453123;
|
||||
p[0].fract()
|
||||
}
|
||||
|
||||
// let sdf = |x: f32, y: f32, z: f32| {
|
||||
// Vec3::new((x % 1024.) - 512., (y % 1024.) - 512., (z % 1024.) - 512.).length() - 512.
|
||||
// };
|
||||
|
||||
// let sdf = |x: f32, y: f32, z: f32| {
|
||||
// let scale = 128.;
|
||||
// let sdf = |mut x: f32, mut y: f32, mut z: f32| {
|
||||
// // x = -5000. * 1024.;
|
||||
// // z = -5000. * 1024.;
|
||||
// y -= 1024.;
|
||||
// let scale = 2048.;
|
||||
// let tx = x / scale;
|
||||
// let ty = y / scale;
|
||||
// let tz = z / scale;
|
||||
//
|
||||
// let val = (self.perlin.get([tx as f64, ty as f64, tz as f64]) - 0.1) * 0.23;
|
||||
// let val = (self.perlin.get([tx as f64, tz as f64, ty as f64]) + 0.5) * 0.23;
|
||||
// let dist = val * scale as f64;
|
||||
// return dist as f32;
|
||||
// return (dist as f32).max(ty);
|
||||
// };
|
||||
|
||||
// let sdf = |x: f32, y: f32, z: f32| {
|
||||
@@ -532,12 +525,6 @@ where
|
||||
// };
|
||||
|
||||
let sdf = |x: f32, y: f32, z: f32| {
|
||||
fn hash(mut p: [f32; 3]) -> f32
|
||||
{
|
||||
p[0] = (p[0] * 127.1 + p[1] * 311.7 + p[2] * 74.7).sin() * 43758.5453123;
|
||||
p[0].fract()
|
||||
}
|
||||
|
||||
let scale = 10. * 1024.;
|
||||
let height = 5000.;
|
||||
let tx = x / scale;
|
||||
@@ -590,8 +577,7 @@ where
|
||||
let gny = ny * node_size + cy;
|
||||
let gnz = nz * node_size + cz;
|
||||
// Iterate on children of this node
|
||||
for ((cz, cy), cx) in (0..N).cartesian_product(0..N).cartesian_product(0..N)
|
||||
{
|
||||
for ((cz, cy), cx) in (0..N).cartesian_product(0..N).cartesian_product(0..N) {
|
||||
let gvx = gnx + cx * child_size + (child_size / 2);
|
||||
let gvy = gny + cy * child_size + (child_size / 2);
|
||||
let gvz = gnz + cz * child_size + (child_size / 2);
|
||||
@@ -601,20 +587,15 @@ where
|
||||
|
||||
let alpha;
|
||||
let subdivided;
|
||||
if dist.abs() < child_diagonal_length
|
||||
{
|
||||
if dist.abs() < child_diagonal_length {
|
||||
//children.push(StructurePointer::new(depth <= 3, false, 0));
|
||||
subdivided = depth < (self.chunk_power - 1);
|
||||
alpha = if dist >= 0. { 0. } else { 1. };
|
||||
//alpha = 0.;
|
||||
}
|
||||
else if dist >= 0.
|
||||
{
|
||||
} else if dist >= 0. {
|
||||
subdivided = false;
|
||||
alpha = 0.;
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
subdivided = false;
|
||||
alpha = 1.;
|
||||
}
|
||||
@@ -644,12 +625,9 @@ where
|
||||
|
||||
let normal = Vec3::new(a - b - c + d, -a - b + c + d, -a + b - c + d);
|
||||
|
||||
let normal = if normal.length() <= f32::EPSILON
|
||||
{
|
||||
let normal = if normal.length() <= f32::EPSILON {
|
||||
Vec3::new(1., 0., 0.)
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
normal.normalize()
|
||||
};
|
||||
|
||||
@@ -676,3 +654,75 @@ where
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Produces cache pages from an in-memory sparse tree.
|
||||
///
|
||||
/// The node to produce is named by the request's `node_locator`, so the
|
||||
/// producer never needs to know whether the cache asked for a structure root
|
||||
/// or an internal child.
|
||||
pub struct TreeProducer<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
tree: NTree<N, VoxelAttributes>,
|
||||
}
|
||||
|
||||
impl<const N: usize> TreeProducer<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(tree: NTree<N, VoxelAttributes>) -> Self {
|
||||
Self { tree }
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> VoxelProducer<N, VoxelAttributes> for TreeProducer<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
fn produce(
|
||||
&self,
|
||||
_anchor: StructureAnchor,
|
||||
locator: StructureLocator,
|
||||
) -> ProducedNode<N, VoxelAttributes> {
|
||||
let locator = TreeLocator::<N>::from(locator);
|
||||
let node = self
|
||||
.tree
|
||||
.get_by_loc(locator)
|
||||
.expect("requested node is not in the source tree");
|
||||
|
||||
let mut children = [ChildInformation::NONE; N * N * N];
|
||||
let mut attributes = [VoxelAttributes::default(); N * N * N];
|
||||
|
||||
if node.subdivided {
|
||||
for (index, child_locator) in locator.children().enumerate() {
|
||||
let child = self
|
||||
.tree
|
||||
.get_by_loc(child_locator)
|
||||
.expect("subdivided node is missing a child");
|
||||
|
||||
children[index] = ChildInformation::new(
|
||||
child.subdivided,
|
||||
child.subdivided || ColorByte(child.attribute.color).as_color().3 != 0.,
|
||||
);
|
||||
attributes[index] = VoxelAttributes {
|
||||
color: child.attribute.color,
|
||||
normal: child.attribute.normal,
|
||||
};
|
||||
}
|
||||
} else {
|
||||
let color = node.attribute.color;
|
||||
let occupied = ColorByte(node.attribute.color).as_color().3 != 0.;
|
||||
|
||||
for index in 0..N * N * N {
|
||||
children[index] = ChildInformation::new(false, occupied);
|
||||
attributes[index] = VoxelAttributes {
|
||||
color,
|
||||
normal: node.attribute.normal,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
ProducedNode::new(InsertionInformation { children }, attributes)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
# Architecture
|
||||
|
||||
This document describes the system as it exists in this checkout, plus the
|
||||
product vision that motivates it. For implementation-level detail see:
|
||||
|
||||
- [`voxel-cache.md`](./voxel-cache.md) — pages, pointers, requests, eviction, tables.
|
||||
- [`shaders.md`](./shaders.md) — Slang/WGSL shader architecture and compilation.
|
||||
- [`pipeline-and-producers.md`](./pipeline-and-producers.md) — how data gets into the cache.
|
||||
|
||||
> **Temporary code:** `crates/vxls/src/main.rs` and `crates/vxls/src/producers.rs` are a playground/test
|
||||
> harness built alongside the cache. They contain hardcoded parameters and
|
||||
> blocking workarounds. Do not treat them as stable architecture, public API, or
|
||||
> examples of intended concurrency. The durable system is `crates/vxls-voxel-cache/src/*`
|
||||
> and `shaders/`.
|
||||
|
||||
---
|
||||
|
||||
## 1. What this project is
|
||||
|
||||
A Rust + wgpu voxel renderer built around a GPU-resident sparse voxel cache
|
||||
(GigaVoxels-style: Crassin et al.). The tree is a 4×4×4 N-tree — every node has
|
||||
64 children — and nodes are stored in flat GPU page pools rather than a separate
|
||||
brick pool.
|
||||
|
||||
The renderer's goal is to display very large, addressable worlds while only a
|
||||
small working set of voxels is resident on the GPU. Rendering, request
|
||||
generation, page insertion, and eviction all run on the GPU; the CPU orchestrates
|
||||
passes and fulfils producer requests.
|
||||
|
||||
### Product vision
|
||||
|
||||
- Voxel size around pebble scale (~5–10 cm) near the player.
|
||||
- Render distance of tens of kilometres, with several valleys and mountain
|
||||
ranges visible at once.
|
||||
- Billions to hundreds of billions of *addressable* voxels, with only a small
|
||||
working set resident.
|
||||
- Interactive frame rates (the original target was ~60 fps at 1440p on
|
||||
mid-range hardware) with a stylized-voxel look but realistic large-scale
|
||||
terrain structure.
|
||||
- Longer term: a renderer a real game can be built on — dynamic edits, entities,
|
||||
water, vegetation, lighting, tooling, a stable API.
|
||||
|
||||
### Architectural principles
|
||||
|
||||
These principles are the yardstick for changes. They are not all satisfied yet.
|
||||
|
||||
1. **GPU-driven, CPU-light.** The CPU orchestrates; it must not iterate over
|
||||
voxels or per-frame visibility. Prefer indirect dispatch and GPU-side
|
||||
compaction of request lists.
|
||||
2. **Working-set bound, not world-size bound.** Cost must scale with screen
|
||||
pixels and cache size, never with total world size. Flag anything that
|
||||
violates this.
|
||||
3. **LOD is native to the structure.** Ray marching terminates at a level chosen
|
||||
by projected voxel size (about one pixel or less). Coarser levels must carry
|
||||
well-filtered data.
|
||||
4. **Asynchronous and latency-tolerant.** Missing data must never stall the
|
||||
frame. Render with the best available coarser level and refine as data
|
||||
arrives. Avoid visible popping where possible (blending, hysteresis,
|
||||
prioritisation by screen coverage and distance).
|
||||
5. **Producers are pluggable.** The renderer only knows "request node/brick X at
|
||||
level L, give me payload". Procedural terrain, heightmap-derived data, edited
|
||||
chunks, and baked/disk-streamed data should sit behind the same interface.
|
||||
6. **Measure first.** No optimisation advice without a way to measure it
|
||||
(timestamp queries, counters in a debug buffer, RenderDoc/Nsight/RGP
|
||||
captures). Suggest instrumentation before suggesting rewrites.
|
||||
|
||||
### Roadmap context
|
||||
|
||||
The roadmap below is from the original project notes and is **not** a commitment.
|
||||
Treat it as direction, not a specification.
|
||||
|
||||
- **Near term:** stabilise the cache + request pipeline, lighting/shadows,
|
||||
atmosphere, a real terrain producer, camera-relative coordinates.
|
||||
- **Mid term:** world edits, entities and depth compositing, TAA,
|
||||
vegetation/props.
|
||||
- **Long term:** engine API, tooling, physics integration, disk streaming.
|
||||
|
||||
---
|
||||
|
||||
## 2. Current state at a glance
|
||||
|
||||
Implemented and wired into the running demo:
|
||||
|
||||
- GPU voxel cache with 4×4×4 branching and configurable page/request counts.
|
||||
- GPU-emitted requests based on per-child counters, top-K selection, and a
|
||||
descending radix sort.
|
||||
- Page recycling driven by LRU timestamps, with deepest-first depth ties (see
|
||||
[`voxel-cache.md`](./voxel-cache.md#7-eviction-policy--timestamp-major-deepest-first-ties)).
|
||||
- External (structure-table) and internal (cache) insertion modes.
|
||||
- Structure tables: a fixed dense table and a toroidal wrapper for an
|
||||
"infinite" block of chunks around the camera.
|
||||
- Slang ray-marching shaders with pixel-footprint LOD, compiled ahead of time.
|
||||
- WGSL cache-management shaders, specialised at runtime with generated
|
||||
constants.
|
||||
- Procedural fixtures (`SdfGenerator`, `TerrainGenerator`, `BallGenerator`) and
|
||||
a blocking host request-fulfilment loop in `main.rs` built on `RequestQueue`,
|
||||
`Producer`/`ProducedNode`, and `CacheInsertionData::upload`.
|
||||
|
||||
Not wired in: the terrain/ball fixtures, `tree.rs`, and `VoxelGiPipeline`
|
||||
(module compiles but is never instantiated). The demo uses `TreeProducer` and
|
||||
the production subsystem's queue. See the module map below.
|
||||
|
||||
---
|
||||
|
||||
## 3. High-level data flow
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Cam[Camera / window] --> Render[Render compute pass<br/>voxel.slang]
|
||||
Render -->|reads| Cache[(Voxel cache pages)]
|
||||
Render -->|reads| Table[(Structure table)]
|
||||
Render -->|increments| Req[(Per-page request counters)]
|
||||
Table -->|increments| TReq[(Table request counters)]
|
||||
|
||||
Req --> Gather[gather_requests<br/>top-K + radix sort]
|
||||
TReq --> TGather[table gather_requests]
|
||||
Gather --> RBuffer[(Request buffer<br/>anchor, node_id, child)]
|
||||
TGather --> TRBuffer[(Table request buffer<br/>anchor, slot)]
|
||||
|
||||
RBuffer --> Host[Host fulfils requests]
|
||||
TRBuffer --> Host
|
||||
Host -->|CacheInsertionData| Insert[VoxelCache::insert]
|
||||
Host -->|structure insertion| TableInsert[ToroidalStructureTable::insert]
|
||||
Insert -->|writes| Cache
|
||||
Insert -->|recycles pages| Evict[Evictor]
|
||||
TableInsert -->|root pointers| Table
|
||||
```
|
||||
|
||||
Two request/response loops are visible:
|
||||
|
||||
- **Structure-table loop.** The table maps chunk coordinates to the root pointer
|
||||
of each chunk's tree in the cache. A miss requests a *chunk root*.
|
||||
- **Cache loop.** During ray marching, the cache tracer requests missing
|
||||
children of nodes that are marked subdividable but not resident.
|
||||
|
||||
Both loops share the same request-buffer implementation and host download path.
|
||||
|
||||
---
|
||||
|
||||
## 4. Frame lifecycle (what the current driver does)
|
||||
|
||||
`State::render` in `crates/vxls/src/main.rs` is the only driver. One iteration does roughly:
|
||||
|
||||
1. **Move the toroidal table** to the camera position. Chunks leaving the block
|
||||
are invalidated; chunks entering are marked as needing a root pointer.
|
||||
2. **Render pass** (`ray_march_compute` in `voxel.slang`):
|
||||
- trace the toroidal chunk grid, then descend the voxel cache;
|
||||
- write position/albedo/normal G-buffers;
|
||||
- update per-page usage timestamps;
|
||||
- increment request counters for missing children.
|
||||
3. **GI / AO pass** (`gi.slang`) — reads the world-space G-buffer, traces a few
|
||||
short hemisphere rays per pixel with `any_hit` and a finite `t_max`, and
|
||||
multiplies albedo by the AO term.
|
||||
4. **Blit / UI** — copy the selected debug texture, draw egui, download a usage
|
||||
histogram for the plot.
|
||||
5. **Encode request gathering** for both the cache and the structure table
|
||||
(unless `F` is held): top-K, gather, radix sort, write request buffers, reset
|
||||
counters.
|
||||
6. **Submit and present.**
|
||||
7. **Read back timings** asynchronously.
|
||||
8. **Fulfil requests and insert** (unless `F` is held):
|
||||
- start asynchronous downloads of both request buffers;
|
||||
- busily poll the device until both callbacks have run;
|
||||
- on the CPU, produce nodes for every request (parallel over requests);
|
||||
- upload `CacheInsertionData` buffers;
|
||||
- encode `VoxelCache::insert` with both an external insertion (table roots)
|
||||
and an internal insertion (cache children);
|
||||
- encode `ToroidalStructureTable::insert` to point table entries at the new
|
||||
root pages;
|
||||
- submit.
|
||||
|
||||
Consequences agents should keep in mind:
|
||||
|
||||
- Inserted pages become visible on the **next** frame; the render pass of the
|
||||
current frame already ran.
|
||||
- The host step is **synchronous and blocking** even though the download API is
|
||||
callback-based. The `loop { device.poll(...) }` at the end of `render` is a
|
||||
workaround, not the intended design.
|
||||
- Holding `F` freezes cache management so the resident set can be inspected.
|
||||
- Debug display keys: `T` target, `N` normals, `Q` albedo, `P` position.
|
||||
|
||||
---
|
||||
|
||||
## 5. Module map
|
||||
|
||||
| Path | Role | Status |
|
||||
|---|---|---|
|
||||
| `crates/vxls/src/main.rs` | Window, wgpu setup, frame loop, host fulfilment | **Temporary playground** |
|
||||
| `crates/vxls/src/producers.rs` | `ChunkedProducer` + procedural fixtures | **Temporary playground** (trait is the useful part) |
|
||||
| `crates/vxls-voxel-cache/src/lib.rs` | `VoxelCache` orchestrator, public API, raytrace bind group | Active, durable |
|
||||
| `crates/vxls-voxel-cache/src/schema.rs` | Pointer bits, page structs, request structs | Active, durable |
|
||||
| `crates/vxls-attributes/src/attributes.rs` | Producer-facing `Attribute`/`Attributes` traits and static attribute layouts | Active, durable |
|
||||
| `crates/vxls-attributes-derive/src/lib.rs` | `#[derive(Attributes)]` layout generator | Active, durable |
|
||||
| `crates/vxls-voxel-cache/src/layout.rs` | `CacheAttribute`/`CacheLayout`, bridge from `AttributesLayout`, generated WGSL constants | Active, durable |
|
||||
| `crates/vxls-voxel-cache/src/attributes.rs` | Attribute page buffers and bind group | Active, durable |
|
||||
| `crates/vxls-voxel-cache/src/structure.rs` | Pointer/location/depth page buffers | Active, durable |
|
||||
| `crates/vxls-voxel-cache/src/requests.rs` | Request counters, request buffer, top-K/sort, host download | Active, durable |
|
||||
| `crates/vxls-voxel-cache/src/insertion.rs` | `CacheInsertionData` upload buffers | Active, durable |
|
||||
| `crates/vxls-voxel-cache/src/eviction.rs` | Timestamp buffer and eviction ordering | Active, durable |
|
||||
| `crates/vxls-voxel-cache/src/pipelines.rs` | Write-requests, insertion, invalidation, write-pointers passes | Active, durable |
|
||||
| `crates/vxls-voxel-cache/src/tables.rs` | `FixedStructureTable` (dense root pointers) | Active, durable |
|
||||
| `crates/vxls-terrain/src/lib.rs` | `ToroidalStructureTable` wrapper around the fixed table | Active, durable (name is misleading) |
|
||||
| `crates/vxls-bvh/src/lib.rs` (+ `aabb`, `build`, `debug`, `gpu`) | CPU BVH2 build, GPU buffers, and debug render | Active infrastructure |
|
||||
| `crates/vxls-gpu/src/` | Radix sort, top-K, indirect dispatch, compaction helpers | Active infrastructure |
|
||||
| `crates/vxls-profiler/src/` | Timestamp profiling and memory accounting wrappers | Active infrastructure |
|
||||
| `crates/vxls/src/gi_pipeline.rs` (+ `sparse_set.rs`) | Planned GI pipeline using cache attribute sets | **Compiled but never instantiated** |
|
||||
| `crates/vxls-production/src/lib.rs` | Producer ID, `StructureAnchor` re-export, `Producer`/`ProducedNode` | Compiled; durable contract |
|
||||
| `crates/vxls-production/src/tree_locator.rs` | Compact N-tree locator encoding | Active via `RequestKey::node_locator` and `TreeProducer` |
|
||||
| `crates/vxls-production/src/request_queue.rs` | Bounded, deduplicating, priority-ordered request queue | Active in the demo driver, unit-tested |
|
||||
| `crates/vxls/src/sparse_tree.rs` | CPU `NTree` prototype, packed color helper and node locator used by producers | Active via `main.rs`/`producers.rs` |
|
||||
|
||||
The workspace uses edition 2024. Crates that use const-generic expressions enable
|
||||
`generic_const_exprs` (voxel cache, production, BVH, terrain, app); `float_algebraic`
|
||||
is only used by the app crate. Building requires a nightly toolchain.
|
||||
|
||||
---
|
||||
|
||||
## 6. Coordinate and tree model
|
||||
|
||||
The world is treated as a floating-point cube; the cache exploits float
|
||||
mantissas to derive tree levels.
|
||||
|
||||
- Branching factor `N = 4`; a node has `N³ = 64` children.
|
||||
- Child index is `x + 4*y + 16*z` (x fastest). This matches the WGSL
|
||||
`child_index` and the Rust producer loops.
|
||||
- A node's level is encoded by `scale_exp`: `scale_exp = 23 - 2*depth` for
|
||||
single-precision floats. The root starts at `scale_exp = 21` (depth 1 in that
|
||||
mapping); each subdivision subtracts 2.
|
||||
- Because 23 mantissa bits are available, the tree has room for roughly
|
||||
11 levels of 2-bit levels. The configured demo uses `chunk_power = 5`, i.e. a
|
||||
chunk is `4^5 = 1024` voxels per axis.
|
||||
- Position-to-child conversion takes two mantissa bits at the current
|
||||
`scale_exp`, so the tree is effectively spatially indexed by float bit
|
||||
patterns. This is why the tracer can descend without explicit bounding boxes.
|
||||
|
||||
The trace stack is caller-owned through `ITraceStack`. The local
|
||||
implementation (`LocalTraceStack` in `voxel_tracing.slang`) is a 5-entry stack
|
||||
indexed by `10 - scale_exp/2`. That hardcodes the maximum supported depth and
|
||||
the branching factor. It also assumes `chunk_power = 5`; changing chunk depth
|
||||
without updating the stack breaks tracing. A groupshared-backed implementation
|
||||
is a front-end change and needs no trace-core edits.
|
||||
|
||||
The toroidal table is a dense 3D grid of chunk root pointers. It wraps with
|
||||
`imod`, so moving the camera across a chunk boundary invalidates the departing
|
||||
slab and reuses those slots for incoming chunks. Identity is kept separate from
|
||||
placement: each slot carries a table-defined `StructureAnchor` (world position
|
||||
plus a version word), and the anchor is the structure identity. Anchors that stay
|
||||
in view keep their identity while their slot may change; anchors that leave are
|
||||
retired. In-flight root work carries the anchor and the latest slot, and the GPU
|
||||
rejects an insertion whose anchor no longer matches the slot, so queue
|
||||
invalidation is only a cancellation optimisation.
|
||||
|
||||
---
|
||||
|
||||
## 7. Shader split
|
||||
|
||||
There are two independent shader worlds, described fully in
|
||||
[`shaders.md`](./shaders.md):
|
||||
|
||||
- **Slang** (`shaders/*.slang`) for rendering. Built offline with `slangc` into
|
||||
checked-in `shaders/out/*.spv`, embedded with `include_spirv_source!`, and
|
||||
loaded as passthrough modules.
|
||||
- **WGSL** (`crates/vxls-voxel-cache/src/shaders/*.wgsl`) for cache management. Concatenated
|
||||
at runtime with generated constants (`CHILDREN_COUNT`, `PAGE_COUNT`, attribute
|
||||
metadata) and compiled with `include_wgsl!`-style module creation.
|
||||
|
||||
The two worlds agree only by convention on data layout. Attribute order, page
|
||||
stride, child index, and pointer bits are load-bearing contracts between them.
|
||||
|
||||
---
|
||||
|
||||
## 8. Memory and performance envelope
|
||||
|
||||
The demo configuration is `VoxelCache<4>` with 150,000 pages and 1,024 maximum
|
||||
requests, plus a 20×20×20 toroidal table.
|
||||
|
||||
Approximate steady-state GPU buffers (decimal units, `CHILDREN_COUNT = 64`):
|
||||
|
||||
| Buffer | Bytes per page | At 150k pages |
|
||||
|---|---:|---:|
|
||||
| Pointer pages (`u64` mask + 64×`u32`) | 264 | ~39.6 MB |
|
||||
| Location pages (allocated at 264 B; see below) | 264 | ~39.6 MB |
|
||||
| Depth pages | 4 | ~0.6 MB |
|
||||
| `color` attribute (1 word × 64) | 256 | ~38.4 MB |
|
||||
| `normal` attribute (3 words × 64) | 768 | ~115.2 MB |
|
||||
| Request counters (64×`u32`) | 256 | ~38.4 MB |
|
||||
| Sorted requests (64×`u32`) | 256 | ~38.4 MB |
|
||||
| Scratch (64×`u32`) | 256 | ~38.4 MB |
|
||||
| Timestamps + LRU list | 8 | ~1.2 MB |
|
||||
|
||||
Total is roughly **400 MB** before pipelines, bind groups, profiler buffers, and
|
||||
the separate structure-table allocations. The single largest avoidable waste is
|
||||
the location-page over-allocation described in the issues table.
|
||||
|
||||
Performance is dominated by ray marching, not by cache management in the current
|
||||
demo; the UI plots both a frame timer and a ray-march timer.
|
||||
|
||||
---
|
||||
|
||||
## 9. Known issues (architecture level)
|
||||
|
||||
| Symptom | Location | Impact | Confidence |
|
||||
|---|---|---|---|
|
||||
| Location pages are sized with `size_of::<StructurePage<N>>()` (264 B at N=4) instead of `LocationPage` (28 B). | `crates/vxls-voxel-cache/src/structure.rs:44` | ~39.6 MB allocated where ~4.2 MB is needed. | High — direct code read. |
|
||||
| The host request path busy-waits on `device.poll`, making a callback design behave synchronously. | `crates/vxls/src/main.rs` around the `loop { ... poll ... }` after request downloads | Stalls the CPU on the render thread; prevents real pipelining/streaming. | High. |
|
||||
| The caller-owned trace stack (`LocalTraceStack`, or a groupshared-backed `ITraceStack`) is 5 entries and indexes `entries[10 - scale_exp/2]`, assuming `N = 4` and `chunk_power = 5`. | `shaders/voxel_tracing.slang`, `shaders/voxel_cache.slang` | Changing branching or chunk depth silently corrupts tracing. | High. |
|
||||
| Slang hardcodes `64` children per node and attribute meanings (0 = packed color, 1 = 3-word normal). | `shaders/voxel_cache.slang`, `shaders/voxel.slang` | Any cache layout change must be mirrored in Slang; mismatches are not caught at compile time. | High. |
|
||||
| `gi.slang` is a simple AO pass (4 fixed hemisphere rays, no denoiser), not a full GI solution. | `shaders/gi.slang` | Noisy, view-dependent AO; it exists as a secondary-ray smoke test. | High. |
|
||||
| `FixedStructureTable` / `ToroidalStructureTable` naming: the toroidal wrapper delegates to the fixed table, and `fixed_structure_table.slang` is imported but unused by `voxel.slang`. | `crates/vxls-terrain/src/lib.rs`, `shaders/fixed_structure_table.slang`, `shaders/voxel.slang:3` | Readers may look for toroidal logic in the wrong shader/module. | High. |
|
||||
| Several subsystems are present but not wired into the binary (see module map). | `crates/vxls/src/gi_pipeline.rs`, terrain/ball fixtures | Dead code can be mistaken for current architecture; it does not compile into the binary unless declared. | High. |
|
||||
| The demo worker thread still lives in `main.rs`, so scheduling and producer ownership are not reusable. | `crates/vxls/src/main.rs` | Production types are durable; the host service around them is playground code. | Medium. |
|
||||
@@ -0,0 +1,527 @@
|
||||
# Pipeline and producers
|
||||
|
||||
This document follows data from a GPU-emitted request to a resident cache page,
|
||||
and describes the producer interface. It also marks which producer code is
|
||||
durable and which is throwaway.
|
||||
|
||||
> **Temporary code:** `crates/vxls/src/main.rs` and `crates/vxls/src/producers.rs` are a playground/test
|
||||
> harness built alongside the cache. They contain hardcoded parameters and
|
||||
> blocking workarounds. Do not treat them as stable architecture, public API, or
|
||||
> examples of intended concurrency. The `ChunkedProducer` shape and the
|
||||
> insertion/data-flow contract are the durable parts; the concrete generators
|
||||
> (including `SdfGenerator` and `TerrainGenerator`) are throwaway fixtures and
|
||||
> should be replaced.
|
||||
|
||||
---
|
||||
|
||||
## 1. End-to-end sequence
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant R as Render pass (GPU)
|
||||
participant C as Voxel cache (GPU)
|
||||
participant T as Structure table (GPU)
|
||||
participant H as Host (main.rs)
|
||||
participant I as Insertion passes (GPU)
|
||||
|
||||
R->>C: descend pages, mark usage, increment missing-child counters
|
||||
R->>T: trace chunk cells, increment missing-root counters
|
||||
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 (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
|
||||
I->>C: write new child pointers
|
||||
I->>T: validate/point table slots at new root pages
|
||||
Note over R: next frame sees the new pages
|
||||
```
|
||||
|
||||
Timing detail: in the current driver the render pass runs **before** request
|
||||
gathering and insertion in the same `render()` call. Therefore pages produced in
|
||||
response to frame N are first visible in frame N+1.
|
||||
|
||||
---
|
||||
|
||||
## 2. The request/response contract
|
||||
|
||||
### 2.1 Request
|
||||
|
||||
```rust
|
||||
struct RequestInformation {
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
```
|
||||
|
||||
- The producer receives both `RequestInformation` and `RequestMeta`, so it can
|
||||
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`, `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.
|
||||
- `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.
|
||||
|
||||
`node_id` and `producer_id` are `StructureLocator` and `ProducerId` on the Rust
|
||||
side (transparent over `u32`); the layout above is the GPU wire layout.
|
||||
|
||||
### 2.2 Response
|
||||
|
||||
One `CacheInsertionData` entry per produced node. Entries do **not** have to be in
|
||||
request order, because each one carries its own attachment point:
|
||||
|
||||
```rust
|
||||
struct InsertionInformation<N> {
|
||||
children: [ChildInformation; 64], // bit 31 subdividable, bit 30 occupied
|
||||
}
|
||||
|
||||
struct LocationPage {
|
||||
node_id: u32, // locator of the node itself
|
||||
producer_id: u32,
|
||||
anchor: StructureAnchor,
|
||||
}
|
||||
|
||||
struct InsertionParent {
|
||||
kind: u32, // 0 = child of a resident page, 1 = external root
|
||||
page_index: u32, // parent page, or 0xFFFFFFFF for an external root
|
||||
children_index: u32,
|
||||
depth: u32, // parent depth, or 0xFFFFFFFF
|
||||
node_id: u32, // parent locator (0 for an external root)
|
||||
producer_id: u32,
|
||||
anchor: StructureAnchor,
|
||||
table_slot: u32, // external root placement, NO_TABLE_SLOT internally
|
||||
}
|
||||
```
|
||||
|
||||
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 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
|
||||
that received entry `i`, or `0xFFFFFFFF` if it was rejected (invalid, out of
|
||||
capacity, or too recently used). A real producer should read it and retry the
|
||||
request if needed.
|
||||
|
||||
### 2.3 Ordering and staleness
|
||||
|
||||
There is no longer an ordering requirement between requests and insertion
|
||||
entries. `write_pointers.wgsl` and `fixed_table/insertion.wgsl` use the batch's
|
||||
`InsertionParent`, and re-check parent identity before linking. This is what
|
||||
makes asynchronous, cross-frame production safe: a page produced for a parent
|
||||
that has since been evicted or reused is dropped at insertion time instead of
|
||||
corrupting the tree.
|
||||
|
||||
---
|
||||
|
||||
## 3. The durable producer shape
|
||||
|
||||
The durable interface is `vxls-production::Producer`, and the demo driver uses
|
||||
it through `TreeProducer` in `crates/vxls/src/producers.rs`:
|
||||
|
||||
```rust
|
||||
pub trait Producer<const N: usize, A: Attributes>
|
||||
where [(); N * N * N]:,
|
||||
{
|
||||
fn produce(
|
||||
&self,
|
||||
anchor: StructureAnchor,
|
||||
locator: StructureLocator,
|
||||
) -> ProducedNode<N, A>;
|
||||
}
|
||||
|
||||
pub struct ProducedNode<const N: usize, A: Attributes>
|
||||
where [(); N * N * N]:,
|
||||
{
|
||||
pub insertion: InsertionInformation<N>,
|
||||
pub attributes: [A; N * N * N],
|
||||
}
|
||||
```
|
||||
|
||||
`locator` is the content-local path of the node to produce, obtained from the
|
||||
request with `RequestKey::node_locator::<N>()`. The producer does not need to
|
||||
know whether the request was a structure root or an internal child: the locator
|
||||
already names the node, and the cache derives the matching `LocationPage` from
|
||||
the same key.
|
||||
|
||||
The cache owns identity, so `ProducedNode` deliberately carries no producer id,
|
||||
anchor, table slot, or location. The host/queue adds those when it builds an
|
||||
`InsertionEntry`.
|
||||
|
||||
The older `ChunkedProducer` / `ProducedChunk` shape in
|
||||
`crates/vxls/src/producers.rs` is retained only for the unused terrain/ball
|
||||
fixtures. It is not the interface new producers should implement.
|
||||
|
||||
Interpretation:
|
||||
|
||||
- A leaf is `subdividable = false`. A node that should be refined later is
|
||||
`subdividable = true`. Occupancy controls hit testing and coarse skipping.
|
||||
- The producer fills one entry per child of the requested node, plus the
|
||||
attributes for those children.
|
||||
- `anchor` is the content identity. A producer must derive world position from
|
||||
it and never from a table slot.
|
||||
|
||||
### 3.1 Fulfilling a request
|
||||
|
||||
`TreeProducer` (`crates/vxls/src/producers.rs`) does:
|
||||
|
||||
1. Decode `locator` with `TreeLocator::<N>::from`.
|
||||
2. If the node is not subdivided, emit a constant page: every child has the
|
||||
node's attribute and `ChildInformation::new(false, occupied)`.
|
||||
3. Otherwise iterate `locator.children()` and emit each child's
|
||||
`ChildInformation` and `VoxelAttributes`.
|
||||
4. Return a `ProducedNode`; no location or parent is produced here.
|
||||
|
||||
The request path is:
|
||||
|
||||
1. `RequestQueue` yields a `WorkItem` with a `RequestKey`.
|
||||
2. The worker calls `producer.produce(key.anchor, key.node_locator::<4>())`.
|
||||
3. On drain, `ReadyItem::insertion_entry()` combines the payload with
|
||||
`ReadyItem::insertion_parent()` and `ReadyItem::location_page()`.
|
||||
4. `CacheInsertionData::upload` writes the batch.
|
||||
|
||||
### 3.2 Locators
|
||||
|
||||
`TreeLocator<N>` (`crates/vxls-production/src/tree_locator.rs`) is the locator
|
||||
used by the request queue and the demo producer. Three base-N accumulators
|
||||
(`x`, `y`, `z`) with a leading `1` digit; root is `(1,1,1)`; `depth =
|
||||
ilog_N(x)`; `parent` divides each coordinate by `N`; `child` multiplies by `N`
|
||||
and adds the child digit. `StructureLocator` is a flat interleaved form.
|
||||
|
||||
`NTree<N>` in `crates/vxls/src/sparse_tree.rs` is keyed by the same locator, so
|
||||
a `RequestKey` can name a produced node directly. Locators must round-trip
|
||||
through the 32-bit `node_id`.
|
||||
|
||||
---
|
||||
|
||||
## 4. The current driver, step by step
|
||||
|
||||
Relevant code: `State::render` and `TreeProducer` in `crates/vxls/src/main.rs` /
|
||||
`crates/vxls/src/producers.rs`.
|
||||
|
||||
1. **Render** writes G-buffers and request counters.
|
||||
2. **Gather** encodes both request pipelines (cache + table) into the same
|
||||
command buffer, then submits and presents.
|
||||
3. **Download** starts three asynchronous reads per request buffer (count,
|
||||
informations, meta). Each callback only ingests the wire requests into the
|
||||
shared `RequestQueue`; it does not drain or upload.
|
||||
4. **Busy-wait**:
|
||||
|
||||
```rust
|
||||
loop {
|
||||
if finished.load(Relaxed) >= 2 { break; }
|
||||
let _ = self.device.poll(wgpu::wgt::PollType::Poll);
|
||||
}
|
||||
```
|
||||
|
||||
`finished` counts completed callbacks (one cache, one table), so completion
|
||||
does not require all six reads to land independently. Each callback
|
||||
increments it only after ingesting.
|
||||
5. **Drain** the queue once both downloads have landed:
|
||||
|
||||
```rust
|
||||
let children = queue.drain_ready_matching(
|
||||
frame_id, cache_insertion.capacity(), |key| !key.is_root());
|
||||
let roots = queue.drain_ready_matching(
|
||||
frame_id, structure_table_insertion.capacity(), |key| key.is_root());
|
||||
```
|
||||
|
||||
`frame_id` is a host-owned monotonic counter, not the cache timestamp word.
|
||||
6. **Produce** on the worker thread with rayon, one `Producer::produce` call per
|
||||
`WorkItem`. Each result is a `ProducedNode<N, A>` keyed by
|
||||
`RequestKey::node_locator::<N>()`. On drain,
|
||||
`ReadyItem::insertion_entry()` attaches the parent and location, and
|
||||
`CacheInsertionData::upload` writes the whole batch (structure, location,
|
||||
parent, attributes, `valid_count`, `page_count`). `destination_indices` is
|
||||
reset by the validation shaders, not by the host.
|
||||
7. **Insert** encodes:
|
||||
|
||||
```rust
|
||||
cache.insert(&device, &mut encoder, &mut [
|
||||
&mut VoxelCacheInsertion::ExternalRequest(
|
||||
&structure_table_cache_insertion, &mut *structure_table),
|
||||
&mut VoxelCacheInsertion::InternalRequest(&cache_insertion),
|
||||
]);
|
||||
structure_table.insert(&device, &mut encoder,
|
||||
&structure_table_cache_insertion);
|
||||
```
|
||||
|
||||
Validation and compaction run first for both batches, then one eviction
|
||||
preparation is shared by both page allocations. It orders pages by timestamp
|
||||
first (least recently used first) and depth second (deepest first among equal
|
||||
timestamps).
|
||||
8. **Submit** and read back the insertion profile.
|
||||
|
||||
Because the external insertion is processed first, newly produced chunk roots
|
||||
are resident before the internal child insertion links them. The table insertion
|
||||
then points the slot at the root page.
|
||||
|
||||
### 4.1 Problems this creates
|
||||
|
||||
- The render thread blocks waiting for downloads before it can drain results, so
|
||||
production does not overlap with rendering.
|
||||
- Request buffers are read back every frame even when empty.
|
||||
- `finished >= 2` is a coarse synchronization; it assumes exactly two buffers
|
||||
and no retries.
|
||||
- The worker thread is spawned from the playground, so scheduling and producer
|
||||
ownership are not reusable outside `main.rs`.
|
||||
- No backpressure or prioritisation beyond the top-K request cap.
|
||||
- Rejected insertions (`destination_indices == 0xFFFFFFFF`) are still not
|
||||
reported back to the producer.
|
||||
|
||||
These are acceptable for a playground and are the first things to redesign for a
|
||||
real engine.
|
||||
|
||||
---
|
||||
|
||||
## 5. Generators in `crates/vxls/src/producers.rs`
|
||||
|
||||
All are fixtures. They exist to exercise the cache and should not be treated as
|
||||
stable.
|
||||
|
||||
| Generator | Status | What it does |
|
||||
|---|---|---|
|
||||
| `TreeProducer<N>` | Used by the demo | Implements the durable `vxls_production::Producer` over an in-memory `NTree`; the request's `node_locator` selects the node. |
|
||||
| `SdfGenerator<N>` | Fixture, unused | Signed-distance field from FBM simplex noise plus procedural "trees"; derives normal by finite differences; packs color from normal. |
|
||||
| `TerrainGenerator<N>` | Fixture, unused | Loads a TIFF heightmap and a JPEG/PNG colormap; builds low-resolution mips; produces nodes from min/max height spans. |
|
||||
| `BallGenerator<N>` | Fixture, unused | Implements the local playground `producers::Producer<N>` trait, not the durable one. |
|
||||
|
||||
`TerrainGenerator` is the closest thing to a realistic producer, but it is
|
||||
single-threaded at load time and uses hardcoded mip factors (8×). It also has
|
||||
branching logic based on `depth <= 2`.
|
||||
|
||||
`SdfGenerator` demonstrates the attribute math:
|
||||
|
||||
- `alpha = 0` above the surface, `1` below;
|
||||
- `subdivided = depth < chunk_power - 1` near the surface;
|
||||
- normal from four SDF samples;
|
||||
- color derived from the normal with a small random tint.
|
||||
|
||||
---
|
||||
|
||||
## 6. The production subsystem
|
||||
|
||||
`crates/vxls-production/src/lib.rs` and its children are compiled, and the demo
|
||||
driver now uses its durable `Producer` / `ProducedNode` / `RequestQueue` types.
|
||||
The `main.rs` producer remains a playground fixture, but it implements the
|
||||
durable interface.
|
||||
|
||||
### 6.1 `crates/vxls-production/src/lib.rs`
|
||||
|
||||
Defines the producer-facing attribute vocabulary and the production interface.
|
||||
The attribute traits and layouts live in `vxls-attributes` and are re-exported
|
||||
here:
|
||||
|
||||
```rust
|
||||
// Identity types live in vxls-voxel-cache::schema and are re-exported here.
|
||||
pub use vxls_attributes::{Attribute, AttributeDescriptor, Attributes, AttributesLayout};
|
||||
pub use vxls_voxel_cache::schema::{ProducerId, StructureAnchor, StructureLocator};
|
||||
|
||||
pub trait Attributes: Attribute {
|
||||
const LAYOUT: AttributesLayout;
|
||||
fn get_attr(&self, index: usize) -> &[u8];
|
||||
fn get_attr_mut(&mut self, index: usize) -> &mut [u8];
|
||||
}
|
||||
|
||||
pub trait Producer<const N: usize, A: Attributes> {
|
||||
fn produce(&self, anchor: StructureAnchor, locator: StructureLocator)
|
||||
-> ProducedNode<N, A>;
|
||||
}
|
||||
|
||||
pub struct ProducedNode<const N: usize, A: Attributes> {
|
||||
pub insertion: InsertionInformation<N>,
|
||||
pub attributes: [A; N * N * N],
|
||||
}
|
||||
```
|
||||
|
||||
The cache-facing side is:
|
||||
|
||||
```rust
|
||||
let layout = CacheLayout::from_attributes(&A::LAYOUT, &[]);
|
||||
let insertion = CacheInsertionData::new(&device, max_entries, &layout);
|
||||
let entries: Vec<InsertionEntry<N>> = ...;
|
||||
insertion.upload(&queue, &entries, &voxels)?;
|
||||
```
|
||||
|
||||
Differences from the legacy `ChunkedProducer` fixture interface:
|
||||
|
||||
- Attributes are abstracted behind `Attributes`, avoiding hardcoded
|
||||
color/normal buffers.
|
||||
- The producer receives a `StructureLocator` rather than depth + coordinates,
|
||||
pushing locator arithmetic into the producer.
|
||||
- `ProducedNode` carries no identity: the request key supplies producer, anchor,
|
||||
parent, and `LocationPage` when the entry is staged.
|
||||
- `anchor` is the content identity. A producer must derive world position from
|
||||
it and never from a table slot.
|
||||
|
||||
### 6.1.1 Identity model
|
||||
|
||||
| Concept | Meaning |
|
||||
|---|---|
|
||||
| `ProducerId` | Which producer fulfils the request. |
|
||||
| `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, 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 Host production helper (not present)
|
||||
|
||||
There is no `crates/vxls-production/src/host_production.rs` in this tree. The
|
||||
worker thread and `RequestQueue` in `crates/vxls/src/main.rs` are the current
|
||||
host-side implementation.
|
||||
|
||||
### 6.3 `crates/vxls-production/src/tree_locator.rs`
|
||||
|
||||
`TreeLocator<N>` (described in §3.2) plus `From<StructureLocator>` /
|
||||
`Into<StructureLocator>` conversions.
|
||||
|
||||
### 6.4 `crates/vxls-production/src/request_queue.rs`
|
||||
|
||||
A bounded, deduplicating, priority-ordered request queue. It is the durable
|
||||
answer to "the cache re-emits the same request every frame".
|
||||
|
||||
Key model:
|
||||
|
||||
```rust
|
||||
RequestKey {
|
||||
producer_id,
|
||||
anchor, // table-defined content identity
|
||||
target: Root | Child { parent: StructureLocator, children_index },
|
||||
}
|
||||
```
|
||||
|
||||
`Root` vs `Child` is explicit, so `(node_id = 0, children_index = 0)` (external
|
||||
root and child 0 of the root) do not collide.
|
||||
|
||||
Properties:
|
||||
|
||||
- `ingest(frame, requests)` refreshes duplicates in place and drops requests
|
||||
unseen for more than `stale_after` frames.
|
||||
- Priority is `(root before child, higher demand, shallower depth)`, with
|
||||
`first_seen` as a tie-breaker so old requests do not starve.
|
||||
- Separate bounds `max_queued`, `max_in_flight`, and `max_ready`. Dispatch
|
||||
preserves `ready.len() + in_flight <= max_ready`, so backpressure is visible
|
||||
before workers run.
|
||||
- New requests only evict queued jobs when strictly more urgent; otherwise they
|
||||
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` 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.
|
||||
- `RequestKey::node_locator::<N>()` derives the locator of the requested node
|
||||
(root or child) from the key, so producers and `LocationPage` agree.
|
||||
- `ReadyItem::insertion_parent()` builds the `InsertionParent` for the insertion
|
||||
batch from the key and the latest `RequestMeta` (which carries `table_slot`).
|
||||
- `ReadyItem::location_page::<N>()` builds the `LocationPage` from the key, not
|
||||
from the producer payload or the table slot.
|
||||
- `ReadyItem::insertion_entry()` combines the payload's `InsertionInformation`
|
||||
with those two into a cache-facing `InsertionEntry`.
|
||||
|
||||
The queue is unit-tested without a GPU (`cargo test -p vxls-production request_queue`).
|
||||
|
||||
### 6.5 `crates/vxls/src/sparse_tree.rs`
|
||||
|
||||
A CPU `NTree<N>` prototype backed by a `HashMap<TreeLocator<N>, NTreeNode>`,
|
||||
with `constant`, `get`, `set`, array conversion, and explicit-structure export.
|
||||
It also provides the packed `Color` helper and PLY loading. Useful for
|
||||
understanding the tree and used by the playground producers, not by the renderer.
|
||||
|
||||
### 6.6 `crates/vxls/src/gi_pipeline.rs` + `sparse_set.rs`
|
||||
|
||||
Compiles (declared in `main.rs`) but `VoxelGiPipeline` is never instantiated. It
|
||||
adds `DontTouch` attributes for a leaf list and radiance, and a `GpuSparseSet`
|
||||
for resident leaves. It is a sketch of a future GI integration, not working
|
||||
code.
|
||||
|
||||
---
|
||||
|
||||
## 7. Adding a producer
|
||||
|
||||
Minimum viable path with the current demo interface:
|
||||
|
||||
1. Implement the durable `vxls_production::Producer<N, A>`:
|
||||
|
||||
```rust
|
||||
impl Producer<4, MyAttributes> for MyProducer {
|
||||
fn produce(
|
||||
&self,
|
||||
anchor: StructureAnchor,
|
||||
locator: StructureLocator,
|
||||
) -> ProducedNode<4, MyAttributes> { ... }
|
||||
}
|
||||
```
|
||||
|
||||
2. Decode `locator` with `TreeLocator::<N>::from` if the producer needs node
|
||||
coordinates.
|
||||
3. For each child of the requested node, compute:
|
||||
- `subdividable`: can this child be refined?
|
||||
- `occupied`: can it produce a hit?
|
||||
- attribute words in the cache layout order.
|
||||
4. Return a `ProducedNode` with `InsertionInformation` and the attribute array.
|
||||
Do not emit a `LocationPage` or `InsertionParent`; those are derived from the
|
||||
`RequestKey` when the result is drained.
|
||||
5. Replace `TreeProducer` in `crates/vxls/src/main.rs` with the new producer.
|
||||
6. Keep `CacheInsertionData::new` capacity at least as large as the maximum
|
||||
number of entries the queue can drain in one frame.
|
||||
|
||||
A production-ready producer should additionally:
|
||||
|
||||
- use the `Attributes` abstraction so attributes are not hardcoded;
|
||||
- run through `RequestQueue` on a worker thread and stream results across frames
|
||||
without blocking the render loop;
|
||||
- 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 `ProducerId` and anchors.
|
||||
|
||||
---
|
||||
|
||||
## 8. Known issues
|
||||
|
||||
| Symptom | Location | Impact | Confidence |
|
||||
|---|---|---|---|
|
||||
| The host request path busy-waits on `device.poll`; production blocks the render thread. | `crates/vxls/src/main.rs` (`loop { ... poll ... }` in `render`) | No overlap, frame stalls, no streaming. | High |
|
||||
| The demo driver is still synchronous: it downloads, produces, and inserts in one frame. | `crates/vxls/src/main.rs` (`render`), `crates/vxls-production/src/request_queue.rs` | No overlap between production and rendering in the demo. The queue is on the live path but the scheduler is still frame-blocking. | High |
|
||||
| If `destination_indices[i] == 0xFFFFFFFF`, the producer is not told; the cache will re-request the node later. | `insertion.wgsl`, host callback | Wasted work and repeated requests; no metric for dropped pages. | High |
|
||||
| The external table insertion consumes the same eviction list as the cache insertion; if it inserts fewer roots than requested, the table has missing entries with no host-visible signal. | `VoxelCache::insert`, `fixed_table/insertion.wgsl` | Silent holes in the world. | Medium |
|
||||
| `TerrainGenerator` uses hardcoded mip factor 8 and `depth <= 2` special cases. | `crates/vxls/src/producers.rs` | Not robust to different chunk resolutions. | High |
|
||||
| `BallGenerator` implements the local playground `producers::Producer<N>` trait, not the durable `vxls_production::Producer`. | `crates/vxls/src/producers.rs` | Copying it as a template will not work with the current driver. | High |
|
||||
| The worker thread is owned by `main.rs` rather than `vxls-production`, so queue scheduling and producers are not reusable yet. | `crates/vxls/src/main.rs` | Durable producer types exist, but the host service around them does not. | Medium |
|
||||
+633
@@ -0,0 +1,633 @@
|
||||
# Shaders
|
||||
|
||||
The project uses two shader languages for two different jobs:
|
||||
|
||||
| | Slang (`shaders/*.slang`) | WGSL (`crates/vxls-voxel-cache/src/shaders/*.wgsl`) |
|
||||
|---|---|---|
|
||||
| Used for | Rendering / ray marching | Cache management passes |
|
||||
| Compilation | Offline via `slangc`, SPIR-V checked in | Runtime via wgpu |
|
||||
| Specialisation | Compile-time types and generics | Runtime string concatenation + generated `const`s |
|
||||
| Embedded with | `include_spirv_source!` / `include_spirv!` | `include_str!` into a generated module |
|
||||
| Rust entry point | `main.rs` passthrough shader modules | `pipelines.rs`, `requests.rs`, `eviction.rs`, `tables.rs` |
|
||||
|
||||
> **Temporary code:** bind-group and pipeline setup in `crates/vxls/src/main.rs` is part of
|
||||
> the playground driver. Read shader contracts from the Rust cache/table
|
||||
> wrappers (`crates/vxls-voxel-cache/src/*`) and this document, not from `main.rs` alone.
|
||||
|
||||
---
|
||||
|
||||
## 1. Slang build model
|
||||
|
||||
`shaders/Makefile`:
|
||||
|
||||
```make
|
||||
all: clean voxel.spv compaction.spv gi.spv radix_sort.spv radix_reduce.spv
|
||||
|
||||
clean:
|
||||
rm -f out/*.spv
|
||||
|
||||
%.spv: %.slang
|
||||
slangc $< -O3 -g0 -fp-mode fast -emit-spirv-directly -fvk-use-entrypoint-name -target spirv -o out/$@
|
||||
```
|
||||
|
||||
Build with:
|
||||
|
||||
```sh
|
||||
make -C shaders
|
||||
```
|
||||
|
||||
Generated files live in `shaders/out/` and are **checked in**. Do not hand-edit
|
||||
them; edit the `.slang` source and rebuild.
|
||||
|
||||
### How SPIR-V reaches wgpu
|
||||
|
||||
- Rendering shaders are loaded with
|
||||
`create_shader_module_passthrough` (requires `PASSTHROUGH_SHADERS`), which
|
||||
avoids wgpu's shader validation and requires explicit entry-point workgroup
|
||||
sizes:
|
||||
- `shaders/out/voxel.spv` → entry `ray_march_compute`, workgroup `(16,16,1)`
|
||||
- `shaders/out/gi.spv` → entry `gi`, workgroup `(16,16,1)`
|
||||
- Utility shaders are loaded with ordinary `include_spirv!`:
|
||||
- `shaders/out/radix_sort.spv` in `crates/vxls-gpu/src/radix_sort.rs`
|
||||
- `shaders/out/compaction.spv` in `crates/vxls-gpu/src/buffer_compactor.rs`
|
||||
- `radix_reduce.spv` is built by the Makefile but currently not referenced by
|
||||
Rust source.
|
||||
|
||||
The declared entry-point name must match `-fvk-use-entrypoint-name`; otherwise
|
||||
module creation fails.
|
||||
|
||||
---
|
||||
|
||||
## 2. Slang module graph
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
V[voxel.slang<br/>ray_march_compute] --> VC[voxel_cache.slang<br/>VoxelCacheTracer]
|
||||
V --> VT[voxel_tracing.slang<br/>Tracer / interfaces]
|
||||
V --> BVH[bvh.slang<br/>Bvh]
|
||||
V --> TST[toroidal_structure_table.slang<br/>ToroidalStructureTableTracer]
|
||||
V --> LOD[lod_policies.slang<br/>PixelFootprintLod]
|
||||
V -. unused import .-> FST[fixed_structure_table.slang]
|
||||
G[gi.slang<br/>AO pass] --> VC
|
||||
G --> VT
|
||||
G --> BVH
|
||||
G --> LOD
|
||||
VC --> VT
|
||||
TST --> VT
|
||||
TST --> VC
|
||||
BVH --> VT
|
||||
BVH --> VC
|
||||
```
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `voxel_tracing.slang` | `Ray`, `Cell`, `Hit`, `TraceSettings`, `ITraceStack`/`LocalTraceStack`; `IStructure`, `IVoxelCache`, `ILodPolicy`; generic `Tracer`. |
|
||||
| `voxel_cache.slang` | `StructurePointer`, `StructureElement`, `VoxelCacheParameters`, `VoxelCacheTracer`, `ColorHit`, attribute helpers. |
|
||||
| `bvh.slang` | `Bvh` structure: restart-trail traversal, object transforms, bounded distance (`max_t`) for secondary rays. |
|
||||
| `toroidal_structure_table.slang` | Dense wrapped chunk grid; produces cache entry cells. |
|
||||
| `lod_policies.slang` | `PixelFootprintLod`. |
|
||||
| `fixed_structure_table.slang` | Non-wrapping chunk grid; imported by `voxel.slang` but not used. |
|
||||
| `voxel.slang` | Push constants, G-buffer bindings, `ray_march_compute`. |
|
||||
| `gi.slang` | Screen-space AO: reads the world-space G-buffer and traces short hemisphere rays with the shared tracer. |
|
||||
| `compaction.slang`, `radix_sort.slang`, `radix_reduce.slang` | GPU utility kernels. |
|
||||
|
||||
---
|
||||
|
||||
## 3. Bindings and immediates (rendering)
|
||||
|
||||
`voxel.slang` declares:
|
||||
|
||||
```slang
|
||||
[[vk::push_constant]] uniform PushConstants constants;
|
||||
|
||||
ParameterBlock<VoxelCacheParameters<2>> cache_parameters; // group 0
|
||||
ParameterBlock<ToroidalStructureTable> table_parameters; // group 1
|
||||
|
||||
[[vk::binding(0,2)]] WTexture2D<float4> gbuffer_position; // group 2
|
||||
[[vk::binding(1,2)]] WTexture2D<float4> gbuffer_albedo;
|
||||
[[vk::binding(2,2)]] WTexture2D<float4> gbuffer_normal;
|
||||
```
|
||||
|
||||
### Group 0 — cache (`VoxelCacheParameters<N>`)
|
||||
|
||||
| Binding | Contents |
|
||||
|---|---|
|
||||
| 0 | `structure_pool`: pointer pages (`StructureElement`) |
|
||||
| 1 | `request_buffer`: per-child atomic counters (`RequestBufferElement`) |
|
||||
| 2 | `usage_buffer`: per-page timestamp |
|
||||
| 3 | `attributes_pool[N]`: attribute pages (N = attribute count = 2 here) |
|
||||
|
||||
### Group 1 — structure table
|
||||
|
||||
| Binding | Contents |
|
||||
|---|---|
|
||||
| 0 | `structure_table_pointer`: one `StructurePointer` per chunk slot |
|
||||
| 1 | `structure_table_request_buffer`: one atomic counter per slot |
|
||||
|
||||
### Group 2 — G-buffers
|
||||
|
||||
Three `rgba32f` storage textures written by the main pass. Position and normal
|
||||
are **world space**: the tracer maps the cache's unit-cube hit through
|
||||
`Cell::cube_to_world` / `Cell::world_origin`, and rotates local attribute
|
||||
normals with `Hit::normal_to_world`. `gi.slang` binds target + position +
|
||||
albedo + normal and uses the world-space position/normal as AO ray origins.
|
||||
|
||||
### Push constants / immediates
|
||||
|
||||
```slang
|
||||
struct PushConstants {
|
||||
float4x4 view_proj;
|
||||
float3 cam_pos;
|
||||
uint32_t frame_timestamp;
|
||||
uint32_t width;
|
||||
uint32_t height;
|
||||
uint32_t chunk_width;
|
||||
uint32_t chunk_height;
|
||||
uint32_t chunk_alt;
|
||||
}
|
||||
```
|
||||
|
||||
Rust passes `camera.view_proj().inverse()` in `view_proj`, while the shader does
|
||||
`mul(constants.view_proj, ndc)`. The pair reconstructs a world-space ray
|
||||
direction. `chunk_*` feeds the toroidal table extent; in the demo all three are
|
||||
20, which hides an ordering inconsistency in the naming (Rust passes
|
||||
`(width, alt, height)` to the table but `(width, height, alt)` to the shader).
|
||||
|
||||
`frame_timestamp` must equal `VoxelCache::current_timestamp()` when the render
|
||||
pass is recorded; it is used both for usage reporting and for deciding which
|
||||
pages were touched this frame.
|
||||
|
||||
---
|
||||
|
||||
## 4. Tracing interfaces
|
||||
|
||||
`voxel_tracing.slang` defines the composition pattern:
|
||||
|
||||
```slang
|
||||
public interface IStructure {
|
||||
associatedtype Cursor;
|
||||
Cursor begin(Ray worldRay);
|
||||
bool next(inout Cursor c, out Cell cell);
|
||||
}
|
||||
|
||||
public interface IVoxelCache {
|
||||
bool trace<L : ILodPolicy, St : ITraceStack>(
|
||||
uint32_t root, Ray r, L lod, TraceSettings settings,
|
||||
float offset_t, inout St stack, out Hit v);
|
||||
}
|
||||
|
||||
public interface ILodPolicy {
|
||||
bool shouldStop(float t, float nodeSize);
|
||||
}
|
||||
|
||||
public struct Tracer<S : IStructure, C : IVoxelCache, L : ILodPolicy> {
|
||||
S structure; C cache; L lod;
|
||||
bool trace<St : ITraceStack>(
|
||||
out Hit h, Ray r, TraceSettings settings, inout St stack);
|
||||
}
|
||||
```
|
||||
|
||||
`Tracer::trace` walks structure cells and asks the cache to trace each one. Any
|
||||
interface can be replaced without touching the others; this is the main
|
||||
extensibility point on the render side.
|
||||
|
||||
`TraceSettings` is the per-ray policy shared by primary and secondary rays:
|
||||
|
||||
```slang
|
||||
public struct TraceSettings {
|
||||
float t_min; // start of the search interval
|
||||
float t_max; // end (exclusive); FLT_MAX for unbounded
|
||||
uint32_t max_cells; // structure cells visited
|
||||
uint32_t max_steps; // DDA iterations inside one cache cell
|
||||
bool any_hit; // first acceptable hit instead of nearest
|
||||
bool report_usage; // refresh LRU timestamps
|
||||
bool report_requests; // emit cache detail requests
|
||||
}
|
||||
```
|
||||
|
||||
The same tracer therefore serves the primary pass (closest hit, camera LOD,
|
||||
usage + requests) and shadow/visibility rays (`any_hit`, a finite `t_max`,
|
||||
requests off) without a separate code path.
|
||||
|
||||
---
|
||||
|
||||
## 5. `VoxelCacheTracer` algorithm
|
||||
|
||||
`voxel_cache.slang`. The tracer descends a 4-ary tree encoded by float mantissas.
|
||||
|
||||
### 5.1 Ray mirroring
|
||||
|
||||
To make the DDA always move toward increasing coordinates, the ray is reflected
|
||||
into the positive octant:
|
||||
|
||||
1. `r.origin += 1` and clamp to `[1, 2)`.
|
||||
2. For each axis with positive direction, flip the mantissa bits
|
||||
(`asuint(origin) ^ 0x007fffff`).
|
||||
3. Build `child_mirror`, which flips the 2-bit child coordinate per axis.
|
||||
|
||||
Hit locations are mirrored back before being returned.
|
||||
|
||||
### 5.2 Tree levels
|
||||
|
||||
```slang
|
||||
uint32_t scale_exp = 23 - 2; // root level
|
||||
uint32_t child_index = get_children_index(pos, scale_exp) ^ child_mirror;
|
||||
```
|
||||
|
||||
`get_children_index` extracts two mantissa bits:
|
||||
|
||||
```slang
|
||||
cell_position = (asuint(position) >> scale_exp) & 3;
|
||||
child_index = x + y*4 + z*16;
|
||||
```
|
||||
|
||||
Each subdivision does `scale_exp -= 2`. `node_size(scale_exp)` reconstructs the
|
||||
world-space node size from the exponent/mantissa.
|
||||
|
||||
### 5.3 Main loop
|
||||
|
||||
Per iteration (`settings.max_steps`, 500 for primary rays):
|
||||
|
||||
1. If `offset_t + t >= settings.t_max`, stop: the rest of the ray is outside the
|
||||
requested interval.
|
||||
2. Read the current child pointer.
|
||||
3. **Descend** while the pointer is `subdivided_valid()` (bits 31 and 30 set)
|
||||
and the LOD policy says the node is still too large:
|
||||
- `scale_exp -= 2`, `current_node_index = pointer()`, push onto the
|
||||
trace stack, report usage when `settings.report_usage`.
|
||||
4. **Request** if `settings.report_requests`, the LOD still wants detail, the
|
||||
pointer is subdividable, and it is not resident:
|
||||
`requests[current_node_index][child_index] += 1`.
|
||||
5. **Hit test** using the occupancy mask and `IVoxelHit::shouldHit`.
|
||||
6. **DDA step**:
|
||||
- If the coarser 2×2×2 neighbourhood is empty
|
||||
(`(occupancy >> (child_index & 0b101010)) & 0x00330033 == 0`), advance one
|
||||
extra level (`adv_scale_exp++`) to skip empty space.
|
||||
- Compute the next face intersection from the mirrored ray, step `pos` to the
|
||||
face (clamped by the neighbour maximum).
|
||||
- Find the most common ancestor of old and new positions via XOR and
|
||||
`firstbithigh`, then restore `scale_exp` and pop the stack to that level.
|
||||
|
||||
`Tracer::trace` bounds the structure walk with `settings.max_cells`. It skips
|
||||
cells that start at or beyond `t_max` or (for closest-hit traces) the best hit
|
||||
so far. Structure cells are not distance ordered, so it never breaks on those
|
||||
conditions.
|
||||
|
||||
### 5.4 Stack
|
||||
|
||||
```slang
|
||||
public interface ITraceStack {
|
||||
uint32_t get(uint32_t depth);
|
||||
[mutating] void set(uint32_t depth, uint32_t node);
|
||||
}
|
||||
|
||||
public struct LocalTraceStack : ITraceStack {
|
||||
public uint32_t entries[5];
|
||||
// get/set index entries[depth]
|
||||
}
|
||||
```
|
||||
|
||||
The stack is **caller-owned**, so the tracer has no module-scope storage and no
|
||||
dependency on the dispatch shape. `voxel.slang` keeps one per thread as a local
|
||||
(`LocalTraceStack stack;`), which the driver can promote to registers or spill
|
||||
to per-thread scratch. If the primary pass regresses, the front-end can switch
|
||||
to groupshared storage without touching the trace core: implement `ITraceStack`
|
||||
over a module-scope groupshared array plus a per-thread base slot, and pass that
|
||||
handle instead.
|
||||
|
||||
```slang
|
||||
groupshared uint32_t trace_stacks[5 * 256];
|
||||
|
||||
public struct GroupsharedTraceStack : ITraceStack {
|
||||
public uint32_t base; // slot * 5
|
||||
|
||||
public uint32_t get(uint32_t depth) { return trace_stacks[base + depth]; }
|
||||
[mutating]
|
||||
public void set(uint32_t depth, uint32_t node) { trace_stacks[base + depth] = node; }
|
||||
}
|
||||
|
||||
// entry point
|
||||
GroupsharedTraceStack stack;
|
||||
stack.base = (local_location.x + local_location.y * 16) * 5;
|
||||
```
|
||||
|
||||
Both variants compile from the same primary entry point; only the implementation
|
||||
type and its construction change.
|
||||
|
||||
The index `depth = 10 - scale_exp / 2` hardcodes the supported trace depth. With
|
||||
`N = 4` and `chunk_power = 5`, the deepest level used is 5, so the stack must
|
||||
hold entries for levels 1..5. Changing the branching factor or chunk depth
|
||||
requires changing both the stack size and this index formula.
|
||||
|
||||
### 5.5 Hit test
|
||||
|
||||
`voxel_cache.slang` defines `ColorHit<2>` (shared by the primary and AO passes):
|
||||
|
||||
```slang
|
||||
bool shouldHit(VoxelCacheParameters<N> cache, uint32_t node_index, uint32_t child_index) {
|
||||
return ByteColor(cache.attributes_pool[0][node_index * 64 + child_index]).byte_a != 0;
|
||||
}
|
||||
```
|
||||
|
||||
So a child is a hit when the alpha byte of its packed color is non-zero. The hit
|
||||
result exposes `node_index`, `child_index`, and a mirrored-back
|
||||
`hit_location`.
|
||||
|
||||
---
|
||||
|
||||
## 6. Structure traversal
|
||||
|
||||
### 6.1 Toroidal tracer
|
||||
|
||||
`toroidal_structure_table.slang` walks unit cells (one cell per structure slot):
|
||||
|
||||
- `begin`: `current_voxel = floor(origin)`, `offset = current_voxel - extent/2`.
|
||||
It initialises the 3D DDA `t` values from the ray direction.
|
||||
- `next`, while the current cell is inside the block:
|
||||
- compute wrapped local coordinates with `imod`;
|
||||
- compute the slot index
|
||||
`x + z*extent.x + y*extent.x*extent.z`;
|
||||
- if the slot pointer is resident, emit a `Cell` with
|
||||
`local_ray.origin = position - current_voxel` (fractional position inside the
|
||||
unit cell), and return it;
|
||||
- if the slot is subdividable but not resident, increment its request counter;
|
||||
- step the DDA to the next cell.
|
||||
|
||||
In shader space one cell is a unit cube. The producer decides how many voxels
|
||||
that cube contains (`chunk_power = 5` means `4^5 = 1024` voxels per axis in the
|
||||
demo). The cache tracer subdivides the unit cube; it never sees the producer's
|
||||
voxel count directly.
|
||||
|
||||
The `min_mask` + `sign(direction)` stepping means the traversal advances one
|
||||
cell per axis crossing; it does not skip empty chunks based on occupancy.
|
||||
|
||||
### 6.2 `fixed_structure_table.slang`
|
||||
|
||||
A non-wrapping version of the same idea. It is imported by `voxel.slang` but not
|
||||
instantiated; the Rust `FixedStructureTable` is used through the toroidal
|
||||
wrapper instead.
|
||||
|
||||
### 6.3 `bvh.slang` (active demo path)
|
||||
|
||||
`Bvh` walks a top-level BVH of transformed unit-cube objects and emits a `Cell`
|
||||
for each object the ray can enter. Traversal uses a restart trail instead of a
|
||||
stack, so the cells are **not** distance ordered (the tracer accumulates the
|
||||
nearest hit and skips rather than breaks).
|
||||
|
||||
`Bvh::max_t` bounds the traversal: nodes and objects whose entry distance is
|
||||
beyond it are culled. Primary rays set `FLT_MAX`; secondary passes (the AO pass)
|
||||
set their ray length, which avoids walking the infinite ray through every object
|
||||
behind the surface. The field assumes rigid rotation/translation transforms, so
|
||||
local and world distances match.
|
||||
|
||||
Each emitted cell carries `world_origin` and `cube_to_world`; `Tracer::trace`
|
||||
uses them to turn the cache's unit-cube hit into a world-space `Hit` and to
|
||||
rotate local attribute normals.
|
||||
|
||||
---
|
||||
|
||||
## 7. LOD
|
||||
|
||||
```slang
|
||||
struct PixelFootprintLod : ILodPolicy {
|
||||
float pixelAngle; // angular size of one pixel (radians)
|
||||
float pixelThreshold; // pixels a node may cover before we stop
|
||||
float coneRadius0; // footprint at t = 0
|
||||
|
||||
float footprint(float t) { return coneRadius0 + t * pixelAngle; }
|
||||
|
||||
bool shouldStop(float t, float nodeSize) {
|
||||
return nodeSize <= footprint(t) * pixelThreshold;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`create(fovYRadians, imageHeightPixels, pixelThreshold, coneRadius0)` computes
|
||||
`pixelAngle = 2*tan(fovY/2)/imageHeightPixels`.
|
||||
|
||||
Demo call:
|
||||
|
||||
```slang
|
||||
PixelFootprintLod lod = PixelFootprintLod.create((100.f * 3.14f) / 180.f, 1080.f, 2.f);
|
||||
```
|
||||
|
||||
Interpretation:
|
||||
|
||||
- `pixelThreshold = 1.0` → stop when a node is about one pixel wide.
|
||||
- `2.0` (the demo) → stop when a node is two pixels wide, i.e. coarser/faster.
|
||||
- `coneRadius0 = 0` is a pinhole camera; secondary rays should inherit a
|
||||
non-zero footprint from their parent bounce.
|
||||
|
||||
---
|
||||
|
||||
## 8. Main render entry point
|
||||
|
||||
`voxel.slang`:
|
||||
|
||||
```slang
|
||||
[shader("compute")]
|
||||
[numthreads(16,16,1)]
|
||||
void ray_march_compute(uint32_t3 location : SV_DispatchThreadID)
|
||||
```
|
||||
|
||||
1. Bounds-check against `constants.width/height`.
|
||||
2. Build a `VoxelCacheTracer<2, ColorHit<2>>` with the frame timestamp.
|
||||
3. Fill in `TraceSettings` (unbounded closest-hit, 500 DDA steps, usage and
|
||||
requests on) and declare the per-ray `LocalTraceStack`.
|
||||
4. Build a `Tracer` (currently over `Bvh`) and call `trace` with the stack.
|
||||
5. On hit, store the world-space hit position, the world-space normal
|
||||
(`Hit::normal_to_world` rotates the local attribute normal), and albedo.
|
||||
6. On miss, store zero albedo.
|
||||
|
||||
`fetch_color` and `fetch_normal` hardcode the demo layout:
|
||||
|
||||
```slang
|
||||
attributes_pool[0][node * 64 + child] // color
|
||||
attributes_pool[1][node * 64*3 + child*3 + 0..2] // normal
|
||||
```
|
||||
|
||||
This is the most important cross-language contract in the repo. If you reorder
|
||||
or resize attributes in `CacheLayout`, update these functions and `ColorHit`.
|
||||
|
||||
### 8.1 AO pass (`gi.slang`)
|
||||
|
||||
The AO pass is the secondary-ray smoke test. It reuses the same tracer, hit
|
||||
predicate, structure (`Bvh`) and LOD policy as the primary pass:
|
||||
|
||||
```slang
|
||||
TraceSettings settings;
|
||||
settings.t_min = 0.01; // skip the surface itself
|
||||
settings.t_max = 0.25; // short, local occlusion
|
||||
settings.max_cells = 64;
|
||||
settings.max_steps = 64;
|
||||
settings.any_hit = true; // visibility, not nearest
|
||||
settings.report_usage = true;
|
||||
settings.report_requests = false; // secondaries do not drive detail
|
||||
```
|
||||
|
||||
Per pixel it reconstructs a world-space origin/normal from the G-buffer, then
|
||||
traces four cosine-weighted hemisphere samples rotated by a per-pixel hash. The
|
||||
AO term is `1 - occluded / 4`, softened before multiplying albedo. The pass is
|
||||
incoherent by nature; the caller-owned `LocalTraceStack` is reused sequentially
|
||||
across the four rays, which is exactly why the stack is not tied to the
|
||||
workgroup shape.
|
||||
|
||||
---
|
||||
|
||||
## 9. WGSL cache shaders
|
||||
|
||||
### 9.1 Composition
|
||||
|
||||
Cache management shaders are assembled at runtime from concatenated strings:
|
||||
|
||||
```text
|
||||
common.wgsl // structs, pointer helpers, enable wgpu_binding_array
|
||||
<generated constants> // CHILDREN_COUNT, PAGE_COUNT, attribute metadata
|
||||
cache_common.wgsl // PointerPage, InsertionInformation, index helpers
|
||||
<pass file> // entry point(s)
|
||||
```
|
||||
|
||||
`programmatic_common_wgsl!` in `pipelines.rs` generates:
|
||||
|
||||
```wgsl
|
||||
const CHILDREN_COUNT: u32 = 64; // N*N*N
|
||||
const PAGE_COUNT: u32 = 150000;
|
||||
const ATTRIBUTE_COUNT: u32 = 2;
|
||||
const ATTRIBUTE_WORD_COUNTS: array<u32,2> = ...;
|
||||
const ATTRIBUTE_COPY: array<bool,2> = ...;
|
||||
```
|
||||
|
||||
Structure-table shaders use a simpler concatenation:
|
||||
`common.wgsl` + pass file.
|
||||
|
||||
`common.wgsl` starts with `enable wgpu_binding_array;` and defines the shared
|
||||
`CacheIndex`, `StructureAnchor`/`anchor_eq`, `RequestInformation`, `RequestMeta`,
|
||||
`InsertionParent`, `AttributeArray`, `LocationPage`, and child-pointer helpers so
|
||||
the Rust and WGSL sides share names. The wire structs carry the anchor and the
|
||||
external table slot; see [`voxel-cache.md`](./voxel-cache.md#22-location-page).
|
||||
|
||||
Structure-table shaders that emit requests or validate/insert roots bind a third
|
||||
group:
|
||||
|
||||
- group 0 — table pointers, or request handler;
|
||||
- group 1 — request buffer, or insertion data;
|
||||
- group 2 — slot metadata: binding 0 `fixed_table_anchors`.
|
||||
|
||||
### 9.2 WGSL modules and entry points
|
||||
|
||||
| File | Entry point(s) | Purpose |
|
||||
|---|---|---|
|
||||
| `shaders/requests.wgsl` | `reset_requests` | Zero all per-child request counters. |
|
||||
| `shaders/gather_requests.wgsl` | `gather_requests` | Copy selected top-K counts/indices into radix key/value buffers. |
|
||||
| `shaders/write_requests.wgsl` | `write_requests` | Convert sorted flat indices into `RequestInformation`/`RequestMeta`. |
|
||||
| `shaders/insertion.wgsl` | `validate_internal`, `insertion`, `consume` | Validate/compact internal entries, recycle pages, write pointer/location/depth/attributes, advance consumed count. |
|
||||
| `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 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. |
|
||||
|
||||
All compute workgroups are `(256,1,1)` except `toroidal_structure.wgsl`, which
|
||||
uses `(4,4,4)`.
|
||||
|
||||
### 9.3 Bind-group conventions
|
||||
|
||||
Cache shaders consistently bind:
|
||||
|
||||
- group 0 — cache structure (pointer, location, depth pages), except
|
||||
`insertion.wgsl` where group 0 is attributes and group 1 is structure;
|
||||
- group 1 — request handler, evictor, insertion data, or request buffer
|
||||
depending on the pass;
|
||||
- group 2 — request buffer, insertion data, or scratch buffer;
|
||||
- group 3 — evictor or insertion data;
|
||||
- group 4 — inserted-count atomic.
|
||||
|
||||
The authoritative table is in [`voxel-cache.md`](./voxel-cache.md#9-bind-groups).
|
||||
|
||||
### 9.4 Immediates
|
||||
|
||||
WGSL passes use `var<immediate>` for a small `u32`:
|
||||
|
||||
- `insertion.wgsl`: `new_timestamp` (the frame timestamp assigned to new pages).
|
||||
- `invalidation.wgsl`: `new_timestamp` (marks which pages are dirty this pass).
|
||||
- `toroidal_structure.wgsl`: a struct of `extent`, `previous_offset`, `offset`.
|
||||
|
||||
Rust sets these with `pass.set_immediates(0, ...)`; the pipeline layouts declare
|
||||
`immediate_size` accordingly.
|
||||
|
||||
### 9.5 Attribute copy contract
|
||||
|
||||
`insertion.wgsl` copies attributes for each page slot:
|
||||
|
||||
```wgsl
|
||||
for (attribute_index in 0..ATTRIBUTE_COUNT) {
|
||||
if (!ATTRIBUTE_COPY[attribute_index]) { continue; }
|
||||
page_stride = CHILDREN_COUNT * ATTRIBUTE_WORD_COUNTS[attribute_index];
|
||||
dest_offset = page_stride * page_index;
|
||||
src_offset = page_stride * insertion_slot;
|
||||
for (word in 0..page_stride) {
|
||||
cache_attributes[attribute_index].values[dest_offset + word]
|
||||
= insertion_data_attributes[attribute_index].values[src_offset + word];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
So attribute buffers are always `page_count * 64 * word_count` words, and the
|
||||
insertion batch is indexed by request slot.
|
||||
|
||||
---
|
||||
|
||||
## 10. Changing shaders: checklist
|
||||
|
||||
### Adding or resizing a cache attribute
|
||||
|
||||
1. Add it to `CacheLayout` in the caller (order matters).
|
||||
2. If the renderer reads it, update `VoxelCacheParameters` usage and
|
||||
`fetch_*` functions in `voxel_cache.slang` / `voxel.slang`.
|
||||
3. Update `ColorHit` if the hit criterion changes.
|
||||
4. Check the `VoxelCacheParameters<N>` attribute count `N` (not the branching
|
||||
factor).
|
||||
5. Rebuild Slang if you changed `.slang` files.
|
||||
|
||||
### Changing the branching factor
|
||||
|
||||
Do not do this casually. Required changes include:
|
||||
|
||||
- `VoxelCache<N>` / producer `N` and all 64-element assumptions;
|
||||
- `get_children_index` (`*4`, `*16`) and the child-mirror shifts;
|
||||
- `LocalTraceStack` size and `10 - scale_exp/2` indexing;
|
||||
- `StructureElement.pointers[64]`;
|
||||
- `fetch_color`/`fetch_normal` strides (`*64`, `*64*3`);
|
||||
- generated WGSL `CHILDREN_COUNT`;
|
||||
- the `0b101010` / `0x00330033` empty-neighbourhood test.
|
||||
|
||||
### Rebuilding
|
||||
|
||||
```sh
|
||||
make -C shaders # regenerates shaders/out/*.spv
|
||||
cargo run -p vxls # wgpu embeds the checked-in SPIR-V at compile time
|
||||
```
|
||||
|
||||
Because SPIR-V is embedded with `include_*!`, changing `.spv` requires a Rust
|
||||
rebuild. CI or fresh checkouts must either commit the `.spv` files or run the
|
||||
Makefile before building.
|
||||
|
||||
---
|
||||
|
||||
## 11. Known issues
|
||||
|
||||
| Symptom | Location | Impact | Confidence |
|
||||
|---|---|---|---|
|
||||
| `voxel.slang` imports `fixed_structure_table` but never uses it. | `shaders/voxel.slang:3` | Misleads readers; increases compile surface. | High |
|
||||
| `gi.slang` is a simple AO pass, not a full GI solution (no bounces, no denoiser, 4 fixed hemisphere samples). | `shaders/gi.slang` | AO is noisy and view-dependent; it is a secondary-ray smoke test, not production lighting. | High. |
|
||||
| `PixelFootprintLod` demo parameters are hardcoded (100° FOV, 1080 px, threshold 2). | `shaders/voxel.slang:149` | LOD does not follow the window/FOV; resizing the window changes effective LOD. | High |
|
||||
| `LocalTraceStack` size and indexing assume `N = 4` and `chunk_power = 5`. | `shaders/voxel_tracing.slang` (`ITraceStack`/`LocalTraceStack`), `shaders/voxel_cache.slang` | Branching/depth changes silently break tracing. | High |
|
||||
| `fetch_color` / `fetch_normal` hardcode stride 64 and attribute indices 0/1. | `shaders/voxel.slang:68-79` | Cache layout changes break rendering with no compile-time error. | High |
|
||||
| The child-index and child-mirror arithmetic hardcodes `4` and `16`. | `shaders/voxel_cache.slang:103-108,154-165` | Not generic over branching factor. | High |
|
||||
| The toroidal tracer walks one unit cell per axis crossing with no empty-chunk skip. | `shaders/toroidal_structure_table.slang:62-101` | Cost scales with traversed grid cells, not just occupied chunks. | Medium |
|
||||
| `chunk_*` immediate field naming/order differs between Rust (`width, height, alt`) and the table extent (`width, alt, height`). | `crates/vxls/src/main.rs:1049-1062`, `shaders/voxel.slang:140` | Hidden because the demo uses 20×20×20; non-cubic extents would mismatch. | Medium |
|
||||
| `radix_reduce.spv` is built and checked in but unused. | `shaders/Makefile:1` | Confusing build artifact. | High |
|
||||
| `voxel.slang` uses `create_shader_module_passthrough`, so wgpu validation is bypassed for the render pipeline. | `crates/vxls/src/main.rs:477-498` | Layout/limit errors appear as driver errors, not friendly validation messages. | Medium |
|
||||
@@ -0,0 +1,803 @@
|
||||
# Voxel cache
|
||||
|
||||
`crates/vxls-voxel-cache/src/lib.rs` and `crates/vxls-voxel-cache/src/*` implement a GPU-resident sparse
|
||||
voxel cache. This document covers the page model, pointer encoding, public API,
|
||||
request/insertion pipelines, eviction, and the structure tables that provide
|
||||
entry points into the cache.
|
||||
|
||||
> **Temporary caller:** the public `VoxelCache` surface is intended API;
|
||||
> `crates/vxls/src/main.rs` is only one caller and currently uses it in a blocking,
|
||||
> single-threaded playground way. See [`pipeline-and-producers.md`](./pipeline-and-producers.md).
|
||||
|
||||
---
|
||||
|
||||
## 1. Model
|
||||
|
||||
- An N-tree with branching factor `N` (`N = 4` in the demo). One node has
|
||||
`N³ = 64` children.
|
||||
- The cache owns a fixed pool of **pages**. A page stores everything about one
|
||||
node: its 64 child pointers, a 64-bit occupancy mask, its location tag, its
|
||||
depth, and the node's attributes. There is **no separate brick pool**.
|
||||
- Pages are recycled. When a page is reused, every pointer that targeted it
|
||||
must be invalidated.
|
||||
- The unit of transfer is a page (one node's worth of data), not a single voxel
|
||||
or a brick.
|
||||
|
||||
Key invariants:
|
||||
|
||||
1. `page_index` must fit in 30 bits (`CachePointer` stores it in bits 0..29).
|
||||
2. An insertion is identified by its own `InsertionParent`, not by its position
|
||||
in a request buffer. Request order and insertion order may differ.
|
||||
3. Slang consumers assume a child count of 64 and the demo attribute order.
|
||||
Changing the cache layout requires editing the Slang shaders.
|
||||
4. A page's `LocationPage` must describe the node the page represents, not its
|
||||
parent.
|
||||
|
||||
---
|
||||
|
||||
## 2. Page layouts
|
||||
|
||||
### 2.1 Pointer page
|
||||
|
||||
```text
|
||||
struct PointerPage { // WGSL (cache_common.wgsl)
|
||||
occupancy_low: u32,
|
||||
occupancy_high: u32,
|
||||
pointers: array<u32, 64>,
|
||||
}
|
||||
```
|
||||
|
||||
```rust
|
||||
struct StructurePage<N> { // Rust (schema.rs), used for sizing only
|
||||
occupancy_mask: u64,
|
||||
pointers: [CachePointer; N*N*N],
|
||||
}
|
||||
```
|
||||
|
||||
`occupancy_low`/`occupancy_high` are the low/high halves of the same 64-bit
|
||||
mask as `StructurePage::occupancy_mask` on little-endian hardware. Bit `i` means
|
||||
child `i` is occupied (may produce a hit). The occupancy mask lets the tracer
|
||||
skip empty regions and coalesce DDA steps.
|
||||
|
||||
The Rust `StructurePage` is only used to size `pointer_pages`; the authoritative
|
||||
layout is the WGSL `PointerPage`. Keep them in sync.
|
||||
|
||||
For `N = 4`, a pointer page is `8 + 64*4 = 264` bytes.
|
||||
|
||||
### 2.2 Location page
|
||||
|
||||
```rust
|
||||
struct LocationPage {
|
||||
node_id: u32, // application-defined locator within that structure
|
||||
producer_id: u32, // producer that owns the node
|
||||
anchor: StructureAnchor, // opaque, table-defined content identity
|
||||
}
|
||||
```
|
||||
|
||||
The cache never interprets these values; they are copied from insertion data and
|
||||
returned in requests so the producer knows which node is missing. On the Rust
|
||||
side, `node_id` is a `StructureLocator` encoded through `TreeLocator<N>`. In the
|
||||
demo the active BVH table uses zeroed anchors; the toroidal table variant uses
|
||||
world position plus a version word. The anchor is the structure identity, so
|
||||
child requests inherit it from their parent page and producers never need a
|
||||
host-side identity directory. `LocationPage` is 24 bytes.
|
||||
|
||||
On the Rust side, `node_id` and `producer_id` are the typed
|
||||
`StructureLocator` and `ProducerId` newtypes (both `#[repr(transparent)]`
|
||||
over `u32`), so the on-GPU layout above is unchanged. The same applies to
|
||||
`RequestInformation` and `InsertionParent`.
|
||||
|
||||
### 2.3 Depth page
|
||||
|
||||
```rust
|
||||
struct DepthPage(u32); // u32::MAX = unused
|
||||
```
|
||||
|
||||
- External insertions start at depth 0.
|
||||
- Internal insertions get parent depth + 1.
|
||||
- Unused pages use `u32::MAX`.
|
||||
- Depth is the eviction tie-breaker: pages are sorted deepest-first before the
|
||||
stable timestamp sort, so deeper pages win ties (see §7).
|
||||
|
||||
### 2.4 Attribute pages
|
||||
|
||||
Each attribute is its own buffer:
|
||||
|
||||
```text
|
||||
attribute buffer layout (per attribute)
|
||||
┌────────────────────────────── page 0 ──────────────────────────────┐
|
||||
│ child 0 words[0..W] │ child 1 words[0..W] │ ... │ child 63 words[0..W] │
|
||||
├────────────────────────────── page 1 ──────────────────────────────┤
|
||||
│ ... │
|
||||
└────────────────────────────────────────────────────────────────────┘
|
||||
total size = page_count * 64 * W * 4 bytes
|
||||
```
|
||||
|
||||
An attribute is described by `CacheAttribute`:
|
||||
|
||||
```rust
|
||||
pub struct CacheAttribute {
|
||||
pub label: Option<&'static str>,
|
||||
pub word_count: u32,
|
||||
pub init: CacheAttributeInit,
|
||||
}
|
||||
|
||||
pub enum CacheAttributeInit {
|
||||
External, // copied from insertion data
|
||||
DontTouch, // cache never writes it; application owns it
|
||||
}
|
||||
```
|
||||
|
||||
`CacheLayout::add_attribute` returns the attribute index. The layout generates
|
||||
WGSL constants used by the insertion shader:
|
||||
|
||||
```wgsl
|
||||
const ATTRIBUTE_COUNT: u32 = ...;
|
||||
const ATTRIBUTE_WORD_COUNTS: array<u32, ...> = ...;
|
||||
const ATTRIBUTE_COPY: array<bool, ...> = ...; // true for External
|
||||
```
|
||||
|
||||
The demo layout is:
|
||||
|
||||
| Index | Label | Words | Meaning |
|
||||
|---|---|---:|---|
|
||||
| 0 | `color` | 1 | packed RGBA bytes |
|
||||
| 1 | `normal` | 3 | three floats |
|
||||
|
||||
Slang hardcodes these meanings (color at index 0, normal at index 1, stride 64).
|
||||
`CacheAttributeInit::DontTouch` exists for application-computed data such as GI
|
||||
or a leaf list; `VoxelGiPipeline` intended to use it but is not wired in.
|
||||
|
||||
---
|
||||
|
||||
## 3. Pointer encoding
|
||||
|
||||
```text
|
||||
bit 31 30 29 .. 0
|
||||
┌───────────┬──────────┬────────────────────────┐
|
||||
│subdividable│available │ page pointer (30 bits) │
|
||||
└───────────┴──────────┴────────────────────────┘
|
||||
```
|
||||
|
||||
| Bits 31/30 | Meaning |
|
||||
|---|---|
|
||||
| `0/0` | Leaf: cannot be subdivided. No payload. |
|
||||
| `1/0` | Subdividable but not resident. A request may be issued. |
|
||||
| `1/1` | Subdividable, resident. Bits 0..29 are the page index. |
|
||||
|
||||
Rust API: `CachePointer::new(Option<Option<u32>>)`.
|
||||
|
||||
| Argument | Bits | Meaning |
|
||||
|---|---|---|
|
||||
| `None` | `0x00000000` | leaf / unsubdividable |
|
||||
| `Some(None)` | `0x80000000` | subdividable, unavailable |
|
||||
| `Some(Some(p))` | `0xC0000000 \| p` | subdividable, available at page `p` |
|
||||
|
||||
WGSL helpers in `crates/vxls-voxel-cache/src/shaders/common.wgsl`:
|
||||
|
||||
- `child_pointer_empty(subdivisible)`
|
||||
- `child_pointer_subdivided(pointer)`
|
||||
- `child_pointer_available(pointer)` — checks both bits
|
||||
- `child_pointer_pointer(pointer)` — masks to 30 bits
|
||||
- `child_pointer_make_available(pointer)`
|
||||
|
||||
Child index convention (Rust and WGSL):
|
||||
|
||||
```text
|
||||
child_index = x + 4*y + 16*z // x fastest
|
||||
```
|
||||
|
||||
`pointer_index_to_cache_index(i)` decomposes a flat request index into
|
||||
`page_index = i / 64`, `children_index = i % 64`.
|
||||
|
||||
---
|
||||
|
||||
## 4. Public API
|
||||
|
||||
### 4.1 Construction
|
||||
|
||||
```rust
|
||||
impl<const N: usize> VoxelCache<N>
|
||||
where [(); N * N * N]:,
|
||||
{
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
page_count: usize,
|
||||
max_requests: usize,
|
||||
layout: &CacheLayout,
|
||||
) -> Self;
|
||||
|
||||
pub fn gather_requests(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
request_buffer: &CacheRequestBuffer,
|
||||
);
|
||||
|
||||
pub fn insert(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
insertions: &mut [&mut VoxelCacheInsertion<N>],
|
||||
);
|
||||
|
||||
pub fn current_timestamp(&self) -> u32;
|
||||
pub fn raytrace_bind_group_layout(&self) -> &BindGroupLayout;
|
||||
pub fn raytrace_bind_group(&self) -> &BindGroup;
|
||||
|
||||
// debug
|
||||
pub fn usage_timestamps(&self) -> &wgpu::Buffer;
|
||||
}
|
||||
```
|
||||
|
||||
`page_count` fixes every pool size. `max_requests` fixes the top-K capacity and
|
||||
the request buffer capacity. Both are immutable after construction.
|
||||
|
||||
`N` is the branching factor, so `N=4` means 64 children. This is a different `N`
|
||||
from the `N` in Slang's `VoxelCacheParameters<N>`, which is the **attribute
|
||||
count** (2 in the demo). This naming collision is a common source of confusion.
|
||||
|
||||
### 4.2 Insertion modes
|
||||
|
||||
```rust
|
||||
pub enum VoxelCacheInsertion<'a, const N: usize> {
|
||||
ExternalRequest(&'a CacheInsertionData<N>, &'a mut dyn CacheInvalidable<N>),
|
||||
InternalRequest(&'a CacheInsertionData<N>),
|
||||
}
|
||||
```
|
||||
|
||||
- **External** — bring brand-new pages into the cache (e.g. a structure root).
|
||||
After insertion, the external owner is told to invalidate any of its pointers
|
||||
that targeted recycled pages.
|
||||
- **Internal** — respond to cache-emitted requests. After insertion, the cache
|
||||
writes the new page indices into the requesting pages' child pointers.
|
||||
|
||||
You can pass several insertions in one call; they share one eviction
|
||||
preparation pass and one timestamp.
|
||||
|
||||
`CacheInvalidable` is implemented by the structure tables:
|
||||
|
||||
```rust
|
||||
pub trait CacheInvalidable<const N: usize> {
|
||||
fn invalidate(
|
||||
&mut self,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
cache_evictor: &CacheEvictor,
|
||||
invalid_timestamp: u32,
|
||||
);
|
||||
|
||||
fn validate_insertion(
|
||||
&mut self,
|
||||
device: &Device,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
insertion: &CacheInsertionData<N>,
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
`validate_insertion` runs before page allocation: the table checks that each
|
||||
external root's named slot still carries the same `anchor` and is still
|
||||
`subdividable, unavailable`, then compacts the valid entries. This prevents a
|
||||
stale root response from consuming a page, and lets a slot be reused (toroidal
|
||||
move) without accepting a response for its old world position. The anchor check
|
||||
is what makes host queue invalidation a cancellation hint rather than a
|
||||
correctness requirement.
|
||||
|
||||
### 4.3 Insertion data
|
||||
|
||||
`CacheInsertionData::new(device, max_page_count, layout)` allocates:
|
||||
|
||||
| Buffer | Contents |
|
||||
|---|---|
|
||||
| `page_count` | number of entries in this batch |
|
||||
| `insertion_information` | dense `InsertionInformation<N>` per entry |
|
||||
| `location_pages` | dense `LocationPage` per entry (includes `producer_id`) |
|
||||
| `insertion_parents` | dense `InsertionParent` per entry |
|
||||
| `destination_indices` | reset to `0xFFFFFFFF` by the validation pass; the insertion pass writes the destination page for accepted entries |
|
||||
| `valid_indices` | filled by the validation pass: compacted indices of valid entries |
|
||||
| `valid_count` | `CacheInsertionData::upload` writes `0`; the validation pass fills the amount of valid entries |
|
||||
| attribute buffers | dense per-entry attribute payloads |
|
||||
|
||||
Build the layout from a producer payload with
|
||||
`CacheLayout::from_attributes(&A::LAYOUT, &extras)`: producer attributes become
|
||||
`CacheAttributeInit::External` and come first, `extras` are appended for
|
||||
GPU-only data.
|
||||
|
||||
Upload a complete batch with
|
||||
|
||||
```rust
|
||||
let entries: Vec<InsertionEntry<N>> = ...;
|
||||
insertion.upload(&queue, &entries, &voxels)?;
|
||||
```
|
||||
|
||||
`InsertionEntry` bundles the produced page's `InsertionInformation`, its
|
||||
`InsertionParent`, and its `LocationPage`. `voxels` is a slice in
|
||||
`[entry][child]` order (child order is `x + 4*y + 16*z`) and must contain
|
||||
exactly `entries.len() * N^3` elements. `upload` writes the structure, location,
|
||||
and parent arrays, resets `valid_count`, sets `page_count`, and delegates the
|
||||
attribute payloads to `write_attributes`. It does not pre-fill
|
||||
`destination_indices`; both validation shaders reset every entry they process.
|
||||
|
||||
`write_attributes` validates that `A::LAYOUT` matches the cache layout and writes
|
||||
one buffer per attribute. The `DontTouch` attributes after the producer prefix
|
||||
are left untouched.
|
||||
|
||||
`InsertionInformation<N>` is just `children: [ChildInformation; 64]`, where each
|
||||
`ChildInformation` uses the four-state encoding below.
|
||||
|
||||
```text
|
||||
bit 31 = subdividable
|
||||
bit 30 = occupied
|
||||
```
|
||||
|
||||
`InsertionParent` makes the batch self-describing. It is what replaces the
|
||||
former request-buffer lookup:
|
||||
|
||||
```rust
|
||||
struct InsertionParent {
|
||||
kind: u32, // 0 = internal child, 1 = external root
|
||||
page_index: u32, // parent cache page, or 0xFFFFFFFF for an external root
|
||||
children_index: u32, // child slot in the parent
|
||||
depth: u32, // parent depth, or 0xFFFFFFFF for an external root
|
||||
node_id: u32, // locator of the parent (0 for an external root)
|
||||
producer_id: u32, // producer that owns the parent
|
||||
anchor: StructureAnchor, // content identity of the structure
|
||||
table_slot: u32, // external root placement, 0xFFFFFFFF internally
|
||||
}
|
||||
```
|
||||
|
||||
For an internal insertion, validation requires the parent page's
|
||||
`LocationPage` to match `node_id`, `producer_id`, and `anchor`.
|
||||
For an external insertion, validation requires the slot indexed by `table_slot`
|
||||
to currently hold the parent's `anchor`. `write_pointers.wgsl`
|
||||
repeats the internal check before linking, and the table insertion pass repeats
|
||||
the external check after page allocation.
|
||||
|
||||
A batch no longer has to be ordered like the request buffer. The host may
|
||||
reorder, filter, or produce entries on different frames; the GPU validates each
|
||||
entry independently.
|
||||
|
||||
The insertion shader converts child information into a `PointerPage`:
|
||||
|
||||
- every child pointer starts as `empty(subdividable)`;
|
||||
- the occupancy mask bits are assembled from `occupied`;
|
||||
- attributes are copied for `External` attributes only.
|
||||
|
||||
`destination_indices` is an output used by `write_pointers` and by the structure
|
||||
table insertion pass. `0xFFFFFFFF` means "not inserted" (out of capacity, too
|
||||
recently used, or invalid).
|
||||
|
||||
---
|
||||
|
||||
## 5. Request pipeline
|
||||
|
||||
### 5.1 Where requests come from
|
||||
|
||||
- **During rendering**, `VoxelCacheTracer::trace` descends nodes. If a child is
|
||||
subdividable, not resident, and the LOD says "keep going", it does
|
||||
`request_buffer[current_node_index].requests[child_index].add(1)`.
|
||||
- The structure tracer does the same for table slots whose root pointer is
|
||||
subdividable but unavailable.
|
||||
- Every invocation also writes `usage_buffer[page] = frame_timestamp` for pages
|
||||
it touches (if usage reporting is enabled).
|
||||
|
||||
The request-counter buffers are indexed **per child**, not per page:
|
||||
`request_counts_pages[page_index * 64 + child_index]`.
|
||||
|
||||
### 5.2 `VoxelCache::gather_requests`
|
||||
|
||||
Encoded in this order:
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[request_counts_pages<br/>9.6M u32] --> B[top-K select<br/>k = max_requests]
|
||||
B --> C[gather<br/>keys = counts<br/>values = indices]
|
||||
C --> D[radix sort<br/>descending by count]
|
||||
D --> E[write_requests.wgsl]
|
||||
E --> F[(CacheRequestBuffer)]
|
||||
B -.->|reset| A
|
||||
```
|
||||
|
||||
1. **Top-K** (`TopKSelector::select`): selects up to `k` of the flat
|
||||
`page*64 + child` counters with the highest counts. `k` is
|
||||
`request_buffer.max_requests` (1024 in the demo).
|
||||
`selected_count` is written to a buffer; a zero count means no dispatch.
|
||||
2. **Gather** (`gather_requests.wgsl`): copies the selected counts into the
|
||||
shared scratch buffer as radix keys and the selected flat indices into
|
||||
`sorted_requests` as radix values. Dispatch is indirect from
|
||||
`selected_count`.
|
||||
3. **Radix sort** (`RadixSorter::sort`, descending): sorts the selected requests
|
||||
by request count, highest first.
|
||||
4. **Write requests** (`write_requests.wgsl`): for each sorted index, converts
|
||||
the flat index to `(page_index, children_index)`, looks up the page's
|
||||
`LocationPage`, and writes:
|
||||
|
||||
```rust
|
||||
struct RequestInformation {
|
||||
node_id: u32, // from LocationPage (the parent node)
|
||||
children_index: u32, // requested child
|
||||
producer_id: u32, // from LocationPage
|
||||
demand: u32, // request counter for this slot this frame
|
||||
anchor: StructureAnchor, // from LocationPage (content identity)
|
||||
}
|
||||
|
||||
struct RequestMeta {
|
||||
page_index: u32, // parent page, or 0xFFFFFFFF if external
|
||||
children_index: u32,
|
||||
depth: u32, // parent depth
|
||||
table_slot: u32, // 0xFFFFFFFF internally; external root placement
|
||||
}
|
||||
```
|
||||
|
||||
`producer_id` lets a cache mix several producers and lets the host queue route
|
||||
requests without guessing. `demand` is the raw request counter; the queue uses it
|
||||
as the primary priority key. `anchor` lets producers stay stateless and lets the
|
||||
queue key roots by content identity instead of table placement. `table_slot`
|
||||
travels in `RequestMeta` because it is reinsertion/attachment information, not
|
||||
request identity.
|
||||
|
||||
The external-root marker is `RequestMeta.page_index == 0xFFFFFFFF`, **not**
|
||||
`node_id == 0`. Both an external root and child 0 of the root carry
|
||||
`node_id = 0, children_index = 0`, so a queue keyed on those fields alone would
|
||||
collapse them.
|
||||
|
||||
5. **Reset** (`requests.wgsl`): zeroes all request counters for the next frame.
|
||||
|
||||
`request_count` is copied from `top_k.selected_count` and then clamped in
|
||||
`write_requests.wgsl` to the request-buffer capacity.
|
||||
|
||||
### 5.3 Host download
|
||||
|
||||
`CacheRequestBuffer::host_download_requests(device, queue, callback)` uses three
|
||||
`DownloadBuffer::read_buffer` calls (count + informations + meta). A small
|
||||
`RequestMapState` waits for all three and invokes the callback with
|
||||
`&request_informations[0..count]` and `&request_meta[0..count]`.
|
||||
|
||||
The callback is asynchronous by API, but the demo blocks on it with a
|
||||
`device.poll` loop. The callback only ingests the wire requests into the
|
||||
`RequestQueue`; the demo drains produced results and uploads the insertion batch
|
||||
after both request buffers have landed. See
|
||||
[`pipeline-and-producers.md`](./pipeline-and-producers.md).
|
||||
|
||||
### 5.4 What a producer receives
|
||||
|
||||
For an **internal** request:
|
||||
|
||||
- `node_id` and `anchor` identify the **parent** node.
|
||||
- `children_index` identifies which child is missing.
|
||||
- The producer generates that child node as a `ProducedNode`. It does not emit a
|
||||
`LocationPage` or `InsertionParent`: `RequestKey::node_locator::<N>()` names
|
||||
the produced node, and `ReadyItem::insertion_entry()` derives both from the
|
||||
request key.
|
||||
|
||||
For an **external** (structure-table) request:
|
||||
|
||||
- `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 generates a chunk root as a `ProducedNode`; the queue derives the
|
||||
root `LocationPage` and an 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`.
|
||||
|
||||
---
|
||||
|
||||
## 6. Insertion pipeline
|
||||
|
||||
`VoxelCache::insert` runs these stages in one encoder:
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[prepare eviction list] --> B[validate + compact<br/>one per insertion]
|
||||
B --> C[insertion pass<br/>one per insertion]
|
||||
C --> D[external invalidation]
|
||||
D --> E[cache invalidation]
|
||||
E --> F[write pointers<br/>internal insertions only]
|
||||
F --> G[frame_timestamp += 1]
|
||||
```
|
||||
|
||||
### 6.1 Eviction preparation
|
||||
|
||||
`CacheEvictor::prepare_eviction_list`:
|
||||
|
||||
1. `reset_lru_list`: `lru_list[i] = i`, `consumed_count = 0`.
|
||||
2. Copy `depth_pages` into the scratch buffer and radix-sort **descending** with
|
||||
`lru_list` as values. `lru_list` is now page indices ordered **deepest
|
||||
first**.
|
||||
3. `indirect_copy`: `scratch[i] = timestamp_pages[lru_list[i]]`, rearranging
|
||||
timestamps into depth order.
|
||||
4. Radix-sort `scratch` **ascending** with `lru_list` as values. This sort is
|
||||
stable, so equal timestamps keep the deepest-first order from step 2.
|
||||
|
||||
The resulting order is **timestamp-major, depth-minor**: least recently used
|
||||
first, with deeper pages first among equal timestamps. See §7.
|
||||
|
||||
### 6.2 Validation and insertion
|
||||
|
||||
Before any page is allocated, each batch is validated:
|
||||
|
||||
- **Internal** (`insertion.wgsl`, `validate_internal`): the parent page must
|
||||
still have the 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 `anchor`, and must still be
|
||||
`subdividable, unavailable`.
|
||||
|
||||
Valid entries are compacted into `valid_indices` and counted in `valid_count`.
|
||||
The validation pass resets every `destination_indices` entry to `0xFFFFFFFF`,
|
||||
so invalid entries never get a page even if the host reuses an insertion buffer.
|
||||
|
||||
For each insertion, `CacheInsertionPass::encode` then:
|
||||
|
||||
1. Dispatches `insertion` indirectly from `page_count`.
|
||||
2. Reads `valid_count` and computes
|
||||
`available_amount = min(page_count_free - consumed, valid_count)`.
|
||||
3. For compacted slot `i`:
|
||||
- if `i >= available_amount`, leave `destination_indices[entry]` at
|
||||
`0xFFFFFFFF` (already reset by validation);
|
||||
- pick `page_index = lru_list[i + consumed_count]`;
|
||||
- if `timestamp_pages[page_index] >= new_timestamp - 1`, do not insert
|
||||
(protects pages touched in the previous frame). **Note:** on the very
|
||||
first `insert` call, `new_timestamp` is 1 and unused pages have timestamp 0,
|
||||
so `0 >= 0` rejects every page. The first insertion is therefore a no-op
|
||||
and the cache only starts filling on the second call. See §11;
|
||||
- otherwise mark the page, increment `pass_inserted_count`, write location,
|
||||
pointer page, timestamp, depth 0, and copy external attributes.
|
||||
4. Dispatch `consume` (1 workgroup): `consumed_count += inserted_count`, then
|
||||
reset `inserted_count`.
|
||||
|
||||
Each insertion in the same `insert` call sees the updated `consumed_count`
|
||||
because the passes are ordered, so multiple batches consume disjoint pages.
|
||||
|
||||
### 6.3 External invalidation
|
||||
|
||||
For each `ExternalRequest`, the cache calls `invalidable.invalidate(...)`.
|
||||
`FixedStructureTable`/`ToroidalStructureTable` scan their pointer arrays and
|
||||
clear any pointer whose target page has `timestamp == new_timestamp` (i.e. was
|
||||
just recycled).
|
||||
|
||||
### 6.4 Cache invalidation
|
||||
|
||||
`invalidation.wgsl` scans every page's 64 pointers. If a pointer is available
|
||||
and points at a page whose timestamp equals `new_timestamp`, the pointer is reset
|
||||
to `empty(subdividable = true)` — i.e. the node becomes "missing again" and can
|
||||
be requested later.
|
||||
|
||||
### 6.5 Write pointers
|
||||
|
||||
For each internal insertion, `write_pointers.wgsl` reads the batch's own
|
||||
`InsertionParent` (there is no request buffer):
|
||||
|
||||
```wgsl
|
||||
let parent = insertion_data_parents[index];
|
||||
if(parent.kind == INSERTION_PARENT_INTERNAL &&
|
||||
insertion_data_destination_indices[index] != 0xFFFFFFFF &&
|
||||
parent.page_index != insertion_data_destination_indices[index] &&
|
||||
location_pages[parent.page_index] still has parent's identity)
|
||||
{
|
||||
structure_pointer_pages[parent.page_index].pointers[parent.children_index]
|
||||
= child_pointer_make_available(destination_index);
|
||||
structure_depth_pages[destination_index] = parent.depth + 1;
|
||||
}
|
||||
```
|
||||
|
||||
This is the step that actually links the new pages into the tree. The identity
|
||||
re-check catches the case where the parent page itself was recycled by the same
|
||||
insertion batch.
|
||||
|
||||
### 6.6 Timestamp advance
|
||||
|
||||
At the end of `insert`, `frame_timestamp += 1`. The renderer reads this value
|
||||
via `current_timestamp()` and passes it to the shader as `frame_timestamp`, so
|
||||
usage reporting and "dirty last frame" detection share one clock.
|
||||
|
||||
---
|
||||
|
||||
## 7. Eviction policy — timestamp-major, deepest-first ties
|
||||
|
||||
The eviction order is built in two radix passes:
|
||||
|
||||
1. **Depth, descending.** Pages are sorted deepest first. This is the
|
||||
tie-breaker, not the primary key.
|
||||
2. **Timestamp, ascending and stable.** Pages are sorted by last-use timestamp.
|
||||
Because the radix sort is stable, equal timestamps keep the deepest-first
|
||||
order from pass 1.
|
||||
|
||||
Final order:
|
||||
|
||||
- **Primary:** least recently used first (oldest timestamp).
|
||||
- **Tie-break:** deepest first (largest depth).
|
||||
|
||||
Consumption is in list order, so the oldest pages are reused first. The
|
||||
deepest-first tie-break means that, among pages last used at the same time, a
|
||||
page's resident children (which are deeper) appear earlier in the list and are
|
||||
reused first. This avoids recycling a parent and orphaning a subtree that is
|
||||
still resident, assuming the children's timestamps are equal or older.
|
||||
|
||||
Additional details:
|
||||
|
||||
- Unused pages have depth `u32::MAX` and initial timestamp 0, so they lead both
|
||||
orderings and are normally consumed before resident data.
|
||||
- The insertion shader additionally rejects pages with
|
||||
`timestamp >= new_timestamp - 1`, so pages touched in the immediately previous
|
||||
frame are skipped even if selected.
|
||||
- For pages with distinct timestamps, the depth tie-break has no effect; the
|
||||
result behaves like a pure LRU list.
|
||||
|
||||
---
|
||||
|
||||
## 8. Structure tables
|
||||
|
||||
The cache needs an entry point: given a world/chunk coordinate, where is the
|
||||
root page? Structure tables answer that and emit requests when it is missing.
|
||||
|
||||
### 8.1 `FixedStructureTable`
|
||||
|
||||
`crates/vxls-voxel-cache/src/tables.rs`.
|
||||
|
||||
- Backing buffer: one `CachePointer` per slot, initialised to
|
||||
`subdividable, unavailable`.
|
||||
- One request counter per slot (`CacheRequestHandler<1>`).
|
||||
- `raytrace_bind_group`: bindings `[pointers, request_counts]` (group 1 in the
|
||||
render pipeline).
|
||||
- `gather_requests`: top-K + sort + `fixed_table/write_requests.wgsl`; emits
|
||||
`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.
|
||||
- `insert`: `fixed_table/insertion.wgsl` reads each entry's `InsertionParent`
|
||||
and sets `pointers[slot] = available(destination_indices[i])` for external
|
||||
roots whose slot is still waiting.
|
||||
- `invalidate`: clears slots pointing at pages recycled this insert.
|
||||
|
||||
The table is dense: allocation is `slot_count * 4` bytes for pointers plus
|
||||
`slot_count * 4` for request counters.
|
||||
|
||||
### 8.2 `ToroidalStructureTable`
|
||||
|
||||
`crates/vxls-terrain/src/lib.rs`. Wraps `FixedStructureTable` with a movable block of chunks.
|
||||
|
||||
- `extent = (x, y, z)` chunk counts.
|
||||
- Slot index from local coordinates:
|
||||
`x + z*extent.x + y*extent.x*extent.z` (shader) — note the y/z order.
|
||||
- `move_position(queue, encoder, position)` computes a new integer offset,
|
||||
reassigns every slot's anchor through `FixedStructureTable::reassign_slots`,
|
||||
and runs `terrain/shaders/toroidal_structure.wgsl`: any slot whose world
|
||||
position changed is reset to `subdividable, unavailable`, so it will be
|
||||
re-requested.
|
||||
- Slot identity is preserved across the move: 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.
|
||||
|
||||
The Slang module `toroidal_structure_table.slang` mirrors this indexing and walks
|
||||
the block of chunks (`ToroidalStructureTableTracer`). `fixed_structure_table.slang`
|
||||
is imported by `voxel.slang` but unused.
|
||||
|
||||
### 8.3 `DynamicStructureTable`
|
||||
|
||||
`crates/vxls-voxel-cache/src/tables.rs`. A table whose slots are allocated and released at
|
||||
runtime. It shares the GPU scaffolding with `FixedStructureTable` through the
|
||||
private `StructureTableCore`; only the host-side slot management differs.
|
||||
|
||||
- **Allocator.** A host-side LIFO free list. `allocate(queue, anchor) -> Option<u32>`
|
||||
pops a slot and installs the anchor; `release(queue, slot) -> Option<StructureAnchor>`
|
||||
clears the pointer and pushes the slot back. Allocating an already-live anchor
|
||||
is idempotent and returns its existing slot. `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
|
||||
|
||||
### 9.1 Raytrace bind group (group 0 of the render pipeline)
|
||||
|
||||
| Binding | Buffer | Access |
|
||||
|---|---|---|
|
||||
| 0 | `pointer_pages` | read-only storage |
|
||||
| 1 | `request_counts_pages` | read-write storage |
|
||||
| 2 | `timestamp_pages` (usage) | read-write storage |
|
||||
| 3 | attribute buffers (`binding_array`) | read-write storage |
|
||||
|
||||
The Slang `VoxelCacheParameters<2>` parameter block maps to these four bindings
|
||||
in this order.
|
||||
|
||||
### 9.2 `CacheStructure` bind group
|
||||
|
||||
| Binding | Buffer |
|
||||
|---|---|
|
||||
| 0 | pointer pages |
|
||||
| 1 | location pages |
|
||||
| 2 | depth pages |
|
||||
|
||||
Used by write-requests, insertion, invalidation, and write-pointers passes.
|
||||
|
||||
### 9.3 Other pass bind groups
|
||||
|
||||
| Pass | Group 0 | Group 1 | Group 2 | Group 3 | Group 4 |
|
||||
|---|---|---|---|---|---|
|
||||
| `WriteRequestsPass` | structure | request handler (count + sorted) | request buffer | — | — |
|
||||
| `CacheInsertionPass` | cache attributes | structure | insertion data | evictor | inserted count |
|
||||
| `CacheInvalidationPass` | structure | evictor | — | — | — |
|
||||
| `WritePointersPass` | structure | insertion data | — | — | — |
|
||||
| Eviction reset / indirect copy | evictor | structure | scratch | — | — |
|
||||
|
||||
---
|
||||
|
||||
## 10. Configuration and sizing
|
||||
|
||||
The demo (`main.rs`) uses:
|
||||
|
||||
```rust
|
||||
let mut layout = CacheLayout::default();
|
||||
layout.add_attribute(CacheAttribute { label: Some("color"), word_count: 1, init: External });
|
||||
layout.add_attribute(CacheAttribute { label: Some("normal"), word_count: 3, init: External });
|
||||
|
||||
let request_buffer = CacheRequestBuffer::new(&device, 1024);
|
||||
let cache = VoxelCache::<4>::new(&device, 150_000, request_buffer.max_requests, &layout);
|
||||
let insertion = CacheInsertionData::new(&device, 1024, &layout);
|
||||
```
|
||||
|
||||
Scaling rules:
|
||||
|
||||
- Doubling `page_count` doubles every page pool, every attribute pool, the
|
||||
request counter array, the sorted request array, and the scratch buffer.
|
||||
- `page_count * N³` must fit in `u32` (the request handler asserts this).
|
||||
- `page_count` must be `< 2^30` because pointers use 30 bits.
|
||||
- `max_requests` bounds top-K and the host request buffers. It does **not** bound
|
||||
`InsertionData`; the demo keeps them equal by convention.
|
||||
- Each attribute adds `page_count * 64 * word_count * 4` bytes.
|
||||
- `DontTouch` attributes are allocated but never written by the cache, so the
|
||||
application must initialise and maintain them.
|
||||
|
||||
Memory example at 150k pages and 2 attributes is tabulated in
|
||||
[`architecture.md`](./architecture.md#8-memory-and-performance-envelope).
|
||||
|
||||
---
|
||||
|
||||
## 11. Known issues
|
||||
|
||||
| Symptom | Location | Impact | Confidence |
|
||||
|---|---|---|---|
|
||||
| `CacheStructure::new` allocates `location_pages` with `size_of::<StructurePage<N>>()` instead of `size_of::<LocationPage>()`. | `crates/vxls-voxel-cache/src/structure.rs:44` | At N=4, 264 B/page instead of 8 B/page: ~39.6 MB instead of ~1.2 MB for 150k pages. No correctness issue because shaders index by `LocationPage` stride. | High |
|
||||
| `StructurePage` (Rust, `u64` mask) and `PointerPage` (WGSL, two `u32`) are duplicated layout definitions. | `crates/vxls-voxel-cache/src/schema.rs:89-100`, `crates/vxls-voxel-cache/src/shaders/cache_common.wgsl:3-8` | Little-endian compatible today; any field reorder breaks silently. `StructurePage` is only used for sizing. | High |
|
||||
| `request_buffer_count` is written by every invocation of `write_requests.wgsl` with the same value. | `crates/vxls-voxel-cache/src/shaders/write_requests.wgsl:50` | Benign data race (identical writes), but unnecessary and confusing. | Medium |
|
||||
| Insertion order no longer matters: each entry is validated against its `InsertionParent` and linked statelessly. | `insertion.wgsl`, `write_pointers.wgsl`, `fixed_table/insertion.wgsl` | A producer may reorder or filter results; unchanged request order is no longer a correctness requirement. | High |
|
||||
| `CacheInsertionPass` can silently insert fewer pages than requested (`0xFFFFFFFF` destinations) with no host feedback. | `crates/vxls-voxel-cache/src/shaders/insertion.wgsl` | Producer believes data is resident; requests may repeat or data may be missing. | High |
|
||||
| The first `VoxelCache::insert` call inserts nothing: `new_timestamp = 1`, unused pages have timestamp 0, and the guard rejects `0 >= new_timestamp - 1` (`0 >= 0`). | `crates/vxls-voxel-cache/src/lib.rs:248`, `crates/vxls-voxel-cache/src/shaders/insertion.wgsl:141-146` | One-frame startup delay; any external roots submitted in the first batch are dropped and must be re-requested. | High |
|
||||
| Pointer/page-count limits are implicit (`< 2^30`, total elements `< 2^32`). | `schema.rs`, `requests.rs:82-85` | Large configurations fail via asserts or truncation. | High |
|
||||
| `CacheAttributeInit::DontTouch` attributes can become stale after a page is recycled; the cache deliberately does not clear them. | `crates/vxls-voxel-cache/src/shaders/insertion.wgsl:164-178` | Any consumer of such an attribute must tolerate garbage for recycled pages. | Medium |
|
||||
| The cache exposes `usage_timestamps()` for debugging only; timestamps are also used internally for invalidation and eviction. | `crates/vxls-voxel-cache/src/lib.rs:445-449` | Easy to corrupt cache behaviour by writing to that buffer. | Medium |
|
||||
BIN
Binary file not shown.
+2
-2
@@ -1,7 +1,7 @@
|
||||
all: clean voxel.spv compaction.spv gi.spv radix_sort.spv radix_reduce.spv
|
||||
|
||||
clean:
|
||||
rm -f *.spv
|
||||
rm -f out/*.spv
|
||||
|
||||
%.spv: %.slang
|
||||
slangc $< -O3 -fvk-use-entrypoint-name -target spirv -o $@
|
||||
slangc $< -O3 -g0 -fp-mode fast -emit-spirv-directly -fvk-use-entrypoint-name -target spirv -o out/$@
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
import voxel_tracing;
|
||||
import voxel_cache;
|
||||
|
||||
public struct Aabb
|
||||
{
|
||||
public float3 min;
|
||||
uint32_t _pad0; // std430 aligns float3 to 16 bytes
|
||||
|
||||
public float3 max;
|
||||
uint32_t _pad1;
|
||||
}
|
||||
|
||||
public struct BvhNode
|
||||
{
|
||||
public Aabb aabb;
|
||||
public uint32_t count;
|
||||
public uint32_t first_or_left;
|
||||
|
||||
public bool is_leaf()
|
||||
{
|
||||
return this.count != 0;
|
||||
}
|
||||
|
||||
public bool is_internal()
|
||||
{
|
||||
return this.count == 0;
|
||||
}
|
||||
}
|
||||
|
||||
public struct BvhObject
|
||||
{
|
||||
public float4x4 local_to_world;
|
||||
public float4x4 world_to_local;
|
||||
public uint32_t table_slot;
|
||||
uint32_t _pad0;
|
||||
uint32_t _pad1;
|
||||
uint32_t _pad2;
|
||||
}
|
||||
|
||||
/// Traversal state for a single ray.
|
||||
///
|
||||
/// The BVH is traversed with a restart trail instead of a stack: one bit per
|
||||
/// tree level records what has already been processed, and every restart
|
||||
/// re-walks from the root steered by that trail. [`BvhCursor::trail`] is the
|
||||
/// only traversal state that survives between calls to [`Bvh::next`].
|
||||
///
|
||||
/// Trail invariant: bits `0 .. leaf_depth-1` encode the path to the current
|
||||
/// leaf (`0` = near child, `1` = far child); all deeper bits are clear.
|
||||
/// A 64 bit trail supports trees up to 64 levels deep.
|
||||
public struct BvhCursor
|
||||
{
|
||||
public Ray ray;
|
||||
|
||||
/// Reciprocal of [`Ray::direction`]; computed once per ray and reused for
|
||||
/// every node test.
|
||||
public float3 inv_direction;
|
||||
|
||||
/// Restart trail, see the struct documentation.
|
||||
public uint64_t trail;
|
||||
|
||||
/// Objects of the leaf currently being drained.
|
||||
public uint32_t leaf_first;
|
||||
public uint32_t leaf_count;
|
||||
public uint32_t leaf_next;
|
||||
public uint32_t leaf_depth;
|
||||
|
||||
/// True while [`Self::leaf_next`] still points into a valid leaf.
|
||||
public bool have_leaf;
|
||||
|
||||
/// Set once the whole tree has been processed.
|
||||
public bool done;
|
||||
}
|
||||
|
||||
public struct BvhParameters
|
||||
{
|
||||
StructuredBuffer<BvhNode> nodes;
|
||||
StructuredBuffer<BvhObject> objects;
|
||||
RWStructuredBuffer<StructurePointer> slots;
|
||||
RWStructuredBuffer<Atomic<uint32_t>> requests;
|
||||
}
|
||||
|
||||
public struct Bvh : IStructure
|
||||
{
|
||||
typedef BvhCursor Cursor;
|
||||
public BvhParameters parameters;
|
||||
|
||||
/// Reject nodes/objects whose entry distance is beyond this value.
|
||||
/// Set to FLT_MAX for unbounded primary rays. Distances are in the
|
||||
/// object's local units, which equal world units for the rigid
|
||||
/// rotation/translation transforms used here.
|
||||
public float max_t;
|
||||
|
||||
public BvhCursor begin(Ray world_ray)
|
||||
{
|
||||
BvhCursor c;
|
||||
c.ray = world_ray;
|
||||
c.inv_direction = safe_reciprocal(world_ray.direction);
|
||||
c.trail = uint64_t(0);
|
||||
c.leaf_first = 0;
|
||||
c.leaf_count = 0;
|
||||
c.leaf_next = 0;
|
||||
c.leaf_depth = 0;
|
||||
c.have_leaf = false;
|
||||
|
||||
// Early out when the ray misses the whole scene or the root is beyond
|
||||
// the requested range.
|
||||
let root = this.parameters.nodes[0];
|
||||
let root_t = intersect_aabb(
|
||||
world_ray.origin,
|
||||
c.inv_direction,
|
||||
root.aabb.min,
|
||||
root.aabb.max);
|
||||
c.done = !(root_t.y >= max(root_t.x, 0.) && root_t.x <= this.max_t);
|
||||
|
||||
return c;
|
||||
}
|
||||
|
||||
public bool next(inout BvhCursor c, out Cell cell)
|
||||
{
|
||||
// The out parameter is only meaningful on a `true` return, but
|
||||
// initialising it keeps the compiler's definite-assignment analysis
|
||||
// happy on all early-outs.
|
||||
cell.cache_pointer = 0;
|
||||
cell.local_ray.origin = float3(0.);
|
||||
cell.local_ray.direction = float3(0.);
|
||||
cell.t = 0.;
|
||||
cell.cube_to_world = mat3_identity();
|
||||
cell.world_origin = float3(0.);
|
||||
|
||||
if (c.done)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
[loop]
|
||||
for (;;)
|
||||
{
|
||||
// 1. Drain the objects of the leaf we are currently in.
|
||||
[loop]
|
||||
while (c.leaf_next < c.leaf_count)
|
||||
{
|
||||
let object_index = c.leaf_first + c.leaf_next;
|
||||
c.leaf_next += 1;
|
||||
|
||||
Cell candidate;
|
||||
if (this.object_hit(object_index, c.ray, candidate))
|
||||
{
|
||||
cell = candidate;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. The leaf is exhausted: advance the trail past it.
|
||||
if (c.have_leaf)
|
||||
{
|
||||
c.have_leaf = false;
|
||||
if (!advance_trail(c, c.leaf_depth))
|
||||
{
|
||||
c.done = true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Restart: descend from the root, steered by the trail.
|
||||
uint32_t node = 0;
|
||||
uint32_t level = 0;
|
||||
bool dead = false;
|
||||
|
||||
[loop]
|
||||
for (;;)
|
||||
{
|
||||
let n = this.parameters.nodes[node];
|
||||
if (n.is_leaf())
|
||||
{
|
||||
c.leaf_first = n.first_or_left;
|
||||
c.leaf_count = n.count;
|
||||
c.leaf_next = 0;
|
||||
c.leaf_depth = level;
|
||||
c.have_leaf = true;
|
||||
break;
|
||||
}
|
||||
|
||||
let left = n.first_or_left;
|
||||
let right = left + 1;
|
||||
|
||||
let t_left = intersect_aabb(
|
||||
c.ray.origin,
|
||||
c.inv_direction,
|
||||
this.parameters.nodes[left].aabb.min,
|
||||
this.parameters.nodes[left].aabb.max);
|
||||
let t_right = intersect_aabb(
|
||||
c.ray.origin,
|
||||
c.inv_direction,
|
||||
this.parameters.nodes[right].aabb.min,
|
||||
this.parameters.nodes[right].aabb.max);
|
||||
|
||||
let hit_left = t_left.y >= max(t_left.x, 0.) && t_left.x <= this.max_t;
|
||||
let hit_right = t_right.y >= max(t_right.x, 0.) && t_right.x <= this.max_t;
|
||||
|
||||
if (hit_left && hit_right)
|
||||
{
|
||||
// Trail bit 0 means "near child first", 1 means "far".
|
||||
// The near/far decision is deterministic for a fixed ray,
|
||||
// so it stays consistent across restarts.
|
||||
let left_is_near = t_left.x <= t_right.x;
|
||||
let go_far = ((c.trail >> level) & uint64_t(1)) != uint64_t(0);
|
||||
|
||||
if (left_is_near)
|
||||
{
|
||||
node = go_far ? right : left;
|
||||
}
|
||||
else
|
||||
{
|
||||
node = go_far ? left : right;
|
||||
}
|
||||
level += 1;
|
||||
}
|
||||
else if (hit_left)
|
||||
{
|
||||
// The far child has no work; mark this level processed so
|
||||
// a later restart does not try to enter it.
|
||||
c.trail |= (uint64_t(1) << level);
|
||||
node = left;
|
||||
level += 1;
|
||||
}
|
||||
else if (hit_right)
|
||||
{
|
||||
c.trail |= (uint64_t(1) << level);
|
||||
node = right;
|
||||
level += 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
dead = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (level >= 64)
|
||||
{
|
||||
// The trail cannot represent anything deeper.
|
||||
c.done = true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (dead)
|
||||
{
|
||||
// No child of this node is hit: move on to the next
|
||||
// unprocessed part of the tree.
|
||||
if (!advance_trail(c, level))
|
||||
{
|
||||
c.done = true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests a leaf object and, if it can be traced, fills its cache cell.
|
||||
bool object_hit(uint32_t object_index, Ray world_ray, out Cell cell)
|
||||
{
|
||||
cell.cache_pointer = 0;
|
||||
cell.local_ray.origin = float3(0.);
|
||||
cell.local_ray.direction = float3(0.);
|
||||
cell.t = 0.;
|
||||
cell.cube_to_world = mat3_identity();
|
||||
cell.world_origin = float3(0.);
|
||||
|
||||
let object = this.parameters.objects[object_index];
|
||||
|
||||
// Transform the ray to the object's local space, where the voxel
|
||||
// chunk is the unit cube.
|
||||
let local_origin = mul(object.world_to_local, float4(world_ray.origin, 1.)).xyz;
|
||||
let local_direction = mul(object.world_to_local, float4(world_ray.direction, 0.)).xyz;
|
||||
|
||||
let t = intersect_aabb(
|
||||
local_origin,
|
||||
safe_reciprocal(local_direction),
|
||||
float3(0.),
|
||||
float3(1.));
|
||||
|
||||
if (t.y < max(t.x, 0.) || t.x > this.max_t)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let pointer = this.parameters.slots[object.table_slot];
|
||||
if (pointer.subdivided_valid())
|
||||
{
|
||||
let entry_t = max(t.x, 0.);
|
||||
cell.cache_pointer = pointer.pointer();
|
||||
cell.local_ray.origin = local_origin + local_direction * entry_t;
|
||||
cell.local_ray.direction = local_direction;
|
||||
cell.t = entry_t;
|
||||
cell.cube_to_world = float3x3(object.local_to_world);
|
||||
cell.world_origin = mul(object.local_to_world, float4(0., 0., 0., 1.)).xyz;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (pointer.subdivided())
|
||||
{
|
||||
// The root of this object is requested but not available yet.
|
||||
this.parameters.requests[object.table_slot].add(1);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the trail to the next unprocessed part of the tree.
|
||||
///
|
||||
/// Finds the nearest ancestor with a pending far child, marks it processed
|
||||
/// and clears the path below it. Returns false when the whole tree has been
|
||||
/// visited.
|
||||
bool advance_trail(inout BvhCursor c, uint32_t depth)
|
||||
{
|
||||
uint32_t level = depth;
|
||||
uint64_t trail = (~c.trail) & ((1 << uint64_t(level)) - 1);
|
||||
int32_t fbh = firstbithigh(trail);
|
||||
if (trail == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
level = fbh;
|
||||
c.trail |= (uint64_t(1) << level);
|
||||
// Keep the path bits up to and including this level, drop the
|
||||
// stale path below it.
|
||||
c.trail &= (uint64_t(2) << level) - uint64_t(1);
|
||||
|
||||
// [loop]
|
||||
// while (level > 0)
|
||||
// {
|
||||
// level -= 1;
|
||||
// if (((c.trail >> level) & uint64_t(1)) == uint64_t(0))
|
||||
// {
|
||||
// c.trail |= (uint64_t(1) << level);
|
||||
// // Keep the path bits up to and including this level, drop the
|
||||
// // stale path below it.
|
||||
// c.trail &= (uint64_t(2) << level) - uint64_t(1);
|
||||
// return true;
|
||||
// }
|
||||
// }
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Slab test against an axis aligned box, using a precomputed reciprocal.
|
||||
///
|
||||
/// Returns `(t_near, t_far)`. A hit is `t_far >= max(t_near, 0)`.
|
||||
float2 intersect_aabb(float3 origin, float3 inv_direction, float3 box_min, float3 box_max)
|
||||
{
|
||||
let t0 = (box_min - origin) * inv_direction;
|
||||
let t1 = (box_max - origin) * inv_direction;
|
||||
|
||||
let t_near = min(t0, t1);
|
||||
let t_far = max(t0, t1);
|
||||
|
||||
return float2(
|
||||
max(t_near.x, max(t_near.y, t_near.z)),
|
||||
min(t_far.x, min(t_far.y, t_far.z)));
|
||||
}
|
||||
|
||||
/// Reciprocal that avoids `0 * inf = NaN` for rays parallel to a slab.
|
||||
///
|
||||
/// A component that is (near) zero is replaced by a tiny positive value. The
|
||||
/// slab test stays correct: the resulting huge `t` values either do not
|
||||
/// constrain the interval or reject the box, depending on which side of the
|
||||
/// slab the origin lies.
|
||||
float3 safe_reciprocal(float3 direction)
|
||||
{
|
||||
let tiny = abs(direction) < float3(1e-8);
|
||||
return 1. / select(tiny, float3(1e-8), direction);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
module fixed_structure_table;
|
||||
|
||||
import voxel_cache;
|
||||
import voxel_tracing;
|
||||
|
||||
/// Parameters for the fixed structure table
|
||||
public struct FixedStructureTable
|
||||
{
|
||||
RWStructuredBuffer<StructurePointer> structure_table_pointer;
|
||||
RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
|
||||
}
|
||||
|
||||
public struct FixedStructureTableChunksCursor
|
||||
{
|
||||
int32_t3 current_voxel;
|
||||
float3 t_off;
|
||||
float3 t;
|
||||
|
||||
Ray r;
|
||||
}
|
||||
|
||||
/// Uses a fixed structure table as a dense array of chunks
|
||||
public struct FixedStructureTableChunks : IStructure
|
||||
{
|
||||
typedef FixedStructureTableChunksCursor Cursor;
|
||||
|
||||
public FixedStructureTable structure_table;
|
||||
public uint32_t3 extent;
|
||||
|
||||
public FixedStructureTableChunksCursor begin(Ray worldRay, Span s)
|
||||
{
|
||||
FixedStructureTableChunksCursor cursor;
|
||||
|
||||
// Intersect with bounds
|
||||
var inter = box_intersect(worldRay.origin, worldRay.direction, float3(0.), float3(this.extent.x, this.extent.y, this.extent.z));
|
||||
|
||||
// No hit if out of box
|
||||
if (inter.y <= inter.x || inter.y <= 0.)
|
||||
{
|
||||
// Take position way off so it exits on firt next call
|
||||
cursor.current_voxel = int32_t3(-1);
|
||||
cursor.t_off = float3(0.);
|
||||
return cursor;
|
||||
}
|
||||
inter.x = max(0., inter.x);
|
||||
|
||||
// Now march inside chunk bounds
|
||||
let start_position = inter.x * worldRay.direction + worldRay.origin;
|
||||
|
||||
// FVT clamp to block
|
||||
cursor.current_voxel = clamp(
|
||||
int32_t3(floor(start_position)),
|
||||
int32_t3(0),
|
||||
int32_t3(this.extent.x - 1, this.extent.y - 1, this.extent.z - 1));
|
||||
cursor.t_off = abs(worldRay.invDirection);
|
||||
|
||||
// Take t of next boundary
|
||||
cursor.t = select(
|
||||
worldRay.direction > 0.,
|
||||
cursor.current_voxel + int32_t3(1) - start_position,
|
||||
start_position - cursor.current_voxel) *
|
||||
cursor.t_off;
|
||||
|
||||
// Add camera offset
|
||||
cursor.t += inter.x;
|
||||
cursor.r = worldRay;
|
||||
return cursor;
|
||||
}
|
||||
|
||||
public bool next(inout Cursor c, out Cell cell)
|
||||
{
|
||||
while (all(c.current_voxel >= 0) && all(c.current_voxel < int32_t3(this.extent.x, this.extent.y, this.extent.z)))
|
||||
{
|
||||
// Current hit
|
||||
let off = c.t - c.t_off;
|
||||
let t_adv = max(max(off.x, max(off.y, off.z)), 0.);
|
||||
let chunk_index = c.current_voxel.x + c.current_voxel.z * this.extent.x + c.current_voxel.y * this.extent.x * this.extent.z;
|
||||
let position = c.r.origin + c.r.direction * t_adv;
|
||||
|
||||
var hit = false;
|
||||
if (this.structure_table.structure_table_pointer[chunk_index].subdivided_valid())
|
||||
{
|
||||
cell.cache_pointer = this.structure_table.structure_table_pointer[chunk_index].pointer();
|
||||
cell.local_ray.origin = position - float3(c.current_voxel);
|
||||
cell.local_ray.direction = c.r.direction;
|
||||
cell.local_ray.invDirection = c.r.invDirection;
|
||||
cell.t = t_adv;
|
||||
hit = true;
|
||||
}
|
||||
else if (this.structure_table.structure_table_pointer[chunk_index].subdivided())
|
||||
{
|
||||
this.structure_table.structure_table_request_buffer[chunk_index].add(1);
|
||||
hit = false;
|
||||
}
|
||||
|
||||
// Advance
|
||||
let min_mask = min_mask(c.t);
|
||||
c.t += select(min_mask, c.t_off, float3(0.));
|
||||
c.current_voxel += select(min_mask, int32_t3(sign(c.r.direction)), int32_t3(0));
|
||||
|
||||
if (hit)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool3 min_mask(float3 val)
|
||||
{
|
||||
let min_val = min(val.x, min(val.y, val.z));
|
||||
return val == min_val;
|
||||
}
|
||||
|
||||
float2 box_intersect(float3 origin, float3 ray_direction, float3 box_min, float3 box_max)
|
||||
{
|
||||
let min_ts = (box_min - origin) / ray_direction;
|
||||
let max_ts = (box_max - origin) / ray_direction;
|
||||
|
||||
let far_ts = max(min_ts, max_ts);
|
||||
let near_ts = min(min_ts, max_ts);
|
||||
|
||||
let far_t = min(far_ts.x, min(far_ts.y, far_ts.z));
|
||||
let near_t = max(near_ts.x, max(near_ts.y, near_ts.z));
|
||||
return float2(near_t, far_t);
|
||||
}
|
||||
|
||||
+108
-196
@@ -1,4 +1,12 @@
|
||||
import ray_cast;
|
||||
import voxel_cache;
|
||||
import bvh;
|
||||
import voxel_tracing;
|
||||
import lod_policies;
|
||||
|
||||
// Simple screen-space AO: reconstruct the world-space surface from the primary
|
||||
// G-buffer and trace a few short, incoherent hemisphere rays per pixel through
|
||||
// the same tracer the primary pass uses. This is the secondary-ray smoke test:
|
||||
// short `t_max`, any-hit, usage feedback only, no detail requests.
|
||||
|
||||
struct PushConstants
|
||||
{
|
||||
@@ -11,104 +19,18 @@ struct PushConstants
|
||||
uint32_t chunk_width;
|
||||
uint32_t chunk_height;
|
||||
uint32_t chunk_alt;
|
||||
}
|
||||
|
||||
public struct VertexOutput
|
||||
{
|
||||
public float4 position : SV_Position;
|
||||
|
||||
[vk::location(0)]
|
||||
public float3 world_position;
|
||||
|
||||
[vk::location(1)]
|
||||
public nointerpolation uint32_t structure_id;
|
||||
|
||||
[vk::location(2)]
|
||||
public float3 cam_position;
|
||||
|
||||
[vk::location(3)]
|
||||
public float3 chunk_position;
|
||||
// Canonical table slot of the visible block's minimum corner.
|
||||
uint32_t table_base_slot_x;
|
||||
uint32_t table_base_slot_y;
|
||||
uint32_t table_base_slot_z;
|
||||
}
|
||||
|
||||
[[vk::push_constant]]
|
||||
uniform PushConstants constants;
|
||||
|
||||
struct ByteColor
|
||||
{
|
||||
uint32_t byte_color;
|
||||
|
||||
property uint32_t byte_r
|
||||
{
|
||||
get {
|
||||
return byte_color & 0xFF;
|
||||
}
|
||||
}
|
||||
|
||||
property uint32_t byte_g
|
||||
{
|
||||
get {
|
||||
return (byte_color >> 8) & 0xFF;
|
||||
}
|
||||
}
|
||||
|
||||
property uint32_t byte_b
|
||||
{
|
||||
get {
|
||||
return (byte_color >> 16) & 0xFF;
|
||||
}
|
||||
}
|
||||
|
||||
property uint32_t byte_a
|
||||
{
|
||||
get {
|
||||
return byte_color >> 24;
|
||||
}
|
||||
}
|
||||
|
||||
property float4 float_color
|
||||
{
|
||||
get {
|
||||
return float4(
|
||||
float(byte_r) / 255.,
|
||||
float(byte_g) / 255.,
|
||||
float(byte_b) / 255.,
|
||||
float(byte_a) / 255.);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[vk::binding(0, 0)]]
|
||||
RWStructuredBuffer<StructurePoolElement> structure_pool;
|
||||
[[vk::binding(1, 0)]]
|
||||
RWStructuredBuffer<uint32_t> attributes_pool[2];
|
||||
[[vk::binding(2, 0)]]
|
||||
RWStructuredBuffer<RequestBufferElement> request_buffer;
|
||||
[[vk::binding(3, 0)]]
|
||||
RWStructuredBuffer<uint32_t> usage_buffer;
|
||||
|
||||
[[vk::binding(0, 1)]]
|
||||
RWStructuredBuffer<StructurePointer> structure_table_pointer;
|
||||
[[vk::binding(1, 1)]]
|
||||
RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
|
||||
|
||||
ByteColor fetch_color(uint32_t index, uint32_t child_index)
|
||||
{
|
||||
return ByteColor(attributes_pool[0][index * 64 + child_index]);
|
||||
}
|
||||
|
||||
float3 fetch_normal(uint32_t index, uint32_t child_index)
|
||||
{
|
||||
let a = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3]);
|
||||
let b = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3 + 1]);
|
||||
let c = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3 + 2]);
|
||||
return float3(a, b, c);
|
||||
}
|
||||
|
||||
bool3 min_mask(float3 val)
|
||||
{
|
||||
let min_val = min(val.x, min(val.y, val.z));
|
||||
return val == min_val;
|
||||
}
|
||||
ParameterBlock<VoxelCacheParameters<2>> cache_parameters;
|
||||
ParameterBlock<BvhParameters> table_parameters;
|
||||
|
||||
[[vk::binding(0, 2)]]
|
||||
[[format("rgba32f")]]
|
||||
@@ -126,139 +48,129 @@ RWTexture2D<float4> gbuffer_albedo;
|
||||
[[format("rgba32f")]]
|
||||
RWTexture2D<float4> gbuffer_normal;
|
||||
|
||||
float3 get_ray_direction(uint32_t2 pixel_loc)
|
||||
static const uint32_t AO_SAMPLE_COUNT = 4;
|
||||
static const float AO_RADIUS = 0.25;
|
||||
static const float AO_EPSILON = 0.01;
|
||||
|
||||
float hash12(float2 p)
|
||||
{
|
||||
let ndc_loc_x = (float)pixel_loc.x / (float)constants.width * 2. - 1.;
|
||||
let ndc_loc_y = 1. - (float)pixel_loc.y / (float)constants.height * 2.;
|
||||
var world_loc = mul(constants.view_proj, float4(ndc_loc_x, ndc_loc_y, 1., 1.));
|
||||
world_loc /= world_loc.w;
|
||||
return normalize(world_loc.xyz - constants.cam_pos);
|
||||
var p3 = frac(float3(p.xyx) * 0.1031);
|
||||
p3 += dot(p3, p3.yzx + 33.33);
|
||||
return frac((p3.x + p3.y) * p3.z);
|
||||
}
|
||||
|
||||
float3 fetch_normal(uint32_t index, uint32_t child_index)
|
||||
{
|
||||
let a = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3]);
|
||||
let b = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3 + 1]);
|
||||
let c = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3 + 2]);
|
||||
return float3(a, b, c);
|
||||
}
|
||||
|
||||
/// Cosine-weighted hemisphere sample around `n`, rotated per pixel so the
|
||||
/// fixed sample count does not band.
|
||||
float3 hemisphere_sample(float3 n, uint32_t sample_index, float rotation)
|
||||
{
|
||||
let up = select(abs(n.z) < 0.999, float3(1., 0., 0.), float3(0., 0., 1.));
|
||||
let tangent = normalize(cross(up, n));
|
||||
let bitangent = cross(n, tangent);
|
||||
|
||||
let r = sqrt((float(sample_index) + 0.5) / float(AO_SAMPLE_COUNT));
|
||||
let phi = 6.28318530718 * frac(rotation + float(sample_index) * 0.61803398875);
|
||||
let disk = r * float2(cos(phi), sin(phi));
|
||||
|
||||
return normalize(tangent * disk.x + bitangent * disk.y + n * sqrt(max(0., 1. - r * r)));
|
||||
}
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(16, 16, 1)]
|
||||
void gi(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID)
|
||||
void gi(uint32_t3 location: SV_DispatchThreadID)
|
||||
{
|
||||
if (location.x >= constants.width || location.y >= constants.height)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (gbuffer_albedo.Load(location.xy).w == 0.)
|
||||
let albedo = gbuffer_albedo.Load(location.xy);
|
||||
// Shunt albedo
|
||||
target_texture.Store(location.xy, albedo);
|
||||
return;
|
||||
|
||||
// AO Example
|
||||
|
||||
if (albedo.w == 0.)
|
||||
{
|
||||
target_texture.Store(location.xy, float4(0.));
|
||||
return;
|
||||
}
|
||||
|
||||
let pos = gbuffer_position.Load(location.xy);
|
||||
let normal = gbuffer_normal.Load(location.xy);
|
||||
let albedo = gbuffer_albedo.Load(location.xy);
|
||||
target_texture.Store(location.xy, albedo);
|
||||
return;
|
||||
|
||||
let illumination = dot(float3(0., 1., 0.), normal.xyz);
|
||||
|
||||
let view_dir = pos.xyz - constants.cam_pos;
|
||||
// let ray_dir = normalize(reflect(view_dir, normal.xyz));
|
||||
let ray_dir = sampleHemisphere(normal.xyz, constants.frame_timestamp, 6767 + (location.x * 67) + (location.y * 91));
|
||||
if (any(isinf(ray_dir)) || any(isnan(ray_dir)))
|
||||
let position = gbuffer_position.Load(location.xy).xyz;
|
||||
let normal_raw = gbuffer_normal.Load(location.xy).xyz;
|
||||
let normal_length = length(normal_raw);
|
||||
if (normal_length < 1e-6)
|
||||
{
|
||||
target_texture.Store(location.xy, albedo);
|
||||
return;
|
||||
}
|
||||
let normal = -normal_raw / normal_length;
|
||||
|
||||
let stack_index = local_location.x + local_location.y * 16;
|
||||
VoxelCacheTracer<2, ColorHit<2>> cache_tracer;
|
||||
cache_tracer.parameters = cache_parameters;
|
||||
cache_tracer.frame_timestamp = constants.frame_timestamp;
|
||||
cache_tracer.voxel_hit = ColorHit<2>();
|
||||
|
||||
var voxel_cache : VoxelCache;
|
||||
voxel_cache.structure_pool = structure_pool;
|
||||
voxel_cache.attributes_pool = attributes_pool;
|
||||
voxel_cache.request_buffer = request_buffer;
|
||||
voxel_cache.usage_buffer = usage_buffer;
|
||||
voxel_cache.structure_table_pointer = structure_table_pointer;
|
||||
voxel_cache.structure_table_request_buffer = structure_table_request_buffer;
|
||||
Bvh bvh;
|
||||
bvh.parameters = table_parameters;
|
||||
bvh.max_t = AO_RADIUS;
|
||||
|
||||
var ray_cast_context : RayCastContext;
|
||||
ray_cast_context.ray_direction = ray_dir;
|
||||
ray_cast_context.ray_origin = pos.xyz + normal.xyz * 0.1;
|
||||
ray_cast_context.bounds = uint32_t3(constants.chunk_width, constants.chunk_alt, constants.chunk_width);
|
||||
ray_cast_context.frame_timestamp = constants.frame_timestamp;
|
||||
ray_cast_context.cache_report = true;
|
||||
// Coarse LOD: AO does not need primary-ray detail.
|
||||
// PixelFootprintLod lod = PixelFootprintLod.create((100.f * 3.14f) / 180.f, 1080.f, 2.f, 0.05f);
|
||||
PixelFootprintLod lod = PixelFootprintLod.create((100.f * 3.14f) / 180.f, 1080.f, 2.f);
|
||||
|
||||
let hit = ray_cast(voxel_cache, ray_cast_context, stack_index);
|
||||
Tracer<Bvh, VoxelCacheTracer<2, ColorHit<2>>, PixelFootprintLod> tracer;
|
||||
tracer.structure = bvh;
|
||||
tracer.cache = cache_tracer;
|
||||
tracer.lod = lod;
|
||||
|
||||
if (hit.hit)
|
||||
TraceSettings settings;
|
||||
settings.t_min = AO_EPSILON;
|
||||
settings.t_max = 100.;
|
||||
settings.max_cells = 64;
|
||||
settings.max_steps = 64;
|
||||
settings.any_hit = false;
|
||||
settings.report_usage = true;
|
||||
settings.report_requests = false;
|
||||
|
||||
LocalTraceStack stack;
|
||||
|
||||
let rotation = hash12(float2(location.xy));
|
||||
uint32_t occluded = 0;
|
||||
|
||||
// [loop]
|
||||
// for (uint32_t sample_index = 0; sample_index < AO_SAMPLE_COUNT; sample_index++)
|
||||
// {
|
||||
Ray r;
|
||||
r.origin = position + normal * (AO_EPSILON + 0.1);
|
||||
r.direction = reflect(normalize(position - constants.cam_pos), normal);
|
||||
// r.direction = hemisphere_sample(normal, sample_index, rotation);
|
||||
|
||||
Hit h;
|
||||
if (tracer.trace(h, r, settings, stack))
|
||||
{
|
||||
// Gather
|
||||
let smpl_albedo = fetch_color(hit.node_index, hit.child_index).float_color;
|
||||
target_texture.Store(location.xy, albedo * smpl_albedo);
|
||||
occluded += 1;
|
||||
let hit_normal = fetch_normal(h.node_index, h.child_index);
|
||||
let shade = max(dot(hit_normal, float3(0., 1., 0.)), 0.1);
|
||||
target_texture.Store(location.xy, float4(shade));
|
||||
}
|
||||
else
|
||||
{
|
||||
target_texture.Store(location.xy, float4(float3(illumination), 1.));
|
||||
target_texture.Store(location.xy, float4(0.));
|
||||
}
|
||||
}
|
||||
//}
|
||||
|
||||
float2 box_intersect(float3 origin, float3 ray_direction, float3 box_min, float3 box_max)
|
||||
{
|
||||
let min_ts = (box_min - origin) / ray_direction;
|
||||
let max_ts = (box_max - origin) / ray_direction;
|
||||
|
||||
let far_ts = max(min_ts, max_ts);
|
||||
let near_ts = min(min_ts, max_ts);
|
||||
|
||||
let far_t = min(far_ts.x, min(far_ts.y, far_ts.z));
|
||||
let near_t = max(near_ts.x, max(near_ts.y, near_ts.z));
|
||||
return float2(near_t, far_t);
|
||||
}
|
||||
|
||||
// Returns a cosine-weighted random direction in the hemisphere
|
||||
// oriented around `normal`.
|
||||
//
|
||||
// `frame` should change every frame/sample sequence.
|
||||
// `seed` can be a per-pixel or per-path identifier.
|
||||
float3 sampleHemisphere(float3 normal, uint frame, uint seed)
|
||||
{
|
||||
// Hash to get two uniform random numbers in [0, 1).
|
||||
uint state = seed ^ (frame * 0x9E3779B9u);
|
||||
|
||||
state ^= state >> 16;
|
||||
state *= 0x7FEB352Du;
|
||||
state ^= state >> 15;
|
||||
state *= 0x846CA68Bu;
|
||||
state ^= state >> 16;
|
||||
|
||||
float u1 = float(state) * (1.0 / 4294967296.0);
|
||||
|
||||
state ^= state >> 16;
|
||||
state *= 0x7FEB352Du;
|
||||
state ^= state >> 15;
|
||||
state *= 0x846CA68Bu;
|
||||
state ^= state >> 16;
|
||||
|
||||
float u2 = float(state) * (1.0 / 4294967296.0);
|
||||
|
||||
// Cosine-weighted hemisphere sampling.
|
||||
float r = sqrt(u1);
|
||||
float phi = 2.0 * 3.14159 * u2;
|
||||
|
||||
float x = r * cos(phi);
|
||||
float y = r * sin(phi);
|
||||
float z = sqrt(max(0.0, 1.0 - u1));
|
||||
|
||||
// Build an orthonormal basis around the normal.
|
||||
float3 tangent;
|
||||
|
||||
if (abs(normal.z) < 0.999)
|
||||
tangent = normalize(cross(float3(0.0, 0.0, 1.0), normal));
|
||||
else
|
||||
tangent = normalize(cross(float3(0.0, 1.0, 0.0), normal));
|
||||
|
||||
float3 bitangent = cross(normal, tangent);
|
||||
|
||||
// Transform from local hemisphere space to world space.
|
||||
return normalize(
|
||||
tangent * x +
|
||||
bitangent * y +
|
||||
normal * z);
|
||||
// let ao = 1. - float(occluded) / float(AO_SAMPLE_COUNT);
|
||||
// Soften the effect: a fully black crevice reads as a hole in this demo.
|
||||
// let lit = lerp(1., ao, 0.7);
|
||||
// target_texture.Store(location.xy, float4(albedo.rgb * lit, albedo.a));
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,45 @@
|
||||
module lod_policies;
|
||||
import voxel_tracing;
|
||||
|
||||
public struct PixelFootprintLod : ILodPolicy
|
||||
{
|
||||
// Angular size of one pixel in radians (small-angle approximation).
|
||||
// For a pinhole camera: 2 * tan(fovY * 0.5) / imageHeightInPixels.
|
||||
public float pixelAngle;
|
||||
|
||||
// How many pixels a node may cover before we refuse to stop.
|
||||
// 1.0 = stop once a node is <= 1 pixel wide.
|
||||
// < 1.0 = more detail (sharper, slower), > 1.0 = coarser (faster, blurrier).
|
||||
public float pixelThreshold;
|
||||
|
||||
// Cone radius at t = 0. Zero for a pinhole camera; non-zero for
|
||||
// secondary rays that inherit a footprint from a previous bounce.
|
||||
public float coneRadius0;
|
||||
|
||||
// Footprint (world-space width of one pixel) at ray distance t.
|
||||
public float footprint(float t)
|
||||
{
|
||||
return coneRadius0 + t * pixelAngle;
|
||||
}
|
||||
|
||||
public bool shouldStop(float t, float nodeSize)
|
||||
{
|
||||
// Node edge length not larger than the allowed pixel coverage -> stop.
|
||||
return nodeSize <= footprint(t) * pixelThreshold;
|
||||
}
|
||||
|
||||
// Convenience constructor from camera parameters.
|
||||
public static PixelFootprintLod create(
|
||||
float fovYRadians,
|
||||
float imageHeightPixels,
|
||||
float pixelThreshold = 1.0,
|
||||
float coneRadius0 = 0.0)
|
||||
{
|
||||
PixelFootprintLod p;
|
||||
p.pixelAngle = 2.0 * tan(0.5 * fovYRadians) / imageHeightPixels;
|
||||
p.pixelThreshold = pixelThreshold;
|
||||
p.coneRadius0 = coneRadius0;
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,390 +0,0 @@
|
||||
module ray_cast;
|
||||
|
||||
struct ByteColor
|
||||
{
|
||||
uint32_t byte_color;
|
||||
|
||||
property uint32_t byte_r
|
||||
{
|
||||
get {
|
||||
return byte_color & 0xFF;
|
||||
}
|
||||
}
|
||||
|
||||
property uint32_t byte_g
|
||||
{
|
||||
get {
|
||||
return (byte_color >> 8) & 0xFF;
|
||||
}
|
||||
}
|
||||
|
||||
property uint32_t byte_b
|
||||
{
|
||||
get {
|
||||
return (byte_color >> 16) & 0xFF;
|
||||
}
|
||||
}
|
||||
|
||||
property uint32_t byte_a
|
||||
{
|
||||
get {
|
||||
return byte_color >> 24;
|
||||
}
|
||||
}
|
||||
|
||||
property float4 float_color
|
||||
{
|
||||
get {
|
||||
return float4(
|
||||
float(byte_r) / 255.,
|
||||
float(byte_g) / 255.,
|
||||
float(byte_b) / 255.,
|
||||
float(byte_a) / 255.);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public struct StructurePointer
|
||||
{
|
||||
uint32_t value;
|
||||
|
||||
bool subdivided()
|
||||
{
|
||||
return (this.value & 0x80000000) != 0;
|
||||
}
|
||||
|
||||
bool pointer_valid()
|
||||
{
|
||||
return (this.value & 0x40000000) != 0;
|
||||
}
|
||||
|
||||
bool subdivided_valid()
|
||||
{
|
||||
return (this.value & 0xC0000000) == 0xC0000000;
|
||||
}
|
||||
|
||||
uint32_t pointer()
|
||||
{
|
||||
return this.value & 0x3FFFFFFF;
|
||||
}
|
||||
}
|
||||
|
||||
public struct StructurePoolElement
|
||||
{
|
||||
public uint32_t occupancy_low;
|
||||
public uint32_t occupancy_high;
|
||||
public StructurePointer pointers[64];
|
||||
}
|
||||
|
||||
public struct RequestBufferElement
|
||||
{
|
||||
public Atomic<uint32_t> requests[64];
|
||||
}
|
||||
|
||||
public struct VoxelCache
|
||||
{
|
||||
public RWStructuredBuffer<StructurePoolElement> structure_pool;
|
||||
public RWStructuredBuffer<uint32_t> attributes_pool[2];
|
||||
public RWStructuredBuffer<RequestBufferElement> request_buffer;
|
||||
public RWStructuredBuffer<uint32_t> usage_buffer;
|
||||
|
||||
public RWStructuredBuffer<StructurePointer> structure_table_pointer;
|
||||
public RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
|
||||
}
|
||||
|
||||
ByteColor fetch_color(VoxelCache cache, uint32_t index, uint32_t child_index)
|
||||
{
|
||||
return ByteColor(cache.attributes_pool[0][index * 64 + child_index]);
|
||||
}
|
||||
|
||||
uint32_t3 get_children_pos(float3 position, uint32_t scale_exp)
|
||||
{
|
||||
return (asuint(position) >> scale_exp) & 3;
|
||||
}
|
||||
|
||||
uint32_t get_children_index(float3 position, uint32_t scale_exp)
|
||||
{
|
||||
// Get mantissa bits for this scale exp an retain bits for the specific children
|
||||
uint32_t3 cell_position = (asuint(position) >> scale_exp) & 3;
|
||||
return cell_position.x + cell_position.y * 4 + cell_position.z * 4 * 4;
|
||||
}
|
||||
|
||||
uint64_t get_child_mask(uint32_t low, uint32_t high)
|
||||
{
|
||||
return ((uint64_t)high << 32) | (uint64_t)low;
|
||||
}
|
||||
|
||||
float3 floor_scale(float3 position, uint32_t scale_exp)
|
||||
{
|
||||
uint32_t mask = ~0u << scale_exp;
|
||||
return asfloat(asuint(position) & mask);
|
||||
}
|
||||
|
||||
public struct HitInformation
|
||||
{
|
||||
public bool hit;
|
||||
public float3 hit_pos;
|
||||
public uint32_t node_index;
|
||||
public uint32_t child_index;
|
||||
public float4 color;
|
||||
}
|
||||
|
||||
groupshared uint32_t stack[256 * 5];
|
||||
|
||||
HitInformation chunk_ray_march(
|
||||
VoxelCache cache,
|
||||
float3 real_ray_direction,
|
||||
float3 ray_origin,
|
||||
uint32_t root_id,
|
||||
float dist_offset,
|
||||
uint32_t stack_index,
|
||||
uint32_t frame_timestamp,
|
||||
bool report, )
|
||||
{
|
||||
// Cone tracing info
|
||||
float fov_deg = 100. / 1920.;
|
||||
float fov_rad = (float.getPi() * fov_deg) / 180.;
|
||||
float cone_factor = tan(fov_rad / 2.) * 2; // Horizontal size of pixel
|
||||
|
||||
let st_pointer = cache.structure_table_pointer[root_id];
|
||||
|
||||
if (!st_pointer.subdivided())
|
||||
{
|
||||
var hit : HitInformation;
|
||||
hit.hit = false;
|
||||
return hit;
|
||||
}
|
||||
|
||||
if (!st_pointer.pointer_valid())
|
||||
{
|
||||
// Record request
|
||||
if (report)
|
||||
{
|
||||
cache.structure_table_request_buffer[root_id].add(1);
|
||||
}
|
||||
var hit : HitInformation;
|
||||
hit.hit = false;
|
||||
return hit;
|
||||
}
|
||||
// _hit.color = float4(0., 1., 0., 1.);
|
||||
// return _hit;
|
||||
|
||||
// Ray mirroring
|
||||
ray_origin += float3(1.);
|
||||
ray_origin = clamp(ray_origin, float(1.), asfloat(0x3fffffff));
|
||||
ray_origin = select(real_ray_direction > 0., asfloat(asuint(ray_origin) ^ 0x007fffff), ray_origin);
|
||||
uint32_t child_mirror = 0;
|
||||
if (real_ray_direction.x > 0.)
|
||||
{
|
||||
child_mirror |= 3;
|
||||
}
|
||||
if (real_ray_direction.y > 0.)
|
||||
{
|
||||
child_mirror |= 3 << 2;
|
||||
}
|
||||
if (real_ray_direction.z > 0.)
|
||||
{
|
||||
child_mirror |= 3 << 4;
|
||||
}
|
||||
let ray_direction = -abs(real_ray_direction);
|
||||
|
||||
float3 pos = ray_origin;
|
||||
uint32_t scale_exp = 23 - 2;
|
||||
uint32_t current_node_index = cache.structure_table_pointer[root_id].pointer();
|
||||
if (report)
|
||||
{
|
||||
cache.usage_buffer[current_node_index] = frame_timestamp;
|
||||
}
|
||||
stack[stack_index * 5 + 10 - scale_exp / 2] = current_node_index;
|
||||
|
||||
[loop]
|
||||
for (uint32_t iter = 0; iter < 500; iter++)
|
||||
{
|
||||
uint32_t child_index = get_children_index(pos, scale_exp) ^ child_mirror;
|
||||
StructurePointer current_node = cache.structure_pool[current_node_index].pointers[child_index];
|
||||
|
||||
// Scale computations
|
||||
let cone_size = (length(ray_origin - pos) + dist_offset) * cone_factor;
|
||||
let exponent =
|
||||
select(
|
||||
cone_size == 0.,
|
||||
0,
|
||||
23 - (127 - (asuint(cone_size) >> 23)));
|
||||
|
||||
while (
|
||||
current_node.subdivided_valid() &&
|
||||
scale_exp - 2 > exponent)
|
||||
{
|
||||
scale_exp -= 2;
|
||||
current_node_index = current_node.pointer();
|
||||
stack[stack_index * 5 + 10 - scale_exp / 2] = current_node_index;
|
||||
child_index = get_children_index(pos, scale_exp) ^ child_mirror;
|
||||
current_node = cache.structure_pool[current_node_index].pointers[child_index];
|
||||
// Write usage
|
||||
if (report)
|
||||
{
|
||||
cache.usage_buffer[current_node_index] = frame_timestamp;
|
||||
}
|
||||
}
|
||||
|
||||
// Request subdiv
|
||||
if (report && current_node.subdivided() && !current_node.pointer_valid())
|
||||
{
|
||||
cache.request_buffer[current_node_index].requests[child_index].add(1);
|
||||
}
|
||||
|
||||
uint64_t occupancy = get_child_mask(cache.structure_pool[current_node_index].occupancy_low, cache.structure_pool[current_node_index].occupancy_high);
|
||||
let occupied = ((occupancy >> child_index) & 1) != 0;
|
||||
if (fetch_color(cache, current_node_index, child_index).byte_a != 0)
|
||||
{
|
||||
var hit : HitInformation;
|
||||
hit.hit = true;
|
||||
hit.node_index = current_node_index;
|
||||
hit.child_index = child_index;
|
||||
hit.hit_pos =
|
||||
select(
|
||||
real_ray_direction > 0.,
|
||||
asfloat(asuint(pos) ^ 0x007fffff),
|
||||
pos) -
|
||||
float3(1.);
|
||||
return hit;
|
||||
}
|
||||
|
||||
uint32_t adv_scale_exp = scale_exp;
|
||||
if (((occupancy >> (child_index & 0b101010)) & 0x00330033) == 0)
|
||||
{
|
||||
adv_scale_exp++;
|
||||
}
|
||||
|
||||
// Perform dda
|
||||
// Compute correct exponent, and shift it into the exponent part of floatt
|
||||
let child_pos : float3 = floor_scale(pos, adv_scale_exp);
|
||||
// Intersection t
|
||||
let inter_ts : float3 = (child_pos - ray_origin) / ray_direction;
|
||||
float inter_t = min(inter_ts.x, min(inter_ts.y, inter_ts.z));
|
||||
// return float4(inter_t);
|
||||
|
||||
// Perform dda step
|
||||
// let neighbor_max = asint(child_pos) + select(inter_t == inter_ts, -1, (1 << adv_scale_exp) - 1);
|
||||
let neighbor_max = asint(child_pos) + select(inter_t == inter_ts, -1, (1 << adv_scale_exp) - 1);
|
||||
pos = min(ray_origin + ray_direction * inter_t, asfloat(neighbor_max));
|
||||
|
||||
// Find most common ancestor
|
||||
uint32_t3 diffs = asuint(child_pos) ^ asuint(pos);
|
||||
uint32_t diff = (diffs.x | diffs.y | diffs.z);
|
||||
|
||||
int32_t common_depth = (1 + (22 - firstbithigh(diff)) / 2) * 2;
|
||||
if (common_depth <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
scale_exp = 23 - common_depth;
|
||||
current_node_index = stack[stack_index * 5 + 10 - scale_exp / 2];
|
||||
}
|
||||
|
||||
var hit : HitInformation;
|
||||
hit.hit = false;
|
||||
return hit;
|
||||
}
|
||||
|
||||
public struct RayCastContext
|
||||
{
|
||||
public float3 ray_direction;
|
||||
public float3 ray_origin;
|
||||
public uint32_t3 bounds;
|
||||
public uint32_t frame_timestamp;
|
||||
public bool cache_report;
|
||||
}
|
||||
|
||||
public HitInformation ray_cast(
|
||||
VoxelCache cache,
|
||||
RayCastContext context,
|
||||
uint32_t thread_id)
|
||||
{
|
||||
let stack_index = thread_id;
|
||||
|
||||
// Intersect with bounds
|
||||
var inter = box_intersect(context.ray_origin, context.ray_direction, float3(0.), float3(context.bounds.x, context.bounds.y, context.bounds.z));
|
||||
|
||||
// No hit if out of box
|
||||
if (inter.y <= inter.x || inter.y <= 0.)
|
||||
{
|
||||
var hit : HitInformation;
|
||||
hit.hit = false;
|
||||
return hit;
|
||||
}
|
||||
inter.x = max(0., inter.x);
|
||||
|
||||
// Now march inside chunk bounds
|
||||
let start_position = inter.x * context.ray_direction + context.ray_origin;
|
||||
// FVT
|
||||
int32_t3 current_voxel = clamp(
|
||||
int32_t3(floor(start_position)),
|
||||
int32_t3(0),
|
||||
int32_t3(context.bounds.x - 1, context.bounds.y - 1, context.bounds.z - 1));
|
||||
// int32_t3 offset = int32_t3(sign(ray_direction));
|
||||
// float3 delta = abs(1. / ray_direction);
|
||||
float3 t = select(
|
||||
context.ray_direction > 0.,
|
||||
current_voxel + int32_t3(1) - start_position,
|
||||
start_position - current_voxel) /
|
||||
abs(context.ray_direction);
|
||||
t += inter.x;
|
||||
|
||||
[loop]
|
||||
while (true)
|
||||
{
|
||||
if (any(current_voxel < 0) || any(current_voxel >= int32_t3(context.bounds.x, context.bounds.y, context.bounds.z)))
|
||||
{
|
||||
var hit : HitInformation;
|
||||
hit.hit = false;
|
||||
return hit;
|
||||
}
|
||||
{
|
||||
let off = t - abs(1. / context.ray_direction);
|
||||
let t_adv = max(max(off.x, max(off.y, off.z)), 0.);
|
||||
// let chunk_index = current_voxel.y + current_voxel.z * context.bounds.y + current_voxel.x * context.bounds.y * context.bounds.z;
|
||||
let chunk_index = current_voxel.x + current_voxel.z * context.bounds.x + current_voxel.y * context.bounds.x * context.bounds.z;
|
||||
let position = context.ray_origin + context.ray_direction * t_adv;
|
||||
var hit = chunk_ray_march(
|
||||
cache,
|
||||
context.ray_direction,
|
||||
position - float3(current_voxel),
|
||||
chunk_index,
|
||||
max(t_adv, 0.01),
|
||||
stack_index,
|
||||
context.frame_timestamp,
|
||||
context.cache_report);
|
||||
if (hit.hit)
|
||||
{
|
||||
hit.hit_pos += float3(current_voxel);
|
||||
return hit;
|
||||
}
|
||||
}
|
||||
|
||||
let min_mask = min_mask(t);
|
||||
t += select(min_mask, abs(1. / context.ray_direction), float3(0.));
|
||||
current_voxel += select(min_mask, int32_t3(sign(context.ray_direction)), int32_t3(0));
|
||||
}
|
||||
}
|
||||
|
||||
bool3 min_mask(float3 val)
|
||||
{
|
||||
let min_val = min(val.x, min(val.y, val.z));
|
||||
return val == min_val;
|
||||
}
|
||||
|
||||
float2 box_intersect(float3 origin, float3 ray_direction, float3 box_min, float3 box_max)
|
||||
{
|
||||
let min_ts = (box_min - origin) / ray_direction;
|
||||
let max_ts = (box_max - origin) / ray_direction;
|
||||
|
||||
let far_ts = max(min_ts, max_ts);
|
||||
let near_ts = min(min_ts, max_ts);
|
||||
|
||||
let far_t = min(far_ts.x, min(far_ts.y, far_ts.z));
|
||||
let near_t = max(near_ts.x, max(near_ts.y, near_ts.z));
|
||||
return float2(near_t, far_t);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
module toroidal_structure_table;
|
||||
|
||||
import voxel_cache;
|
||||
import voxel_tracing;
|
||||
|
||||
/// Parameters for the fixed structure table
|
||||
public struct ToroidalStructureTable
|
||||
{
|
||||
RWStructuredBuffer<StructurePointer> structure_table_pointer;
|
||||
RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
|
||||
}
|
||||
|
||||
public struct ToroidalStructureTableChunksCursor
|
||||
{
|
||||
/// World-space minimum corner of the visible chunk block.
|
||||
int32_t3 offset;
|
||||
|
||||
/// Current chunk in world space. This is deliberately *not* wrapped: it is
|
||||
/// used for the block bounds and to compute the ray position inside the
|
||||
/// chunk.
|
||||
int32_t3 current_voxel;
|
||||
|
||||
/// Current chunk in table-slot space. Always in [0, extent), advanced
|
||||
/// incrementally so the hot loop never needs an integer modulo.
|
||||
int32_t3 local_voxel;
|
||||
|
||||
float3 t_off;
|
||||
float3 t;
|
||||
|
||||
Ray r;
|
||||
}
|
||||
|
||||
/// Uses a fixed structure table as a dense array of chunks
|
||||
public struct ToroidalStructureTableTracer : IStructure
|
||||
{
|
||||
typedef ToroidalStructureTableChunksCursor Cursor;
|
||||
|
||||
public ToroidalStructureTable structure_table;
|
||||
public uint32_t3 extent;
|
||||
|
||||
/// Canonical table slot of the block minimum corner:
|
||||
/// `imod(current_offset, extent)`. Computed on the CPU once per table move
|
||||
/// so the shader does not need integer modulo anywhere.
|
||||
public uint32_t3 base_slot;
|
||||
|
||||
public ToroidalStructureTableChunksCursor begin(Ray worldRay)
|
||||
{
|
||||
ToroidalStructureTableChunksCursor cursor;
|
||||
// Now march inside chunk bounds
|
||||
let start_position = worldRay.origin;
|
||||
|
||||
// FVT clamp to block
|
||||
cursor.current_voxel = int32_t3(floor(start_position));
|
||||
cursor.offset = cursor.current_voxel - int32_t3(this.extent) / 2;
|
||||
|
||||
// The block is exactly one table period wide. Starting from the base
|
||||
// slot of the block corner, the slot of the current chunk is the
|
||||
// block-local coordinate plus that base, wrapped once.
|
||||
let block_local = cursor.current_voxel - cursor.offset;
|
||||
cursor.local_voxel = block_local + int32_t3(this.base_slot);
|
||||
cursor.local_voxel = select(
|
||||
cursor.local_voxel >= int32_t3(this.extent),
|
||||
cursor.local_voxel - int32_t3(this.extent),
|
||||
cursor.local_voxel);
|
||||
|
||||
cursor.t_off = abs(1. / worldRay.direction);
|
||||
|
||||
// Take t of next boundary
|
||||
cursor.t = select(
|
||||
worldRay.direction > 0.,
|
||||
cursor.current_voxel + int32_t3(1) - start_position,
|
||||
start_position - cursor.current_voxel) *
|
||||
cursor.t_off;
|
||||
|
||||
// Add camera offset
|
||||
cursor.r = worldRay;
|
||||
return cursor;
|
||||
}
|
||||
|
||||
public bool next(inout Cursor c, out Cell cell)
|
||||
{
|
||||
while (all(c.current_voxel >= c.offset) && all(c.current_voxel < c.offset + int32_t3(extent)))
|
||||
{
|
||||
// Current hit
|
||||
let off = c.t - c.t_off;
|
||||
let t_adv = max(max(off.x, max(off.y, off.z)), 0.);
|
||||
let chunk_index =
|
||||
c.local_voxel.x +
|
||||
c.local_voxel.z * this.extent.x +
|
||||
c.local_voxel.y * this.extent.x * this.extent.z;
|
||||
let position = c.r.origin + c.r.direction * t_adv;
|
||||
|
||||
var hit = false;
|
||||
if (this.structure_table.structure_table_pointer[chunk_index].subdivided_valid())
|
||||
{
|
||||
cell.cache_pointer = this.structure_table.structure_table_pointer[chunk_index].pointer();
|
||||
cell.local_ray.origin = position - float3(c.current_voxel);
|
||||
cell.local_ray.direction = c.r.direction;
|
||||
cell.t = t_adv;
|
||||
cell.cube_to_world = mat3_identity();
|
||||
cell.world_origin = float3(c.current_voxel);
|
||||
hit = true;
|
||||
}
|
||||
else if (this.structure_table.structure_table_pointer[chunk_index].subdivided())
|
||||
{
|
||||
this.structure_table.structure_table_request_buffer[chunk_index].add(1);
|
||||
hit = false;
|
||||
}
|
||||
|
||||
// Advance. One axis may step by +/-1 (or several axes on a tie).
|
||||
let advance = min_mask(c.t);
|
||||
let step = select(advance, int32_t3(sign(c.r.direction)), int32_t3(0));
|
||||
c.t += select(advance, c.t_off, float3(0.));
|
||||
c.current_voxel += step;
|
||||
|
||||
// Keep the table slot wrapped incrementally. Since `local_voxel`
|
||||
// is in [0, extent) and `step` is at most one per axis, a single
|
||||
// conditional add/sub is enough.
|
||||
c.local_voxel += step;
|
||||
c.local_voxel = select(
|
||||
c.local_voxel >= int32_t3(this.extent),
|
||||
c.local_voxel - int32_t3(this.extent),
|
||||
c.local_voxel);
|
||||
c.local_voxel = select(
|
||||
c.local_voxel < int32_t3(0),
|
||||
c.local_voxel + int32_t3(this.extent),
|
||||
c.local_voxel);
|
||||
|
||||
if (hit)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool3 min_mask(float3 val)
|
||||
{
|
||||
let min_val = min(val.x, min(val.y, val.z));
|
||||
return val == min_val;
|
||||
}
|
||||
|
||||
float2 box_intersect(float3 origin, float3 ray_direction, float3 box_min, float3 box_max)
|
||||
{
|
||||
let min_ts = (box_min - origin) / ray_direction;
|
||||
let max_ts = (box_max - origin) / ray_direction;
|
||||
|
||||
let far_ts = max(min_ts, max_ts);
|
||||
let near_ts = min(min_ts, max_ts);
|
||||
|
||||
let far_t = min(far_ts.x, min(far_ts.y, far_ts.z));
|
||||
let near_t = max(near_ts.x, max(near_ts.y, near_ts.z));
|
||||
return float2(near_t, far_t);
|
||||
}
|
||||
|
||||
+102
-85
@@ -1,4 +1,10 @@
|
||||
import ray_cast;
|
||||
// import ray_cast;
|
||||
import voxel_cache;
|
||||
// import fixed_structure_table;
|
||||
import toroidal_structure_table;
|
||||
import bvh;
|
||||
import voxel_tracing;
|
||||
import lod_policies;
|
||||
|
||||
struct PushConstants
|
||||
{
|
||||
@@ -11,6 +17,12 @@ struct PushConstants
|
||||
uint32_t chunk_width;
|
||||
uint32_t chunk_height;
|
||||
uint32_t chunk_alt;
|
||||
|
||||
// Canonical table slot of the visible block's minimum corner. Computed on
|
||||
// the CPU from the toroidal table's current offset.
|
||||
uint32_t table_base_slot_x;
|
||||
uint32_t table_base_slot_y;
|
||||
uint32_t table_base_slot_z;
|
||||
}
|
||||
|
||||
public struct VertexOutput
|
||||
@@ -21,86 +33,46 @@ 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;
|
||||
}
|
||||
|
||||
[[vk::push_constant]]
|
||||
uniform PushConstants constants;
|
||||
|
||||
struct ByteColor
|
||||
{
|
||||
uint32_t byte_color;
|
||||
ParameterBlock<VoxelCacheParameters<2>> cache_parameters;
|
||||
// ParameterBlock<ToroidalStructureTable> table_parameters;
|
||||
ParameterBlock<BvhParameters> table_parameters;
|
||||
|
||||
property uint32_t byte_r
|
||||
{
|
||||
get {
|
||||
return byte_color & 0xFF;
|
||||
}
|
||||
}
|
||||
// ColorHit<2> (the demo hit predicate) lives in voxel_cache.slang so the
|
||||
// primary and secondary front-ends share one definition.
|
||||
|
||||
property uint32_t byte_g
|
||||
{
|
||||
get {
|
||||
return (byte_color >> 8) & 0xFF;
|
||||
}
|
||||
}
|
||||
|
||||
property uint32_t byte_b
|
||||
{
|
||||
get {
|
||||
return (byte_color >> 16) & 0xFF;
|
||||
}
|
||||
}
|
||||
|
||||
property uint32_t byte_a
|
||||
{
|
||||
get {
|
||||
return byte_color >> 24;
|
||||
}
|
||||
}
|
||||
|
||||
property float4 float_color
|
||||
{
|
||||
get {
|
||||
return float4(
|
||||
float(byte_r) / 255.,
|
||||
float(byte_g) / 255.,
|
||||
float(byte_b) / 255.,
|
||||
float(byte_a) / 255.);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[vk::binding(0, 0)]]
|
||||
RWStructuredBuffer<StructurePoolElement> structure_pool;
|
||||
[[vk::binding(1, 0)]]
|
||||
RWStructuredBuffer<uint32_t> attributes_pool[2];
|
||||
[[vk::binding(2, 0)]]
|
||||
RWStructuredBuffer<RequestBufferElement> request_buffer;
|
||||
[[vk::binding(3, 0)]]
|
||||
RWStructuredBuffer<uint32_t> usage_buffer;
|
||||
|
||||
[[vk::binding(0, 1)]]
|
||||
RWStructuredBuffer<StructurePointer> structure_table_pointer;
|
||||
[[vk::binding(1, 1)]]
|
||||
RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
|
||||
// [[vk::binding(0, 0)]]
|
||||
// RWStructuredBuffer<StructurePoolElement> structure_pool;
|
||||
// [[vk::binding(1, 0)]]
|
||||
// RWStructuredBuffer<RequestBufferElement> request_buffer;
|
||||
// [[vk::binding(2, 0)]]
|
||||
// RWStructuredBuffer<uint32_t> usage_buffer;
|
||||
// [[vk::binding(3, 0)]]
|
||||
// RWStructuredBuffer<uint32_t> attributes_pool[2];
|
||||
//
|
||||
// [[vk::binding(0, 1)]]
|
||||
// RWStructuredBuffer<StructurePointer> structure_table_pointer;
|
||||
// [[vk::binding(1, 1)]]
|
||||
// RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
|
||||
|
||||
ByteColor fetch_color(uint32_t index, uint32_t child_index)
|
||||
{
|
||||
return ByteColor(attributes_pool[0][index * 64 + child_index]);
|
||||
return ByteColor(cache_parameters.attributes_pool[0][index * 64 + child_index]);
|
||||
}
|
||||
|
||||
float3 fetch_normal(uint32_t index, uint32_t child_index)
|
||||
{
|
||||
let a = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3]);
|
||||
let b = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3 + 1]);
|
||||
let c = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3 + 2]);
|
||||
let a = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3]);
|
||||
let b = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3 + 1]);
|
||||
let c = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3 + 2]);
|
||||
return float3(a, b, c);
|
||||
}
|
||||
|
||||
@@ -143,42 +115,87 @@ void gi_march(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location:
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(16, 16, 1)]
|
||||
void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID)
|
||||
void ray_march_compute(uint32_t3 location: SV_DispatchThreadID)
|
||||
{
|
||||
if (location.x >= constants.width || location.y >= constants.height)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let stack_index = local_location.x + local_location.y * 16;
|
||||
VoxelCacheTracer<2, ColorHit<2>> cache_tracer;
|
||||
cache_tracer.parameters = cache_parameters;
|
||||
cache_tracer.frame_timestamp = constants.frame_timestamp;
|
||||
cache_tracer.voxel_hit = ColorHit<2>();
|
||||
|
||||
var voxel_cache : VoxelCache;
|
||||
voxel_cache.structure_pool = structure_pool;
|
||||
voxel_cache.attributes_pool = attributes_pool;
|
||||
voxel_cache.request_buffer = request_buffer;
|
||||
voxel_cache.usage_buffer = usage_buffer;
|
||||
voxel_cache.structure_table_pointer = structure_table_pointer;
|
||||
voxel_cache.structure_table_request_buffer = structure_table_request_buffer;
|
||||
// Per-ray trace state. Local storage keeps the tracer independent of the
|
||||
// workgroup shape; swap this for a groupshared-backed ITraceStack if the
|
||||
// primary pass needs groupshared memory back.
|
||||
LocalTraceStack stack;
|
||||
|
||||
TraceSettings settings;
|
||||
settings.t_min = 0.;
|
||||
settings.t_max = asfloat(0x7f7fffff); // FLT_MAX
|
||||
settings.max_cells = 0xFFFFFFFF;
|
||||
settings.max_steps = 500;
|
||||
settings.any_hit = false;
|
||||
settings.report_usage = true;
|
||||
settings.report_requests = true;
|
||||
|
||||
let ray_direction = get_ray_direction(location.xy);
|
||||
|
||||
var ray_cast_context : RayCastContext;
|
||||
ray_cast_context.ray_direction = ray_direction;
|
||||
ray_cast_context.ray_origin = constants.cam_pos;
|
||||
ray_cast_context.bounds = uint32_t3(constants.chunk_width, constants.chunk_alt, constants.chunk_width);
|
||||
ray_cast_context.frame_timestamp = constants.frame_timestamp;
|
||||
ray_cast_context.cache_report = true;
|
||||
Ray r;
|
||||
r.origin = constants.cam_pos;
|
||||
r.direction = ray_direction;
|
||||
|
||||
let hit = ray_cast(voxel_cache, ray_cast_context, stack_index);
|
||||
Bvh bvh;
|
||||
bvh.parameters = table_parameters;
|
||||
bvh.max_t = asfloat(0x7f7fffff); // FLT_MAX: unbounded primary rays
|
||||
// BvhCursor c = bvh.begin(r);
|
||||
Cell cell;
|
||||
|
||||
if (hit.hit)
|
||||
// Setup for simple bvh traversal check
|
||||
// if (bvh.next(c, cell))
|
||||
// {
|
||||
// gbuffer_albedo.Store(location.xy, float4(0., 1., 0., 1.));
|
||||
// return;
|
||||
// }
|
||||
// gbuffer_albedo.Store(location.xy, float4(0.));
|
||||
|
||||
// ToroidalStructureTableTracer table_tracer;
|
||||
// table_tracer.structure_table = table_parameters;
|
||||
// table_tracer.extent =
|
||||
// uint32_t3(constants.chunk_width, constants.chunk_alt, constants.chunk_height);
|
||||
// table_tracer.base_slot = uint32_t3(
|
||||
// constants.table_base_slot_x,
|
||||
// constants.table_base_slot_y,
|
||||
// constants.table_base_slot_z);
|
||||
|
||||
PixelFootprintLod lod = PixelFootprintLod.create((100.f * 3.14f) / 180.f, 1080.f, 2.f);
|
||||
|
||||
Tracer<Bvh, VoxelCacheTracer<2, ColorHit<2>>, PixelFootprintLod> tracer;
|
||||
tracer.structure = bvh;
|
||||
tracer.cache = cache_tracer;
|
||||
tracer.lod = lod;
|
||||
|
||||
Hit h;
|
||||
// Closest hit at or past tMin. Re-trace past a hit with:
|
||||
// settings.t_min = h.t + 1e-4;
|
||||
// hit = tracer.trace(h, r, settings, stack);
|
||||
bool hit = tracer.trace(h, r, settings, stack);
|
||||
|
||||
// ToroidalStructureTableTracer.Cursor cursor = table_tracer.begin(r);
|
||||
// Cell cell;
|
||||
|
||||
if (hit)
|
||||
{
|
||||
// Gather
|
||||
let hit_pos = hit.hit_pos;
|
||||
// `Hit` is already in world space; only the local attribute normal
|
||||
// still needs rotating into world space.
|
||||
let hit_pos = h.hit_location;
|
||||
|
||||
let hit_normal = fetch_normal(hit.node_index, hit.child_index);
|
||||
let local_normal = mul(h.normal_to_world, fetch_normal(h.node_index, h.child_index));
|
||||
let hit_normal = local_normal / max(length(local_normal), 1e-6);
|
||||
var hit_albedo = float4(0.);
|
||||
hit_albedo = fetch_color(hit.node_index, hit.child_index).float_color;
|
||||
hit_albedo = fetch_color(h.node_index, h.child_index).float_color;
|
||||
// let hit_albedo = hit.color;
|
||||
|
||||
gbuffer_position.Store(location.xy, float4(hit_pos, 1.));
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,281 @@
|
||||
import voxel_tracing;
|
||||
|
||||
public struct ByteColor
|
||||
{
|
||||
public uint32_t byte_color;
|
||||
|
||||
public property uint32_t byte_r
|
||||
{
|
||||
get {
|
||||
return byte_color & 0xFF;
|
||||
}
|
||||
}
|
||||
|
||||
public property uint32_t byte_g
|
||||
{
|
||||
get {
|
||||
return (byte_color >> 8) & 0xFF;
|
||||
}
|
||||
}
|
||||
|
||||
public property uint32_t byte_b
|
||||
{
|
||||
get {
|
||||
return (byte_color >> 16) & 0xFF;
|
||||
}
|
||||
}
|
||||
|
||||
public property uint32_t byte_a
|
||||
{
|
||||
get {
|
||||
return byte_color >> 24;
|
||||
}
|
||||
}
|
||||
|
||||
public property float4 float_color
|
||||
{
|
||||
get {
|
||||
return float4(
|
||||
float(byte_r) / 255.,
|
||||
float(byte_g) / 255.,
|
||||
float(byte_b) / 255.,
|
||||
float(byte_a) / 255.);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public struct StructurePointer
|
||||
{
|
||||
uint32_t value;
|
||||
|
||||
public bool subdivided()
|
||||
{
|
||||
return (this.value & 0x80000000) != 0;
|
||||
}
|
||||
|
||||
public bool pointer_valid()
|
||||
{
|
||||
return (this.value & 0x40000000) != 0;
|
||||
}
|
||||
|
||||
public bool subdivided_valid()
|
||||
{
|
||||
return (this.value & 0xC0000000) == 0xC0000000;
|
||||
}
|
||||
|
||||
public uint32_t pointer()
|
||||
{
|
||||
return this.value & 0x3FFFFFFF;
|
||||
}
|
||||
}
|
||||
|
||||
public struct StructureElement
|
||||
{
|
||||
public uint32_t occupancy_low;
|
||||
public uint32_t occupancy_high;
|
||||
public StructurePointer pointers[64];
|
||||
}
|
||||
|
||||
public struct RequestBufferElement
|
||||
{
|
||||
public Atomic<uint32_t> requests[64];
|
||||
}
|
||||
|
||||
/// Everything needed to trace within a voxelCache, to be used with a parameter block
|
||||
public struct VoxelCacheParameters<let N : uint>
|
||||
{
|
||||
public RWStructuredBuffer<StructureElement> structure_pool;
|
||||
public RWStructuredBuffer<RequestBufferElement> request_buffer;
|
||||
public RWStructuredBuffer<uint32_t> usage_buffer;
|
||||
public RWStructuredBuffer<uint32_t> attributes_pool[N];
|
||||
}
|
||||
|
||||
uint32_t3 get_children_pos(float3 position, uint32_t scale_exp)
|
||||
{
|
||||
return (asuint(position) >> scale_exp) & 3;
|
||||
}
|
||||
|
||||
uint32_t get_children_index(float3 position, uint32_t scale_exp)
|
||||
{
|
||||
// Get mantissa bits for this scale exp an retain bits for the specific children
|
||||
uint32_t3 cell_position = (asuint(position) >> scale_exp) & 3;
|
||||
return cell_position.x + cell_position.y * 4 + cell_position.z * 4 * 4;
|
||||
}
|
||||
|
||||
uint64_t get_child_mask(uint32_t low, uint32_t high)
|
||||
{
|
||||
return ((uint64_t)high << 32) | (uint64_t)low;
|
||||
}
|
||||
|
||||
float3 floor_scale(float3 position, uint32_t scale_exp)
|
||||
{
|
||||
uint32_t mask = ~0u << scale_exp;
|
||||
return asfloat(asuint(position) & mask);
|
||||
}
|
||||
|
||||
float node_size(uint32_t scale_exp)
|
||||
{
|
||||
let mantissa_mask = ~(~0u << 23);
|
||||
return asfloat(((1 << scale_exp) & mantissa_mask | (127 << 23))) - 1.f;
|
||||
}
|
||||
|
||||
ByteColor fetch_color<let N : int>(VoxelCacheParameters<N> p, uint32_t index, uint32_t child_index)
|
||||
{
|
||||
return ByteColor(p.attributes_pool[0][index * 64 + child_index]);
|
||||
}
|
||||
|
||||
public interface IVoxelHit<let N : uint32_t>
|
||||
{
|
||||
public bool shouldHit(VoxelCacheParameters<N> parameters, uint32_t node_index, uint32_t child_index);
|
||||
}
|
||||
|
||||
/// Default hit test for the demo layout: alpha != 0 means solid.
|
||||
public struct ColorHit<let N : uint32_t> : IVoxelHit<N>
|
||||
{
|
||||
public __init() {};
|
||||
|
||||
public bool shouldHit(VoxelCacheParameters<N> cache, uint32_t node_index, uint32_t child_index)
|
||||
{
|
||||
return ByteColor(cache.attributes_pool[0][node_index * 64 + child_index]).byte_a != 0;
|
||||
}
|
||||
}
|
||||
|
||||
public struct VoxelCacheTracer<let N : int, H : IVoxelHit<N>> : IVoxelCache
|
||||
{
|
||||
public uint32_t frame_timestamp;
|
||||
public H voxel_hit;
|
||||
public VoxelCacheParameters<N> parameters;
|
||||
|
||||
public bool trace<L : ILodPolicy, St : ITraceStack>(
|
||||
uint32_t root,
|
||||
Ray r,
|
||||
L lod,
|
||||
TraceSettings settings,
|
||||
float offset_t,
|
||||
inout St stack,
|
||||
out Hit v)
|
||||
{
|
||||
v.t = 0.;
|
||||
|
||||
// Ray mirroring
|
||||
r.origin += float3(1.);
|
||||
r.origin = clamp(r.origin, float(1.), asfloat(0x3fffffff));
|
||||
r.origin = select(r.direction > 0., asfloat(asuint(r.origin) ^ 0x007fffff), r.origin);
|
||||
uint32_t child_mirror = 0;
|
||||
if (r.direction.x > 0.)
|
||||
{
|
||||
child_mirror |= 3;
|
||||
}
|
||||
if (r.direction.y > 0.)
|
||||
{
|
||||
child_mirror |= 3 << 2;
|
||||
}
|
||||
if (r.direction.z > 0.)
|
||||
{
|
||||
child_mirror |= 3 << 4;
|
||||
}
|
||||
|
||||
let ray_direction = -abs(r.direction);
|
||||
|
||||
float t = 0.;
|
||||
float3 pos = r.origin;
|
||||
uint32_t scale_exp = 23 - 2;
|
||||
uint32_t current_node_index = root;
|
||||
if (settings.report_usage)
|
||||
{
|
||||
this.parameters.usage_buffer[current_node_index] = this.frame_timestamp;
|
||||
}
|
||||
stack.set(10 - scale_exp / 2, current_node_index);
|
||||
|
||||
[loop]
|
||||
for (uint32_t iter = 0; iter < settings.max_steps; iter++)
|
||||
{
|
||||
if (offset_t + t >= settings.t_max)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
uint32_t child_index = get_children_index(pos, scale_exp) ^ child_mirror;
|
||||
StructurePointer current_node = this.parameters.structure_pool[current_node_index].pointers[child_index];
|
||||
|
||||
while (current_node.subdivided_valid() && !lod.shouldStop(offset_t + t, node_size(scale_exp)))
|
||||
{
|
||||
scale_exp -= 2;
|
||||
current_node_index = current_node.pointer();
|
||||
stack.set(10 - scale_exp / 2, current_node_index);
|
||||
child_index = get_children_index(pos, scale_exp) ^ child_mirror;
|
||||
current_node = this.parameters.structure_pool[current_node_index].pointers[child_index];
|
||||
// Write usage
|
||||
if (settings.report_usage)
|
||||
{
|
||||
this.parameters.usage_buffer[current_node_index] = frame_timestamp;
|
||||
}
|
||||
}
|
||||
|
||||
// Request subdiv
|
||||
if (settings.report_requests && !lod.shouldStop(t + offset_t, node_size(scale_exp)) && current_node.subdivided() && !current_node.pointer_valid())
|
||||
{
|
||||
this.parameters.request_buffer[current_node_index].requests[child_index].add(1);
|
||||
}
|
||||
|
||||
uint64_t occupancy = get_child_mask(
|
||||
this.parameters.structure_pool[current_node_index].occupancy_low,
|
||||
this.parameters.structure_pool[current_node_index].occupancy_high);
|
||||
|
||||
let occupied = ((occupancy >> child_index) & 1) != 0;
|
||||
// if (fetch_color(this.parameters, current_node_index, child_index).byte_a != 0)
|
||||
// if (fetch_color(cache, current_node_index, child_index).byte_a != 0)
|
||||
if (occupied && voxel_hit.shouldHit(this.parameters, current_node_index, child_index))
|
||||
{
|
||||
v.hit = true;
|
||||
v.node_index = current_node_index;
|
||||
v.child_index = child_index;
|
||||
v.hit_location =
|
||||
select(
|
||||
r.direction > 0.,
|
||||
asfloat(asuint(pos) ^ 0x007fffff),
|
||||
pos) -
|
||||
float3(1.);
|
||||
v.t = offset_t + t;
|
||||
return true;
|
||||
}
|
||||
|
||||
uint32_t adv_scale_exp = scale_exp;
|
||||
if (((occupancy >> (child_index & 0b101010)) & 0x00330033) == 0)
|
||||
{
|
||||
adv_scale_exp++;
|
||||
}
|
||||
|
||||
// Perform dda
|
||||
// Compute correct exponent, and shift it into the exponent part of floatt
|
||||
let child_pos : float3 = floor_scale(pos, adv_scale_exp);
|
||||
// Intersection t
|
||||
let inter_ts : float3 = (child_pos - r.origin) / ray_direction;
|
||||
float inter_t = min(inter_ts.x, min(inter_ts.y, inter_ts.z));
|
||||
t = inter_t;
|
||||
// return float4(inter_t);
|
||||
|
||||
// Perform dda step
|
||||
// let neighbor_max = asint(child_pos) + select(inter_t == inter_ts, -1, (1 << adv_scale_exp) - 1);
|
||||
let neighbor_max = asint(child_pos) + select(inter_t == inter_ts, -1, (1 << adv_scale_exp) - 1);
|
||||
pos = min(r.origin + ray_direction * inter_t, asfloat(neighbor_max));
|
||||
|
||||
// Find most common ancestor
|
||||
uint32_t3 diffs = asuint(child_pos) ^ asuint(pos);
|
||||
uint32_t diff = (diffs.x | diffs.y | diffs.z);
|
||||
|
||||
int32_t common_depth = (1 + (22 - firstbithigh(diff)) / 2) * 2;
|
||||
if (common_depth <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
scale_exp = 23 - common_depth;
|
||||
current_node_index = stack.get(10 - scale_exp / 2);
|
||||
}
|
||||
|
||||
v.hit = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
module voxel_tracing;
|
||||
|
||||
public struct Ray
|
||||
{
|
||||
public float3 origin;
|
||||
public float3 direction;
|
||||
}
|
||||
|
||||
public struct Cell
|
||||
{
|
||||
/// Entry pointer into the cache
|
||||
public uint32_t cache_pointer; // entry into the cache
|
||||
|
||||
/// Ray to be traced inside the cache
|
||||
public Ray local_ray;
|
||||
|
||||
/// How much distance from the camera
|
||||
public float t;
|
||||
|
||||
/// Rotation/scale from the cell's unit-cube space to world space.
|
||||
/// Identity for axis-aligned chunks.
|
||||
public float3x3 cube_to_world;
|
||||
|
||||
/// World-space position of the cell's unit-cube origin.
|
||||
public float3 world_origin;
|
||||
}
|
||||
|
||||
public interface IStructure
|
||||
{
|
||||
/// A cursor structure to keep ray state
|
||||
public associatedtype Cursor;
|
||||
|
||||
/// Begins tracing a certain ray, with a span
|
||||
public Cursor begin(Ray worldRay);
|
||||
|
||||
/// Returns whether it hits, updating the state, and returning a cell structure if hit.
|
||||
public bool next(inout Cursor c, out Cell cell); // next populated cell along the ray
|
||||
}
|
||||
|
||||
public interface ILodPolicy
|
||||
{
|
||||
/// cone / pixel-footprint termination
|
||||
public bool shouldStop(float t, float nodeSize);
|
||||
}
|
||||
|
||||
public struct Hit
|
||||
{
|
||||
public bool hit;
|
||||
|
||||
// Cache location
|
||||
public uint32_t node_index;
|
||||
public uint32_t child_index;
|
||||
public float3 hit_location; // world space
|
||||
|
||||
/// Rotation applied to the hit's local attribute normals.
|
||||
public float3x3 normal_to_world;
|
||||
|
||||
/// Distance of the hit from the ray origin, in the units of the ray
|
||||
/// direction. Used to order hits and to restart the traversal past a hit.
|
||||
public float t;
|
||||
}
|
||||
|
||||
/// Identity matrix helper (scalar-to-matrix casts splat instead of making an
|
||||
/// identity in Slang).
|
||||
public float3x3 mat3_identity()
|
||||
{
|
||||
return float3x3(
|
||||
1., 0., 0.,
|
||||
0., 1., 0.,
|
||||
0., 0., 1.);
|
||||
}
|
||||
|
||||
/// Per-ray parameters for a trace call.
|
||||
///
|
||||
/// Primary and secondary rays use the same tracer; only these values differ.
|
||||
/// `t_min`/`t_max` are world-space distances along the (normalised) ray
|
||||
/// direction. A hit at exactly `t_max` is excluded, so `t_max` is an open
|
||||
/// interval end.
|
||||
public struct TraceSettings
|
||||
{
|
||||
/// Start of the search interval. Re-traces set this just past the
|
||||
/// previous hit.
|
||||
public float t_min;
|
||||
|
||||
/// End of the search interval. Use FLT_MAX for unbounded traces.
|
||||
public float t_max;
|
||||
|
||||
/// Maximum number of structure cells to visit.
|
||||
public uint32_t max_cells;
|
||||
|
||||
/// Maximum number of DDA iterations inside one cache cell.
|
||||
public uint32_t max_steps;
|
||||
|
||||
/// Stop at the first acceptable hit instead of accumulating the nearest
|
||||
/// one. Meant for shadow/visibility rays.
|
||||
public bool any_hit;
|
||||
|
||||
/// Refresh the LRU timestamp of every node the ray touches.
|
||||
public bool report_usage;
|
||||
|
||||
/// Emit cache detail requests for nodes the ray reaches at the LOD.
|
||||
public bool report_requests;
|
||||
}
|
||||
|
||||
/// Per-ray stack access owned by the caller.
|
||||
///
|
||||
/// The trace core never stores the stack itself, so a front-end chooses where
|
||||
/// it lives. [`LocalTraceStack`] keeps it in per-thread storage. A primary pass
|
||||
/// that wants groupshared memory implements this interface over a module-scope
|
||||
/// `groupshared` array plus a thread slot instead; no trace-core code changes.
|
||||
///
|
||||
/// The depth index (`10 - scale_exp / 2`) assumes branching 4 and
|
||||
/// `chunk_power = 5`, so implementations store five entries.
|
||||
public interface ITraceStack
|
||||
{
|
||||
public uint32_t get(uint32_t depth);
|
||||
[mutating] public void set(uint32_t depth, uint32_t node);
|
||||
}
|
||||
|
||||
public struct LocalTraceStack : ITraceStack
|
||||
{
|
||||
public uint32_t entries[5];
|
||||
|
||||
public uint32_t get(uint32_t depth)
|
||||
{
|
||||
return this.entries[depth];
|
||||
}
|
||||
|
||||
[mutating]
|
||||
public void set(uint32_t depth, uint32_t node)
|
||||
{
|
||||
this.entries[depth] = node;
|
||||
}
|
||||
}
|
||||
|
||||
public interface IVoxelCache
|
||||
{
|
||||
public bool trace<L : ILodPolicy, St : ITraceStack>(
|
||||
uint32_t root,
|
||||
Ray r,
|
||||
L lod,
|
||||
TraceSettings settings,
|
||||
float offset_t,
|
||||
inout St stack,
|
||||
out Hit v);
|
||||
}
|
||||
|
||||
public struct Tracer<S : IStructure, C : IVoxelCache, L : ILodPolicy>
|
||||
{
|
||||
|
||||
public S structure;
|
||||
public C cache;
|
||||
public L lod;
|
||||
|
||||
/// Traces the closest hit (or the first acceptable hit when
|
||||
/// `settings.any_hit`) at or past `settings.t_min`.
|
||||
///
|
||||
/// The structure may return cells in any order (the BVH restart trail is
|
||||
/// not distance ordered). Instead of returning on the first cache hit, we
|
||||
/// keep the closest hit found so far and skip cells that start beyond it:
|
||||
/// every hit inside a cell is at least `cell.t` away, so a cell with
|
||||
/// `entry >= best_t` cannot improve the result. Because the cells are not
|
||||
/// ordered, such cells are skipped and never used to break the loop.
|
||||
///
|
||||
/// `stack` is caller-owned trace state. Keeping it out of the cache tracer
|
||||
/// lets primary and secondary front-ends choose their own storage.
|
||||
public bool trace<St : ITraceStack>(
|
||||
out Hit h,
|
||||
Ray r,
|
||||
TraceSettings settings,
|
||||
inout St stack)
|
||||
{
|
||||
h.hit = false;
|
||||
h.hit_location = float3(0.f);
|
||||
h.child_index = 0;
|
||||
h.node_index = 0;
|
||||
h.normal_to_world = mat3_identity();
|
||||
h.t = 0.f;
|
||||
|
||||
// Start just past the previous hit.
|
||||
Ray adjusted = r;
|
||||
adjusted.origin += r.direction * settings.t_min;
|
||||
|
||||
float best_t = settings.t_max;
|
||||
Hit best_hit = h;
|
||||
bool found = false;
|
||||
|
||||
S.Cursor cursor = this.structure.begin(adjusted);
|
||||
Cell cell;
|
||||
uint32_t visited = 0;
|
||||
|
||||
[loop]
|
||||
while (visited++ < settings.max_cells && this.structure.next(cursor, cell))
|
||||
{
|
||||
// `cell.t` is relative to the advanced origin, `best_t` is not.
|
||||
float cell_t = settings.t_min + cell.t;
|
||||
|
||||
// No hit inside this cell can be closer than the current best.
|
||||
// Cells are not ordered, so skip instead of breaking.
|
||||
if (cell_t >= settings.t_max)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (!settings.any_hit && cell_t >= best_t)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
Hit candidate = h;
|
||||
if (cache.trace(
|
||||
cell.cache_pointer,
|
||||
cell.local_ray,
|
||||
lod,
|
||||
settings,
|
||||
cell_t,
|
||||
stack,
|
||||
candidate))
|
||||
{
|
||||
// The cache enforces `t_max`; the guard keeps a misbehaving
|
||||
// implementation from accepting an out-of-range hit.
|
||||
if (candidate.t >= settings.t_max)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// The cache reports hits in its unit-cube space. Bring the
|
||||
// position and the local attribute normal into world space so
|
||||
// front-ends can use the hit directly, including as the origin
|
||||
// of secondary rays.
|
||||
candidate.hit_location =
|
||||
cell.world_origin + mul(cell.cube_to_world, candidate.hit_location);
|
||||
candidate.normal_to_world = cell.cube_to_world;
|
||||
|
||||
if (settings.any_hit)
|
||||
{
|
||||
h = candidate;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (candidate.t < best_t)
|
||||
{
|
||||
best_t = candidate.t;
|
||||
best_hit = candidate;
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (found)
|
||||
{
|
||||
h = best_hit;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
use crate::gi_pipeline::sparse_set::GpuSparseSet;
|
||||
use crate::voxel_cache::VoxelCache;
|
||||
use crate::voxel_cache::{self};
|
||||
|
||||
mod sparse_set;
|
||||
|
||||
pub struct VoxelGiPipeline<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
voxel_cache: VoxelCache<N>,
|
||||
|
||||
/// Keeps a set of the leaves present in the cache.
|
||||
/// Kept in correspondancy with the leaf list attribute within the cache
|
||||
leaf_list: GpuSparseSet,
|
||||
leaf_list_attribute: usize,
|
||||
}
|
||||
|
||||
impl<const N: usize> VoxelGiPipeline<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
cache_size: usize,
|
||||
cache_layout: &mut voxel_cache::CacheLayout,
|
||||
) -> Self
|
||||
{
|
||||
let leaf_list_attribute = cache_layout.add_attribute(voxel_cache::CacheAttribute {
|
||||
label: Some("VoxelGiPipeline::leaf_list_pointer"),
|
||||
word_count: 1,
|
||||
init: voxel_cache::CacheAttributeInit::External,
|
||||
});
|
||||
|
||||
cache_layout.add_attribute(voxel_cache::CacheAttribute {
|
||||
label: Some("VoxelGiPipeline::radiance"),
|
||||
word_count: 3,
|
||||
init: voxel_cache::CacheAttributeInit::DontTouch,
|
||||
});
|
||||
|
||||
let voxel_cache = VoxelCache::new(device, cache_size, cache_layout);
|
||||
|
||||
Self {
|
||||
voxel_cache,
|
||||
leaf_list: GpuSparseSet::new(device, cache_size),
|
||||
leaf_list_attribute,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
// Contains useful facilities to render data streamed in from the host
|
||||
|
||||
// Can produce a voxel given
|
||||
// - Its depth
|
||||
// - Its position within the chunk
|
||||
// - The chunks position
|
||||
pub trait ChunkVoxelProducer
|
||||
{
|
||||
fn produce_voxel(
|
||||
&mut self,
|
||||
depth: usize,
|
||||
chunk_position: (usize, usize, usize),
|
||||
voxel_position: (usize, usize, usize),
|
||||
);
|
||||
}
|
||||
@@ -1,533 +0,0 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
use itertools::Itertools;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct Color(pub f32, pub f32, pub f32, pub f32);
|
||||
|
||||
impl Color
|
||||
{
|
||||
pub fn average<I: Iterator<Item = Color>>(iter: I) -> Self
|
||||
{
|
||||
let mut c = Color(0., 0., 0., 0.);
|
||||
let mut count = 0;
|
||||
for Color(r, g, b, a) in iter
|
||||
{
|
||||
count += 1;
|
||||
c.0 += r;
|
||||
c.1 += g;
|
||||
c.2 += b;
|
||||
c.3 += a;
|
||||
}
|
||||
c.0 /= count as f32;
|
||||
c.1 /= count as f32;
|
||||
c.2 /= count as f32;
|
||||
c.3 /= count as f32;
|
||||
c
|
||||
}
|
||||
|
||||
pub fn as_packed_u32(&self) -> u32
|
||||
{
|
||||
let mapped_r = (self.0 * 255.0).clamp(0., 255.0) as u32;
|
||||
let mapped_g = (self.1 * 255.0).clamp(0., 255.0) as u32;
|
||||
let mapped_b = (self.2 * 255.0).clamp(0., 255.0) as u32;
|
||||
let mapped_a = (self.3 * 255.0).clamp(0., 255.0) as u32;
|
||||
mapped_r | (mapped_g << 8) | (mapped_b << 16) | (mapped_a << 24)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NTree<const N: usize>
|
||||
{
|
||||
map: HashMap<NTreeNodeLocator<N>, NTreeNode>,
|
||||
|
||||
// Depth is the parameter such that
|
||||
// N^depth == max_number_of_voxels
|
||||
// one root => depth = 1
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
pub struct NTreeIter<'a, const N: usize>
|
||||
{
|
||||
tree: &'a NTree<N>,
|
||||
dfs_stack: Vec<NTreeNodeLocator<N>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct NTreeNode
|
||||
{
|
||||
color: Color,
|
||||
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]:,
|
||||
{
|
||||
pub fn constant(color: Color, depth: usize) -> Self
|
||||
{
|
||||
let mut map = HashMap::new();
|
||||
let root = NTreeNode {
|
||||
color,
|
||||
subdivided: false,
|
||||
};
|
||||
map.insert(NTreeNodeLocator::<N>::root(), root);
|
||||
Self { map, depth }
|
||||
}
|
||||
|
||||
pub fn set(&mut self, x: usize, y: usize, z: usize, color: Color)
|
||||
{
|
||||
self.set_at_depth(x, y, z, self.depth, color);
|
||||
}
|
||||
|
||||
pub fn get(&self, x: usize, y: usize, z: usize) -> Color
|
||||
{
|
||||
assert!(x < N.pow(self.depth as u32));
|
||||
assert!(y < N.pow(self.depth as u32));
|
||||
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_size = N.pow(self.depth as u32);
|
||||
let mut current_node = self.map.get(¤t_node_loc).unwrap();
|
||||
|
||||
loop
|
||||
{
|
||||
if !current_node.subdivided
|
||||
{
|
||||
return current_node.color;
|
||||
}
|
||||
|
||||
// Descend to relevant node,
|
||||
let child_node_size = current_node_size / N;
|
||||
let child_x = (x % current_node_size) / child_node_size;
|
||||
let child_y = (y % current_node_size) / child_node_size;
|
||||
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 = self.map.get(¤t_node_loc).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_at_depth(&mut self, x: usize, y: usize, z: usize, depth: usize, color: Color)
|
||||
{
|
||||
assert!(x < N.pow(depth as u32));
|
||||
assert!(y < N.pow(depth as u32));
|
||||
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_size = N.pow(self.depth as u32);
|
||||
let mut current_depth = 0;
|
||||
let mut current_node = self.map.get_mut(¤t_node_loc).unwrap();
|
||||
|
||||
while current_depth != depth
|
||||
{
|
||||
if current_node.color == color
|
||||
{
|
||||
// Color is already correct, work is finished
|
||||
return;
|
||||
}
|
||||
|
||||
// Current is not subdivided, and color is different => subdivide
|
||||
if !current_node.subdivided
|
||||
{
|
||||
current_node.subdivided = true;
|
||||
let new_nodes = NTreeNode {
|
||||
color: current_node.color,
|
||||
subdivided: false,
|
||||
};
|
||||
current_node_loc.children().into_iter().for_each(|child| {
|
||||
self.map.insert(child, new_nodes);
|
||||
});
|
||||
}
|
||||
|
||||
// Descend to relevant node,
|
||||
let child_node_size = current_node_size / N;
|
||||
let child_x = (x % current_node_size) / child_node_size;
|
||||
let child_y = (y % current_node_size) / child_node_size;
|
||||
let child_z = (z % current_node_size) / child_node_size;
|
||||
current_node_size = child_node_size;
|
||||
current_depth += 1;
|
||||
|
||||
current_node_loc = current_node_loc.child(child_x, child_y, child_z);
|
||||
current_node = self.map.get_mut(¤t_node_loc).unwrap();
|
||||
}
|
||||
|
||||
if current_node.subdivided
|
||||
{
|
||||
self.make_constant(current_node_loc, color);
|
||||
}
|
||||
else
|
||||
{
|
||||
current_node.color = color;
|
||||
}
|
||||
|
||||
// We need to go back up the hierarchy to combine nodes
|
||||
// current_node is the modified node, go one up
|
||||
|
||||
loop
|
||||
{
|
||||
// Go one node up
|
||||
current_depth -= 1;
|
||||
current_node_loc = current_node_loc.parent().unwrap();
|
||||
//current_node_size *= N;
|
||||
|
||||
// Access all children's colors
|
||||
let children_color_avg = current_node_loc
|
||||
.children()
|
||||
.iter()
|
||||
.map(|child_loc| self.map.get(child_loc).unwrap().color)
|
||||
// AGGREGATE AND AVERAGE HERE !!
|
||||
.next()
|
||||
.unwrap();
|
||||
|
||||
current_node = self.map.get_mut(¤t_node_loc).unwrap();
|
||||
current_node.color = children_color_avg;
|
||||
|
||||
if current_depth == 0
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn make_constant(&mut self, locator: NTreeNodeLocator<N>, color: Color)
|
||||
{
|
||||
let mut dfs_stack = Vec::new();
|
||||
dfs_stack.push(locator);
|
||||
|
||||
while let Some(current) = dfs_stack.pop()
|
||||
{
|
||||
// Remove element
|
||||
let removed = self.map.remove(¤t);
|
||||
let handle_children = removed.is_some_and(|x| x.subdivided);
|
||||
|
||||
// If children have to be handled, push on stack
|
||||
if handle_children
|
||||
{
|
||||
dfs_stack.extend(current.children());
|
||||
}
|
||||
}
|
||||
|
||||
self.map.insert(
|
||||
locator,
|
||||
NTreeNode {
|
||||
color,
|
||||
subdivided: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
pub fn from_array(array: &[Color], depth: usize) -> Self
|
||||
{
|
||||
let mut structure = HashMap::new();
|
||||
// Per voxel in the array :
|
||||
// 0 -> Voxel not merged yet
|
||||
// _ -> size of the block in which the voxel was merged
|
||||
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)
|
||||
{
|
||||
let mut z = 0;
|
||||
while z < 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];
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check smallest depth aligned with current position
|
||||
let x_trailing = base_trailing_zeroes::<N>(x).unwrap_or(depth as u32);
|
||||
let y_trailing = base_trailing_zeroes::<N>(y).unwrap_or(depth as u32);
|
||||
let z_trailing = base_trailing_zeroes::<N>(z).unwrap_or(depth as u32);
|
||||
|
||||
// Biggest block size power of which this voxel can be a lower corner
|
||||
let block_power = x_trailing.min(y_trailing.min(z_trailing));
|
||||
|
||||
// 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);
|
||||
'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)
|
||||
.cartesian_product(0..block_size)
|
||||
.cartesian_product(0..block_size)
|
||||
{
|
||||
if array
|
||||
[(x + merge_x) + (y + merge_y) * width + (z + merge_z) * width * width]
|
||||
!= color
|
||||
{
|
||||
break 'power_search;
|
||||
}
|
||||
}
|
||||
|
||||
// Update biggest candidate block
|
||||
locator = locator.parent().unwrap();
|
||||
max_power_merge = power;
|
||||
}
|
||||
|
||||
// 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)
|
||||
.cartesian_product(0..block_size)
|
||||
.cartesian_product(0..block_size)
|
||||
{
|
||||
merged_size
|
||||
[(x + merge_x) + (y + merge_y) * width + (z + merge_z) * width * width] =
|
||||
block_size;
|
||||
}
|
||||
|
||||
// Add new found block in our structure
|
||||
// If power is depth, this is the whole structure, thus depth is 0
|
||||
let node = NTreeNode {
|
||||
color,
|
||||
subdivided: false,
|
||||
};
|
||||
structure.insert(locator, node);
|
||||
z += block_size;
|
||||
}
|
||||
}
|
||||
|
||||
// The structure now consists of the leaf most nodes, we need to rebuild the hierarchy
|
||||
// bottom up
|
||||
for current_power in 1..=depth
|
||||
{
|
||||
// Iterate on the blocks of this size
|
||||
let block_size = N.pow(current_power as u32);
|
||||
let block_count = width / block_size;
|
||||
|
||||
for ((block_x, block_y), block_z) in (0..block_count)
|
||||
.cartesian_product(0..block_count)
|
||||
.cartesian_product(0..block_count)
|
||||
{
|
||||
// Check the lower corner of this block
|
||||
let corner = merged_size[(block_x * block_size)
|
||||
+ (block_y * block_size) * width
|
||||
+ (block_z * block_size) * width * width];
|
||||
if corner >= block_size
|
||||
{
|
||||
// Children are merged in bigger block
|
||||
continue;
|
||||
}
|
||||
|
||||
// Add hierarchy node
|
||||
let locator =
|
||||
NTreeNodeLocator::<N>::new(depth - current_power, block_x, block_y, block_z);
|
||||
|
||||
// Get average color of children
|
||||
let color = Color::average(
|
||||
locator
|
||||
.children()
|
||||
.iter()
|
||||
.map(|child_loc| structure.get(child_loc).unwrap().color),
|
||||
);
|
||||
|
||||
let hierarchy_node = NTreeNode {
|
||||
color,
|
||||
subdivided: true,
|
||||
};
|
||||
structure.insert(locator, hierarchy_node);
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
map: structure,
|
||||
depth,
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
pub fn as_explicit_structure(&self) -> (Color, Vec<ExplicitNTreeNode<N>>)
|
||||
{
|
||||
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)
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
fn base_trailing_zeroes<const N: usize>(mut number: usize) -> Option<u32>
|
||||
{
|
||||
if number == 0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut trailing_zeroes = 0;
|
||||
while number % N == 0
|
||||
{
|
||||
number /= N;
|
||||
trailing_zeroes += 1;
|
||||
}
|
||||
|
||||
Some(trailing_zeroes)
|
||||
}
|
||||
|
||||
impl<const N: usize> NTreeNodeLocator<N>
|
||||
{
|
||||
pub fn root() -> Self
|
||||
{
|
||||
Self(1)
|
||||
}
|
||||
|
||||
pub fn from_usize(n: usize) -> Self
|
||||
{
|
||||
Self(n)
|
||||
}
|
||||
|
||||
pub fn new(mut depth: usize, x: usize, y: usize, z: usize) -> Self
|
||||
{
|
||||
let mut loc = Self::root();
|
||||
let mut size = N.pow(depth as u32);
|
||||
while depth != 0
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
return loc;
|
||||
}
|
||||
|
||||
pub fn depth(&self) -> usize
|
||||
{
|
||||
let mut n = self.0;
|
||||
let mut depth = 0;
|
||||
while n != 1
|
||||
{
|
||||
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 z in 0..N
|
||||
{
|
||||
children.push(self.child(x, y, z));
|
||||
}
|
||||
}
|
||||
}
|
||||
children
|
||||
}
|
||||
}
|
||||
-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);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user