Compare commits

...
2 Commits
16 changed files with 1221 additions and 119 deletions
+3
View File
@@ -18,7 +18,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"] }
+12
View File
@@ -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
+313
View File
@@ -0,0 +1,313 @@
//! Derive macro for the `vxls_production::Attributes` trait.
//!
//! # Example
//!
//! ```ignore
//! use bytemuck::{Pod, Zeroable};
//! use vxls_production::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_production::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::parse_macro_input;
use syn::Data;
use syn::DeriveInput;
use syn::Error;
use syn::Fields;
use syn::LitStr;
use syn::Result;
#[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_production::AttributeDescriptor {
label: #label,
word_count: (::core::mem::size_of::<#ty>() / 4) as u32,
semantic: #semantic,
}
});
getters.push(quote! {
#index => ::vxls_production::bytemuck::bytes_of(&self.#name),
});
getters_mut.push(quote! {
#index => ::vxls_production::bytemuck::bytes_of_mut(&mut self.#name),
});
averages.push(quote! {
#name: <#ty as ::vxls_production::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_production::Attributes for #ident
{
const LAYOUT: ::vxls_production::AttributesLayout =
::vxls_production::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_production::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)]`",
))
}
}
+1
View File
@@ -8,4 +8,5 @@ bytemuck.workspace = true
itertools.workspace = true
rayon.workspace = true
wgpu.workspace = true
vxls-attributes-derive = { path = "../vxls-attributes-derive" }
vxls-voxel-cache = { path = "../vxls-voxel-cache" }
+459
View File
@@ -0,0 +1,459 @@
//! 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.
use bytemuck::Pod;
use bytemuck::Zeroable;
use vxls_voxel_cache::CacheAttribute;
use vxls_voxel_cache::CacheAttributeInit;
use vxls_voxel_cache::CacheLayout;
/// 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
}
/// Converts this layout to the GPU-facing [`CacheLayout`].
///
/// Every attribute of this layout is inserted from the producer and is
/// therefore [`CacheAttributeInit::External`]. `extra` attributes are
/// appended after them and are meant for GPU-only data
/// ([`CacheAttributeInit::DontTouch`]), which producers never fill.
pub fn to_cache_layout(&self, extra: &[CacheAttribute]) -> CacheLayout
{
let mut layout = CacheLayout::default();
for attribute in self.attributes
{
layout.add_attribute(CacheAttribute {
label: Some(attribute.label),
word_count: attribute.word_count,
init: CacheAttributeInit::External,
});
}
for attribute in extra
{
layout.add_attribute(*attribute);
}
layout
}
/// Converts this layout to the GPU-facing [`CacheLayout`] without extra
/// GPU-only attributes.
pub fn to_cache_layout_only(&self) -> CacheLayout
{
self.to_cache_layout(&[])
}
}
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,
);
+33 -76
View File
@@ -1,14 +1,39 @@
#![allow(incomplete_features)]
#![feature(generic_const_exprs)]
use bytemuck::Pod;
use bytemuck::Zeroable;
//! Producer-side API: attributes, produced nodes and cache layout bridging.
//!
//! 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],
//! }
//! ```
use vxls_voxel_cache::schema::InsertionInformation;
use vxls_voxel_cache::schema::LocationPage;
pub use bytemuck;
pub use vxls_attributes_derive::Attributes;
pub use vxls_voxel_cache::schema::StructureAnchor;
use wgpu::naga::keywords;
mod attributes;
mod producer;
pub use attributes::*;
pub use producer::*;
/// A structure locator format to locate node within an ntree
pub mod tree_locator;
@@ -16,76 +41,8 @@ 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;
/// 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);
/// A voxel attribute must be able to be turned into bytes, and just be a bit of data
pub trait Attribute:
// An attribute can be turned into predictable, safe, raw bytes
bytemuck::Pod +
bytemuck::Zeroable +
// It can be compared with itself, equal attributes mean they can be merged in a sparse structure
PartialEq +
Eq +
// It can be crated by anybody, without knowing what is inside
Default +
// It can be moved arround without problems, and does not depend on anything
Clone +
Copy +
Send +
Sync +
'static
{
/// Many attributes can be averaged together
fn average(attributes: &[Self]) -> Self;
}
pub trait Has<A: Attribute>
{
fn get(&self) -> &A;
fn get_mut(&mut self) -> &mut A;
fn get_bytes(&self) -> &[u8]
{
bytemuck::bytes_of(self.get())
}
fn get_bytes_mut(&mut self) -> &mut [u8]
{
bytemuck::bytes_of_mut(self.get_mut())
}
}
pub struct ProducedNode<const N: usize, A: Attribute>
where [(); N * N * N]:,
{
insersion_info: InsertionInformation<N>,
location: LocationPage,
attributes: [A; N * N * N],
}
pub trait Producer<const N: usize, A: Attribute>
where [(); N * N * N]:,
{
fn produce(&self,
producer_id: ProducerId,
anchor: StructureAnchor,
locator: StructureLocator
) -> ProducedNode<N, A>;
}
/// Routing voxel production to different producers
pub mod production_router;
+131
View File
@@ -0,0 +1,131 @@
//! Producers and the nodes they produce.
use vxls_voxel_cache::schema::InsertionInformation;
pub use vxls_voxel_cache::schema::ProducerId;
pub use vxls_voxel_cache::schema::StructureLocator;
use crate::StructureAnchor;
use crate::attributes::Attributes;
/// 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
}
/// 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)
}
}
+8 -8
View File
@@ -158,7 +158,7 @@ impl IncomingRequest
/// `node_id == 0` (which also describes child 0 of the root).
pub fn from_wire(request: &RequestInformation, meta: &RequestMeta) -> Self
{
let producer_id = ProducerId(request.producer_id);
let producer_id = request.producer_id;
let anchor = request.anchor;
let (key, priority) = if meta.page_index == NO_PARENT_PAGE
@@ -174,7 +174,7 @@ impl IncomingRequest
RequestKey::child(
producer_id,
anchor,
StructureLocator(request.node_id),
request.node_id,
request.children_index,
),
RequestPriority::child(request.demand, meta.depth),
@@ -225,7 +225,7 @@ impl<T> ReadyItem<T>
match self.key.target
{
RequestTarget::Root => InsertionParent::external(
self.key.producer_id.0,
self.key.producer_id,
self.key.anchor,
self.meta.table_slot,
),
@@ -241,7 +241,7 @@ impl<T> ReadyItem<T>
children_index,
..self.meta
};
InsertionParent::internal(&meta, parent.0, self.key.producer_id.0, self.key.anchor)
InsertionParent::internal(&meta, parent, self.key.producer_id, self.key.anchor)
}
}
}
@@ -856,9 +856,9 @@ mod tests
{
(
RequestInformation {
node_id: node,
node_id: StructureLocator(node),
children_index: child,
producer_id: producer,
producer_id: ProducerId(producer),
demand,
anchor,
},
@@ -969,7 +969,7 @@ mod tests
let external = ready[0].insertion_parent();
assert!(external.is_external());
assert_eq!(external.page_index, NO_PARENT_PAGE);
assert_eq!(external.producer_id, PRODUCER.0);
assert_eq!(external.producer_id, PRODUCER);
assert_eq!(external.anchor, ANCHOR);
assert_eq!(external.table_slot, 5);
@@ -978,7 +978,7 @@ mod tests
assert_eq!(internal.page_index, 7);
assert_eq!(internal.children_index, 2);
assert_eq!(internal.depth, 3);
assert_eq!(internal.node_id, 4);
assert_eq!(internal.node_id, StructureLocator(4));
assert_eq!(internal.anchor, ANCHOR);
assert_eq!(internal.table_slot, NO_TABLE_SLOT);
}
+192
View File
@@ -0,0 +1,192 @@
#![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::CacheAttribute;
use vxls_voxel_cache::CacheAttributeInit;
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 cache_layout_starts_with_external_attributes_then_extras()
{
let layout = TestAttributes::LAYOUT.to_cache_layout(&[CacheAttribute {
label: Some("gi"),
word_count: 2,
init: CacheAttributeInit::DontTouch,
}]);
let attributes = layout.attributes();
assert_eq!(attributes.len(), 3);
assert_eq!(attributes[0].label, Some("color"));
assert_eq!(attributes[0].word_count, 1);
assert_eq!(attributes[0].init, CacheAttributeInit::External);
assert_eq!(attributes[1].label, Some("normal"));
assert_eq!(attributes[1].word_count, 3);
assert_eq!(attributes[2].label, Some("gi"));
assert_eq!(attributes[2].word_count, 2);
assert_eq!(attributes[2].init, CacheAttributeInit::DontTouch);
assert_eq!(TestAttributes::LAYOUT.to_cache_layout_only().attributes().len(), 2);
}
#[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));
}
+6
View File
@@ -96,6 +96,12 @@ impl CacheLayout
index
}
/// The attributes of this layout, in binding order
pub fn attributes(&self) -> &[CacheAttribute]
{
&self.attributes
}
/// Produces a wgsl declaration describing this layout :
///
/// ```wgsl
+23 -11
View File
@@ -149,6 +149,18 @@ impl StructureAnchor
}
}
/// 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)]
@@ -156,10 +168,10 @@ impl StructureAnchor
pub struct LocationPage
{
/// Identifier for locating this particular node within the structure
pub node_id: u32,
pub node_id: StructureLocator,
/// Identifier of the producer that owns this node
pub producer_id: u32,
pub producer_id: ProducerId,
/// Opaque content identity inherited from the root request.
pub anchor: StructureAnchor,
@@ -196,13 +208,13 @@ impl DepthPage
pub struct RequestInformation
{
/// Identifier for locating this particular node within the structure
pub node_id: u32,
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: u32,
pub producer_id: ProducerId,
/// The amount of times this request was emitted this frame. Higher means more urgent.
pub demand: u32,
@@ -274,11 +286,11 @@ pub struct InsertionParent
/// Depth of the parent. [`NO_PARENT_PAGE`] for external roots.
pub depth: u32,
/// Locator of the parent inside the structure. `0` for external roots.
pub node_id: 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: u32,
pub producer_id: ProducerId,
/// Opaque content identity of the structure the parent belongs to.
pub anchor: StructureAnchor,
@@ -293,8 +305,8 @@ impl InsertionParent
/// Parent information for a child of a resident cache page.
pub fn internal(
meta: &RequestMeta,
node_id: u32,
producer_id: u32,
node_id: StructureLocator,
producer_id: ProducerId,
anchor: StructureAnchor,
) -> Self
{
@@ -311,14 +323,14 @@ impl InsertionParent
}
/// Parent information for the root of an external structure.
pub fn external(producer_id: u32, anchor: StructureAnchor, table_slot: u32) -> Self
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: 0,
node_id: StructureLocator(0),
producer_id,
anchor,
table_slot,
+12 -21
View File
@@ -68,6 +68,7 @@ use vxls_bvh::BvhStructureTable;
use vxls_bvh::aabb::Aabb;
use vxls_bvh::build::Bvh;
use vxls_bvh::debug::BvhDebugPipeline;
use vxls_production::Attributes;
use vxls_production::ProducerId;
use vxls_production::StructureAnchor;
use vxls_production::StructureLocator;
@@ -395,17 +396,7 @@ impl State
let egui_renderer = EguiRenderer::new(&device, surface_format, &window);
let mut layout = vxls_voxel_cache::layout::CacheLayout::default();
layout.add_attribute(vxls_voxel_cache::CacheAttribute {
label: Some("color"),
word_count: 1,
init: vxls_voxel_cache::CacheAttributeInit::External,
});
layout.add_attribute(vxls_voxel_cache::CacheAttribute {
label: Some("normal"),
word_count: 3,
init: vxls_voxel_cache::CacheAttributeInit::External,
});
let layout = crate::producers::VoxelAttributes::LAYOUT.to_cache_layout_only();
let request_buffer = CacheRequestBuffer::new(&device, 1024);
let voxel_cache =
@@ -1885,8 +1876,8 @@ fn fullfill_request_tree<const N: usize>(
children: [ChildInformation::new(false, root.color.3 != 0.); N * N * N],
},
LocationPage {
node_id: StructureLocator::from(TreeLocator::<N>::root()).0,
producer_id: 0,
node_id: StructureLocator::from(TreeLocator::<N>::root()),
producer_id: ProducerId(0),
anchor: StructureAnchor::zeroed(),
},
)
@@ -1911,8 +1902,8 @@ fn fullfill_request_tree<const N: usize>(
children: std::array::from_fn(|i| children[i]),
},
LocationPage {
node_id: StructureLocator::from(TreeLocator::<N>::root()).0,
producer_id: 0,
node_id: StructureLocator::from(TreeLocator::<N>::root()),
producer_id: ProducerId(0),
anchor: StructureAnchor::zeroed(),
},
)
@@ -1948,8 +1939,8 @@ fn fullfill_request_tree<const N: usize>(
children: std::array::from_fn(|i| children[i]),
},
LocationPage {
node_id: StructureLocator::from(loc).0,
producer_id: 0,
node_id: StructureLocator::from(loc),
producer_id: ProducerId(0),
anchor: StructureAnchor::zeroed(),
},
)
@@ -2002,8 +1993,8 @@ where
node = generator.produce_node(0, 0, 0, 0, (chunk_x, chunk_y, chunk_z));
let locator: StructureLocator = TreeLocator::<N>::root().into();
location = LocationPage {
node_id: locator.0,
producer_id: request.producer_id.0,
node_id: locator,
producer_id: request.producer_id,
anchor,
};
}
@@ -2040,8 +2031,8 @@ where
let st_loc: StructureLocator = child_locator.into();
location = LocationPage {
node_id: st_loc.0 as u32,
producer_id: request.producer_id.0,
node_id: st_loc,
producer_id: request.producer_id,
anchor,
};
}
+18
View File
@@ -1,6 +1,8 @@
use std::fs::File;
use std::path::Path;
use bytemuck::Pod;
use bytemuck::Zeroable;
use glam::Vec3;
use itertools::Itertools;
use noise::Cylinders;
@@ -12,6 +14,22 @@ use rand::random;
use crate::sparse_tree::Color;
use vxls_voxel_cache::schema::ChildInformation;
/// 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,
+5 -3
View File
@@ -84,6 +84,9 @@ struct RequestMeta {
- `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
@@ -331,9 +334,8 @@ production types are the durable contract; the driver is still the playground.
Defines a more ambitious interface:
```rust
pub struct ProducerId(pub u32);
pub struct StructureLocator(pub u32);
pub use crate::voxel_cache::schema::StructureAnchor;
// Identity types live in vxls-voxel-cache::schema and are re-exported here.
pub use voxel_cache::schema::{ProducerId, StructureAnchor, StructureLocator};
pub trait VoxelAttributes<const N: usize> {
fn attribute_count() -> usize;
+5
View File
@@ -81,6 +81,11 @@ 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