Compare commits

..
4 Commits
Author SHA1 Message Date
octagonal 11d26ad16b memory profile 2026-11-02 12:06:56 +01:00
octagonal 9b9f637842 Adding depth sorting to new cache 2026-11-01 22:17:40 +01:00
octagonal b8658b7186 Parallel generation 2026-11-01 17:19:25 +01:00
octagonal e4cbafb632 timestamp radix profile 2026-10-31 12:15:57 +01:00
23 changed files with 791 additions and 228 deletions
+49
View File
@@ -0,0 +1,49 @@
use crate::gi_pipeline::sparse_set::GpuSparseSet;
use crate::voxel_cache::VoxelCache;
use crate::voxel_cache::{self};
mod sparse_set;
pub struct VoxelGiPipeline<const N: usize>
where
[(); N * N * N]:,
{
voxel_cache: VoxelCache<N>,
/// Keeps a set of the leaves present in the cache.
/// Kept in correspondancy with the leaf list attribute within the cache
leaf_list: GpuSparseSet,
leaf_list_attribute: usize,
}
impl<const N: usize> VoxelGiPipeline<N>
where
[(); N * N * N]:,
{
pub fn new(
device: &wgpu::Device,
cache_size: usize,
cache_layout: &mut voxel_cache::CacheLayout,
) -> Self
{
let leaf_list_attribute = cache_layout.add_attribute(voxel_cache::CacheAttribute {
label: Some("VoxelGiPipeline::leaf_list_pointer"),
word_count: 1,
init: voxel_cache::CacheAttributeInit::External,
});
cache_layout.add_attribute(voxel_cache::CacheAttribute {
label: Some("VoxelGiPipeline::radiance"),
word_count: 3,
init: voxel_cache::CacheAttributeInit::DontTouch,
});
let voxel_cache = VoxelCache::new(device, cache_size, cache_layout);
Self {
voxel_cache,
leaf_list: GpuSparseSet::new(device, cache_size),
leaf_list_attribute,
}
}
}
+57
View File
@@ -0,0 +1,57 @@
use wgpu::util::DeviceExt;
use crate::gpu::create_multi_buffers_bind_group;
use crate::gpu::create_multi_buffers_bind_group_layout;
/// To keep a set of voxel nodes in the cache
pub struct GpuSparseSet
{
/// Maximum size of the set
size: usize,
/// Contains pointers to nodes in the cache
pointers_buffer: wgpu::Buffer,
/// Amount of elements in the set
count_buffer: wgpu::Buffer,
bind_group: wgpu::BindGroup,
}
impl GpuSparseSet
{
pub fn new(device: &wgpu::Device, size: usize) -> Self
{
let pointers_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("GpuSparseSet::pointers_buffer"),
usage: wgpu::BufferUsages::STORAGE,
contents: bytemuck::cast_slice(&vec![0u32; size]),
});
let count_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("GpuSparseSet::count_buffer"),
usage: wgpu::BufferUsages::STORAGE,
contents: bytemuck::bytes_of(&0u32),
});
let bind_group_layout = Self::create_bind_group_layout(device);
let bind_group = create_multi_buffers_bind_group(
device,
&bind_group_layout,
&[&pointers_buffer, &count_buffer],
Some("GpuSparseSet::bind_group"),
);
Self {
size,
pointers_buffer,
count_buffer,
bind_group,
}
}
pub fn create_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout
{
create_multi_buffers_bind_group_layout(device, 2, Some("GpuSparseSet::bind_group_layout"))
}
}
+60
View File
@@ -2,3 +2,63 @@
pub mod buffer_compactor;
pub mod indirect_buffer;
pub mod radix_sort;
// Utilities
pub fn create_multi_buffers_bind_group_layout(
device: &wgpu::Device,
count: u32,
label: Option<&str>,
) -> wgpu::BindGroupLayout
{
let entries = (0..count)
.map(|i| wgpu::BindGroupLayoutEntry {
binding: i,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
})
.collect::<Vec<_>>();
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label,
entries: &entries,
})
}
pub fn create_multi_buffers_bind_group(
device: &wgpu::Device,
layout: &wgpu::BindGroupLayout,
buffers: &[&wgpu::Buffer],
label: Option<&str>,
) -> wgpu::BindGroup
{
let entries = buffers
.iter()
.enumerate()
.map(|(i, buffer)| wgpu::BindGroupEntry {
binding: i as u32,
resource: buffer.as_entire_binding(),
})
.collect::<Vec<_>>();
device.create_bind_group(&wgpu::BindGroupDescriptor {
label,
layout,
entries: &entries,
})
}
pub fn create_multi_buffers_bg_bg_layout(
device: &wgpu::Device,
buffers: &[&wgpu::Buffer],
label: Option<&str>,
) -> (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)
}
+2
View File
@@ -12,6 +12,8 @@ use wgpu::Device;
use wgpu::QuerySet;
use wgpu::Queue;
pub mod memory_profiler;
macro_rules! begin_frame {
($encoder:ident) => {
let mut $encoder = $encoder.begin_frame(None);
+205
View File
@@ -0,0 +1,205 @@
use std::ops::Deref;
use wgpu::util::DeviceExt;
pub struct Buffer
{
pub label: String,
pub size: usize,
}
pub struct Group
{
pub label: &'static str,
size: Option<usize>,
pub buffers: Vec<Buffer>,
pub sub_groups: Vec<Group>,
}
impl Group
{
pub fn new(label: &'static str) -> Self
{
Self {
label,
size: None,
buffers: Vec::new(),
sub_groups: Vec::new(),
}
}
pub fn size(&self) -> usize
{
self.size.unwrap_or_else(|| {
self.buffers.iter().map(|b| b.size).sum::<usize>()
+ self.sub_groups.iter().map(Self::size).sum::<usize>()
})
}
pub fn size_mut(&mut self) -> usize
{
*self.size.get_or_insert_with(|| {
self.buffers.iter().map(|b| b.size).sum::<usize>()
+ self
.sub_groups
.iter_mut()
.map(Self::size_mut)
.sum::<usize>()
})
}
}
pub struct MemoryProfile
{
stack: Vec<Group>,
}
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
{
let buffer = self.device.create_buffer(desc);
self.profile.add_buffer(Buffer {
label: desc.label.unwrap_or("Unnamed").into(),
size: desc.size as usize,
});
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(),
size: desc.contents.len(),
});
buffer
}
pub fn group<'b>(&'b mut self, group_label: &'static str) -> Device<'b>
where
'a: 'b,
{
self.profile.open_group(group_label);
Device {
device: self.device.clone(),
profile: self.profile,
}
}
}
impl<'a> Drop for Device<'a>
{
fn drop(&mut self)
{
self.profile.close_group();
}
}
impl Deref for Device<'_>
{
type Target = wgpu::Device;
fn deref(&self) -> &Self::Target
{
&self.device
}
}
impl MemoryProfile
{
pub fn new(label: &'static str) -> Self
{
Self {
stack: vec![Group::new(label)],
}
}
pub fn begin(&mut self, device: &wgpu::Device) -> Device
{
Device {
device: device.clone(),
profile: self,
}
}
pub fn terminate(mut self) -> Group
{
self.stack.pop().unwrap()
}
fn open_group(&mut self, label: &'static str)
{
self.stack.push(Group::new(label));
}
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()
{
parent.sub_groups.push(group);
}
else
{
self.stack.push(group);
}
}
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
{
self.fmt_with_indent(f, 0)
}
}
impl Group
{
fn fmt_with_indent(&self, f: &mut fmt::Formatter<'_>, indent: usize) -> fmt::Result
{
let prefix = " ".repeat(indent);
writeln!(
f,
"{}{} ({} bytes)",
prefix,
self.label,
self.size.unwrap_or_else(|| self.size())
)?;
// Print buffers
for buffer in &self.buffers
{
writeln!(
f,
"{} ├── {} ({} bytes)",
prefix, buffer.label, buffer.size
)?;
}
// Print subgroups
for (i, group) in self.sub_groups.iter().enumerate()
{
group.fmt_with_indent(f, indent + 1)?;
}
Ok(())
}
}
+70 -56
View File
@@ -17,6 +17,8 @@ use glam::Mat4;
use glam::Vec3;
use glam::Vec4;
use itertools::Itertools;
use rayon::iter::IntoParallelRefIterator;
use rayon::iter::ParallelIterator;
use wgpu::BindGroupLayout;
use wgpu::Buffer;
use wgpu::BufferUsages;
@@ -48,6 +50,8 @@ use winit::window::WindowId;
use crate::camera::Camera;
use crate::egui_renderer::EguiRenderer;
use crate::gpu::radix_sort;
use crate::gpu::radix_sort::RadixSorter;
use crate::gpu_profiler::Frame;
use crate::gpu_profiler::Profile;
use crate::gpu_profiler::ProfilingEncoder;
@@ -200,6 +204,7 @@ impl State
max_storage_buffers_per_shader_stage: 32,
max_binding_array_elements_per_shader_stage: 16,
max_bind_groups: 8,
max_storage_buffer_binding_size: 1_000_000_000,
..Default::default()
},
..Default::default()
@@ -215,7 +220,7 @@ impl State
//let elt_count = 100_000;
//let elt_count = (21 * 4096) as u32;
//let elt_count = 3000 as u32;
let elt_count_real = 500_000;
let elt_count_real = 1_000_000;
let count_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("count_buffer"),
usage: wgpu::BufferUsages::STORAGE,
@@ -227,7 +232,7 @@ impl State
let org_big_value_buffer = (0..(elt_count as u32)).collect::<Vec<_>>();
let org_big_key_buffer = org_big_value_buffer
.iter()
.map(|_| random::<u32>())
.map(|_| rand::random::<u32>())
//.map(|_| random_range(1..256))
.collect::<Vec<_>>();
@@ -276,6 +281,7 @@ impl State
&big_key_buffer,
&big_value_buffer,
Some(&count_buffer),
None,
&mut encoder,
radix_sort::RadixSortDirection::Ascending,
);
@@ -354,7 +360,7 @@ impl State
init: voxel_cache::CacheAttributeInit::External,
});
let voxel_cache = VoxelCache::<4>::new(&device, 100_000, &layout);
let voxel_cache = VoxelCache::<4>::new(&device, 200_000, &layout);
let request_buffer = CacheRequestBuffer::new(&device, 1024);
let insertion_data = CacheInsertionData::new(&device, 1024, &layout);
@@ -377,9 +383,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
@@ -389,8 +395,8 @@ impl State
let total_chunk_count = terrain_height * terrain_width * terrain_alt;
let structure_table = FixedStructureTable::new(&device, total_chunk_count, &layout);
let structure_table_request_buffer = CacheRequestBuffer::new(&device, 1024);
let structure_table_insertion_data = CacheInsertionData::new(&device, 1024, &layout);
let structure_table_request_buffer = CacheRequestBuffer::new(&device, 128);
let structure_table_insertion_data = CacheInsertionData::new(&device, 128, &layout);
let chunk_instances = (0..terrain_alt)
.cartesian_product(0..terrain_height)
.cartesian_product(0..terrain_width)
@@ -1151,24 +1157,24 @@ impl State
}
// ~~ Build usage buffer histogram
// let time_stamp = self.voxel_cache.lock().current_timestamp();
// let cloned_usage_histogram = self.usage_vec.clone();
// DownloadBuffer::read_buffer(
// &self.device,
// &self.queue,
// &self.voxel_cache.lock().usage_buffer.slice(..),
// move |slice| {
// let slice = slice.unwrap();
// let cache_slice: &[u32] = bytemuck::cast_slice(&slice);
// let mut v = vec![0; 100];
// for x in cache_slice.iter()
// {
// let diff = (time_stamp - x).min(99);
// v[diff as usize] += 1;
// }
// *cloned_usage_histogram.lock() = v;
// },
// );
let time_stamp = self.voxel_cache.lock().current_timestamp();
let cloned_usage_histogram = self.usage_vec.clone();
DownloadBuffer::read_buffer(
&self.device,
&self.queue,
&self.voxel_cache.lock().usage_timestamps().slice(..),
move |slice| {
let slice = slice.unwrap();
let cache_slice: &[u32] = bytemuck::cast_slice(&slice);
let mut v = vec![0; 100];
for x in cache_slice.iter()
{
let diff = (time_stamp - x).min(99);
v[diff as usize] += 1;
}
*cloned_usage_histogram.lock() = v;
},
);
// DownloadBuffer::read_buffer(
// &self.device,
@@ -1281,19 +1287,23 @@ impl State
let mut normal_attributes: Vec<[[f32; 3]; 64]> = vec![];
let mut location_pages = vec![];
for request in request_informations.iter()
{
let (colors, normals, insertion_info, location) = fullfill_request(
cloned_generator.as_ref(),
request,
cloned_map.as_ref(),
);
insertion_infos.push(insertion_info);
color_attributes.push(colors);
normal_attributes.push(std::array::from_fn(|i| normals[i].into()));
location_pages.push(location);
}
request_informations
.par_iter()
.map(|request| {
fullfill_request(
cloned_generator.as_ref(),
request,
cloned_map.as_ref(),
)
})
.collect::<Vec<_>>()
.into_iter()
.for_each(|(colors, normals, insertion_info, location)| {
insertion_infos.push(insertion_info);
color_attributes.push(colors);
normal_attributes.push(std::array::from_fn(|i| normals[i].into()));
location_pages.push(location);
});
cloned_queue.write_buffer(
cloned_insertion_data.insertion_information_buffer(),
@@ -1360,19 +1370,23 @@ impl State
let mut normal_attributes: Vec<[[f32; 3]; 64]> = vec![];
let mut location_pages = vec![];
for request in request_informations.iter()
{
let (colors, normals, insertion_info, location) = fullfill_request(
cloned_generator.as_ref(),
request,
cloned_map.as_ref(),
);
insertion_infos.push(insertion_info);
color_attributes.push(colors);
normal_attributes.push(std::array::from_fn(|i| normals[i].into()));
location_pages.push(location);
}
request_informations
.par_iter()
.map(|request| {
fullfill_request(
cloned_generator.as_ref(),
request,
cloned_map.as_ref(),
)
})
.collect::<Vec<_>>()
.into_iter()
.for_each(|(colors, normals, insertion_info, location)| {
insertion_infos.push(insertion_info);
color_attributes.push(colors);
normal_attributes.push(std::array::from_fn(|i| normals[i].into()));
location_pages.push(location);
});
cloned_queue.write_buffer(
cloned_st_insertion_data.insertion_information_buffer(),
@@ -1567,14 +1581,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,
),
],
);
+65 -14
View File
@@ -1,15 +1,10 @@
use std::f32::EPSILON;
use std::f32::INFINITY;
use std::fs::File;
use std::path::Path;
use glam::Vec3;
use itertools::Itertools;
use noise::Fbm;
use noise::NoiseFn;
use noise::Perlin;
use noise::Simplex;
use noise::Worley;
use rand::random;
use crate::sparse_tree::Color;
@@ -483,7 +478,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 +488,8 @@ impl<const N: usize> SdfGenerator<N>
{
Self {
chunk_power,
perlin: Perlin::new(67),
//perlin: Fbm::new(67),
perlin: Simplex::new(67),
}
}
}
@@ -514,14 +511,68 @@ where
// 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 sdf = |x: f32, y: f32, z: f32| {
// 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]) - 0.1) * 0.23;
// let dist = val * scale as f64;
// return dist as f32;
// };
let val = self.perlin.get([tx as f64, ty as f64, tz as f64]);
let dist = val * 128.;
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);
+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)
}
}
+58 -69
View File
@@ -3,13 +3,16 @@ use std::num::NonZero;
use wgpu::CommandEncoder;
use wgpu::Device;
use crate::gpu::create_multi_buffers_bg_bg_layout;
use crate::gpu::create_multi_buffers_bind_group_layout;
use crate::gpu::radix_sort::RadixSorter;
use crate::gpu_profiler;
use crate::gpu_profiler::ScopeEncoder;
use crate::gpu_profiler::memory_profiler;
use crate::gpu_profiler::memory_profiler::MemoryProfile;
use crate::voxel_cache::attributes::CacheAttributes;
use crate::voxel_cache::eviction::CacheEvictor;
use crate::voxel_cache::insertion::CacheInsertionData;
use crate::voxel_cache::layout::CacheLayout;
use crate::voxel_cache::pipelines::CacheInsertionPass;
use crate::voxel_cache::pipelines::CacheInvalidationPass;
use crate::voxel_cache::pipelines::WritePointersPass;
@@ -28,18 +31,21 @@ pub mod schema;
pub mod structure;
pub mod tables;
pub use layout::*;
pub use layout::CacheAttribute;
pub use layout::CacheAttributeInit;
pub use layout::CacheLayout;
/// Stores some ressources that can be reused throughout the modules of the cache
struct CacheRessources<const N: usize>
{
scratch_buffer: wgpu::Buffer,
scratch_buffer_bind_group: wgpu::BindGroup,
radix_sorter: RadixSorter,
}
impl<const N: usize> CacheRessources<N>
{
pub fn new(device: &Device, page_count: usize) -> Self
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"),
@@ -50,11 +56,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>
@@ -106,11 +132,20 @@ where
{
pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self
{
let structure = CacheStructure::new(device, page_count);
let attributes = CacheAttributes::from_cache_layout(device, layout, page_count);
let request_handler = CacheRequestHandler::new(device, page_count);
let evictor = CacheEvictor::new(device, page_count, 0u32);
let common_ressources = CacheRessources::new(device, page_count);
let mut cache_memory_profile = MemoryProfile::new("VoxelCache");
let mut mem_device = cache_memory_profile.begin(device);
let structure = CacheStructure::new(&mut mem_device.group("CacheStructure"), page_count);
let attributes = CacheAttributes::from_cache_layout(
&mut mem_device.group("CacheAttributes"),
layout,
page_count,
);
let request_handler =
CacheRequestHandler::new(&mut mem_device.group("CacheRequestHandler"), page_count);
let evictor = CacheEvictor::new(&mut mem_device.group("CacheEvictor"), page_count, 0u32);
let common_ressources =
CacheRessources::new(&mut mem_device.group("CacheRessources"), page_count);
let write_requests_pass = WriteRequestsPass::new(device, page_count, layout);
let cache_insertion_pass = CacheInsertionPass::new(device, page_count, layout);
@@ -125,6 +160,10 @@ where
&evictor,
);
drop(mem_device);
let mut root_group = cache_memory_profile.terminate();
println!("{}", root_group);
Self {
page_count,
structure,
@@ -185,8 +224,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()
{
@@ -351,64 +394,10 @@ where
{
&self.raytrace_bind_group
}
}
// Utilities
fn create_multi_buffers_bind_group_layout(
device: &Device,
count: u32,
label: Option<&str>,
) -> wgpu::BindGroupLayout
{
let entries = (0..count)
.map(|i| wgpu::BindGroupLayoutEntry {
binding: i,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
})
.collect::<Vec<_>>();
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label,
entries: &entries,
})
}
fn create_multi_buffers_bind_group(
device: &Device,
layout: &wgpu::BindGroupLayout,
buffers: &[&wgpu::Buffer],
label: Option<&str>,
) -> wgpu::BindGroup
{
let entries = buffers
.iter()
.enumerate()
.map(|(i, buffer)| wgpu::BindGroupEntry {
binding: i as u32,
resource: buffer.as_entire_binding(),
})
.collect::<Vec<_>>();
device.create_bind_group(&wgpu::BindGroupDescriptor {
label,
layout,
entries: &entries,
})
}
fn create_multi_buffers_bg_bg_layout(
device: &Device,
buffers: &[&wgpu::Buffer],
label: Option<&str>,
) -> (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)
// For debugging
pub fn usage_timestamps(&self) -> &wgpu::Buffer
{
self.evictor.timestamp_pages_buffer()
}
}
+12 -3
View File
@@ -2,6 +2,7 @@ use wgpu::BindGroupLayout;
use wgpu::Buffer;
use wgpu::BufferUsages;
use crate::gpu_profiler::memory_profiler;
use crate::voxel_cache::layout::CacheLayout;
/// Contains instanciated gpu buffers to hold data for cache attributes
@@ -15,14 +16,22 @@ pub struct CacheAttributes<const N: usize>
impl<const N: usize> CacheAttributes<N>
{
pub fn from_cache_layout(device: &wgpu::Device, layout: &CacheLayout, page_count: usize)
-> Self
pub fn from_cache_layout(
device: &mut memory_profiler::Device,
layout: &CacheLayout,
page_count: usize,
) -> Self
{
let attribute_buffers = layout
.attributes
.iter()
.map(|attribute| {
attribute.create_buffer(device, N * N * N, page_count, BufferUsages::STORAGE)
attribute.create_buffer_profiled(
device,
N * N * N,
page_count,
BufferUsages::STORAGE,
)
})
.collect::<Vec<_>>();
+103 -56
View File
@@ -6,13 +6,14 @@ use wgpu::ComputePipeline;
use wgpu::include_wgsl;
use wgpu::util::DeviceExt;
use crate::gpu::create_multi_buffers_bind_group;
use crate::gpu::radix_sort;
use crate::gpu_profiler::ScopeEncoder;
use crate::gpu_profiler::memory_profiler;
use crate::gpu_profiler::{self};
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,
@@ -41,7 +44,11 @@ pub struct CacheEvictor
impl CacheEvictor
{
pub fn new(device: &wgpu::Device, page_count: usize, initial_timestamp: u32) -> Self
pub fn new(
device: &mut memory_profiler::Device,
page_count: usize,
initial_timestamp: u32,
) -> Self
{
let timestamp_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("CacheUsage::timestamp_pages"),
@@ -62,30 +69,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 +77,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 +126,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,20 +139,61 @@ 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);
}
ressources.radix_sorter.sort(
device,
&ressources.scratch_buffer,
&self.lru_list,
None,
Some(self.page_count),
&mut encoder,
radix_sort::RadixSortDirection::Ascending,
);
// 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);
}
{
gpu_profiler::begin_scope!(encoder, "timestamp radix");
ressources.radix_sorter.sort(
device,
&ressources.scratch_buffer,
&self.lru_list,
None,
Some(self.page_count),
&mut encoder,
radix_sort::RadixSortDirection::Ascending,
);
}
}
pub fn bind_group(&self) -> &BindGroup
+25
View File
@@ -1,5 +1,7 @@
use wgpu::BufferUsages;
use crate::gpu_profiler::memory_profiler;
/// Defines how a [`VoxelCache`]'s attribute is populated upon populating a page
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CacheAttributeInit
@@ -26,6 +28,29 @@ pub struct CacheAttribute
impl CacheAttribute
{
pub fn create_buffer_profiled(
&self,
device: &mut memory_profiler::Device,
child_count: usize,
page_count: usize,
usage: wgpu::BufferUsages,
) -> wgpu::Buffer
{
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(
format!(
"VoxelCacheAttribute ({}) {} word(s)",
self.label.unwrap_or("no-name"),
self.word_count
)
.as_str(),
),
size: (self.word_count as usize * page_count * child_count * size_of::<u32>()) as u64,
usage,
mapped_at_creation: false,
})
}
/// Creates the wgpu buffer necessary to store this attribute in the cache
pub fn create_buffer(
&self,
+3 -2
View File
@@ -10,12 +10,13 @@ use wgpu::include_wgsl;
use wgpu::util::DeviceExt;
use crate::gpu::buffer_compactor::NonZeroBufferCompactor;
use crate::gpu::create_multi_buffers_bind_group;
use crate::gpu::radix_sort::{self};
use crate::gpu_profiler::ScopeEncoder;
use crate::gpu_profiler::memory_profiler;
use crate::gpu_profiler::{self};
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::schema::RequestInformation;
use crate::voxel_cache::schema::RequestMeta;
@@ -65,7 +66,7 @@ pub struct CacheRequestBuffer
impl<const N: usize> CacheRequestHandler<N>
{
pub fn new(device: &wgpu::Device, page_count: usize) -> Self
pub fn new(device: &mut memory_profiler::Device, page_count: usize) -> Self
{
let request_counts_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("CacheRequestHandler::request_counts_pages"),
+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;
+11 -6
View File
@@ -2,10 +2,10 @@ use wgpu::BindGroup;
use wgpu::BindGroupLayout;
use wgpu::Buffer;
use wgpu::BufferUsages;
use wgpu::util::DeviceExt;
use crate::voxel_cache::create_multi_buffers_bind_group;
use crate::voxel_cache::create_multi_buffers_bind_group_layout;
use crate::gpu::create_multi_buffers_bind_group;
use crate::gpu::create_multi_buffers_bind_group_layout;
use crate::gpu_profiler::memory_profiler;
use crate::voxel_cache::schema::DepthPage;
use crate::voxel_cache::schema::StructurePage;
@@ -30,7 +30,7 @@ where
pub const LOCATION_PAGES_BINDING: u32 = 1;
pub const DEPTH_PAGES_BINDING: u32 = 2;
pub fn new(device: &wgpu::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"),
@@ -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
}
}
+11 -2
View File
@@ -2,6 +2,7 @@ use wgpu::util::DeviceExt;
use crate::gpu::indirect_buffer::IndirectBuffer1D;
use crate::gpu_profiler::ScopeEncoder;
use crate::gpu_profiler::memory_profiler::MemoryProfile;
use crate::voxel_cache::CacheInvalidable;
use crate::voxel_cache::CacheRessources;
use crate::voxel_cache::create_multi_buffers_bg_bg_layout;
@@ -68,7 +69,15 @@ impl FixedStructureTable
contents: bytemuck::cast_slice(&vec![pointer; size]),
});
let request_handler = CacheRequestHandler::<1>::new(device, size);
let mut memory_profile = MemoryProfile::new("FixedStructureTable");
let mut mem_device = memory_profile.begin(device);
let request_handler =
CacheRequestHandler::<1>::new(&mut mem_device.group("CacheRequestHandler"), size);
let common_ressources =
CacheRessources::new(&mut mem_device.group("CacheRessources"), size);
drop(mem_device);
drop(memory_profile);
let (pointers_bind_group_layout, pointers_bind_group) = create_multi_buffers_bg_bg_layout(
device,
@@ -167,7 +176,7 @@ impl FixedStructureTable
size,
pointers,
pointers_bind_group,
common_ressources: CacheRessources::new(device, size),
common_ressources,
request_handler,
indirect_buffer: IndirectBuffer1D::new(device),
write_requests_pass,