Adding attribute system to the cache

This commit is contained in:
2026-09-19 15:41:23 +02:00
parent 306b01b44c
commit a332ac08ed
8 changed files with 134 additions and 88 deletions
+12 -5
View File
@@ -62,10 +62,12 @@ use crate::producers::ChunkedProducer;
use crate::producers::SineGenerator;
use crate::producers::TerrainGenerator;
use crate::sparse_tree::NTreeNodeLocator;
use crate::voxel_cache::VoxelAttribute;
use crate::voxel_cache::VoxelCache;
use crate::voxel_cache::data::CacheNodeRequest;
use crate::voxel_cache::data::CacheResponse;
use crate::voxel_cache::data::ColorBytes;
use crate::voxel_cache::data::ColorPoolElement;
use crate::voxel_cache::data::DestinationElement;
use crate::voxel_cache::data::LocationPoolElement;
use crate::voxel_cache::data::StructurePoolElement;
@@ -166,10 +168,13 @@ impl State
| Features::SHADER_I16
| Features::SHADER_F16
| Features::TIMESTAMP_QUERY_INSIDE_ENCODERS
| Features::STORAGE_RESOURCE_BINDING_ARRAY
| Features::BUFFER_BINDING_ARRAY
| Features::SHADER_INT64,
required_limits: wgpu::Limits {
max_immediate_size: 112,
max_storage_buffers_per_shader_stage: 16,
max_binding_array_elements_per_shader_stage: 16,
..Default::default()
},
..Default::default()
@@ -187,8 +192,10 @@ impl State
let egui_renderer = EguiRenderer::new(&device, surface_format, &window);
let mut voxel_cache = VoxelCache::<4>::new(100_000, device.clone(), queue.clone());
let cache_interface = CacheProducerInterface::new(256, &device);
let attributes = vec![VoxelAttribute { word_count: 1 }];
let mut voxel_cache =
VoxelCache::<4>::new(100_000, device.clone(), queue.clone(), attributes.clone());
let cache_interface = CacheProducerInterface::new(1024, &device, attributes.clone());
let terrain_generator = TerrainGenerator::<4>::new(5, "vxls_height.tif", 0.2, "img.jpg");
// let terrain_generator = TerrainGenerator::<4>::new(
@@ -891,14 +898,14 @@ impl State
unsafe { as_raw_bytes(structure_nodes.as_slice()) },
);
cloned_queue.write_buffer(
cloned_cache_interface.color_nodes_buffer(),
&cloned_cache_interface.attributes_buffers()[0],
0,
unsafe { as_raw_bytes(&color_nodes.as_slice()) },
unsafe { as_raw_bytes(color_nodes.as_slice()) },
);
cloned_queue.write_buffer(
cloned_cache_interface.location_nodes_buffer(),
0,
unsafe { as_raw_bytes(&&location_nodes.as_slice()) },
unsafe { as_raw_bytes(location_nodes.as_slice()) },
);
let mut encoder = cloned_device.create_command_encoder(&Default::default());
+10 -24
View File
@@ -73,35 +73,28 @@ where
let child_diagonal_length = (child_size as f32 / 2.) * f32::sqrt(3.);
let alpha;
let subdivided;
if (dist - (global_size as f32 / 2.)).abs() <= child_diagonal_length
{
//children.push(StructurePointer::new(depth <= 3, false, 0));
children.push(StructurePointer(
if depth < (self.chunk_power - 1)
{
0xFFFFFFFF
}
else
{
0
},
));
subdivided = depth < (self.chunk_power - 1);
alpha = if dist > 128. { 0. } else { 1. };
}
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(depth <= 3, false, 0));
children.push(StructurePointer::new(subdivided, subdivided || alpha != 0.));
children_color.push(Color(
gvx as f32 / global_size as f32,
gvy as f32 / global_size as f32,
@@ -530,28 +523,20 @@ where
let gcy = gny + cy * child_size;
let index = cz * N * N + cy * N + cx;
let alpha;
let subdivided;
if gcy > sample_max
{
children[index] = StructurePointer(0);
subdivided = false;
alpha = 0.;
}
else if gcy + child_size < sample_min
{
children[index] = StructurePointer(0);
subdivided = false;
alpha = 1.;
}
else
{
children[index] = StructurePointer(
if depth < (self.chunk_power - 1)
{
0xFFFFFFFF
}
else
{
0
},
);
subdivided = depth < (self.chunk_power - 1);
//children.push(StructurePointer(0));
alpha = if (sample_max + sample_min / 2) > gcy + (child_size / 2)
{
@@ -563,6 +548,7 @@ where
};
}
children[index] = StructurePointer::new(subdivided, subdivided || alpha != 0.);
children_color[index] = Color(color_avg.0, color_avg.1, color_avg.2, alpha);
}
}
+2
View File
@@ -348,6 +348,7 @@ where
}
}
/*
pub fn as_explicit_structure(&self) -> (Color, Vec<ExplicitNTreeNode<N>>)
{
let root = self.map.get(&NTreeNodeLocator::root()).unwrap();
@@ -391,6 +392,7 @@ where
(root.color, explicit_structure)
}
*/
}
fn base_trailing_zeroes<const N: usize>(mut number: usize) -> Option<u32>
+69 -35
View File
@@ -1,3 +1,5 @@
use std::num::NonZero;
use bytemuck::Zeroable;
use wgpu::{BindGroup, BindGroupLayout, Buffer, BufferUsages, CommandEncoder, ComputePipeline, Device, Queue, ShaderStages};
@@ -18,8 +20,8 @@ pub struct VoxelCache<const N: usize>
device: Device,
queue: Queue,
structure_pool: Buffer,
color_pool: Buffer,
location_pool: Buffer,
attributes_pools: Vec<Buffer>,
pub structure_table: StructureTable,
@@ -41,6 +43,12 @@ pub struct VoxelCache<const N: usize>
pub usage_buffer: UsageBuffer,
}
#[derive(Clone, Copy)]
pub struct VoxelAttribute
{
pub word_count: u32
}
#[derive(Zeroable, bytemuck::Pod, Clone, Copy)]
#[repr(C)]
@@ -60,7 +68,7 @@ impl<const N: usize> VoxelCache<N>
where
[(); N * N * N]:,
{
pub fn new(cache_size: usize, device: Device, queue: Queue) -> Self
pub fn new(cache_size: usize, device: Device, queue: Queue, attributes: Vec<VoxelAttribute>) -> Self
{
let structure_pool = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Structure pool"),
@@ -76,17 +84,23 @@ where
mapped_at_creation: false,
});
let color_pool = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Color pool"),
size: (size_of::<ColorPoolElement<N>>() * cache_size) as u64,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
});
// Create attribttues
let attributes_pools =
attributes.iter().enumerate()
.map(|(i, x)|
device.create_buffer(&wgpu::BufferDescriptor
{
label: Some(format!("VoxelCache<{N}>::attributes[{i}]").as_str()),
size: ((x.word_count as usize) * N * N * N * cache_size * size_of::<u32>()) as u64,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
})
).collect::<Vec<_>>();
let request_buffer = RequestBuffer::new(cache_size, device.clone());
let usage_buffer = UsageBuffer::new(cache_size, device.clone());
let request_interface_bind_group_layout = CacheProducerInterface::<N>::request_side_bind_group_layout(&device);
let request_interface_bind_group_layout = CacheProducerInterface::<N>::request_side_bind_group_layout(&device, &attributes);
// Rendering bing group layouts
let voxel_cache_render_bind_group_layout =
@@ -104,7 +118,7 @@ where
},
count: None,
},
// Color pool
// Attributes pool
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::COMPUTE,
@@ -113,7 +127,7 @@ where
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
count: Some(NonZero::new(attributes.len() as u32).unwrap()),
},
// Location pool
wgpu::BindGroupLayoutEntry {
@@ -191,7 +205,7 @@ where
},
count: None,
},
// Color pool
// Attributes pool
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::COMPUTE,
@@ -200,7 +214,7 @@ where
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
count: Some(NonZero::new(attributes.len() as u32).unwrap()),
},
// Location pool
wgpu::BindGroupLayoutEntry {
@@ -260,6 +274,7 @@ where
],
});
let attributes_bindings = attributes_pools.iter().map(|x| x.as_entire_buffer_binding()).collect::<Vec<wgpu::BufferBinding<'_>>>();
let voxel_cache_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("voxel_cache_bind_group"),
layout: &voxel_cache_bind_group_layout,
@@ -269,10 +284,12 @@ where
binding: 0,
resource: structure_pool.as_entire_binding(),
},
// Color pool
// Attributes pool
wgpu::BindGroupEntry {
binding: 1,
resource: color_pool.as_entire_binding(),
resource: wgpu::BindingResource::BufferArray(
attributes_bindings.as_slice()
),
},
// Location pool
wgpu::BindGroupEntry {
@@ -343,8 +360,11 @@ where
});
let children_count = N*N*N;
let attribute_count = attributes.len();
let wgsl_bindings =
format!("
enable wgpu_binding_array;
struct StructurePoolElement
{{
occupancy_low: atomic<u32>,
@@ -369,8 +389,13 @@ where
child: u32
}}
struct AttributeArray
{{
values: array<u32>,
}}
@group(0) @binding(0) var<storage, read_write> structure_pool: array<StructurePoolElement>;
@group(0) @binding(1) var<storage, read_write> color_pool: array<ColorPoolElement>;
@group(0) @binding(1) var<storage, read_write> attributes_pools: binding_array<AttributeArray, {attribute_count}>;
@group(0) @binding(2) var<storage, read_write> location_pool: array<LocationPoolElement>;
@group(0) @binding(3) var<storage, read> sorted_requests: array<u32>;
@group(0) @binding(4) var<storage, read> lru_list: array<u32>;
@@ -495,7 +520,7 @@ where
let caching_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("caching_pipelien_layout"),
label: Some("caching_pipeline_layout"),
bind_group_layouts: &[
Some(&voxel_cache_bind_group_layout),
Some(&structure_table_bind_group_layout),
@@ -504,6 +529,23 @@ where
immediate_size: size_of::<CachingPipelineImmediates>() as u32, // Current frame timestamp
});
// Generate attributes copy loops
let mut copy_loops = String::new();
for (attribute_index, attribute) in attributes.iter().enumerate()
{
let node_size = attribute.word_count * children_count as u32;
let word_count = attribute.word_count;
copy_loops += format!("
for(var i = 0u; i < {children_count}; i++){{
for(var j = 0u; j < {word_count}; j++){{
let offset = i * {word_count} + j;
attributes_pools[{attribute_index}].values[overwritten_element * {node_size} + offset]
= attributes_nodes[{attribute_index}].values[index * {node_size} + offset];
}}
}}
").as_str();
}
let children_count = N * N * N;
let caching_pipeline =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
@@ -513,6 +555,7 @@ where
label: Some("caching_pipeline_shader_module"),
source: wgpu::ShaderSource::Wgsl(
format!("
{wgsl_bindings}
struct DestinationElement
{{
@@ -526,7 +569,6 @@ where
write_pointers: u32
}}
{wgsl_bindings}
var<immediate> parameters: CachingPipelineImmediates;
@@ -548,7 +590,7 @@ where
@group(2) @binding(2) var<storage, read_write> request_count: u32;
@group(2) @binding(3) var<storage, read_write> structure_nodes: array<StructurePoolElement>;
@group(2) @binding(4) var<storage, read_write> color_nodes: array<ColorPoolElement>;
@group(2) @binding(4) var<storage, read_write> attributes_nodes: binding_array<AttributeArray, {attribute_count}>;
@group(2) @binding(5) var<storage, read_write> locations: array<LocationPoolElement>;
@compute
@@ -571,18 +613,18 @@ where
{{
// Phase 1
// Copy into cache page
var occupancy_high = u32(0);
var occupancy_high = u32(0);
var occupancy_low = u32(0);
for(var i = 0; i < {children_count}; i++)
{{
structure_pool[overwritten_element].pointers[i] = select(u32(0), u32(1)<<31, structure_nodes[index].pointers[i] != 0);
structure_pool[overwritten_element].pointers[i] =
select(u32(0), u32(1)<<31, (structure_nodes[index].pointers[i] >> 31) != 0);
let turn_on_bit =
select(
u32(0),
u32(u32(1) << u32(i % ({children_count} / 2))),
((color_nodes[index].colors[i] >> 24) != 0) ||
structure_nodes[index].pointers[i] != 0
((structure_nodes[index].pointers[i] >> 30) & 1) != 0
);
if(i > {children_count} / 2)
@@ -596,7 +638,7 @@ where
atomicStore(&structure_pool[overwritten_element].occupancy_low, occupancy_low);
atomicStore(&structure_pool[overwritten_element].occupancy_high, occupancy_high);
color_pool[overwritten_element] = color_nodes[index];
{copy_loops}
location_pool[overwritten_element] = locations[index];
// Mark dirty/correct timestamp
@@ -616,15 +658,6 @@ where
}}else if usage_buffer[requests_wb[index].node_index] != parameters.frame_timestamp + 1
{{
structure_pool[requests_wb[index].node_index].pointers[requests_wb[index].child_index] = new_pointer;
let turn_on_bit = u32(1 << (requests_wb[index].child_index % ({children_count} / 2)));
if(requests_wb[index].child_index > {children_count} / 2)
{{
//atomicOr(&structure_pool[requests_wb[index].node_index].occupancy_high, turn_on_bit);
}}else
{{
//atomicOr(&structure_pool[requests_wb[index].node_index].occupancy_low, turn_on_bit);
}}
}}
}}
@@ -725,7 +758,7 @@ where
queue,
device,
structure_pool,
color_pool,
attributes_pools,
location_pool,
request_buffer,
usage_buffer,
@@ -752,6 +785,7 @@ where
pub fn bind_group(&self) -> BindGroup
{
let attributes_bindings = self.attributes_pools.iter().map(|x| x.as_entire_buffer_binding()).collect::<Vec<wgpu::BufferBinding<'_>>>();
self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("voxel_cache_render_bind_group"),
layout: &self.voxel_cache_render_bind_group_layout,
@@ -764,7 +798,7 @@ where
// Color pool
wgpu::BindGroupEntry {
binding: 1,
resource: self.color_pool.as_entire_binding(),
resource: wgpu::BindingResource::BufferArray(attributes_bindings.as_slice()),
},
// Location pool
wgpu::BindGroupEntry {
+2 -3
View File
@@ -87,10 +87,9 @@ pub struct StructurePointer(pub u32);
impl StructurePointer
{
pub fn new(subdivided: bool, pointer_valid: bool, pointer: u32) -> Self
pub fn new(subdivided: bool, occupied: bool) -> Self
{
assert!(pointer >> 30 == 0);
StructurePointer((subdivided as u32) << 31 | (pointer_valid as u32) << 30 | pointer)
StructurePointer(((subdivided as u32) << 31) | ((occupied as u32) << 30))
}
}
+37 -19
View File
@@ -2,6 +2,8 @@
// The cache producer interface provides the necessary buffers to contains
// these, so that use applications can fullfill the requests
use std::num::NonZero;
use bytemuck::Pod;
use bytemuck::Zeroable;
use wgpu::BindGroup;
@@ -15,6 +17,7 @@ use wgpu::Device;
use wgpu::Queue;
use wgpu::util::DownloadBuffer;
use crate::voxel_cache::VoxelAttribute;
use crate::voxel_cache::data::ColorPoolElement;
use crate::voxel_cache::data::LocationPoolElement;
use crate::voxel_cache::data::StructurePoolElement;
@@ -51,7 +54,7 @@ where
pub(super) requests_wb_info: Buffer,
// Request fullfillment
pub(super) structure_nodes: Buffer,
pub(super) color_nodes: Buffer,
pub(super) attributes_nodes: Vec<Buffer>,
pub(super) location_nodes: Buffer,
pub(super) request_side_bind_group_layout: BindGroupLayout,
@@ -64,7 +67,7 @@ impl<const N: usize> CacheProducerInterface<N>
where
[(); N * N * N]:,
{
pub fn new(size: usize, device: &Device) -> Self
pub fn new(size: usize, device: &Device, attributes: Vec<VoxelAttribute>) -> Self
{
let requests = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("cache_interface_request_buffer"),
@@ -87,12 +90,19 @@ where
mapped_at_creation: false,
});
let color_nodes = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("cache_interface_structure_nodes"),
size: (size_of::<ColorPoolElement<N>>() * size) as u64,
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST,
mapped_at_creation: false,
});
// Create attributes
let attributes_nodes = attributes
.iter()
.enumerate()
.map(|(i, x)| {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(format!("VoxelCache<{N}>::attributes[{i}]").as_str()),
size: ((x.word_count as usize) * N * N * N * size * size_of::<u32>()) as u64,
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST,
mapped_at_creation: false,
})
})
.collect::<Vec<_>>();
let location_nodes = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("cache_interface_structure_nodes"),
@@ -108,7 +118,8 @@ where
mapped_at_creation: false,
});
let request_side_bind_group_layout = Self::request_side_bind_group_layout(device);
let request_side_bind_group_layout =
Self::request_side_bind_group_layout(device, &attributes);
let producer_side_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("cache_interface_producer_side_bind_group_layout"),
@@ -146,7 +157,7 @@ where
},
count: None,
},
// Color nodes
// Attributes nodes
BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::COMPUTE,
@@ -155,7 +166,7 @@ where
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
count: Some(NonZero::new(attributes.len() as u32).unwrap()),
},
// Location nodes
BindGroupLayoutEntry {
@@ -172,6 +183,10 @@ where
});
// Bind groups
let attributes_bindings = attributes_nodes
.iter()
.map(|x| x.as_entire_buffer_binding())
.collect::<Vec<wgpu::BufferBinding<'_>>>();
let request_side_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("cache_interface_request_side_bind_group"),
layout: &request_side_bind_group_layout,
@@ -194,7 +209,7 @@ where
},
BindGroupEntry {
binding: 4,
resource: color_nodes.as_entire_binding(),
resource: wgpu::BindingResource::BufferArray(&attributes_bindings),
},
BindGroupEntry {
binding: 5,
@@ -221,7 +236,7 @@ where
},
BindGroupEntry {
binding: 3,
resource: color_nodes.as_entire_binding(),
resource: wgpu::BindingResource::BufferArray(&attributes_bindings),
},
BindGroupEntry {
binding: 4,
@@ -236,7 +251,7 @@ where
request_count,
requests_wb_info,
structure_nodes,
color_nodes,
attributes_nodes,
location_nodes,
request_side_bind_group_layout,
@@ -256,9 +271,9 @@ where
&self.structure_nodes
}
pub fn color_nodes_buffer(&self) -> &Buffer
pub fn attributes_buffers(&self) -> &[Buffer]
{
&self.color_nodes
&self.attributes_nodes
}
pub fn location_nodes_buffer(&self) -> &Buffer
@@ -292,7 +307,10 @@ where
//panic!("Could not retrieve total request count.");
}
pub fn request_side_bind_group_layout(device: &Device) -> BindGroupLayout
pub fn request_side_bind_group_layout(
device: &Device,
attributes: &[VoxelAttribute],
) -> BindGroupLayout
{
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("cache_interface_request_side_bind_group_layout"),
@@ -341,7 +359,7 @@ where
},
count: None,
},
// Color nodes
// Attributes nodes
BindGroupLayoutEntry {
binding: 4,
visibility: wgpu::ShaderStages::COMPUTE,
@@ -350,7 +368,7 @@ where
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
count: Some(NonZero::new(attributes.len() as u32).unwrap()),
},
// Location nodes
BindGroupLayoutEntry {
+1 -1
View File
@@ -236,7 +236,7 @@ where
let next_phase_width = phase_total_width * 2;
if(next_phase_width >= (request_count * 2) && phase_total_width >= (request_count * 2))
{{
//indirect_count = vec3<u32>(0);
indirect_count = vec3<u32>(0);
}}
}}
+1 -1
View File
@@ -119,7 +119,7 @@ impl StructureTable
NonZero::new(size_of::<u32>() as u64).unwrap(),
)
.copy_from_slice(bytemuck::bytes_of(
&StructurePointer::new(subdivided, false, 0).0,
&StructurePointer::new(subdivided, false).0,
));
self.write_staging.finish_and_recall_on_submit(&encoder);
self.queue.submit([encoder.finish()]);