diff --git a/Cargo.toml b/Cargo.toml index bf1c1ec..2edbbe0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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"] } diff --git a/crates/vxls-attributes-derive/Cargo.toml b/crates/vxls-attributes-derive/Cargo.toml new file mode 100644 index 0000000..acf38cb --- /dev/null +++ b/crates/vxls-attributes-derive/Cargo.toml @@ -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 diff --git a/crates/vxls-attributes-derive/src/lib.rs b/crates/vxls-attributes-derive/src/lib.rs new file mode 100644 index 0000000..f4087c1 --- /dev/null +++ b/crates/vxls-attributes-derive/src/lib.rs @@ -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 +{ + 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::()?); + return Ok(()); + } + + if meta.path.is_ident("semantic") + { + options.semantic = Some(meta.value()?.parse::()?); + 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 ::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, + semantic: Option, +} + +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)]`", + )) + } +} diff --git a/crates/vxls-production/Cargo.toml b/crates/vxls-production/Cargo.toml index 529361b..e5a5d92 100644 --- a/crates/vxls-production/Cargo.toml +++ b/crates/vxls-production/Cargo.toml @@ -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" } diff --git a/crates/vxls-production/src/attributes.rs b/crates/vxls-production/src/attributes.rs new file mode 100644 index 0000000..3a203d0 --- /dev/null +++ b/crates/vxls-production/src/attributes.rs @@ -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::() 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 + '_ + { + 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::() / 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::() / 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::() / attributes.len() as f32 + } +} + +macro_rules! impl_array_attribute { + ($($count:literal),* $(,)?) => { + $( + impl 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::>(), + ) + }) + } + } + )* + }; +} + +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, +); diff --git a/crates/vxls-production/src/lib.rs b/crates/vxls-production/src/lib.rs index b77c308..2ac2c3d 100644 --- a/crates/vxls-production/src/lib.rs +++ b/crates/vxls-production/src/lib.rs @@ -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 -{ - 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 -where [(); N * N * N]:, -{ - insersion_info: InsertionInformation, - location: LocationPage, - attributes: [A; N * N * N], -} - -pub trait Producer -where [(); N * N * N]:, -{ - fn produce(&self, - producer_id: ProducerId, - anchor: StructureAnchor, - locator: StructureLocator - ) -> ProducedNode; -} +/// Routing voxel production to different producers +pub mod production_router; diff --git a/crates/vxls-production/src/producer.rs b/crates/vxls-production/src/producer.rs new file mode 100644 index 0000000..e2f5798 --- /dev/null +++ b/crates/vxls-production/src/producer.rs @@ -0,0 +1,142 @@ +//! Producers and the nodes they produce. + +use bytemuck::Pod; +use bytemuck::Zeroable; +use vxls_voxel_cache::schema::InsertionInformation; + +use crate::StructureAnchor; +use crate::attributes::Attributes; + +/// 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 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 +where + [(); N * N * N]:, +{ + /// Structure of the produced page + pub insertion: InsertionInformation, + + /// The voxels of the page, in child-major order (`x + 4*y + 16*z`) + pub attributes: [A; N * N * N], +} + +impl ProducedNode +where + [(); N * N * N]:, +{ + /// Creates a produced node + pub fn new(insertion: InsertionInformation, 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) + { + 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::(), + "attribute size does not match its declared word count", + ); + + for word in bytes.chunks_exact(size_of::()) + { + out.push(u32::from_ne_bytes( + word.try_into().expect("chunks_exact yields 4-byte slices"), + )); + } + } + } +} + +/// Produces cache pages on demand +pub trait Producer +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` + /// impl) to decode it into coordinates. + fn produce(&self, anchor: StructureAnchor, locator: StructureLocator) -> ProducedNode; +} + +pub struct FnProducer +where + T: Fn(StructureAnchor, StructureLocator) -> ProducedNode, + A: Attributes, + [(); N * N * N]:, +{ + f: T, +} + +impl FnProducer +where + T: Fn(StructureAnchor, StructureLocator) -> ProducedNode, + A: Attributes, + [(); N * N * N]:, +{ + pub fn new(f: T) -> Self + { + Self { f } + } +} + +impl Producer for FnProducer +where + T: Fn(StructureAnchor, StructureLocator) -> ProducedNode, + A: Attributes, + [(); N * N * N]:, +{ + fn produce(&self, anchor: StructureAnchor, locator: StructureLocator) -> ProducedNode + { + (self.f)(anchor, locator) + } +} diff --git a/crates/vxls-production/src/production_router.rs b/crates/vxls-production/src/production_router.rs new file mode 100644 index 0000000..e69de29 diff --git a/crates/vxls-production/tests/attributes.rs b/crates/vxls-production/tests/attributes.rs new file mode 100644 index 0000000..e19092e --- /dev/null +++ b/crates/vxls-production/tests/attributes.rs @@ -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::(&value.normal) + ); + + node.write_attribute_words(0, &mut words); + assert_eq!(words.len(), 64); + assert!(words.iter().all(|word| *word == 0x0102_0304)); +} diff --git a/crates/vxls-voxel-cache/src/layout.rs b/crates/vxls-voxel-cache/src/layout.rs index 6acac0f..3585513 100644 --- a/crates/vxls-voxel-cache/src/layout.rs +++ b/crates/vxls-voxel-cache/src/layout.rs @@ -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 diff --git a/crates/vxls/src/main.rs b/crates/vxls/src/main.rs index 4d91476..ba43cce 100644 --- a/crates/vxls/src/main.rs +++ b/crates/vxls/src/main.rs @@ -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 = diff --git a/crates/vxls/src/producers.rs b/crates/vxls/src/producers.rs index 91b1b95..98534b7 100644 --- a/crates/vxls/src/producers.rs +++ b/crates/vxls/src/producers.rs @@ -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 { chunk_power: usize,