refactor: Removing structureID, keep structure anchor as id

This commit is contained in:
2026-11-12 15:51:05 +01:00
parent a39256a0f1
commit c31f3a9bc3
23 changed files with 1417 additions and 806 deletions
+224 -25
View File
@@ -1,12 +1,14 @@
#![feature(generic_const_exprs)]
#![feature(float_algebraic)]
use std::arch::x86_64;
use std::marker::PhantomData;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU32;
use std::sync::mpsc::Sender;
use std::thread::Thread;
use std::time::Instant;
use bytemuck::Pod;
use bytemuck::Zeroable;
@@ -16,9 +18,12 @@ use egui::Color32;
use egui::mutex::Mutex;
use egui_plot::BarChart;
use glam::Mat4;
use glam::Quat;
use glam::Vec3;
use glam::Vec4;
use itertools::Itertools;
use rand::random_bool;
use rand::random_range;
use rayon::iter::IntoParallelRefIterator;
use rayon::iter::ParallelIterator;
use wgpu::BindGroupLayout;
@@ -49,6 +54,10 @@ use winit::event_loop::OwnedDisplayHandle;
use winit::window::Window;
use winit::window::WindowId;
use crate::bvh::BvhObject;
use crate::bvh::BvhStructureTable;
use crate::bvh::aabb::Aabb;
use crate::bvh::debug::BvhDebugPipeline;
use crate::camera::Camera;
use crate::egui_renderer::EguiRenderer;
use crate::gpu_profiler::Frame;
@@ -56,21 +65,31 @@ use crate::gpu_profiler::Profile;
use crate::gpu_profiler::ProfilingEncoder;
use crate::producers::ChunkedProducer;
use crate::producers::SdfGenerator;
use crate::production::ProducerId;
use crate::production::StructureAnchor;
use crate::production::StructureLocator;
use crate::production::request_queue::FrameId;
use crate::production::request_queue::IncomingRequest;
use crate::production::request_queue::QueueConfig;
use crate::production::request_queue::RequestKey;
use crate::production::request_queue::RequestQueue;
use crate::production::request_queue::RequestTarget;
use crate::sparse_tree::NTreeNodeLocator;
use crate::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 crate::terrain::ToroidalStructureTable;
use crate::voxel_cache::VoxelCache;
use crate::voxel_cache::VoxelCacheInsertion;
use crate::voxel_cache::insertion::CacheInsertionData;
use crate::voxel_cache::requests::CacheRequestBuffer;
use crate::voxel_cache::schema::ChildInformation;
use crate::voxel_cache::schema::InsertionInformation;
use crate::voxel_cache::schema::LocationPage;
use crate::voxel_cache::tables::FixedStructureTable;
pub mod bvh;
mod camera;
mod egui_renderer;
mod gi_pipeline;
@@ -81,7 +100,6 @@ mod production;
mod sparse_tree;
mod terrain;
mod voxel_cache;
//
enum DisplayTexture
{
@@ -134,8 +152,6 @@ struct State
structure_table: Arc<Mutex<ToroidalStructureTable>>,
structure_table_request_buffer: Arc<CacheRequestBuffer>,
structure_table_cache_insertion: Arc<CacheInsertionData<4>>,
instance_buffer: Buffer,
instance_count: usize,
usage_vec: Arc<Mutex<Vec<usize>>>,
rm_time: Arc<Mutex<f32>>,
frame_time: Arc<Mutex<f32>>,
@@ -153,6 +169,9 @@ struct State
// Producers workers
wakeup: Sender<()>,
bvh: BvhStructureTable,
bvh_debug: BvhDebugPipeline,
}
pub unsafe fn as_raw_bytes<T: Sized>(slice: &[T]) -> &[u8]
@@ -358,6 +377,19 @@ impl State
panic!();
*/
// Load dragon ply
let tree: NTree<4> = 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)
// {
// if Vec3::new(x as f32, y as f32, z as f32).length() < 128.
// {
// let index = x + y * 256 + z * 256 * 256;
// //arrays[index] = Color(1., 1., 1., 1.);
// }
// }
// let tree: NTree<4> = NTree::from_array(&arrays, 4);
let size = window.inner_size();
let surface = instance.create_surface(window.clone()).unwrap();
@@ -413,11 +445,12 @@ impl State
let total_chunk_count = terrain_height * terrain_width * terrain_alt;
let structure_table_request_buffer = CacheRequestBuffer::new(&device, 128);
//let structure_table = FixedStructureTable::new(
// &device,
// total_chunk_count,
// structure_table_request_buffer.max_requests,
//);
// let structure_table = FixedStructureTable::new(
// &device,
// total_chunk_count,
// structure_table_request_buffer.max_requests,
// 0,
// );
let structure_table = ToroidalStructureTable::new(
&device,
(terrain_width, terrain_alt, terrain_height),
@@ -490,6 +523,48 @@ impl State
// )
// };
let mut bvh = BvhStructureTable::new(&device, 128, 128);
let extent = Aabb::new(-10. * Vec3::ONE, 10. * Vec3::ONE);
for _ in 0..200
{
let transform = Mat4::from_rotation_translation(
Quat::from_euler(
glam::EulerRot::XYZ,
random_range(-3.1..3.1),
random_range(-3.1..3.1),
random_range(-3.1..3.1),
),
Vec3::new(
random_range(extent.min().x..extent.max().x),
random_range(extent.min().y..extent.max().y),
random_range(extent.min().z..extent.max().z),
),
);
bvh.add(
&device,
&queue,
BvhObject {
anchor: StructureAnchor::zeroed(),
producer_id: ProducerId(0),
transform,
bounding_box: Aabb::CHUNK,
},
);
}
let now = Instant::now();
bvh.rebuild(&device, &queue);
let time = Instant::now() - now;
println!("Bvh build time : {}ms", time.as_millis());
let bvh_debug = BvhDebugPipeline::new(
&device,
surface_format.add_srgb_suffix(),
wgpu::TextureFormat::Depth24PlusStencil8,
);
let shader_module = unsafe {
device.create_shader_module_passthrough({
wgpu::ShaderModuleDescriptorPassthrough {
@@ -706,11 +781,12 @@ impl State
let finshed = work
.par_iter()
.map(|work_item| {
let d = fullfill_request(
&terrain_generator,
&work_item.key,
&structure_table_1,
);
// let d = fullfill_request(
// &terrain_generator,
// &work_item.key,
// &structure_table_1,
// );
let d = fullfill_request_tree(&tree, &work_item.key);
(
work_item,
VoxelPayload {
@@ -781,8 +857,6 @@ impl State
insertion_debounce: false,
camera: Default::default(),
instance_buffer,
instance_count,
rm_time: Arc::new(Mutex::new(0.)),
frame_time: Arc::new(Mutex::new(0.)),
terrain_width,
@@ -792,6 +866,8 @@ impl State
insert_profile: Arc::new(Mutex::new(Profile::default())),
cursor_grabed: true,
wakeup: wakeup_tx,
bvh,
bvh_debug,
};
// Configure surface for the first time
@@ -1103,9 +1179,9 @@ impl State
// Cancellation is only an optimisation: stale insertions are
// rejected by the GPU because they no longer match the slot.
let mut request_queue = self.request_queue.lock();
for structure in retired
for anchor in retired
{
request_queue.invalidate_structure(structure);
request_queue.invalidate_anchor(anchor);
}
}
@@ -1147,6 +1223,7 @@ impl State
chunk_height: self.terrain_height as u32,
chunk_alt: self.terrain_alt as u32,
//table_base_slot: Default::default(),
table_base_slot,
}];
renderpass.set_immediates(0, unsafe { as_raw_bytes(&imm) });
@@ -1177,6 +1254,19 @@ impl State
self.target_blitter
.copy(&self.device, &mut encoder, target_view, &texture_view);
self.bvh_debug.render(
&self.device,
&self.queue,
&mut encoder,
&texture_view,
&self.depth_buffer.1,
self.camera.view_proj(),
self.bvh.bvh_nodes(),
self.bvh.bvh_objects(),
self.bvh.node_count(),
2,
);
// ~~ EGUI Render pass ~~
{
self.egui_renderer.begin_frame(&self.window);
@@ -1747,6 +1837,108 @@ pub struct ChunkImmediate
frame_timestamp: u32,
}
fn fullfill_request_tree<const N: usize>(
tree: &NTree<N>,
request: &RequestKey,
) -> (
[u32; N * N * N],
[[f32; 3]; N * N * N],
InsertionInformation<N>,
LocationPage,
)
{
match request.target
{
RequestTarget::Root =>
{
let root = tree
.get_by_loc(TreeLocator::root())
.expect("Root must exist");
if !root.subdivided
{
// Produce little node of constant
(
[root.color.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],
},
LocationPage {
node_id: StructureLocator::from(TreeLocator::<N>::root()).0,
producer_id: 0,
anchor: StructureAnchor::zeroed(),
},
)
}
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());
children.push(ChildInformation::new(
node.subdivided,
node.subdivided || node.color.3 != 0.,
));
});
(
std::array::from_fn(|i| colors[i]),
[Default::default(); N * N * N],
InsertionInformation {
children: std::array::from_fn(|i| children[i]),
},
LocationPage {
node_id: StructureLocator::from(TreeLocator::<N>::root()).0,
producer_id: 0,
anchor: StructureAnchor::zeroed(),
},
)
}
}
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;
let loc: TreeLocator<N> = parent.into();
let loc = loc.child(child_x, child_y, child_z);
let mut colors = vec![];
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());
children.push(ChildInformation::new(
node.subdivided,
node.subdivided || node.color.3 != 0.,
));
});
(
std::array::from_fn(|i| colors[i]),
[Default::default(); N * N * N],
InsertionInformation {
children: std::array::from_fn(|i| children[i]),
},
LocationPage {
node_id: StructureLocator::from(loc).0,
producer_id: 0,
anchor: StructureAnchor::zeroed(),
},
)
}
}
}
/*
fn fullfill_request<const N: usize>(
generator: &dyn ChunkedProducer<N>,
request: &RequestKey,
@@ -1789,9 +1981,9 @@ where
// one without a parent page; `node_id == 0` also happens for child 0 of
// the root, so it cannot be used to detect roots.
node = generator.produce_node(0, 0, 0, 0, (chunk_x, chunk_y, chunk_z));
let locator: StructureLocator = TreeLocator::<N>::root().into();
location = LocationPage {
structure_id: request.structure_id.0,
node_id: NTreeNodeLocator::<4>::root().as_usize() as u32,
node_id: locator.0,
producer_id: request.producer_id.0,
anchor,
};
@@ -1807,7 +1999,7 @@ where
unreachable!();
};
// Figure out depth of request
let locator = NTreeNodeLocator::<4>::from_usize(parent.0 as usize);
let locator: TreeLocator<4> = (*parent).into();
let depth = locator.depth();
//let (x, y, z) = locator.node_location();
@@ -1815,15 +2007,21 @@ where
let child_y = (children_index % (4 * 4)) / 4;
let child_x = children_index % 4;
let child_locator = locator.child(child_x as usize, child_y as usize, child_z as usize);
let child_locator = locator.child(child_x, child_y, child_z);
let (nx, ny, nz) = child_locator.node_location();
node = generator.produce_node(depth + 1, nx, ny, nz, (chunk_x, chunk_y, chunk_z));
node = generator.produce_node(
(depth + 1) as usize,
nx as usize,
ny as usize,
nz as usize,
(chunk_x, chunk_y, chunk_z),
);
let st_loc: StructureLocator = child_locator.into();
location = LocationPage {
structure_id: request.structure_id.0,
node_id: child_locator.as_usize() as u32,
node_id: st_loc.0 as u32,
producer_id: request.producer_id.0,
anchor,
};
@@ -1838,3 +2036,4 @@ where
location,
)
}
*/