cool profiling

This commit is contained in:
2026-10-06 23:55:43 +02:00
parent b560f6afd7
commit 6b2e738a22
4 changed files with 872 additions and 265 deletions
+1
View File
@@ -9,6 +9,7 @@ crevice = {version = "0.20.1", features = ["glam"]}
egui = "0.36.1"
egui-wgpu = "0.36.1"
egui-winit = "0.36.1"
egui_ltreeview = "0.9.0"
egui_plot = "0.37.0"
env_logger = "0.11.11"
fastapprox = "0.3.1"
+454
View File
@@ -0,0 +1,454 @@
use std::fmt::Debug;
use std::iter::Peekable;
use std::ops::Deref;
use std::ops::DerefMut;
use egui::Sense;
use egui::Ui;
use wgpu::Buffer;
use wgpu::BufferUsages;
use wgpu::CommandEncoder;
use wgpu::Device;
use wgpu::QUERY_RESOLVE_BUFFER_ALIGNMENT;
use wgpu::QuerySet;
use wgpu::Queue;
macro_rules! begin_frame {
($encoder:ident) => {
let mut $encoder = $encoder.begin_frame(None);
};
($encoder:ident, $name:literal) => {
let mut $encoder = $encoder.begin_frame(Some(literal));
};
}
macro_rules! begin_scope {
($scope:ident, $name:literal) => {
let mut $scope = $scope.begin_scope($name);
};
}
pub(crate) use begin_frame;
pub(crate) use begin_scope;
pub struct ScopeEncoder<'enc, 'prof_enc>
{
encoder: &'prof_enc mut ProfilingEncoder<'enc>,
scope_index: usize,
}
pub struct Scope
{
name: &'static str,
start_index: QuerySetHandle,
end_index: Option<QuerySetHandle>,
children: Vec<usize>,
}
pub struct ProfilingEncoder<'enc>
{
device: Device,
encoder: &'enc mut CommandEncoder,
query_set_allocator: QuerySetAllocator,
scopes: Vec<Scope>,
index_stack: Vec<usize>,
}
pub struct GpuProfile
{
scopes: Vec<Scope>,
timestamps: Buffer,
}
pub struct Frame
{
pub name: &'static str,
pub children: Vec<usize>,
pub start_timestamp: u64,
pub end_timestamp: u64,
}
#[derive(Default)]
pub struct Profile
{
pub frames: Vec<Frame>,
}
impl<'enc> ProfilingEncoder<'enc>
{
pub fn new(device: &Device, encoder: &'enc mut CommandEncoder) -> Self
{
Self {
encoder,
query_set_allocator: QuerySetAllocator::new(device),
scopes: Vec::new(),
device: device.clone(),
index_stack: Vec::new(),
}
}
pub fn begin_frame<'prof_enc>(
&'prof_enc mut self,
frame_name: Option<&'static str>,
) -> ScopeEncoder<'enc, 'prof_enc>
{
let scope_index = self.begin_scope(None, frame_name.unwrap_or("Frame"));
self.index_stack.push(scope_index);
ScopeEncoder {
encoder: self,
scope_index,
}
}
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);
let scope = Scope {
name,
start_index: begin_query,
end_index: None,
children: Vec::new(),
};
let new_scope_index = self.scopes.len();
self.scopes.push(scope);
self.index_stack.push(new_scope_index);
// Add this new stack to parent
if let Some(scope_index) = scope_index
{
self.scopes[scope_index].children.push(new_scope_index);
}
new_scope_index
}
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);
let scope = &mut self.scopes[scope_index];
let pop = self.index_stack.pop().unwrap();
assert_eq!(
pop, scope_index,
"Scopes must be defined in a stack fashion."
);
scope.end_index = Some(end_query);
}
pub fn finish_profiler(self) -> GpuProfile
{
let timestamp_count = self.query_set_allocator.allocated_count();
let resolve_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("ProfilingEncoder::resolve_buffer"),
size: size_of::<u64>() as u64 * timestamp_count as u64,
usage: BufferUsages::QUERY_RESOLVE | BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
self.query_set_allocator
.resolve_all(self.encoder, &resolve_buffer);
GpuProfile {
scopes: self.scopes,
timestamps: resolve_buffer,
}
}
}
impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc>
{
pub fn begin_scope<'scope>(&'scope mut self, name: &'static str) -> ScopeEncoder<'enc, 'scope>
where
'prof_enc: 'scope,
{
let scope_index = self.encoder.begin_scope(Some(self.scope_index), name);
ScopeEncoder {
encoder: self.encoder,
scope_index,
}
}
pub fn end_scope(self)
{
drop(self);
}
}
impl<'enc, 'prof_enc> Drop for ScopeEncoder<'enc, 'prof_enc>
{
fn drop(&mut self)
{
self.encoder.end_scope(self.scope_index);
}
}
impl<'enc, 'prof_enc> DerefMut for ScopeEncoder<'enc, 'prof_enc>
{
fn deref_mut(&mut self) -> &mut Self::Target
{
&mut *self.encoder
}
}
impl<'enc, 'prof_enc> Deref for ScopeEncoder<'enc, 'prof_enc>
{
type Target = CommandEncoder;
fn deref(&self) -> &Self::Target
{
&*self.encoder
}
}
impl<'enc> DerefMut for ProfilingEncoder<'enc>
{
fn deref_mut(&mut self) -> &mut Self::Target
{
self.encoder
}
}
impl<'enc> Deref for ProfilingEncoder<'enc>
{
type Target = CommandEncoder;
fn deref(&self) -> &Self::Target
{
self.encoder
}
}
struct QuerySetAllocator
{
device: Device,
current_size: u32,
current_id: u32,
query_sets: Vec<(u32, u32, QuerySet)>,
}
#[derive(PartialEq, Eq)]
struct QuerySetHandle(usize, u32, u32);
impl QuerySetHandle
{
pub fn index(&self) -> usize
{
self.2 as usize
}
}
impl PartialOrd for QuerySetHandle
{
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering>
{
Some(self.cmp(other))
}
}
impl Ord for QuerySetHandle
{
fn cmp(&self, other: &Self) -> std::cmp::Ordering
{
match self.0.cmp(&other.0)
{
core::cmp::Ordering::Equal =>
{}
ord => return ord,
}
self.1.cmp(&other.1)
}
}
impl QuerySetAllocator
{
pub fn new(device: &Device) -> Self
{
let current_size = 32;
let query_sets = vec![(
0,
current_size,
Self::new_query_set(device, current_size, 0),
)];
QuerySetAllocator {
query_sets,
current_size,
current_id: 0,
device: device.clone(),
}
}
pub fn allocated_count(&self) -> u32
{
self.query_sets
.iter()
.map(|(allocated, _, _)| *allocated)
.sum()
}
pub fn resolve_all(&self, encoder: &mut CommandEncoder, target: &Buffer)
{
let mut offset = 0;
for (allocated, _, query_set) in self.query_sets.iter()
{
encoder.resolve_query_set(query_set, 0..*allocated, target, offset);
offset += *allocated as u64 * size_of::<u64>() as u64;
}
}
pub fn allocate(&mut self) -> QuerySetHandle
{
// Check if allocation is possible
if self
.query_sets
.last()
.is_some_and(|(allocated, available, _)| allocated == available)
{
// No more room, allocate new query set
self.current_size *= 2;
self.query_sets.push((
0,
self.current_size,
Self::new_query_set(&self.device, self.current_size, self.query_sets.len()),
));
}
// Last allocation is guaranteed to have room
let (allocated, _available, _query_set) = self.query_sets.last_mut().unwrap();
let query_index = *allocated;
*allocated += 1;
let query_set_index = self.query_sets.len() - 1;
let id = self.current_id;
self.current_id += 1;
QuerySetHandle(query_set_index, query_index, id)
}
fn new_query_set(device: &Device, size: u32, index: usize) -> QuerySet
{
device.create_query_set(&wgpu::QuerySetDescriptor {
label: Some(format!("QuerySetAllocator::query_set_{index}").as_str()),
ty: wgpu::QueryType::Timestamp,
count: size,
})
}
fn write_timestamp(&mut self, encoder: &mut CommandEncoder, handle: &QuerySetHandle)
{
let query_set = &self.query_sets[handle.0].2;
encoder.write_timestamp(query_set, handle.1);
}
}
impl GpuProfile
{
pub fn read_back(
self,
device: &Device,
queue: &Queue,
mut callback: impl FnMut(Profile) + Send + Sync + 'static,
)
{
// Readback timestamps
wgpu::util::DownloadBuffer::read_buffer(
device,
queue,
&self.timestamps.slice(..),
move |buffer| {
let buffer = buffer.unwrap();
let timestamps: Vec<u64> = bytemuck::pod_collect_to_vec(&buffer);
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()],
})
.collect::<Vec<_>>();
callback(Profile { frames });
},
);
}
}
impl Profile
{
pub fn to_display_string(&self, q: f32) -> String
{
let mut str = String::new();
self.frames[0].build_string(&self.frames, 0, q, &mut str);
str
}
pub fn show(&self, ui: &mut Ui, q: f32)
{
if !self.frames.is_empty()
{
self.frames[0].show(ui, q, &self.frames);
}
}
}
impl Frame
{
fn time(&self, q: f32) -> f32
{
(self.end_timestamp - self.start_timestamp) as f32 * q
}
fn build_string(&self, frames: &Vec<Frame>, depth: usize, q: f32, str: &mut String)
{
let mut depth_string = String::new();
(0..depth).for_each(|_| depth_string.push_str(" "));
let time = (self.end_timestamp - self.start_timestamp) as f32 * q;
str.push_str(&format!("{depth_string}{}: {:.2}\n", self.name, time));
self.children
.iter()
.for_each(|c| frames[*c].build_string(frames, depth + 1, q, str));
}
pub fn show(&self, ui: &mut Ui, q: f32, frames: &Vec<Frame>)
{
let id = ui.make_persistent_id(self.name);
egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true)
.show_header(ui, |ui| {
ui.horizontal(|ui| {
ui.label(self.name);
// Right-aligned label, laid out first from the right edge
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.label(format!("{:.2}ms", self.time(q)));
// Whatever space remains between the two labels:
// draw a thin line across it, vertically centered.
let rect = ui.available_rect_before_wrap();
let y = rect.center().y;
ui.painter().hline(
rect.x_range(),
y,
ui.visuals().widgets.noninteractive.bg_stroke,
);
});
});
})
.body(|ui| {
self.children
.iter()
.for_each(|i| frames[*i].show(ui, q, frames));
});
}
}
+269 -224
View File
@@ -52,14 +52,12 @@ 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::Profile;
use crate::gpu_profiler::ProfilingEncoder;
use crate::producers::ChunkedProducer;
use crate::producers::SdfGenerator;
use crate::producers::SineGenerator;
use crate::producers::TerrainGenerator;
use crate::sparse_tree::NTreeNodeLocator;
use crate::voxel_cache::VoxelAttribute;
use crate::voxel_cache::VoxelCache;
use crate::voxel_cache::data::ColorBytes;
use crate::voxel_cache::data::LocationPoolElement;
@@ -71,6 +69,7 @@ use crate::voxel_cache::producer_interface::CacheRequest;
mod camera;
mod egui_renderer;
mod gpu;
pub mod gpu_profiler;
mod producers;
mod sparse_tree;
mod voxel_cache;
@@ -109,8 +108,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,7 +122,10 @@ struct State
terrain_height: usize,
terrain_alt: usize,
profile: Arc<Mutex<Profile>>,
camera: Camera,
cursor_grabed: bool,
}
pub unsafe fn as_raw_bytes<T: Sized>(slice: &[T]) -> &[u8]
@@ -187,7 +189,7 @@ impl State
| Features::SHADER_INT64,
required_limits: wgpu::Limits {
max_immediate_size: 112,
max_storage_buffers_per_shader_stage: 16,
max_storage_buffers_per_shader_stage: 32,
max_binding_array_elements_per_shader_stage: 16,
max_bind_groups: 8,
..Default::default()
@@ -337,11 +339,11 @@ impl State
.add_attribute(voxel_cache::layout::VoxelCacheAttribute { word_count: 3 });
let mut voxel_cache =
VoxelCache::<4>::new(100_000, device.clone(), queue.clone(), &attributes);
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",
@@ -350,18 +352,18 @@ impl State
// );
// let terrain_generator = TerrainGenerator::<4>::new(
// 5,
// "/home/albin/Documents/vxls_maps/lapiz/height.tif",
// "/home/albin/Documents/vxls_maps/orgere/height.tif",
// 0.2,
// "/home/albin/Documents/vxls_maps/lapiz/ortho.jpg",
// "/home/albin/Documents/vxls_maps/orgere/color.jpg",
// );
//
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
@@ -664,6 +666,8 @@ impl State
terrain_width,
terrain_height,
terrain_alt,
profile: Arc::new(Mutex::new(Profile::default())),
cursor_grabed: true,
};
// Configure surface for the first time
@@ -729,6 +733,17 @@ impl State
self.egui_renderer.handle_input(&self.window, event);
self.camera.handle_input(event);
if self
.camera
.pressed_keyset
.contains(&winit::keyboard::KeyCode::Escape)
{
let _ = self
.window
.set_cursor_grab(winit::window::CursorGrabMode::None);
self.cursor_grabed = false;
}
if self
.camera
.pressed_keyset
@@ -767,7 +782,7 @@ impl State
#[allow(clippy::single_match)]
match event
{
winit::event::DeviceEvent::MouseMotion { delta } =>
winit::event::DeviceEvent::MouseMotion { delta } if self.cursor_grabed =>
{
self.camera.cursor_moved(delta.0 as f32, delta.1 as f32);
}
@@ -952,230 +967,260 @@ impl State
});
// ~~ Main render pass ~~
let mut encoder = self.device.create_command_encoder(&Default::default());
encoder.write_timestamp(&timestamp_query, 0);
{
let mut renderpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("compute_render_pass"),
timestamp_writes: Some(wgpu::ComputePassTimestampWrites {
query_set: &timestamp_query,
beginning_of_pass_write_index: Some(2),
end_of_pass_write_index: Some(3),
}),
});
let mut command_encoder = self.device.create_command_encoder(&Default::default());
let mut prof_command_encoder = ProfilingEncoder::new(&self.device, &mut command_encoder);
renderpass.set_pipeline(&self.pipeline);
renderpass.set_bind_group(0, &self.voxel_cache.lock().user_bind_group(), &[]);
renderpass.set_bind_group(1, Some(&surface_bg), &[]);
let imm = [Immediates {
view_proj: self.camera.view_proj().inverse(),
cam_pos: self.camera.position,
frame_timestamp: self.voxel_cache.lock().current_timestamp(),
width: self.size.width,
height: self.size.height,
// chunk_width: self.terrain_generator.chunk_width as u32,
// chunk_height: self.terrain_generator.chunk_height as u32,
// chunk_alt: self.terrain_generator.chunk_alt as u32,
chunk_width: self.terrain_width as u32,
chunk_height: self.terrain_height as u32,
chunk_alt: self.terrain_alt as u32,
}];
renderpass.set_immediates(0, unsafe { as_raw_bytes(&imm) });
renderpass.dispatch_workgroups(
self.size.width.div_ceil(16),
self.size.height.div_ceil(16),
1,
);
renderpass.set_pipeline(&self.gi_pipeline);
renderpass.set_immediates(0, unsafe { as_raw_bytes(&imm) });
renderpass.set_bind_group(1, Some(&gi_surface_bg), &[]);
renderpass.dispatch_workgroups(
self.size.width.div_ceil(16),
self.size.height.div_ceil(16),
1,
);
drop(renderpass);
}
let target_view = match self.display
{
DisplayTexture::Target => &self.target_texture.1,
DisplayTexture::Normal => &self.normal_gbuffer.1,
DisplayTexture::Pos => &self.position_gbuffer.1,
DisplayTexture::Albedo => &self.albedo_gbuffer.1,
};
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,
let mut encoder = prof_command_encoder.begin_frame(Some("Main frame"));
encoder.write_timestamp(&timestamp_query, 0);
{
gpu_profiler::begin_scope!(encoder, "Compute render pass");
let mut renderpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("compute_render_pass"),
timestamp_writes: Some(wgpu::ComputePassTimestampWrites {
query_set: &timestamp_query,
beginning_of_pass_write_index: Some(2),
end_of_pass_write_index: Some(3),
}),
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));
renderpass.set_pipeline(&self.pipeline);
renderpass.set_bind_group(0, &self.voxel_cache.lock().user_bind_group(), &[]);
renderpass.set_bind_group(1, Some(&surface_bg), &[]);
let imm = [Immediates {
view_proj: self.camera.view_proj().inverse(),
cam_pos: self.camera.position,
frame_timestamp: self.voxel_cache.lock().current_timestamp(),
width: self.size.width,
height: self.size.height,
// End the renderpass.
drop(renderpass);
// chunk_width: self.terrain_generator.chunk_width as u32,
// chunk_height: self.terrain_generator.chunk_height as u32,
// chunk_alt: self.terrain_generator.chunk_alt as u32,
chunk_width: self.terrain_width as u32,
chunk_height: self.terrain_height as u32,
chunk_alt: self.terrain_alt as u32,
}];
renderpass.set_immediates(0, unsafe { as_raw_bytes(&imm) });
renderpass.dispatch_workgroups(
self.size.width.div_ceil(16),
self.size.height.div_ceil(16),
1,
);
renderpass.set_pipeline(&self.gi_pipeline);
renderpass.set_immediates(0, unsafe { as_raw_bytes(&imm) });
renderpass.set_bind_group(1, Some(&gi_surface_bg), &[]);
renderpass.dispatch_workgroups(
self.size.width.div_ceil(16),
self.size.height.div_ceil(16),
1,
);
drop(renderpass);
encoder.end_scope();
}
encoder.resolve_query_set(&timestamp_query, 0..2, &timestamp_buffer, 0);
}
*/
let target_view = match self.display
{
DisplayTexture::Target => &self.target_texture.1,
DisplayTexture::Normal => &self.normal_gbuffer.1,
DisplayTexture::Pos => &self.position_gbuffer.1,
DisplayTexture::Albedo => &self.albedo_gbuffer.1,
};
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,
});
// ~~ EGUI Render pass ~~
{
self.egui_renderer.begin_frame(&self.window);
egui::Window::new("Window ! ").resizable(true).show(
self.egui_renderer.context(),
|ui| {
if self
.camera
.pressed_keyset
.contains(&winit::keyboard::KeyCode::KeyF)
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 ~~
{
self.egui_renderer.begin_frame(&self.window);
egui::Window::new("Window ! ").resizable(true).show(
self.egui_renderer.context(),
|ui| {
if ui.ctx().input(|i| i.pointer.any_pressed())
&& !ui.response().contains_pointer()
{
self.cursor_grabed = true;
let _ = self
.window
.set_cursor_grab(winit::window::CursorGrabMode::Locked);
}
if self
.camera
.pressed_keyset
.contains(&winit::keyboard::KeyCode::KeyF)
{
ui.label(
egui::RichText::new("Cache paused")
.color(Color32::RED)
.size(28.),
);
}
ui.label(format!(
"frame time: {}",
*self.frame_time.lock() / 1_000_000.
));
ui.label(format!(
"Ray-marching time: {}",
*self.rm_time.lock() / 1_000_000.
));
// ui.image(egui::ImageSource::Texture(egui::load::SizedTexture::new(
// position_id,
// [512., 512.],
// )));
egui_plot::Plot::new("Plot")
.height(512.)
.show(ui, |plot_ui| {
plot_ui.bar_chart(BarChart::new(
"histo",
self.usage_vec
.lock()
.iter()
.enumerate()
.map(|(i, x)| egui_plot::Bar::new(i as f64, *x as f64))
.collect(),
));
});
let q = self.queue.get_timestamp_period() / 1_000_000.;
self.profile.lock().show(ui, q);
},
);
let screen_descriptor = egui_wgpu::ScreenDescriptor {
size_in_pixels: [self.size.width, self.size.height],
pixels_per_point: self.window.as_ref().scale_factor() as f32,
};
gpu_profiler::begin_scope!(encoder, "Egui");
self.egui_renderer.end_frame_and_draw(
&self.device,
&self.queue,
&mut encoder,
&self.window,
&texture_view,
screen_descriptor,
);
}
// ~~ 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()
{
ui.label(
egui::RichText::new("Cache paused")
.color(Color32::RED)
.size(28.),
);
let diff = (time_stamp - x).min(99);
v[diff as usize] += 1;
}
ui.label(format!(
"frame time: {}",
*self.frame_time.lock() / 1_000_000.
));
ui.label(format!(
"Ray-marching time: {}",
*self.rm_time.lock() / 1_000_000.
));
// ui.image(egui::ImageSource::Texture(egui::load::SizedTexture::new(
// position_id,
// [512., 512.],
// )));
egui_plot::Plot::new("Plot")
.height(512.)
.show(ui, |plot_ui| {
plot_ui.bar_chart(BarChart::new(
"histo",
self.usage_vec
.lock()
.iter()
.enumerate()
.map(|(i, x)| egui_plot::Bar::new(i as f64, *x as f64))
.collect(),
));
});
*cloned_usage_histogram.lock() = v;
},
);
let screen_descriptor = egui_wgpu::ScreenDescriptor {
size_in_pixels: [self.size.width, self.size.height],
pixels_per_point: self.window.as_ref().scale_factor() as f32,
};
// DownloadBuffer::read_buffer(
// &self.device,
// &self.queue,
// &self
// .voxel_cache
// .lock()
// .structure_table
// .request_buffer
// .request_count_buffer()
// .slice(..),
// move |slice| {
// let slice = slice.unwrap();
// let cache_slice: &[u32] = bytemuck::cast_slice(&slice);
// println!("structure_table count: {}", cache_slice[0]);
// },
// );
self.egui_renderer.end_frame_and_draw(
&self.device,
&self.queue,
&mut encoder,
&self.window,
&texture_view,
screen_descriptor,
);
// ~~ Do cache managment
if !self
.camera
.pressed_keyset
.contains(&winit::keyboard::KeyCode::KeyF)
{
self.voxel_cache
.lock()
.cache_post_render(&mut encoder, &self.cache_interface);
}
// ~~ Submit command buffer ~~
encoder.write_timestamp(&timestamp_query, 1);
encoder.resolve_query_set(&timestamp_query, 0..4, &timestamp_buffer, 0);
encoder.end_scope();
}
// ~~ 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 profile = prof_command_encoder.finish_profiler();
// DownloadBuffer::read_buffer(
// &self.device,
// &self.queue,
// &self
// .voxel_cache
// .lock()
// .structure_table
// .request_buffer
// .request_count_buffer()
// .slice(..),
// move |slice| {
// let slice = slice.unwrap();
// let cache_slice: &[u32] = bytemuck::cast_slice(&slice);
// println!("structure_table count: {}", cache_slice[0]);
// },
// );
// ~~ Do cache managment
if !self
.camera
.pressed_keyset
.contains(&winit::keyboard::KeyCode::KeyF)
{
self.voxel_cache
.lock()
.cache_post_render(&mut encoder, &self.cache_interface);
}
// ~~ Submit command buffer ~~
encoder.write_timestamp(&timestamp_query, 1);
encoder.resolve_query_set(&timestamp_query, 0..4, &timestamp_buffer, 0);
self.queue.submit([encoder.finish()]);
self.queue.submit([command_encoder.finish()]);
self.window.pre_present_notify();
self.queue.present(surface_texture);
let q = self.queue.get_timestamp_period();
let cloned_profile = self.profile.clone();
profile.read_back(&self.device, &self.queue, move |frame| {
*cloned_profile.lock() = frame;
});
// ~~ Get Ray-marching timestamps, report time ~~
let cloned_rm_time = self.rm_time.clone();
let cloned_frame_time = self.frame_time.clone();
+148 -41
View File
@@ -1,9 +1,10 @@
use std::num::NonZero;
use bytemuck::Zeroable;
use tiff::encoder;
use wgpu::{BindGroup, BindGroupLayout, Buffer, BufferUsages, CommandEncoder, ComputePipeline, Device, Queue, ShaderStages, naga::back::spv::Capability::Shader, util::DeviceExt};
use crate::{gpu::radix_sort::{self, RadixSorter}, 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}};
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}};
pub mod request_buffer;
@@ -26,6 +27,9 @@ pub struct VoxelCache<const N: usize>
// Contains location information per node for end application
location_pool: Buffer,
// Contains the depth of node from its structure table indirection
depth_pool: Buffer,
// User attributes
attributes_pools: Vec<Buffer>,
@@ -62,6 +66,7 @@ pub struct VoxelCache<const N: usize>
caching_pass: ComputePipeline,
invalidation_pass: ComputePipeline,
reset_pass: ComputePipeline,
indirect_usage_copy_pass: ComputePipeline,
buffer_compactor: NonZeroBufferCompactor,
sorter: RadixSorter,
@@ -113,6 +118,12 @@ where
mapped_at_creation: false,
});
let depth_pool = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("VoxelCache::depth_pool"),
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
contents: bytemuck::cast_slice(vec![u32::MAX; cache_size].as_slice()), // Fill empty nodes with max depth, so they end up first
});
// Create attribttues
let attributes_pools =
layout.attributes().iter().enumerate()
@@ -212,7 +223,7 @@ where
let (structure_bind_group_layout, structure_bind_group) = create_multi_buffers_bg_bg_layout(
&device,
&[&structure_pool, &location_pool],
&[&structure_pool, &location_pool, &depth_pool],
Some("VoxelCache::structure_bind_group"));
let (management_bind_group_layout, management_bind_group) = create_multi_buffers_bg_bg_layout(
@@ -264,6 +275,7 @@ where
// Structure bind group
@group(0) @binding(0) var<storage, read_write> structure_pool: array<StructurePoolElement>;
@group(0) @binding(1) var<storage, read_write> location_pool: array<LocationPoolElement>;
@group(0) @binding(2) var<storage, read_write> depth_pool: array<u32>;
// Management bind group
@group(1) @binding(0) var<storage, read_write> lru_list: array<u32>;
@@ -271,6 +283,7 @@ where
@group(1) @binding(2) var<storage, read_write> usage_buffer: array<u32>;
@group(1) @binding(3) var<storage, read_write> request_buffer: array<u32>;
@group(1) @binding(4) var<storage, read_write> cache_request_count: u32;
@group(1) @binding(5) var<storage, read_write> cache_scratch_buffer: array<u32>;
// Attributes bind group
@group(2) @binding(0) var<storage, read_write> attributes_pools: binding_array<AttributeArray, {attribute_count}>;
@@ -568,12 +581,12 @@ where
if(requests_wb[index].child_index == 0xFFFFFFFF)
{{
structure_table_pointers[requests_wb[index].node_index] = new_pointer;
//depth_pool[overwritten_element] = 0;
depth_pool[overwritten_element] = 0;
}}
else if(usage_buffer[requests_wb[index].node_index] != parameters.frame_timestamp + 1)
{{
structure_pool[requests_wb[index].node_index].pointers[requests_wb[index].child_index] = new_pointer;
//depth_pool[overwritten_element] = depth_pool[requests_wb[index].node_index] + 1;
depth_pool[overwritten_element] = depth_pool[requests_wb[index].node_index] + 1;
}}
}}
@@ -719,6 +732,41 @@ where
cache: None,
});
// ~~~ Indirect usage copy pipeline ~~~
// Copies usage according to indicies already sorted by depth in the lru list
// So they can be further sorted by usage
let indirect_usage_copy_pass =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("VoxelCache::indirect_usage_copy_pass"),
layout: Some(&invalidation_pipeline_layout),
module: &device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("VoxelCache::indirect_usage_copy_pass_shader_module"),
source: wgpu::ShaderSource::Wgsl(
format!("
{wgsl_cache_bindings}
@compute
@workgroup_size(64)
fn main(
@builtin(global_invocation_id) global_invocation_id: vec3<u32>
)
{{
var index = global_invocation_id.x;
let total_pool = arrayLength(&lru_list);
var sorted_index = lru_list[index];
var usage = usage_buffer[sorted_index];
cache_scratch_buffer[index] = usage;
}}
")
.into(),
),
}),
entry_point: Some("main"),
compilation_options: Default::default(),
cache: None,
});
// ~~ Structure table
let structure_table = StructureTable::new(device.clone(), queue.clone());
@@ -793,6 +841,7 @@ where
structure_pool,
attributes_pools,
location_pool,
depth_pool,
request_buffer,
sorted_request_buffer,
request_count_buffer,
@@ -810,6 +859,7 @@ where
caching_pass,
invalidation_pass,
reset_pass,
indirect_usage_copy_pass,
buffer_compactor,
sorter,
@@ -876,55 +926,112 @@ where
], Some("VoxelCache::structure_table_bind_group"))
}
pub fn cache_post_render(&mut self, encoder: &mut CommandEncoder, request_interface: &CacheProducerInterface<N>)
pub fn cache_post_render(&mut self, encoder: &mut ScopeEncoder, request_interface: &CacheProducerInterface<N>)
{
gpu_profiler::begin_scope!(encoder, "cache_post_render");
// Sort request buffer
{
self.buffer_compactor
.compact_buffer(
&self.device,
encoder,
&self.request_buffer,
&self.sorted_request_buffer,
Some(&self.cache_scratch_buffer)
);
self.buffer_compactor.copy_count_to_buffer(encoder, &self.request_count_buffer);
gpu_profiler::begin_scope!(encoder, "request_sort");
{
gpu_profiler::begin_scope!(encoder, "compaction");
self.buffer_compactor
.compact_buffer(
&self.device,
&mut encoder,
&self.request_buffer,
&self.sorted_request_buffer,
Some(&self.cache_scratch_buffer)
);
self.buffer_compactor.copy_count_to_buffer(&mut encoder, &self.request_count_buffer);
}
{
gpu_profiler::begin_scope!(encoder, "radix_sort");
self.sorter
.sort(
&self.device,
&self.cache_scratch_buffer,
&self.sorted_request_buffer,
Some(&self.request_count_buffer),
None,
&mut encoder,
radix_sort::RadixSortDirection::Descending
);
}
}
// Usage sorting
{
gpu_profiler::begin_scope!(encoder, "usage_sorting");
// Copy depth to scratch to preserve during sort
encoder.copy_buffer_to_buffer(
&self.depth_pool,
0,
&self.cache_scratch_buffer,
0, (self.size * size_of::<u32>()) as u64);
{
gpu_profiler::begin_scope!(encoder, "depth_radix");
// First sort by depth
// Deeper nodes are first now
self.sorter
.sort(
&self.device,
&self.cache_scratch_buffer,
&self.sorted_request_buffer,
Some(&self.request_count_buffer),
None,
encoder,
&self.lru_list,
None,
Some(self.size),
&mut encoder,
radix_sort::RadixSortDirection::Descending
);
); // Lowest (oldest) first
}
{
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,
});
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), &[]);
indirect_usage_copy_pass.set_bind_group(2, Some(&self.attributes_bind_group), &[]);
indirect_usage_copy_pass.set_bind_group(3, Some(&self.structure_table_bind_group()), &[]);
indirect_usage_copy_pass.set_pipeline(&self.indirect_usage_copy_pass);
indirect_usage_copy_pass.dispatch_workgroups(self.size.div_ceil(64) as u32, 1, 1);
drop(indirect_usage_copy_pass);
}
{
gpu_profiler::begin_scope!(encoder, "usage_radix");
// Sort usage
self.sorter
.sort(
&self.device,
&self.cache_scratch_buffer,
&self.lru_list,
None,
Some(self.size),
&mut encoder,
radix_sort::RadixSortDirection::Ascending
); // Lowest (oldest) first
}
}
// Copy usage to scratch to preserve during sort
encoder.copy_buffer_to_buffer(
&self.usage_buffer,
0,
&self.cache_scratch_buffer,
0, (self.size * size_of::<u32>()) as u64);
// Sort usage
self.sorter
.sort(
&self.device,
&self.cache_scratch_buffer,
&self.lru_list,
None,
Some(self.size),
encoder,
radix_sort::RadixSortDirection::Ascending
); // Lowest (oldest) first
self.structure_table
.request_buffer_mut()
.sort_requests(encoder);
{
gpu_profiler::begin_scope!(encoder, "structure_table");
self.structure_table
.request_buffer_mut()
.sort_requests(&mut encoder);
}
// 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,
@@ -946,7 +1053,7 @@ where
self.structure_table
.request_buffer_mut()
.reset_requests(encoder);
.reset_requests(&mut encoder);
}
pub fn current_timestamp(&self) -> u32