Adding depth sorting to new cache

This commit is contained in:
2026-11-01 22:17:40 +01:00
parent b8658b7186
commit 9b9f637842
14 changed files with 258 additions and 88 deletions
+10 -10
View File
@@ -359,7 +359,7 @@ impl State
init: voxel_cache::CacheAttributeInit::External,
});
let voxel_cache = VoxelCache::<4>::new(&device, 150_000, &layout);
let voxel_cache = VoxelCache::<4>::new(&device, 100_000, &layout);
let request_buffer = CacheRequestBuffer::new(&device, 1024);
let insertion_data = CacheInsertionData::new(&device, 1024, &layout);
@@ -382,9 +382,9 @@ impl State
// let terrain_width = terrain_generator.chunk_width;
// let terrain_height = terrain_generator.chunk_height;
// let terrain_alt = terrain_generator.chunk_alt;
let terrain_width = 10;
let terrain_height = 10;
let terrain_alt = 10;
let terrain_width = 20;
let terrain_height = 20;
let terrain_alt = 20;
println!(
"Chunk count : {}",
terrain_width * terrain_height * terrain_alt
@@ -1279,7 +1279,7 @@ impl State
return;
}
println!("Cache : {} requests", request_informations.len());
//println!("Cache : {} requests", request_informations.len());
let mut insertion_infos = vec![];
let mut color_attributes = vec![];
@@ -1362,7 +1362,7 @@ impl State
return;
}
println!("Structure table: {} requests", request_informations.len());
//println!("Structure table: {} requests", request_informations.len());
let mut insertion_infos = vec![];
let mut color_attributes = vec![];
@@ -1580,14 +1580,14 @@ impl State
&self.device,
&mut scoped_encoder,
&mut [
&mut VoxelCacheInsertion::InternalRequest(
&self.cache_insertion,
&self.request_buffer,
),
&mut VoxelCacheInsertion::ExternalRequest(
&self.structure_table_cache_insertion,
&mut *locked_st,
),
&mut VoxelCacheInsertion::InternalRequest(
&self.cache_insertion,
&self.request_buffer,
),
],
);
+70 -10
View File
@@ -5,10 +5,14 @@ use std::path::Path;
use glam::Vec3;
use itertools::Itertools;
use noise::Billow;
use noise::Cylinders;
use noise::Fbm;
use noise::NoiseFn;
use noise::Perlin;
use noise::RidgedMulti;
use noise::Simplex;
use noise::SuperSimplex;
use noise::Worley;
use rand::random;
@@ -483,7 +487,8 @@ where
pub struct SdfGenerator<const N: usize>
{
chunk_power: usize,
perlin: Perlin,
//perlin: Fbm<Simplex>,
perlin: Simplex,
}
impl<const N: usize> SdfGenerator<N>
@@ -492,7 +497,8 @@ impl<const N: usize> SdfGenerator<N>
{
Self {
chunk_power,
perlin: Perlin::new(67),
//perlin: Fbm::new(67),
perlin: Simplex::new(67),
}
}
}
@@ -510,20 +516,74 @@ where
chunk_pos: (usize, usize, usize),
) -> ProducedChunk<N>
{
let sdf = |x: f32, y: f32, z: f32| {
Vec3::new((x % 1024.) - 512., (y % 1024.) - 512., (z % 1024.) - 512.).length() - 512.
};
// let sdf = |x: f32, y: f32, z: f32| {
// Vec3::new((x % 1024.) - 512., (y % 1024.) - 512., (z % 1024.) - 512.).length() - 512.
// };
// let sdf = |x: f32, y: f32, z: f32| {
// let tx = x / 512.;
// let ty = y / 512.;
// let tz = z / 512.;
// let scale = 128.;
// let tx = x / scale;
// let ty = y / scale;
// let tz = z / scale;
//
// let val = self.perlin.get([tx as f64, ty as f64, tz as f64]);
// let dist = val * 128.;
// let val = (self.perlin.get([tx as f64, ty as f64, tz as f64]) - 0.1) * 0.23;
// let dist = val * scale as f64;
// return dist as f32;
// };
// let sdf = |x: f32, y: f32, z: f32| {
// let scale = 1024. * 10.;
// let domain = 1.;
// let tx = map(x, 0., scale, -domain, domain);
// let ty = map(y, 0., scale, -domain, domain);
// let tz = map(z, 0., scale, -domain, domain);
// nebula_sdf(tx, ty, tz) * 0.2 * scale / domain
// };
let sdf = |x: f32, y: f32, z: f32| {
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()
}
let scale = 10. * 1024.;
let height = 5000.;
let tx = x / scale;
let tz = z / scale;
let ty = y;
let val = map(
self.perlin.get([tx as f64, tz as f64]) as f32,
-1.,
1.,
1.,
height,
);
// Trees
let tree_space = 10.;
let mx = x.rem_euclid(tree_space);
let mz = z.rem_euclid(tree_space);
let tree_x = x.div_euclid(tree_space);
let tree_z = z.div_euclid(tree_space);
let h1 = hash([tree_x, tree_z, 1.]);
let h2 = hash([tree_z, tree_x, 1.]);
let h3 = hash([tree_z, tree_x, tree_z]);
let d = Vec3::new(
mx + h1 * 3. - tree_space * 0.5,
(ty - val) * 0.2,
mz + h2 * 3. - tree_space * 0.5,
)
.length()
- 4. * map(h3, 0., 1., 0.8, 1.2);
let bound = 1. / scale * height;
((ty - val) / (1. + bound.powf(2.)).sqrt()).min(d)
};
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);
+4 -4
View File
@@ -32,10 +32,10 @@ impl Color
pub fn as_packed_u32(&self) -> u32
{
let mapped_r = (self.0 * 255.0) as u32;
let mapped_g = (self.1 * 255.0) as u32;
let mapped_b = (self.2 * 255.0) as u32;
let mapped_a = (self.3 * 255.0) as 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)
}
}
+27 -2
View File
@@ -34,6 +34,7 @@ pub use layout::*;
struct CacheRessources<const N: usize>
{
scratch_buffer: wgpu::Buffer,
scratch_buffer_bind_group: wgpu::BindGroup,
radix_sorter: RadixSorter,
}
@@ -50,11 +51,31 @@ impl<const N: usize> CacheRessources<N>
let radix_sorter = RadixSorter::new(device, page_count * N * N * N);
let (_, scratch_buffer_bind_group) = create_multi_buffers_bg_bg_layout(
device,
&[&scratch_buffer],
Some("CacheRessources::scratch_buffer_bind_group"),
);
Self {
scratch_buffer,
scratch_buffer_bind_group,
radix_sorter,
}
}
pub fn create_scratch_buffer_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout
{
create_multi_buffers_bind_group_layout(
device,
1,
Some("CacheRessources::scratch_buffer_bind_group_layout"),
)
}
pub fn scratch_buffer_bind_group(&self) -> &wgpu::BindGroup
{
&self.scratch_buffer_bind_group
}
}
pub struct VoxelCache<const N: usize>
@@ -185,8 +206,12 @@ where
gpu_profiler::begin_scope!(encoder, "insertion");
let new_timestamp = self.frame_timestamp + 1;
self.evictor
.prepare_eviction_list(device, &self.common_ressources, &mut encoder);
self.evictor.prepare_eviction_list(
device,
&self.common_ressources,
&self.structure,
&mut encoder,
);
for insertion in insertions.iter()
{
+84 -44
View File
@@ -13,6 +13,7 @@ use crate::voxel_cache::CacheRessources;
use crate::voxel_cache::create_multi_buffers_bg_bg_layout;
use crate::voxel_cache::create_multi_buffers_bind_group;
use crate::voxel_cache::create_multi_buffers_bind_group_layout;
use crate::voxel_cache::structure::CacheStructure;
/// Retains usage information about pages in the cache under the form of timestamps.
/// Produces a list of LRU eviction order, from which the cache can pull pages to recycle
@@ -29,10 +30,12 @@ pub struct CacheEvictor
/// When reusing pages, count of lru pages consumed
consumed_count: wgpu::Buffer,
// Reset lru list pass
reset_lru_list_bind_group: BindGroup,
reset_lru_list_pass: ComputePipeline,
reset_lru_list_dispatch: u32,
/// To reset lru indices between insertions
reset_lru_pass: wgpu::ComputePipeline,
/// To copy corresponding timestamp values after first depth sort
indirect_copy_pass: wgpu::ComputePipeline,
pipelines_dispatch_count: u32,
// For external passes
bind_group_layout: BindGroupLayout,
@@ -62,30 +65,6 @@ impl CacheEvictor
contents: bytemuck::bytes_of(&0u32),
});
let (reset_lru_list_bg_layout, reset_lru_list_bind_group) =
create_multi_buffers_bg_bg_layout(
device,
&[&lru_list, &consumed_count],
Some("CacheEvictor::reset_lru_list_bind_group"),
);
let reset_lru_list_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("CacheEvictor::reset_lru_list_pipeline_layout"),
bind_group_layouts: &[Some(&reset_lru_list_bg_layout)],
immediate_size: 0,
});
let reset_lru_list_pass =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("CacheEvictor::reset_lru_list_pass"),
layout: Some(&reset_lru_list_pipeline_layout),
module: &device.create_shader_module(include_wgsl!("./shaders/eviction.wgsl")),
entry_point: Some("reset_lru_list"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
});
let bind_group_layout = Self::create_bind_group_layout(device);
let bind_group = create_multi_buffers_bind_group(
device,
@@ -94,15 +73,45 @@ impl CacheEvictor
Some("CacheEvictor::bind_group"),
);
let pipelines_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("CacheEvictor::reset_lru_list_pipeline_layout"),
bind_group_layouts: &[
Some(&bind_group_layout),
Some(&CacheStructure::<1>::create_bind_group_layout(device)),
Some(&CacheRessources::<1>::create_scratch_buffer_bind_group_layout(device)),
],
immediate_size: 0,
});
let shader_module = device.create_shader_module(include_wgsl!("./shaders/eviction.wgsl"));
let reset_lru_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("CacheEvictor::reset_lru_pass"),
layout: Some(&pipelines_layout),
module: &shader_module,
entry_point: Some("reset_lru_list"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
});
let indirect_copy_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("CacheEvictor::indirect_copy_pass"),
layout: Some(&pipelines_layout),
module: &shader_module,
entry_point: Some("indirect_copy"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
});
Self {
page_count,
timestamp_pages,
lru_list,
consumed_count,
reset_lru_list_bind_group,
reset_lru_list_pass,
reset_lru_list_dispatch: page_count.div_ceil(256) as u32,
reset_lru_pass,
indirect_copy_pass,
pipelines_dispatch_count: page_count.div_ceil(256) as u32,
bind_group_layout,
bind_group,
@@ -113,19 +122,12 @@ impl CacheEvictor
&self,
device: &wgpu::Device,
ressources: &CacheRessources<N>,
structure: &CacheStructure<N>,
encoder: &mut ScopeEncoder<CommandEncoder>,
)
) where
[(); N * N * N]:,
{
gpu_profiler::begin_scope!(encoder, "CacheEvictor::prepare_eviction_list");
// Use the scratch buffer as the sort work buffer
encoder.copy_buffer_to_buffer(
&self.timestamp_pages,
0,
&ressources.scratch_buffer,
0,
self.timestamp_pages.size(),
);
// Reset lru list
{
let mut reset_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
@@ -133,9 +135,47 @@ impl CacheEvictor
timestamp_writes: None,
});
reset_pass.set_bind_group(0, Some(&self.reset_lru_list_bind_group), &[]);
reset_pass.set_pipeline(&self.reset_lru_list_pass);
reset_pass.dispatch_workgroups(self.reset_lru_list_dispatch, 1, 1);
reset_pass.set_bind_group(0, Some(&self.bind_group), &[]);
reset_pass.set_bind_group(1, Some(structure.bind_group()), &[]);
reset_pass.set_bind_group(2, Some(ressources.scratch_buffer_bind_group()), &[]);
reset_pass.set_pipeline(&self.reset_lru_pass);
reset_pass.dispatch_workgroups(self.pipelines_dispatch_count, 1, 1);
}
// First sort nodes per depth
{
gpu_profiler::begin_scope!(encoder, "depth radix");
encoder.copy_buffer_to_buffer(
structure.depth_pages(),
0,
&ressources.scratch_buffer,
0,
structure.depth_pages().size(),
);
ressources.radix_sorter.sort(
device,
&ressources.scratch_buffer,
&self.lru_list,
None,
Some(self.page_count),
&mut encoder,
radix_sort::RadixSortDirection::Ascending,
);
}
{
gpu_profiler::begin_scope!(encoder, "indirect copy");
let mut indirect_copy_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("CacheEvictor::indirect_copy_pass"),
timestamp_writes: None,
});
indirect_copy_pass.set_bind_group(0, Some(&self.bind_group), &[]);
indirect_copy_pass.set_bind_group(1, Some(structure.bind_group()), &[]);
indirect_copy_pass.set_bind_group(2, Some(ressources.scratch_buffer_bind_group()), &[]);
indirect_copy_pass.set_pipeline(&self.indirect_copy_pass);
indirect_copy_pass.dispatch_workgroups(self.pipelines_dispatch_count, 1, 1);
}
{
+10
View File
@@ -115,6 +115,13 @@ pub struct LocationPage
/// Page storing the depth of the current node related to its root.
/// - 0xFFFFFFFF: Page unused
/// - 0..0xFFFFFFFF(excl): Depth
///
/// An external insertion gets the 0 depth.
/// Internal insertions get the parent's depth plus one.
///
/// As such, when inserting pages in the cache, we first sort the lru pages
/// by depth. This prevents replacing a high page that pointed to a deeper tree strucutre
/// effectively invalidating the minimum amount of data.
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
#[repr(C)]
pub struct DepthPage(pub u32);
@@ -152,6 +159,9 @@ pub struct RequestMeta
/// The children on which the request was issued
pub children_index: u32,
/// The depth on which the request was issued
pub depth: u32,
}
/// Structure information about the children of a node.
+2 -7
View File
@@ -15,7 +15,8 @@ struct RequestInformation
struct RequestMeta
{
page_index: u32,
children_index: u32
children_index: u32,
depth: u32
}
struct AttributeArray
@@ -29,12 +30,6 @@ struct LocationPage
node_id: u32,
}
struct DepthPage
{
depth: u32
}
fn child_information_occupied(info: u32) -> bool
{
return ((info >> 30) & 1) != 0;
+33 -2
View File
@@ -1,5 +1,15 @@
@group(0) @binding(0) var<storage, read_write> lru_list: array<u32>;
@group(0) @binding(1) var<storage, read_write> consumed_count: u32;
/// Group 0: Lru list
@group(0) @binding(0) var<storage, read_write> timestamp_pages: array<u32>;
@group(0) @binding(1) var<storage, read_write> lru_list: array<u32>;
@group(0) @binding(2) var<storage, read_write> consumed_count: u32;
/// Group 1: Cache structure
@group(1) @binding(0) var<storage, read_write> structure_pointer_pages: array<u32>; // UNUSED
@group(1) @binding(1) var<storage, read_write> structure_location_pages: array<u32>; // UNUSED
@group(1) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
/// Group 2: Scratch buffer
@group(2) @binding(0) var<storage, read_write> scratch_buffer: array<u32>;
/// Resets the lru list
@compute
@@ -17,3 +27,24 @@ fn reset_lru_list(@builtin(global_invocation_id) global_invocation_id: vec3<u32>
lru_list[index] = index;
consumed_count = 0;
}
/// Indirect copy, in between the depth sort and the timestamp sort
@compute
@workgroup_size(256, 1, 1)
fn indirect_copy(@builtin(global_invocation_id) global_invocation_id: vec3<u32>)
{
let index = global_invocation_id.x;
if(index >= arrayLength(&lru_list))
{
return;
}
// Index sorted by depth
let gather_index = lru_list[index];
// Fetch corresponding timestamp
let ts = timestamp_pages[gather_index];
// Copy to corresponding locatoin
scratch_buffer[index] = ts;
}
@@ -12,7 +12,7 @@
fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
request_buffer_count = request_handler_count;
request_buffer_count = min(request_handler_count, arrayLength(&request_buffer_informations));
if(index >= request_handler_count)
{
return;
@@ -26,6 +26,8 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
var request_meta: RequestMeta;
request_meta.page_index = 0;
request_meta.children_index = 0;
// u32s wrap arround
request_meta.depth = 0xFFFFFFFF;
request_buffer_informations[index] = request_info;
request_buffer_meta[index] = request_meta;
+3 -3
View File
@@ -5,7 +5,7 @@
/// Group 1: Cache structure
@group(1) @binding(0) var<storage, read_write> structure_pointer_pages: array<PointerPage>;
@group(1) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
@group(1) @binding(2) var<storage, read_write> structure_depth_pages: array<DepthPage>;
@group(1) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
// Group 2: Cache insertion data
@group(2) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
@@ -87,8 +87,8 @@ fn insertion(@builtin(global_invocation_id) gid: vec3<u32>)
// Mark page as dirty for invalidation
cache_evictor_timestamps[page_index] = new_timestamp;
// Copy new depth
// TODO: Copy new depth
// Set default depth
structure_depth_pages[page_index] = 0;
// Copy attributes
for(var attribute_index = u32(0); attribute_index < ATTRIBUTE_COUNT; attribute_index ++)
+1 -1
View File
@@ -1,7 +1,7 @@
/// Group 0: Cache structure
@group(0) @binding(0) var<storage, read_write> structure_pointer_pages: array<PointerPage>;
@group(0) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<DepthPage>;
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
// Group 1: Cache evictor
@group(1) @binding(0) var<storage, read_write> cache_evictor_timestamps: array<u32>;
+2 -1
View File
@@ -1,7 +1,7 @@
/// Group 0: Cache structure
@group(0) @binding(0) var<storage, read_write> structure_pointer_pages: array<PointerPage>;
@group(0) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<DepthPage>;
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
/// Group 1: Request buffer
@group(1) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
@@ -31,5 +31,6 @@ fn write_pointers(@builtin(global_invocation_id) gid: vec3<u32>)
{
structure_pointer_pages[meta_inf.page_index].pointers[meta_inf.children_index]
= child_pointer_make_available(page_index);
structure_depth_pages[page_index] = meta_inf.depth + 1;
}
}
+2 -1
View File
@@ -3,7 +3,7 @@
/// Group 0: Cache structure
@group(0) @binding(0) var<storage, read_write> structure_pointer_pages: array<PointerPage>;
@group(0) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<DepthPage>;
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
/// Group 1: Cache request handler
@group(1) @binding(0) var<storage, read_write> request_handler_count: u32; // Request count
@@ -40,6 +40,7 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
var request_meta: RequestMeta;
request_meta.page_index = page_index;
request_meta.children_index = request_location.children_index;
request_meta.depth = structure_depth_pages[page_index];
// Write them to request buffer
request_buffer_informations[index] = request_information;
+7 -2
View File
@@ -49,8 +49,8 @@ where
// Depth pages need to be initialized to unused, this prioritizes them in the
// depth sort used in the eviction pass
let depth_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("CacheStructure::location_pages"),
usage: BufferUsages::STORAGE,
label: Some("CacheStructure::depth_pages"),
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
contents: bytemuck::cast_slice(&vec![DepthPage::PAGE_UNUSED; page_count]),
});
@@ -91,4 +91,9 @@ where
{
&self.pointer_pages
}
pub fn depth_pages(&self) -> &Buffer
{
&self.depth_pages
}
}