diff --git a/crates/vxls-attributes-derive/src/lib.rs b/crates/vxls-attributes-derive/src/lib.rs index 154983e..d73ebb7 100644 --- a/crates/vxls-attributes-derive/src/lib.rs +++ b/crates/vxls-attributes-derive/src/lib.rs @@ -38,17 +38,16 @@ 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; +use syn::parse_macro_input; #[proc_macro_derive(Attributes, attributes(attribute))] -pub fn derive_attributes(input: TokenStream) -> TokenStream -{ +pub fn derive_attributes(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); expand(input) @@ -56,12 +55,10 @@ pub fn derive_attributes(input: TokenStream) -> TokenStream .into() } -fn expand(input: DeriveInput) -> Result -{ +fn expand(input: DeriveInput) -> Result { let ident = &input.ident; - if !input.generics.params.is_empty() - { + if !input.generics.params.is_empty() { return Err(Error::new_spanned( &input.generics, "`Attributes` cannot be derived for generic structs", @@ -70,8 +67,7 @@ fn expand(input: DeriveInput) -> Result check_repr(&input)?; - let data = match &input.data - { + let data = match &input.data { Data::Struct(data) => data, Data::Enum(_) => { return Err(Error::new_spanned( @@ -87,8 +83,7 @@ fn expand(input: DeriveInput) -> Result } }; - let fields = match &data.fields - { + let fields = match &data.fields { Fields::Named(fields) => &fields.named, _ => { return Err(Error::new_spanned( @@ -106,8 +101,7 @@ fn expand(input: DeriveInput) -> Result let mut field_types = Vec::new(); let mut index = 0usize; - for field in fields - { + for field in fields { let name = field .ident .as_ref() @@ -117,10 +111,8 @@ fn expand(input: DeriveInput) -> Result field_types.push(quote! { #ty }); let mut options = FieldOptions::default(); - for attribute in &field.attrs - { - if !attribute.path().is_ident("attribute") - { + for attribute in &field.attrs { + if !attribute.path().is_ident("attribute") { continue; } @@ -149,8 +141,7 @@ fn expand(input: DeriveInput) -> Result })?; } - if options.skip - { + if options.skip { skipped.push(quote! { #name: ::core::default::Default::default() }); @@ -161,8 +152,7 @@ fn expand(input: DeriveInput) -> Result .label .unwrap_or_else(|| LitStr::new(&name.to_string(), name.span())); - let semantic = match options.semantic - { + let semantic = match options.semantic { Some(semantic) => quote! { ::core::option::Option::Some(#semantic) }, None => quote! { ::core::option::Option::None }, }; @@ -272,39 +262,31 @@ fn expand(input: DeriveInput) -> Result /// Collects the `#[attribute(...)]` options of a single field. #[derive(Default)] -struct FieldOptions -{ +struct FieldOptions { skip: bool, label: Option, semantic: Option, } -fn check_repr(input: &DeriveInput) -> Result<()> -{ +fn check_repr(input: &DeriveInput) -> Result<()> { let mut found = false; - for attribute in &input.attrs - { - if !attribute.path().is_ident("repr") - { + 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") - { + if meta.path.is_ident("C") || meta.path.is_ident("transparent") { found = true; } Ok(()) })?; } - if found - { + if found { Ok(()) - } - else - { + } else { Err(Error::new_spanned( &input.ident, "`Attributes` requires the struct to be `#[repr(C)]` or `#[repr(transparent)]`", diff --git a/crates/vxls-attributes/src/attributes.rs b/crates/vxls-attributes/src/attributes.rs index 56b9a77..e983e79 100644 --- a/crates/vxls-attributes/src/attributes.rs +++ b/crates/vxls-attributes/src/attributes.rs @@ -51,8 +51,7 @@ pub trait Attribute: /// 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 -{ +pub trait Attributes: Attribute { /// The attributes layout for this struct. /// /// Built by `#[derive(Attributes)]`, but it can also be written by hand. @@ -73,22 +72,19 @@ pub trait Attributes: Attribute 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]> - { + 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]> - { + 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 -{ +pub struct AttributeDescriptor { /// A name for the attribute, used as the GPU buffer label pub label: &'static str, @@ -102,11 +98,9 @@ pub struct AttributeDescriptor pub semantic: Option<&'static str>, } -impl AttributeDescriptor -{ +impl AttributeDescriptor { /// Creates a descriptor without a semantic role - pub const fn new(label: &'static str, word_count: u32) -> Self - { + pub const fn new(label: &'static str, word_count: u32) -> Self { Self { label, word_count, @@ -115,15 +109,13 @@ impl AttributeDescriptor } /// Adds a semantic role to this descriptor - pub const fn with_semantic(mut self, semantic: &'static str) -> Self - { + 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 - { + pub const fn size_bytes(&self) -> u32 { self.word_count * size_of::() as u32 } } @@ -133,50 +125,42 @@ impl AttributeDescriptor /// 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 -{ +pub struct AttributesLayout { /// The attributes, in binding order pub attributes: &'static [AttributeDescriptor], } -impl AttributesLayout -{ +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 - { + pub const fn new(attributes: &'static [AttributeDescriptor]) -> Self { Self { attributes } } /// Number of attributes - pub const fn len(&self) -> usize - { + pub const fn len(&self) -> usize { self.attributes.len() } /// Whether the layout has no attributes - pub const fn is_empty(&self) -> bool - { + pub const fn is_empty(&self) -> bool { self.attributes.is_empty() } /// Gets the descriptor at `index` - pub fn get(&self, index: usize) -> Option<&AttributeDescriptor> - { + pub fn get(&self, index: usize) -> Option<&AttributeDescriptor> { self.attributes.get(index) } /// Iterates over `(index, descriptor)` pairs - pub fn iter(&self) -> impl Iterator + '_ - { + 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 - { + pub fn total_word_count(&self) -> u32 { self.attributes .iter() .map(|attribute| attribute.word_count) @@ -184,35 +168,28 @@ impl AttributesLayout } /// Finds an attribute by label - pub fn by_label(&self, label: &str) -> Option<(usize, &AttributeDescriptor)> - { + 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)> - { + 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() - { + 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() - { + for (index, attribute) in self.attributes.iter().enumerate() { + if attribute.label.is_empty() { return Err(LayoutError::EmptyLabel { index }); } - if attribute.word_count == 0 - { + if attribute.word_count == 0 { return Err(LayoutError::ZeroWordCount { index }); } @@ -249,19 +226,15 @@ impl AttributesLayout /// 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 - { + pub fn fingerprint(&self) -> u64 { let mut hash = 0xcbf2_9ce4_8422_2325u64; - for attribute in self.attributes - { + 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) => - { + match attribute.semantic { + Some(semantic) => { fnv1a(&mut hash, &[1]); fnv1a(&mut hash, semantic.as_bytes()); } @@ -286,8 +259,7 @@ impl AttributesLayout /// /// /// ``` - pub fn wgsl_layout_decl(&self) -> String - { + pub fn wgsl_layout_decl(&self) -> String { let mut decl = String::new(); decl += &format!("const ATTRIBUTE_COUNT: u32 = {};", self.attributes.len()); @@ -299,8 +271,7 @@ impl AttributesLayout self.attributes.len() ); - for attribute in self.attributes.iter() - { + for attribute in self.attributes.iter() { decl += &format!(" {},", attribute.word_count); } @@ -310,10 +281,8 @@ impl AttributesLayout } } -fn fnv1a(hash: &mut u64, bytes: &[u8]) -{ - for byte in bytes - { +fn fnv1a(hash: &mut u64, bytes: &[u8]) { + for byte in bytes { *hash ^= *byte as u64; *hash = hash.wrapping_mul(0x0000_0100_0000_01b3); } @@ -321,33 +290,28 @@ fn fnv1a(hash: &mut u64, bytes: &[u8]) /// Errors reported by [`AttributesLayout::validate`] #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum LayoutError -{ +pub enum LayoutError { /// The layout has no attributes, which a cache cannot represent Empty, /// An attribute has an empty label - EmptyLabel - { + EmptyLabel { /// Index of the offending attribute index: usize, }, /// An attribute has a zero word count - ZeroWordCount - { + ZeroWordCount { /// Index of the offending attribute index: usize, }, /// Two attributes share a label - DuplicateLabel - { + DuplicateLabel { /// Index of the first attribute first: usize, /// Index of the duplicate attribute second: usize, }, /// Two attributes share a semantic role - DuplicateSemantic - { + DuplicateSemantic { /// Index of the first attribute first: usize, /// Index of the duplicate attribute @@ -355,30 +319,23 @@ pub enum LayoutError }, } -impl std::fmt::Display for LayoutError -{ - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result - { - match self - { +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 } => - { + Self::EmptyLabel { index } => { write!(formatter, "attribute {index} has an empty label") } - Self::ZeroWordCount { index } => - { + Self::ZeroWordCount { index } => { write!(formatter, "attribute {index} has a zero word count") } - Self::DuplicateLabel { first, second } => - { + Self::DuplicateLabel { first, second } => { write!( formatter, "attributes {first} and {second} share the same label" ) } - Self::DuplicateSemantic { first, second } => - { + Self::DuplicateSemantic { first, second } => { write!( formatter, "attributes {first} and {second} share the same semantic role" @@ -392,12 +349,9 @@ impl std::error::Error for LayoutError {} // Primitive attributes -impl Attribute for u32 -{ - fn average(attributes: &[Self]) -> Self - { - if attributes.is_empty() - { +impl Attribute for u32 { + fn average(attributes: &[Self]) -> Self { + if attributes.is_empty() { return Self::default(); } @@ -405,12 +359,9 @@ impl Attribute for u32 } } -impl Attribute for i32 -{ - fn average(attributes: &[Self]) -> Self - { - if attributes.is_empty() - { +impl Attribute for i32 { + fn average(attributes: &[Self]) -> Self { + if attributes.is_empty() { return Self::default(); } @@ -418,12 +369,9 @@ impl Attribute for i32 } } -impl Attribute for f32 -{ - fn average(attributes: &[Self]) -> Self - { - if attributes.is_empty() - { +impl Attribute for f32 { + fn average(attributes: &[Self]) -> Self { + if attributes.is_empty() { return Self::default(); } diff --git a/crates/vxls-attributes/tests/attributes.rs b/crates/vxls-attributes/tests/attributes.rs index 9fb9ddc..81b4190 100644 --- a/crates/vxls-attributes/tests/attributes.rs +++ b/crates/vxls-attributes/tests/attributes.rs @@ -8,8 +8,7 @@ use vxls_attributes::LayoutError; #[derive(Clone, Copy, PartialEq, Default, Pod, Zeroable, Attributes, Debug)] #[repr(C)] -struct TestAttributes -{ +struct TestAttributes { #[attribute(label = "color", semantic = "color")] color: u32, @@ -20,8 +19,7 @@ struct TestAttributes reserved: u32, } -fn sample(color: u32, normal: [f32; 3]) -> TestAttributes -{ +fn sample(color: u32, normal: [f32; 3]) -> TestAttributes { TestAttributes { color, normal, @@ -30,8 +28,7 @@ fn sample(color: u32, normal: [f32; 3]) -> TestAttributes } #[test] -fn layout_matches_the_declared_fields() -{ +fn layout_matches_the_declared_fields() { let layout = TestAttributes::LAYOUT; assert_eq!(layout.len(), 2); @@ -54,8 +51,7 @@ fn layout_matches_the_declared_fields() } #[test] -fn get_attr_returns_the_field_bytes() -{ +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)); @@ -63,14 +59,15 @@ fn get_attr_returns_the_field_bytes() 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()); + 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() -{ +fn average_is_component_wise_and_skips_the_reserved_field() { let first = TestAttributes { color: 2, normal: [1.0, 2.0, 3.0], @@ -92,8 +89,7 @@ fn average_is_component_wise_and_skips_the_reserved_field() } #[test] -fn validate_rejects_duplicate_labels_and_semantics() -{ +fn validate_rejects_duplicate_labels_and_semantics() { const DUPLICATE_LABELS: AttributesLayout = AttributesLayout { attributes: &[ AttributeDescriptor { diff --git a/crates/vxls-bvh/src/aabb.rs b/crates/vxls-bvh/src/aabb.rs index 35bd2bb..a713317 100644 --- a/crates/vxls-bvh/src/aabb.rs +++ b/crates/vxls-bvh/src/aabb.rs @@ -10,14 +10,12 @@ use glam::Vec3; /// [`Aabb::union`] and [`Aabb::union_point`]. #[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)] #[repr(C)] -pub struct Aabb -{ +pub struct Aabb { min: Vec3, max: Vec3, } -impl Aabb -{ +impl Aabb { /// The empty box: it contains no point and is the identity element for /// union operations. pub const EMPTY: Self = Self { @@ -36,14 +34,12 @@ impl Aabb /// /// 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 - { + 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 - { + pub fn from_center_half_extents(center: Vec3, half_extents: Vec3) -> Self { Self { min: center - half_extents, max: center + half_extents, @@ -53,106 +49,86 @@ impl Aabb /// Builds the tightest box containing every point. /// /// An empty iterator produces [`Aabb::EMPTY`]. - pub fn from_points(points: impl IntoIterator) -> Self - { + pub fn from_points(points: impl IntoIterator) -> Self { let mut aabb = Self::EMPTY; - for point in points - { + for point in points { aabb.union_point(point); } aabb } - pub const fn min(&self) -> Vec3 - { + pub const fn min(&self) -> Vec3 { self.min } - pub const fn max(&self) -> Vec3 - { + pub const fn max(&self) -> Vec3 { self.max } /// Center of the box. Not meaningful for an empty box. - pub fn center(&self) -> Vec3 - { + 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 - { + pub fn size(&self) -> Vec3 { self.max - self.min } /// Half extent of the box along each axis. - pub fn half_size(&self) -> Vec3 - { + 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 - { + 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 - { + 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 - { + pub fn longest_axis(&self) -> usize { let size = self.size(); - if size.x >= size.y && size.x >= size.z - { + if size.x >= size.y && size.x >= size.z { 0 - } - else if size.y >= size.z - { + } else if size.y >= size.z { 1 - } - else - { + } else { 2 } } /// Returns `true` when the box contains no point. - pub fn is_empty(&self) -> bool - { + 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 - { + pub fn is_finite(&self) -> bool { self.min.is_finite() && self.max.is_finite() } - pub fn contains_point(&self, point: Vec3) -> bool - { + 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 - { + 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 - { + pub fn intersects(&self, other: &Self) -> bool { !self.is_empty() && !other.is_empty() && self.min.cmple(other.max).all() @@ -162,8 +138,7 @@ impl Aabb /// Overlap of both boxes. /// /// The result is empty when the boxes do not intersect. - pub fn intersection(&self, other: &Self) -> Self - { + pub fn intersection(&self, other: &Self) -> Self { Self { min: self.min.max(other.min), max: self.max.min(other.max), @@ -171,22 +146,19 @@ impl Aabb } /// Grows the box to contain `point`. - pub fn union_point(&mut self, point: Vec3) - { + 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) - { + 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 - { + pub fn expanded(&self, margin: f32) -> Self { let margin = Vec3::splat(margin); Self { min: self.min - margin, @@ -199,10 +171,8 @@ impl Aabb /// /// 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() - { + pub fn padded_to_min_size(&self, min_size: f32) -> Self { + if self.is_empty() { return Self::EMPTY; } @@ -211,8 +181,7 @@ impl Aabb } /// Returns an iterator over all of the corner points of the box - pub fn corner_points(&self) -> impl Iterator - { + pub fn corner_points(&self) -> impl Iterator { (0..=7).map(|i| { let a = &self.min; let b = &self.max; @@ -226,8 +195,7 @@ impl Aabb } /// Returns the Aabb bounding box of the box transformed by `transformed` - pub fn as_transformed_by(&self, transform: &Mat4) -> Self - { + pub fn as_transformed_by(&self, transform: &Mat4) -> Self { Self::from_points( self.corner_points() .map(|point| transform.transform_point3(point)), @@ -235,23 +203,19 @@ impl Aabb } } -impl Default for Aabb -{ - fn default() -> Self - { +impl Default for Aabb { + fn default() -> Self { Self::EMPTY } } #[cfg(test)] -mod tests -{ +mod tests { use super::*; const EPSILON: f32 = 1e-6; - fn assert_vec3_eq(a: Vec3, b: Vec3) - { + fn assert_vec3_eq(a: Vec3, b: Vec3) { assert!( (a - b).abs().max_element() <= EPSILON, "expected {b:?}, got {a:?}" @@ -259,8 +223,7 @@ mod tests } #[test] - fn empty_box_contains_nothing() - { + fn empty_box_contains_nothing() { let aabb = Aabb::EMPTY; assert!(aabb.is_empty()); assert!(!aabb.contains_point(Vec3::ZERO)); @@ -268,8 +231,7 @@ mod tests } #[test] - fn empty_is_identity_for_union() - { + fn empty_is_identity_for_union() { let aabb = Aabb::new(Vec3::ZERO, Vec3::ONE); let mut grown = Aabb::EMPTY; @@ -282,14 +244,12 @@ mod tests } #[test] - fn from_points_of_empty_iterator_is_empty() - { + fn from_points_of_empty_iterator_is_empty() { assert!(Aabb::from_points(std::iter::empty()).is_empty()); } #[test] - fn from_points_bounds_all_points() - { + fn from_points_bounds_all_points() { let points = [ Vec3::new(1.0, -2.0, 3.0), Vec3::new(-4.0, 5.0, -6.0), @@ -299,15 +259,13 @@ mod tests 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 - { + for point in points { assert!(aabb.contains_point(point)); } } #[test] - fn center_and_size() - { + 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)); @@ -316,8 +274,7 @@ mod tests } #[test] - fn from_center_half_extents_round_trips() - { + 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)); @@ -325,8 +282,7 @@ mod tests } #[test] - fn union_grows_to_contain_both_boxes() - { + 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)); @@ -340,8 +296,7 @@ mod tests } #[test] - fn contains_point_respects_faces() - { + fn contains_point_respects_faces() { let aabb = Aabb::new(Vec3::ZERO, Vec3::ONE); assert!(aabb.contains_point(Vec3::ZERO)); @@ -352,8 +307,7 @@ mod tests } #[test] - fn contains_box() - { + fn contains_box() { let outer = Aabb::new(Vec3::ZERO, Vec3::splat(4.0)); let inner = Aabb::new(Vec3::ONE, Vec3::splat(3.0)); @@ -363,8 +317,7 @@ mod tests } #[test] - fn separated_boxes_do_not_intersect() - { + 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)); @@ -374,8 +327,7 @@ mod tests } #[test] - fn touching_boxes_intersect() - { + 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)); @@ -384,8 +336,7 @@ mod tests } #[test] - fn overlapping_boxes_intersect() - { + fn overlapping_boxes_intersect() { let a = Aabb::new(Vec3::ZERO, Vec3::splat(2.0)); let b = Aabb::new(Vec3::ONE, Vec3::splat(3.0)); @@ -397,8 +348,7 @@ mod tests } #[test] - fn surface_area_and_volume() - { + 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); @@ -406,8 +356,7 @@ mod tests } #[test] - fn longest_axis_picks_largest_extent() - { + fn longest_axis_picks_largest_extent() { assert_eq!( Aabb::new(Vec3::ZERO, Vec3::new(3.0, 1.0, 2.0)).longest_axis(), 0 @@ -423,8 +372,7 @@ mod tests } #[test] - fn expanded_adds_margin_on_every_side() - { + 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)); @@ -433,8 +381,7 @@ mod tests } #[test] - fn padded_to_min_size_keeps_flat_box_usable() - { + 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); @@ -447,21 +394,18 @@ mod tests } #[test] - fn padded_empty_box_stays_empty() - { + fn padded_empty_box_stays_empty() { assert!(Aabb::EMPTY.padded_to_min_size(1.0).is_empty()); } #[test] - fn default_is_empty() - { + fn default_is_empty() { assert_eq!(Aabb::default(), Aabb::EMPTY); assert!(Aabb::default().is_empty()); } #[test] - fn layout_is_two_vec3s() - { + fn layout_is_two_vec3s() { assert_eq!(std::mem::size_of::(), 24); assert_eq!(bytemuck::bytes_of(&Aabb::EMPTY).len(), 24); } diff --git a/crates/vxls-bvh/src/build.rs b/crates/vxls-bvh/src/build.rs index 9c17019..493712f 100644 --- a/crates/vxls-bvh/src/build.rs +++ b/crates/vxls-bvh/src/build.rs @@ -11,8 +11,7 @@ use super::aabb::Aabb; macro_rules! get_dim { ($v:expr, $d:expr) => { - match $d - { + match $d { 0 => $v.x, 1 => $v.y, _ => $v.z, @@ -29,8 +28,7 @@ const SAH_INTERSECT: f32 = 1.; const SAH_BIN_COUNT: usize = 16; #[derive(Clone, Copy)] -pub struct BvhNode -{ +pub struct BvhNode { /// The bounding box of this bvh node aabb: Aabb, @@ -43,10 +41,8 @@ pub struct BvhNode first_or_left: u32, } -impl From for BvhNode -{ - fn from(value: GpuBvhNode) -> Self - { +impl From for BvhNode { + fn from(value: GpuBvhNode) -> Self { Self { aabb: value.aabb.into(), count: value.count, @@ -55,10 +51,8 @@ impl From for BvhNode } } -impl From for GpuBvhNode -{ - fn from(value: BvhNode) -> Self - { +impl From for GpuBvhNode { + fn from(value: BvhNode) -> Self { GpuBvhNode { aabb: value.aabb.into(), count: value.count, @@ -68,10 +62,8 @@ impl From for GpuBvhNode } } -impl BvhNode -{ - pub fn internal(aabb: Aabb, left: u32) -> BvhNode - { +impl BvhNode { + pub fn internal(aabb: Aabb, left: u32) -> BvhNode { Self { aabb, count: 0, @@ -79,8 +71,7 @@ impl BvhNode } } - pub fn leaf(aabb: Aabb, count: NonZero, first_index: u32) -> BvhNode - { + pub fn leaf(aabb: Aabb, count: NonZero, first_index: u32) -> BvhNode { Self { aabb, count: count.into(), @@ -88,78 +79,59 @@ impl BvhNode } } - pub fn is_internal(&self) -> bool - { + pub fn is_internal(&self) -> bool { self.count == 0 } - pub fn is_leaf(&self) -> bool - { + pub fn is_leaf(&self) -> bool { self.count != 0 } - pub fn first(&self) -> Option - { - if !self.is_leaf() - { + pub fn first(&self) -> Option { + if !self.is_leaf() { None - } - else - { + } else { Some(self.first_or_left) } } - pub fn count(&self) -> Option - { - if !self.is_leaf() - { + pub fn count(&self) -> Option { + if !self.is_leaf() { None - } - else - { + } else { Some(self.count) } } - pub fn left(&self) -> Option - { - if !self.is_internal() - { + pub fn left(&self) -> Option { + if !self.is_internal() { None - } - else - { + } else { Some(self.first_or_left) } } - pub fn right(&self) -> Option - { + pub fn right(&self) -> Option { self.left().map(|x| x + 1) } } -pub struct BvhPrimitive -{ +pub struct BvhPrimitive { pub aabb: Aabb, pub handle: T, } -pub struct Bvh -{ +pub struct Bvh { /// List of the bvh's nodes pub nodes: Vec, pub depth: usize, } -pub fn build_bvh(primitives: &mut [BvhPrimitive], leaf_max: usize) -> Bvh -{ +pub fn build_bvh(primitives: &mut [BvhPrimitive], leaf_max: usize) -> Bvh { let mut nodes = Vec::new(); //let mut prim_indices = Vec::new(); - if primitives.is_empty() - { + if primitives.is_empty() { return Bvh { nodes, depth: 1, @@ -194,8 +166,7 @@ pub fn build_node( 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"); @@ -207,10 +178,8 @@ pub fn build_node( // 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)) => - { + 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| { @@ -222,15 +191,11 @@ pub fn build_node( 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 - { + 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 - { + } else { right_aabb.union(&primitive.aabb); } } @@ -275,11 +240,9 @@ pub fn build_node( max_depth, ); } - None => - { + None => { // Sah says keep as leaf, do nothing - if depth > *max_depth - { + if depth > *max_depth { *max_depth = depth; } } @@ -287,11 +250,9 @@ pub fn build_node( } /// Returns Some if SAH says split, none if it wants a leaf -pub fn sah_split(primitives: &[BvhPrimitive], leaf_max: usize) -> Option<(usize, f32)> -{ +pub fn sah_split(primitives: &[BvhPrimitive], leaf_max: usize) -> Option<(usize, f32)> { // Don't even bother, spliting it does nothing - if primitives.len() <= 2 - { + if primitives.len() <= 2 { return None; } @@ -308,8 +269,7 @@ pub fn sah_split(primitives: &[BvhPrimitive], leaf_max: usize) -> Option<( let mut best_dimension = 0; let mut minimum_cost = f32::INFINITY; let mut minimum_split_plane = 0.; - for dimension in 0..3usize - { + for dimension in 0..3usize { let cetroid_min = get_dim!(centroid_bounds.min(), dimension); // The size of a bin in this dimension @@ -320,8 +280,7 @@ pub fn sah_split(primitives: &[BvhPrimitive], leaf_max: usize) -> Option<( let mut bin_counts: [usize; SAH_BIN_COUNT] = Default::default(); // Bin elements - for primitive in primitives.iter() - { + 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); @@ -338,8 +297,7 @@ pub fn sah_split(primitives: &[BvhPrimitive], leaf_max: usize) -> Option<( let mut suffix_counts: [usize; SAH_BIN_COUNT] = bin_counts; // We build prefix and suffix simultaneously - for i in 1..SAH_BIN_COUNT - { + 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]; @@ -352,14 +310,12 @@ pub fn sah_split(primitives: &[BvhPrimitive], leaf_max: usize) -> Option<( // 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) - { + 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 - { + if split_sah < minimum_cost { best_dimension = dimension; minimum_cost = split_sah; @@ -369,13 +325,10 @@ pub fn sah_split(primitives: &[BvhPrimitive], leaf_max: usize) -> Option<( } } - if leaf_sah < minimum_cost && primitives.len() <= leaf_max - { + if leaf_sah < minimum_cost && primitives.len() <= leaf_max { // SAH requires leaf None - } - else - { + } else { // SAH requires split Some((best_dimension, minimum_split_plane)) } diff --git a/crates/vxls-bvh/src/debug.rs b/crates/vxls-bvh/src/debug.rs index 7b21631..7725cbb 100644 --- a/crates/vxls-bvh/src/debug.rs +++ b/crates/vxls-bvh/src/debug.rs @@ -18,24 +18,21 @@ const _: () = { /// /// One instance is one `GpuBvhNode`; the shader generates all vertices, so no /// vertex or index buffer is needed. -pub struct BvhDebugPipeline -{ +pub struct BvhDebugPipeline { solid_pipeline: wgpu::RenderPipeline, line_pipeline: wgpu::RenderPipeline, bind_group_layout: wgpu::BindGroupLayout, view_proj_buffer: wgpu::Buffer, } -impl BvhDebugPipeline -{ +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 - { + ) -> Self { let shader = device.create_shader_module(wgpu::include_wgsl!("debug.wgsl")); let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { @@ -182,10 +179,8 @@ impl BvhDebugPipeline object_buffer: &wgpu::Buffer, node_count: u32, max_objects_per_leaf: u32, - ) - { - if node_count == 0 - { + ) { + if node_count == 0 { return; } @@ -238,8 +233,7 @@ impl BvhDebugPipeline // Filled object boxes first so the wireframes can depth-test against // them. - if max_objects_per_leaf > 0 - { + if max_objects_per_leaf > 0 { pass.set_pipeline(&self.solid_pipeline); pass.draw(0..36 * max_objects_per_leaf, 0..node_count); } diff --git a/crates/vxls-bvh/src/gpu.rs b/crates/vxls-bvh/src/gpu.rs index f7fc5a8..f7ea798 100644 --- a/crates/vxls-bvh/src/gpu.rs +++ b/crates/vxls-bvh/src/gpu.rs @@ -7,8 +7,7 @@ use crate::aabb::Aabb; #[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)] #[repr(C)] -pub struct GpuAabb -{ +pub struct GpuAabb { pub min: Vec3, _pad0: u32, // On the GPU vec3 are aligned to 4 u32 pub max: Vec3, @@ -22,8 +21,7 @@ pub struct GpuAabb /// of data up to a 48-byte stride. #[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)] #[repr(C)] -pub struct GpuBvhNode -{ +pub struct GpuBvhNode { pub aabb: GpuAabb, pub count: u32, pub first_or_left: u32, @@ -33,34 +31,27 @@ pub struct GpuBvhNode /// To be a leaf of a GPU BVH #[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)] #[repr(C)] -pub struct GpuObject -{ +pub struct GpuObject { local_to_world: Mat4, // Tranform world_to_local: Mat4, // Ray to chunk table_slot: u32, _pad0: [u32; 3], } -impl From for GpuAabb -{ - fn from(value: Aabb) -> Self - { +impl From for GpuAabb { + fn from(value: Aabb) -> Self { Self::new(value.min(), value.max()) } } -impl From for Aabb -{ - fn from(value: GpuAabb) -> Self - { +impl From for Aabb { + fn from(value: GpuAabb) -> Self { Aabb::new(value.min, value.max) } } -impl GpuObject -{ - pub fn new(slot: u32, transform: Mat4) -> Self - { +impl GpuObject { + pub fn new(slot: u32, transform: Mat4) -> Self { GpuObject { local_to_world: transform, world_to_local: transform.inverse(), @@ -70,10 +61,8 @@ impl GpuObject } } -impl GpuAabb -{ - pub fn new(min: Vec3, max: Vec3) -> Self - { +impl GpuAabb { + pub fn new(min: Vec3, max: Vec3) -> Self { Self { min, _pad0: Default::default(), diff --git a/crates/vxls-bvh/src/lib.rs b/crates/vxls-bvh/src/lib.rs index 5dd7694..443385e 100644 --- a/crates/vxls-bvh/src/lib.rs +++ b/crates/vxls-bvh/src/lib.rs @@ -31,8 +31,7 @@ pub mod gpu; /// To handle an object stored in the bvh #[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)] -pub struct BvhHandle -{ +pub struct BvhHandle { pub anchor: StructureAnchor, pub producer_id: ProducerId, @@ -42,8 +41,7 @@ pub struct BvhHandle } /// An object that is stored by the BVH structure -pub struct BvhObject -{ +pub struct BvhObject { /// Identity of the voxel data pub anchor: StructureAnchor, pub producer_id: ProducerId, @@ -56,15 +54,12 @@ pub struct BvhObject pub bounding_box: Aabb, } -impl BvhObject -{ - pub fn world_bounding_box(&self) -> Aabb - { +impl BvhObject { + pub fn world_bounding_box(&self) -> Aabb { self.bounding_box.as_transformed_by(&self.transform) } - pub fn structure_anchor(&self) -> StructureAnchor - { + pub fn structure_anchor(&self) -> StructureAnchor { self.anchor } } @@ -79,8 +74,7 @@ impl BvhObject /// Raytrace bindings: /// 0 = `GpuBvhNode[]` (read-only), 1 = `GpuObject[]` (read-only), /// 2 = inner structure-table pointers, 3 = inner structure-table requests. -pub struct BvhStructureTable -{ +pub struct BvhStructureTable { /// Handle to object in the bvh objects: HashMap, @@ -111,10 +105,8 @@ pub struct BvhStructureTable } #[allow(dead_code)] -impl BvhStructureTable -{ - pub fn new(device: &wgpu::Device, initial_capacity: usize, max_requests: usize) -> Self - { +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); @@ -151,8 +143,7 @@ impl BvhStructureTable device: &wgpu::Device, queue: &wgpu::Queue, object: BvhObject, - ) -> BvhHandle - { + ) -> BvhHandle { let key = self.current_key; self.current_key += 1; let handle = BvhHandle { @@ -170,8 +161,7 @@ impl BvhStructureTable handle } - pub fn build(&self) -> (Vec, Vec) - { + pub fn build(&self) -> (Vec, Vec) { // Collect primitives let mut primitives = self .objects @@ -207,29 +197,24 @@ impl BvhStructureTable /// 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) - { + 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 - { + 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) - { + 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 - { + pub fn rebuild_if_dirty(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) { + if self.dirty { self.rebuild(device, queue); } } @@ -240,29 +225,24 @@ impl BvhStructureTable queue: &wgpu::Queue, nodes: &[GpuBvhNode], objects: &[GpuObject], - ) - { + ) { let node_capacity = grown_capacity(self.node_capacity, nodes.len()); - if node_capacity > self.node_capacity - { + if node_capacity > self.node_capacity { self.node_capacity = node_capacity; self.bvh_nodes = create_bvh_buffer::(device, node_capacity, "bvh_nodes"); } let object_capacity = grown_capacity(self.object_capacity, objects.len()); - if object_capacity > self.object_capacity - { + if object_capacity > self.object_capacity { self.object_capacity = object_capacity; self.bvh_objects = create_bvh_buffer::(device, object_capacity, "bvh_objects"); } - if !nodes.is_empty() - { + if !nodes.is_empty() { queue.write_buffer(&self.bvh_nodes, 0, bytemuck::cast_slice(nodes)); } - if !objects.is_empty() - { + if !objects.is_empty() { queue.write_buffer(&self.bvh_objects, 0, bytemuck::cast_slice(objects)); } @@ -284,33 +264,27 @@ impl BvhStructureTable self.dirty = false; } - pub fn bvh_nodes(&self) -> &wgpu::Buffer - { + pub fn bvh_nodes(&self) -> &wgpu::Buffer { &self.bvh_nodes } - pub fn bvh_objects(&self) -> &wgpu::Buffer - { + pub fn bvh_objects(&self) -> &wgpu::Buffer { &self.bvh_objects } - pub fn node_count(&self) -> u32 - { + pub fn node_count(&self) -> u32 { self.node_count } - pub fn object_count(&self) -> u32 - { + pub fn object_count(&self) -> u32 { self.object_count } - 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 } @@ -321,8 +295,7 @@ impl BvhStructureTable device: &wgpu::Device, encoder: &mut ScopeEncoder, request_buffer: &CacheRequestBuffer, - ) - { + ) { self.structure_table .gather_requests(device, encoder, request_buffer); } @@ -340,13 +313,11 @@ impl BvhStructureTable self.structure_table.insert(device, encoder, insertion); } - pub fn get(&self, handle: &BvhHandle) -> Option<&BvhObject> - { + pub fn get(&self, handle: &BvhHandle) -> Option<&BvhObject> { self.objects.get(handle) } - pub fn get_mut(&mut self, handle: &BvhHandle) -> Option<&mut BvhObject> - { + pub fn get_mut(&mut self, handle: &BvhHandle) -> Option<&mut BvhObject> { self.objects.get_mut(handle) } } @@ -360,8 +331,7 @@ where device: &wgpu::Device, encoder: &mut ScopeEncoder, insertion: &CacheInsertionData, - ) - { + ) { self.structure_table .validate_insertion(device, encoder, insertion); } @@ -371,15 +341,13 @@ where encoder: &mut ScopeEncoder, cache_evictor: &CacheEvictor, invalid_timestamp: u32, - ) - { + ) { self.structure_table .invalidate(encoder, cache_evictor, invalid_timestamp); } } -fn create_bvh_buffer(device: &wgpu::Device, capacity: usize, label: &str) -> wgpu::Buffer -{ +fn create_bvh_buffer(device: &wgpu::Device, capacity: usize, label: &str) -> wgpu::Buffer { let capacity = capacity.max(1); device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), @@ -389,23 +357,19 @@ fn create_bvh_buffer(device: &wgpu::Device, capacity: usize, label: &str) -> }) } -fn grown_capacity(current: usize, required: usize) -> usize -{ - if required <= current - { +fn grown_capacity(current: usize, required: usize) -> usize { + if required <= current { return current; } let mut capacity = current.max(1); - while capacity < required - { + while capacity < required { capacity = capacity.saturating_mul(2); } capacity } -fn create_bvh_raytrace_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout -{ +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, @@ -450,8 +414,7 @@ fn create_bvh_raytrace_bind_group( objects: &wgpu::Buffer, structure_pointers: &wgpu::Buffer, structure_requests: &wgpu::Buffer, -) -> wgpu::BindGroup -{ +) -> wgpu::BindGroup { device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("BvhStructureTable::raytrace_bind_group"), layout, diff --git a/crates/vxls-gpu/src/buffer_compactor.rs b/crates/vxls-gpu/src/buffer_compactor.rs index 610ecfd..db80035 100644 --- a/crates/vxls-gpu/src/buffer_compactor.rs +++ b/crates/vxls-gpu/src/buffer_compactor.rs @@ -10,8 +10,7 @@ use wgpu::Device; use wgpu::ShaderStages; use wgpu::util::DeviceExt; -pub struct NonZeroBufferCompactor -{ +pub struct NonZeroBufferCompactor { block_count: usize, reduced_buffer: Buffer, #[allow(unused)] @@ -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"), @@ -189,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::() * 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::() * self.block_count) as u64, @@ -213,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, @@ -253,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) }, ); diff --git a/crates/vxls-gpu/src/indirect_buffer.rs b/crates/vxls-gpu/src/indirect_buffer.rs index 82a295f..5856e71 100644 --- a/crates/vxls-gpu/src/indirect_buffer.rs +++ b/crates/vxls-gpu/src/indirect_buffer.rs @@ -4,8 +4,7 @@ use wgpu::Buffer; use wgpu::CommandEncoder; /// 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::() 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"), diff --git a/crates/vxls-gpu/src/lib.rs b/crates/vxls-gpu/src/lib.rs index 91d3555..1426e09 100644 --- a/crates/vxls-gpu/src/lib.rs +++ b/crates/vxls-gpu/src/lib.rs @@ -9,8 +9,7 @@ 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, @@ -35,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() @@ -57,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) diff --git a/crates/vxls-gpu/src/radix_sort.rs b/crates/vxls-gpu/src/radix_sort.rs index 94759e2..6838233 100644 --- a/crates/vxls-gpu/src/radix_sort.rs +++ b/crates/vxls-gpu/src/radix_sort.rs @@ -9,23 +9,20 @@ use wgpu::QuerySet; use wgpu::include_spirv; #[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, @@ -56,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; @@ -79,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); @@ -330,8 +325,7 @@ impl RadixSorter direct_length: Option, 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, @@ -379,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, @@ -421,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, }, diff --git a/crates/vxls-gpu/src/top_k.rs b/crates/vxls-gpu/src/top_k.rs index 886cdd8..20727b1 100644 --- a/crates/vxls-gpu/src/top_k.rs +++ b/crates/vxls-gpu/src/top_k.rs @@ -47,8 +47,7 @@ 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 -{ +struct TopKParams { element_count: u32, k: u32, } @@ -58,8 +57,7 @@ struct TopKParams /// 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 -{ +pub struct TopKSelector { max_selected: u32, histogram: Buffer, @@ -75,11 +73,9 @@ pub struct TopKSelector select_pass: ComputePipeline, } -impl TopKSelector -{ +impl TopKSelector { /// Creates a selector that can output at most `max_selected` indices. - pub fn new(device: &Device, max_selected: u32) -> Self - { + pub fn new(device: &Device, max_selected: u32) -> Self { assert!( device.features().contains(wgpu::Features::IMMEDIATES), "TopKSelector requires the IMMEDIATES feature" @@ -284,8 +280,7 @@ impl TopKSelector requests: &Buffer, element_count: u32, k: u32, - ) - { + ) { assert!( k <= self.max_selected, "TopKSelector: k ({k}) exceeds the max_selected capacity ({})", @@ -355,51 +350,41 @@ impl TopKSelector } /// Number of indices emitted by the last [`Self::select`] call. - pub fn selected_count_buffer(&self) -> &Buffer - { + 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 - { + 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 - { + pub fn threshold_buffer(&self) -> &Buffer { &self.threshold } /// Maximum number of indices this selector can emit. - pub fn max_selected(&self) -> u32 - { + pub fn max_selected(&self) -> u32 { self.max_selected } } #[cfg(test)] -mod tests -{ +mod tests { use super::*; /// CPU mirror of the WGSL quantizer. - fn quantize_cpu(count: u32) -> u32 - { - if count == 0 - { + fn quantize_cpu(count: u32) -> u32 { + if count == 0 { return 0; } let exponent = 31 - count.leading_zeros(); - let extra = if exponent >= LOG_SUB_BINS - { + let extra = if exponent >= LOG_SUB_BINS { (count >> (exponent - LOG_SUB_BINS)) & (SUB_BINS - 1) - } - else - { + } else { (count << (LOG_SUB_BINS - exponent)) & (SUB_BINS - 1) }; @@ -407,14 +392,11 @@ mod tests } /// CPU mirror of the three passes. - fn select_cpu(counts: &[u32], k: u32) -> (Vec, i32) - { + fn select_cpu(counts: &[u32], k: u32) -> (Vec, i32) { let mut histogram = vec![0u32; BIN_COUNT as usize]; - for &count in counts - { - if count != 0 - { + for &count in counts { + if count != 0 { histogram[quantize_cpu(count) as usize] += 1; } } @@ -422,12 +404,10 @@ mod tests let mut sum = 0u32; let mut threshold = -1i32; - for bin in (0..BIN_COUNT as usize).rev() - { + for bin in (0..BIN_COUNT as usize).rev() { let count = histogram[bin]; - if sum + count >= k - { + if sum + count >= k { threshold = bin as i32; break; } @@ -447,18 +427,14 @@ mod tests // 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 - { + if threshold >= 0 { let mut slots = remaining; - for (index, &count) in counts.iter().enumerate() - { - if slots == 0 - { + for (index, &count) in counts.iter().enumerate() { + if slots == 0 { break; } - if count != 0 && quantize_cpu(count) as i32 == threshold - { + if count != 0 && quantize_cpu(count) as i32 == threshold { selected.push(index as u32); slots -= 1; } @@ -468,8 +444,7 @@ mod tests (selected, threshold) } - fn next_random(state: &mut u64) -> u32 - { + fn next_random(state: &mut u64) -> u32 { *state ^= *state << 13; *state ^= *state >> 7; *state ^= *state << 17; @@ -477,12 +452,10 @@ mod tests } #[test] - fn quantize_is_monotonic() - { + fn quantize_is_monotonic() { let mut previous = 0; - for count in 1..100_000u32 - { + for count in 1..100_000u32 { let bin = quantize_cpu(count); assert!(bin >= previous, "quantize({count}) = {bin} < {previous}"); assert!(bin < BIN_COUNT); @@ -496,8 +469,7 @@ mod tests values.sort_unstable(); let mut previous = 0; - for count in values - { + for count in values { let bin = quantize_cpu(count); assert!(bin >= previous); assert!(bin < BIN_COUNT); @@ -506,19 +478,16 @@ mod tests } #[test] - fn quantize_handles_zero_and_max() - { + 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() - { + fn selection_selects_exactly_min_k_and_non_zero() { let mut state = 0x0ddc_0ffe_e15e_beefu64; - for _ in 0..100 - { + for _ in 0..100 { let len = 1 + (next_random(&mut state) % 1000) as usize; let counts = (0..len) .map(|_| next_random(&mut state) % 64) @@ -526,8 +495,7 @@ mod tests let non_zero = counts.iter().filter(|&&count| count != 0).count(); - for k in 0..=20 - { + for k in 0..=20 { let (selected, threshold) = select_cpu(&counts, k); assert_eq!(selected.len(), (k as usize).min(non_zero)); @@ -537,8 +505,7 @@ mod tests sorted.dedup(); assert_eq!(sorted.len(), selected.len(), "duplicate indices"); - for &index in &selected - { + for &index in &selected { let count = counts[index as usize]; assert!(count != 0); assert!(quantize_cpu(count) as i32 >= threshold); @@ -548,8 +515,7 @@ mod tests } #[test] - fn selection_fills_threshold_bin_to_exactly_k() - { + fn selection_fills_threshold_bin_to_exactly_k() { let counts = [1, 5, 3, 5, 2]; let (selected, _) = select_cpu(&counts, 3); @@ -560,8 +526,7 @@ mod tests } #[test] - fn selection_with_fewer_candidates_than_k() - { + fn selection_with_fewer_candidates_than_k() { let counts = [1, 0, 2, 0, 3]; let (selected, threshold) = select_cpu(&counts, 10); @@ -570,8 +535,7 @@ mod tests } #[test] - fn selection_with_k_zero() - { + fn selection_with_k_zero() { let counts = [1, 2, 3]; let (selected, _) = select_cpu(&counts, 0); @@ -579,8 +543,7 @@ mod tests } #[test] - fn selection_with_all_equal_counts_selects_k() - { + fn selection_with_all_equal_counts_selects_k() { let counts = [7, 7, 7, 7]; let (selected, threshold) = select_cpu(&counts, 2); @@ -590,8 +553,7 @@ mod tests } #[test] - fn selection_with_all_zero_counts() - { + fn selection_with_all_zero_counts() { let counts = [0, 0, 0, 0]; let (selected, threshold) = select_cpu(&counts, 2); @@ -601,8 +563,7 @@ mod tests #[test] #[ignore = "requires a GPU adapter with the IMMEDIATES feature"] - fn gpu_selection_smoke_test() - { + 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())) @@ -628,8 +589,7 @@ mod tests // Run the selection twice to verify that the histogram and fill state // are reset between calls. - for _ in 0..2 - { + for _ in 0..2 { let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("TopKSelector::test_encoder"), }); @@ -678,8 +638,7 @@ mod tests device: &wgpu::Device, queue: &wgpu::Queue, selector: &TopKSelector, - ) -> (u32, Vec) - { + ) -> (u32, Vec) { let count = std::sync::Arc::new(std::sync::Mutex::new(None)); let count_clone = count.clone(); wgpu::util::DownloadBuffer::read_buffer( diff --git a/crates/vxls-production/src/io.rs b/crates/vxls-production/src/io.rs index c17dc06..9bce226 100644 --- a/crates/vxls-production/src/io.rs +++ b/crates/vxls-production/src/io.rs @@ -206,6 +206,9 @@ mod write; pub use error::TreeFileError; pub use format::FileAttribute; -pub use read::{FileLayout, TreeFile, read_tree, read_tree_from_path}; -pub use write::{write_tree, write_tree_to_path}; - +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; diff --git a/crates/vxls-production/src/io/chunk.rs b/crates/vxls-production/src/io/chunk.rs index ee4ced1..825c65e 100644 --- a/crates/vxls-production/src/io/chunk.rs +++ b/crates/vxls-production/src/io/chunk.rs @@ -1,8 +1,12 @@ //! Chunk framing: 8-byte alignment, tag/size headers and CRC-32. -use std::io::{Read, Seek, Write}; +use std::io::Read; +use std::io::Seek; +use std::io::Write; -use binrw::{BinRead, BinWrite, Endian}; +use binrw::BinRead; +use binrw::BinWrite; +use binrw::Endian; use super::error::TreeFileError; use super::format::CHUNK_FRAME_SIZE; @@ -15,30 +19,24 @@ const ZEROES: [u8; 8] = [0; 8]; /// A chunk read from a file, with its CRC already verified. #[derive(Clone, Debug)] -pub struct Chunk -{ +pub struct Chunk { pub tag: u32, pub size: u64, pub body: Vec, } /// 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 -{ +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( - writer: &mut W, -) -> Result<(), TreeFileError> -{ +pub fn write_padding_to_alignment(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 - { + if padding > 0 { writer.write_all(&ZEROES[..padding])?; } @@ -50,12 +48,10 @@ pub fn write_chunk( writer: &mut W, tag: u32, body: &[u8], -) -> Result<(), TreeFileError> -{ +) -> Result<(), TreeFileError> { let position = writer.stream_position()?; - if position % CHUNK_ALIGNMENT != 0 - { + if position % CHUNK_ALIGNMENT != 0 { return Err(TreeFileError::MisalignedOffset { offset: position }); } @@ -82,22 +78,16 @@ pub fn write_chunk( /// 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( - reader: &mut R, - file_len: u64, -) -> Result -{ +pub fn read_chunk(reader: &mut R, file_len: u64) -> Result { let offset = reader.stream_position()?; - if offset % CHUNK_ALIGNMENT != 0 - { + 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 - { + if frame.chunk_size < CHUNK_FRAME_SIZE { return Err(TreeFileError::ChunkSizeTooSmall { tag: frame.chunk_type_tag, size: frame.chunk_size, @@ -109,8 +99,7 @@ pub fn read_chunk( .and_then(|value| value.checked_add(4)) .ok_or(TreeFileError::Overflow { what: "chunk end" })?; - if end > file_len - { + if end > file_len { return Err(TreeFileError::ChunkOutOfBounds { tag: frame.chunk_type_tag, offset, @@ -118,8 +107,11 @@ pub fn read_chunk( }); } - let body_len = usize::try_from(frame.chunk_size - CHUNK_FRAME_SIZE) - .map_err(|_| TreeFileError::Overflow { what: "chunk body length" })?; + 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)?; @@ -134,8 +126,7 @@ pub fn read_chunk( hasher.update(&body); let expected = hasher.finalize(); - if expected != found - { + if expected != found { return Err(TreeFileError::CrcMismatch { tag: frame.chunk_type_tag, offset, @@ -154,15 +145,10 @@ pub fn read_chunk( /// Reads the gap between `position` and `target`, requiring every byte to be zero. /// /// The caller guarantees `position <= target < position + 8`. -pub fn read_padding( - reader: &mut R, - target: u64, -) -> Result<(), TreeFileError> -{ +pub fn read_padding(reader: &mut R, target: u64) -> Result<(), TreeFileError> { let position = reader.stream_position()?; - if target < position - { + if target < position { return Err(TreeFileError::ChunkOffsetMismatch { tag: 0, expected: target, @@ -172,18 +158,15 @@ pub fn read_padding( let length = target - position; - if length >= CHUNK_ALIGNMENT - { + 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 - { + for (index, byte) in buffer[..length as usize].iter().enumerate() { + if *byte != 0 { return Err(TreeFileError::NonZeroPadding { offset: position + index as u64, value: *byte, diff --git a/crates/vxls-production/src/io/error.rs b/crates/vxls-production/src/io/error.rs index ddb82b8..dd395bc 100644 --- a/crates/vxls-production/src/io/error.rs +++ b/crates/vxls-production/src/io/error.rs @@ -5,8 +5,7 @@ use std::io; /// Anything that can go wrong reading or writing a sparse-tree file. #[derive(Debug)] -pub enum TreeFileError -{ +pub enum TreeFileError { /// An underlying I/O error. Io(io::Error), @@ -14,246 +13,129 @@ pub enum TreeFileError Binrw(binrw::Error), /// The file does not start with `b"VXLS"`. - BadMagic - { - found: [u8; 4], - }, + BadMagic { found: [u8; 4] }, /// The file is not a sparse tree (`b"ST\0\0"`). - BadFileType - { - found: [u8; 4], - }, + BadFileType { found: [u8; 4] }, /// The file's version is not readable by this implementation. - UnsupportedVersion - { - major: u32, - minor: u32, - }, + UnsupportedVersion { major: u32, minor: u32 }, /// The file is shorter than a mandatory fixed-size section. - FileTooSmall - { - len: u64, - needed: u64, - }, + FileTooSmall { len: u64, needed: u64 }, /// The preamble's declared size does not match the real file length. - FileSizeMismatch - { - declared: u64, - actual: u64, - }, + FileSizeMismatch { declared: u64, actual: u64 }, /// `header_size` is below the minimum. - HeaderTooSmall - { - header_size: u32, - }, + HeaderTooSmall { header_size: u32 }, /// The header extends past the end of the file. - HeaderOutOfBounds - { - header_size: u32, - file_len: u64, - }, + HeaderOutOfBounds { header_size: u32, file_len: u64 }, /// `tree_arity` is below 2. - ArityTooSmall - { - arity: u32, - }, + ArityTooSmall { arity: u32 }, /// The file's arity does not match the requested `N`. - ArityMismatch - { - file: u32, - requested: u32, - }, + ArityMismatch { file: u32, requested: u32 }, /// `tree_depth` exceeds what `TreeLocator` can address for this arity. - DepthTooLarge - { - depth: u32, - max: u32, - }, + 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, - }, + InvalidWordCount { index: usize, word_count: u32 }, /// The layout's word count does not match `size_of::()`. - LayoutSizeMismatch - { + LayoutSizeMismatch { layout_words: u64, payload_words: u64, }, /// `size_of::()` is not a whole number of 32-bit words. - PayloadNotWordAligned - { - size: usize, - }, + PayloadNotWordAligned { size: usize }, /// The file's attribute word counts differ from the expected layout. - LayoutMismatch - { - expected: Vec, - found: Vec, - }, + LayoutMismatch { expected: Vec, found: Vec }, /// The offset table size is not a multiple of the entry size. - OffsetTableNotAligned - { - size: u32, - }, + OffsetTableNotAligned { size: u32 }, /// The offset table extends past the end of the file. - OffsetTableOutOfBounds - { - end: u64, - file_len: u64, - }, + 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, - }, + MisalignedOffset { offset: u64 }, /// A chunk does not start where the previous chunk and the alignment rule say. - ChunkOffsetMismatch - { - tag: u32, - expected: u64, - found: u64, - }, + ChunkOffsetMismatch { tag: u32, expected: u64, found: u64 }, /// Padding between chunks contains a non-zero byte. - NonZeroPadding - { - offset: u64, - value: u8, - }, + NonZeroPadding { offset: u64, value: u8 }, /// A chunk extends past the end of the file. - ChunkOutOfBounds - { - tag: u32, - offset: u64, - size: u64, - }, + ChunkOutOfBounds { tag: u32, offset: u64, size: u64 }, /// A chunk declares a size smaller than the 12-byte frame. - ChunkSizeTooSmall - { - tag: u32, - size: u64, - }, + ChunkSizeTooSmall { tag: u32, size: u64 }, /// A chunk's declared size does not match the bytes its body consumed. - ChunkSizeMismatch - { + 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, - }, + 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, - }, + ChunkTagMismatch { entry: u32, frame: u32 }, /// The same chunk tag appears more than once. - DuplicateChunk - { - tag: u32, - }, + DuplicateChunk { tag: u32 }, /// The file contains an undefined tag. - UnexpectedTag - { - tag: u32, - }, + UnexpectedTag { tag: u32 }, /// The mandatory attributes chunk is missing. MissingAttributesChunk, /// A tree level has no chunk. - MissingLevelChunk - { - level: u32, - }, + MissingLevelChunk { level: u32 }, /// A tree level chunk is beyond `tree_depth`. - LevelOutOfRange - { - level: u32, - tree_depth: u32, - }, + LevelOutOfRange { level: u32, tree_depth: u32 }, /// A level declares a different number of nodes than its parents imply. - NodeCountMismatch - { + NodeCountMismatch { level: u32, declared: u32, expected: u64, }, /// The unused bits of a level's subdivision flags are not zero. - TrailingFlagBits - { - level: u32, - }, + TrailingFlagBits { level: u32 }, /// The deepest level contains a subdivided node. - SubdividedAtDeepestLevel - { - level: u32, - }, + SubdividedAtDeepestLevel { level: u32 }, /// The tree contains nodes that cannot be reached from the root, or vice versa. - UnreachableNodes - { - reachable: usize, - stored: usize, - }, + UnreachableNodes { reachable: usize, stored: usize }, /// The in-memory tree cannot be represented by the format. - InconsistentTree - { - reason: &'static str, - }, + InconsistentTree { reason: &'static str }, /// An arithmetic operation overflowed while sizing the file. - Overflow - { - what: &'static str, - }, + Overflow { what: &'static str }, /// A chunk's CRC does not match its contents. - CrcMismatch - { + CrcMismatch { tag: u32, offset: u64, expected: u32, @@ -261,19 +143,12 @@ pub enum TreeFileError }, /// Bytes remain after the last chunk. - TrailingBytes - { - end: u64, - file_len: u64, - }, + TrailingBytes { end: u64, file_len: u64 }, } -impl fmt::Display for TreeFileError -{ - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result - { - match self - { +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 } => { @@ -289,10 +164,16 @@ impl fmt::Display for TreeFileError 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") + 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") + write!( + f, + "header_size {header_size} is smaller than the 12-byte header" + ) } Self::HeaderOutOfBounds { header_size, @@ -303,7 +184,10 @@ impl fmt::Display for TreeFileError ), 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}") + write!( + f, + "file arity {file} does not match requested arity {requested}" + ) } Self::DepthTooLarge { depth, max } => { write!(f, "tree_depth {depth} exceeds the maximum {max}") @@ -324,13 +208,19 @@ impl fmt::Display for TreeFileError 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:?}") + 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") + 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") @@ -378,10 +268,9 @@ impl fmt::Display for TreeFileError 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::LevelOutOfRange { level, tree_depth } => { + write!(f, "level chunk {level} is beyond tree_depth {tree_depth}") + } Self::NodeCountMismatch { level, declared, @@ -394,7 +283,10 @@ impl fmt::Display for TreeFileError 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") + write!( + f, + "level {level} is the deepest level but has subdivided nodes" + ) } Self::UnreachableNodes { reachable, stored } => write!( f, @@ -419,12 +311,9 @@ impl fmt::Display for TreeFileError } } -impl std::error::Error for TreeFileError -{ - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> - { - match self - { +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, @@ -432,18 +321,14 @@ impl std::error::Error for TreeFileError } } -impl From for TreeFileError -{ - fn from(value: io::Error) -> Self - { +impl From for TreeFileError { + fn from(value: io::Error) -> Self { Self::Io(value) } } -impl From for TreeFileError -{ - fn from(value: binrw::Error) -> Self - { +impl From for TreeFileError { + fn from(value: binrw::Error) -> Self { Self::Binrw(value) } } diff --git a/crates/vxls-production/src/io/format.rs b/crates/vxls-production/src/io/format.rs index 9b887bb..aeb5fa7 100644 --- a/crates/vxls-production/src/io/format.rs +++ b/crates/vxls-production/src/io/format.rs @@ -5,9 +5,15 @@ //! are structure-of-arrays with counts taken from the stream and from the //! attribute layout. -use std::io::{Read, Seek, SeekFrom, Write}; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::io::Write; -use binrw::{BinRead, BinResult, BinWrite, Endian}; +use binrw::BinRead; +use binrw::BinResult; +use binrw::BinWrite; +use binrw::Endian; /// File magic. pub const MAGIC: [u8; 4] = *b"VXLS"; @@ -40,34 +46,27 @@ pub const CURRENT_MAJOR: u32 = 1; 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 -{ +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 -{ - if tag & TAG_LEVEL_FLAG != 0 - { +pub const fn level_of(tag: u32) -> Option { + if tag & TAG_LEVEL_FLAG != 0 { Some(tag & !TAG_LEVEL_FLAG) - } - else - { + } else { None } } /// Number of `u32` words needed for `node_count` subdivision flags. -pub const fn mask_words(node_count: u32) -> usize -{ +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 struct Preamble { pub magic: [u8; 4], pub file_type: [u8; 4], pub major_version: u32, @@ -78,8 +77,7 @@ pub struct Preamble /// Fixed header following the preamble. #[derive(BinRead, BinWrite, Clone, Copy, Debug, PartialEq, Eq)] #[brw(little)] -pub struct Header -{ +pub struct Header { pub header_size: u32, pub tree_arity: u32, pub tree_depth: u32, @@ -88,8 +86,7 @@ pub struct Header /// The fixed part of a chunk frame. #[derive(BinRead, BinWrite, Clone, Copy, Debug, PartialEq, Eq)] #[brw(little)] -pub struct ChunkFrame -{ +pub struct ChunkFrame { pub chunk_type_tag: u32, pub chunk_size: u64, } @@ -97,8 +94,7 @@ pub struct ChunkFrame /// One entry of the offset table. #[derive(BinRead, BinWrite, Clone, Copy, Debug, PartialEq, Eq)] #[brw(little)] -pub struct OffsetEntry -{ +pub struct OffsetEntry { pub chunk_type_tag: u32, pub reserved: u32, pub file_offset: u64, @@ -107,8 +103,7 @@ pub struct OffsetEntry /// One attribute as recorded in the attributes chunk. #[derive(Clone, Debug, PartialEq, Eq)] -pub struct FileAttribute -{ +pub struct FileAttribute { /// Human-readable name. The format does not interpret it. pub label: String, @@ -118,28 +113,24 @@ pub struct FileAttribute /// The attributes chunk body. #[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct AttributesBody -{ +pub struct AttributesBody { pub attributes: Vec, } -impl BinRead for AttributesBody -{ +impl BinRead for AttributesBody { type Args<'a> = (); fn read_options( reader: &mut R, endian: Endian, _args: Self::Args<'_>, - ) -> BinResult - { + ) -> BinResult { 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 - { + if count as u64 > remaining / 8 { return Err(binrw::Error::AssertFail { pos: start, message: format!( @@ -150,14 +141,12 @@ impl BinRead for AttributesBody let mut attributes = Vec::with_capacity(count as usize); - for index in 0..count - { + 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)? - { + if label_size as u64 > remaining_bytes(reader)? { return Err(binrw::Error::AssertFail { pos: position, message: format!( @@ -181,8 +170,7 @@ impl BinRead for AttributesBody } } -impl BinWrite for AttributesBody -{ +impl BinWrite for AttributesBody { type Args<'a> = (); fn write_options( @@ -190,24 +178,19 @@ impl BinWrite for AttributesBody 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(), - } + ) -> 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 { + 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, ())?; @@ -220,8 +203,7 @@ impl BinWrite for AttributesBody /// One tree level, stored as a structure of arrays. #[derive(Clone, Debug, PartialEq, Eq)] -pub struct LevelBody -{ +pub struct LevelBody { /// Number of nodes at this level. pub node_count: u32, @@ -233,30 +215,26 @@ pub struct LevelBody } /// Arguments of [`LevelBody::read_options`]. -pub struct LevelArgs<'a> -{ +pub struct LevelArgs<'a> { /// Word count of every attribute, in binding order. pub word_counts: &'a [u32], } -impl BinRead for LevelBody -{ +impl BinRead for LevelBody { type Args<'a> = LevelArgs<'a>; fn read_options( reader: &mut R, endian: Endian, args: Self::Args<'_>, - ) -> BinResult - { + ) -> BinResult { 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)? - { + if mask_bytes > remaining_bytes(reader)? { return Err(binrw::Error::AssertFail { pos: start, message: format!( @@ -267,15 +245,13 @@ impl BinRead for LevelBody let mut subdivided = Vec::with_capacity(words); - for _ in 0..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() - { + 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 { @@ -285,8 +261,7 @@ impl BinRead for LevelBody ), })?; - if count.saturating_mul(4) > remaining_bytes(reader)? - { + if count.saturating_mul(4) > remaining_bytes(reader)? { return Err(binrw::Error::AssertFail { pos: start, message: format!( @@ -298,8 +273,7 @@ impl BinRead for LevelBody let count = count as usize; let mut attribute = Vec::with_capacity(count); - for _ in 0..count - { + for _ in 0..count { attribute.push(u32::read_options(reader, endian, ())?); } @@ -314,8 +288,7 @@ impl BinRead for LevelBody } } -impl BinWrite for LevelBody -{ +impl BinWrite for LevelBody { type Args<'a> = (); fn write_options( @@ -323,19 +296,15 @@ impl BinWrite for LevelBody writer: &mut W, endian: Endian, _args: Self::Args<'_>, - ) -> BinResult<()> - { + ) -> BinResult<()> { self.node_count.write_options(writer, endian, ())?; - for word in &self.subdivided - { + for word in &self.subdivided { word.write_options(writer, endian, ())?; } - for attribute in &self.attributes - { - for word in attribute - { + for attribute in &self.attributes { + for word in attribute { word.write_options(writer, endian, ())?; } } @@ -344,8 +313,7 @@ impl BinWrite for LevelBody } } -fn remaining_bytes(reader: &mut R) -> BinResult -{ +fn remaining_bytes(reader: &mut R) -> BinResult { let position = reader.stream_position()?; let end = reader.seek(SeekFrom::End(0))?; reader.seek(SeekFrom::Start(position))?; diff --git a/crates/vxls-production/src/io/read.rs b/crates/vxls-production/src/io/read.rs index 16b7ba3..2d37e64 100644 --- a/crates/vxls-production/src/io/read.rs +++ b/crates/vxls-production/src/io/read.rs @@ -1,36 +1,56 @@ //! Reading and validating VXLS sparse-tree files. -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; +use std::collections::HashSet; use std::fs::File; -use std::io::{Cursor, Read, Seek, SeekFrom}; +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, Endian}; +use binrw::BinRead; +use binrw::Endian; -use super::chunk::{CHUNK_ALIGNMENT, Chunk, align_up, read_chunk, read_padding}; +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, CURRENT_MAJOR, CHUNK_FRAME_SIZE, FILE_TYPE_SPARSE_TREE, FileAttribute, - HEADER_SIZE, Header, LevelArgs, LevelBody, MAGIC, OFFSET_ENTRY_SIZE, OffsetEntry, PREAMBLE_SIZE, - Preamble, TAG_ATTRIBUTES, level_of, mask_words, -}; -use crate::{Attribute, AttributesLayout}; -use crate::sparse_tree::{NTree, NTreeNode}; +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 struct FileLayout { pub attributes: Vec, } -impl FileLayout -{ +impl FileLayout { /// Total number of 32-bit words per voxel. - pub fn total_word_count(&self) -> u64 - { + pub fn total_word_count(&self) -> u64 { self.attributes .iter() .map(|attribute| attribute.word_count as u64) @@ -38,8 +58,7 @@ impl FileLayout } /// Index of the first attribute with this label. - pub fn by_label(&self, label: &str) -> Option - { + pub fn by_label(&self, label: &str) -> Option { self.attributes .iter() .position(|attribute| attribute.label == label) @@ -47,8 +66,7 @@ impl FileLayout } /// A tree and its attribute layout, as read from a file. -pub struct TreeFile -{ +pub struct TreeFile { /// The parsed tree. pub tree: NTree, @@ -62,10 +80,8 @@ pub struct TreeFile pub minor_version: u32, } -impl std::fmt::Debug for TreeFile -{ - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result - { +impl std::fmt::Debug for TreeFile { + 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()) @@ -89,16 +105,14 @@ where T: Attribute, [(); N * N * N]:, { - if N < 2 - { + 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 - { + if file_len < PREAMBLE_SIZE { return Err(TreeFileError::FileTooSmall { len: file_len, needed: PREAMBLE_SIZE, @@ -107,22 +121,19 @@ where let preamble = Preamble::read_options(reader, Endian::Little, ())?; - if preamble.magic != MAGIC - { + if preamble.magic != MAGIC { return Err(TreeFileError::BadMagic { found: preamble.magic, }); } - if preamble.file_type != FILE_TYPE_SPARSE_TREE - { + if preamble.file_type != FILE_TYPE_SPARSE_TREE { return Err(TreeFileError::BadFileType { found: preamble.file_type, }); } - if preamble.major_version != CURRENT_MAJOR - { + if preamble.major_version != CURRENT_MAJOR { return Err(TreeFileError::UnsupportedVersion { major: preamble.major_version, minor: preamble.minor_version, @@ -132,8 +143,7 @@ where // A newer minor is accepted: unknown chunks are skipped while walking the // offset table. - if preamble.total_file_size != file_len - { + if preamble.total_file_size != file_len { return Err(TreeFileError::FileSizeMismatch { declared: preamble.total_file_size, actual: file_len, @@ -142,8 +152,7 @@ where let minimum_header_end = PREAMBLE_SIZE + HEADER_SIZE as u64; - if file_len < minimum_header_end - { + if file_len < minimum_header_end { return Err(TreeFileError::FileTooSmall { len: file_len, needed: minimum_header_end, @@ -152,8 +161,7 @@ where let header = Header::read_options(reader, Endian::Little, ())?; - if header.header_size < HEADER_SIZE - { + if header.header_size < HEADER_SIZE { return Err(TreeFileError::HeaderTooSmall { header_size: header.header_size, }); @@ -161,8 +169,7 @@ where let header_end = PREAMBLE_SIZE + header.header_size as u64; - if header_end > file_len - { + if header_end > file_len { return Err(TreeFileError::HeaderOutOfBounds { header_size: header.header_size, file_len, @@ -171,23 +178,20 @@ where reader.seek(SeekFrom::Start(header_end))?; - if header.tree_arity < 2 - { + if header.tree_arity < 2 { return Err(TreeFileError::ArityTooSmall { arity: header.tree_arity, }); } - if header.tree_arity != N as u32 - { + if header.tree_arity != N as u32 { return Err(TreeFileError::ArityMismatch { file: header.tree_arity, requested: N as u32, }); } - if header.tree_depth > TreeLocator::::max_depth() - { + if header.tree_depth > TreeLocator::::max_depth() { return Err(TreeFileError::DepthTooLarge { depth: header.tree_depth, max: TreeLocator::::max_depth(), @@ -196,15 +200,13 @@ where let table_size = u32::read_options(reader, Endian::Little, ())?; - if !(table_size as u64).is_multiple_of(OFFSET_ENTRY_SIZE) - { + 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 - { + if table_end > file_len { return Err(TreeFileError::OffsetTableOutOfBounds { end: table_end, file_len, @@ -216,26 +218,22 @@ where let mut tags = HashSet::with_capacity(entry_count); let mut previous_offset = None; - for _ in 0..entry_count - { + for _ in 0..entry_count { let entry = OffsetEntry::read_options(reader, Endian::Little, ())?; - if !tags.insert(entry.chunk_type_tag) - { + if !tags.insert(entry.chunk_type_tag) { return Err(TreeFileError::DuplicateChunk { tag: entry.chunk_type_tag, }); } - if entry.file_offset % CHUNK_ALIGNMENT != 0 - { + if entry.file_offset % CHUNK_ALIGNMENT != 0 { return Err(TreeFileError::MisalignedOffset { offset: entry.file_offset, }); } - if entry.chunk_size < CHUNK_FRAME_SIZE - { + if entry.chunk_size < CHUNK_FRAME_SIZE { return Err(TreeFileError::ChunkSizeTooSmall { tag: entry.chunk_type_tag, size: entry.chunk_size, @@ -248,8 +246,7 @@ where .and_then(|value| value.checked_add(4)) .ok_or(TreeFileError::Overflow { what: "chunk end" })?; - if end > file_len - { + if end > file_len { return Err(TreeFileError::ChunkOutOfBounds { tag: entry.chunk_type_tag, offset: entry.file_offset, @@ -267,20 +264,17 @@ where entries.push(entry); } - if entry_count == 0 - { + 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 - { + for entry in &entries { let expected = align_up(previous_end, CHUNK_ALIGNMENT); - if entry.file_offset != expected - { + if entry.file_offset != expected { return Err(TreeFileError::ChunkOffsetMismatch { tag: entry.chunk_type_tag, expected, @@ -294,8 +288,7 @@ where previous_end = entry.file_offset + entry.chunk_size + 4; } - if previous_end != file_len - { + if previous_end != file_len { return Err(TreeFileError::TrailingBytes { end: previous_end, file_len, @@ -305,16 +298,11 @@ where let mut attributes_entry = None; let mut level_entries = HashMap::new(); - for entry in &entries - { - if entry.chunk_type_tag == TAG_ATTRIBUTES - { + 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 - { + } 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, @@ -322,9 +310,7 @@ where } level_entries.insert(level, *entry); - } - else if entry.chunk_type_tag == 0 - { + } else if entry.chunk_type_tag == 0 { return Err(TreeFileError::UnexpectedTag { tag: entry.chunk_type_tag, }); @@ -336,15 +322,12 @@ where let level_count = level_entries.len(); - if level_count == 0 - { + if level_count == 0 { return Err(TreeFileError::MissingLevelChunk { level: 0 }); } - for level in 0..level_count as u32 - { - if !level_entries.contains_key(&level) - { + for level in 0..level_count as u32 { + if !level_entries.contains_key(&level) { return Err(TreeFileError::MissingLevelChunk { level }); } } @@ -353,8 +336,7 @@ where let layout = read_attributes(reader, &attributes_entry, file_len)?; - if let Some(expected) = expected - { + if let Some(expected) = expected { let expected_words: Vec = expected .attributes .iter() @@ -366,8 +348,7 @@ where .map(|attribute| attribute.word_count) .collect(); - if expected_words != found_words - { + if expected_words != found_words { return Err(TreeFileError::LayoutMismatch { expected: expected_words, found: found_words, @@ -375,10 +356,8 @@ where } } - for (index, attribute) in layout.attributes.iter().enumerate() - { - if attribute.word_count == 0 - { + for (index, attribute) in layout.attributes.iter().enumerate() { + if attribute.word_count == 0 { return Err(TreeFileError::InvalidWordCount { index, word_count: attribute.word_count, @@ -386,16 +365,16 @@ where } } - if !size_of::().is_multiple_of(4) - { - return Err(TreeFileError::PayloadNotWordAligned { size: size_of::() }); + if !size_of::().is_multiple_of(4) { + return Err(TreeFileError::PayloadNotWordAligned { + size: size_of::(), + }); } let layout_words = layout.total_word_count(); let payload_words = (size_of::() / 4) as u64; - if layout_words != payload_words - { + if layout_words != payload_words { return Err(TreeFileError::LayoutSizeMismatch { layout_words, payload_words, @@ -443,12 +422,10 @@ fn read_attributes( reader: &mut R, entry: &OffsetEntry, file_len: u64, -) -> Result -{ +) -> Result { let chunk = read_chunk_at(reader, entry, file_len)?; - if chunk.tag != TAG_ATTRIBUTES - { + if chunk.tag != TAG_ATTRIBUTES { return Err(TreeFileError::ChunkTagMismatch { entry: TAG_ATTRIBUTES, frame: chunk.tag, @@ -458,8 +435,7 @@ fn read_attributes( let mut cursor = Cursor::new(&chunk.body); let body = AttributesBody::read_options(&mut cursor, Endian::Little, ())?; - if cursor.position() != chunk.body.len() as u64 - { + if cursor.position() != chunk.body.len() as u64 { return Err(TreeFileError::ChunkSizeMismatch { tag: chunk.tag, declared: chunk.body.len() as u64, @@ -487,15 +463,13 @@ where let mut parents = vec![TreeLocator::::root()]; let mut scratch = vec![0u8; size_of::()]; - for level in 0..=deepest - { + 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) - { + if level_of(chunk.tag) != Some(level) { return Err(TreeFileError::ChunkTagMismatch { entry: entry.chunk_type_tag, frame: chunk.tag, @@ -503,14 +477,9 @@ where } let mut cursor = Cursor::new(&chunk.body); - let body = LevelBody::read_options( - &mut cursor, - Endian::Little, - LevelArgs { word_counts }, - )?; + let body = LevelBody::read_options(&mut cursor, Endian::Little, LevelArgs { word_counts })?; - if cursor.position() != chunk.body.len() as u64 - { + if cursor.position() != chunk.body.len() as u64 { return Err(TreeFileError::ChunkSizeMismatch { tag: chunk.tag, declared: chunk.body.len() as u64, @@ -520,8 +489,7 @@ where let node_count = body.node_count as usize; - if node_count as u64 != parents.len() as u64 - { + if node_count as u64 != parents.len() as u64 { return Err(TreeFileError::NodeCountMismatch { level, declared: body.node_count, @@ -529,43 +497,36 @@ where }); } - if body.subdivided.len() != mask_words(body.node_count) - { + 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 - { + if body.node_count % 32 != 0 { let used = body.node_count % 32; let last = *body.subdivided.last().unwrap_or(&0); - if last >> used != 0 - { + if last >> used != 0 { return Err(TreeFileError::TrailingFlagBits { level }); } } let mut next = Vec::new(); - for (index, parent) in parents.iter().enumerate() - { + 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() - { + 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()); + for word in words { + scratch[byte_offset..byte_offset + 4].copy_from_slice(&word.to_ne_bytes()); byte_offset += 4; } } @@ -580,22 +541,19 @@ where }, ); - if subdivided - { + if subdivided { next.extend(parent.children()); } } - if level == deepest && !next.is_empty() - { + if level == deepest && !next.is_empty() { return Err(TreeFileError::SubdividedAtDeepestLevel { level }); } parents = next; } - if !parents.is_empty() - { + if !parents.is_empty() { return Err(TreeFileError::NodeCountMismatch { level: deepest, declared: 0, @@ -610,21 +568,18 @@ fn read_chunk_at( reader: &mut R, entry: &OffsetEntry, file_len: u64, -) -> Result -{ +) -> Result { reader.seek(SeekFrom::Start(entry.file_offset))?; let chunk = read_chunk(reader, file_len)?; - if chunk.tag != entry.chunk_type_tag - { + 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 - { + if chunk.size != entry.chunk_size { return Err(TreeFileError::EntrySizeMismatch { tag: chunk.tag, entry: entry.chunk_size, diff --git a/crates/vxls-production/src/io/write.rs b/crates/vxls-production/src/io/write.rs index dc5168d..cc6b373 100644 --- a/crates/vxls-production/src/io/write.rs +++ b/crates/vxls-production/src/io/write.rs @@ -1,39 +1,52 @@ //! Writing VXLS sparse-tree files. use std::fs::File; -use std::io::{Cursor, Write}; +use std::io::Cursor; +use std::io::Write; use std::mem::size_of; use std::path::Path; -use binrw::{BinWrite, Endian}; +use binrw::BinWrite; +use binrw::Endian; -use super::chunk::{CHUNK_ALIGNMENT, align_up, write_chunk, write_padding_to_alignment}; +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, CURRENT_MAJOR, CURRENT_MINOR, FILE_TYPE_SPARSE_TREE, FileAttribute, - HEADER_SIZE, Header, LevelBody, MAGIC, OFFSET_ENTRY_SIZE, OffsetEntry, PREAMBLE_SIZE, Preamble, - TAG_ATTRIBUTES, level_tag, mask_words, -}; -use crate::{Attribute, AttributesLayout}; +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 -{ +struct LevelPlan { locators: Vec>, subdivided: Vec, } -impl LevelPlan -{ - fn node_count(&self) -> u64 - { +impl LevelPlan { + fn node_count(&self) -> u64 { self.locators.len() as u64 } - fn body_len(&self, total_words: u64) -> 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; @@ -41,8 +54,7 @@ impl LevelPlan } } -struct ChunkPlan -{ +struct ChunkPlan { tag: u32, offset: u64, chunk_size: u64, @@ -62,8 +74,7 @@ where T: Attribute, [(); N * N * N]:, { - if N < 2 - { + if N < 2 { return Err(TreeFileError::ArityTooSmall { arity: N as u32 }); } @@ -72,29 +83,26 @@ where .and_then(|value| value.checked_mul(N as u64)) .ok_or(TreeFileError::Overflow { what: "N^3" })?; - if children_per_node > u32::MAX as u64 - { + 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::().is_multiple_of(4) - { - return Err(TreeFileError::PayloadNotWordAligned { size: size_of::() }); + if !size_of::().is_multiple_of(4) { + return Err(TreeFileError::PayloadNotWordAligned { + size: size_of::(), + }); } - if layout.attributes.is_empty() - { + 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 - { + for (index, attribute) in layout.attributes.iter().enumerate() { + if attribute.word_count == 0 { return Err(TreeFileError::InvalidWordCount { index, word_count: attribute.word_count, @@ -110,8 +118,7 @@ where let payload_words = (size_of::() / 4) as u64; - if layout_words != payload_words - { + if layout_words != payload_words { return Err(TreeFileError::LayoutSizeMismatch { layout_words, payload_words, @@ -123,8 +130,7 @@ where max: TreeLocator::::max_depth(), })?; - if tree_depth > TreeLocator::::max_depth() - { + if tree_depth > TreeLocator::::max_depth() { return Err(TreeFileError::DepthTooLarge { depth: tree_depth, max: TreeLocator::::max_depth(), @@ -142,8 +148,7 @@ where .try_into() .unwrap_or(usize::MAX); - if reachable != tree.node_count() - { + if reachable != tree.node_count() { return Err(TreeFileError::UnreachableNodes { reachable, stored: tree.node_count(), @@ -163,8 +168,7 @@ where chunk_size: chunk_size_for(attributes_body_len)?, }); - for (level, plan) in levels.iter().enumerate() - { + for (level, plan) in levels.iter().enumerate() { plans.push(ChunkPlan { tag: level_tag(level as u32), offset: 0, @@ -173,26 +177,24 @@ where } 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_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 - { + 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 last = plans.last().ok_or(TreeFileError::InconsistentTree { + reason: "no chunks to write", + })?; let total_file_size = last.offset + last.chunk_size + 4; Preamble { @@ -217,8 +219,7 @@ where })? .write_options(writer, Endian::Little, ())?; - for plan in &plans - { + for plan in &plans { OffsetEntry { chunk_type_tag: plan.tag, reserved: 0, @@ -228,14 +229,12 @@ where .write_options(writer, Endian::Little, ())?; } - for (index, plan) in plans.iter().enumerate() - { + for (index, plan) in plans.iter().enumerate() { write_padding_to_alignment(writer)?; let position = writer.stream_position()?; - if position != plan.offset - { + if position != plan.offset { return Err(TreeFileError::ChunkOffsetMismatch { tag: plan.tag, expected: plan.offset, @@ -243,12 +242,9 @@ where }); } - let body = if index == 0 - { + let body = if index == 0 { build_attributes_body(layout)? - } - else - { + } else { build_level_body(tree, &levels[index - 1], layout, &word_offsets)? }; @@ -257,8 +253,7 @@ where let position = writer.stream_position()?; - if position != total_file_size - { + if position != total_file_size { return Err(TreeFileError::FileSizeMismatch { declared: total_file_size, actual: position, @@ -294,22 +289,21 @@ where let mut current = vec![TreeLocator::::root()]; let mut level = 0u32; - loop - { + 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", - })?; + 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 - { + if subdivided_count > 0 && level == capacity { return Err(TreeFileError::InconsistentTree { reason: "a node at the maximum depth is subdivided", }); @@ -317,26 +311,24 @@ where let mut next = Vec::new(); - if subdivided_count > 0 - { + 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 = + (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 - { + for (locator, is_subdivided) in current.iter().zip(&subdivided) { + if *is_subdivided { next.extend(locator.children()); } } @@ -347,8 +339,7 @@ where subdivided, }; - if u32::try_from(plan.locators.len()).is_err() - { + if u32::try_from(plan.locators.len()).is_err() { return Err(TreeFileError::Overflow { what: "level node count does not fit in a u32", }); @@ -356,8 +347,7 @@ where levels.push(plan); - if next.is_empty() - { + if next.is_empty() { break; } @@ -368,13 +358,11 @@ where Ok(levels) } -fn attribute_word_offsets(layout: AttributesLayout) -> Vec -{ +fn attribute_word_offsets(layout: AttributesLayout) -> Vec { let mut offsets = Vec::with_capacity(layout.attributes.len()); let mut offset = 0usize; - for attribute in layout.attributes - { + for attribute in layout.attributes { offsets.push(offset); offset += attribute.word_count as usize; } @@ -382,12 +370,10 @@ fn attribute_word_offsets(layout: AttributesLayout) -> Vec offsets } -fn attributes_body_len(layout: AttributesLayout) -> Result -{ +fn attributes_body_len(layout: AttributesLayout) -> Result { let mut length = 4u64; - for attribute in layout.attributes - { + for attribute in layout.attributes { length = length .checked_add(8) .and_then(|value| value.checked_add(attribute.label.len() as u64)) @@ -399,8 +385,7 @@ fn attributes_body_len(layout: AttributesLayout) -> Result Ok(length) } -fn build_attributes_body(layout: AttributesLayout) -> Result, TreeFileError> -{ +fn build_attributes_body(layout: AttributesLayout) -> Result, TreeFileError> { let body = AttributesBody { attributes: layout .attributes @@ -426,18 +411,14 @@ fn build_level_body( 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 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 - { + for (index, subdivided) in plan.subdivided.iter().enumerate() { + if *subdivided { flags[index / 32] |= 1 << (index % 32); } } @@ -445,30 +426,26 @@ where let mut attributes: Vec> = layout .attributes .iter() - .map(|attribute| { - Vec::with_capacity(node_count as usize * attribute.word_count as usize) - }) + .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", - })?; + 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() - { + 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"), - ); + 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); } } @@ -485,46 +462,45 @@ where Ok(cursor.into_inner()) } -fn chunk_size_for(body_len: u64) -> Result -{ +fn chunk_size_for(body_len: u64) -> Result { super::format::CHUNK_FRAME_SIZE .checked_add(body_len) .ok_or(TreeFileError::Overflow { what: "chunk size" }) } #[cfg(test)] -mod tests -{ +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, Header, LevelArgs, LevelBody, OffsetEntry, PREAMBLE_SIZE, level_of, - }; - use binrw::{BinRead, BinWrite}; + 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 - { + fn write(tree: &NTree<2, u32>) -> Vec { let mut cursor = Cursor::new(Vec::new()); write_tree(&mut cursor, tree, U32_LAYOUT).unwrap(); cursor.into_inner() } - fn entries(bytes: &[u8]) -> Vec - { + fn entries(bytes: &[u8]) -> Vec { 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, - )) + .seek(SeekFrom::Start(PREAMBLE_SIZE + header.header_size as u64)) .unwrap(); let table_size = u32::read_options(&mut cursor, Endian::Little, ()).unwrap(); @@ -533,8 +509,7 @@ mod tests .collect() } - fn bodies(bytes: &[u8]) -> Vec<(u32, Vec)> - { + fn bodies(bytes: &[u8]) -> Vec<(u32, Vec)> { let mut cursor = Cursor::new(bytes); entries(bytes) .into_iter() @@ -548,8 +523,7 @@ mod tests } #[test] - fn child_order_is_x_fastest() - { + fn child_order_is_x_fastest() { let mut tree = NTree::<2, u32>::constant(0, 1); tree.set(1, 0, 0, 9); @@ -563,9 +537,7 @@ mod tests let root = LevelBody::read_options( &mut Cursor::new(&chunks[1].1), Endian::Little, - LevelArgs { - word_counts: &[1], - }, + LevelArgs { word_counts: &[1] }, ) .unwrap(); assert_eq!(root.node_count, 1); @@ -575,9 +547,7 @@ mod tests let level = LevelBody::read_options( &mut Cursor::new(&chunks[2].1), Endian::Little, - LevelArgs { - word_counts: &[1], - }, + LevelArgs { word_counts: &[1] }, ) .unwrap(); assert_eq!(level.node_count, 8); @@ -586,8 +556,7 @@ mod tests } #[test] - fn chunks_are_aligned_and_packed() - { + fn chunks_are_aligned_and_packed() { let tree = NTree::<2, u32>::constant(3, 2); let bytes = write(&tree); let entries = entries(&bytes); @@ -597,8 +566,7 @@ mod tests let mut previous_end = table_end; - for entry in &entries - { + 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); @@ -609,8 +577,7 @@ mod tests } #[test] - fn attributes_chunk_roundtrip() - { + fn attributes_chunk_roundtrip() { let body = AttributesBody { attributes: vec![ FileAttribute { @@ -634,8 +601,7 @@ mod tests } #[test] - fn shallow_tree_keeps_capacity_in_the_header() - { + 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( @@ -646,8 +612,7 @@ mod tests }, ); - for child in TreeLocator::<2>::root().children() - { + for child in TreeLocator::<2>::root().children() { map.insert( child, crate::sparse_tree::NTreeNode { @@ -668,8 +633,7 @@ mod tests 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(); + 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); diff --git a/crates/vxls-production/src/main.rs b/crates/vxls-production/src/main.rs index 3bfcd33..e866edb 100644 --- a/crates/vxls-production/src/main.rs +++ b/crates/vxls-production/src/main.rs @@ -9,8 +9,7 @@ use vxls_production::sparse_tree::Color; use vxls_production::sparse_tree::NTree; use vxls_production::sparse_tree::load_ply; -fn main() -{ +fn main() { let dragon: NTree<4, Color> = load_ply("../../dragon.txt"); let mut file = File::create("../../dragon.vxls").unwrap(); diff --git a/crates/vxls-production/src/producer.rs b/crates/vxls-production/src/producer.rs index aa994f8..caf90bf 100644 --- a/crates/vxls-production/src/producer.rs +++ b/crates/vxls-production/src/producer.rs @@ -31,8 +31,7 @@ where [(); N * N * N]:, { /// Creates a produced node - pub fn new(insertion: InsertionInformation, attributes: [A; N * N * N]) -> Self - { + pub fn new(insertion: InsertionInformation, attributes: [A; N * N * N]) -> Self { Self { insertion, attributes, @@ -40,14 +39,12 @@ where } /// The produced voxels - pub fn attributes(&self) -> &[A] - { + pub fn attributes(&self) -> &[A] { &self.attributes } /// The produced voxels, mutably - pub fn attributes_mut(&mut self) -> &mut [A] - { + pub fn attributes_mut(&mut self) -> &mut [A] { &mut self.attributes } @@ -59,8 +56,7 @@ where &self, queue: &wgpu::Queue, insertion: &CacheInsertionData, - ) -> Result - { + ) -> Result { insertion.write_attributes(queue, &self.attributes) } @@ -73,15 +69,13 @@ where /// # Panics /// /// Panics if `index` is not a valid attribute index. - pub fn write_attribute_words(&self, index: usize, out: &mut Vec) - { + 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 - { + for node in &self.attributes { let bytes = node.get_attr(index); debug_assert_eq!( bytes.len(), @@ -89,8 +83,7 @@ where "attribute size does not match its declared word count", ); - for word in bytes.chunks_exact(size_of::()) - { + for word in bytes.chunks_exact(size_of::()) { out.push(u32::from_ne_bytes( word.try_into().expect("chunks_exact yields 4-byte slices"), )); @@ -127,8 +120,7 @@ where A: Attributes, [(); N * N * N]:, { - pub fn new(f: T) -> Self - { + pub fn new(f: T) -> Self { Self { f } } } @@ -139,8 +131,7 @@ where A: Attributes, [(); N * N * N]:, { - fn produce(&self, anchor: StructureAnchor, locator: StructureLocator) -> ProducedNode - { + 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 index e69de29..8b13789 100644 --- a/crates/vxls-production/src/production_router.rs +++ b/crates/vxls-production/src/production_router.rs @@ -0,0 +1 @@ + diff --git a/crates/vxls-production/src/request_queue.rs b/crates/vxls-production/src/request_queue.rs index 07bc026..ccdc507 100644 --- a/crates/vxls-production/src/request_queue.rs +++ b/crates/vxls-production/src/request_queue.rs @@ -20,14 +20,12 @@ pub type FrameId = u64; /// both carry `(node_id = 0, children_index = 0)` on the wire, so the key must /// distinguish them explicitly. #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)] -pub enum RequestTarget -{ +pub enum RequestTarget { /// Request for the root node of a structure (structure-table request). Root, /// Request for a child of a resident node. - Child - { + Child { parent: StructureLocator, children_index: u32, }, @@ -39,17 +37,14 @@ pub enum RequestTarget /// not identity. Excluding it lets an in-flight root job survive a slot move /// while the same anchor stays in view. #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)] -pub struct RequestKey -{ +pub struct RequestKey { pub producer_id: ProducerId, pub anchor: StructureAnchor, pub target: RequestTarget, } -impl RequestKey -{ - pub fn root(producer_id: ProducerId, anchor: StructureAnchor) -> Self - { +impl RequestKey { + pub fn root(producer_id: ProducerId, anchor: StructureAnchor) -> Self { Self { producer_id, anchor, @@ -62,8 +57,7 @@ impl RequestKey anchor: StructureAnchor, parent: StructureLocator, children_index: u32, - ) -> Self - { + ) -> Self { Self { producer_id, anchor, @@ -74,8 +68,7 @@ impl RequestKey } } - pub fn is_root(&self) -> bool - { + pub fn is_root(&self) -> bool { matches!(self.target, RequestTarget::Root) } } @@ -87,20 +80,17 @@ impl RequestKey /// 2. demand (higher first) /// 3. depth (shallower first) #[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub struct RequestPriority -{ +pub struct RequestPriority { pub class: u8, pub demand: u32, pub depth: u32, } -impl RequestPriority -{ +impl RequestPriority { pub const ROOT_CLASS: u8 = 1; pub const CHILD_CLASS: u8 = 0; - pub fn new(class: u8, demand: u32, depth: u32) -> Self - { + pub fn new(class: u8, demand: u32, depth: u32) -> Self { Self { class, demand, @@ -108,21 +98,17 @@ impl RequestPriority } } - pub fn root(demand: u32) -> Self - { + pub fn root(demand: u32) -> Self { Self::new(Self::ROOT_CLASS, demand, 0) } - pub fn child(demand: u32, depth: u32) -> Self - { + pub fn child(demand: u32, depth: u32) -> Self { Self::new(Self::CHILD_CLASS, demand, depth) } } -impl Ord for RequestPriority -{ - fn cmp(&self, other: &Self) -> Ordering - { +impl Ord for RequestPriority { + fn cmp(&self, other: &Self) -> Ordering { self.class .cmp(&other.class) .then_with(|| self.demand.cmp(&other.demand)) @@ -131,18 +117,15 @@ impl Ord for RequestPriority } } -impl PartialOrd for RequestPriority -{ - fn partial_cmp(&self, other: &Self) -> Option - { +impl PartialOrd for RequestPriority { + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } /// A request as ingested from the host. #[derive(Clone, Copy, Debug)] -pub struct IncomingRequest -{ +pub struct IncomingRequest { pub key: RequestKey, pub priority: RequestPriority, @@ -151,25 +134,20 @@ pub struct IncomingRequest pub meta: RequestMeta, } -impl IncomingRequest -{ +impl IncomingRequest { /// Builds an incoming request from the wire request/meta pair emitted by the /// cache. An external root is identified by its missing parent page, not by /// `node_id == 0` (which also describes child 0 of the root). - pub fn from_wire(request: &RequestInformation, meta: &RequestMeta) -> Self - { + pub fn from_wire(request: &RequestInformation, meta: &RequestMeta) -> Self { let producer_id = request.producer_id; let anchor = request.anchor; - let (key, priority) = if meta.page_index == NO_PARENT_PAGE - { + let (key, priority) = if meta.page_index == NO_PARENT_PAGE { ( RequestKey::root(producer_id, anchor), RequestPriority::root(request.demand), ) - } - else - { + } else { ( RequestKey::child(producer_id, anchor, request.node_id, request.children_index), RequestPriority::child(request.demand, meta.depth), @@ -185,8 +163,7 @@ impl IncomingRequest } #[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub enum JobState -{ +pub enum JobState { Queued, InFlight, Ready, @@ -194,8 +171,7 @@ pub enum JobState /// A job handed to a worker. #[derive(Clone, Copy, Debug)] -pub struct WorkItem -{ +pub struct WorkItem { pub key: RequestKey, pub generation: u64, pub attempt: u32, @@ -204,21 +180,17 @@ pub struct WorkItem /// A completed job waiting to be inserted. #[derive(Debug)] -pub struct ReadyItem -{ +pub struct ReadyItem { pub key: RequestKey, pub meta: RequestMeta, pub payload: T, } -impl ReadyItem -{ +impl ReadyItem { /// Attachment information to carry in the insertion batch so the GPU can /// validate and link the produced page without the request buffer. - pub fn insertion_parent(&self) -> InsertionParent - { - match self.key.target - { + pub fn insertion_parent(&self) -> InsertionParent { + match self.key.target { RequestTarget::Root => InsertionParent::external( self.key.producer_id, self.key.anchor, @@ -227,8 +199,7 @@ impl ReadyItem RequestTarget::Child { parent, children_index, - } => - { + } => { // The key and the meta should agree; prefer the key so the // attachment point can never drift from the identity used for // deduplication. @@ -243,15 +214,13 @@ impl ReadyItem } #[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub enum CompleteOutcome -{ +pub enum CompleteOutcome { Accepted, Discarded, } #[derive(Clone, Copy, Debug)] -pub struct QueueConfig -{ +pub struct QueueConfig { /// Maximum number of undispatched jobs. pub max_queued: usize, @@ -270,10 +239,8 @@ pub struct QueueConfig pub max_attempts: u32, } -impl Default for QueueConfig -{ - fn default() -> Self - { +impl Default for QueueConfig { + fn default() -> Self { Self { max_queued: 4096, max_in_flight: 64, @@ -285,8 +252,7 @@ impl Default for QueueConfig } #[derive(Clone, Copy, Debug, Default)] -pub struct IngestStats -{ +pub struct IngestStats { pub new: usize, pub refreshed: usize, pub evicted: usize, @@ -295,8 +261,7 @@ pub struct IngestStats } #[derive(Clone, Copy, Debug, Default)] -pub struct QueueStats -{ +pub struct QueueStats { pub queued: usize, pub in_flight: usize, pub ready: usize, @@ -308,8 +273,7 @@ pub struct QueueStats pub total_stale_completions: u64, } -struct Job -{ +struct Job { key: RequestKey, state: JobState, priority: RequestPriority, @@ -325,17 +289,14 @@ struct Job /// Entry in the queued/ready ordered sets. Larger means more urgent. #[derive(Clone, Copy, PartialEq, Eq, Debug)] -struct QueueEntry -{ +struct QueueEntry { priority: RequestPriority, first_seen: FrameId, key: RequestKey, } -impl Ord for QueueEntry -{ - fn cmp(&self, other: &Self) -> Ordering - { +impl Ord for QueueEntry { + fn cmp(&self, other: &Self) -> Ordering { self.priority .cmp(&other.priority) // Older jobs win ties, limiting starvation. @@ -344,16 +305,13 @@ impl Ord for QueueEntry } } -impl PartialOrd for QueueEntry -{ - fn partial_cmp(&self, other: &Self) -> Option - { +impl PartialOrd for QueueEntry { + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } -fn entry_of(job: &Job) -> QueueEntry -{ +fn entry_of(job: &Job) -> QueueEntry { QueueEntry { priority: job.priority, first_seen: job.first_seen, @@ -361,8 +319,7 @@ fn entry_of(job: &Job) -> QueueEntry } } -pub struct RequestQueue -{ +pub struct RequestQueue { config: QueueConfig, frame: FrameId, next_generation: u64, @@ -375,10 +332,8 @@ pub struct RequestQueue stats: QueueStats, } -impl RequestQueue -{ - pub fn new(config: QueueConfig) -> Self - { +impl RequestQueue { + pub fn new(config: QueueConfig) -> Self { Self { config, frame: 0, @@ -391,13 +346,11 @@ impl RequestQueue } } - pub fn config(&self) -> &QueueConfig - { + pub fn config(&self) -> &QueueConfig { &self.config } - pub fn frame(&self) -> FrameId - { + pub fn frame(&self) -> FrameId { self.frame } @@ -414,44 +367,34 @@ impl RequestQueue let mut stats = IngestStats::default(); - for request in requests - { - if let Some(job) = self.jobs.get_mut(&request.key) - { + for request in requests { + if let Some(job) = self.jobs.get_mut(&request.key) { // Refresh an existing job. It may be queued, in flight, or // ready; in all cases only the scheduling metadata changes. let old_entry = entry_of(job); - match job.state - { - JobState::Queued => - { + match job.state { + JobState::Queued => { self.queued.remove(&old_entry); } - JobState::Ready => - { + JobState::Ready => { self.ready.remove(&old_entry); } - JobState::InFlight => - {} + JobState::InFlight => {} } job.priority = request.priority; job.meta = request.meta; job.last_seen = frame; - match job.state - { - JobState::Queued => - { + match job.state { + JobState::Queued => { self.queued.insert(entry_of(job)); } - JobState::Ready => - { + JobState::Ready => { self.ready.insert(entry_of(job)); } - JobState::InFlight => - {} + JobState::InFlight => {} } stats.refreshed += 1; @@ -462,23 +405,18 @@ impl RequestQueue // priority queued job, but only when the newcomer is strictly more // urgent. Otherwise the newcomer is dropped; the cache will emit it // again next frame if it is still needed. - if self.queued.len() >= self.config.max_queued - { + if self.queued.len() >= self.config.max_queued { let victim = self.queued.first().copied(); let should_evict = victim .map(|victim| victim.priority < request.priority) .unwrap_or(false); - if should_evict - { - if let Some(victim) = victim - { + if should_evict { + if let Some(victim) = victim { self.remove_job(&victim.key); stats.evicted += 1; } - } - else - { + } else { stats.dropped += 1; continue; } @@ -515,16 +453,13 @@ impl RequestQueue } /// Takes the most urgent queued job and marks it in flight. - pub fn pop(&mut self) -> Option - { - if self.in_flight >= self.config.max_in_flight - { + pub fn pop(&mut self) -> Option { + if self.in_flight >= self.config.max_in_flight { return None; } // Reserve room for every in-flight result to become ready. - if self.ready.len() + self.in_flight >= self.config.max_ready - { + if self.ready.len() + self.in_flight >= self.config.max_ready { return None; } @@ -551,11 +486,8 @@ impl RequestQueue /// Accepts a worker result. /// /// Results for evicted, expired, or retried jobs are discarded. - pub fn complete(&mut self, item: WorkItem, payload: T) -> CompleteOutcome - { - let Some(job) = self.jobs.get_mut(&item.key) - else - { + pub fn complete(&mut self, item: WorkItem, payload: T) -> CompleteOutcome { + let Some(job) = self.jobs.get_mut(&item.key) else { self.stats.total_stale_completions += 1; return CompleteOutcome::Discarded; }; @@ -579,11 +511,8 @@ impl RequestQueue /// Reports a failed worker attempt. The job is retried until /// `config.max_attempts` is reached, then dropped. - pub fn fail(&mut self, item: WorkItem) - { - let Some(job) = self.jobs.get(&item.key) - else - { + pub fn fail(&mut self, item: WorkItem) { + let Some(job) = self.jobs.get(&item.key) else { self.stats.total_stale_completions += 1; return; }; @@ -600,8 +529,7 @@ impl RequestQueue self.in_flight = self.in_flight.saturating_sub(1); - if attempt >= self.config.max_attempts - { + if attempt >= self.config.max_attempts { self.jobs.remove(&item.key); self.stats.total_dropped += 1; return; @@ -639,40 +567,31 @@ impl RequestQueue where F: FnMut(&RequestKey) -> bool, { - if max == 0 - { + if max == 0 { return Vec::new(); } let candidates: Vec = self.ready.iter().rev().copied().collect(); let mut result = Vec::new(); - for entry in candidates - { - if result.len() >= max - { + for entry in candidates { + if result.len() >= max { break; } - let Some(job) = self.jobs.get(&entry.key) - else - { + let Some(job) = self.jobs.get(&entry.key) else { continue; }; - if job.last_seen != frame || !keep(&entry.key) - { + if job.last_seen != frame || !keep(&entry.key) { continue; } - let Some(job) = self.remove_job(&entry.key) - else - { + let Some(job) = self.remove_job(&entry.key) else { continue; }; - if let Some(payload) = job.payload - { + if let Some(payload) = job.payload { result.push(ReadyItem { key: job.key, meta: job.meta, @@ -685,14 +604,12 @@ impl RequestQueue } /// Removes every job belonging to a producer. - pub fn invalidate_producer(&mut self, producer: ProducerId) -> usize - { + pub fn invalidate_producer(&mut self, producer: ProducerId) -> usize { self.invalidate_matching(|key| key.producer_id == producer) } /// Removes every job whose anchor matches. - pub fn invalidate_anchor(&mut self, anchor: StructureAnchor) -> usize - { + pub fn invalidate_anchor(&mut self, anchor: StructureAnchor) -> usize { self.invalidate_matching(|key| key.anchor == anchor) } @@ -708,15 +625,13 @@ impl RequestQueue .collect(); let count = keys.len(); - for key in keys - { + for key in keys { self.remove_job(&key); } count } - fn expire(&mut self, frame: FrameId, stats: &mut IngestStats) - { + fn expire(&mut self, frame: FrameId, stats: &mut IngestStats) { let keys: Vec = self .jobs .iter() @@ -724,30 +639,24 @@ impl RequestQueue .map(|(key, _)| *key) .collect(); - for key in keys - { + for key in keys { self.remove_job(&key); stats.expired += 1; } } - fn remove_job(&mut self, key: &RequestKey) -> Option> - { + fn remove_job(&mut self, key: &RequestKey) -> Option> { let job = self.jobs.remove(key)?; let entry = entry_of(&job); - match job.state - { - JobState::Queued => - { + match job.state { + JobState::Queued => { self.queued.remove(&entry); } - JobState::Ready => - { + JobState::Ready => { self.ready.remove(&entry); } - JobState::InFlight => - { + JobState::InFlight => { self.in_flight = self.in_flight.saturating_sub(1); } } @@ -755,43 +664,35 @@ impl RequestQueue Some(job) } - pub fn len(&self) -> usize - { + pub fn len(&self) -> usize { self.jobs.len() } - pub fn is_empty(&self) -> bool - { + pub fn is_empty(&self) -> bool { self.jobs.is_empty() } - pub fn queued_len(&self) -> usize - { + pub fn queued_len(&self) -> usize { self.queued.len() } - pub fn in_flight_len(&self) -> usize - { + pub fn in_flight_len(&self) -> usize { self.in_flight } - pub fn ready_len(&self) -> usize - { + pub fn ready_len(&self) -> usize { self.ready.len() } - pub fn contains(&self, key: &RequestKey) -> bool - { + pub fn contains(&self, key: &RequestKey) -> bool { self.jobs.contains_key(key) } - pub fn state_of(&self, key: &RequestKey) -> Option - { + pub fn state_of(&self, key: &RequestKey) -> Option { self.jobs.get(key).map(|job| job.state) } - pub fn stats(&self) -> QueueStats - { + pub fn stats(&self) -> QueueStats { QueueStats { queued: self.queued.len(), in_flight: self.in_flight, @@ -802,8 +703,7 @@ impl RequestQueue } #[cfg(test)] -mod tests -{ +mod tests { use super::*; use vxls_voxel_cache::schema::NO_TABLE_SLOT; @@ -811,8 +711,7 @@ mod tests const PRODUCER: ProducerId = ProducerId(0); const ANCHOR: StructureAnchor = StructureAnchor::ZERO; - fn meta(page: u32, child: u32, depth: u32) -> RequestMeta - { + fn meta(page: u32, child: u32, depth: u32) -> RequestMeta { RequestMeta { page_index: page, children_index: child, @@ -821,13 +720,11 @@ mod tests } } - fn child_key(parent: u32, child: u32) -> RequestKey - { + fn child_key(parent: u32, child: u32) -> RequestKey { RequestKey::child(PRODUCER, ANCHOR, StructureLocator(parent), child) } - fn incoming(key: RequestKey, priority: RequestPriority) -> IncomingRequest - { + fn incoming(key: RequestKey, priority: RequestPriority) -> IncomingRequest { IncomingRequest { key, priority, @@ -845,8 +742,7 @@ mod tests depth: u32, anchor: StructureAnchor, table_slot: u32, - ) -> (RequestInformation, RequestMeta) - { + ) -> (RequestInformation, RequestMeta) { ( RequestInformation { node_id: StructureLocator(node), @@ -864,8 +760,7 @@ mod tests ) } - fn queue(max_queued: usize, max_in_flight: usize, max_ready: usize) -> RequestQueue - { + fn queue(max_queued: usize, max_in_flight: usize, max_ready: usize) -> RequestQueue { RequestQueue::new(QueueConfig { max_queued, max_in_flight, @@ -876,8 +771,7 @@ mod tests } #[test] - fn root_and_root_child_zero_do_not_collide() - { + fn root_and_root_child_zero_do_not_collide() { let mut q = queue(8, 1, 8); let root = RequestKey::root(PRODUCER, ANCHOR); let child = child_key(0, 0); @@ -896,8 +790,7 @@ mod tests } #[test] - fn from_wire_distinguishes_root_from_root_child_zero() - { + fn from_wire_distinguishes_root_from_root_child_zero() { let (root_info, root_meta) = wire(0, 0, PRODUCER.0, 7, u32::MAX, u32::MAX, ANCHOR, 3); let (child_info, child_meta) = wire(0, 0, PRODUCER.0, 7, 3, 0, ANCHOR, NO_TABLE_SLOT); @@ -915,8 +808,7 @@ mod tests } #[test] - fn from_wire_carries_demand_and_depth_into_priority() - { + fn from_wire_carries_demand_and_depth_into_priority() { let (info, meta) = wire(5, 2, PRODUCER.0, 11, 9, 3, ANCHOR, NO_TABLE_SLOT); let request = IncomingRequest::from_wire(&info, &meta); @@ -926,8 +818,7 @@ mod tests } #[test] - fn ready_item_builds_stateless_insertion_parent() - { + fn ready_item_builds_stateless_insertion_parent() { let mut q = queue(8, 2, 8); let root = RequestKey::root(PRODUCER, ANCHOR); let child = child_key(4, 2); @@ -977,8 +868,7 @@ mod tests } #[test] - fn ready_item_prefers_key_child_slot_over_meta() - { + fn ready_item_prefers_key_child_slot_over_meta() { let mut q = queue(8, 1, 8); let child = child_key(4, 2); @@ -1002,8 +892,7 @@ mod tests } #[test] - fn producer_id_disambiguates_identical_structure_keys() - { + fn producer_id_disambiguates_identical_structure_keys() { let mut q = queue(8, 1, 8); let a = RequestKey::child(ProducerId(0), ANCHOR, StructureLocator(7), 3); let b = RequestKey::child(ProducerId(1), ANCHOR, StructureLocator(7), 3); @@ -1022,8 +911,7 @@ mod tests } #[test] - fn duplicate_keys_are_deduplicated() - { + fn duplicate_keys_are_deduplicated() { let mut q = queue(8, 1, 8); let key = child_key(1, 2); let req = incoming(key, RequestPriority::child(1, 0)); @@ -1036,8 +924,7 @@ mod tests } #[test] - fn priority_ordering_prefers_higher_demand() - { + fn priority_ordering_prefers_higher_demand() { let mut q = queue(8, 8, 8); let low = child_key(1, 0); let high = child_key(2, 0); @@ -1055,8 +942,7 @@ mod tests } #[test] - fn roots_outrank_children() - { + fn roots_outrank_children() { let mut q = queue(8, 8, 8); let root = RequestKey::root(PRODUCER, ANCHOR); let child = child_key(0, 0); @@ -1073,8 +959,7 @@ mod tests } #[test] - fn shallower_children_are_more_urgent() - { + fn shallower_children_are_more_urgent() { let mut q = queue(8, 8, 8); let deep = child_key(1, 0); let shallow = child_key(2, 0); @@ -1091,8 +976,7 @@ mod tests } #[test] - fn priority_updates_reorder_queued_jobs() - { + fn priority_updates_reorder_queued_jobs() { let mut q = queue(8, 8, 8); let a = child_key(1, 0); let b = child_key(2, 0); @@ -1113,8 +997,7 @@ mod tests } #[test] - fn queued_bound_evicts_lowest_priority() - { + fn queued_bound_evicts_lowest_priority() { let mut q = queue(2, 8, 8); let a = child_key(1, 0); let b = child_key(2, 0); @@ -1137,8 +1020,7 @@ mod tests } #[test] - fn lower_priority_newcomer_is_dropped_when_full() - { + fn lower_priority_newcomer_is_dropped_when_full() { let mut q = queue(1, 8, 8); let a = child_key(1, 0); let b = child_key(2, 0); @@ -1153,8 +1035,7 @@ mod tests } #[test] - fn unseen_jobs_expire_after_grace_period() - { + fn unseen_jobs_expire_after_grace_period() { let mut q = queue(8, 8, 8); let key = child_key(1, 0); @@ -1167,8 +1048,7 @@ mod tests } #[test] - fn in_flight_jobs_expire_and_their_completion_is_discarded() - { + fn in_flight_jobs_expire_and_their_completion_is_discarded() { let mut q = queue(8, 8, 8); let key = child_key(1, 0); @@ -1183,8 +1063,7 @@ mod tests } #[test] - fn stale_completion_after_recreation_is_discarded() - { + fn stale_completion_after_recreation_is_discarded() { let mut q = queue(8, 8, 8); let key = child_key(1, 0); @@ -1202,8 +1081,7 @@ mod tests } #[test] - fn completed_jobs_become_ready_and_drain() - { + fn completed_jobs_become_ready_and_drain() { let mut q = queue(8, 8, 8); let key = child_key(1, 0); @@ -1222,8 +1100,7 @@ mod tests } #[test] - fn drain_only_returns_jobs_seen_in_the_requested_frame() - { + fn drain_only_returns_jobs_seen_in_the_requested_frame() { let mut q = queue(8, 8, 8); let key = child_key(1, 0); @@ -1242,8 +1119,7 @@ mod tests } #[test] - fn drain_respects_keep_predicate() - { + fn drain_respects_keep_predicate() { let mut q = queue(8, 8, 8); let a = child_key(1, 0); let b = child_key(2, 0); @@ -1267,8 +1143,7 @@ mod tests } #[test] - fn ready_backpressure_stops_dispatch() - { + fn ready_backpressure_stops_dispatch() { let mut q = queue(8, 4, 2); let a = child_key(1, 0); let b = child_key(2, 0); @@ -1290,15 +1165,13 @@ mod tests } #[test] - fn fail_requeues_until_max_attempts() - { + fn fail_requeues_until_max_attempts() { let mut q = queue(8, 1, 8); let key = child_key(1, 0); q.ingest(0, [incoming(key, RequestPriority::child(1, 0))]); - for attempt in 1..=3 - { + for attempt in 1..=3 { let item = q.pop().unwrap(); assert_eq!(item.attempt, attempt); q.fail(item); @@ -1308,8 +1181,7 @@ mod tests } #[test] - fn invalidation_removes_queued_and_ready_jobs() - { + fn invalidation_removes_queued_and_ready_jobs() { let mut q = queue(8, 8, 8); let a = child_key(1, 0); let b = child_key(9, 0); @@ -1331,8 +1203,7 @@ mod tests } #[test] - fn invalidate_producer_only_removes_that_producer() - { + fn invalidate_producer_only_removes_that_producer() { let mut q = queue(8, 8, 8); let a = RequestKey::child(ProducerId(0), ANCHOR, StructureLocator(1), 0); let b = RequestKey::child(ProducerId(1), ANCHOR, StructureLocator(1), 0); @@ -1350,8 +1221,7 @@ mod tests } #[test] - fn zero_queued_capacity_drops_everything() - { + fn zero_queued_capacity_drops_everything() { let mut q = queue(0, 1, 8); let key = child_key(1, 0); let stats = q.ingest(0, [incoming(key, RequestPriority::child(1, 0))]); @@ -1359,8 +1229,7 @@ mod tests assert!(q.is_empty()); } - fn root_incoming(slot: u32) -> IncomingRequest - { + fn root_incoming(slot: u32) -> IncomingRequest { IncomingRequest { key: RequestKey::root(PRODUCER, ANCHOR), priority: RequestPriority::root(1), @@ -1372,8 +1241,7 @@ mod tests } #[test] - fn root_job_refreshes_table_slot_while_in_flight() - { + fn root_job_refreshes_table_slot_while_in_flight() { let mut q = queue(8, 1, 8); q.ingest(0, [root_incoming(1)]); @@ -1393,8 +1261,7 @@ mod tests } #[test] - fn root_key_is_stable_across_slot_moves() - { + fn root_key_is_stable_across_slot_moves() { let mut q = queue(8, 1, 8); q.ingest(0, [root_incoming(1)]); @@ -1411,8 +1278,7 @@ mod tests } #[test] - fn different_anchors_are_distinct() - { + fn different_anchors_are_distinct() { let mut q = queue(8, 1, 8); let a = RequestKey::child(PRODUCER, ANCHOR, StructureLocator(1), 0); let b = RequestKey::child( @@ -1434,8 +1300,7 @@ mod tests } #[test] - fn invalidate_anchor_removes_matching_jobs() - { + fn invalidate_anchor_removes_matching_jobs() { let mut q = queue(8, 8, 8); let anchor = StructureAnchor::from_world(4, 5, 6, 0); let a = RequestKey::child(PRODUCER, anchor, StructureLocator(1), 0); diff --git a/crates/vxls-production/src/sparse_tree.rs b/crates/vxls-production/src/sparse_tree.rs index 9cbca27..0cc3677 100644 --- a/crates/vxls-production/src/sparse_tree.rs +++ b/crates/vxls-production/src/sparse_tree.rs @@ -20,18 +20,14 @@ pub struct ColorByte(pub u32); // 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() - { +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 - { + for color in attributes { c.0 += color.0; c.1 += color.1; c.2 += color.2; @@ -47,18 +43,14 @@ impl Attribute for Color } } -impl Attribute for ColorByte -{ - fn average(attributes: &[Self]) -> Self - { - if attributes.is_empty() - { +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 - { + for color in attributes { let color = color.as_color(); c.0 += color.0; c.1 += color.1; @@ -75,10 +67,8 @@ impl Attribute for ColorByte } } -impl Color -{ - pub fn as_packed_u32(&self) -> 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; @@ -86,16 +76,13 @@ impl Color mapped_r | (mapped_g << 8) | (mapped_b << 16) | (mapped_a << 24) } - pub fn as_color_byte(&self) -> ColorByte - { + pub fn as_color_byte(&self) -> ColorByte { ColorByte(self.as_packed_u32()) } } -impl ColorByte -{ - pub fn as_color(&self) -> Color - { +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; @@ -105,8 +92,7 @@ impl ColorByte } #[derive(Debug, Clone)] -pub struct NTree -{ +pub struct NTree { map: HashMap, NTreeNode>, // Depth is the parameter such that @@ -116,23 +102,19 @@ pub struct NTree } #[derive(Debug, Clone, Copy)] -pub struct NTreeNode -{ +pub struct NTreeNode { pub attribute: T, pub subdivided: bool, } -impl NTree -{ +impl NTree { /// Maximum voxel depth: the tree spans `N.pow(depth)` voxels per axis. - pub fn depth(&self) -> usize - { + pub fn depth(&self) -> usize { self.depth } /// Number of nodes currently stored, reachable from the root or not. - pub fn node_count(&self) -> usize - { + pub fn node_count(&self) -> usize { self.map.len() } } @@ -142,8 +124,7 @@ where [(); N * N * N]:, T: Attribute, { - pub fn constant(value: T, depth: usize) -> Self - { + pub fn constant(value: T, depth: usize) -> Self { let mut map = HashMap::new(); let root = NTreeNode { attribute: value, @@ -153,13 +134,11 @@ where Self { map, depth } } - pub fn set(&mut self, x: usize, y: usize, z: usize, value: T) - { + 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>(&self, mut map: F) -> NTree - { + pub fn mapped D>(&self, mut map: F) -> NTree { NTree:: { map: self .map @@ -178,8 +157,7 @@ where } } - pub fn get(&self, x: usize, y: usize, z: usize) -> T - { + 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)); @@ -189,10 +167,8 @@ where 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 - { + loop { + if !current_node.subdivided { return current_node.attribute; } @@ -209,8 +185,7 @@ where } } - pub fn set_at_depth(&mut self, x: usize, y: usize, z: usize, depth: usize, value: T) - { + 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)); @@ -221,17 +196,14 @@ where 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 - { + 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 - { + if !current_node.subdivided { current_node.subdivided = true; let new_nodes = NTreeNode { attribute: current_node.attribute, @@ -255,20 +227,16 @@ where current_node = self.map.get_mut(¤t_node_loc).unwrap(); } - if current_node.subdivided - { + if current_node.subdivided { self.make_constant(current_node_loc, value); - } - else - { + } 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 - { + loop { // Go one node up current_depth -= 1; current_node_loc = current_node_loc.parent().unwrap(); @@ -284,27 +252,23 @@ where current_node = self.map.get_mut(¤t_node_loc).unwrap(); current_node.attribute = children_attribute_avg; - if current_depth == 0 - { + if current_depth == 0 { break; } } } - fn make_constant(&mut self, locator: TreeLocator, value: T) - { + fn make_constant(&mut self, locator: TreeLocator, value: T) { let mut dfs_stack = Vec::new(); dfs_stack.push(locator); - while let Some(current) = dfs_stack.pop() - { + 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 - { + if handle_children { dfs_stack.extend(current.children()); } } @@ -318,8 +282,7 @@ where ); } - pub fn from_array(array: &[T], depth: usize) -> Self - { + pub fn from_array(array: &[T], depth: usize) -> Self { let mut structure = HashMap::new(); // Per voxel in the array : // 0 -> Voxel not merged yet @@ -327,13 +290,10 @@ where 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) - { + 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 - { + 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 @@ -354,8 +314,7 @@ where let attribute = array[x + y * width + z * width * width]; let mut locator = TreeLocator::::from_node_coords(depth as u32, x as u32, y as u32, z as u32); - 'power_search: for power in 1..=block_power - { + '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) @@ -400,8 +359,7 @@ where // The structure now consists of the leaf most nodes, we need to rebuild the hierarchy // bottom up - for current_power in 1..=depth - { + 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; @@ -414,8 +372,7 @@ where let corner = merged_size[(block_x * block_size) + (block_y * block_size) * width + (block_z * block_size) * width * width]; - if corner >= block_size - { + if corner >= block_size { // Children are merged in bigger block continue; } @@ -449,8 +406,7 @@ where } } - pub fn get_by_loc(&self, locator: TreeLocator) -> Option> - { + pub fn get_by_loc(&self, locator: TreeLocator) -> Option> { self.map.get(&locator).copied() } @@ -459,21 +415,17 @@ where /// 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, NTreeNode>, depth: usize) -> Self - { + pub(crate) fn from_nodes(map: HashMap, NTreeNode>, depth: usize) -> Self { Self { map, depth } } } -fn base_trailing_zeroes(mut number: usize) -> Option -{ - if number == 0 - { +fn base_trailing_zeroes(mut number: usize) -> Option { + if number == 0 { return None; } let mut trailing_zeroes = 0; - while number.is_multiple_of(N) - { + while number.is_multiple_of(N) { number /= N; trailing_zeroes += 1; } @@ -488,8 +440,7 @@ where let file = std::fs::read_to_string(path).unwrap(); let mut colors = vec![Color::default(); 256 * 256 * 256]; - for line in file.lines() - { + for line in file.lines() { let coords = line .split(',') .take(3) @@ -503,16 +454,14 @@ where NTree::::from_array(&colors, 4) } -mod test -{ +mod test { #[allow(unused_imports)] use crate::sparse_tree::Color; #[allow(unused_imports)] use crate::sparse_tree::NTree; #[test] - fn constant_set() - { + 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.)); @@ -520,15 +469,13 @@ mod test } #[test] - fn load_read_same() - { + 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() - { + for line in file.lines() { let coords = line .split(',') .take(3) @@ -543,12 +490,9 @@ mod test 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 - { + 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); diff --git a/crates/vxls-production/src/tree_locator.rs b/crates/vxls-production/src/tree_locator.rs index 1b6ee9b..eaee113 100644 --- a/crates/vxls-production/src/tree_locator.rs +++ b/crates/vxls-production/src/tree_locator.rs @@ -15,23 +15,19 @@ use crate::StructureLocator; /// 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 -{ +pub struct TreeLocator { x: u32, y: u32, z: u32, } -impl From for TreeLocator -{ - fn from(value: StructureLocator) -> Self - { +impl From for TreeLocator { + fn from(value: StructureLocator) -> Self { let mut value = value.0; let mut locator = Self::root(); let n = N as u32; - while value != 1 - { + while value != 1 { let z = value % n; value /= n; let y = value % n; @@ -45,13 +41,10 @@ impl From for TreeLocator } } -impl From> for StructureLocator -{ - fn from(mut value: TreeLocator) -> StructureLocator - { +impl From> for StructureLocator { + fn from(mut value: TreeLocator) -> StructureLocator { let mut locator = 1u32; - while !value.is_root() - { + while !value.is_root() { let (x, y, z) = value.local_coords(); value = value.parent().unwrap(); @@ -69,12 +62,10 @@ impl From> for StructureLocator } } -impl TreeLocator -{ +impl TreeLocator { pub const ROOT: TreeLocator = TreeLocator { x: 1, y: 1, z: 1 }; - pub fn root() -> Self - { + pub fn root() -> Self { Self::ROOT } @@ -82,8 +73,7 @@ impl TreeLocator /// `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 - { + 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, @@ -98,8 +88,7 @@ impl TreeLocator "Node coordinates out of bounds." ); - if depth == 0 - { + if depth == 0 { return Self::ROOT; } @@ -113,19 +102,16 @@ impl TreeLocator } /// Computes the maximum depth supported for this tree arity - pub fn max_depth() -> u32 - { + pub fn max_depth() -> u32 { (u32::MAX as usize).ilog(N) - 1 } - pub fn is_root(&self) -> bool - { + 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 - { + 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 @@ -134,8 +120,7 @@ impl TreeLocator /// 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 - { + pub fn node_size(&self, max_depth: u32) -> u32 { let depth = self.depth(); // 0 if voxel, max_depth if root @@ -145,14 +130,10 @@ impl TreeLocator } /// Returns the locator of this node's parent, `None` if `self` is the root - pub fn parent(&self) -> Option - { - if self.is_root() - { + pub fn parent(&self) -> Option { + if self.is_root() { None - } - else - { + } else { Some(Self { x: self.x / N as u32, y: self.y / N as u32, @@ -165,8 +146,7 @@ impl TreeLocator /// `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 - { + 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."); @@ -195,8 +175,7 @@ impl TreeLocator } /// Returns an iterator on the children of this node - pub fn children(&self) -> impl Iterator - { + pub fn children(&self) -> impl Iterator { (0..N as u32) .cartesian_product(0..N as u32) .cartesian_product(0..N as u32) @@ -205,10 +184,8 @@ impl TreeLocator /// 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() - { + pub fn local_coords(&self) -> (u32, u32, u32) { + if self.is_root() { return (0, 0, 0); } @@ -220,8 +197,7 @@ impl TreeLocator } /// Returns the location of this node at in the space of this depth - pub fn node_location(&self) -> (u32, u32, u32) - { + pub fn node_location(&self) -> (u32, u32, u32) { let depth = self.depth(); // Puts a one in base-N on the Nth digit @@ -231,18 +207,15 @@ impl TreeLocator } #[cfg(test)] -mod tests -{ +mod tests { use super::*; - fn raw(l: TreeLocator) -> (u32, u32, u32) - { + fn raw(l: TreeLocator) -> (u32, u32, u32) { (l.x, l.y, l.z) } #[test] - fn root_is_depth_zero() - { + fn root_is_depth_zero() { let r = TreeLocator::<4>::root(); assert!(r.is_root()); assert_eq!(r.depth(), 0); @@ -252,8 +225,7 @@ mod tests } #[test] - fn child_encoding_matches_doc_example() - { + 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) @@ -267,8 +239,7 @@ mod tests } #[test] - fn child_uses_independent_coordinates() - { + 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); @@ -276,8 +247,7 @@ mod tests } #[test] - fn parent_undoes_child() - { + fn parent_undoes_child() { let root = TreeLocator::<4>::root(); let c = root.child(3, 0, 2); let gc = c.child(1, 1, 0); @@ -287,15 +257,13 @@ mod tests } #[test] - fn from_node_coords_depth_zero_is_root() - { + 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() - { + 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); @@ -306,23 +274,20 @@ mod tests } #[test] - fn from_node_coords_parent_is_coarser_node() - { + 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() - { + 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() - { + while let Some(parent) = cur.parent() { path.push(cur.local_coords()); cur = parent; } @@ -331,16 +296,14 @@ mod tests // Walk back down and rebuild. let mut rebuilt = TreeLocator::<3>::root(); - for (x, y, z) in path.into_iter().rev() - { + 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() - { + fn children_are_complete_distinct_and_valid() { let parent = TreeLocator::<3>::root().child(2, 1, 0); let kids: Vec<_> = parent.children().collect(); @@ -348,8 +311,7 @@ mod tests let mut seen = std::collections::HashSet::new(); let mut locals = std::collections::HashSet::new(); - for k in &kids - { + 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"); @@ -360,8 +322,7 @@ mod tests } #[test] - fn node_size_scales_with_depth() - { + 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 @@ -377,17 +338,14 @@ mod tests } #[test] - fn max_depth_is_reachable_without_overflow() - { + fn max_depth_is_reachable_without_overflow() { // `max_depth` may be conservative, but it must always be safe to reach. - fn check() - { + fn check() { let max = TreeLocator::::max_depth(); let last = N as u32 - 1; let mut l = TreeLocator::::root(); - for _ in 0..max - { + for _ in 0..max { l = l.child(last, last, last); } assert_eq!(l.depth(), max); @@ -406,33 +364,28 @@ mod tests #[test] #[should_panic(expected = "Out of bounds child coordinate.")] - fn child_rejects_out_of_range_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() - { + 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() - { + fn child_rejects_overflowing_depth() { let mut l = TreeLocator::<2>::root(); - for _ in 0..40 - { + for _ in 0..40 { l = l.child(1, 1, 1); } } #[test] - fn node_at_depth_roundtrip() - { + 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); diff --git a/crates/vxls-production/tests/attributes.rs b/crates/vxls-production/tests/attributes.rs index fd34c03..df42b93 100644 --- a/crates/vxls-production/tests/attributes.rs +++ b/crates/vxls-production/tests/attributes.rs @@ -14,8 +14,7 @@ use vxls_voxel_cache::schema::InsertionInformation; #[derive(Clone, Copy, PartialEq, Default, Pod, Zeroable, Attributes, Debug)] #[repr(C)] -struct TestAttributes -{ +struct TestAttributes { #[attribute(label = "color", semantic = "color")] color: u32, @@ -26,8 +25,7 @@ struct TestAttributes reserved: u32, } -fn sample(color: u32, normal: [f32; 3]) -> TestAttributes -{ +fn sample(color: u32, normal: [f32; 3]) -> TestAttributes { TestAttributes { color, normal, @@ -36,8 +34,7 @@ fn sample(color: u32, normal: [f32; 3]) -> TestAttributes } #[test] -fn layout_matches_the_declared_fields() -{ +fn layout_matches_the_declared_fields() { let layout = TestAttributes::LAYOUT; assert_eq!(layout.len(), 2); @@ -60,8 +57,7 @@ fn layout_matches_the_declared_fields() } #[test] -fn get_attr_returns_the_field_bytes() -{ +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)); @@ -77,8 +73,7 @@ fn get_attr_returns_the_field_bytes() } #[test] -fn average_is_component_wise_and_skips_the_reserved_field() -{ +fn average_is_component_wise_and_skips_the_reserved_field() { let first = TestAttributes { color: 2, normal: [1.0, 2.0, 3.0], @@ -100,8 +95,7 @@ fn average_is_component_wise_and_skips_the_reserved_field() } #[test] -fn validate_rejects_duplicate_labels_and_semantics() -{ +fn validate_rejects_duplicate_labels_and_semantics() { const DUPLICATE_LABELS: AttributesLayout = AttributesLayout { attributes: &[ AttributeDescriptor { @@ -149,8 +143,7 @@ fn validate_rejects_duplicate_labels_and_semantics() } #[test] -fn produced_node_transposes_attributes_for_the_insertion_buffer() -{ +fn produced_node_transposes_attributes_for_the_insertion_buffer() { let value = sample(0x0102_0304, [1.0, 2.0, 3.0]); let insertion = InsertionInformation::<4> { diff --git a/crates/vxls-production/tests/io.rs b/crates/vxls-production/tests/io.rs index 345b726..bb4185e 100644 --- a/crates/vxls-production/tests/io.rs +++ b/crates/vxls-production/tests/io.rs @@ -6,7 +6,8 @@ use std::io::Cursor; use std::ops::Range; -use bytemuck::{Pod, Zeroable}; +use bytemuck::Pod; +use bytemuck::Zeroable; use vxls_production::Attribute; use vxls_production::AttributeDescriptor; use vxls_production::Attributes; @@ -42,33 +43,31 @@ where } #[derive(Clone, Copy, Debug)] -struct Entry -{ +struct Entry { tag: u32, offset: usize, size: usize, table_position: usize, } -impl Entry -{ - fn body(&self) -> Range - { +impl Entry { + fn body(&self) -> Range { self.offset + 12..self.offset + self.size } } -fn header_size(bytes: &[u8]) -> usize -{ +fn header_size(bytes: &[u8]) -> usize { u32::from_le_bytes(bytes[24..28].try_into().unwrap()) as usize } -fn entries(bytes: &[u8]) -> Vec -{ +fn entries(bytes: &[u8]) -> Vec { 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 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) @@ -76,8 +75,7 @@ fn entries(bytes: &[u8]) -> Vec 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, + 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, } @@ -85,37 +83,32 @@ fn entries(bytes: &[u8]) -> Vec .collect() } -fn find_level(bytes: &[u8], level: u32) -> Entry -{ +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) -{ +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) -{ +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) -{ +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() -{ +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(); @@ -126,16 +119,12 @@ fn constant_tree_roundtrip() } #[test] -fn one_voxel_roundtrip_matches_every_position() -{ +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 - { + 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); } } @@ -143,12 +132,9 @@ fn one_voxel_roundtrip_matches_every_position() 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 - { + 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}"); } } @@ -156,16 +142,12 @@ fn one_voxel_roundtrip_matches_every_position() } #[test] -fn deep_tree_roundtrip() -{ +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 - { + 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); } } @@ -173,12 +155,9 @@ fn deep_tree_roundtrip() 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 - { + 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}"); } } @@ -186,16 +165,12 @@ fn deep_tree_roundtrip() } #[test] -fn arity_three_roundtrip() -{ +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 - { + 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); } } @@ -203,12 +178,9 @@ fn arity_three_roundtrip() 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 - { + 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}"); } } @@ -216,8 +188,7 @@ fn arity_three_roundtrip() } #[test] -fn shallow_tree_keeps_capacity_in_header() -{ +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(); @@ -227,18 +198,14 @@ fn shallow_tree_keeps_capacity_in_header() } #[test] -fn from_array_roundtrip() -{ +fn from_array_roundtrip() { let values: Vec = (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 - { + 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}"); } } @@ -247,8 +214,7 @@ fn from_array_roundtrip() #[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable, Attributes)] #[repr(C)] -struct Payload -{ +struct Payload { #[attribute(label = "color", semantic = "color")] color: u32, @@ -257,16 +223,12 @@ struct Payload } #[test] -fn multi_attribute_roundtrip() -{ +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 - { + for z in 0..4 { + for y in 0..4 { + for x in 0..4 { tree.set( x, y, @@ -290,12 +252,9 @@ fn multi_attribute_roundtrip() 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 - { + 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)); } } @@ -303,8 +262,7 @@ fn multi_attribute_roundtrip() } #[test] -fn write_rejects_layout_size_mismatch() -{ +fn write_rejects_layout_size_mismatch() { let tree = NTree::<2, u32>::constant(0, 1); let mut cursor = Cursor::new(Vec::new()); @@ -315,8 +273,7 @@ fn write_rejects_layout_size_mismatch() } #[test] -fn write_rejects_empty_layout() -{ +fn write_rejects_empty_layout() { let tree = NTree::<2, u32>::constant(0, 1); let mut cursor = Cursor::new(Vec::new()); @@ -327,8 +284,7 @@ fn write_rejects_empty_layout() } #[test] -fn write_rejects_zero_word_count() -{ +fn write_rejects_zero_word_count() { const ZERO: AttributesLayout = AttributesLayout::new(&[AttributeDescriptor::new("zero", 0)]); let tree = NTree::<2, u32>::constant(0, 1); @@ -341,8 +297,7 @@ fn write_rejects_zero_word_count() } #[test] -fn rejects_bad_magic() -{ +fn rejects_bad_magic() { let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); bytes[0] = b'X'; @@ -353,8 +308,7 @@ fn rejects_bad_magic() } #[test] -fn rejects_bad_file_type() -{ +fn rejects_bad_file_type() { let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); bytes[4] = b'X'; @@ -365,8 +319,7 @@ fn rejects_bad_file_type() } #[test] -fn rejects_unsupported_major_version() -{ +fn rejects_unsupported_major_version() { let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); patch_u32(&mut bytes, 8, 99); @@ -377,8 +330,7 @@ fn rejects_unsupported_major_version() } #[test] -fn accepts_newer_minor_version() -{ +fn accepts_newer_minor_version() { let mut bytes = encode(&NTree::<2, u32>::constant(3, 1), U32_LAYOUT); patch_u32(&mut bytes, 12, 7); @@ -387,8 +339,7 @@ fn accepts_newer_minor_version() } #[test] -fn rejects_file_size_mismatch() -{ +fn rejects_file_size_mismatch() { let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); bytes.pop(); @@ -399,8 +350,7 @@ fn rejects_file_size_mismatch() } #[test] -fn rejects_arity_mismatch() -{ +fn rejects_arity_mismatch() { let bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); assert!(matches!( @@ -413,8 +363,7 @@ fn rejects_arity_mismatch() } #[test] -fn rejects_small_header() -{ +fn rejects_small_header() { let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); patch_u32(&mut bytes, 24, 4); @@ -425,8 +374,7 @@ fn rejects_small_header() } #[test] -fn rejects_excessive_depth() -{ +fn rejects_excessive_depth() { let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); patch_u32(&mut bytes, 32, 31); @@ -437,11 +385,14 @@ fn rejects_excessive_depth() } #[test] -fn rejects_misaligned_offset_table_entry() -{ +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); + patch_u32( + &mut bytes, + entry.table_position + 8, + entry.offset as u32 + 1, + ); assert!(matches!( decode::<2, u32>(&bytes, None), @@ -450,8 +401,7 @@ fn rejects_misaligned_offset_table_entry() } #[test] -fn rejects_duplicate_chunk_tag() -{ +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]; @@ -464,8 +414,7 @@ fn rejects_duplicate_chunk_tag() } #[test] -fn rejects_non_zero_padding() -{ +fn rejects_non_zero_padding() { let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); let entries = entries(&bytes); @@ -486,8 +435,7 @@ fn rejects_non_zero_padding() } #[test] -fn rejects_wrong_frame_tag() -{ +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); @@ -500,8 +448,7 @@ fn rejects_wrong_frame_tag() } #[test] -fn rejects_bad_crc() -{ +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(); @@ -514,8 +461,7 @@ fn rejects_bad_crc() } #[test] -fn rejects_invalid_utf8_label() -{ +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(); @@ -530,8 +476,7 @@ fn rejects_invalid_utf8_label() } #[test] -fn rejects_layout_mismatch() -{ +fn rejects_layout_mismatch() { let bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); assert!(matches!( @@ -541,8 +486,7 @@ fn rejects_layout_mismatch() } #[test] -fn rejects_layout_size_mismatch() -{ +fn rejects_layout_size_mismatch() { let tree = NTree::<2, [u32; 2]>::constant([1, 2], 1); let bytes = encode(&tree, PAIR_LAYOUT); @@ -553,8 +497,7 @@ fn rejects_layout_size_mismatch() } #[test] -fn rejects_trailing_bytes() -{ +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; @@ -567,8 +510,7 @@ fn rejects_trailing_bytes() } #[test] -fn rejects_missing_level_chunk() -{ +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); @@ -587,8 +529,7 @@ fn rejects_missing_level_chunk() } #[test] -fn rejects_node_count_mismatch() -{ +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); @@ -609,8 +550,7 @@ fn rejects_node_count_mismatch() } #[test] -fn rejects_subdivision_at_deepest_level() -{ +fn rejects_subdivision_at_deepest_level() { let mut tree = NTree::<2, u32>::constant(0, 1); tree.set(0, 0, 0, 1); @@ -629,8 +569,7 @@ fn rejects_subdivision_at_deepest_level() } #[test] -fn rejects_non_zero_unused_flag_bits() -{ +fn rejects_non_zero_unused_flag_bits() { let mut tree = NTree::<2, u32>::constant(0, 1); tree.set(0, 0, 0, 1); @@ -649,8 +588,7 @@ fn rejects_non_zero_unused_flag_bits() } #[test] -fn file_path_helpers_roundtrip() -{ +fn file_path_helpers_roundtrip() { let directory = std::env::temp_dir().join(format!( "vxls-io-test-{}-{}", std::process::id(), diff --git a/crates/vxls-profiler/src/lib.rs b/crates/vxls-profiler/src/lib.rs index 21341e2..116a148 100644 --- a/crates/vxls-profiler/src/lib.rs +++ b/crates/vxls-profiler/src/lib.rs @@ -32,23 +32,20 @@ macro_rules! 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, } -pub struct Scope -{ +pub struct Scope { name: &'static str, start_index: QuerySetHandle, end_index: Option, children: Vec, } -pub struct ProfilingEncoder<'enc> -{ +pub struct ProfilingEncoder<'enc> { device: Device, encoder: &'enc mut CommandEncoder, query_set_allocator: QuerySetAllocator, @@ -59,14 +56,12 @@ pub struct ProfilingEncoder<'enc> compute_pass: Option<(usize, ComputePass<'static>)>, } -pub struct GpuProfile -{ +pub struct GpuProfile { scopes: Vec, timestamps: Buffer, } -pub struct Frame -{ +pub struct Frame { pub name: &'static str, pub children: Vec, @@ -75,15 +70,12 @@ pub struct Frame } #[derive(Default)] -pub struct Profile -{ +pub struct Profile { pub frames: Vec, } -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), @@ -97,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 { @@ -108,17 +99,13 @@ impl<'enc> ProfilingEncoder<'enc> } } - fn begin_scope(&mut self, scope_index: Option, name: &'static str) -> usize - { + fn begin_scope(&mut self, scope_index: Option, 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); } @@ -135,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); } @@ -167,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"), @@ -187,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 @@ -227,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, @@ -250,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 { @@ -270,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, @@ -332,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 - { +impl PartialOrd for QuerySetHandle { + fn partial_cmp(&self, other: &Self) -> Option { 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, @@ -380,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::() as u64; } } - pub fn allocate(&mut self) -> QuerySetHandle - { + pub fn allocate(&mut self) -> QuerySetHandle { // Check if allocation is possible if self .query_sets @@ -430,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, @@ -439,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, @@ -487,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, depth: usize, q: f32, str: &mut String) - { + fn build_string(&self, frames: &Vec, depth: usize, q: f32, str: &mut String) { let mut depth_string = String::new(); (0..depth).for_each(|_| depth_string.push_str(" ")); @@ -535,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) - { + pub fn show(&self, ui: &mut Ui, q: f32, frames: &Vec) { let id = ui.make_persistent_id(self.name); egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true) .show_header(ui, |ui| { @@ -567,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.; @@ -581,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 } @@ -612,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)); @@ -647,18 +570,15 @@ impl Profile let mut hovered: Option = 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; @@ -666,18 +586,15 @@ 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 - { + 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, @@ -689,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; @@ -705,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() diff --git a/crates/vxls-profiler/src/memory_profiler.rs b/crates/vxls-profiler/src/memory_profiler.rs index a8aa738..90fcd86 100644 --- a/crates/vxls-profiler/src/memory_profiler.rs +++ b/crates/vxls-profiler/src/memory_profiler.rs @@ -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, pub buffers: Vec, pub sub_groups: Vec, } -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::() + self.sub_groups.iter().map(Self::size).sum::() }) } - 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::() + self @@ -48,21 +42,17 @@ impl Group } } -pub struct MemoryProfile -{ +pub struct MemoryProfile { stack: Vec, } -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 group in self.sub_groups.iter() - { + for group in self.sub_groups.iter() { group.fmt_with_indent(f, indent + 1)?; } diff --git a/crates/vxls-terrain/src/lib.rs b/crates/vxls-terrain/src/lib.rs index 2f591a8..8288356 100644 --- a/crates/vxls-terrain/src/lib.rs +++ b/crates/vxls-terrain/src/lib.rs @@ -17,8 +17,7 @@ use vxls_voxel_cache::tables::FixedStructureTable; /// 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 -{ +pub struct ToroidalStructureTable { /// Size of the torroidal structure : how many chunks in each direction can be rendered at once extent: (usize, usize, usize), @@ -31,8 +30,7 @@ pub struct ToroidalStructureTable #[derive(Debug, Clone, Copy, Zeroable, Pod)] #[repr(C)] -struct ToroidalInvalidationImmediates -{ +struct ToroidalInvalidationImmediates { extent: [u32; 3], _pad1: u32, previous_offset: [i32; 3], @@ -41,16 +39,14 @@ struct ToroidalInvalidationImmediates _pad3: u32, } -impl ToroidalStructureTable -{ +impl ToroidalStructureTable { pub fn new( device: &wgpu::Device, extent: (usize, usize, usize), initial_position: Vec3, max_requests: usize, producer_id: u32, - ) -> Self - { + ) -> Self { let size = extent.0 * extent.1 * extent.2; assert!(size <= (u32::MAX as usize)); @@ -121,16 +117,14 @@ impl ToroidalStructureTable queue: &wgpu::Queue, encoder: &mut CommandEncoder, new_position: Vec3, - ) -> Vec - { + ) -> Vec { let previous_offset = self.current_offset; let new_offset = Self::offset_from_center(self.extent, new_position); self.current_offset = new_offset; self.position = new_position; let mut retired = Vec::new(); - if previous_offset != new_offset - { + if previous_offset != new_offset { let size = self.extent.0 * self.extent.1 * self.extent.2; let new_anchors: Vec = (0..size) .map(|slot| { @@ -183,8 +177,7 @@ impl ToroidalStructureTable } /// Returns the world position encoded in a table anchor. - pub fn position_for_anchor(&self, anchor: StructureAnchor) -> (isize, isize, isize) - { + 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) } @@ -193,8 +186,7 @@ impl ToroidalStructureTable /// /// 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] - { + pub fn base_slot(&self) -> [u32; 3] { let (ox, oy, oz) = self.current_offset; let (ex, ey, ez) = self.extent; [ @@ -208,8 +200,7 @@ impl ToroidalStructureTable extent: (usize, usize, usize), slot: usize, offset: (isize, isize, isize), - ) -> (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; @@ -226,8 +217,7 @@ impl ToroidalStructureTable ) } - fn offset_from_center(extent: (usize, usize, usize), position: Vec3) -> (isize, isize, isize) - { + 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), @@ -237,13 +227,11 @@ impl ToroidalStructureTable // Function calls through to fixed_structure_table - pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup - { + pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup { self.fixed_structure_table.raytrace_bind_group() } - pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout - { + pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout { self.fixed_structure_table.raytrace_bind_group_layout() } @@ -264,8 +252,7 @@ impl ToroidalStructureTable device: &wgpu::Device, encoder: &mut vxls_profiler::ScopeEncoder, request_buffer: &vxls_voxel_cache::requests::CacheRequestBuffer, - ) - { + ) { self.fixed_structure_table .gather_requests(device, encoder, request_buffer); } @@ -280,8 +267,7 @@ where device: &wgpu::Device, encoder: &mut vxls_profiler::ScopeEncoder, insertion: &vxls_voxel_cache::insertion::CacheInsertionData, - ) - { + ) { self.fixed_structure_table .validate_insertion(device, encoder, insertion); } @@ -291,8 +277,7 @@ where encoder: &mut vxls_profiler::ScopeEncoder, cache_evictor: &vxls_voxel_cache::eviction::CacheEvictor, invalid_timestamp: u32, - ) - { + ) { self.fixed_structure_table .invalidate(encoder, cache_evictor, invalid_timestamp); } diff --git a/crates/vxls-voxel-cache/src/attributes.rs b/crates/vxls-voxel-cache/src/attributes.rs index 75798aa..9624975 100644 --- a/crates/vxls-voxel-cache/src/attributes.rs +++ b/crates/vxls-voxel-cache/src/attributes.rs @@ -6,22 +6,19 @@ use wgpu::Buffer; use vxls_profiler::memory_profiler; /// Contains instanciated gpu buffers to hold data for cache attributes -pub struct CacheAttributes -{ +pub struct CacheAttributes { attribute_buffers: Vec, bind_group_layout: wgpu::BindGroupLayout, bind_group: wgpu::BindGroup, } -impl CacheAttributes -{ +impl CacheAttributes { pub fn from_attribute_layout( device: &mut memory_profiler::Device, layout: &AttributesLayout, page_count: usize, - ) -> Self - { + ) -> Self { let attribute_buffers = layout .attributes .iter() @@ -61,8 +58,7 @@ impl CacheAttributes pub fn create_bind_group_layout( device: &wgpu::Device, layout: &AttributesLayout, - ) -> BindGroupLayout - { + ) -> BindGroupLayout { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("CacheAttributes::bind_group_layout"), entries: &[wgpu::BindGroupLayoutEntry { @@ -81,18 +77,15 @@ impl CacheAttributes }) } - 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 } } @@ -102,8 +95,7 @@ pub fn create_attributes_buffer_profiled( attribute_descriptor: &AttributeDescriptor, page_count: usize, usage: wgpu::BufferUsages, -) -> wgpu::Buffer -{ +) -> wgpu::Buffer { device.create_buffer(&wgpu::BufferDescriptor { label: Some( format!( @@ -124,8 +116,7 @@ pub fn create_attributes_buffer( attribute_descriptor: &AttributeDescriptor, page_count: usize, usage: wgpu::BufferUsages, -) -> wgpu::Buffer -{ +) -> wgpu::Buffer { device.create_buffer(&wgpu::BufferDescriptor { label: Some( format!( diff --git a/crates/vxls-voxel-cache/src/eviction.rs b/crates/vxls-voxel-cache/src/eviction.rs index 1d9911d..afa3f3f 100644 --- a/crates/vxls-voxel-cache/src/eviction.rs +++ b/crates/vxls-voxel-cache/src/eviction.rs @@ -20,8 +20,7 @@ use vxls_profiler::{self}; /// 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 -{ +pub struct CacheEvictor { page_count: usize, /// Contains a u32 timestamp per page, so that we know when a page was last used @@ -48,14 +47,12 @@ pub struct CacheEvictor 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, @@ -213,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 } } diff --git a/crates/vxls-voxel-cache/src/insertion.rs b/crates/vxls-voxel-cache/src/insertion.rs index 4852b03..138e35c 100644 --- a/crates/vxls-voxel-cache/src/insertion.rs +++ b/crates/vxls-voxel-cache/src/insertion.rs @@ -56,57 +56,38 @@ where /// Errors reported while uploading a producer attribute slice into /// [`CacheInsertionData`]. #[derive(Clone, Debug, PartialEq, Eq)] -pub enum AttributeUploadError -{ +pub enum AttributeUploadError { /// The slice is not a whole number of pages. - NotWholePages - { - voxel_count: usize, children: usize - }, + NotWholePages { voxel_count: usize, children: usize }, /// The slice does not fit in this insertion batch. - TooManyVoxels - { - voxel_count: usize, capacity: usize - }, + TooManyVoxels { voxel_count: usize, capacity: usize }, /// The producer declares more attributes than the cache layout has. - MissingCacheAttribute - { - index: usize - }, + MissingCacheAttribute { index: usize }, /// The producer attribute index is out of bounds. - AttributeIndexOutOfBounds - { - index: usize - }, + AttributeIndexOutOfBounds { index: usize }, /// The cache attribute is not `External`, so insertion will not copy it. - NotExternal - { - index: usize - }, + NotExternal { index: usize }, /// Declared word counts disagree. - WordCountMismatch - { + WordCountMismatch { index: usize, producer: u32, cache: u32, }, /// Declared labels disagree (only checked when the cache label is present). - LabelMismatch - { + LabelMismatch { index: usize, producer: &'static str, cache: Option<&'static str>, }, /// A `get_attr` implementation returned the wrong number of bytes. - BadAttributeBytes - { + BadAttributeBytes { index: usize, expected: usize, actual: usize, @@ -118,18 +99,15 @@ pub fn validate_voxel_count( voxel_count: usize, children: usize, capacity: usize, -) -> Result<(), AttributeUploadError> -{ - if !voxel_count.is_multiple_of(children) - { +) -> Result<(), AttributeUploadError> { + if !voxel_count.is_multiple_of(children) { return Err(AttributeUploadError::NotWholePages { voxel_count, children, }); } - if voxel_count > capacity - { + if voxel_count > capacity { return Err(AttributeUploadError::TooManyVoxels { voxel_count, capacity, @@ -146,23 +124,18 @@ pub fn validate_voxel_count( pub fn collect_attribute_bytes( voxels: &[A], index: usize, -) -> Result, AttributeUploadError> -{ - let Some(descriptor) = A::LAYOUT.attributes.get(index) - else - { +) -> Result, AttributeUploadError> { + let Some(descriptor) = A::LAYOUT.attributes.get(index) else { return Err(AttributeUploadError::AttributeIndexOutOfBounds { index }); }; let expected = descriptor.word_count as usize * size_of::(); let mut bytes = Vec::with_capacity(voxels.len() * expected); - for voxel in voxels - { + for voxel in voxels { let attribute = voxel.get_attr(index); - if attribute.len() != expected - { + if attribute.len() != expected { return Err(AttributeUploadError::BadAttributeBytes { index, expected, @@ -180,8 +153,7 @@ impl CacheInsertionData where [(); N * N * N]:, { - pub fn new(device: &wgpu::Device, max_page_count: usize, layout: &AttributesLayout) -> Self - { + 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, @@ -330,8 +302,7 @@ where pub fn create_bind_group_layout( device: &wgpu::Device, layout: Option<&AttributesLayout>, - ) -> BindGroupLayout - { + ) -> BindGroupLayout { let storage_entry = |binding: u32| wgpu::BindGroupLayoutEntry { binding, visibility: ShaderStages::COMPUTE, @@ -353,8 +324,7 @@ where storage_entry(6), // valid count ]; - if let Some(layout) = layout - { + if let Some(layout) = layout { entries.push(wgpu::BindGroupLayoutEntry { binding: 7, visibility: ShaderStages::COMPUTE, @@ -373,82 +343,67 @@ where }) } - pub fn bind_group(&self) -> &wgpu::BindGroup - { + pub fn bind_group(&self) -> &wgpu::BindGroup { &self.bind_group } - pub fn bind_group_no_attributes(&self) -> &wgpu::BindGroup - { + pub fn bind_group_no_attributes(&self) -> &wgpu::BindGroup { &self.bind_group_no_attributes } - pub fn page_count(&self) -> usize - { + pub fn page_count(&self) -> usize { self.max_page_count } - pub fn page_count_buffer(&self) -> &wgpu::Buffer - { + pub fn page_count_buffer(&self) -> &wgpu::Buffer { &self.page_count_buffer } - pub fn insertion_information_buffer(&self) -> &wgpu::Buffer - { + pub fn insertion_information_buffer(&self) -> &wgpu::Buffer { &self.insertion_information } - pub fn location_pages_buffer(&self) -> &wgpu::Buffer - { + pub fn location_pages_buffer(&self) -> &wgpu::Buffer { &self.location_pages } - pub fn destination_indices_buffer(&self) -> &wgpu::Buffer - { + pub fn destination_indices_buffer(&self) -> &wgpu::Buffer { &self.destination_indices } - pub fn insertion_parents_buffer(&self) -> &wgpu::Buffer - { + pub fn insertion_parents_buffer(&self) -> &wgpu::Buffer { &self.insertion_parents } - pub fn valid_indices_buffer(&self) -> &wgpu::Buffer - { + pub fn valid_indices_buffer(&self) -> &wgpu::Buffer { &self.valid_indices } - pub fn valid_count_buffer(&self) -> &wgpu::Buffer - { + pub fn valid_count_buffer(&self) -> &wgpu::Buffer { &self.valid_count } - pub fn attributes_buffers(&self) -> &[wgpu::Buffer] - { + pub fn attributes_buffers(&self) -> &[wgpu::Buffer] { &self.attributes } /// The layout this insertion data was created from. - pub fn layout(&self) -> &AttributesLayout - { + pub fn layout(&self) -> &AttributesLayout { &self.layout } /// Number of attribute buffers in this insertion batch. - pub fn attribute_count(&self) -> usize - { + 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> - { + 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 - { + pub fn attribute_capacity(&self) -> usize { self.max_page_count * N * N * N } @@ -464,10 +419,8 @@ where &self, queue: &wgpu::Queue, voxels: &[A], - ) -> Result - { - if A::LAYOUT != self.layout - { + ) -> Result { + if A::LAYOUT != self.layout { return Err(AttributeUploadError::LabelMismatch { index: 0, producer: "..", @@ -476,13 +429,11 @@ where } validate_voxel_count(voxels.len(), N * N * N, self.attribute_capacity())?; - if voxels.is_empty() - { + if voxels.is_empty() { return Ok(0); } - for index in 0..A::LAYOUT.len() - { + for index in 0..A::LAYOUT.len() { let bytes = collect_attribute_bytes(voxels, index)?; queue.write_buffer(&self.attributes[index], 0, &bytes); } @@ -492,8 +443,7 @@ where } #[cfg(test)] -mod tests -{ +mod tests { use super::*; use vxls_attributes::Attribute; @@ -502,18 +452,14 @@ mod tests #[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)] #[repr(C)] - struct TestAttributes - { + struct TestAttributes { color: u32, normal: [f32; 3], } - impl Attribute for TestAttributes - { - fn average(attributes: &[Self]) -> Self - { - if attributes.is_empty() - { + impl Attribute for TestAttributes { + fn average(attributes: &[Self]) -> Self { + if attributes.is_empty() { return Self::default(); } @@ -536,27 +482,22 @@ mod tests } } - impl Attributes for TestAttributes - { + 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 - { + 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 - { + 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"), @@ -565,8 +506,7 @@ mod tests } #[test] - fn collect_attribute_bytes_orders_by_voxel() - { + fn collect_attribute_bytes_orders_by_voxel() { let voxels = [ TestAttributes { color: 1, @@ -594,8 +534,7 @@ mod tests } #[test] - fn voxel_counts_must_be_whole_pages_within_capacity() - { + 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), diff --git a/crates/vxls-voxel-cache/src/lib.rs b/crates/vxls-voxel-cache/src/lib.rs index b9f002b..d43305e 100644 --- a/crates/vxls-voxel-cache/src/lib.rs +++ b/crates/vxls-voxel-cache/src/lib.rs @@ -35,17 +35,14 @@ pub mod structure; pub mod tables; /// Stores some ressources that can be reused throughout the modules of the cache -struct CacheRessources -{ +struct CacheRessources { scratch_buffer: wgpu::Buffer, scratch_buffer_bind_group: wgpu::BindGroup, radix_sorter: RadixSorter, } -impl CacheRessources -{ - pub fn new(device: &mut memory_profiler::Device, page_count: usize) -> Self - { +impl CacheRessources { + 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, @@ -67,8 +64,7 @@ impl CacheRessources } } - 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, @@ -76,8 +72,7 @@ impl CacheRessources ) } - pub fn scratch_buffer_bind_group(&self) -> &wgpu::BindGroup - { + pub fn scratch_buffer_bind_group(&self) -> &wgpu::BindGroup { &self.scratch_buffer_bind_group } } @@ -145,8 +140,7 @@ where page_count: usize, max_requests: usize, attributes_layout: &AttributesLayout, - ) -> Self - { + ) -> Self { let mut cache_memory_profile = MemoryProfile::new("VoxelCache"); let mut mem_device = cache_memory_profile.begin(device); @@ -208,8 +202,7 @@ where device: &Device, encoder: &mut ScopeEncoder, request_buffer: &CacheRequestBuffer, - ) - { + ) { vxls_profiler::begin_scope!(encoder, "gather_requests"); self.request_handler.sort_requests( @@ -242,8 +235,7 @@ where device: &Device, encoder: &mut ScopeEncoder, insertions: &mut [&mut VoxelCacheInsertion], - ) - { + ) { vxls_profiler::begin_scope!(encoder, "insertion"); let new_timestamp = self.frame_timestamp + 1; @@ -256,16 +248,12 @@ where // 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) => - { + 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) => - { + VoxelCacheInsertion::InternalRequest(cache_insertion_data) => { self.cache_insertion_pass.encode_validation( device, &mut encoder, @@ -278,13 +266,10 @@ where } } - for insertion in insertions.iter() - { - match insertion - { + 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, @@ -299,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); } } @@ -316,10 +299,8 @@ where ); // Write internal requests pointers - for insertion in insertions.iter_mut() - { - if let VoxelCacheInsertion::InternalRequest(insertion) = insertion - { + for insertion in insertions.iter_mut() { + if let VoxelCacheInsertion::InternalRequest(insertion) = insertion { self.write_pointers_pass .encode(&mut encoder, device, &self.structure, insertion); } @@ -329,8 +310,7 @@ where self.frame_timestamp = new_timestamp; } - pub fn current_timestamp(&self) -> u32 - { + pub fn current_timestamp(&self) -> u32 { self.frame_timestamp } @@ -340,8 +320,7 @@ where attributes: &CacheAttributes, request_handler: &CacheRequestHandler, 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"), @@ -427,24 +406,20 @@ where (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 - { + pub fn size(&self) -> usize { self.page_count } } diff --git a/crates/vxls-voxel-cache/src/pipelines.rs b/crates/vxls-voxel-cache/src/pipelines.rs index 0db31f6..ce2f56b 100644 --- a/crates/vxls-voxel-cache/src/pipelines.rs +++ b/crates/vxls-voxel-cache/src/pipelines.rs @@ -67,8 +67,7 @@ impl WriteRequestsPass where [(); N * N * N]:, { - pub fn new(device: &Device, page_count: usize, cache_layout: &AttributesLayout) -> Self - { + pub fn new(device: &Device, page_count: usize, cache_layout: &AttributesLayout) -> Self { // Binds // - structure // - request buffer @@ -117,8 +116,7 @@ where cache_structure: &CacheStructure, cache_request_handler: &CacheRequestHandler, target_request_buffer: &CacheRequestBuffer, - ) - { + ) { vxls_profiler::begin_scope!(encoder, "WriteRequests"); let indirect_dispatch_buffer = self.indirect_buffer.workgroup_count( @@ -177,8 +175,7 @@ impl CacheInsertionPass where [(); N * N * N]:, { - pub fn new(device: &Device, page_count: usize, layout: &AttributesLayout) -> Self - { + pub fn new(device: &Device, page_count: usize, layout: &AttributesLayout) -> Self { // Binds // - structure // - request buffer @@ -279,8 +276,7 @@ where cache_structure: &CacheStructure, insertion_data: &CacheInsertionData, cache_evictor: &CacheEvictor, - ) - { + ) { vxls_profiler::begin_scope!(encoder, "PageInsertionValidation"); let indirect_write_dispatch = self.indirect_dispatcher.workgroup_count( @@ -315,8 +311,7 @@ where insertion_data: &CacheInsertionData, cache_evictor: &CacheEvictor, timestamp: u32, - ) - { + ) { vxls_profiler::begin_scope!(encoder, "PageInsertion"); let indirect_write_dispatch = self.indirect_dispatcher.workgroup_count( @@ -362,8 +357,7 @@ impl CacheInvalidationPass where [(); N * N * N]:, { - pub fn new(device: &Device, page_count: usize, layout: &AttributesLayout) -> Self - { + pub fn new(device: &Device, page_count: usize, layout: &AttributesLayout) -> Self { // Binds // - structure // - request buffer @@ -411,8 +405,7 @@ where cache_structure: &CacheStructure, cache_evictor: &CacheEvictor, timestamp: u32, - ) - { + ) { vxls_profiler::begin_scope!(encoder, "CacheInvalidation"); let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { @@ -443,8 +436,7 @@ impl WritePointersPass where [(); N * N * N]:, { - pub fn new(device: &Device, page_count: usize, layout: &AttributesLayout) -> Self - { + pub fn new(device: &Device, page_count: usize, layout: &AttributesLayout) -> Self { let bindings = [ // To find where pages are pointing Some(&CacheStructure::::create_bind_group_layout(device)), @@ -489,8 +481,7 @@ where device: &Device, cache_structure: &CacheStructure, cache_insertion_data: &CacheInsertionData, - ) - { + ) { vxls_profiler::begin_scope!(encoder, "WritePointers"); let indirect_buffer = self.indirect_buffer.workgroup_count( diff --git a/crates/vxls-voxel-cache/src/requests.rs b/crates/vxls-voxel-cache/src/requests.rs index 6a81e84..1b4b423 100644 --- a/crates/vxls-voxel-cache/src/requests.rs +++ b/crates/vxls-voxel-cache/src/requests.rs @@ -23,8 +23,7 @@ use vxls_profiler::memory_profiler; use vxls_profiler::{self}; /// Records, handles, and produces a list of requested data inside the cache -pub struct CacheRequestHandler -{ +pub struct CacheRequestHandler { /// 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, @@ -58,8 +57,7 @@ pub struct CacheRequestHandler } /// 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 @@ -76,10 +74,8 @@ pub struct CacheRequestBuffer bind_group: wgpu::BindGroup, } -impl CacheRequestHandler -{ - pub fn new(device: &mut memory_profiler::Device, page_count: usize, max_selected: u32) -> Self - { +impl CacheRequestHandler { + 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, @@ -175,8 +171,7 @@ impl CacheRequestHandler } } - fn create_gather_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout - { + fn create_gather_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout { let entry = |binding: u32, read_only: bool| wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, @@ -211,8 +206,7 @@ impl CacheRequestHandler ressources: &CacheRessources, encoder: &mut ScopeEncoder, k: u32, - ) - { + ) { vxls_profiler::begin_scope!(encoder, "RequestHandler::sort_requests"); // Select the most requested pages. @@ -297,8 +291,7 @@ impl CacheRequestHandler ); } - 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, @@ -306,24 +299,20 @@ impl CacheRequestHandler ) } - 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) - { + pub fn reset(&self, encoder: &mut ScopeEncoder) { let mut compute_pass = encoder.begin_profiled_compute_pass("CacheRequestHandler::reset"); compute_pass.set_pipeline(&self.reset_pass); @@ -332,11 +321,9 @@ impl CacheRequestHandler } } -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 @@ -378,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, @@ -387,8 +373,7 @@ impl CacheRequestBuffer ) } - pub fn bind_group(&self) -> &BindGroup - { + pub fn bind_group(&self) -> &BindGroup { &self.bind_group } @@ -399,8 +384,7 @@ impl CacheRequestBuffer device: &Device, queue: &wgpu::Queue, callback: F, - ) - { + ) { // 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))); @@ -456,18 +440,15 @@ impl CacheRequestBuffer } } -struct RequestMapState -{ +struct RequestMapState { request_count: Option, request_infos: Option>, request_metas: Option>, callback: F, } -impl RequestMapState -{ - pub fn new(callback: F) -> Self - { +impl RequestMapState { + pub fn new(callback: F) -> Self { Self { request_count: None, request_infos: None, @@ -476,8 +457,7 @@ impl Re } } - fn try_callback(&mut self) - { + 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) { @@ -488,20 +468,17 @@ impl Re } } - 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) - { + pub fn set_request_infos(&mut self, request_infos: Vec) { self.request_infos = Some(request_infos); self.try_callback(); } - pub fn set_request_metas(&mut self, request_metas: Vec) - { + pub fn set_request_metas(&mut self, request_metas: Vec) { self.request_metas = Some(request_metas); self.try_callback(); } diff --git a/crates/vxls-voxel-cache/src/schema.rs b/crates/vxls-voxel-cache/src/schema.rs index 05c736e..d659992 100644 --- a/crates/vxls-voxel-cache/src/schema.rs +++ b/crates/vxls-voxel-cache/src/schema.rs @@ -26,22 +26,17 @@ use bytemuck::Zeroable; #[repr(transparent)] pub struct CachePointer(u32); -impl CachePointer -{ +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>) -> Self - { - CachePointer(match value - { - Some(available) => match available - { - Some(pointer) => - { + pub fn new(value: Option>) -> Self { + CachePointer(match value { + Some(available) => match available { + Some(pointer) => { assert_eq!( pointer >> 30, 0, @@ -55,17 +50,14 @@ impl CachePointer }) } - pub fn as_option(&self) -> Option> - { + pub fn as_option(&self) -> Option> { let subdivisable = (self.0 >> 31) != 0; let available = ((self.0 >> 30) & 1) != 0; let pointer = self.0 & 0x3FFFFFFF; - match (subdivisable, available) - { + match (subdivisable, available) { (false, true) => panic!("Invalid cache pointer. (not subdivisable and available)"), - (false, _) if pointer != 0 => - { + (false, _) if pointer != 0 => { panic!("Invalid cache pointer. (non null unsubdivisable pointer)") } (false, _) => None, @@ -75,10 +67,8 @@ impl CachePointer } } -impl From for CachePointer -{ - fn from(value: u32) -> Self - { +impl From for CachePointer { + fn from(value: u32) -> Self { CachePointer(value) } } @@ -116,13 +106,11 @@ pub const NO_TABLE_SLOT: u32 = u32::MAX; /// 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 struct StructureAnchor { pub words: [u32; ANCHOR_WORDS], } -impl StructureAnchor -{ +impl StructureAnchor { /// Convenience anchor used by tests and by tables that do not need a /// distinguishable identity at startup. #[allow(dead_code)] @@ -131,15 +119,13 @@ impl StructureAnchor }; /// Table-defined helper for world-position anchors: `(x, y, z, version)`. - pub fn from_world(x: i32, y: i32, z: i32, version: u32) -> Self - { + 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) - { + pub fn world(self) -> (i32, i32, i32, u32) { ( self.words[0] as i32, self.words[1] as i32, @@ -165,8 +151,7 @@ pub struct StructureLocator(pub u32); /// particular request #[derive(Debug, Clone, Copy, Zeroable, Pod)] #[repr(C)] -pub struct LocationPage -{ +pub struct LocationPage { /// Identifier for locating this particular node within the structure pub node_id: StructureLocator, @@ -195,8 +180,7 @@ pub struct LocationPage #[repr(C)] pub struct DepthPage(pub u32); -impl DepthPage -{ +impl DepthPage { pub const PAGE_UNUSED: Self = DepthPage(u32::MAX); } @@ -205,8 +189,7 @@ impl DepthPage /// children is needed #[derive(Debug, Clone, Copy, Zeroable, Pod)] #[repr(C)] -pub struct RequestInformation -{ +pub struct RequestInformation { /// Identifier for locating this particular node within the structure pub node_id: StructureLocator, @@ -226,8 +209,7 @@ pub struct RequestInformation /// Metainformation kept along each request, to know which node made the demand #[derive(Debug, Clone, Copy, Zeroable, Pod)] #[repr(C)] -pub struct RequestMeta -{ +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, @@ -252,16 +234,14 @@ pub const NO_PARENT_PAGE: u32 = u32::MAX; #[repr(transparent)] pub struct InsertionParentKind(u32); -impl InsertionParentKind -{ +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 - { + pub fn raw(self) -> u32 { self.0 } } @@ -272,8 +252,7 @@ impl InsertionParentKind /// 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 -{ +pub struct InsertionParent { /// [`InsertionParentKind`]. pub kind: u32, @@ -300,16 +279,14 @@ pub struct InsertionParent pub table_slot: u32, } -impl InsertionParent -{ +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 { Self { kind: InsertionParentKind::INTERNAL.raw(), page_index: meta.page_index, @@ -323,8 +300,7 @@ impl InsertionParent } /// Parent information for the root of an external structure. - pub fn external(producer_id: ProducerId, 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, @@ -337,13 +313,11 @@ impl InsertionParent } } - pub fn is_external(&self) -> bool - { + pub fn is_external(&self) -> bool { self.kind == InsertionParentKind::EXTERNAL.raw() } - pub fn is_internal(&self) -> bool - { + pub fn is_internal(&self) -> bool { self.kind == InsertionParentKind::INTERNAL.raw() } } @@ -361,22 +335,18 @@ impl InsertionParent #[repr(transparent)] pub struct ChildInformation(u32); -impl ChildInformation -{ +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 - { + pub fn new(subdivisable: bool, occupied: bool) -> Self { let mut n = Self::NONE; - if subdivisable - { + if subdivisable { n = n | Self::SUBDIVISABLE; } - if occupied - { + if occupied { n = n | Self::OCCUPIED; } @@ -384,12 +354,10 @@ impl ChildInformation } } -impl BitOr for ChildInformation -{ +impl BitOr for ChildInformation { type Output = Self; - fn bitor(self, rhs: Self) -> Self::Output - { + fn bitor(self, rhs: Self) -> Self::Output { Self(self.0 | rhs.0) } } @@ -409,13 +377,11 @@ where unsafe impl Pod for InsertionInformation where [(); N * N * N]: {} #[cfg(test)] -mod tests -{ +mod tests { use super::*; #[test] - fn wire_layout_sizes_are_stable() - { + fn wire_layout_sizes_are_stable() { assert_eq!(size_of::(), 16); assert_eq!(size_of::(), 32); assert_eq!(size_of::(), 24); @@ -424,8 +390,7 @@ mod tests } #[test] - fn anchor_world_round_trips_negative_coordinates() - { + fn anchor_world_round_trips_negative_coordinates() { let anchor = StructureAnchor::from_world(-17, 42, -3, 7); assert_eq!(anchor.world(), (-17, 42, -3, 7)); } diff --git a/crates/vxls-voxel-cache/src/structure.rs b/crates/vxls-voxel-cache/src/structure.rs index 8173b3d..3011b48 100644 --- a/crates/vxls-voxel-cache/src/structure.rs +++ b/crates/vxls-voxel-cache/src/structure.rs @@ -31,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::>() * page_count) as u64, @@ -74,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 } } diff --git a/crates/vxls-voxel-cache/src/tables.rs b/crates/vxls-voxel-cache/src/tables.rs index 76e5aee..f9efdc2 100644 --- a/crates/vxls-voxel-cache/src/tables.rs +++ b/crates/vxls-voxel-cache/src/tables.rs @@ -46,8 +46,7 @@ macro_rules! include_table_wgsl { fn retired_anchors( old_anchors: &[StructureAnchor], new_anchors: &[StructureAnchor], -) -> Vec -{ +) -> Vec { use std::collections::HashSet; assert!( @@ -74,8 +73,7 @@ fn retired_anchors( /// keeps its stale anchor on the GPU until it is reused; the empty pointer keeps /// the tracer from ever treating it as live. #[allow(dead_code)] -struct SlotAllocator -{ +struct SlotAllocator { /// Slot-indexed liveness. `None` means the slot is free. slot_anchors: Vec>, @@ -89,10 +87,8 @@ struct SlotAllocator } #[allow(dead_code)] -impl SlotAllocator -{ - fn new(capacity: usize) -> Self - { +impl SlotAllocator { + fn new(capacity: usize) -> Self { assert!( capacity <= u32::MAX as usize, "structure table capacity exceeds the u32 slot index space" @@ -107,11 +103,9 @@ impl SlotAllocator } } - fn allocate(&mut self, anchor: StructureAnchor) -> Option - { + fn allocate(&mut self, anchor: StructureAnchor) -> Option { // Allocating an anchor that is already live is idempotent. - if let Some(&slot) = self.anchor_slot.get(&anchor) - { + if let Some(&slot) = self.anchor_slot.get(&anchor) { return Some(slot); } @@ -122,8 +116,7 @@ impl SlotAllocator Some(slot) } - fn release(&mut self, slot: u32) -> Option - { + fn release(&mut self, slot: u32) -> Option { let anchor = self.slot_anchors.get_mut(slot as usize)?.take()?; self.anchor_slot.remove(&anchor); self.live -= 1; @@ -132,11 +125,9 @@ impl SlotAllocator } /// Extends the slot space. Existing allocations keep their slot indices. - fn grow(&mut self, new_capacity: usize) - { + fn grow(&mut self, new_capacity: usize) { let old_capacity = self.slot_anchors.len(); - if new_capacity <= old_capacity - { + if new_capacity <= old_capacity { return; } @@ -152,35 +143,29 @@ impl SlotAllocator .extend((old_capacity..new_capacity).rev().map(|slot| slot as u32)); } - fn capacity(&self) -> usize - { + fn capacity(&self) -> usize { self.slot_anchors.len() } - fn live_count(&self) -> usize - { + fn live_count(&self) -> usize { self.live } - fn is_full(&self) -> bool - { + fn is_full(&self) -> bool { self.free.is_empty() } - fn is_live(&self, slot: u32) -> bool - { + fn is_live(&self, slot: u32) -> bool { self.slot_anchors .get(slot as usize) .is_some_and(|anchor| anchor.is_some()) } - fn slot_anchor(&self, slot: u32) -> Option - { + fn slot_anchor(&self, slot: u32) -> Option { self.slot_anchors.get(slot as usize).copied().flatten() } - fn slot_for_anchor(&self, anchor: &StructureAnchor) -> Option - { + fn slot_for_anchor(&self, anchor: &StructureAnchor) -> Option { self.anchor_slot.get(anchor).copied() } } @@ -196,8 +181,7 @@ impl SlotAllocator /// pipelines, indirect buffer) and size-dependent ones (buffers, bind groups, /// request handler, scratch resources). [`Self::resize`] rebuilds only the /// latter so external pipeline layouts stay valid. -struct StructureTableCore -{ +struct StructureTableCore { size: usize, #[allow(dead_code)] max_requests: u32, @@ -231,8 +215,7 @@ struct StructureTableCore raytrace_bind_group: wgpu::BindGroup, } -impl StructureTableCore -{ +impl StructureTableCore { fn new( device: &wgpu::Device, size: usize, @@ -240,8 +223,7 @@ impl StructureTableCore producer_id: u32, initial_anchors: &[StructureAnchor], initial_pointers: &[CachePointer], - ) -> Self - { + ) -> Self { assert_eq!(initial_anchors.len(), size); assert_eq!(initial_pointers.len(), size); @@ -422,10 +404,8 @@ impl StructureTableCore /// outside this type remain compatible. Any bind group obtained before the /// resize must be re-fetched. #[allow(dead_code)] - fn resize(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, new_size: usize) - { - if new_size <= self.size - { + fn resize(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, new_size: usize) { + if new_size <= self.size { return; } @@ -516,8 +496,7 @@ impl StructureTableCore self.raytrace_bind_group = raytrace_bind_group; } - fn write_anchor(&self, queue: &wgpu::Queue, slot: u32, anchor: StructureAnchor) - { + fn write_anchor(&self, queue: &wgpu::Queue, slot: u32, anchor: StructureAnchor) { queue.write_buffer( &self.anchors, slot as u64 * size_of::() as u64, @@ -526,8 +505,7 @@ impl StructureTableCore } #[allow(dead_code)] - fn write_pointer(&self, queue: &wgpu::Queue, slot: u32, pointer: CachePointer) - { + fn write_pointer(&self, queue: &wgpu::Queue, slot: u32, pointer: CachePointer) { queue.write_buffer( &self.pointers, slot as u64 * size_of::() as u64, @@ -540,8 +518,7 @@ impl StructureTableCore device: &wgpu::Device, encoder: &mut ScopeEncoder, request_buffer: &CacheRequestBuffer, - ) - { + ) { self.request_handler.sort_requests( device, &self.common_ressources, @@ -652,8 +629,7 @@ impl StructureTableCore encoder: &mut ScopeEncoder, cache_evictor: &CacheEvictor, invalid_timestamp: u32, - ) - { + ) { let mut invalidate_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("StructureTableCore::invalidate_pass"), timestamp_writes: None, @@ -667,29 +643,24 @@ impl StructureTableCore invalidate_pass.dispatch_workgroups(self.size.div_ceil(256) as u32, 1, 1); } - fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout - { + fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout { &self.raytrace_bind_group_layout } - fn raytrace_bind_group(&self) -> &wgpu::BindGroup - { + fn raytrace_bind_group(&self) -> &wgpu::BindGroup { &self.raytrace_bind_group } #[allow(dead_code)] - fn pointers_buffer(&self) -> &wgpu::Buffer - { + fn pointers_buffer(&self) -> &wgpu::Buffer { &self.pointers } - fn request_pages_buffer(&self) -> &wgpu::Buffer - { + fn request_pages_buffer(&self) -> &wgpu::Buffer { self.request_handler.request_pages_buffer() } - fn pointers_bind_group(&self) -> &wgpu::BindGroup - { + fn pointers_bind_group(&self) -> &wgpu::BindGroup { &self.pointers_bind_group } } @@ -697,23 +668,20 @@ impl StructureTableCore /// A structure table with a fixed length. /// /// Every slot is live and is kept in sync with [`Self::reassign_slots`]. -pub struct FixedStructureTable -{ +pub struct FixedStructureTable { core: StructureTableCore, /// Host mirror used to preserve identity across slot moves. slot_anchors: Vec, } -impl FixedStructureTable -{ +impl FixedStructureTable { /// Creates a static table with one distinct anchor per slot. /// /// Retained for callers that do not move slots; [`Self::new_with_anchors`] /// is the general constructor. #[allow(dead_code)] - pub fn new(device: &wgpu::Device, size: usize, max_requests: usize, producer_id: u32) -> Self - { + pub fn new(device: &wgpu::Device, size: usize, max_requests: usize, producer_id: u32) -> Self { let anchors = (0..size) .map(|slot| StructureAnchor { words: [slot as u32, 0, 0, 0], @@ -729,8 +697,7 @@ impl FixedStructureTable max_requests: usize, producer_id: u32, anchors: Vec, - ) -> Self - { + ) -> Self { assert_eq!(anchors.len(), size); let pointers = vec![CachePointer::new(Some(None)); size]; @@ -753,18 +720,15 @@ impl FixedStructureTable &mut self, queue: &wgpu::Queue, new_anchors: &[StructureAnchor], - ) -> Vec - { + ) -> Vec { assert_eq!(new_anchors.len(), self.core.size); let retired = retired_anchors(&self.slot_anchors, new_anchors); #[allow(clippy::needless_range_loop)] - for slot in 0..self.core.size - { + for slot in 0..self.core.size { let anchor = new_anchors[slot]; - if self.slot_anchors[slot] == anchor - { + if self.slot_anchors[slot] == anchor { continue; } @@ -777,8 +741,7 @@ impl FixedStructureTable /// Returns the current slot for an anchor, if it is in the table. #[allow(dead_code)] - pub fn slot_for_anchor(&self, anchor: &StructureAnchor) -> Option - { + pub fn slot_for_anchor(&self, anchor: &StructureAnchor) -> Option { self.slot_anchors .iter() .position(|candidate| candidate == anchor) @@ -786,8 +749,7 @@ impl FixedStructureTable } #[allow(dead_code)] - pub fn slot_anchor(&self, slot: u32) -> Option - { + pub fn slot_anchor(&self, slot: u32) -> Option { self.slot_anchors.get(slot as usize).copied() } @@ -796,8 +758,7 @@ impl FixedStructureTable device: &wgpu::Device, encoder: &mut ScopeEncoder, request_buffer: &CacheRequestBuffer, - ) - { + ) { self.core.gather_requests(device, encoder, request_buffer); } @@ -813,24 +774,20 @@ impl FixedStructureTable self.core.insert(device, encoder, insertion); } - pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout - { + pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout { self.core.raytrace_bind_group_layout() } - pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup - { + pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup { self.core.raytrace_bind_group() } #[allow(dead_code)] - pub fn pointers_buffer(&self) -> &wgpu::Buffer - { + pub fn pointers_buffer(&self) -> &wgpu::Buffer { self.core.pointers_buffer() } - pub fn pointers_bind_group(&self) -> &wgpu::BindGroup - { + pub fn pointers_bind_group(&self) -> &wgpu::BindGroup { self.core.pointers_bind_group() } } @@ -847,23 +804,20 @@ impl FixedStructureTable /// size-dependent GPU resources, so it must happen between frames; any bind /// group obtained from the table before growth must be re-fetched. #[allow(dead_code)] -pub struct DynamicStructureTable -{ +pub struct DynamicStructureTable { core: StructureTableCore, allocator: SlotAllocator, } #[allow(dead_code)] -impl DynamicStructureTable -{ +impl DynamicStructureTable { /// Creates a table with `capacity` free slots. pub fn new( device: &wgpu::Device, capacity: usize, max_requests: usize, producer_id: u32, - ) -> Self - { + ) -> Self { // Free slots keep a stale (here zero) anchor; only the empty pointer is // meaningful for liveness. let anchors = vec![StructureAnchor::ZERO; capacity]; @@ -888,8 +842,7 @@ impl DynamicStructureTable /// Returns `None` if the table is full. Allocating an anchor that is already /// live returns its existing slot. The slot is marked subdivisible but not /// available, so the cache emits a root request for it. - pub fn allocate(&mut self, queue: &wgpu::Queue, anchor: StructureAnchor) -> Option - { + pub fn allocate(&mut self, queue: &wgpu::Queue, anchor: StructureAnchor) -> Option { let slot = self.allocator.allocate(anchor)?; self.core.write_anchor(queue, slot, anchor); @@ -908,8 +861,7 @@ impl DynamicStructureTable /// /// This does not free cache pages: the root becomes unreachable and its /// pages are reclaimed by the normal LRU eviction. - pub fn release(&mut self, queue: &wgpu::Queue, slot: u32) -> Option - { + pub fn release(&mut self, queue: &wgpu::Queue, slot: u32) -> Option { let anchor = self.allocator.release(slot)?; self.core .write_pointer(queue, slot, CachePointer::new(None)); @@ -920,16 +872,14 @@ impl DynamicStructureTable /// /// Capacity doubles from the current value until it reaches `min_capacity`. /// Must be called between frames. - pub fn reserve(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, min_capacity: usize) - { + pub fn reserve(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, min_capacity: usize) { assert!( min_capacity <= u32::MAX as usize, "structure table capacity exceeds the u32 slot index space" ); let new_capacity = self.grown_capacity(min_capacity); - if new_capacity <= self.capacity() - { + if new_capacity <= self.capacity() { return; } @@ -938,8 +888,7 @@ impl DynamicStructureTable } /// Doubles the table capacity. Must be called between frames. - pub fn grow(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) - { + pub fn grow(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) { let max = u32::MAX as usize; let min_capacity = self.capacity().saturating_mul(2).min(max).max(1); self.reserve(device, queue, min_capacity); @@ -951,54 +900,44 @@ impl DynamicStructureTable device: &wgpu::Device, queue: &wgpu::Queue, anchor: StructureAnchor, - ) -> Option - { - if let Some(slot) = self.allocator.slot_for_anchor(&anchor) - { + ) -> Option { + if let Some(slot) = self.allocator.slot_for_anchor(&anchor) { return Some(slot); } - if self.allocator.is_full() - { + if self.allocator.is_full() { self.grow(device, queue); } self.allocate(queue, anchor) } - fn grown_capacity(&self, min_capacity: usize) -> usize - { + fn grown_capacity(&self, min_capacity: usize) -> usize { let max = u32::MAX as usize; let mut capacity = self.capacity().max(1); - while capacity < min_capacity - { + while capacity < min_capacity { capacity = capacity.saturating_mul(2).min(max); } capacity } - pub fn capacity(&self) -> usize - { + pub fn capacity(&self) -> usize { self.allocator.capacity() } - pub fn live_count(&self) -> usize - { + pub fn live_count(&self) -> usize { self.allocator.live_count() } - pub fn is_live(&self, slot: u32) -> bool - { + pub fn is_live(&self, slot: u32) -> bool { self.allocator.is_live(slot) } - pub fn slot_anchor(&self, slot: u32) -> Option - { + pub fn slot_anchor(&self, slot: u32) -> Option { self.allocator.slot_anchor(slot) } - pub fn slot_for_anchor(&self, anchor: &StructureAnchor) -> Option - { + pub fn slot_for_anchor(&self, anchor: &StructureAnchor) -> Option { self.allocator.slot_for_anchor(anchor) } @@ -1007,8 +946,7 @@ impl DynamicStructureTable device: &wgpu::Device, encoder: &mut ScopeEncoder, request_buffer: &CacheRequestBuffer, - ) - { + ) { self.core.gather_requests(device, encoder, request_buffer); } @@ -1024,29 +962,24 @@ impl DynamicStructureTable self.core.insert(device, encoder, insertion); } - pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout - { + pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout { self.core.raytrace_bind_group_layout() } - pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup - { + pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup { self.core.raytrace_bind_group() } #[allow(dead_code)] - pub fn pointers_buffer(&self) -> &wgpu::Buffer - { + pub fn pointers_buffer(&self) -> &wgpu::Buffer { self.core.pointers_buffer() } - pub fn request_pages_buffer(&self) -> &wgpu::Buffer - { + pub fn request_pages_buffer(&self) -> &wgpu::Buffer { self.core.request_pages_buffer() } - pub fn pointers_bind_group(&self) -> &wgpu::BindGroup - { + pub fn pointers_bind_group(&self) -> &wgpu::BindGroup { self.core.pointers_bind_group() } } @@ -1060,8 +993,7 @@ where device: &wgpu::Device, encoder: &mut ScopeEncoder, insertion: &CacheInsertionData, - ) - { + ) { self.core.validate_insertion(device, encoder, insertion); } @@ -1070,8 +1002,7 @@ where encoder: &mut ScopeEncoder, cache_evictor: &CacheEvictor, invalid_timestamp: u32, - ) - { + ) { self.core .invalidate(encoder, cache_evictor, invalid_timestamp); } @@ -1086,8 +1017,7 @@ where device: &wgpu::Device, encoder: &mut ScopeEncoder, insertion: &CacheInsertionData, - ) - { + ) { self.core.validate_insertion(device, encoder, insertion); } @@ -1096,26 +1026,22 @@ where encoder: &mut ScopeEncoder, cache_evictor: &CacheEvictor, invalid_timestamp: u32, - ) - { + ) { self.core .invalidate(encoder, cache_evictor, invalid_timestamp); } } #[cfg(test)] -mod tests -{ +mod tests { use super::*; - fn anchor(x: i32) -> StructureAnchor - { + fn anchor(x: i32) -> StructureAnchor { StructureAnchor::from_world(x, 0, 0, 0) } #[test] - fn permuted_anchors_retire_nothing() - { + fn permuted_anchors_retire_nothing() { let old_anchors = [anchor(0), anchor(1), anchor(2)]; let new_anchors = [anchor(2), anchor(0), anchor(1)]; @@ -1125,8 +1051,7 @@ mod tests } #[test] - fn leaving_anchor_retires() - { + fn leaving_anchor_retires() { let old_anchors = [anchor(0), anchor(1)]; let new_anchors = [anchor(1), anchor(2)]; @@ -1136,8 +1061,7 @@ mod tests } #[test] - fn reentering_anchor_is_the_same_identity() - { + fn reentering_anchor_is_the_same_identity() { let first = retired_anchors(&[anchor(0)], &[anchor(5)]); assert_eq!(first, vec![anchor(0)]); @@ -1147,14 +1071,12 @@ mod tests #[test] #[should_panic(expected = "a structure table must not expose two live slots")] - fn duplicate_live_anchors_are_rejected() - { + fn duplicate_live_anchors_are_rejected() { let _ = retired_anchors(&[], &[anchor(0), anchor(0)]); } #[test] - fn allocator_allocates_low_indices_first() - { + fn allocator_allocates_low_indices_first() { let mut allocator = SlotAllocator::new(4); assert_eq!(allocator.allocate(anchor(0)), Some(0)); @@ -1165,8 +1087,7 @@ mod tests } #[test] - fn allocator_reuses_released_slots() - { + fn allocator_reuses_released_slots() { let mut allocator = SlotAllocator::new(2); let a = allocator.allocate(anchor(0)).unwrap(); let b = allocator.allocate(anchor(1)).unwrap(); @@ -1180,8 +1101,7 @@ mod tests } #[test] - fn allocator_is_idempotent_for_live_anchors() - { + fn allocator_is_idempotent_for_live_anchors() { let mut allocator = SlotAllocator::new(2); let slot = allocator.allocate(anchor(0)).unwrap(); @@ -1190,8 +1110,7 @@ mod tests } #[test] - fn allocator_release_unknown_slot_is_none() - { + fn allocator_release_unknown_slot_is_none() { let mut allocator = SlotAllocator::new(2); assert_eq!(allocator.release(0), None); @@ -1199,8 +1118,7 @@ mod tests } #[test] - fn allocator_tracks_liveness() - { + fn allocator_tracks_liveness() { let mut allocator = SlotAllocator::new(2); let slot = allocator.allocate(anchor(0)).unwrap(); @@ -1216,8 +1134,7 @@ mod tests } #[test] - fn allocator_grow_preserves_live_slots() - { + fn allocator_grow_preserves_live_slots() { let mut allocator = SlotAllocator::new(2); let a = allocator.allocate(anchor(0)).unwrap(); let b = allocator.allocate(anchor(1)).unwrap(); diff --git a/crates/vxls/src/camera.rs b/crates/vxls/src/camera.rs index 25a4ec9..ed7e536 100644 --- a/crates/vxls/src/camera.rs +++ b/crates/vxls/src/camera.rs @@ -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, } -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); diff --git a/crates/vxls/src/egui_renderer.rs b/crates/vxls/src/egui_renderer.rs index 2c28777..f2f57c0 100644 --- a/crates/vxls/src/egui_renderer.rs +++ b/crates/vxls/src/egui_renderer.rs @@ -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); } diff --git a/crates/vxls/src/main.rs b/crates/vxls/src/main.rs index 620c7f8..89a1480 100644 --- a/crates/vxls/src/main.rs +++ b/crates/vxls/src/main.rs @@ -23,6 +23,9 @@ use itertools::Itertools; use rand::random_range; use rayon::iter::IntoParallelRefIterator; use rayon::iter::ParallelIterator; +use vxls_production::sparse_tree::Color; +use vxls_production::sparse_tree::NTree; +use vxls_production::sparse_tree::load_ply; use wgpu::BindGroupLayout; use wgpu::BufferUsages; use wgpu::ComputePipeline; @@ -53,8 +56,6 @@ use winit::window::WindowId; use crate::camera::Camera; use crate::egui_renderer::EguiRenderer; use crate::producers::SdfGenerator; -use crate::sparse_tree::NTree; -use crate::sparse_tree::load_ply; use vxls_bvh::BvhHandle; use vxls_bvh::BvhObject; use vxls_bvh::BvhStructureTable; @@ -85,10 +86,8 @@ use vxls_voxel_cache::schema::LocationPage; mod camera; mod egui_renderer; mod producers; -mod sparse_tree; -enum DisplayTexture -{ +enum DisplayTexture { Target, Normal, Pos, @@ -105,8 +104,7 @@ where location_page: LocationPage, } -struct State -{ +struct State { instance: wgpu::Instance, window: Arc, device: wgpu::Device, @@ -161,15 +159,13 @@ struct State bvh_objs: Vec<(BvhHandle, Vec3)>, } -pub unsafe fn as_raw_bytes(slice: &[T]) -> &[u8] -{ +pub unsafe fn as_raw_bytes(slice: &[T]) -> &[u8] { let size = slice.len() * size_of::(); unsafe { std::slice::from_raw_parts(slice.as_ptr() as *const u8, size) } } #[derive(Clone, Copy)] -struct Immediates -{ +struct Immediates { view_proj: Mat4, cam_pos: Vec3, frame_timestamp: u32, @@ -185,18 +181,15 @@ struct Immediates #[derive(Debug, Clone, Copy, Zeroable, Pod)] #[repr(C)] -struct InstanceAttribute -{ +struct InstanceAttribute { x: f32, y: f32, z: f32, id: u32, } -impl State -{ - async fn new(display: OwnedDisplayHandle, window: Arc) -> State - { +impl State { + async fn new(display: OwnedDisplayHandle, window: Arc) -> State { let instance = wgpu::Instance::new(InstanceDescriptor { backends: wgpu::Backends::VULKAN, display: Some(Box::new(display)), @@ -365,7 +358,7 @@ impl State */ // Load dragon ply - let tree: NTree<4> = load_ply("../../dragon.txt"); + let tree: NTree<4, Color> = load_ply("../../dragon.txt"); // let mut arrays = vec![Color(0., 0., 0., 0.); 256 * 256 * 256]; // for ((x, y), z) in (0..256).cartesian_product(0..256).cartesian_product(0..256) // { @@ -425,8 +418,7 @@ impl State let mut bvh = BvhStructureTable::new(&device, 128, 128); let extent = Aabb::new(-10. * Vec3::ONE, 10. * Vec3::ONE); let mut bvh_objs = Vec::new(); - for _ in 0..1000 - { + for _ in 0..1000 { let transform = Mat4::from_rotation_translation( Quat::from_euler( glam::EulerRot::XYZ, @@ -742,15 +734,12 @@ impl State let request_queue_1 = request_queue.clone(); let (wakeup_tx, wakeup_rx) = std::sync::mpsc::channel(); std::thread::spawn(move || { - loop - { - if !wakeup_rx.recv().is_ok() - { + loop { + if !wakeup_rx.recv().is_ok() { break; } - loop - { + loop { // Try to get some work from the queue let mut work = vec![]; { @@ -762,8 +751,7 @@ impl State } } - if work.is_empty() - { + if work.is_empty() { break; } @@ -870,8 +858,7 @@ impl State width: u32, height: u32, format: wgpu::TextureFormat, - ) -> (Texture, TextureView) - { + ) -> (Texture, TextureView) { let texture = device.create_texture(&wgpu::TextureDescriptor { label: Some("Target texture"), size: Extent3d { @@ -891,8 +878,7 @@ impl State (texture, texture_view) } - fn create_target_texture(device: &Device, width: u32, height: u32) -> (Texture, TextureView) - { + fn create_target_texture(device: &Device, width: u32, height: u32) -> (Texture, TextureView) { let texture = device.create_texture(&wgpu::TextureDescriptor { label: Some("Target texture"), size: Extent3d { @@ -912,13 +898,11 @@ impl State (texture, texture_view) } - fn get_window(&self) -> &Window - { + fn get_window(&self) -> &Window { &self.window } - fn handle_event(&mut self, event: &WindowEvent) - { + fn handle_event(&mut self, event: &WindowEvent) { self.egui_renderer.handle_input(&self.window, event); self.camera.handle_input(event); @@ -966,23 +950,18 @@ impl State } } - fn handle_device_event(&mut self, event: &DeviceEvent) - { + fn handle_device_event(&mut self, event: &DeviceEvent) { #[allow(clippy::single_match)] - match event - { - winit::event::DeviceEvent::MouseMotion { delta } if self.cursor_grabed => - { + match event { + winit::event::DeviceEvent::MouseMotion { delta } if self.cursor_grabed => { self.camera.cursor_moved(delta.0 as f32, delta.1 as f32); } - _ => - {} + _ => {} } } - fn create_depth_buffer(device: &Device, width: u32, height: u32) -> (Texture, TextureView) - { + fn create_depth_buffer(device: &Device, width: u32, height: u32) -> (Texture, TextureView) { let texture = device.create_texture(&wgpu::wgt::TextureDescriptor { label: Some("Depth buffer"), size: Extent3d { @@ -1004,8 +983,7 @@ impl State (texture, texture_view) } - fn configure_surface(&self) - { + fn configure_surface(&self) { let surface_config = wgpu::SurfaceConfiguration { color_space: wgpu::SurfaceColorSpace::Auto, usage: wgpu::TextureUsages::RENDER_ATTACHMENT, @@ -1022,8 +1000,7 @@ impl State self.surface.configure(&self.device, &surface_config); } - fn resize(&mut self, new_size: winit::dpi::PhysicalSize) - { + fn resize(&mut self, new_size: winit::dpi::PhysicalSize) { self.size = new_size; self.camera.aspect = new_size.width as f32 / new_size.height as f32; self.configure_surface(); @@ -1054,16 +1031,13 @@ impl State ); } - fn render(&mut self) - { + fn render(&mut self) { self.camera.update(); let mut locked_table = self.structure_table.lock(); - for (hndl, dir) in self.bvh_objs.iter_mut() - { + for (hndl, dir) in self.bvh_objs.iter_mut() { let obj = locked_table.get_mut(hndl); - if let Some(obj) = obj - { + if let Some(obj) = obj { let (scale, mut rot, mut trans) = obj.transform.to_scale_rotation_translation(); let speed = 0.01; rot = rot.mul_quat(Quat::from_axis_angle(*dir, speed)); @@ -1084,27 +1058,22 @@ impl State // NOTE: We must handle Timeout because the surface may be unavailable // (e.g., when the window is occluded on macOS). // ~~ Texture view creation ~~ - let surface_texture = match self.surface.get_current_texture() - { + let surface_texture = match self.surface.get_current_texture() { wgpu::CurrentSurfaceTexture::Success(texture) => texture, wgpu::CurrentSurfaceTexture::Occluded | wgpu::CurrentSurfaceTexture::Timeout => return, - wgpu::CurrentSurfaceTexture::Suboptimal(texture) => - { + wgpu::CurrentSurfaceTexture::Suboptimal(texture) => { drop(texture); self.configure_surface(); return; } - wgpu::CurrentSurfaceTexture::Outdated => - { + wgpu::CurrentSurfaceTexture::Outdated => { self.configure_surface(); return; } - wgpu::CurrentSurfaceTexture::Validation => - { + wgpu::CurrentSurfaceTexture::Validation => { unreachable!("No error scope registered, so validation errors will panic") } - wgpu::CurrentSurfaceTexture::Lost => - { + wgpu::CurrentSurfaceTexture::Lost => { self.surface = self.instance.create_surface(self.window.clone()).unwrap(); self.configure_surface(); return; @@ -1240,8 +1209,7 @@ impl State encoder.end_scope(); } - let target_view = match self.display - { + let target_view = match self.display { DisplayTexture::Target => &self.target_texture.1, DisplayTexture::Normal => &self.normal_gbuffer.1, DisplayTexture::Pos => &self.position_gbuffer.1, @@ -1367,8 +1335,7 @@ impl State let slice = slice.unwrap(); let cache_slice: &[u32] = bytemuck::cast_slice(&slice); let mut v = vec![0; 100]; - for x in cache_slice.iter() - { + for x in cache_slice.iter() { let diff = (time_stamp - x).min(99); v[diff as usize] += 1; } @@ -1470,13 +1437,10 @@ impl State &self.queue, move |request_informations, request_metas| { let done = request_buffer_done_1.load(std::sync::atomic::Ordering::Relaxed); - if !done - { + if !done { request_buffer_done_1.store(true, std::sync::atomic::Ordering::Relaxed); finshed_1.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - } - else - { + } else { return; } @@ -1575,14 +1539,11 @@ impl State move |request_informations, request_metas| { let done = structure_table_request_buffer_done_1 .load(std::sync::atomic::Ordering::Relaxed); - if !done - { + if !done { structure_table_request_buffer_done_1 .store(true, std::sync::atomic::Ordering::Relaxed); finshed_2.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - } - else - { + } else { return; } @@ -1669,10 +1630,8 @@ impl State self.wakeup.send(()).unwrap(); - loop - { - if finished.load(std::sync::atomic::Ordering::Relaxed) >= 2 - { + loop { + if finished.load(std::sync::atomic::Ordering::Relaxed) >= 2 { break; } let _ = self.device.poll(wgpu::wgt::PollType::Poll); @@ -1712,25 +1671,20 @@ impl State } } - pub fn mouse_wheel(&mut self, delta: MouseScrollDelta) - { - if let MouseScrollDelta::LineDelta(_, y) = delta - { + pub fn mouse_wheel(&mut self, delta: MouseScrollDelta) { + if let MouseScrollDelta::LineDelta(_, y) = delta { self.camera.speed += y * (self.camera.speed * 0.05); } } } #[derive(Default)] -struct App -{ +struct App { state: Option, } -impl ApplicationHandler for App -{ - fn resumed(&mut self, event_loop: &ActiveEventLoop) - { +impl ApplicationHandler for App { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { // Create window object let window = Arc::new( event_loop @@ -1754,31 +1708,25 @@ impl ApplicationHandler for App .or_else(|_| window.set_cursor_grab(winit::window::CursorGrabMode::Confined)); } - fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) - { + fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) { let state = self.state.as_mut().unwrap(); state.handle_event(&event); - match event - { - WindowEvent::CloseRequested => - { + match event { + WindowEvent::CloseRequested => { println!("The close button was pressed; stopping"); event_loop.exit(); } - WindowEvent::RedrawRequested => - { + WindowEvent::RedrawRequested => { state.render(); // Emits a new redraw requested event. state.get_window().request_redraw(); } - WindowEvent::Resized(size) => - { + WindowEvent::Resized(size) => { // Reconfigures the size of the surface. We do not re-render // here as this event is always followed up by redraw request. state.resize(size); } - WindowEvent::MouseWheel { delta, .. } => - { + WindowEvent::MouseWheel { delta, .. } => { state.mouse_wheel(delta); } @@ -1791,15 +1739,13 @@ impl ApplicationHandler for App _event_loop: &event_loop::ActiveEventLoop, _device_id: winit::event::DeviceId, event: winit::event::DeviceEvent, - ) - { + ) { let state = self.state.as_mut().unwrap(); state.handle_device_event(&event); } } -fn main() -{ +fn main() { // wgpu uses `log` for all of our logging, so we initialize a logger with the `env_logger` crate. // // To change the log level, set the `RUST_LOG` environment variable. See the `env_logger` @@ -1826,8 +1772,7 @@ fn main() } #[derive(AsStd140)] -pub struct ChunkImmediate -{ +pub struct ChunkImmediate { mvp: Mat4, eye_pos: Vec3, root_color: Vec4, @@ -1836,32 +1781,28 @@ pub struct ChunkImmediate } fn fullfill_request_tree( - tree: &NTree, + tree: &NTree, request: &RequestKey, ) -> ( [u32; N * N * N], [[f32; 3]; N * N * N], InsertionInformation, LocationPage, -) -{ - match request.target - { - RequestTarget::Root => - { +) { + match request.target { + RequestTarget::Root => { let root = tree .get_by_loc(TreeLocator::root()) .expect("Root must exist"); - if !root.subdivided - { + if !root.subdivided { // Produce little node of constant ( - [root.color.as_packed_u32(); N * N * N], + [root.attribute.as_packed_u32(); N * N * N], //[sparse_tree::Color(1., 1., 1., 1.).as_packed_u32(); N * N * N], [Default::default(); N * N * N], InsertionInformation { - children: [ChildInformation::new(false, root.color.3 != 0.); N * N * N], + children: [ChildInformation::new(false, root.attribute.3 != 0.); N * N * N], }, LocationPage { node_id: StructureLocator::from(TreeLocator::::root()), @@ -1869,17 +1810,15 @@ fn fullfill_request_tree( anchor: StructureAnchor::zeroed(), }, ) - } - else - { + } else { let mut colors = vec![]; let mut children = vec![]; TreeLocator::root().children().for_each(|loc| { let node = tree.get_by_loc(loc).unwrap(); - colors.push(node.color.as_packed_u32()); + colors.push(node.attribute.as_packed_u32()); children.push(ChildInformation::new( node.subdivided, - node.subdivided || node.color.3 != 0., + node.subdivided || node.attribute.3 != 0., )); }); @@ -1900,8 +1839,7 @@ fn fullfill_request_tree( RequestTarget::Child { parent, children_index, - } => - { + } => { let child_z = children_index / (4 * 4); let child_y = (children_index % (4 * 4)) / 4; let child_x = children_index % 4; @@ -1913,10 +1851,10 @@ fn fullfill_request_tree( let mut children = vec![]; loc.children().for_each(|child_loc| { let node = tree.get_by_loc(child_loc).unwrap(); - colors.push(node.color.as_packed_u32()); + colors.push(node.attribute.as_packed_u32()); children.push(ChildInformation::new( node.subdivided, - node.subdivided || node.color.3 != 0., + node.subdivided || node.attribute.3 != 0., )); }); diff --git a/crates/vxls/src/producers.rs b/crates/vxls/src/producers.rs index 98534b7..2f46f43 100644 --- a/crates/vxls/src/producers.rs +++ b/crates/vxls/src/producers.rs @@ -11,7 +11,7 @@ use noise::NoiseFn; use noise::Simplex; use rand::random; -use crate::sparse_tree::Color; +use vxls_production::sparse_tree::Color; use vxls_voxel_cache::schema::ChildInformation; /// The voxel attributes used by the demo cache. @@ -21,8 +21,7 @@ use vxls_voxel_cache::schema::ChildInformation; /// `shaders/voxel.slang`. #[derive(Clone, Copy, PartialEq, Default, Pod, Zeroable, vxls_production::Attributes, Debug)] #[repr(C)] -pub struct VoxelAttributes -{ +pub struct VoxelAttributes { #[attribute(label = "color", semantic = "color")] pub color: u32, @@ -30,13 +29,11 @@ pub struct VoxelAttributes pub normal: [f32; 3], } -pub struct BallGenerator -{ +pub struct BallGenerator { 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); @@ -57,8 +54,7 @@ impl BallGenerator where [(); N * N * N]:, { - pub fn new(chunk_power: usize) -> Self - { + pub fn new(chunk_power: usize) -> Self { BallGenerator { chunk_power } } } @@ -67,8 +63,7 @@ impl Producer for BallGenerator where [(); N * N * N]:, { - fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ProducedChunk - { + fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ProducedChunk { 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); @@ -81,8 +76,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); @@ -97,19 +91,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.; } @@ -169,8 +158,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(); @@ -178,8 +166,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"), }; @@ -229,16 +216,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]); } @@ -254,17 +237,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; @@ -318,8 +297,7 @@ where ny: usize, nz: usize, chunk_pos: (usize, usize, usize), - ) -> ProducedChunk - { + ) -> ProducedChunk { 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); @@ -332,8 +310,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; @@ -345,14 +322,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; @@ -376,15 +350,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; @@ -427,32 +397,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. }; } @@ -495,17 +456,14 @@ where ) -> ProducedChunk; } -pub struct SdfGenerator -{ +pub struct SdfGenerator { chunk_power: usize, perlin: Fbm, //perlin: Cylinders, } -impl SdfGenerator -{ - pub fn new(chunk_power: usize) -> Self - { +impl SdfGenerator { + pub fn new(chunk_power: usize) -> Self { Self { chunk_power, perlin: Fbm::new(67), @@ -525,10 +483,8 @@ where ny: usize, nz: usize, chunk_pos: (usize, usize, usize), - ) -> ProducedChunk - { - fn hash(mut p: [f32; 3]) -> f32 - { + ) -> ProducedChunk { + 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() } @@ -613,8 +569,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); @@ -624,20 +579,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.; } @@ -667,12 +617,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() }; diff --git a/crates/vxls/src/sparse_tree.rs b/crates/vxls/src/sparse_tree.rs deleted file mode 100644 index 455097c..0000000 --- a/crates/vxls/src/sparse_tree.rs +++ /dev/null @@ -1,464 +0,0 @@ -use std::collections::HashMap; -use std::collections::VecDeque; - -use bytemuck::Pod; -use bytemuck::Zeroable; -use itertools::Itertools; -use noise::Terrace; - -use vxls_production::tree_locator::TreeLocator; - -#[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>(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 -{ - map: HashMap, 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, - dfs_stack: Vec>, -} - -#[derive(Debug, Clone, Copy)] -pub struct NTreeNode -{ - pub color: Color, - pub subdivided: bool, -} - -impl NTree -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(TreeLocator::::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 = TreeLocator::::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 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, 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 = TreeLocator::::root(); - let mut current_node_size = N.pow(self.depth as u32); - let mut current_depth = 0; - let mut current_node = self.map.get_mut(¤t_node_loc).unwrap(); - - 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().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, 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() - .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: TreeLocator, 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 (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::(x).unwrap_or(depth as u32); - let y_trailing = base_trailing_zeroes::(y).unwrap_or(depth as u32); - let z_trailing = base_trailing_zeroes::(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 = - TreeLocator::::from_node_coords(depth as u32, x as u32, y as u32, z as u32); - 'power_search: for power in 1..=block_power - { - let block_size = N.pow(power); - // Check if candidate block has the same color - for ((merge_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] - != 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_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 { - color, - 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::::from_node_coords( - (depth - current_power) as u32, - block_x as u32, - block_y as u32, - block_z as u32, - ); - - // Get average color of children - let color = Color::average( - locator - .children() - .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 get_by_loc(&self, locator: TreeLocator) -> Option - { - self.map.get(&locator).copied() - } -} - -fn base_trailing_zeroes(mut number: usize) -> Option -{ - if number == 0 - { - return None; - } - let mut trailing_zeroes = 0; - while number % N == 0 - { - number /= N; - trailing_zeroes += 1; - } - - Some(trailing_zeroes) -} - -pub fn load_ply, const N: usize>(path: P) -> NTree -where - [(); N * N * N]:, -{ - let file = std::fs::read_to_string(path).unwrap(); - - let mut colors = vec![Color(0., 0., 0., 0.); 256 * 256 * 256]; - for line in file.lines() - { - let coords = line - .split(',') - .take(3) - .map(|s| s.trim_end().trim_start().parse::().unwrap()) - .collect::>(); - let (x, y, z) = (coords[0], coords[1], coords[2]); - let index = x + z * 256 + y * 256 * 256; - colors[index as usize] = Color(1., 1., 1., 1.); - } - - NTree::from_array(&colors, 4) -} - -mod test -{ - use glam::Vec3; - use rand::random; - - use vxls_production::tree_locator::TreeLocator; - use crate::sparse_tree::Color; - use crate::sparse_tree::NTree; - - #[test] - fn constant_set() - { - let mut tree = NTree::<4>::constant(Color(0., 0., 0., 0.), 4); - assert!(tree.get(0, 0, 0) == Color(0., 0., 0., 0.)); - tree.set(0, 0, 0, Color(1., 1., 1., 1.)); - assert!(tree.get(0, 0, 0) == Color(1., 1., 1., 1.)); - } - - #[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::().unwrap()) - .collect::>(); - let (x, y, z) = (coords[0], coords[1], coords[2]); - let index = x + z * 256 + y * 256 * 256; - colors[index as usize] = Color(1., 1., 1., 1.); - } - - println!("building tree"); - let tree = NTree::<4>::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); - } - } - } - } -}