Compare commits

...
3 Commits
Author SHA1 Message Date
octagonal 9b8fd9840e feat: producer sketch 2026-11-16 12:01:35 +01:00
octagonal 3ccbfe55eb refactor: Merge vxls-data into vxls-production 2026-11-16 11:09:33 +01:00
octagonal cbb3b4eaf0 feat: sparse_tree is now generic 2026-11-16 10:58:24 +01:00
6 changed files with 144 additions and 210 deletions
-9
View File
@@ -1,9 +0,0 @@
[package]
name = "vxls-data"
version = "0.1.0"
edition = "2024"
[dependencies]
vxls-production = { src = "../vxls-production" }
bytemuck.workspace = true
itertools.workspace = true
-24
View File
@@ -1,24 +0,0 @@
//!
//! This crate contains types and structures to store voxel data
//!
pub mod sparse_tree;
/// A voxel attribute must be able to be turned into bytes, and just be a bit of data
pub trait Attribute: bytemuck::Pod + bytemuck::Zeroable + Clone + Copy + 'static
{
// Whether the two attributes can be merged into one single voxel
pub fn mergeable(&self, other: &Self) -> bool;
pub fn merge(&self, other: &Self) -> Self;
pub fn merge_iter<I: Iterator<Item = S>, S: AsRef<Self>>(iter: I) -> Option<Self>
{
iter.reduce(<Self as Attribute>::merge).map(|x| *x.as_ref())
}
}
pub trait Has<A: Attribute>
{
fn get(&self) -> &A;
fn get_mut(&mut self) -> &mut A;
}
@@ -1,69 +0,0 @@
use rayon::ThreadPool;
use rayon::iter::IndexedParallelIterator;
use rayon::iter::IntoParallelRefIterator;
use rayon::iter::IntoParallelRefMutIterator;
use rayon::iter::ParallelIterator;
use crate::VoxelProducer;
use vxls_voxel_cache::insertion::CacheInsertionData;
use vxls_voxel_cache::requests::CacheRequestBuffer;
use vxls_voxel_cache::schema::InsertionInformation;
use vxls_voxel_cache::schema::RequestInformation;
/// Handles requests made by the cache on the host
pub struct HostRequestHandler<const N: usize, P: VoxelProducer<N>>
where
[(); N * N * N]:,
{
producer: P,
thread_pool: ThreadPool,
}
impl<const N: usize, P: VoxelProducer<N> + Sync> HostRequestHandler<N, P>
where
[(); N * N * N]:,
{
pub fn new(producer: P, thread_pool: ThreadPool) -> Self
{
Self {
producer,
thread_pool,
}
}
pub fn fullfill(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
request_buffer: &CacheRequestBuffer,
insertion: &CacheInsertionData<N>,
)
{
request_buffer.host_download_requests(device, queue, |_requests, _metas| {});
}
pub fn produce_requests(
&self,
requests: &[RequestInformation],
informations: &mut [InsertionInformation<N>],
attributes: &mut [[P::Output; N * N * N]],
)
{
self.thread_pool.install(|| {
requests
.par_iter()
.zip(informations.par_iter_mut())
.zip(attributes.par_iter_mut())
.for_each(|((request, dest_information), dest_attributes)| {
let (info, attributes) = self.producer.produce(
super::ProducerId(0),
request.anchor,
super::StructureLocator(request.node_id),
);
*dest_information = info;
*dest_attributes = attributes;
});
})
}
}
+56 -28
View File
@@ -1,23 +1,25 @@
#![allow(incomplete_features)]
#![feature(generic_const_exprs)]
use bytemuck::Pod;
use bytemuck::Zeroable;
use vxls_voxel_cache::schema::InsertionInformation;
use vxls_voxel_cache::schema::InsertionInformation;
use vxls_voxel_cache::schema::LocationPage;
pub use vxls_voxel_cache::schema::StructureAnchor;
use wgpu::naga::keywords;
/// A structure locator format to locate node within an ntree
pub mod tree_locator;
/// Facilities for voxel production on the host (CPU) side
pub mod host_production;
/// Sparse NTree to store voxel data
pub mod sparse_tree;
/// Bounded, deduplicating, priority-ordered cache request queue
pub mod request_queue;
/// This module contains definition and common logic to produce voxel data to feed a [`VoxelCache`]
/// A cache might hold data owned by multiple different producers. To discriminate where to route the
/// request, a node is always tagged by a [`ProducerId`].
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)]
@@ -30,34 +32,60 @@ pub struct ProducerId(pub u32);
#[repr(transparent)]
pub struct StructureLocator(pub u32);
/// For structs which can be used as a voxel attribute source
pub trait VoxelAttributes<const N: usize>: 'static + Clone + Send + Sync
{
/// The amount of attributes this struct holds
fn attribute_count() -> usize;
/// A voxel attribute must be able to be turned into bytes, and just be a bit of data
pub trait Attribute:
// An attribute can be turned into predictable, safe, raw bytes
bytemuck::Pod +
bytemuck::Zeroable +
/// Must returns the words for a single attribute.
fn attribute(&self, attribute_index: usize) -> &[u32];
// It can be compared with itself, equal attributes mean they can be merged in a sparse structure
PartialEq +
Eq +
// It can be crated by anybody, without knowing what is inside
Default +
// It can be moved arround without problems, and does not depend on anything
Clone +
Copy +
Send +
Sync +
'static
{
/// Many attributes can be averaged together
fn average(attributes: &[Self]) -> Self;
}
/// Represents something that can produce a voxel node.
pub trait VoxelProducer<const N: usize>
where
[(); N * N * N]:,
pub trait Has<A: Attribute>
{
/// The voxel data produced by this producer
type Output: VoxelAttributes<N>;
fn get(&self) -> &A;
fn get_mut(&mut self) -> &mut A;
/// A pure function that can produce a voxel node based on the owner producer
/// id, requesting structure, and the requesting location within the structure.
///
/// `anchor` is the table-defined content identity of the structure. Producers
/// must derive world position/content from it rather than from any table
/// slot: slots are placement and may change while the anchor stays stable.
fn produce(
&self,
fn get_bytes(&self) -> &[u8]
{
bytemuck::bytes_of(self.get())
}
fn get_bytes_mut(&mut self) -> &mut [u8]
{
bytemuck::bytes_of_mut(self.get_mut())
}
}
pub struct ProducedNode<const N: usize, A: Attribute>
where [(); N * N * N]:,
{
insersion_info: InsertionInformation<N>,
location: LocationPage,
attributes: [A; N * N * N],
}
pub trait Producer<const N: usize, A: Attribute>
where [(); N * N * N]:,
{
fn produce(&self,
producer_id: ProducerId,
anchor: StructureAnchor,
locator: StructureLocator,
) -> (InsertionInformation<N>, [Self::Output; N * N * N]);
locator: StructureLocator
) -> ProducedNode<N, A>;
}
@@ -1,37 +1,50 @@
use std::collections::HashMap;
use std::collections::VecDeque;
use bytemuck::Pod;
use bytemuck::Zeroable;
use itertools::Itertools;
use vxls_production::tree_locator::TreeLocator;
use super::tree_locator::TreeLocator;
#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
use crate::Attribute;
#[derive(Debug, Clone, Copy, PartialEq, Default, Pod, Zeroable)]
#[repr(C)]
pub struct Color(pub f32, pub f32, pub f32, pub f32);
impl Color
// `Attribute` requires `Eq`. `Color` is only ever constructed from finite,
// non-NaN values in this crate, so equality is well-behaved here.
impl Eq for Color {}
impl Attribute for Color
{
pub fn average<I: Iterator<Item = Color>>(iter: I) -> Self
fn average(attributes: &[Self]) -> Self
{
let mut c = Color(0., 0., 0., 0.);
let mut count = 0;
for Color(r, g, b, a) in iter
if attributes.is_empty()
{
count += 1;
c.0 += r;
c.1 += g;
c.2 += b;
c.3 += a;
return Self::default();
}
c.0 /= count as f32;
c.1 /= count as f32;
c.2 /= count as f32;
c.3 /= count as f32;
let mut c = Self::default();
for color in attributes
{
c.0 += color.0;
c.1 += color.1;
c.2 += color.2;
c.3 += color.3;
}
let count = attributes.len() as f32;
c.0 /= count;
c.1 /= count;
c.2 /= count;
c.3 /= count;
c
}
}
impl Color
{
pub fn as_packed_u32(&self) -> u32
{
let mapped_r = (self.0 * 255.0).clamp(0., 255.0) as u32;
@@ -43,9 +56,9 @@ impl Color
}
#[derive(Debug, Clone)]
pub struct NTree<const N: usize>
pub struct NTree<const N: usize, T: Attribute>
{
map: HashMap<TreeLocator<N>, NTreeNode>,
map: HashMap<TreeLocator<N>, NTreeNode<T>>,
// Depth is the parameter such that
// N^depth == max_number_of_voxels
@@ -53,40 +66,41 @@ pub struct NTree<const N: usize>
depth: usize,
}
pub struct NTreeIter<'a, const N: usize>
pub struct NTreeIter<'a, const N: usize, T: Attribute>
{
tree: &'a NTree<N>,
tree: &'a NTree<N, T>,
dfs_stack: Vec<TreeLocator<N>>,
}
#[derive(Debug, Clone, Copy)]
pub struct NTreeNode
pub struct NTreeNode<T: Attribute>
{
pub color: Color,
pub attribute: T,
pub subdivided: bool,
}
impl<const N: usize> NTree<N>
impl<const N: usize, T> NTree<N, T>
where
[(); N * N * N]:,
T: Attribute,
{
pub fn constant(color: Color, depth: usize) -> Self
pub fn constant(value: T, depth: usize) -> Self
{
let mut map = HashMap::new();
let root = NTreeNode {
color,
attribute: value,
subdivided: false,
};
map.insert(TreeLocator::<N>::root(), root);
Self { map, depth }
}
pub fn set(&mut self, x: usize, y: usize, z: usize, color: Color)
pub fn set(&mut self, x: usize, y: usize, z: usize, value: T)
{
self.set_at_depth(x, y, z, self.depth, color);
self.set_at_depth(x, y, z, self.depth, value);
}
pub fn get(&self, x: usize, y: usize, z: usize) -> Color
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));
@@ -101,7 +115,7 @@ where
{
if !current_node.subdivided
{
return current_node.color;
return current_node.attribute;
}
// Descend to relevant node,
@@ -117,7 +131,7 @@ where
}
}
pub fn set_at_depth(&mut self, x: usize, y: usize, z: usize, depth: usize, color: Color)
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));
@@ -131,18 +145,18 @@ where
while current_depth != depth
{
if current_node.color == color
if current_node.attribute == value
{
// Color is already correct, work is finished
// Attribute is already correct, work is finished
return;
}
// Current is not subdivided, and color is different => subdivide
// Current is not subdivided, and attribute is different => subdivide
if !current_node.subdivided
{
current_node.subdivided = true;
let new_nodes = NTreeNode {
color: current_node.color,
attribute: current_node.attribute,
subdivided: false,
};
current_node_loc.children().for_each(|child| {
@@ -165,11 +179,11 @@ where
if current_node.subdivided
{
self.make_constant(current_node_loc, color);
self.make_constant(current_node_loc, value);
}
else
{
current_node.color = color;
current_node.attribute = value;
}
// We need to go back up the hierarchy to combine nodes
@@ -182,16 +196,15 @@ where
current_node_loc = current_node_loc.parent().unwrap();
//current_node_size *= N;
// Access all children's colors
let children_color_avg = current_node_loc
// Access all children's attributes
let children_attributes = current_node_loc
.children()
.map(|child_loc| self.map.get(&child_loc).unwrap().color)
// AGGREGATE AND AVERAGE HERE !!
.next()
.unwrap();
.map(|child_loc| self.map.get(&child_loc).unwrap().attribute)
.collect::<Vec<_>>();
let children_attribute_avg = T::average(&children_attributes);
current_node = self.map.get_mut(&current_node_loc).unwrap();
current_node.color = children_color_avg;
current_node.attribute = children_attribute_avg;
if current_depth == 0
{
@@ -200,7 +213,7 @@ where
}
}
fn make_constant(&mut self, locator: TreeLocator<N>, color: Color)
fn make_constant(&mut self, locator: TreeLocator<N>, value: T)
{
let mut dfs_stack = Vec::new();
dfs_stack.push(locator);
@@ -221,13 +234,13 @@ where
self.map.insert(
locator,
NTreeNode {
color,
attribute: value,
subdivided: false,
},
);
}
pub fn from_array(array: &[Color], depth: usize) -> Self
pub fn from_array(array: &[T], depth: usize) -> Self
{
let mut structure = HashMap::new();
// Per voxel in the array :
@@ -260,20 +273,20 @@ where
// Try to merge for each depth
let mut max_power_merge = 0; // Single voxel can always be merged
let color = array[x + y * width + z * width * width];
let attribute = array[x + y * width + z * width * width];
let mut locator =
TreeLocator::<N>::from_node_coords(depth as u32, x as u32, y as u32, z as u32);
'power_search: for power in 1..=block_power
{
let block_size = N.pow(power);
// Check if candidate block has the same color
// Check if candidate block has the same attribute
for ((merge_z, merge_y), merge_x) in (0..block_size)
.cartesian_product(0..block_size)
.cartesian_product(0..block_size)
{
if array
[(x + merge_x) + (y + merge_y) * width + (z + merge_z) * width * width]
!= color
!= attribute
{
break 'power_search;
}
@@ -299,7 +312,7 @@ where
// Add new found block in our structure
// If power is depth, this is the whole structure, thus depth is 0
let node = NTreeNode {
color,
attribute,
subdivided: false,
};
structure.insert(locator, node);
@@ -337,15 +350,15 @@ where
block_z as u32,
);
// Get average color of children
let color = Color::average(
locator
.children()
.map(|child_loc| structure.get(&child_loc).unwrap().color),
);
// Get average attribute of children
let children = locator
.children()
.map(|child_loc| structure.get(&child_loc).unwrap().attribute)
.collect::<Vec<_>>();
let attribute = T::average(&children);
let hierarchy_node = NTreeNode {
color,
attribute,
subdivided: true,
};
structure.insert(locator, hierarchy_node);
@@ -358,7 +371,7 @@ where
}
}
pub fn get_by_loc(&self, locator: TreeLocator<N>) -> Option<NTreeNode>
pub fn get_by_loc(&self, locator: TreeLocator<N>) -> Option<NTreeNode<T>>
{
self.map.get(&locator).copied()
}
@@ -380,13 +393,13 @@ fn base_trailing_zeroes<const N: usize>(mut number: usize) -> Option<u32>
Some(trailing_zeroes)
}
pub fn load_ply<P: AsRef<std::path::Path>, const N: usize>(path: P) -> NTree<N>
pub fn load_ply<P: AsRef<std::path::Path>, const N: usize>(path: P) -> NTree<N, Color>
where
[(); N * N * N]:,
{
let file = std::fs::read_to_string(path).unwrap();
let mut colors = vec![Color(0., 0., 0., 0.); 256 * 256 * 256];
let mut colors = vec![Color::default(); 256 * 256 * 256];
for line in file.lines()
{
let coords = line
@@ -399,22 +412,18 @@ where
colors[index as usize] = Color(1., 1., 1., 1.);
}
NTree::from_array(&colors, 4)
NTree::<N, Color>::from_array(&colors, 4)
}
mod test
{
use glam::Vec3;
use rand::random;
use crate::sparse_tree::Color;
use crate::sparse_tree::NTree;
use vxls_production::tree_locator::TreeLocator;
#[test]
fn constant_set()
{
let mut tree = NTree::<4>::constant(Color(0., 0., 0., 0.), 4);
let mut tree = NTree::<4, Color>::constant(Color(0., 0., 0., 0.), 4);
assert!(tree.get(0, 0, 0) == Color(0., 0., 0., 0.));
tree.set(0, 0, 0, Color(1., 1., 1., 1.));
assert!(tree.get(0, 0, 0) == Color(1., 1., 1., 1.));
@@ -441,7 +450,7 @@ mod test
}
println!("building tree");
let tree = NTree::<4>::from_array(&colors, 4);
let tree = NTree::<4, Color>::from_array(&colors, 4);
println!("ok");
for x in 0..256
+11 -12
View File
@@ -54,19 +54,20 @@ use winit::event_loop::OwnedDisplayHandle;
use winit::window::Window;
use winit::window::WindowId;
use crate::camera::Camera;
use crate::egui_renderer::EguiRenderer;
use crate::producers::ChunkedProducer;
use crate::producers::SdfGenerator;
use crate::sparse_tree::Color;
use crate::sparse_tree::NTree;
use crate::sparse_tree::NTreeNode;
use crate::sparse_tree::load_ply;
use vxls_bvh::BvhHandle;
use vxls_bvh::BvhObject;
use vxls_bvh::BvhStructureTable;
use vxls_bvh::aabb::Aabb;
use vxls_bvh::build::Bvh;
use vxls_bvh::debug::BvhDebugPipeline;
use crate::camera::Camera;
use crate::egui_renderer::EguiRenderer;
use vxls_profiler::Frame;
use vxls_profiler::Profile;
use vxls_profiler::ProfilingEncoder;
use crate::producers::ChunkedProducer;
use crate::producers::SdfGenerator;
use vxls_production::ProducerId;
use vxls_production::StructureAnchor;
use vxls_production::StructureLocator;
@@ -77,10 +78,9 @@ use vxls_production::request_queue::RequestKey;
use vxls_production::request_queue::RequestQueue;
use vxls_production::request_queue::RequestTarget;
use vxls_production::tree_locator::TreeLocator;
use crate::sparse_tree::Color;
use crate::sparse_tree::NTree;
use crate::sparse_tree::NTreeNode;
use crate::sparse_tree::load_ply;
use vxls_profiler::Frame;
use vxls_profiler::Profile;
use vxls_profiler::ProfilingEncoder;
use vxls_terrain::ToroidalStructureTable;
use vxls_voxel_cache::VoxelCache;
use vxls_voxel_cache::VoxelCacheInsertion;
@@ -96,7 +96,6 @@ mod egui_renderer;
mod gi_pipeline;
mod producers;
mod sparse_tree;
pub mod voxel_data;
enum DisplayTexture
{