From 570ec62bdf7ad907813213204b65ee4233b6d9c9 Mon Sep 17 00:00:00 2001 From: Albin Chaboissier Date: Fri, 30 Oct 2026 17:32:12 +0100 Subject: [PATCH] Voxel cache rewrite --- shaders/gi.slang | 14 +- shaders/gi.spv | Bin 1896 -> 1896 bytes shaders/ray_cast.slang | 11 +- shaders/voxel.slang | 15 +- shaders/voxel.spv | Bin 14524 -> 14524 bytes src/gi_pipeline.rs | 30 -- src/gpu/indirect_buffer.rs | 10 +- src/main.rs | 432 ++++++++++++++---- src/producers.rs | 174 ++----- src/sparse_tree.rs | 12 +- src/voxel_cache.rs | 237 ++++++++-- src/voxel_cache/attributes.rs | 17 +- src/voxel_cache/eviction.rs | 23 +- src/voxel_cache/insertion.rs | 50 +- src/voxel_cache/layout.rs | 15 +- src/voxel_cache/pipelines.rs | 106 ++++- src/voxel_cache/requests.rs | 153 ++++++- src/voxel_cache/schema.rs | 12 +- src/voxel_cache/shaders/cache_common.wgsl | 76 +-- src/voxel_cache/shaders/common.wgsl | 74 +++ src/voxel_cache/shaders/eviction.wgsl | 12 +- .../shaders/fixed_table/insertion.wgsl | 32 ++ .../shaders/fixed_table/invalidation.wgsl | 42 ++ .../shaders/fixed_table/write_requests.wgsl | 32 ++ src/voxel_cache/shaders/insertion.wgsl | 108 +++-- src/voxel_cache/shaders/invalidation.wgsl | 20 +- src/voxel_cache/shaders/requests.wgsl | 10 +- src/voxel_cache/shaders/write_pointers.wgsl | 34 +- src/voxel_cache/shaders/write_requests.wgsl | 20 +- src/voxel_cache/structure.rs | 5 + src/voxel_cache/tables.rs | 294 ++++++++++++ 31 files changed, 1537 insertions(+), 533 deletions(-) create mode 100644 src/voxel_cache/shaders/common.wgsl create mode 100644 src/voxel_cache/shaders/fixed_table/insertion.wgsl create mode 100644 src/voxel_cache/shaders/fixed_table/invalidation.wgsl create mode 100644 src/voxel_cache/shaders/fixed_table/write_requests.wgsl create mode 100644 src/voxel_cache/tables.rs diff --git a/shaders/gi.slang b/shaders/gi.slang index 0c6226a..ac09ee6 100644 --- a/shaders/gi.slang +++ b/shaders/gi.slang @@ -85,9 +85,10 @@ RWStructuredBuffer attributes_pool[2]; RWStructuredBuffer request_buffer; [[vk::binding(3, 0)]] RWStructuredBuffer usage_buffer; -[[vk::binding(4, 0)]] + +[[vk::binding(0, 1)]] RWStructuredBuffer structure_table_pointer; -[[vk::binding(5, 0)]] +[[vk::binding(1, 1)]] RWStructuredBuffer> structure_table_request_buffer; ByteColor fetch_color(uint32_t index, uint32_t child_index) @@ -109,19 +110,19 @@ bool3 min_mask(float3 val) return val == min_val; } -[[vk::binding(0, 1)]] +[[vk::binding(0, 2)]] [[format("rgba32f")]] WTexture2D target_texture; -[[vk::binding(1, 1)]] +[[vk::binding(1, 2)]] [[format("rgba32f")]] RWTexture2D gbuffer_position; -[[vk::binding(2, 1)]] +[[vk::binding(2, 2)]] [[format("rgba32f")]] RWTexture2D gbuffer_albedo; -[[vk::binding(3, 1)]] +[[vk::binding(3, 2)]] [[format("rgba32f")]] RWTexture2D gbuffer_normal; @@ -154,6 +155,7 @@ void gi(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_Gr let albedo = gbuffer_albedo.Load(location.xy); target_texture.Store(location.xy, albedo); return; + let illumination = dot(float3(0., 1., 0.), normal.xyz); let view_dir = pos.xyz - constants.cam_pos; diff --git a/shaders/gi.spv b/shaders/gi.spv index d281caca3363eec4cbff1f911817b03d9ce58f40..4b93ff24a8aa6a0192cf3d26ccf3ee5fb8b4e4f7 100644 GIT binary patch delta 20 ccmaFC_kwT39wtVn$$Oc!8JRY}WU6NY08$(V{{R30 delta 20 ccmaFC_kwT39wtV{$$Oc!85uXfWU6NY08$DD{Qv*} diff --git a/shaders/ray_cast.slang b/shaders/ray_cast.slang index 1af7044..f15268d 100644 --- a/shaders/ray_cast.slang +++ b/shaders/ray_cast.slang @@ -87,8 +87,9 @@ public struct VoxelCache public RWStructuredBuffer attributes_pool[2]; public RWStructuredBuffer request_buffer; public RWStructuredBuffer usage_buffer; - public RWStructuredBuffer structure_table_pointer; - public RWStructuredBuffer> structure_table_request_buffer; + + public RWStructuredBuffer structure_table_pointer; + public RWStructuredBuffer> structure_table_request_buffer; } ByteColor fetch_color(VoxelCache cache, uint32_t index, uint32_t child_index) @@ -165,6 +166,8 @@ HitInformation chunk_ray_march( hit.hit = false; return hit; } + // _hit.color = float4(0., 1., 0., 1.); + // return _hit; // Ray mirroring ray_origin += float3(1.); @@ -232,7 +235,6 @@ HitInformation chunk_ray_march( uint64_t occupancy = get_child_mask(cache.structure_pool[current_node_index].occupancy_low, cache.structure_pool[current_node_index].occupancy_high); let occupied = ((occupancy >> child_index) & 1) != 0; - // if (occupied) if (fetch_color(cache, current_node_index, child_index).byte_a != 0) { var hit : HitInformation; @@ -342,7 +344,8 @@ public HitInformation ray_cast( { let off = t - abs(1. / context.ray_direction); let t_adv = max(max(off.x, max(off.y, off.z)), 0.); - let chunk_index = current_voxel.y + current_voxel.z * context.bounds.y + current_voxel.x * context.bounds.y * context.bounds.z; + // let chunk_index = current_voxel.y + current_voxel.z * context.bounds.y + current_voxel.x * context.bounds.y * context.bounds.z; + let chunk_index = current_voxel.x + current_voxel.z * context.bounds.x + current_voxel.y * context.bounds.x * context.bounds.z; let position = context.ray_origin + context.ray_direction * t_adv; var hit = chunk_ray_march( cache, diff --git a/shaders/voxel.slang b/shaders/voxel.slang index 9864f6f..6d07188 100644 --- a/shaders/voxel.slang +++ b/shaders/voxel.slang @@ -85,9 +85,10 @@ RWStructuredBuffer attributes_pool[2]; RWStructuredBuffer request_buffer; [[vk::binding(3, 0)]] RWStructuredBuffer usage_buffer; -[[vk::binding(4, 0)]] + +[[vk::binding(0, 1)]] RWStructuredBuffer structure_table_pointer; -[[vk::binding(5, 0)]] +[[vk::binding(1, 1)]] RWStructuredBuffer> structure_table_request_buffer; ByteColor fetch_color(uint32_t index, uint32_t child_index) @@ -109,15 +110,15 @@ bool3 min_mask(float3 val) return val == min_val; } -[[vk::binding(0, 1)]] +[[vk::binding(0, 2)]] [[format("rgba32f")]] WTexture2D gbuffer_position; -[[vk::binding(1, 1)]] +[[vk::binding(1, 2)]] [[format("rgba32f")]] WTexture2D gbuffer_albedo; -[[vk::binding(2, 1)]] +[[vk::binding(2, 2)]] [[format("rgba32f")]] WTexture2D gbuffer_normal; @@ -174,8 +175,10 @@ void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_ { // Gather let hit_pos = hit.hit_pos; + let hit_normal = fetch_normal(hit.node_index, hit.child_index); - let hit_albedo = fetch_color(hit.node_index, hit.child_index).float_color; + var hit_albedo = float4(0.); + hit_albedo = fetch_color(hit.node_index, hit.child_index).float_color; // let hit_albedo = hit.color; gbuffer_position.Store(location.xy, float4(hit_pos, 1.)); diff --git a/shaders/voxel.spv b/shaders/voxel.spv index 43f5cd1ca47789bbb07f61554d15f10dbade2ab2..3cff6c3968c399036dd35d6b3164dd834ed66e7f 100644 GIT binary patch delta 100 zcmdl}xTkQ#2R1>Zu+A!{&tSF~G`Gzdd -{ - voxel_cache: VoxelCache, - // ~~ Leaf list ~~ - // The leaf list is maintained in a sparse swap'n'pop fashion - leaf_list: PageList, -} - -impl VoxelGiPipeline -{ - 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, - } - } -} diff --git a/src/gpu/indirect_buffer.rs b/src/gpu/indirect_buffer.rs index 6427e12..936bfc8 100644 --- a/src/gpu/indirect_buffer.rs +++ b/src/gpu/indirect_buffer.rs @@ -31,7 +31,7 @@ impl IndirectBuffer1D let indirect_storage = device.create_buffer(&wgpu::BufferDescriptor { label: Some("IndirectBuffer1D::indirect_storage"), size: size_of::() as u64, - usage: wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::COPY_SRC, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false, }); @@ -69,8 +69,8 @@ impl IndirectBuffer1D z: u32 } - @group(0) @binding(0) indirect_storage: IndirectDispatchArgs; - @group(1) @binding(0) user_count: u32; + @group(0) @binding(0) var indirect_storage: IndirectDispatchArgs; + @group(1) @binding(0) var user_count: u32; var workgroup_size: u32; @@ -78,7 +78,7 @@ impl IndirectBuffer1D @workgroup_size(1, 1, 1) fn main() { - let workgroup_count = (user_count / workgroup_size) + select(user_count % workgroup_size == 0, u32(0), u32(1)); + let workgroup_count = (user_count / workgroup_size) + select(u32(1), u32(0), user_count % workgroup_size == 0); var args: IndirectDispatchArgs; args.x = workgroup_count; @@ -126,7 +126,7 @@ impl IndirectBuffer1D device: &wgpu::Device, encoder: &mut CommandEncoder, count_buffer: &Buffer, - workgroup_size: usize, + workgroup_size: u32, ) -> &Buffer { // Transient bind group diff --git a/src/main.rs b/src/main.rs index 868c982..9aed685 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,7 +3,8 @@ use std::collections::HashMap; use std::sync::Arc; -use std::sync::mpsc::sync_channel; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::AtomicU32; use bytemuck::Pod; use bytemuck::Zeroable; @@ -16,11 +17,6 @@ use glam::Mat4; use glam::Vec3; use glam::Vec4; use itertools::Itertools; -use rand::random; -use rand::random_range; -use rayon::iter::IndexedParallelIterator; -use rayon::iter::IntoParallelRefIterator; -use rayon::iter::ParallelIterator; use wgpu::BindGroupLayout; use wgpu::Buffer; use wgpu::BufferUsages; @@ -60,12 +56,13 @@ use crate::producers::SdfGenerator; use crate::producers::TerrainGenerator; use crate::sparse_tree::NTreeNodeLocator; use crate::voxel_cache::VoxelCache; -use crate::voxel_cache::data::ColorBytes; -use crate::voxel_cache::data::LocationPoolElement; -use crate::voxel_cache::data::StructurePoolElement; -use crate::voxel_cache::layout::VoxelCacheLayout; -use crate::voxel_cache::producer_interface::CacheProducerInterface; -use crate::voxel_cache::producer_interface::CacheRequest; +use crate::voxel_cache::VoxelCacheInsertion; +use crate::voxel_cache::insertion::CacheInsertionData; +use crate::voxel_cache::requests::CacheRequestBuffer; +use crate::voxel_cache::schema::InsertionInformation; +use crate::voxel_cache::schema::LocationPage; +use crate::voxel_cache::schema::RequestInformation; +use crate::voxel_cache::tables::FixedStructureTable; mod camera; mod egui_renderer; @@ -108,10 +105,16 @@ struct State gi_pipeline: ComputePipeline, surface_bg_layout: BindGroupLayout, gi_bg_layout: BindGroupLayout, + voxel_cache: Arc>>, - cache_interface: Arc>, - //terrain_generator: Arc>, - terrain_generator: Arc>, + request_buffer: Arc, + cache_insertion: Arc>, + + structure_table: Arc>, + structure_table_request_buffer: Arc, + structure_table_cache_insertion: Arc>, + terrain_generator: Arc>, + //terrain_generator: Arc>, chunk_pos_map: Arc>, instance_buffer: Buffer, instance_count: usize, @@ -188,6 +191,7 @@ impl State | Features::TIMESTAMP_QUERY_INSIDE_ENCODERS | Features::TIMESTAMP_QUERY_INSIDE_PASSES | Features::STORAGE_RESOURCE_BINDING_ARRAY + | Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING | Features::BUFFER_BINDING_ARRAY | Features::PASSTHROUGH_SHADERS | Features::SHADER_INT64, @@ -338,24 +342,24 @@ impl State let egui_renderer = EguiRenderer::new(&device, surface_format, &window); - let mut attributes = VoxelCacheLayout::default(); - attributes.add_attribute(voxel_cache::layout::VoxelCacheAttribute { + let mut layout = voxel_cache::layout::CacheLayout::default(); + layout.add_attribute(voxel_cache::CacheAttribute { + label: Some("color"), word_count: 1, - rate: voxel_cache::layout::VoxelCacheAttributeRate::Pointer, - init: voxel_cache::layout::VoxelCacheAttributeInit::Copy, + init: voxel_cache::CacheAttributeInit::External, }); - attributes.add_attribute(voxel_cache::layout::VoxelCacheAttribute { + layout.add_attribute(voxel_cache::CacheAttribute { + label: Some("normal"), word_count: 3, - rate: voxel_cache::layout::VoxelCacheAttributeRate::Pointer, - init: voxel_cache::layout::VoxelCacheAttributeInit::Copy, + init: voxel_cache::CacheAttributeInit::External, }); - let mut voxel_cache = - VoxelCache::<4>::new(150_000, device.clone(), queue.clone(), &attributes); - let cache_interface = CacheProducerInterface::new(1024, &device, &attributes); + let voxel_cache = VoxelCache::<4>::new(&device, 100_000, &layout); + let request_buffer = CacheRequestBuffer::new(&device, 1024); + let insertion_data = CacheInsertionData::new(&device, 1024, &layout); - 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", @@ -370,31 +374,36 @@ 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 + terrain_width * terrain_height * terrain_alt ); let mut chunk_pos_map = HashMap::new(); - let chunk_instances = (0..terrain_width) - .cartesian_product(0..terrain_height) - .cartesian_product(0..terrain_alt) - .map(|((x, z), y)| { - let chunk_id = voxel_cache.structure_table.allocate_structure(true); - //dbg!(chunk_id); + let total_chunk_count = terrain_height * terrain_width * terrain_alt; - chunk_pos_map.insert(chunk_id, (x, y, z)); + 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 chunk_instances = (0..terrain_alt) + .cartesian_product(0..terrain_height) + .cartesian_product(0..terrain_width) + .map(|((y, z), x)| { + //dbg!(chunk_id); + let chunk_id = y * terrain_width * terrain_height + z * terrain_width + x; + + chunk_pos_map.insert(chunk_id as u32, (x, y, z)); InstanceAttribute { x: x as f32, y: y as f32, z: z as f32, - id: chunk_id, + id: chunk_id as u32, } }) .collect::>(); @@ -587,7 +596,8 @@ impl State label: Some("Voxel pipeline layout"), bind_group_layouts: &[ - Some(voxel_cache.user_bind_group_layout()), + Some(voxel_cache.raytrace_bind_group_layout()), + Some(structure_table.raytrace_bind_group_layout()), Some(&ray_march_bind_group_layout), ], immediate_size: size_of::() as u32, @@ -609,7 +619,8 @@ impl State label: Some("Gi pipeline layout"), bind_group_layouts: &[ - Some(&voxel_cache.user_bind_group_layout()), + Some(voxel_cache.raytrace_bind_group_layout()), + Some(structure_table.raytrace_bind_group_layout()), Some(&gi_bind_group_layout), ], immediate_size: size_of::() as u32, @@ -666,7 +677,13 @@ impl State usage_vec: Arc::new(Mutex::new(vec![])), pipeline: chunk_pipeline, voxel_cache: Arc::new(Mutex::new(voxel_cache)), - cache_interface: cache_interface.into(), + request_buffer: Arc::new(request_buffer), + cache_insertion: Arc::new(insertion_data), + + structure_table: Arc::new(Mutex::new(structure_table)), + structure_table_cache_insertion: Arc::new(structure_table_insertion_data), + structure_table_request_buffer: Arc::new(structure_table_request_buffer), + insertion_debounce: false, camera: Default::default(), instance_buffer, @@ -881,7 +898,6 @@ impl State fn render(&mut self) { self.camera.update(); - self.voxel_cache.lock().next_frame(); // Create texture view. // NOTE: We must handle Timeout because the surface may be unavailable @@ -999,8 +1015,13 @@ impl State }); 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), &[]); + renderpass.set_bind_group(0, self.voxel_cache.lock().raytrace_bind_group(), &[]); + renderpass.set_bind_group( + 1, + self.structure_table.lock().raytrace_bind_group(), + &[], + ); + renderpass.set_bind_group(2, Some(&surface_bg), &[]); let imm = [Immediates { view_proj: self.camera.view_proj().inverse(), cam_pos: self.camera.position, @@ -1023,7 +1044,7 @@ impl State ); 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.set_bind_group(2, Some(&gi_surface_bg), &[]); renderpass.dispatch_workgroups( self.size.width.div_ceil(16), self.size.height.div_ceil(16), @@ -1130,24 +1151,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_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; + // }, + // ); // DownloadBuffer::read_buffer( // &self.device, @@ -1172,9 +1193,17 @@ impl State .pressed_keyset .contains(&winit::keyboard::KeyCode::KeyF) { - self.voxel_cache - .lock() - .cache_post_render(&mut encoder, &self.cache_interface); + self.voxel_cache.lock().gather_requests( + &self.device, + &mut encoder, + &self.request_buffer, + ); + + self.structure_table.lock().gather_requests( + &self.device, + &mut encoder, + &self.structure_table_request_buffer, + ); } // ~~ Submit command buffer ~~ @@ -1220,23 +1249,169 @@ impl State .contains(&winit::keyboard::KeyCode::KeyF) { self.insertion_debounce = true; - let request_count = self - .cache_interface - .total_request_count(&self.device, &self.queue); - let cloned_cache = self.voxel_cache.clone(); - let cloned_device = self.device.clone(); let cloned_queue = self.queue.clone(); 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); + let finished = Arc::new(AtomicU32::new(0)); + + // Cache requests + let cloned_insertion_data = self.cache_insertion.clone(); + let request_buffer_done = Arc::new(AtomicBool::new(false)); + let request_buffer_done_1 = request_buffer_done.clone(); + let finshed_1 = finished.clone(); + self.request_buffer.host_download_requests( + &self.device, + &self.queue, + move |request_informations| { + let done = request_buffer_done_1.load(std::sync::atomic::Ordering::Relaxed); + if !done + { + request_buffer_done_1.store(true, std::sync::atomic::Ordering::Relaxed); + finshed_1.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + else + { + return; + } + + //println!("Cache : {} requests", request_informations.len()); + + let mut insertion_infos = vec![]; + let mut color_attributes = vec![]; + 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); + } + + cloned_queue.write_buffer( + cloned_insertion_data.insertion_information_buffer(), + 0, + bytemuck::cast_slice(&insertion_infos), + ); + + cloned_queue.write_buffer( + cloned_insertion_data.location_pages_buffer(), + 0, + bytemuck::cast_slice(&location_pages), + ); + + cloned_queue.write_buffer( + &cloned_insertion_data.attributes_buffers()[0], + 0, + bytemuck::cast_slice(&color_attributes), + ); + + cloned_queue.write_buffer( + &cloned_insertion_data.attributes_buffers()[1], + 0, + bytemuck::cast_slice(&normal_attributes), + ); + + cloned_queue.write_buffer( + cloned_insertion_data.page_count_buffer(), + 0, + bytemuck::bytes_of(&(request_informations.len() as u32)), + ); + }, + ); + + let cloned_queue = self.queue.clone(); + let cloned_generator = self.terrain_generator.clone(); + let cloned_map = self.chunk_pos_map.clone(); + + // Structure table requests + let cloned_st_insertion_data = self.structure_table_cache_insertion.clone(); + let structure_table_request_buffer_done = Arc::new(AtomicBool::new(false)); + let structure_table_request_buffer_done_1 = structure_table_request_buffer_done.clone(); + let finshed_2 = finished.clone(); + self.structure_table_request_buffer.host_download_requests( + &self.device, + &self.queue, + move |request_informations| { + let done = structure_table_request_buffer_done_1 + .load(std::sync::atomic::Ordering::Relaxed); + if !done + { + structure_table_request_buffer_done_1 + .store(true, std::sync::atomic::Ordering::Relaxed); + finshed_2.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + else + { + return; + } + + //println!("Structure table: {} requests", request_informations.len()); + + let mut insertion_infos = vec![]; + let mut color_attributes = vec![]; + 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); + } + + cloned_queue.write_buffer( + cloned_st_insertion_data.insertion_information_buffer(), + 0, + bytemuck::cast_slice(&insertion_infos), + ); + + cloned_queue.write_buffer( + cloned_st_insertion_data.location_pages_buffer(), + 0, + bytemuck::cast_slice(&location_pages), + ); + + cloned_queue.write_buffer( + &cloned_st_insertion_data.attributes_buffers()[0], + 0, + bytemuck::cast_slice(&color_attributes), + ); + + cloned_queue.write_buffer( + &cloned_st_insertion_data.attributes_buffers()[1], + 0, + bytemuck::cast_slice(&normal_attributes), + ); + + cloned_queue.write_buffer( + cloned_st_insertion_data.page_count_buffer(), + 0, + bytemuck::bytes_of(&(request_informations.len() as u32)), + ); + }, + ); // ~~ Download request buffer, fullfill requests, writeback to cache ~~ + /* DownloadBuffer::read_buffer( &self.device.clone(), &self.queue.clone(), - &self.cache_interface.requests_buffer().slice(..), + &self.request_buffer.requests_buffer().slice(..), move |buffer| { if tx.try_send(()).is_err() { @@ -1371,17 +1546,52 @@ impl State } }, ); + */ //println!("Total request count: {}", request_count); loop { - if rx.try_recv().is_ok() + if finished.load(std::sync::atomic::Ordering::Relaxed) >= 2 { break; } let _ = self.device.poll(wgpu::wgt::PollType::Poll); } - drop(rx); + let mut encoder = self.device.create_command_encoder(&Default::default()); + + let mut scoped_encoder = ProfilingEncoder::new(&self.device, &mut encoder); + { + gpu_profiler::begin_frame!(scoped_encoder, "Cache insertion"); + let mut locked_st = self.structure_table.lock(); + self.voxel_cache.lock().insert( + &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, + ), + ], + ); + + locked_st.insert( + &self.device, + &mut scoped_encoder, + &self.structure_table_cache_insertion, + &self.structure_table_request_buffer, + ); + } + + let cloned_insert_profile = self.insert_profile.clone(); + let gpu_profile = scoped_encoder.finish_profiler(); + self.queue.submit([encoder.finish()]); + gpu_profile.read_back(&self.device, &self.queue, move |profile| { + *cloned_insert_profile.lock() = profile; + }); } } @@ -1507,3 +1717,63 @@ pub struct ChunkImmediate root_subdiv: bool, frame_timestamp: u32, } + +fn fullfill_request( + generator: &dyn ChunkedProducer, + request: &RequestInformation, + map: &HashMap, +) -> ( + [u32; N * N * N], + [[f32; 3]; N * N * N], + InsertionInformation, + LocationPage, +) +where + [(); N * N * N]:, +{ + // Unpack structure id + let (chunk_x, chunk_y, chunk_z) = *map.get(&request.structure_id).unwrap(); + + let location; + let node; + if request.node_id == 0 + { + // Produce root node + node = generator.produce_node(0, 0, 0, 0, (chunk_x, chunk_y, chunk_z)); + location = LocationPage { + structure_id: request.structure_id, + node_id: NTreeNodeLocator::<4>::root().as_usize() as u32, + }; + } + else + { + // Figure out depth of request + let locator = NTreeNodeLocator::<4>::from_usize(request.node_id as usize); + let depth = locator.depth(); + //let (x, y, z) = locator.node_location(); + + let child_z = request.children_index / (4 * 4); + let child_y = (request.children_index % (4 * 4)) / 4; + let child_x = request.children_index % 4; + + let child_locator = locator.child(child_x as usize, child_y as usize, child_z as usize); + + let (nx, ny, nz) = child_locator.node_location(); + + node = generator.produce_node(depth + 1, nx, ny, nz, (chunk_x, chunk_y, chunk_z)); + + location = LocationPage { + structure_id: request.structure_id, + node_id: child_locator.as_usize() as u32, + }; + } + + ( + node.colors, + node.normals, + InsertionInformation { + children: node.children, + }, + location, + ) +} diff --git a/src/producers.rs b/src/producers.rs index 7d62e68..c88ab92 100644 --- a/src/producers.rs +++ b/src/producers.rs @@ -13,8 +13,7 @@ use noise::Worley; use rand::random; use crate::sparse_tree::Color; -use crate::voxel_cache::data::ExplicitNTreeNode; -use crate::voxel_cache::data::StructurePointer; +use crate::voxel_cache::schema::ChildInformation; pub struct BallGenerator { @@ -36,7 +35,7 @@ pub trait Producer where [(); N * N * N]:, { - fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ExplicitNTreeNode; + fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ProducedChunk; } impl BallGenerator @@ -53,7 +52,7 @@ impl Producer for BallGenerator where [(); N * N * N]:, { - fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ExplicitNTreeNode + fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ProducedChunk { let node_size = N.pow((self.chunk_power - depth) as u32); let child_size = node_size / N; @@ -91,19 +90,17 @@ where } else if dist > (global_size as f32 / 2.) { - children.push(StructurePointer(0)); subdivided = false; alpha = 0.; } else { - children.push(StructurePointer(0)); subdivided = false; alpha = 1.; } // let alpha = 1.; - children.push(StructurePointer::new(subdivided, subdivided || alpha != 0.)); + children.push(ChildInformation::new(subdivided, subdivided || alpha != 0.)); children_normal.push((0., 0., 0.)); children_color.push(Color( gvx as f32 / global_size as f32, @@ -113,128 +110,10 @@ where )); } - ExplicitNTreeNode { - structure: std::array::from_fn(|i| children[i]), - colors: std::array::from_fn(|i| children_color[i]), - normals: std::array::from_fn(|i| children_normal[i]), - } - } -} - -pub struct SineGenerator -{ - chunk_power: usize, -} - -impl SineGenerator -where - [(); N * N * N]:, -{ - pub fn new(chunk_power: usize) -> Self - { - Self { chunk_power } - } -} - -impl Producer for SineGenerator -where - [(); N * N * N]:, -{ - fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ExplicitNTreeNode - { - let node_size = N.pow((self.chunk_power - depth) as u32); - let child_size = node_size / N; - let global_size = N.pow(self.chunk_power as u32); - - let mut children = vec![]; - let mut children_normal = vec![]; - let mut children_color = vec![]; - - let gnx = nx * node_size; - let gny = ny * node_size; - let gnz = nz * node_size; - // Iterate on children of this node - for ((cx, cy), cz) in (0..N).cartesian_product(0..N).cartesian_product(0..N) - { - let total_sub_voxels = child_size * child_size * child_size; - let mut filled_sub_voxels = 0; - - let gcx = gnx + cx * child_size; - let gcy = gny + cy * child_size; - let gcz = gnz + cz * child_size; - - // prepare 2d values - - // Iterate on children - for (x, z) in (0..child_size).cartesian_product(0..child_size) - { - let gvx = gcx + x; - let gvz = gcz + z; - //let gvy = gcy; - let sx = map(gvx as f32, 0., global_size as f32, -8., 8.).abs(); - let sz = map(gvz as f32, 0., global_size as f32, -8., 8.).abs(); - let sample = (fastapprox::fast::cos(sx) + fastapprox::fast::cos(sz)) * 0.5; - let sample_height = map(sample, -1., 1., 0., 500.); - - let prop = map( - sample_height, - gcy as f32, - (gcy + child_size) as f32, - 0., - child_size as f32, - ) - .clamp(0., child_size as f32) - .floor() as usize; - filled_sub_voxels += prop; - } - - let alpha; - if filled_sub_voxels == 0 - { - children.push(StructurePointer(0)); - alpha = 0.; - } - else if filled_sub_voxels >= total_sub_voxels - { - children.push(StructurePointer(0)); - alpha = 1.; - } - else - { - children.push(StructurePointer( - if depth < (self.chunk_power - 1) - { - 0xFFFFFFFF - } - else - { - 0 - }, - )); - //children.push(StructurePointer(0)); - alpha = if filled_sub_voxels > total_sub_voxels / 2 - { - 1. - } - else - { - 0. - }; - } - - children_normal.push((0., 0., 0.)); - children_color.push(Color( - (gcx + child_size / 2) as f32 / global_size as f32, - (gcy + child_size / 2) as f32 / global_size as f32, - (gcz + child_size / 2) as f32 / global_size as f32, - alpha, - )); - } - - ExplicitNTreeNode { - structure: std::array::from_fn(|i| children[i]), - colors: std::array::from_fn(|i| children_color[i]), - normals: std::array::from_fn(|i| children_normal[i]), + ProducedChunk { + children: std::array::from_fn(|i| children[i]), + colors: std::array::from_fn(|i| children_color[i].as_packed_u32()), + normals: std::array::from_fn(|i| children_normal[i].into()), } } } @@ -424,13 +303,13 @@ where ny: usize, nz: usize, chunk_pos: (usize, usize, usize), - ) -> ExplicitNTreeNode + ) -> ProducedChunk { let node_size = N.pow((self.chunk_power - depth) as u32); let child_size = node_size / N; let global_size = N.pow(self.chunk_power as u32); - let mut children = vec![StructurePointer(0); N * N * N]; + let mut children = vec![ChildInformation::NONE; N * N * N]; let mut children_color = vec![Color(0., 0., 0., 0.); N * N * N]; let mut children_normals = vec![(0., 0., 0.); N * N * N]; @@ -563,21 +442,30 @@ where }; } - children[index] = StructurePointer::new(subdivided, subdivided || alpha != 0.); + children[index] = ChildInformation::new(subdivided, subdivided || alpha != 0.); children_normals[index] = (0., 0., 0.); children_color[index] = Color(color_avg.0, color_avg.1, color_avg.2, alpha); //children_color[index] = Color(1., 1., 1., alpha); } } - ExplicitNTreeNode { - structure: std::array::from_fn(|i| children[i]), - colors: std::array::from_fn(|i| children_color[i]), - normals: std::array::from_fn(|i| children_normals[i]), + ProducedChunk { + children: std::array::from_fn(|i| children[i]), + colors: std::array::from_fn(|i| children_color[i].as_packed_u32()), + normals: std::array::from_fn(|i| children_normals[i].into()), } } } +pub struct ProducedChunk +where + [(); N * N * N]:, +{ + pub children: [ChildInformation; N * N * N], + pub colors: [u32; N * N * N], + pub normals: [[f32; 3]; N * N * N], +} + pub trait ChunkedProducer where [(); N * N * N]:, @@ -589,7 +477,7 @@ where ny: usize, nz: usize, chunk_pos: (usize, usize, usize), - ) -> ExplicitNTreeNode; + ) -> ProducedChunk; } pub struct SdfGenerator @@ -620,7 +508,7 @@ where ny: usize, nz: usize, chunk_pos: (usize, usize, usize), - ) -> ExplicitNTreeNode + ) -> ProducedChunk { // let sdf = |x: f32, y: f32, z: f32| { // Vec3::new((x % 1024.) - 512., (y % 1024.) - 512., (z % 1024.) - 512.).length() - 512. @@ -723,16 +611,16 @@ where // (gvz - cz) as f32 / global_size as f32, // alpha, // )); - children.push(StructurePointer::new(subdivided, subdivided || alpha != 0.)); + children.push(ChildInformation::new(subdivided, subdivided || alpha != 0.)); children_color.push(Color(color + random::() * 0.02, color, color, alpha)); children_normals.push((normal.x, normal.y, normal.z)); //children_color.push(Color(normal.x, normal.y, normal.z, alpha)); } - ExplicitNTreeNode { - structure: std::array::from_fn(|i| children[i]), - colors: std::array::from_fn(|i| children_color[i]), - normals: std::array::from_fn(|i| children_normals[i]), + ProducedChunk { + children: std::array::from_fn(|i| children[i]), + colors: std::array::from_fn(|i| children_color[i].as_packed_u32()), + normals: std::array::from_fn(|i| children_normals[i].into()), //normals: std::array::from_fn(|i| (1., 0., 0.)), } } diff --git a/src/sparse_tree.rs b/src/sparse_tree.rs index 5df04b0..4051da5 100644 --- a/src/sparse_tree.rs +++ b/src/sparse_tree.rs @@ -5,9 +5,6 @@ use bytemuck::Pod; use bytemuck::Zeroable; use itertools::Itertools; -use crate::voxel_cache::data::ExplicitNTreeNode; -use crate::voxel_cache::data::StructurePointer; - #[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)] #[repr(C)] pub struct Color(pub f32, pub f32, pub f32, pub f32); @@ -32,6 +29,15 @@ impl Color c.3 /= count as f32; c } + + 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; + mapped_r | (mapped_g << 8) | (mapped_b << 16) | (mapped_a << 24) + } } #[derive(Debug, Clone)] diff --git a/src/voxel_cache.rs b/src/voxel_cache.rs index 832800b..b182b9f 100644 --- a/src/voxel_cache.rs +++ b/src/voxel_cache.rs @@ -1,3 +1,5 @@ +use std::num::NonZero; + use wgpu::CommandEncoder; use wgpu::Device; @@ -24,6 +26,9 @@ pub mod pipelines; pub mod requests; pub mod schema; pub mod structure; +pub mod tables; + +pub use layout::*; /// Stores some ressources that can be reused throughout the modules of the cache struct CacheRessources @@ -38,7 +43,7 @@ impl CacheRessources { let scratch_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("CacheRessources::scratch_buffer"), - usage: wgpu::BufferUsages::STORAGE, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, size: (size_of::() * page_count * N * N * N) as u64, mapped_at_creation: false, }); @@ -70,14 +75,29 @@ where cache_invalidation_pass: CacheInvalidationPass, write_pointers_pass: WritePointersPass, + // Raytracing + raytrace_bind_group_layout: wgpu::BindGroupLayout, + raytrace_bind_group: wgpu::BindGroup, + frame_timestamp: u32, } -pub struct VoxelCacheWriter<'cache, const N: usize> +pub trait CacheInvalidable +{ + fn invalidate( + &mut self, + encoder: &mut ScopeEncoder, + cache_evictor: &CacheEvictor, + invalid_timestamp: u32, + ); +} + +pub enum VoxelCacheInsertion<'a, const N: usize> where [(); N * N * N]:, { - cache: &'cache mut VoxelCache, + ExternalRequest(&'a CacheInsertionData, &'a mut dyn CacheInvalidable), + InternalRequest(&'a CacheInsertionData, &'a CacheRequestBuffer), } impl VoxelCache @@ -97,6 +117,14 @@ where let cache_invalidation_pass = CacheInvalidationPass::new(device, page_count, layout); let write_pointers_pass = WritePointersPass::new(device, page_count, layout); + let (raytrace_bind_group_layout, raytrace_bind_group) = Self::create_raytrace_bind_group( + device, + &structure, + &attributes, + &request_handler, + &evictor, + ); + Self { page_count, structure, @@ -110,6 +138,9 @@ where cache_invalidation_pass, write_pointers_pass, + raytrace_bind_group_layout, + raytrace_bind_group, + frame_timestamp: 0, } } @@ -125,8 +156,6 @@ where self.request_handler .sort_requests(device, &self.common_ressources, &mut encoder); - self.evictor - .prepare_eviction_list(device, &self.common_ressources, &mut encoder); self.write_requests_pass.encode( &mut encoder, @@ -135,42 +164,192 @@ where &self.request_handler, request_buffer, ); + + self.request_handler.reset(&mut encoder); } - pub fn write_invalidate)>( + /// Inserts new pages into the cache. Two insertion modes are available: + /// + /// External: Inserts brand new pages, regardless of the misses in the cache. This can be used + /// to bring external requests into the cache + /// + /// Internal: This is the response to requests emited inside the cache (gotten through the + /// gather requests method) + pub fn insert( &mut self, - encoder: &mut ScopeEncoder, - mut write_ops: F, - ) - { - let writer = VoxelCacheWriter { cache: self }; - write_ops(&writer); - - self.cache_invalidation_pass.encode( - encoder, - &self.structure, - &self.evictor, - self.frame_timestamp, - ); - } - - pub fn write_pointers( - &self, device: &Device, encoder: &mut ScopeEncoder, - request_buffer: &CacheRequestBuffer, - insertion: &CacheInsertionData, + insertions: &mut [&mut VoxelCacheInsertion], ) { - gpu_profiler::begin_scope!(encoder, "insert_pages"); + gpu_profiler::begin_scope!(encoder, "insertion"); + let new_timestamp = self.frame_timestamp + 1; - self.write_pointers_pass.encode( + self.evictor + .prepare_eviction_list(device, &self.common_ressources, &mut encoder); + + for insertion in insertions.iter() + { + match insertion + { + VoxelCacheInsertion::ExternalRequest(cache_insertion_data, _) + | VoxelCacheInsertion::InternalRequest(cache_insertion_data, _) => + { + self.cache_insertion_pass.encode( + device, + &mut encoder, + &self.attributes, + &self.structure, + cache_insertion_data, + &self.evictor, + new_timestamp, + ); + } + } + } + + // Invalidate external structures pointing inside the cache + for insertion in insertions.iter_mut() + { + if let VoxelCacheInsertion::ExternalRequest(_, invalidable) = insertion + { + invalidable.invalidate(&mut encoder, &self.evictor, new_timestamp); + } + } + + // Invalidate cache pages + self.cache_invalidation_pass.encode( &mut encoder, - device, &self.structure, - request_buffer, &self.evictor, + new_timestamp, ); + + // Write internal requests pointers + for insertion in insertions.iter_mut() + { + if let VoxelCacheInsertion::InternalRequest(insertion, request) = insertion + { + self.write_pointers_pass.encode( + &mut encoder, + device, + &self.structure, + request, + insertion, + ); + } + } + + // Proceed to new frame + self.frame_timestamp = new_timestamp; + } + + pub fn current_timestamp(&self) -> u32 + { + self.frame_timestamp + } + + fn create_raytrace_bind_group( + device: &wgpu::Device, + structure: &CacheStructure, + attributes: &CacheAttributes, + request_handler: &CacheRequestHandler, + evictor: &CacheEvictor, + ) -> (wgpu::BindGroupLayout, wgpu::BindGroup) + { + let attribute_count = attributes.attribute_buffers().len(); + let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("VoxelCache::raytrace_bind_group_layout"), + entries: &[ + // Structure pointers + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: true }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + // Attributes + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: false }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: Some( + NonZero::new(attribute_count as u32) + .expect("Null amount of cache attributes."), + ), + }, + // Request pages + wgpu::BindGroupLayoutEntry { + binding: 2, + 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, + }, + // Usage pages + wgpu::BindGroupLayoutEntry { + binding: 3, + 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, + }, + ], + }); + + let attributes_bindings = attributes + .attribute_buffers() + .iter() + .map(|buffer| buffer.as_entire_buffer_binding()) + .collect::>(); + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("VoxelCache::raytrace_bind_group"), + layout: &bind_group_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: structure.pointer_pages().as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::BufferArray(&attributes_bindings), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: request_handler.request_pages_buffer().as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: evictor.timestamp_pages_buffer().as_entire_binding(), + }, + ], + }); + + (bind_group_layout, bind_group) + } + + pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout + { + &self.raytrace_bind_group_layout + } + + pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup + { + &self.raytrace_bind_group } } diff --git a/src/voxel_cache/attributes.rs b/src/voxel_cache/attributes.rs index 7f64370..1f9e6c0 100644 --- a/src/voxel_cache/attributes.rs +++ b/src/voxel_cache/attributes.rs @@ -1,4 +1,6 @@ use wgpu::BindGroupLayout; +use wgpu::Buffer; +use wgpu::BufferUsages; use crate::voxel_cache::layout::CacheLayout; @@ -19,7 +21,9 @@ impl CacheAttributes let attribute_buffers = layout .attributes .iter() - .map(|attribute| attribute.create_buffer(device, N, page_count)) + .map(|attribute| { + attribute.create_buffer(device, N * N * N, page_count, BufferUsages::STORAGE) + }) .collect::>(); let bind_group_layout = Self::create_bind_group_layout(device, layout); @@ -48,10 +52,10 @@ impl CacheAttributes pub fn create_bind_group_layout(device: &wgpu::Device, layout: &CacheLayout) -> BindGroupLayout { - let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("CacheAttributes::bind_group_layout"), entries: &[wgpu::BindGroupLayoutEntry { - binding: 1, + binding: 0, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: false }, @@ -63,7 +67,7 @@ impl CacheAttributes .expect("Cannot create cache attributes with no attributes"), ), }], - }); + }) } pub fn bind_group_layout(&self) -> &wgpu::BindGroupLayout @@ -75,4 +79,9 @@ impl CacheAttributes { &self.bind_group } + + pub fn attribute_buffers(&self) -> &[Buffer] + { + &self.attribute_buffers + } } diff --git a/src/voxel_cache/eviction.rs b/src/voxel_cache/eviction.rs index 775ea73..a5f9566 100644 --- a/src/voxel_cache/eviction.rs +++ b/src/voxel_cache/eviction.rs @@ -26,6 +26,9 @@ pub struct CacheEvictor /// Contains indices in LRU order, after sorting lru_list: wgpu::Buffer, + /// 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, @@ -42,7 +45,7 @@ impl CacheEvictor { let timestamp_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("CacheUsage::timestamp_pages"), - usage: wgpu::BufferUsages::STORAGE, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, contents: bytemuck::cast_slice(&vec![initial_timestamp; page_count]), }); @@ -53,10 +56,16 @@ impl CacheEvictor mapped_at_creation: false, }); + let consumed_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("CacheUsage::consumed_count"), + usage: wgpu::BufferUsages::STORAGE, + 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], + &[&lru_list, &consumed_count], Some("CacheEvictor::reset_lru_list_bind_group"), ); @@ -81,7 +90,7 @@ impl CacheEvictor let bind_group = create_multi_buffers_bind_group( device, &bind_group_layout, - &[×tamp_pages, &lru_list], + &[×tamp_pages, &lru_list, &consumed_count], Some("CacheEvictor::bind_group"), ); @@ -89,6 +98,7 @@ impl CacheEvictor page_count, timestamp_pages, lru_list, + consumed_count, reset_lru_list_bind_group, reset_lru_list_pass, @@ -146,6 +156,11 @@ impl CacheEvictor pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout { - create_multi_buffers_bind_group_layout(device, 2, Some("CacheEvictor::bind_group_layout")) + create_multi_buffers_bind_group_layout(device, 3, Some("CacheEvictor::bind_group_layout")) + } + + pub fn timestamp_pages_buffer(&self) -> &wgpu::Buffer + { + &self.timestamp_pages } } diff --git a/src/voxel_cache/insertion.rs b/src/voxel_cache/insertion.rs index 8e68e44..a1af67e 100644 --- a/src/voxel_cache/insertion.rs +++ b/src/voxel_cache/insertion.rs @@ -1,6 +1,7 @@ use std::num::NonZero; use wgpu::BindGroupLayout; +use wgpu::BufferUsages; use wgpu::ShaderStages; use crate::voxel_cache::layout::CacheLayout; @@ -42,21 +43,21 @@ where { let page_count_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("CacheInsertionData::page_count_buffer"), - usage: wgpu::BufferUsages::STORAGE, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, size: size_of::() as u64, }); let insertion_information = device.create_buffer(&wgpu::BufferDescriptor { label: Some("CacheInsertionData::insertion_information"), - usage: wgpu::BufferUsages::STORAGE, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, size: (size_of::>() * max_page_count) as u64, }); let location_pages = device.create_buffer(&wgpu::BufferDescriptor { label: Some("CacheInsertionData::location_pages"), - usage: wgpu::BufferUsages::STORAGE, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, size: (size_of::() * max_page_count) as u64, }); @@ -71,7 +72,14 @@ where let attributes = layout .attributes .iter() - .map(|attribute| attribute.create_buffer(device, N, max_page_count)) + .map(|attribute| { + attribute.create_buffer( + device, + N * N * N, + max_page_count, + BufferUsages::STORAGE | BufferUsages::COPY_DST, + ) + }) .collect::>(); let bind_group_bindings = attributes @@ -102,10 +110,6 @@ where }, wgpu::BindGroupEntry { binding: 4, - resource: destination_indices.as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: 5, resource: wgpu::BindingResource::BufferArray(&bind_group_bindings), }, ], @@ -178,16 +182,6 @@ where has_dynamic_offset: false, min_binding_size: None, }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 5, - visibility: ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: false }, - has_dynamic_offset: false, - min_binding_size: None, - }, count: Some(NonZero::new(layout.attributes.len() as u32).unwrap()), }, ], @@ -203,4 +197,24 @@ where { self.max_page_count } + + pub fn page_count_buffer(&self) -> &wgpu::Buffer + { + &self.page_count_buffer + } + + pub fn insertion_information_buffer(&self) -> &wgpu::Buffer + { + &self.insertion_information + } + + pub fn location_pages_buffer(&self) -> &wgpu::Buffer + { + &self.location_pages + } + + pub fn attributes_buffers(&self) -> &[wgpu::Buffer] + { + &self.attributes + } } diff --git a/src/voxel_cache/layout.rs b/src/voxel_cache/layout.rs index 9bc18af..491c544 100644 --- a/src/voxel_cache/layout.rs +++ b/src/voxel_cache/layout.rs @@ -32,6 +32,7 @@ impl CacheAttribute device: &wgpu::Device, child_count: usize, page_count: usize, + usage: wgpu::BufferUsages, ) -> wgpu::Buffer { device.create_buffer(&wgpu::BufferDescriptor { @@ -43,8 +44,8 @@ impl CacheAttribute ) .as_str(), ), - size: (self.word_count as usize * page_count * child_count) as u64, - usage: BufferUsages::STORAGE, + size: (self.word_count as usize * page_count * child_count * size_of::()) as u64, + usage, mapped_at_creation: false, }) } @@ -96,7 +97,8 @@ impl CacheLayout // Word counts decl += &format!( - "const ATTRIBUTE_WORD_COUNTS: array = {{", + "const ATTRIBUTE_WORD_COUNTS: array = array(", + self.attributes.len(), self.attributes.len() ); @@ -105,11 +107,12 @@ impl CacheLayout decl += &format!(" {},", attribute.word_count); } - decl += "};"; + decl += ");"; // Copy decl += &format!( - "const ATTRIBUTE_COPY: array = {{", + "const ATTRIBUTE_COPY: array = array(", + self.attributes.len(), self.attributes.len() ); @@ -118,7 +121,7 @@ impl CacheLayout decl += &format!(" {},", attribute.init == CacheAttributeInit::External); } - decl += "};"; + decl += ");"; decl } diff --git a/src/voxel_cache/pipelines.rs b/src/voxel_cache/pipelines.rs index e6104ae..28c9b1e 100644 --- a/src/voxel_cache/pipelines.rs +++ b/src/voxel_cache/pipelines.rs @@ -1,11 +1,14 @@ +use wgpu::BufferUsages; use wgpu::CommandEncoder; use wgpu::ComputePipeline; use wgpu::Device; +use wgpu::util::DeviceExt; use crate::gpu::indirect_buffer::IndirectBuffer1D; use crate::gpu_profiler; use crate::gpu_profiler::ScopeEncoder; use crate::voxel_cache::attributes::CacheAttributes; +use crate::voxel_cache::create_multi_buffers_bg_bg_layout; use crate::voxel_cache::eviction::CacheEvictor; use crate::voxel_cache::insertion::CacheInsertionData; use crate::voxel_cache::layout::CacheLayout; @@ -23,7 +26,7 @@ const PAGE_COUNT: u32 = u32({}); // Cache layout {} ", - $children_count, + $children_count * $children_count * $children_count, $page_count, $cache_layout.wgsl_layout_decl() ) @@ -35,12 +38,13 @@ macro_rules! include_cache_wgsl { ($path:literal, $children_count:ident, $page_count:ident, $cache_layout:ident) => {{ let mut full_shader = String::new(); - full_shader.push_str(include_str!("./shaders/cache_common.wgsl")); + full_shader.push_str(include_str!("./shaders/common.wgsl")); full_shader.push_str(programmatic_common_wgsl!( $children_count, $page_count, $cache_layout )); + full_shader.push_str(include_str!("./shaders/cache_common.wgsl")); full_shader.push_str(include_str!($path)); wgpu::ShaderModuleDescriptor { @@ -50,6 +54,8 @@ macro_rules! include_cache_wgsl { }}; } +pub(super) use include_cache_wgsl; + pub struct WriteRequestsPass where [(); N * N * N]:, @@ -120,10 +126,18 @@ where let indirect_dispatch_buffer = self.indirect_buffer.workgroup_count( device, &mut encoder, - cache_request_handler.requset_count_buffer(), + cache_request_handler.request_count_buffer(), 256, ); + encoder.copy_buffer_to_buffer( + cache_request_handler.request_count_buffer(), + 0, + &target_request_buffer.request_count, + 0, + cache_request_handler.request_count_buffer().size(), + ); + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("WriteRequestsPass::pass"), timestamp_writes: None, @@ -143,7 +157,18 @@ pub struct CacheInsertionPass where [(); N * N * N]:, { - pipeline: ComputePipeline, + /// Copies new pages into cache using LRU order + write_pipeline: ComputePipeline, + + /// u32 buffer containing amount of inserted data of current pass + inserted_count: wgpu::Buffer, + inserted_count_bind_group: wgpu::BindGroup, + + /// Reports the consumed pages to the evictor by incrementing the consumed pages count + consume_pipeline: ComputePipeline, + + /// To dispatch the correct amount of writters depending on the amout of pages to insert + indirect_dispatcher: IndirectBuffer1D, } impl CacheInsertionPass @@ -156,6 +181,19 @@ where // - structure // - request buffer + let inserted_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("CacheInsertionPass::inserted_count"), + contents: bytemuck::bytes_of(&0u32), + usage: BufferUsages::STORAGE, + }); + + let (inserted_count_bind_group_layout, inserted_count_bind_group) = + create_multi_buffers_bg_bg_layout( + device, + &[&inserted_count], + Some("CacheInsertionPass::inserted_count_bind_group"), + ); + let bindings = [ // To write the new attributes Some(&CacheAttributes::::create_bind_group_layout( @@ -169,12 +207,15 @@ where )), // To get recyclable pages, and mark pages dirty Some(&CacheEvictor::create_bind_group_layout(device)), + Some(&inserted_count_bind_group_layout), ]; let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("CacheInsertionPass::pipeline_layout"), bind_group_layouts: &bindings, - immediate_size: 0, + + // To pass the new timestamp + immediate_size: size_of::() as u32, }); let shader_module = device.create_shader_module(include_cache_wgsl!( @@ -184,8 +225,8 @@ where layout )); - let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("CacheInsertionPass::pipeline"), + let write_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("CacheInsertionPass::write_pipeline"), layout: Some(&pipeline_layout), module: &shader_module, entry_point: Some("insertion"), @@ -193,33 +234,65 @@ where cache: None, }); - Self { pipeline } + let consume_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("CacheInsertionPass::consume_pipeline"), + layout: Some(&pipeline_layout), + module: &shader_module, + entry_point: Some("consume"), + compilation_options: Default::default(), + cache: None, + }); + + Self { + write_pipeline, + consume_pipeline, + inserted_count, + inserted_count_bind_group, + indirect_dispatcher: IndirectBuffer1D::new(device), + } } + #[allow(clippy::too_many_arguments)] pub fn encode( &self, + device: &wgpu::Device, encoder: &mut ScopeEncoder, cache_attributes: &CacheAttributes, cache_structure: &CacheStructure, insertion_data: &CacheInsertionData, cache_evictor: &CacheEvictor, + timestamp: u32, ) { gpu_profiler::begin_scope!(encoder, "PageInsertion"); + let indirect_write_dispatch = self.indirect_dispatcher.workgroup_count( + device, + &mut encoder, + insertion_data.page_count_buffer(), + 256, + ); + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("CacheInsertionPass::pass"), timestamp_writes: None, }); - pass.set_pipeline(&self.pipeline); pass.set_bind_group(0, cache_attributes.bind_group(), &[]); pass.set_bind_group(1, cache_structure.bind_group(), &[]); pass.set_bind_group(2, insertion_data.bind_group(), &[]); pass.set_bind_group(3, cache_evictor.bind_group(), &[]); + pass.set_bind_group(4, &self.inserted_count_bind_group, &[]); - let workgroups = insertion_data.page_count().div_ceil(256) as u32; - pass.dispatch_workgroups(workgroups, 1, 1); + // Write pass + pass.set_pipeline(&self.write_pipeline); + pass.set_immediates(0, bytemuck::bytes_of(×tamp)); + pass.dispatch_workgroups_indirect(indirect_write_dispatch, 0); + + // Consume pass + pass.set_pipeline(&self.consume_pipeline); + pass.set_immediates(0, bytemuck::bytes_of(&0u32)); // Unused + pass.dispatch_workgroups(1, 1, 1); } } @@ -325,7 +398,9 @@ where // To find where the requests came from Some(&CacheRequestBuffer::create_bind_group_layout(device)), // To find where the request's response went - Some(&CacheEvictor::create_bind_group_layout(device)), + Some(&CacheInsertionData::::create_bind_group_layout( + device, layout, + )), ]; let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { @@ -362,7 +437,7 @@ where device: &Device, cache_structure: &CacheStructure, request_buffer: &CacheRequestBuffer, - cache_evictor: &CacheEvictor, + cache_insertion_data: &CacheInsertionData, ) { gpu_profiler::begin_scope!(encoder, "WritePointers"); @@ -370,7 +445,7 @@ where let indirect_buffer = self.indirect_buffer.workgroup_count( device, &mut encoder, - &request_buffer.request_count, + cache_insertion_data.page_count_buffer(), 256, ); @@ -381,7 +456,8 @@ where pass.set_pipeline(&self.pipeline); pass.set_bind_group(0, cache_structure.bind_group(), &[]); - pass.set_bind_group(1, cache_evictor.bind_group(), &[]); + pass.set_bind_group(1, request_buffer.bind_group(), &[]); + pass.set_bind_group(2, cache_insertion_data.bind_group(), &[]); pass.dispatch_workgroups_indirect(indirect_buffer, 0); } diff --git a/src/voxel_cache/requests.rs b/src/voxel_cache/requests.rs index d03a4eb..9b62a92 100644 --- a/src/voxel_cache/requests.rs +++ b/src/voxel_cache/requests.rs @@ -1,3 +1,6 @@ +use std::sync::Arc; +use std::sync::Mutex; + use wgpu::BindGroup; use wgpu::BindGroupLayout; use wgpu::CommandEncoder; @@ -78,13 +81,15 @@ impl CacheRequestHandler let request_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("CacheRequestHandler::request_count"), - usage: wgpu::BufferUsages::STORAGE, + usage: wgpu::BufferUsages::STORAGE + | wgpu::BufferUsages::COPY_DST + | wgpu::BufferUsages::COPY_SRC, contents: bytemuck::bytes_of(&0u32), }); let (reset_pass_bg_layout, reset_pass_bind_group) = create_multi_buffers_bg_bg_layout( device, - [request_counts_pages], + &[&request_counts_pages], Some("CacheRequestHandler::reset_pass_bind_group"), ); @@ -116,11 +121,11 @@ impl CacheRequestHandler request_counts_pages, sorted_requests, request_count, - compactor: NonZeroBufferCompactor::new(device, page_count), + compactor: NonZeroBufferCompactor::new(device, page_count * N * N * N), reset_pass_bind_group, reset_pass, - reset_pass_dispatch: (page_count as u32).div_ceil(256), + reset_pass_dispatch: ((page_count * N * N * N) as u32).div_ceil(256), bind_group_layout, bind_group, @@ -142,13 +147,16 @@ impl CacheRequestHandler gpu_profiler::begin_scope!(encoder, "RequestHandler::sort_requests"); // First perform a fast compaction sort - self.compactor.compact_buffer( - device, - &mut encoder, - &self.request_counts_pages, - &self.sorted_requests, - Some(&ressources.scratch_buffer), - ); + { + gpu_profiler::begin_scope!(encoder, "compaction"); + self.compactor.compact_buffer( + device, + &mut encoder, + &self.request_counts_pages, + &self.sorted_requests, + Some(&ressources.scratch_buffer), + ); + } self.compactor .copy_count_to_buffer(&mut encoder, &self.request_count); @@ -162,15 +170,18 @@ impl CacheRequestHandler // We use the amount of non zero request as the indirect count so that we can sort only the // compacted, non-null requests - ressources.radix_sorter.sort( - device, - &ressources.scratch_buffer, - &self.sorted_requests, - Some(&self.request_count), - None, - &mut encoder, - radix_sort::RadixSortDirection::Descending, - ); + { + gpu_profiler::begin_scope!(encoder, "radix"); + ressources.radix_sorter.sort( + device, + &ressources.scratch_buffer, + &self.sorted_requests, + Some(&self.request_count), + None, + &mut encoder, + radix_sort::RadixSortDirection::Descending, + ); + } } pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout @@ -187,18 +198,23 @@ impl CacheRequestHandler &self.bind_group } - pub fn requset_count_buffer(&self) -> &wgpu::Buffer + pub fn request_count_buffer(&self) -> &wgpu::Buffer { &self.request_count } + pub fn request_pages_buffer(&self) -> &wgpu::Buffer + { + &self.request_counts_pages + } + /// Resets the RequestHandlers request buffer for a next cache usage. pub fn reset(&self, encoder: &mut ScopeEncoder) { let mut compute_pass = encoder.begin_profiled_compute_pass("CacheRequestHandler::reset"); - compute_pass.set_bind_group(0, Some(&self.reset_pass_bind_group), &[]); compute_pass.set_pipeline(&self.reset_pass); + compute_pass.set_bind_group(0, Some(&self.reset_pass_bind_group), &[]); compute_pass.dispatch_workgroups(self.reset_pass_dispatch, 1, 1); } } @@ -210,20 +226,22 @@ impl CacheRequestBuffer { let request_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("CacheRequestBuffer::request_count"), - usage: wgpu::BufferUsages::STORAGE, + usage: wgpu::BufferUsages::STORAGE + | wgpu::BufferUsages::COPY_SRC + | wgpu::BufferUsages::COPY_DST, contents: bytemuck::bytes_of(&0u32), }); let request_informations = device.create_buffer(&wgpu::BufferDescriptor { label: Some("CacheRequestBuffer::request_informations"), - usage: wgpu::BufferUsages::STORAGE, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, size: (size_of::() * max_requests) as u64, mapped_at_creation: false, }); let request_meta = device.create_buffer(&wgpu::BufferDescriptor { label: Some("CacheRequestBuffer::request_meta"), - usage: wgpu::BufferUsages::STORAGE, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, size: (size_of::() * max_requests) as u64, mapped_at_creation: false, }); @@ -260,4 +278,89 @@ impl CacheRequestBuffer { &self.bind_group } + + pub fn host_download_requests( + &self, + device: &Device, + queue: &wgpu::Queue, + callback: F, + ) + { + // Once the two required buffer have been mapped, the requestMapState will automatically + // fire the callback + let request_map_state = Arc::new(Mutex::new(RequestMapState::new(callback))); + + let request_map_state_1 = request_map_state.clone(); + wgpu::util::DownloadBuffer::read_buffer( + device, + queue, + &self.request_count.slice(..), + move |buffer| { + let mapped_buffer = buffer.expect("Could not map request buffer (count)."); + let request_count: u32 = bytemuck::pod_read_unaligned(&mapped_buffer); + + request_map_state_1 + .lock() + .unwrap() + .set_request_count(request_count as usize); + }, + ); + + let request_map_state_2 = request_map_state.clone(); + wgpu::util::DownloadBuffer::read_buffer( + device, + queue, + &self.request_informations.slice(..), + move |buffer| { + let mapped_buffer = buffer.expect("Could not map request buffer (informations)."); + let request_infos: Vec = + bytemuck::pod_collect_to_vec(&mapped_buffer); + + request_map_state_2 + .lock() + .unwrap() + .set_request_infos(request_infos); + }, + ); + } +} + +struct RequestMapState () + Send + Sync + 'static> +{ + request_count: Option, + request_infos: Option>, + callback: F, +} + +impl () + Send + Sync + 'static> RequestMapState +{ + pub fn new(callback: F) -> Self + { + Self { + request_count: None, + request_infos: None, + callback, + } + } + + fn try_callback(&mut self) + { + if let (Some(request_count), Some(request_infos)) = + (self.request_count, &self.request_infos) + { + (self.callback)(&request_infos[0..request_count]) + } + } + + pub fn set_request_count(&mut self, request_count: usize) + { + self.request_count = Some(request_count); + self.try_callback(); + } + + pub fn set_request_infos(&mut self, request_infos: Vec) + { + self.request_infos = Some(request_infos); + self.try_callback(); + } } diff --git a/src/voxel_cache/schema.rs b/src/voxel_cache/schema.rs index a414f4d..d150885 100644 --- a/src/voxel_cache/schema.rs +++ b/src/voxel_cache/schema.rs @@ -86,7 +86,7 @@ impl From for CachePointer /// Pages encoding the structure of the trees in the cache. /// Occupancy mask is a mask containing a bit per children, based on whether it can be skipped /// during raytracing. This can help faster tracing, and coalesce skips. -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, Zeroable)] #[repr(C)] pub struct StructurePage where @@ -96,6 +96,9 @@ where pub pointers: [CachePointer; N * N * N], } +// SAFETY: u64, then packed u32s ([`CachePointer`]s), so no padding, all bit patterns are allowed +unsafe impl Pod for StructurePage where [(); N * N * N]: {} + /// Data stored alongside cache structure so that application can locate a /// particular request #[derive(Debug, Clone, Copy, Zeroable, Pod)] @@ -198,12 +201,15 @@ impl BitOr for ChildInformation } /// Information given for an page insertion operation -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, Zeroable)] #[repr(C)] pub struct InsertionInformation where [(); N * N * N]:, { /// Information to setup structure pointers - pub children: ChildInformation, + pub children: [ChildInformation; N * N * N], } + +// SAFETY: Packed array of u32, no padding, all bit patterns allowed +unsafe impl Pod for InsertionInformation where [(); N * N * N]: {} diff --git a/src/voxel_cache/shaders/cache_common.wgsl b/src/voxel_cache/shaders/cache_common.wgsl index d3e0d38..ee5de94 100644 --- a/src/voxel_cache/shaders/cache_common.wgsl +++ b/src/voxel_cache/shaders/cache_common.wgsl @@ -1,11 +1,4 @@ -// Common helper functions and structures -enable wgpu_binding_array; - -struct CacheIndex -{ - page_index: u32, - child_index: u32, -} +// For things that depend upon the cache layout/children count struct PointerPage { @@ -14,35 +7,6 @@ struct PointerPage pointers: array, } -struct LocationPage -{ - structure_id: u32, - node_id: u32, -} - -struct DepthPage -{ - depth: u32 -} - -struct RequestInformation -{ - structure_id: u32, - node_id: u32, - children_index: u32 -} - -struct RequestMeta -{ - page_index: u32, - children_index: u32 -} - -struct AttributeArray -{ - values: array -} - struct InsertionInformation { /// [`ChildInformation`] in schema.rs @@ -57,41 +21,3 @@ fn pointer_index_to_cache_index(request_index: u32) -> CacheIndex cache_index.children_index = request_index % CHILDREN_COUNT; return cache_index; } - -fn child_information_occupied(info: u32) -> bool -{ - return ((info >> 30) & 1) != 0; -} - -fn child_information_subdivided(info: u32) -> bool -{ - return ((info >> 31) & 1) != 0; -} - -// Makes an empty child pointer, which can be subdivisible or not -// but not available -fn child_pointer_empty(subdivisible: bool) -> bool -{ - return select(subdivisible, 1, 0) << 31; -} - -fn child_pointer_subdivided(pointer: u32) -> bool -{ - return ((pointer >> 31) & 1) != 0; -} - -fn child_pointer_available(pointer: u32) -> bool -{ - // both bits set ? - return pointer >> 30 == u32(3); -} - -fn child_pointer_pointer(pointer: u32) -> bool -{ - return pointer & 0x3FFFFFFF; -} - -fn child_pointer_make_available(pointer: u32) -> u32 -{ - return pointer | (3 << 30); -} diff --git a/src/voxel_cache/shaders/common.wgsl b/src/voxel_cache/shaders/common.wgsl new file mode 100644 index 0000000..a6d48ca --- /dev/null +++ b/src/voxel_cache/shaders/common.wgsl @@ -0,0 +1,74 @@ +enable wgpu_binding_array; + +struct CacheIndex +{ + page_index: u32, + children_index: u32, +} +struct RequestInformation +{ + structure_id: u32, + node_id: u32, + children_index: u32 +} + +struct RequestMeta +{ + page_index: u32, + children_index: u32 +} + +struct AttributeArray +{ + values: array +} + +struct LocationPage +{ + structure_id: u32, + node_id: u32, +} + +struct DepthPage +{ + depth: u32 +} + + +fn child_information_occupied(info: u32) -> bool +{ + return ((info >> 30) & 1) != 0; +} + +fn child_information_subdivided(info: u32) -> bool +{ + return ((info >> 31) & 1) != 0; +} + +// Makes an empty child pointer, which can be subdivisible or not +// but not available +fn child_pointer_empty(subdivisible: bool) -> u32 +{ + return select(u32(0), u32(1), subdivisible) << 31; +} + +fn child_pointer_subdivided(pointer: u32) -> bool +{ + return ((pointer >> 31) & 1) != 0; +} + +fn child_pointer_available(pointer: u32) -> bool +{ + // both bits set ? + return pointer >> 30 == u32(3); +} + +fn child_pointer_pointer(pointer: u32) -> u32 +{ + return pointer & u32(0x3FFFFFFF); +} + +fn child_pointer_make_available(pointer: u32) -> u32 +{ + return pointer | 0xC0000000; +} diff --git a/src/voxel_cache/shaders/eviction.wgsl b/src/voxel_cache/shaders/eviction.wgsl index a24d726..e6eeed7 100644 --- a/src/voxel_cache/shaders/eviction.wgsl +++ b/src/voxel_cache/shaders/eviction.wgsl @@ -1,17 +1,19 @@ -@group(0) @binding(0) lru_list: array; +@group(0) @binding(0) var lru_list: array; +@group(0) @binding(1) var consumed_count: u32; /// Resets the lru list @compute -@workgroups(256, 1, 1) -fn reset_lru_list(@builting(global_invocation_id) global_invocation_id: vec3) +@workgroup_size(256, 1, 1) +fn reset_lru_list(@builtin(global_invocation_id) global_invocation_id: vec3) { let index = global_invocation_id.x; - if(index >= array_length(&request_count_pages)) + if(index >= arrayLength(&lru_list)) { return; } // Indicies must be reset to id, so that the sort operation can use them as values, // and the timestamps as keys - request_count_pages = index; + lru_list[index] = index; + consumed_count = 0; } diff --git a/src/voxel_cache/shaders/fixed_table/insertion.wgsl b/src/voxel_cache/shaders/fixed_table/insertion.wgsl new file mode 100644 index 0000000..09a9a8a --- /dev/null +++ b/src/voxel_cache/shaders/fixed_table/insertion.wgsl @@ -0,0 +1,32 @@ +// Group 0: Table pointers +@group(0) @binding(0) var fixed_table_pointers: array; // Request count + +// Group 1: Cache insertion data +@group(1) @binding(0) var insertion_data_page_count_buffer: u32; +@group(1) @binding(1) var insertion_data_information: array; // UNUSED +@group(1) @binding(2) var insertion_data_location_pages: array; +@group(1) @binding(3) var insertion_data_destination_indices: array; +@group(1) @binding(4) var insertion_data_attributes: binding_array; + +/// Group 2: Request buffer +@group(2) @binding(0) var request_buffer_count: u32; // Request count +@group(2) @binding(1) var request_buffer_informations: array; +@group(2) @binding(2) var request_buffer_meta: array; + +@compute +@workgroup_size(256, 1, 1) +fn insertion(@builtin(global_invocation_id) gid: vec3) +{ + let index = gid.x; + if(index >= insertion_data_page_count_buffer) + { + return; + } + + let destination = insertion_data_destination_indices[index]; + if(destination != 0xFFFFFFFF) + { + let request_location = request_buffer_informations[index].structure_id; + fixed_table_pointers[request_location] = child_pointer_make_available(insertion_data_destination_indices[index]); + } +} diff --git a/src/voxel_cache/shaders/fixed_table/invalidation.wgsl b/src/voxel_cache/shaders/fixed_table/invalidation.wgsl new file mode 100644 index 0000000..59a3346 --- /dev/null +++ b/src/voxel_cache/shaders/fixed_table/invalidation.wgsl @@ -0,0 +1,42 @@ +/// Group 0: Table pointers +@group(0) @binding(0) var fixed_table_pointers: array; // Request count + +// Group 1: Cache evictor +@group(1) @binding(0) var cache_evictor_timestamps: array; +@group(1) @binding(1) var cache_evictor_lru_pages: array; +@group(1) @binding(2) var cache_evictor_consumed_count: u32; + +var new_timestamp: u32; + +@compute +@workgroup_size(256, 1, 1) +fn invalidation(@builtin(global_invocation_id) gid: vec3) +{ + let index = gid.x; + let table_length = arrayLength(&fixed_table_pointers); + if(index >= table_length) + { + return; + } + + let pointer = fixed_table_pointers[index]; + if(pointer_invalid(pointer)) + { + // Invalidate + fixed_table_pointers[index] = child_pointer_empty(child_pointer_subdivided(pointer)); + } +} + +fn pointer_invalid(pointer: u32) -> bool +{ + if(child_pointer_available(pointer)) + { + let pointer = child_pointer_pointer(pointer); + let pointed_timestamp = cache_evictor_timestamps[pointer]; + + // Is dirty marker ? + return pointed_timestamp == new_timestamp; + } + + return false; +} diff --git a/src/voxel_cache/shaders/fixed_table/write_requests.wgsl b/src/voxel_cache/shaders/fixed_table/write_requests.wgsl new file mode 100644 index 0000000..15fed1f --- /dev/null +++ b/src/voxel_cache/shaders/fixed_table/write_requests.wgsl @@ -0,0 +1,32 @@ +/// Group 0: Cache request handler +@group(0) @binding(0) var request_handler_count: u32; // Request count +@group(0) @binding(1) var request_handler_requests: array; + +/// Group 1: Request buffer +@group(1) @binding(0) var request_buffer_count: u32; // Request count +@group(1) @binding(1) var request_buffer_informations: array; +@group(1) @binding(2) var request_buffer_meta: array; + +@compute +@workgroup_size(256, 1, 1) +fn write_requests(@builtin(global_invocation_id) gid: vec3) +{ + let index = gid.x; + request_buffer_count = request_handler_count; + if(index >= request_handler_count) + { + return; + } + + var request_info: RequestInformation; + request_info.structure_id = request_handler_requests[index]; + request_info.node_id = 0; + request_info.children_index = 0; + + var request_meta: RequestMeta; + request_meta.page_index = 0; + request_meta.children_index = 0; + + request_buffer_informations[index] = request_info; + request_buffer_meta[index] = request_meta; +} diff --git a/src/voxel_cache/shaders/insertion.wgsl b/src/voxel_cache/shaders/insertion.wgsl index dec5d0c..a94588e 100644 --- a/src/voxel_cache/shaders/insertion.wgsl +++ b/src/voxel_cache/shaders/insertion.wgsl @@ -1,67 +1,113 @@ // Group 0: cache_attributes -@group(0) @binding(0) cache_attributes: binding_array; +@group(0) @binding(0) var cache_attributes: binding_array; /// Group 1: Cache structure -@group(1) @binding(0) structure_pointer_pages: array; -@group(1) @binding(1) structure_location_pages: array; -@group(1) @binding(2) structure_depth_pages: array; +@group(1) @binding(0) var structure_pointer_pages: array; +@group(1) @binding(1) var structure_location_pages: array; +@group(1) @binding(2) var structure_depth_pages: array; -// Group 2: Cahce insertion data -@group(2) @binding(0) insertion_data_page_count_buffer: u32; -@group(2) @binding(1) insertion_data_information: array; -@group(2) @binding(2) insertion_data_location_pages: array; -@group(2) @binding(3) insertion_data_destination_indices: array; -@group(2) @binding(4) insertion_data_attributes: binding_array; +// Group 2: Cache insertion data +@group(2) @binding(0) var insertion_data_page_count_buffer: u32; +@group(2) @binding(1) var insertion_data_information: array; +@group(2) @binding(2) var insertion_data_location_pages: array; +@group(2) @binding(3) var insertion_data_destination_indices: array; +@group(2) @binding(4) var insertion_data_attributes: binding_array; // Group 3: Cache evictor -@group(3) @binding(0) cache_evictor_timestamps: array; -@group(3) @binding(1) cache_evictor_lru_pages: array; +@group(3) @binding(0) var cache_evictor_timestamps: array; +@group(3) @binding(1) var cache_evictor_lru_pages: array; +@group(3) @binding(2) var cache_evictor_consumed_count: u32; + +// Group 4: Inserted count +@group(4) @binding(0) var pass_inserted_count: atomic; + +var new_timestamp: u32; + +// Computes amount of available LRU pages +fn available_amount() -> u32 +{ + let lru_remaining = arrayLength(&cache_evictor_timestamps) - cache_evictor_consumed_count; + let available_amount = min(lru_remaining, insertion_data_page_count_buffer); + + return available_amount; +} + +@compute +@workgroup_size(1, 1, 1) +fn consume(@builtin(global_invocation_id) gid: vec3) +{ + // Report consumed amount of LRU pages to cache evictor + // So that subsequent insertions can can continue to use new pages + cache_evictor_consumed_count += atomicLoad(&pass_inserted_count); + atomicStore(&pass_inserted_count, 0); +} @compute @workgroup_size(256, 1, 1) fn insertion(@builtin(global_invocation_id) gid: vec3) { let index = gid.x; - let insertion_count = min(array_length(&insertion_data_information), insertion_data_page_count_buffer); - if(index >= insertion_count) { return; } + //let insertion_count = min(array_length(&insertion_data_information), insertion_data_page_count_buffer); + let insertion_count = available_amount(); + + if(index >= insertion_data_page_count_buffer) + { + return; + } + + if(index >= insertion_count) + { + // Report that page was not written + insertion_data_destination_indices[index] = 0xFFFFFFFF; + return; + } // Get a page to evict - let page_index = cache_evictor_lru_pages[index]; + let page_index = cache_evictor_lru_pages[index + cache_evictor_consumed_count]; + let page_timestamp = cache_evictor_timestamps[page_index]; + + if(page_timestamp >= new_timestamp - 1) + { + // Do not insert page + insertion_data_destination_indices[index] = 0xFFFFFFFF; + return; + } + + atomicAdd(&pass_inserted_count, 1); + insertion_data_destination_indices[index] = page_index; // Copy new location structure_location_pages[page_index] = insertion_data_location_pages[index]; // Copy new pointers let new_pointers = insertion_info_to_pointer_page(insertion_data_information[index]); - structure_location_pointer_pages[page_index] = new_pointers; + structure_pointer_pages[page_index] = new_pointers; + + // Mark page as dirty for invalidation + cache_evictor_timestamps[page_index] = new_timestamp; // Copy new depth // TODO: Copy new depth // Copy attributes - for(var attribute = 0; attribute < ATTRIBUTE_COUNT; attribute ++) + for(var attribute_index = u32(0); attribute_index < ATTRIBUTE_COUNT; attribute_index ++) { - if(!ATTRIBUTE_COPY[attribute]) + if(!ATTRIBUTE_COPY[attribute_index]) { continue; } - var page_stride = CHILDREN_COUNT * ATTRIBUTE_WORD_COUNT[attribute]; + var page_stride = CHILDREN_COUNT * ATTRIBUTE_WORD_COUNTS[attribute_index]; var dest_offset = page_stride * page_index; var src_offset = page_stride * index; // Copy all words of the attribute page - for(var word = 0; word < page_stride; word ++) + for(var word = u32(0); word < page_stride; word ++) { - cache_attributes[dest_offset + word] = insertion_data_attributes[src_offset + word]; + cache_attributes[attribute_index].values[dest_offset + word] = insertion_data_attributes[attribute_index].values[src_offset + word]; } } - - insertion_data_destination_indices[index] = page_index; - - // Mark page as dirty for invalidation - cache_evictor_timestamps[page_index] = 0xFFFFFFFF; } fn insertion_info_to_pointer_page(info: InsertionInformation) -> PointerPage @@ -70,18 +116,18 @@ fn insertion_info_to_pointer_page(info: InsertionInformation) -> PointerPage var occupancy_low = u32(0); var occupancy_high = u32(0); - for(var i = 0; i < CHILDREN_COUNT; i++) + for(var i = u32(0); i < CHILDREN_COUNT; i++) { - let insert_info = info.chilren[i]; + let insert_info = info.children[i]; // Pointer - page.pointers[i] = child_information_subdivided(insert_info); + page.pointers[i] = child_pointer_empty(child_information_subdivided(insert_info)); // Occupancy - var bit = select(child_information_occupied(insert_info), 1, 0); + var bit = select(u32(0), u32(1), child_information_occupied(insert_info)); // Dispatch set bit on low or high word - bit <<= i % u32(32); + bit = bit << (i % u32(32)); if(i < 32) { occupancy_low |= bit; diff --git a/src/voxel_cache/shaders/invalidation.wgsl b/src/voxel_cache/shaders/invalidation.wgsl index b3de7f6..c6df0ef 100644 --- a/src/voxel_cache/shaders/invalidation.wgsl +++ b/src/voxel_cache/shaders/invalidation.wgsl @@ -1,11 +1,12 @@ /// Group 0: Cache structure -@group(0) @binding(0) structure_pointer_pages: array; -@group(0) @binding(1) structure_location_pages: array; -@group(0) @binding(2) structure_depth_pages: array; +@group(0) @binding(0) var structure_pointer_pages: array; +@group(0) @binding(1) var structure_location_pages: array; +@group(0) @binding(2) var structure_depth_pages: array; // Group 1: Cache evictor -@group(1) @binding(0) cache_evictor_timestamps: array; -@group(1) @binding(1) cache_evictor_lru_pages: array; +@group(1) @binding(0) var cache_evictor_timestamps: array; +@group(1) @binding(1) var cache_evictor_lru_pages: array; +@group(1) @binding(2) var cache_evictor_consumed_count: u32; var new_timestamp: u32; @@ -14,9 +15,9 @@ var new_timestamp: u32; fn invalidation(@builtin(global_invocation_id) gid: vec3) { let index = gid.x; - if(index >= array_length(structure_pointer_pages)) { return; } + if(index >= arrayLength(&structure_pointer_pages)) { return; } - for(var i = 0; i < CHILDREN_COUNT; i++) + for(var i = u32(0); i < CHILDREN_COUNT; i++) { if(pointer_invalid(structure_pointer_pages[index].pointers[i])) { @@ -33,7 +34,7 @@ fn pointer_invalid(pointer: u32) -> bool let pointed_timestamp = cache_evictor_timestamps[pointer]; // Is dirty marker ? - return pointed_timestamp == 0xFFFFFFFF; + return pointed_timestamp == new_timestamp; } return false; @@ -44,9 +45,6 @@ fn pointer_invalidate(page_index: u32, child_index: u32) let pointer = structure_pointer_pages[page_index].pointers[child_index]; let pointed_page = child_pointer_pointer(pointer); - // Remove dirty mark - cache_evictor_timestamps[pointed_page] = new_timestamp; - let new_pointer = child_pointer_empty(child_pointer_subdivided(pointer)); structure_pointer_pages[page_index].pointers[child_index] = new_pointer; } diff --git a/src/voxel_cache/shaders/requests.wgsl b/src/voxel_cache/shaders/requests.wgsl index 075fd4e..531881d 100644 --- a/src/voxel_cache/shaders/requests.wgsl +++ b/src/voxel_cache/shaders/requests.wgsl @@ -1,15 +1,15 @@ -@group(0) @binding(0) request_count_pages: array; +@group(0) @binding(0) var request_count_pages: array; /// Resets the requests @compute -@workgroups(256, 1, 1) -fn reset_requests(@builting(global_invocation_id) global_invocation_id: vec3) +@workgroup_size(256, 1, 1) +fn reset_requests(@builtin(global_invocation_id) global_invocation_id: vec3) { let index = global_invocation_id.x; - if(index >= array_length(&request_count_pages)) + if(index >= arrayLength(&request_count_pages)) { return; } - request_count_pages = 0; + request_count_pages[index] = 0; } diff --git a/src/voxel_cache/shaders/write_pointers.wgsl b/src/voxel_cache/shaders/write_pointers.wgsl index dff54e5..5bcba5d 100644 --- a/src/voxel_cache/shaders/write_pointers.wgsl +++ b/src/voxel_cache/shaders/write_pointers.wgsl @@ -1,29 +1,35 @@ /// Group 0: Cache structure -@group(0) @binding(0) structure_pointer_pages: array; -@group(0) @binding(1) structure_location_pages: array; -@group(0) @binding(2) structure_depth_pages: array; +@group(0) @binding(0) var structure_pointer_pages: array; +@group(0) @binding(1) var structure_location_pages: array; +@group(0) @binding(2) var structure_depth_pages: array; /// Group 1: Request buffer -@group(1) @binding(0) request_buffer_count: u32; // Request count -@group(1) @binding(1) request_buffer_informations: array; -@group(1) @binding(2) request_buffer_meta: array; +@group(1) @binding(0) var request_buffer_count: u32; // Request count +@group(1) @binding(1) var request_buffer_informations: array; +@group(1) @binding(2) var request_buffer_meta: array; -// Group 2: Cache evictor -@group(2) @binding(0) cache_evictor_timestamps: array; -@group(2) @binding(1) cache_evictor_lru_pages: array; +// Group 2: Cache insertion data +@group(2) @binding(0) var insertion_data_page_count_buffer: u32; +@group(2) @binding(1) var insertion_data_information: array; +@group(2) @binding(2) var insertion_data_location_pages: array; +@group(2) @binding(3) var insertion_data_destination_indices: array; +@group(2) @binding(4) var insertion_data_attributes: binding_array; @compute @workgroup_size(256, 1, 1) fn write_pointers(@builtin(global_invocation_id) gid: vec3) { let index = gid.x; - if(index >= request_buffer_count) { return; } + if(index >= request_buffer_count || index >= insertion_data_page_count_buffer) { return; } // The write pages pass establishes a one-to-one corresepondancy // between requests and recycled pages - let meta = request_buffer_meta[index]; - let page_index = cache_evictor_lru_pages[index]; + let meta_inf = request_buffer_meta[index]; + let page_index = insertion_data_destination_indices[index]; - structure_pointer_pages[meta.page_index].pointers[meta.child_index] - = child_pointer_make_available(page_index); + if(page_index != 0xFFFFFFFF) + { + structure_pointer_pages[meta_inf.page_index].pointers[meta_inf.children_index] + = child_pointer_make_available(page_index); + } } diff --git a/src/voxel_cache/shaders/write_requests.wgsl b/src/voxel_cache/shaders/write_requests.wgsl index 46957d0..f771a26 100644 --- a/src/voxel_cache/shaders/write_requests.wgsl +++ b/src/voxel_cache/shaders/write_requests.wgsl @@ -1,18 +1,18 @@ /// Pipeline to write the requests out in to the request buffer /// Group 0: Cache structure -@group(0) @binding(0) structure_pointer_pages: array; -@group(0) @binding(1) structure_location_pages: array; -@group(0) @binding(2) structure_depth_pages: array; +@group(0) @binding(0) var structure_pointer_pages: array; +@group(0) @binding(1) var structure_location_pages: array; +@group(0) @binding(2) var structure_depth_pages: array; /// Group 1: Cache request handler -@group(1) @binding(0) request_handler_count: u32; // Request count -@group(1) @binding(1) request_handler_requests: array; +@group(1) @binding(0) var request_handler_count: u32; // Request count +@group(1) @binding(1) var request_handler_requests: array; /// Group 3: Request buffer -@group(2) @binding(0) request_buffer_count: u32; // Request count -@group(2) @binding(1) request_buffer_informations: array; -@group(2) @binding(2) request_buffer_meta: array; +@group(2) @binding(0) var request_buffer_count: u32; // Request count +@group(2) @binding(1) var request_buffer_informations: array; +@group(2) @binding(2) var request_buffer_meta: array; @compute @workgroup_size(256, 1, 1) @@ -22,7 +22,7 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3) // Max size of request buffer and request count let max_requests = - max(array_length(&request_buffer_informations), request_handler_count); + min(arrayLength(&request_buffer_informations), request_handler_count); if(index >= max_requests) { return; } @@ -42,7 +42,7 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3) request_meta.children_index = request_location.children_index; // Write them to request buffer - request_buffer_information[index] = request_information; + request_buffer_informations[index] = request_information; request_buffer_meta[index] = request_meta; // Write request count diff --git a/src/voxel_cache/structure.rs b/src/voxel_cache/structure.rs index 874cb9c..c097c16 100644 --- a/src/voxel_cache/structure.rs +++ b/src/voxel_cache/structure.rs @@ -86,4 +86,9 @@ where { &self.bind_group } + + pub fn pointer_pages(&self) -> &Buffer + { + &self.pointer_pages + } } diff --git a/src/voxel_cache/tables.rs b/src/voxel_cache/tables.rs new file mode 100644 index 0000000..69b13cb --- /dev/null +++ b/src/voxel_cache/tables.rs @@ -0,0 +1,294 @@ +use wgpu::util::DeviceExt; + +use crate::gpu::indirect_buffer::IndirectBuffer1D; +use crate::gpu_profiler::ScopeEncoder; +use crate::voxel_cache::CacheInvalidable; +use crate::voxel_cache::CacheRessources; +use crate::voxel_cache::create_multi_buffers_bg_bg_layout; +use crate::voxel_cache::eviction::CacheEvictor; +use crate::voxel_cache::insertion::CacheInsertionData; +use crate::voxel_cache::layout::CacheLayout; +use crate::voxel_cache::requests::CacheRequestBuffer; +use crate::voxel_cache::requests::CacheRequestHandler; +use crate::voxel_cache::schema::CachePointer; + +use super::pipelines::include_cache_wgsl; + +/// Cache keeps pages from different structures within itself. +/// Pages are pieces of structure pointing to each other. But, in order to start tracing inside the +/// voxels, we must enter the cache from somewhere +/// +/// The structure table is a structure that keeps information about where to find the root node +/// inside the cache, or if it is not preset, emit requests. +/// + +macro_rules! include_table_wgsl { + ($path:literal) => {{ + let mut full_shader = String::new(); + + full_shader.push_str(include_str!("./shaders/common.wgsl")); + full_shader.push_str(include_str!($path)); + + wgpu::ShaderModuleDescriptor { + label: Some($path), + source: wgpu::ShaderSource::Wgsl(full_shader.into()), + } + }}; +} + +/// A structure table with a fixed length +pub struct FixedStructureTable +{ + size: usize, + /// Contains [`CachePointer`]s to locations in the cahce + pointers: wgpu::Buffer, + pointers_bind_group: wgpu::BindGroup, + common_ressources: CacheRessources<1>, + request_handler: CacheRequestHandler<1>, + + // To dispatch write request passes per request count + indirect_buffer: IndirectBuffer1D, + write_requests_pass: wgpu::ComputePipeline, + invalidation_pass: wgpu::ComputePipeline, + insertion_pass: wgpu::ComputePipeline, + + // Raytrace + raytrace_bind_group_layout: wgpu::BindGroupLayout, + raytrace_bind_group: wgpu::BindGroup, +} + +impl FixedStructureTable +{ + pub fn new(device: &wgpu::Device, size: usize, layout: &CacheLayout) -> Self + { + let pointer = CachePointer::new(Some(None)); + let pointers = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("FixedStructureTable::pointers"), + usage: wgpu::BufferUsages::STORAGE, + contents: bytemuck::cast_slice(&vec![pointer; size]), + }); + + let request_handler = CacheRequestHandler::<1>::new(device, size); + + let (pointers_bind_group_layout, pointers_bind_group) = create_multi_buffers_bg_bg_layout( + device, + &[&pointers], + Some("FixedStructureTable::pointers"), + ); + + // Write requests + let write_requests_bindings = [ + Some(&CacheRequestHandler::<1>::create_bind_group_layout(device)), + Some(&CacheRequestBuffer::create_bind_group_layout(device)), + ]; + + let write_requests_pipeline_layout = + device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("FixedStructureTable::pipeline_layout"), + bind_group_layouts: &write_requests_bindings, + immediate_size: 0, + }); + + let write_requests_shader_module = device.create_shader_module(include_table_wgsl!( + "./shaders/fixed_table/write_requests.wgsl" + )); + + let write_requests_pass = + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("FixedStructureTable::write_requests_pass"), + layout: Some(&write_requests_pipeline_layout), + module: &write_requests_shader_module, + entry_point: Some("write_requests"), + compilation_options: Default::default(), + cache: None, + }); + + // Invalidation + let invalidation_bindings = [ + Some(&pointers_bind_group_layout), + Some(&CacheEvictor::create_bind_group_layout(device)), + ]; + + let invalidation_pipeline_layout = + device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("FixedStructureTable::invalidation_pipeline_layout"), + bind_group_layouts: &invalidation_bindings, + immediate_size: size_of::() as u32, + }); + + let invalidation_shader_module = device.create_shader_module(include_table_wgsl!( + "./shaders/fixed_table/invalidation.wgsl" + )); + + let invalidation_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("FixedStructureTable::invalidation_pass"), + layout: Some(&invalidation_pipeline_layout), + module: &invalidation_shader_module, + entry_point: Some("invalidation"), + compilation_options: Default::default(), + cache: None, + }); + + let (raytrace_bind_group_layout, raytrace_bind_group) = create_multi_buffers_bg_bg_layout( + device, + &[&pointers, request_handler.request_pages_buffer()], + Some("FixedStructureTable::raytrace_bind_group"), + ); + + // Insertion + let insertion_bindings = [ + Some(&pointers_bind_group_layout), + Some(&CacheInsertionData::<1>::create_bind_group_layout( + device, layout, + )), + Some(&CacheRequestBuffer::create_bind_group_layout(device)), + ]; + + let insertion_pipeline_layout = + device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("FixedStructureTable::insertion_pipeline_layout"), + bind_group_layouts: &insertion_bindings, + immediate_size: 0, + }); + + let insertion_shader_module = device + .create_shader_module(include_table_wgsl!("./shaders/fixed_table/insertion.wgsl")); + + let insertion_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("FixedStructureTable::insertion_pass"), + layout: Some(&insertion_pipeline_layout), + module: &insertion_shader_module, + entry_point: Some("insertion"), + compilation_options: Default::default(), + cache: None, + }); + + Self { + size, + pointers, + pointers_bind_group, + common_ressources: CacheRessources::new(device, size), + request_handler, + indirect_buffer: IndirectBuffer1D::new(device), + write_requests_pass, + invalidation_pass, + insertion_pass, + + raytrace_bind_group, + raytrace_bind_group_layout, + } + } + + pub fn gather_requests( + &self, + device: &wgpu::Device, + encoder: &mut ScopeEncoder, + request_buffer: &CacheRequestBuffer, + ) + { + self.request_handler + .sort_requests(device, &self.common_ressources, encoder); + + let workgroup_count_buffer = self.indirect_buffer.workgroup_count( + device, + encoder, + self.request_handler.request_count_buffer(), + 256, + ); + + // If there are no requests, there are no dispatched workgroups, so we must carry the 0 + // count over + encoder.copy_buffer_to_buffer( + self.request_handler.request_count_buffer(), + 0, + &request_buffer.request_count, + 0, + self.request_handler.request_count_buffer().size(), + ); + + { + let mut write_requests_pass = + encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("FixedStructureTable::write_requests_pass"), + timestamp_writes: None, + }); + + write_requests_pass.set_bind_group(0, self.request_handler.bind_group(), &[]); + write_requests_pass.set_bind_group(1, request_buffer.bind_group(), &[]); + + write_requests_pass.set_pipeline(&self.write_requests_pass); + write_requests_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0); + } + + self.request_handler.reset(encoder); + } + + /// After requests emited by this table, the user creates a [`CacheInsertionData`] struct that + /// populates the cache. After the cache insertion operation, said [`CacheInsertionData`] + /// contains location of written pages in the cache. + /// This function takes this information and populates the structure so that it points into the + /// cache + pub fn insert( + &self, + device: &wgpu::Device, + encoder: &mut ScopeEncoder, + insertion: &CacheInsertionData, + request: &CacheRequestBuffer, + ) where + [(); N * N * N]:, + { + let workgroup_count_buffer = self.indirect_buffer.workgroup_count( + device, + encoder, + insertion.page_count_buffer(), + 256, + ); + + { + let mut insertion_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("FixedStructureTable::insertion_pass"), + timestamp_writes: None, + }); + + insertion_pass.set_bind_group(0, &self.pointers_bind_group, &[]); + insertion_pass.set_bind_group(1, insertion.bind_group(), &[]); + insertion_pass.set_bind_group(2, request.bind_group(), &[]); + + insertion_pass.set_pipeline(&self.insertion_pass); + insertion_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0); + } + } + + pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout + { + &self.raytrace_bind_group_layout + } + + pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup + { + &self.raytrace_bind_group + } +} + +impl CacheInvalidable for FixedStructureTable +{ + fn invalidate( + &mut self, + encoder: &mut ScopeEncoder, + cache_evictor: &CacheEvictor, + invalid_timestamp: u32, + ) + { + let mut invalidate_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("FixedStructureTable::invalidate_pass"), + timestamp_writes: None, + }); + + invalidate_pass.set_bind_group(0, &self.pointers_bind_group, &[]); + invalidate_pass.set_bind_group(1, cache_evictor.bind_group(), &[]); + + invalidate_pass.set_pipeline(&self.invalidation_pass); + invalidate_pass.set_immediates(0, bytemuck::bytes_of(&invalid_timestamp)); + invalidate_pass.dispatch_workgroups(self.size.div_ceil(256) as u32, 1, 1); + } +}