List of evicted pages

This commit is contained in:
2026-10-13 21:17:24 +02:00
parent 2a85708b3a
commit a9785252c7
5 changed files with 535 additions and 125 deletions
+30
View File
@@ -0,0 +1,30 @@
use wgpu::Device;
use wgpu::Queue;
use crate::voxel_cache::PageList;
use crate::voxel_cache::VoxelCache;
use crate::voxel_cache::layout::VoxelCacheLayout;
pub struct VoxelGiPipeline<const N: usize>
{
voxel_cache: VoxelCache<N>,
// ~~ Leaf list ~~
// The leaf list is maintained in a sparse swap'n'pop fashion
leaf_list: PageList,
}
impl<const N: usize> VoxelGiPipeline<N>
{
pub fn new(device: &Device, queue: &Queue, cache_size: usize, layout: VoxelCacheLayout) -> Self
where
[(); N * N * N]:,
{
let voxel_cache = VoxelCache::new(cache_size, device.clone(), queue.clone(), &layout);
let leaf_list = PageList::new(device, cache_size);
VoxelGiPipeline {
voxel_cache,
leaf_list,
}
}
}
+269 -17
View File
@@ -1,17 +1,14 @@
use std::fmt::Debug;
use std::iter::Peekable;
use std::marker::PhantomData;
use std::ops::Deref;
use std::ops::DerefMut;
use egui::Sense;
use egui::Ui;
use egui::vec2;
use wgpu::Buffer;
use wgpu::BufferUsages;
use wgpu::CommandEncoder;
use wgpu::ComputePass;
use wgpu::Device;
use wgpu::QUERY_RESOLVE_BUFFER_ALIGNMENT;
use wgpu::QuerySet;
use wgpu::Queue;
@@ -21,7 +18,7 @@ macro_rules! begin_frame {
};
($encoder:ident, $name:literal) => {
let mut $encoder = $encoder.begin_frame(Some(literal));
let mut $encoder = $encoder.begin_frame(Some($name));
};
}
@@ -57,7 +54,8 @@ pub struct ProfilingEncoder<'enc>
scopes: Vec<Scope>,
index_stack: Vec<usize>,
compute_pass: Option<ComputePass<'static>>,
// Stores a compute pass when currently in one
compute_pass: Option<(usize, ComputePass<'static>)>,
}
pub struct GpuProfile
@@ -112,8 +110,18 @@ impl<'enc> ProfilingEncoder<'enc>
fn begin_scope(&mut self, scope_index: Option<usize>, name: &'static str) -> usize
{
let begin_query = self.query_set_allocator.allocate();
self.query_set_allocator
.write_timestamp(self.encoder, &begin_query);
if let Some((_, pass)) = &mut self.compute_pass
{
self.query_set_allocator
.write_compute_timestamp(pass, &begin_query);
}
else
{
self.query_set_allocator
.write_timestamp(self.encoder, &begin_query);
}
let scope = Scope {
name,
start_index: begin_query,
@@ -137,8 +145,16 @@ impl<'enc> ProfilingEncoder<'enc>
fn end_scope(&mut self, scope_index: usize)
{
let end_query = self.query_set_allocator.allocate();
self.query_set_allocator
.write_timestamp(self.encoder, &end_query);
if let Some((_, pass)) = &mut self.compute_pass
{
self.query_set_allocator
.write_compute_timestamp(pass, &end_query);
}
else
{
self.query_set_allocator
.write_timestamp(self.encoder, &end_query);
}
let scope = &mut self.scopes[scope_index];
let pop = self.index_stack.pop().unwrap();
@@ -170,9 +186,35 @@ impl<'enc> ProfilingEncoder<'enc>
}
}
impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc>
impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc, CommandEncoder>
{
pub fn begin_scope<'scope>(&'scope mut self, name: &'static str) -> ScopeEncoder<'enc, 'scope>
pub fn begin_profiled_compute_pass<'scope>(
&'scope mut self,
label: &'static str,
) -> ScopeEncoder<'enc, 'scope, ComputePass<'static>>
{
let new_scope = self.encoder.begin_scope(Some(self.scope_index), label);
let compute_pass = self
.encoder
.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some(label),
timestamp_writes: None,
})
.forget_lifetime();
self.encoder.compute_pass = Some((new_scope, compute_pass));
ScopeEncoder {
encoder: self.encoder,
scope_index: new_scope,
_phantom: Default::default(),
}
}
pub fn begin_scope<'scope>(
&'scope mut self,
name: &'static str,
) -> ScopeEncoder<'enc, 'scope, CommandEncoder>
where
'prof_enc: 'scope,
{
@@ -180,6 +222,7 @@ impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc>
ScopeEncoder {
encoder: self.encoder,
scope_index,
_phantom: Default::default(),
}
}
@@ -189,15 +232,44 @@ impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc>
}
}
impl<'enc, 'prof_enc> Drop for ScopeEncoder<'enc, 'prof_enc>
impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc, ComputePass<'static>>
{
pub fn begin_scope<'scope>(
&'scope mut self,
name: &'static str,
) -> ScopeEncoder<'enc, 'scope, ComputePass<'static>>
where
'prof_enc: 'scope,
{
let scope_index = self.encoder.begin_scope(Some(self.scope_index), name);
ScopeEncoder {
encoder: self.encoder,
scope_index,
_phantom: Default::default(),
}
}
pub fn end_scope(self)
{
drop(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
{
// Finish compute pass by droping it
self.encoder.compute_pass = None;
}
self.encoder.end_scope(self.scope_index);
}
}
impl<'enc, 'prof_enc> DerefMut for ScopeEncoder<'enc, 'prof_enc>
impl<'enc, 'prof_enc> DerefMut for ScopeEncoder<'enc, 'prof_enc, CommandEncoder>
{
fn deref_mut(&mut self) -> &mut Self::Target
{
@@ -205,7 +277,7 @@ impl<'enc, 'prof_enc> DerefMut for ScopeEncoder<'enc, 'prof_enc>
}
}
impl<'enc, 'prof_enc> Deref for ScopeEncoder<'enc, 'prof_enc>
impl<'enc, 'prof_enc> Deref for ScopeEncoder<'enc, 'prof_enc, CommandEncoder>
{
type Target = CommandEncoder;
fn deref(&self) -> &Self::Target
@@ -214,6 +286,23 @@ impl<'enc, 'prof_enc> Deref for ScopeEncoder<'enc, 'prof_enc>
}
}
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>>
{
type Target = ComputePass<'static>;
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
@@ -354,6 +443,12 @@ impl QuerySetAllocator
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)
{
let query_set = &self.query_sets[handle.0].2;
pass.write_timestamp(query_set, handle.1);
}
}
impl GpuProfile
@@ -373,14 +468,15 @@ impl GpuProfile
move |buffer| {
let buffer = buffer.unwrap();
let timestamps: Vec<u64> = bytemuck::pod_collect_to_vec(&buffer);
let start = timestamps.first().copied().unwrap_or(0);
let frames = self
.scopes
.into_iter()
.map(|scope| Frame {
name: scope.name,
children: scope.children,
start_timestamp: timestamps[scope.start_index.index()],
end_timestamp: timestamps[scope.end_index.unwrap().index()],
start_timestamp: timestamps[scope.start_index.index()] - start,
end_timestamp: timestamps[scope.end_index.unwrap().index()] - start,
})
.collect::<Vec<_>>();
@@ -415,6 +511,16 @@ impl Frame
(self.end_timestamp - self.start_timestamp) as f32 * q
}
fn start(&self, q: f32) -> f32
{
self.start_timestamp as f32 * q
}
fn end(&self, q: f32) -> f32
{
self.end_timestamp as f32 * q
}
fn build_string(&self, frames: &Vec<Frame>, depth: usize, q: f32, str: &mut String)
{
let mut depth_string = String::new();
@@ -459,3 +565,149 @@ impl Frame
});
}
}
impl Profile
{
// Clauderies
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.;
// Full time range and max depth of the tree.
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()
{
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
{
full = (0.0, 1.0); // empty or degenerate input
}
// The view is stored as fractions of the full range (not absolute times), so it
// stays valid when the data changes from frame to frame.
let fspan = full.1 - full.0;
let norm: (f64, f64) = ui.data_mut(|d| d.get_temp(id)).unwrap_or((0.0, 1.0));
let mut view = (full.0 + norm.0 * fspan, full.0 + norm.1 * fspan);
if !(view.1 > view.0) || !view.0.is_finite() || !view.1.is_finite()
{
view = full;
}
let size = vec2(ui.available_width(), (max_depth + 1) as f32 * row_height);
let (resp, painter) = ui.allocate_painter(size, egui::Sense::click_and_drag());
let rect = resp.rect;
let w = rect.width().max(1.0) as f64;
// --- interaction ---
let mut span = view.1 - view.0;
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()
{
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
{
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()
{
view = full;
}
//ui.data_mut(|d| d.insert_temp(id, view));
ui.data_mut(|d| d.insert_temp(id, ((view.0 - full.0) / fspan, (view.1 - full.0) / fspan)));
let span = view.1 - view.0;
let to_x = |t: f64| rect.left() + ((t - view.0) / span) as f32 * rect.width();
// --- drawing ---
painter.rect_filled(rect, 0.0, ui.visuals().extreme_bg_color);
let font = egui::FontId::proportional(12.0);
let hover = resp.hover_pos();
let mut hovered: Option<usize> = None;
let mut stack: Vec<(usize, usize)> = [0].iter().map(|&r| (r, 0)).collect();
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
{
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
{
continue; // too thin to see
}
let y = rect.top() + depth as f32 * row_height;
let r = egui::Rect::from_min_max(egui::pos2(x0, y), egui::pos2(x1, y + row_height))
.shrink2(vec2(0.5, 0.5));
let is_hovered = hover.is_some_and(|p| r.contains(p));
if is_hovered
{
hovered = Some(i);
}
let mut color = color_for(&s.name);
if is_hovered
{
color = color.gamma_multiply(1.15);
}
painter.rect_filled(r, 2.0, color);
if r.width() > 24.0
{
painter.with_clip_rect(r).text(
r.left_center() + vec2(3.0, 0.0),
egui::Align2::LEFT_CENTER,
&s.name,
font.clone(),
egui::Color32::BLACK,
);
}
stack.extend(s.children.iter().map(|&c| (c, depth + 1)));
}
if let Some(i) = hovered
{
let s = &self.frames[i];
let start = s.start(q) as f64;
let end = s.end(q) as f64;
resp.clone().on_hover_ui_at_pointer(|ui| {
ui.strong(s.name);
ui.label(format!("duration: {:.3}", end - start));
ui.label(format!("start: {:.3} end: {:.3}", start, end));
});
}
resp
}
}
/// Stable pastel color derived from the scope name.
fn color_for(name: &str) -> egui::Color32
{
let mut h: u32 = 2166136261; // FNV-1a
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()
}
+56 -70
View File
@@ -52,6 +52,7 @@ use winit::window::WindowId;
use crate::camera::Camera;
use crate::egui_renderer::EguiRenderer;
use crate::gpu_profiler::Frame;
use crate::gpu_profiler::Profile;
use crate::gpu_profiler::ProfilingEncoder;
use crate::producers::ChunkedProducer;
@@ -68,6 +69,7 @@ use crate::voxel_cache::producer_interface::CacheRequest;
mod camera;
mod egui_renderer;
mod gi_pipeline;
mod gpu;
pub mod gpu_profiler;
mod producers;
@@ -108,8 +110,8 @@ struct State
gi_bg_layout: BindGroupLayout,
voxel_cache: Arc<Mutex<VoxelCache<4>>>,
cache_interface: Arc<CacheProducerInterface<4>>,
terrain_generator: Arc<SdfGenerator<4>>,
//terrain_generator: Arc<TerrainGenerator<4>>,
//terrain_generator: Arc<SdfGenerator<4>>,
terrain_generator: Arc<TerrainGenerator<4>>,
chunk_pos_map: Arc<HashMap<u32, (usize, usize, usize)>>,
instance_buffer: Buffer,
instance_count: usize,
@@ -123,6 +125,7 @@ struct State
terrain_alt: usize,
profile: Arc<Mutex<Profile>>,
insert_profile: Arc<Mutex<Profile>>,
camera: Camera,
cursor_grabed: bool,
@@ -183,6 +186,7 @@ impl State
| Features::SHADER_I16
| Features::SHADER_F16
| Features::TIMESTAMP_QUERY_INSIDE_ENCODERS
| Features::TIMESTAMP_QUERY_INSIDE_PASSES
| Features::STORAGE_RESOURCE_BINDING_ARRAY
| Features::BUFFER_BINDING_ARRAY
| Features::PASSTHROUGH_SHADERS
@@ -334,16 +338,24 @@ impl State
let egui_renderer = EguiRenderer::new(&device, surface_format, &window);
let attributes = VoxelCacheLayout::default()
.add_attribute(voxel_cache::layout::VoxelCacheAttribute { word_count: 1 })
.add_attribute(voxel_cache::layout::VoxelCacheAttribute { word_count: 3 });
let mut attributes = VoxelCacheLayout::default();
attributes.add_attribute(voxel_cache::layout::VoxelCacheAttribute {
word_count: 1,
rate: voxel_cache::layout::VoxelCacheAttributeRate::Pointer,
init: voxel_cache::layout::VoxelCacheAttributeInit::Copy,
});
attributes.add_attribute(voxel_cache::layout::VoxelCacheAttribute {
word_count: 3,
rate: voxel_cache::layout::VoxelCacheAttributeRate::Pointer,
init: voxel_cache::layout::VoxelCacheAttributeInit::Copy,
});
let mut voxel_cache =
VoxelCache::<4>::new(150_000, device.clone(), queue.clone(), &attributes);
let cache_interface = CacheProducerInterface::new(1024, &device, &attributes);
//let terrain_generator = TerrainGenerator::<4>::new(5, "vxls_height.tif", 0.2, "img.jpg");
let terrain_generator = SdfGenerator::<4>::new(5);
let terrain_generator = TerrainGenerator::<4>::new(5, "vxls_height.tif", 0.2, "img.jpg");
//let terrain_generator = SdfGenerator::<4>::new(5);
// let terrain_generator = TerrainGenerator::<4>::new(
// 5,
// "./pointe_percee/height.tif",
@@ -358,12 +370,12 @@ 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 = 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;
println!(
"Chunk count : {}",
terrain_width * terrain_height * terrain_width
@@ -667,6 +679,7 @@ impl State
terrain_height,
terrain_alt,
profile: Arc::new(Mutex::new(Profile::default())),
insert_profile: Arc::new(Mutex::new(Profile::default())),
cursor_grabed: true,
};
@@ -1029,58 +1042,6 @@ impl State
};
self.target_blitter
.copy(&self.device, &mut encoder, target_view, &texture_view);
/*
{
let mut renderpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &texture_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 0.,
g: 2. / 255.,
b: 15. / 255.,
a: 1.,
}),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_buffer.1,
depth_ops: Some(Operations {
load: wgpu::LoadOp::Clear(1.),
store: wgpu::StoreOp::Discard,
}),
stencil_ops: None,
}),
timestamp_writes: Some(wgpu::RenderPassTimestampWrites {
query_set: &timestamp_query,
beginning_of_pass_write_index: Some(0),
end_of_pass_write_index: Some(1),
}),
occlusion_query_set: None,
multiview_mask: None,
});
renderpass.set_pipeline(&self.pipeline);
renderpass.set_vertex_buffer(0, self.instance_buffer.slice(..));
renderpass.set_bind_group(0, Some(&self.voxel_cache.lock().bind_group()), &[]);
let imm = [Immediates {
view_proj: self.camera.view_proj(),
cam_pos: self.camera.position,
frame_timestamp: self.voxel_cache.lock().current_timestamp(),
}];
renderpass.set_immediates(0, unsafe { as_raw_bytes(&imm) });
renderpass.draw(0..36, 0..(self.instance_count as u32));
// End the renderpass.
drop(renderpass);
encoder.resolve_query_set(&timestamp_query, 0..2, &timestamp_buffer, 0);
}
*/
// ~~ EGUI Render pass ~~
{
@@ -1121,7 +1082,7 @@ impl State
// [512., 512.],
// )));
egui_plot::Plot::new("Plot")
.height(512.)
.height(256.)
.show(ui, |plot_ui| {
plot_ui.bar_chart(BarChart::new(
"histo",
@@ -1135,7 +1096,20 @@ impl State
});
let q = self.queue.get_timestamp_period() / 1_000_000.;
self.profile.lock().show(ui, q);
let f = Frame {
name: "skibidi",
children: vec![],
start_timestamp: 0,
end_timestamp: 1_000_000,
};
let p = Profile { frames: vec![f] };
// self.profile.lock().show(ui, q);
self.profile
.lock()
.show_flamegraph("first_profile".into(), q, ui);
self.insert_profile
.lock()
.show_flamegraph("second_profile".into(), q, ui);
},
);
@@ -1255,6 +1229,7 @@ impl State
let cloned_generator = self.terrain_generator.clone();
let cloned_map = self.chunk_pos_map.clone();
let cloned_cache_interface = self.cache_interface.clone();
let cloned_insert_profile = self.insert_profile.clone();
let (tx, rx) = sync_channel(1);
// ~~ Download request buffer, fullfill requests, writeback to cache ~~
@@ -1378,10 +1353,21 @@ impl State
);
let mut encoder = cloned_device.create_command_encoder(&Default::default());
cloned_cache
.lock()
.cache_insert(&mut encoder, &cloned_cache_interface);
let mut profiled_encoder =
ProfilingEncoder::new(&cloned_device, &mut encoder);
{
gpu_profiler::begin_frame!(profiled_encoder, "Cache insertion");
{
cloned_cache
.lock()
.cache_insert(&mut profiled_encoder, &cloned_cache_interface);
}
}
let profile = profiled_encoder.finish_profiler();
cloned_queue.submit([encoder.finish()]);
profile.read_back(&cloned_device, &cloned_queue, move |mut profile| {
*cloned_insert_profile.lock() = profile;
});
}
},
);
+109 -36
View File
@@ -1,8 +1,8 @@
use std::num::NonZero;
use bytemuck::Zeroable;
use bytemuck::{Zeroable, bytes_of};
use tiff::encoder;
use wgpu::{BindGroup, BindGroupLayout, Buffer, BufferUsages, CommandEncoder, ComputePipeline, Device, Queue, ShaderStages, naga::back::spv::Capability::Shader, util::DeviceExt};
use wgpu::{BindGroup, BindGroupLayout, Buffer, BufferUsages, CommandEncoder, ComputePassDescriptor, ComputePipeline, Device, Queue, ShaderStages, naga::back::spv::Capability::Shader, util::DeviceExt};
use crate::{gpu::radix_sort::{self, RadixSorter}, gpu_profiler::{self, ProfilingEncoder, ScopeEncoder, begin_scope}, voxel_cache::{data::{CacheNodeRequest, CacheResponse, ColorPoolElement, LocationPoolElement, StructurePoolElement}, indirect_buffer::NonZeroBufferCompactor, layout::VoxelCacheLayout, producer_interface::CacheProducerInterface, request_buffer::RequestBuffer, structure_table::StructureTable, usage_buffer::UsageBuffer}};
@@ -56,6 +56,9 @@ pub struct VoxelCache<const N: usize>
// Scratch buffer of u32 spanning whole cache for operations
cache_scratch_buffer: Buffer,
// To store the amount of pages that have been written in this insertion
written_pages: PageList,
structure_bind_group: BindGroup,
management_bind_group: BindGroup,
attributes_bind_group: BindGroup,
@@ -179,6 +182,8 @@ where
mapped_at_creation: false,
});
let written_pages = PageList::new(&device, cache_size);
// Attributes
let (attributes_bind_group, attributes_bind_group_layout) = {
let attributes_bind_group_layout = device.create_bind_group_layout(
@@ -428,6 +433,7 @@ where
Some(&attributes_bind_group_layout),
Some(&structure_table_bind_group_layout),
Some(&cache_interface_bind_group_layout),
Some(written_pages.bind_group_layout()),
],
immediate_size: size_of::<CachingPipelineImmediates>() as u32, // Current frame timestamp
});
@@ -436,24 +442,13 @@ where
let mut copy_loops = String::new();
for (attribute_index, attribute) in layout.attributes().iter().enumerate()
{
let node_size = attribute.word_count * children_count as u32;
let word_count = attribute.word_count;
copy_loops += format!("
// Iterate on every children
for(var i = 0u; i < {children_count}; i++){{
// Iterate on every word of the attribute
for(var j = 0u; j < {word_count}; j++){{
// Offset within child
let offset = i * {word_count} + j;
attributes_pools[{attribute_index}].values[overwritten_element * {node_size} + offset]
= attributes_producer[{attribute_index}].values[producer_index * {node_size} + offset];
}}
}}
").as_str();
copy_loops += &attribute.wgsl_copy_loop(
"attributes_pools",
"attributes_producer",
"overwritten_element",
"producer_index",
children_count,
attribute_index);
}
let children_count = N * N * N;
@@ -503,6 +498,9 @@ where
@group(4) @binding(4) var<storage, read_write> attributes_producer: binding_array<AttributeArray, {attribute_count}>;
@group(4) @binding(5) var<storage, read_write> locations: array<LocationPoolElement>;
@group(5) @binding(0) var<storage, read_write> written_pages_count: u32;
@group(5) @binding(1) var<storage, read_write> written_pages_indices: array<u32>;
@compute
@workgroup_size(64)
fn main(
@@ -518,9 +516,14 @@ where
return;
}}
written_pages_count = total;
// Get index from lru eviction list
let overwritten_element = lru_list[index];
// Write into the written pages list
written_pages_indices[index] = overwritten_element;
if(parameters.write_pointers == 0 && usage_buffer[overwritten_element] != parameters.frame_timestamp)
{{
// ~~ Phase 1 ~~
@@ -637,6 +640,7 @@ where
let total_pool = arrayLength(&structure_pool);
let total_table = arrayLength(&structure_table_pointers);
if(index < total_table)
{{
// Invocation falls in structure table
@@ -848,6 +852,7 @@ where
usage_buffer,
lru_list,
cache_scratch_buffer,
written_pages: PageList::new(&device, cache_size),
structure_bind_group,
management_bind_group,
@@ -926,7 +931,7 @@ where
], Some("VoxelCache::structure_table_bind_group"))
}
pub fn cache_post_render(&mut self, encoder: &mut ScopeEncoder, request_interface: &CacheProducerInterface<N>)
pub fn cache_post_render(&mut self, encoder: &mut ScopeEncoder<'_, '_, CommandEncoder>, request_interface: &CacheProducerInterface<N>)
{
gpu_profiler::begin_scope!(encoder, "cache_post_render");
// Sort request buffer
@@ -989,11 +994,7 @@ where
}
{
gpu_profiler::begin_scope!(encoder, "indirect_copy");
let mut indirect_usage_copy_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("VoxelCache::indirect_usage_copy_pass"),
timestamp_writes: None,
});
let mut indirect_usage_copy_pass = encoder.begin_profiled_compute_pass("indrect_compute_pass");
indirect_usage_copy_pass.set_bind_group(0, Some(&self.structure_bind_group), &[]);
indirect_usage_copy_pass.set_bind_group(1, Some(&self.management_bind_group), &[]);
@@ -1031,11 +1032,8 @@ where
}
// Sorted requests are now in the group
gpu_profiler::begin_scope!(encoder, "request_pass");
let mut request_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("VoxelCache::write_requests_pass"),
timestamp_writes: None,
});
//gpu_profiler::begin_scope!(encoder, "request_pass");
let mut request_pass = encoder.begin_profiled_compute_pass("VoxelCache::write_requests_pass");
request_pass.set_bind_group(0, Some(&self.structure_bind_group), &[]);
request_pass.set_bind_group(1, Some(&self.management_bind_group), &[]);
@@ -1061,13 +1059,15 @@ where
self.timestamp
}
pub fn cache_insert(&mut self, encoder: &mut CommandEncoder, cache_interface: &CacheProducerInterface<N>)
pub fn cache_insert(&mut self, encoder: &mut ScopeEncoder<'_, '_, CommandEncoder>, cache_interface: &CacheProducerInterface<N>)
{
// Each of the entry of the cache insertion, is matched with the usage list to evict
let mut cache_insertion_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("VoxelCache::cache_insertion_pass"),
timestamp_writes: None,
});
let mut cache_insertion_pass = encoder.begin_profiled_compute_pass("VoxelCache::cache_insertion_pass");
// let mut cache_insertion_pass = encoder.begin_compute_pass(&ComputePassDescriptor
// {
// label: Some("mozeifj"),
// timestamp_writes: None,
// });
// Copy insertions to evicted lru
// Point parents to children
@@ -1075,6 +1075,7 @@ where
// ~~~ Write data + Dirty flagging/timestamp update ~~~
{
gpu_profiler::begin_scope!(cache_insertion_pass, "Write pages");
cache_insertion_pass.set_bind_group(0, Some(&self.structure_bind_group), &[]);
cache_insertion_pass.set_bind_group(1, Some(&self.management_bind_group), &[]);
cache_insertion_pass.set_bind_group(2, Some(&self.attributes_bind_group), &[]);
@@ -1099,6 +1100,7 @@ where
// ~~~ Invalidate pointers ~~~
{
gpu_profiler::begin_scope!(cache_insertion_pass, "Invalidation");
cache_insertion_pass.set_pipeline(&self.invalidation_pass);
cache_insertion_pass.set_bind_group(4, None, &[]);
cache_insertion_pass
@@ -1113,6 +1115,7 @@ where
// ~~~ Write new pointers ~~~
{
gpu_profiler::begin_scope!(cache_insertion_pass, "Pointer write");
cache_insertion_pass.set_pipeline(&self.caching_pass);
cache_insertion_pass.set_bind_group(4, Some(&cache_interface.request_side_bind_group), &[]);
cache_insertion_pass.set_immediates(
@@ -1132,6 +1135,7 @@ where
// Reset state
{
gpu_profiler::begin_scope!(cache_insertion_pass, "Reset state");
cache_insertion_pass.set_pipeline(&self.reset_pass);
cache_insertion_pass.set_bind_group(4, None, &[]);
let shader_invocation_count = self.size;
@@ -1146,6 +1150,75 @@ where
self.timestamp += 1;
}
pub fn written_page_list(&self) -> &PageList
{
&self.written_pages
}
}
pub struct PageList
{
max_size: usize,
// u32: page_count
count_buffer: Buffer,
// Buffer of u32 indices into pages
list_buffer: Buffer,
bind_group_layout: BindGroupLayout,
bind_group: BindGroup,
}
impl PageList
{
pub fn new(device: &Device, max_size: usize) -> Self
{
let count_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor
{
label: Some("PageList::count_buffer"),
contents: bytes_of(&0),
usage: BufferUsages::STORAGE,
});
let list_buffer = device.create_buffer(&wgpu::BufferDescriptor
{
label: Some("PageList::list_buffer"),
usage: BufferUsages::STORAGE,
size: (size_of::<u32>() * max_size) as u64,
mapped_at_creation: false,
});
let (bind_group_layout, bind_group) = create_multi_buffers_bg_bg_layout(device, &[&count_buffer, &list_buffer], Some("PageList::bind_group"));
PageList
{
max_size,
count_buffer,
list_buffer,
bind_group_layout,
bind_group,
}
}
pub fn max_size(&self) -> usize {
self.max_size
}
pub fn count_buffer(&self) -> &Buffer {
&self.count_buffer
}
pub fn list_buffer(&self) -> &Buffer {
&self.list_buffer
}
pub fn bind_group_layout(&self) -> &BindGroupLayout {
&self.bind_group_layout
}
pub fn bind_group(&self) -> &BindGroup {
&self.bind_group
}
}
// Utilities
+71 -2
View File
@@ -4,18 +4,38 @@ pub struct VoxelCacheLayout
pub(super) attributes: Vec<VoxelCacheAttribute>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum VoxelCacheAttributeRate
{
/// Attribute is per page
Page,
/// Attribute is per pointer in pages
Pointer,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum VoxelCacheAttributeInit
{
Copy,
DontTouch,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct VoxelCacheAttribute
{
pub word_count: u32,
pub rate: VoxelCacheAttributeRate,
pub init: VoxelCacheAttributeInit,
}
impl VoxelCacheLayout
{
pub fn add_attribute(mut self, attribute: VoxelCacheAttribute) -> Self
pub fn add_attribute(&mut self, attribute: VoxelCacheAttribute) -> usize
{
let index = self.attributes.len();
self.attributes.push(attribute);
self
index
}
pub fn attributes(&self) -> &[VoxelCacheAttribute]
@@ -23,3 +43,52 @@ impl VoxelCacheLayout
&self.attributes
}
}
impl VoxelCacheAttribute
{
pub fn wgsl_copy_loop(
&self,
source_array: &str,
dest_array: &str,
source_page_index: &str,
dest_page_index: &str,
child_count: usize,
attribute_index: usize,
) -> String
{
match self.init
{
VoxelCacheAttributeInit::Copy =>
{
let real_child_count = match self.rate
{
VoxelCacheAttributeRate::Page => 1,
VoxelCacheAttributeRate::Pointer => child_count,
};
let word_count = self.word_count;
let node_size = real_child_count * word_count as usize;
format!(
"
// Iterate on every children
for(var i = 0u; i < {real_child_count}; i++){{
// Iterate on every word of the attribute
for(var j = 0u; j < {word_count}; j++){{
// Offset within child
let offset = i * {word_count} + j;
{source_array}[{attribute_index}].values[{source_page_index} * {node_size} + offset]
= {dest_array}[{attribute_index}].values[{dest_page_index} * {node_size} + offset];
}}
}}
"
)
}
VoxelCacheAttributeInit::DontTouch => String::from("// Attribute is DontTouch"),
}
}
}