Compare commits
35
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e784d1a8b | ||
|
|
514bf5ba02 | ||
|
|
599a40301e | ||
|
|
9bd2cd5667 | ||
|
|
f8671bd35f | ||
|
|
11d26ad16b | ||
|
|
9b9f637842 | ||
|
|
b8658b7186 | ||
|
|
e4cbafb632 | ||
|
|
570ec62bdf | ||
|
|
92d61b75a8 | ||
|
|
48ff78f58d | ||
|
|
a9785252c7 | ||
|
|
2a85708b3a | ||
|
|
6b2e738a22 | ||
|
|
b560f6afd7 | ||
|
|
d9df73abab | ||
|
|
efd07fd53b | ||
|
|
9af63cf2bd | ||
|
|
7dfcfe56e9 | ||
|
|
41feb52ab5 | ||
|
|
3124978e3f | ||
|
|
e673c6dc0d | ||
|
|
a332ac08ed | ||
|
|
306b01b44c | ||
|
|
f34550e692 | ||
|
|
7c78085b61 | ||
|
|
5ed2f67324 | ||
|
|
532580b9bd | ||
|
|
d1f76fe9f0 | ||
|
|
59e3ed5f87 | ||
|
|
9015ed85d6 | ||
|
|
3835a6fa78 | ||
|
|
a342643ab7 | ||
|
|
54c5e91a7f |
@@ -0,0 +1,3 @@
|
||||
img.jpg filter=lfs diff=lfs merge=lfs -text
|
||||
img_low.jpg filter=lfs diff=lfs merge=lfs -text
|
||||
vxls_height.tif filter=lfs diff=lfs merge=lfs -text
|
||||
@@ -1,11 +1,7 @@
|
||||
/target
|
||||
Cargo.lock
|
||||
|
||||
img.jpg
|
||||
img.png
|
||||
img_low.jpg
|
||||
imgs.tar.gz
|
||||
vxls_height.tif
|
||||
|
||||
# Added by cargo
|
||||
#
|
||||
|
||||
+3
-2
@@ -9,6 +9,7 @@ crevice = {version = "0.20.1", features = ["glam"]}
|
||||
egui = "0.36.1"
|
||||
egui-wgpu = "0.36.1"
|
||||
egui-winit = "0.36.1"
|
||||
egui_ltreeview = "0.9.0"
|
||||
egui_plot = "0.37.0"
|
||||
env_logger = "0.11.11"
|
||||
fastapprox = "0.3.1"
|
||||
@@ -16,10 +17,10 @@ glam = "0.33.5"
|
||||
image = "0.25.10"
|
||||
indicatif = "0.18.6"
|
||||
itertools = "0.15.0"
|
||||
ordered-float = "5.5.0"
|
||||
noise = "0.9.0"
|
||||
pollster = "1.0.1"
|
||||
rand = "0.10.2"
|
||||
rayon = "1.12.0"
|
||||
tiff = "0.11.3"
|
||||
wgpu = "30"
|
||||
wgpu = {version = "30", features = ["spirv"]}
|
||||
winit = "0.30.13"
|
||||
|
||||
LFS
BIN
Binary file not shown.
@@ -0,0 +1,7 @@
|
||||
all: clean voxel.spv compaction.spv gi.spv radix_sort.spv radix_reduce.spv
|
||||
|
||||
clean:
|
||||
rm -f out/*.spv
|
||||
|
||||
%.spv: %.slang
|
||||
slangc $< -O3 -g0 -fp-mode fast -emit-spirv-directly -fvk-use-entrypoint-name -target spirv -o out/$@
|
||||
@@ -1,334 +0,0 @@
|
||||
struct VoxelStructureNode
|
||||
{
|
||||
pointers: array<u32, 64>
|
||||
}
|
||||
|
||||
struct VoxelColorNode
|
||||
{
|
||||
pointers: array<vec4<f32>, 64>
|
||||
}
|
||||
|
||||
struct CacheNodeRequest
|
||||
{
|
||||
location_info: u32,
|
||||
request_count: u32
|
||||
}
|
||||
|
||||
struct CacheNodeUsageBuffer
|
||||
{
|
||||
touch_time: u32,
|
||||
parent: u32,
|
||||
}
|
||||
|
||||
// Rendering kernels
|
||||
struct ChunkInfo
|
||||
{
|
||||
mvp: mat4x4<f32>,
|
||||
eye_pos: vec3<f32>,
|
||||
root_color: vec4<f32>,
|
||||
root_subdiv: u32,
|
||||
frame_timestamp: u32,
|
||||
}
|
||||
|
||||
struct StructureNode
|
||||
{
|
||||
pointers: array<u32, 64>
|
||||
}
|
||||
|
||||
struct RequestElement
|
||||
{
|
||||
pointers: array<atomic<u32>, 64>
|
||||
}
|
||||
|
||||
struct ColorNode
|
||||
{
|
||||
colors: array<vec4<f32>, 64>
|
||||
}
|
||||
|
||||
struct VertexOutput
|
||||
{
|
||||
@builtin(position) postion: vec4<f32>,
|
||||
@location(0) world_loc: vec3<f32>,
|
||||
@location(1) cam_pos: vec3<f32>,
|
||||
}
|
||||
|
||||
var<immediate> constants: ChunkInfo;
|
||||
//var<push_constant> constants: ChunkInfo;
|
||||
|
||||
@vertex
|
||||
fn chunk(@builtin(vertex_index) index: u32) -> VertexOutput
|
||||
{
|
||||
let cube_vertices = array<vec3<f32>, 8>(
|
||||
vec3<f32>(0., 0., 0.),
|
||||
vec3<f32>(0., 0., 1.),
|
||||
vec3<f32>(1., 0., 1.),
|
||||
vec3<f32>(1., 0., 0.),
|
||||
|
||||
vec3<f32>(0., 1., 0.),
|
||||
vec3<f32>(0., 1., 1.),
|
||||
vec3<f32>(1., 1., 1.),
|
||||
vec3<f32>(1., 1., 0.),
|
||||
);
|
||||
|
||||
let cube_faces = array<u32, 24>(
|
||||
// Bottom face
|
||||
1, 0, 2, 3,
|
||||
|
||||
// Top face
|
||||
4, 5, 7, 6,
|
||||
|
||||
// Side faces
|
||||
0, 1, 4, 5,
|
||||
1, 2, 5, 6,
|
||||
2, 3, 6, 7,
|
||||
3, 0, 7, 4,
|
||||
);
|
||||
|
||||
let quad_index = index / (3 * 2);
|
||||
let triangle_index = index % (3 * 2);
|
||||
let triangle_map = array<u32, 6>(
|
||||
0, 1, 2, 1, 3, 2
|
||||
);
|
||||
|
||||
let vertex = cube_vertices[cube_faces[quad_index * 4 + triangle_map[triangle_index]]];
|
||||
let output_vertex = constants.mvp * vec4<f32>(vertex, 1.0f);
|
||||
|
||||
var output: VertexOutput;
|
||||
output.postion = output_vertex;
|
||||
output.world_loc = vertex;
|
||||
output.cam_pos = constants.eye_pos;
|
||||
|
||||
//let output = vec4<f32>(vertex, 1.0f);
|
||||
return output;
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var<storage, read> structure_buffer: array<StructureNode>;
|
||||
@group(0) @binding(1) var<storage, read> color_buffer: array<ColorNode>;
|
||||
@group(0) @binding(2) var<storage, read_write> request_buffer: array<RequestElement>;
|
||||
@group(0) @binding(3) var<storage, read_write> usage_buffer: array<u32>;
|
||||
|
||||
|
||||
fn box_inter(pos: vec3<f32>, ray_dir: vec3<f32>, box_min: vec3<f32>, box_max: vec3<f32>) -> vec2<f32>
|
||||
{
|
||||
let box_min_t = (box_min - pos) / ray_dir;
|
||||
let box_max_t = (box_max - pos) / ray_dir;
|
||||
|
||||
let near_ts = min(box_min_t, box_max_t);
|
||||
let far_ts = max(box_min_t, box_max_t);
|
||||
|
||||
let far_t = min(min(far_ts.x, far_ts.y), far_ts.z);
|
||||
let near_t = max(max(near_ts.x, near_ts.y), near_ts.z);
|
||||
|
||||
return vec2(near_t, far_t);
|
||||
}
|
||||
|
||||
fn sdf(voxel: vec3<i32>) -> bool
|
||||
{
|
||||
let len = length(vec3<f32>(voxel) - vec3(128)) / 128.;
|
||||
return len <= 1.;
|
||||
}
|
||||
|
||||
fn min_vec(x: vec3<f32>) -> f32
|
||||
{
|
||||
return min(x.x, min(x.y, x.z));
|
||||
}
|
||||
|
||||
fn min_mask(x: vec3<f32>) -> vec3<bool>
|
||||
{
|
||||
let min = min(x.x, min(x.y, x.z));
|
||||
|
||||
return vec3<bool>(min == x.x, min == x.y, min == x.z);
|
||||
}
|
||||
|
||||
fn node_subdivided(node: u32) -> bool
|
||||
{
|
||||
return (node >> 31) != 0;
|
||||
}
|
||||
|
||||
fn node_pointer_valid(node: u32) -> bool
|
||||
{
|
||||
return ((node >> 30) & 1) != 0;
|
||||
}
|
||||
|
||||
fn node_pointer(node: u32) -> u32
|
||||
{
|
||||
return node & 0x3FFFFFFF;
|
||||
}
|
||||
|
||||
fn voxel_from_wall(position: vec3<f32>, ray_dir: vec3<f32>) -> vec3<i32>
|
||||
{
|
||||
let integers = round(position);
|
||||
let wall_mask = min_mask(abs(position - vec3<f32>(integers)));
|
||||
let offsets = select(vec3<f32>(-0.5), vec3<f32>(0.5), ray_dir > vec3(0.));
|
||||
return vec3<i32>(floor(position + select(vec3<f32>(0.), offsets, wall_mask)));
|
||||
}
|
||||
|
||||
fn traverse(ray_dir: vec3<f32>, ray_origin: vec3<f32>, root_color: vec4<f32>, root_subdiv: bool) -> vec4<f32>
|
||||
{
|
||||
// Simple FVT
|
||||
let t_off = abs(1. / ray_dir);
|
||||
|
||||
// Start location
|
||||
let voxel_dir = select(vec3(-1), vec3(1), ray_dir >= vec3(0.));
|
||||
var pos_origin = clamp(ray_origin * 256., vec3(0.), vec3(256. - 1.));
|
||||
var voxel = vec3<i32>(pos_origin);
|
||||
var last_voxel = voxel;
|
||||
|
||||
let wall_offset = select(vec3(0), vec3(1), ray_dir > vec3(0.));
|
||||
|
||||
var dfs_stack = array<u32, 5>(0, 0, 0, 0, 0);
|
||||
|
||||
// Current depth of the node we are exploring
|
||||
var current_depth = 0;
|
||||
|
||||
// Index of the current node's data
|
||||
var current_node = u32(0);
|
||||
|
||||
// Current node size
|
||||
var node_size = 4 * 4 * 4 * 4; // 128
|
||||
|
||||
// Size of a child of this node
|
||||
var child_size = node_size / 4;
|
||||
|
||||
// Lut of the node_size per depth
|
||||
var node_size_lut = array<i32, 5>(
|
||||
4 * 4 * 4 * 4,
|
||||
4 * 4 * 4,
|
||||
4 * 4,
|
||||
4,
|
||||
1,
|
||||
);
|
||||
|
||||
let depth_limit = 1;
|
||||
for(var iter = 0; iter < 256; iter ++)
|
||||
{
|
||||
|
||||
// Our ray is currently touching a voxel.
|
||||
// Descend to the lowest node that contains this voxel
|
||||
|
||||
// Position of the child we are in
|
||||
var child_pos = (vec3<u32>(voxel) >> vec3<u32>((4 - u32(current_depth + 1)) * 2)) & vec3<u32>(3); // Hardcode for 4-tree
|
||||
var child_index = child_pos.x + child_pos.y * 4 + child_pos.z * 4 * 4;
|
||||
|
||||
// Current node has been used. report
|
||||
usage_buffer[current_node] = constants.frame_timestamp;
|
||||
|
||||
while(
|
||||
node_subdivided(structure_buffer[current_node].pointers[child_index])
|
||||
&& current_depth < depth_limit)
|
||||
{
|
||||
if(!node_pointer_valid(structure_buffer[current_node].pointers[child_index]))
|
||||
{
|
||||
atomicAdd(&request_buffer[current_node].pointers[child_index], 1);
|
||||
break;
|
||||
}
|
||||
// Child node is subdivided, we go in, save position in stack
|
||||
current_node = node_pointer(structure_buffer[current_node].pointers[child_index]);
|
||||
usage_buffer[current_node] = constants.frame_timestamp;
|
||||
current_depth += 1;
|
||||
dfs_stack[current_depth] = current_node;
|
||||
node_size = node_size_lut[current_depth];
|
||||
|
||||
child_pos = (vec3<u32>(voxel) >> vec3<u32>((4 - u32(current_depth + 1)) * 2)) & vec3<u32>(3); // Hardcode for 4-tree
|
||||
child_index = child_pos.x + child_pos.y * 4 + child_pos.z * 4 * 4;
|
||||
child_size = node_size / 4;
|
||||
}
|
||||
|
||||
|
||||
// At this point current_depth is the depth of the node that contains the voxel
|
||||
// child_pos and child_index relate to the specific child of the node that contains this voxel
|
||||
// It is guaranteed that the child is leave
|
||||
|
||||
// Check current leave's color
|
||||
let color = color_buffer[current_node].colors[child_index];
|
||||
if(color.w != 0.) // Not transparent
|
||||
{
|
||||
let k = child_pos.x + child_pos.y + child_pos.z;
|
||||
let x = select(0.5, 1., k % 2 == 0);
|
||||
return x * color / f32(current_depth);
|
||||
}
|
||||
|
||||
// Voxel and whole child containing it is empty
|
||||
|
||||
// Perform a step through the children of the node
|
||||
let child_position = (voxel / child_size) * child_size;
|
||||
let far_corner = child_position + wall_offset * child_size;
|
||||
let far_ts = (vec3<f32>(far_corner) - pos_origin) / ray_dir; // TODO: Turn into fma
|
||||
let far_t = min(min(far_ts.x, far_ts.y), far_ts.z);
|
||||
|
||||
let next_child_min = select(child_position, child_position + wall_offset * child_size, vec3(far_t) == far_ts);
|
||||
let next_child_max = next_child_min + vec3(child_size);
|
||||
|
||||
// The ray (far_t) is now touching the new child to explore
|
||||
// Find out which actual voxel we are touching
|
||||
let previous_voxel = voxel;
|
||||
let float_voxel = clamp(pos_origin + far_t * ray_dir, vec3<f32>(next_child_min), vec3<f32>(next_child_max));
|
||||
/*
|
||||
voxel = vec3<i32>(
|
||||
floor(
|
||||
select(
|
||||
float_voxel - vec3(0.5),
|
||||
float_voxel + vec3(0.5),
|
||||
ray_dir > vec3(0.)
|
||||
))
|
||||
);
|
||||
*/
|
||||
//voxel = vec3<i32>(round(float_voxel));
|
||||
voxel = voxel_from_wall(float_voxel, ray_dir);
|
||||
if(any(voxel < vec3(0)) || any(voxel >= vec3(256)))
|
||||
{
|
||||
//return vec4(f32(iter) / 100.);
|
||||
discard;
|
||||
}
|
||||
|
||||
// We touched a voxel as if we explored blocks sized by the child size of the current node.
|
||||
// But we might have exited the current node.
|
||||
|
||||
// If this is the case we have to walk back up the tree
|
||||
// And then back down to the next node over
|
||||
|
||||
// As such we find the lowest ancestor that can contain both the privous voxel (in node) and the new voxel (out of node)
|
||||
let bit_diffs = voxel ^ previous_voxel;
|
||||
let bit_diffs_lowest = bit_diffs.x | bit_diffs.y | bit_diffs.z;
|
||||
|
||||
let flb = ((countLeadingZeros(bit_diffs_lowest) - 24) / 2);
|
||||
let common_depth = flb;
|
||||
|
||||
current_depth = common_depth;
|
||||
node_size = node_size_lut[current_depth];
|
||||
child_size = node_size / 4;
|
||||
current_node = dfs_stack[current_depth];
|
||||
|
||||
// Figure out current voxel position
|
||||
//voxel = vec3<i32>(ray_origin + ray_dir * t);
|
||||
|
||||
}
|
||||
return vec4<f32>(1., 0., 1., 1.);
|
||||
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fragment(in: VertexOutput) -> @location(0) vec4<f32>
|
||||
{
|
||||
let ray_dir = normalize(in.world_loc - in.cam_pos);
|
||||
let interp = box_inter(in.cam_pos, ray_dir, vec3(0.), vec3(1));
|
||||
let ray_origin = in.cam_pos + ray_dir * (max(0., interp.x));
|
||||
|
||||
return traverse(ray_dir, ray_origin, constants.root_color, constants.root_subdiv != 0);
|
||||
return vec4(interp.y / 10.);
|
||||
}
|
||||
|
||||
// Cache managment kernels
|
||||
|
||||
// Request buffer managment
|
||||
// Compaction
|
||||
@workgroup_size(64)
|
||||
fn main(
|
||||
@builtin(global_invocation_id) gid: vec3<u32>
|
||||
)
|
||||
{
|
||||
let cache_size = 1024;
|
||||
let index = gid.x;
|
||||
|
||||
for()
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
|
||||
[[vk::binding(0, 0)]]
|
||||
RWStructuredBuffer<uint32_t> count_buffer;
|
||||
[[vk::binding(1, 0)]]
|
||||
RWStructuredBuffer<uint32_t> index_buffer;
|
||||
[[vk::binding(2, 0)]]
|
||||
RWStructuredBuffer<uint32_t> compacted_buffer;
|
||||
|
||||
[[vk::push_constant]]
|
||||
uniform uint32_t write_compact;
|
||||
|
||||
[[vk::binding(0, 1)]]
|
||||
RWStructuredBuffer<uint32_t> reduced_buffer;
|
||||
[[vk::binding(1, 1)]]
|
||||
RWStructuredBuffer<uint32_t> sum_buffer;
|
||||
|
||||
groupshared uint32_t local_data[256 * 2];
|
||||
static uint32_t THREAD_WIDTH = 256;
|
||||
static uint32_t DATA_WIDTH = THREAD_WIDTH * 2;
|
||||
|
||||
[numthreads(256, 1, 1)]
|
||||
[shader("compute")]
|
||||
void block_sum(
|
||||
uint32_t3 workgroup_id: SV_GroupID,
|
||||
uint32_t3 local_thread_id: SV_GroupThreadID,
|
||||
uint32_t3 global_thread_id: SV_DispatchThreadID)
|
||||
{
|
||||
// Perform sum in current block
|
||||
|
||||
// Copy local_datainto LDS with predicate
|
||||
let thread_index = global_thread_id.x;
|
||||
let local_thread_index = local_thread_id.x;
|
||||
let total = count_buffer.getCount();
|
||||
|
||||
if (thread_index * 2 < total)
|
||||
{
|
||||
local_data[local_thread_index * 2] = select(count_buffer[thread_index * 2] != 0, 1, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
local_data[local_thread_index * 2] = 0;
|
||||
}
|
||||
|
||||
if (thread_index * 2 + 1 < total)
|
||||
{
|
||||
local_data[local_thread_index * 2 + 1] = select(count_buffer[thread_index * 2 + 1] != 0, 1, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
local_data[local_thread_index * 2 + 1] = 0;
|
||||
}
|
||||
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
var width : uint32_t = 2;
|
||||
while (width <= DATA_WIDTH)
|
||||
{
|
||||
let dest_index = width * (local_thread_index + 1) - 1;
|
||||
let get_index = dest_index - (width / 2);
|
||||
// println!("{}, {}", get_index, dest_index);
|
||||
if (dest_index < DATA_WIDTH)
|
||||
{
|
||||
local_data[dest_index] += local_data[get_index];
|
||||
}
|
||||
width *= 2;
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
// Write to reduced buffer
|
||||
reduced_buffer[workgroup_id.x] = local_data[DATA_WIDTH - 1];
|
||||
// reduced_buffer[workgroup_id.x] = local_data[DATA_WIDTH - 1];
|
||||
|
||||
local_data[DATA_WIDTH - 1] = 0;
|
||||
while (width >= 2)
|
||||
{
|
||||
let dest_index = width * (local_thread_index + 1) - 1;
|
||||
let get_index = dest_index - (width / 2);
|
||||
// println!("{}, {}", get_index, dest_index);
|
||||
if (dest_index < DATA_WIDTH)
|
||||
{
|
||||
let self_data = local_data[dest_index];
|
||||
local_data[dest_index] += local_data[get_index];
|
||||
local_data[get_index] = self_data;
|
||||
}
|
||||
width /= 2;
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
// Block now contains running local sum
|
||||
// Dump back to sum buffer
|
||||
sum_buffer[2 * thread_index] = local_data[2 * local_thread_index];
|
||||
sum_buffer[2 * thread_index + 1] = local_data[2 * local_thread_index + 1];
|
||||
}
|
||||
|
||||
groupshared uint32_t local_prefix[256];
|
||||
|
||||
[numthreads(256, 1, 1)]
|
||||
[shader("compute")]
|
||||
void linear_reduced_sum(
|
||||
uint32_t3 workgroup_id: SV_GroupID,
|
||||
uint32_t3 local_thread_id: SV_GroupThreadID,
|
||||
uint32_t3 global_thread_id: SV_DispatchThreadID)
|
||||
{
|
||||
let size = reduced_buffer.getCount();
|
||||
|
||||
uint32_t running_sum = 0;
|
||||
for (uint32_t slice = 0; slice < size; slice += 256)
|
||||
{
|
||||
let index = slice + local_thread_id.x;
|
||||
if (index < size)
|
||||
{
|
||||
local_prefix[local_thread_id.x] = reduced_buffer[index];
|
||||
}
|
||||
else
|
||||
{
|
||||
local_prefix[local_thread_id.x] = 0;
|
||||
}
|
||||
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
for (uint32_t offset = 1; offset < 256; offset *= 2)
|
||||
{
|
||||
uint32_t offset_value = select(local_thread_id.x >= offset, local_prefix[local_thread_id.x - offset], 0);
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
local_prefix[local_thread_id.x] += offset_value;
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
if (index < size)
|
||||
{
|
||||
reduced_buffer[index] = select(local_thread_id.x == 0, 0, local_prefix[local_thread_id.x - 1]) + running_sum;
|
||||
}
|
||||
running_sum += local_prefix[255];
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
}
|
||||
|
||||
[numthreads(256, 1, 1)]
|
||||
[shader("compute")]
|
||||
void scatter(
|
||||
uint32_t3 workgroup_id: SV_GroupID,
|
||||
uint32_t3 local_thread_id: SV_GroupThreadID,
|
||||
uint32_t3 global_thread_id: SV_DispatchThreadID)
|
||||
{
|
||||
let total = index_buffer.getCount();
|
||||
let thread_index = global_thread_id.x;
|
||||
let local_thread_index = local_thread_id.x;
|
||||
|
||||
// Gather
|
||||
let reduced_value = reduced_buffer[workgroup_id.x];
|
||||
// Apply
|
||||
let sum1 = sum_buffer[thread_index * 2] + reduced_value;
|
||||
let sum2 = sum_buffer[thread_index * 2 + 1] + reduced_value;
|
||||
|
||||
// Scatter index to compact index buffer if predicate is true
|
||||
if (count_buffer[thread_index * 2] != 0 && sum1 < total)
|
||||
{
|
||||
index_buffer[sum1] = thread_index * 2;
|
||||
}
|
||||
|
||||
if (count_buffer[thread_index * 2 + 1] != 0 && sum2 < total)
|
||||
{
|
||||
index_buffer[sum2] = thread_index * 2 + 1;
|
||||
}
|
||||
|
||||
if (write_compact != 0)
|
||||
{
|
||||
if (count_buffer[thread_index * 2] != 0 && sum1 < total)
|
||||
{
|
||||
compacted_buffer[sum1] = count_buffer[thread_index * 2];
|
||||
}
|
||||
|
||||
if (count_buffer[thread_index * 2 + 1] != 0 && sum2 < total)
|
||||
{
|
||||
compacted_buffer[sum2] = count_buffer[thread_index * 2 + 1];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
module example;
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
module fixed_structure_table;
|
||||
|
||||
import voxel_cache;
|
||||
import voxel_tracing;
|
||||
|
||||
/// Parameters for the fixed structure table
|
||||
public struct FixedStructureTable
|
||||
{
|
||||
RWStructuredBuffer<StructurePointer> structure_table_pointer;
|
||||
RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
|
||||
}
|
||||
|
||||
public struct FixedStructureTableChunksCursor
|
||||
{
|
||||
int32_t3 current_voxel;
|
||||
float3 t_off;
|
||||
float3 t;
|
||||
|
||||
Ray r;
|
||||
}
|
||||
|
||||
/// Uses a fixed structure table as a dense array of chunks
|
||||
public struct FixedStructureTableChunks : IStructure
|
||||
{
|
||||
typedef FixedStructureTableChunksCursor Cursor;
|
||||
|
||||
public FixedStructureTable structure_table;
|
||||
public uint32_t3 extent;
|
||||
|
||||
public FixedStructureTableChunksCursor begin(Ray worldRay, Span s)
|
||||
{
|
||||
FixedStructureTableChunksCursor cursor;
|
||||
|
||||
// Intersect with bounds
|
||||
var inter = box_intersect(worldRay.origin, worldRay.direction, float3(0.), float3(this.extent.x, this.extent.y, this.extent.z));
|
||||
|
||||
// No hit if out of box
|
||||
if (inter.y <= inter.x || inter.y <= 0.)
|
||||
{
|
||||
// Take position way off so it exits on firt next call
|
||||
cursor.current_voxel = int32_t3(-1);
|
||||
cursor.t_off = float3(0.);
|
||||
return cursor;
|
||||
}
|
||||
inter.x = max(0., inter.x);
|
||||
|
||||
// Now march inside chunk bounds
|
||||
let start_position = inter.x * worldRay.direction + worldRay.origin;
|
||||
|
||||
// FVT clamp to block
|
||||
cursor.current_voxel = clamp(
|
||||
int32_t3(floor(start_position)),
|
||||
int32_t3(0),
|
||||
int32_t3(this.extent.x - 1, this.extent.y - 1, this.extent.z - 1));
|
||||
cursor.t_off = abs(worldRay.invDirection);
|
||||
|
||||
// Take t of next boundary
|
||||
cursor.t = select(
|
||||
worldRay.direction > 0.,
|
||||
cursor.current_voxel + int32_t3(1) - start_position,
|
||||
start_position - cursor.current_voxel) *
|
||||
cursor.t_off;
|
||||
|
||||
// Add camera offset
|
||||
cursor.t += inter.x;
|
||||
cursor.r = worldRay;
|
||||
return cursor;
|
||||
}
|
||||
|
||||
public bool next(inout Cursor c, out Cell cell)
|
||||
{
|
||||
while (all(c.current_voxel >= 0) && all(c.current_voxel < int32_t3(this.extent.x, this.extent.y, this.extent.z)))
|
||||
{
|
||||
// Current hit
|
||||
let off = c.t - c.t_off;
|
||||
let t_adv = max(max(off.x, max(off.y, off.z)), 0.);
|
||||
let chunk_index = c.current_voxel.x + c.current_voxel.z * this.extent.x + c.current_voxel.y * this.extent.x * this.extent.z;
|
||||
let position = c.r.origin + c.r.direction * t_adv;
|
||||
|
||||
var hit = false;
|
||||
if (this.structure_table.structure_table_pointer[chunk_index].subdivided_valid())
|
||||
{
|
||||
cell.cache_pointer = this.structure_table.structure_table_pointer[chunk_index].pointer();
|
||||
cell.local_ray.origin = position - float3(c.current_voxel);
|
||||
cell.local_ray.direction = c.r.direction;
|
||||
cell.local_ray.invDirection = c.r.invDirection;
|
||||
cell.t = t_adv;
|
||||
hit = true;
|
||||
}
|
||||
else if (this.structure_table.structure_table_pointer[chunk_index].subdivided())
|
||||
{
|
||||
this.structure_table.structure_table_request_buffer[chunk_index].add(1);
|
||||
hit = false;
|
||||
}
|
||||
|
||||
// Advance
|
||||
let min_mask = min_mask(c.t);
|
||||
c.t += select(min_mask, c.t_off, float3(0.));
|
||||
c.current_voxel += select(min_mask, int32_t3(sign(c.r.direction)), int32_t3(0));
|
||||
|
||||
if (hit)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool3 min_mask(float3 val)
|
||||
{
|
||||
let min_val = min(val.x, min(val.y, val.z));
|
||||
return val == min_val;
|
||||
}
|
||||
|
||||
float2 box_intersect(float3 origin, float3 ray_direction, float3 box_min, float3 box_max)
|
||||
{
|
||||
let min_ts = (box_min - origin) / ray_direction;
|
||||
let max_ts = (box_max - origin) / ray_direction;
|
||||
|
||||
let far_ts = max(min_ts, max_ts);
|
||||
let near_ts = min(min_ts, max_ts);
|
||||
|
||||
let far_t = min(far_ts.x, min(far_ts.y, far_ts.z));
|
||||
let near_t = max(near_ts.x, max(near_ts.y, near_ts.z));
|
||||
return float2(near_t, far_t);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
struct PushConstants
|
||||
{
|
||||
float4x4 view_proj;
|
||||
float3 cam_pos;
|
||||
uint32_t frame_timestamp;
|
||||
uint32_t width;
|
||||
uint32_t height;
|
||||
|
||||
uint32_t chunk_width;
|
||||
uint32_t chunk_height;
|
||||
uint32_t chunk_alt;
|
||||
}
|
||||
|
||||
[[vk::push_constant]]
|
||||
uniform PushConstants constants;
|
||||
|
||||
[[vk::binding(0, 0)]]
|
||||
RWStructuredBuffer<uint32_t> structure_pool;
|
||||
[[vk::binding(1, 0)]]
|
||||
RWStructuredBuffer<uint32_t> attributes_pool[2];
|
||||
[[vk::binding(2, 0)]]
|
||||
RWStructuredBuffer<uint32_t> request_buffer;
|
||||
[[vk::binding(3, 0)]]
|
||||
RWStructuredBuffer<uint32_t> usage_buffer;
|
||||
|
||||
[[vk::binding(0, 1)]]
|
||||
RWStructuredBuffer<uint32_t> structure_table_pointer;
|
||||
[[vk::binding(1, 1)]]
|
||||
RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
|
||||
|
||||
[[vk::binding(0, 2)]]
|
||||
[[format("rgba32f")]]
|
||||
WTexture2D<float4> target_texture;
|
||||
|
||||
[[vk::binding(1, 2)]]
|
||||
[[format("rgba32f")]]
|
||||
RWTexture2D<float4> gbuffer_position;
|
||||
|
||||
[[vk::binding(2, 2)]]
|
||||
[[format("rgba32f")]]
|
||||
RWTexture2D<float4> gbuffer_albedo;
|
||||
|
||||
[[vk::binding(3, 2)]]
|
||||
[[format("rgba32f")]]
|
||||
RWTexture2D<float4> gbuffer_normal;
|
||||
|
||||
float3 get_ray_direction(uint32_t2 pixel_loc)
|
||||
{
|
||||
let ndc_loc_x = (float)pixel_loc.x / (float)constants.width * 2. - 1.;
|
||||
let ndc_loc_y = 1. - (float)pixel_loc.y / (float)constants.height * 2.;
|
||||
var world_loc = mul(constants.view_proj, float4(ndc_loc_x, ndc_loc_y, 1., 1.));
|
||||
world_loc /= world_loc.w;
|
||||
return normalize(world_loc.xyz - constants.cam_pos);
|
||||
}
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(16, 16, 1)]
|
||||
void gi(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID)
|
||||
{
|
||||
if (location.x >= constants.width || location.y >= constants.height)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (gbuffer_albedo.Load(location.xy).w == 0.)
|
||||
{
|
||||
target_texture.Store(location.xy, float4(0.));
|
||||
return;
|
||||
}
|
||||
|
||||
let pos = gbuffer_position.Load(location.xy);
|
||||
let normal = gbuffer_normal.Load(location.xy);
|
||||
let albedo = gbuffer_albedo.Load(location.xy);
|
||||
target_texture.Store(location.xy, albedo);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
module lod_policies;
|
||||
import voxel_tracing;
|
||||
|
||||
public struct PixelFootprintLod : ILodPolicy
|
||||
{
|
||||
// Angular size of one pixel in radians (small-angle approximation).
|
||||
// For a pinhole camera: 2 * tan(fovY * 0.5) / imageHeightInPixels.
|
||||
public float pixelAngle;
|
||||
|
||||
// How many pixels a node may cover before we refuse to stop.
|
||||
// 1.0 = stop once a node is <= 1 pixel wide.
|
||||
// < 1.0 = more detail (sharper, slower), > 1.0 = coarser (faster, blurrier).
|
||||
public float pixelThreshold;
|
||||
|
||||
// Cone radius at t = 0. Zero for a pinhole camera; non-zero for
|
||||
// secondary rays that inherit a footprint from a previous bounce.
|
||||
public float coneRadius0;
|
||||
|
||||
// Footprint (world-space width of one pixel) at ray distance t.
|
||||
public float footprint(float t)
|
||||
{
|
||||
return coneRadius0 + t * pixelAngle;
|
||||
}
|
||||
|
||||
public bool shouldStop(float t, float nodeSize)
|
||||
{
|
||||
// Node edge length not larger than the allowed pixel coverage -> stop.
|
||||
return nodeSize <= footprint(t) * pixelThreshold;
|
||||
}
|
||||
|
||||
// Convenience constructor from camera parameters.
|
||||
public static PixelFootprintLod create(
|
||||
float fovYRadians,
|
||||
float imageHeightPixels,
|
||||
float pixelThreshold = 1.0,
|
||||
float coneRadius0 = 0.0)
|
||||
{
|
||||
PixelFootprintLod p;
|
||||
p.pixelAngle = 2.0 * tan(0.5 * fovYRadians) / imageHeightPixels;
|
||||
p.pixelThreshold = pixelThreshold;
|
||||
p.coneRadius0 = coneRadius0;
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,158 @@
|
||||
[[vk::binding(0, 0)]]
|
||||
RWStructuredBuffer<uint32_t> count_buffer;
|
||||
[[vk::binding(0, 1)]]
|
||||
RWStructuredBuffer<uint32_t> reduced_buffer;
|
||||
|
||||
static const uint32_t THREAD_WIDTH = 256;
|
||||
static const uint32_t DATA_WIDTH = THREAD_WIDTH * 2;
|
||||
static const uint32_t DIGIT_COUNT = 8;
|
||||
static const uint32_t VALUE_COUNT = 1 << DIGIT_COUNT;
|
||||
|
||||
groupshared uint32_t local_data[DATA_WIDTH];
|
||||
|
||||
[numthreads(256, 1, 1)]
|
||||
[shader("compute")]
|
||||
void reduce_pass(
|
||||
uint32_t3 workgroup_id: SV_GroupID,
|
||||
uint32_t3 local_thread_id: SV_GroupThreadID,
|
||||
uint32_t3 global_thread_id: SV_DispatchThreadID)
|
||||
{
|
||||
// Perform sum in current block
|
||||
let thread_index = global_thread_id.x;
|
||||
let local_thread_index = local_thread_id.x;
|
||||
let total = count_buffer.getCount();
|
||||
|
||||
// Load to groupshared
|
||||
local_data[local_thread_index * 2] = select((thread_index * 2) < total, count_buffer[thread_index * 2], 0);
|
||||
local_data[local_thread_index * 2 + 1] = select(((thread_index * 2) + 1) < total, count_buffer[thread_index * 2 + 1], 0);
|
||||
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
// Belloch sum
|
||||
var width : uint32_t = 2;
|
||||
while (width <= DATA_WIDTH)
|
||||
{
|
||||
let dest_index = width * (local_thread_index + 1) - 1;
|
||||
let get_index = dest_index - (width / 2);
|
||||
// println!("{}, {}", get_index, dest_index);
|
||||
if (dest_index < DATA_WIDTH)
|
||||
{
|
||||
local_data[dest_index] += local_data[get_index];
|
||||
}
|
||||
width *= 2;
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
// Write to reduced buffer
|
||||
reduced_buffer[workgroup_id.x] = local_data[DATA_WIDTH - 1];
|
||||
// reduced_buffer[workgroup_id.x] = local_data[DATA_WIDTH - 1];
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
local_data[DATA_WIDTH - 1] = 0;
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
while (width >= 2)
|
||||
{
|
||||
let dest_index = width * (local_thread_index + 1) - 1;
|
||||
let get_index = dest_index - (width / 2);
|
||||
// println!("{}, {}", get_index, dest_index);
|
||||
if (dest_index < DATA_WIDTH)
|
||||
{
|
||||
let self_data = local_data[dest_index];
|
||||
local_data[dest_index] += local_data[get_index];
|
||||
local_data[get_index] = self_data;
|
||||
}
|
||||
width /= 2;
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
// Block now contains running local sum
|
||||
// Dump back to sum buffer
|
||||
if (2 * thread_index < total)
|
||||
{
|
||||
count_buffer[2 * thread_index] = local_data[2 * local_thread_index];
|
||||
}
|
||||
if ((2 * thread_index + 1) < total)
|
||||
{
|
||||
count_buffer[2 * thread_index + 1] = local_data[2 * local_thread_index + 1];
|
||||
}
|
||||
}
|
||||
|
||||
[numthreads(256, 1, 1)]
|
||||
[shader("compute")]
|
||||
void apply_pass(
|
||||
uint32_t3 workgroup_id: SV_GroupID,
|
||||
uint32_t3 local_thread_id: SV_GroupThreadID,
|
||||
uint32_t3 global_thread_id: SV_DispatchThreadID)
|
||||
{
|
||||
let total = count_buffer.getCount();
|
||||
let thread_index = global_thread_id.x;
|
||||
let local_thread_index = local_thread_id.x;
|
||||
|
||||
// Gather
|
||||
let reduced_value = reduced_buffer[workgroup_id.x];
|
||||
|
||||
// Apply sum back
|
||||
if (thread_index * 2 < total)
|
||||
{
|
||||
count_buffer[thread_index * 2] += reduced_value;
|
||||
}
|
||||
|
||||
if ((thread_index * 2 + 1) < total)
|
||||
{
|
||||
count_buffer[thread_index * 2 + 1] += reduced_value;
|
||||
}
|
||||
}
|
||||
|
||||
[numthreads(1, 1, 1)]
|
||||
[shader("compute")]
|
||||
void direct_pass(
|
||||
uint32_t3 workgroup_id: SV_GroupID,
|
||||
uint32_t3 local_thread_id: SV_GroupThreadID,
|
||||
uint32_t3 global_thread_id: SV_DispatchThreadID)
|
||||
{
|
||||
let size = reduced_buffer.getCount();
|
||||
|
||||
// Perform exclusive sum
|
||||
var running_sum : uint32_t = 0;
|
||||
for (uint32_t i = 0; i < size; i++)
|
||||
{
|
||||
let value = reduced_buffer[i];
|
||||
reduced_buffer[i] = running_sum;
|
||||
running_sum += value;
|
||||
}
|
||||
}
|
||||
|
||||
struct IndirectArgs
|
||||
{
|
||||
uint32_t x;
|
||||
uint32_t y;
|
||||
uint32_t z;
|
||||
}
|
||||
|
||||
[[vk::binding(0, 0)]]
|
||||
RWStructuredBuffer<uint32_t> total_count;
|
||||
[[vk::binding(0, 1)]]
|
||||
RWStructuredBuffer<IndirectArgs> group_counts;
|
||||
|
||||
[numthreads(1, 1, 1)]
|
||||
[shader("compute")]
|
||||
void compute_invocation_count(
|
||||
uint32_t3 workgroup_id: SV_GroupID,
|
||||
uint32_t3 local_thread_id: SV_GroupThreadID,
|
||||
uint32_t3 global_thread_id: SV_DispatchThreadID)
|
||||
{
|
||||
var prev_count = total_count[0];
|
||||
for (var i = 0; i < group_counts.getCount(); i++)
|
||||
{
|
||||
prev_count = div_ceil(prev_count, THREAD_WIDTH);
|
||||
group_counts[i].x = prev_count;
|
||||
group_counts[i].y = 1;
|
||||
group_counts[i].z = 1;
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t div_ceil(uint32_t n, uint32_t q)
|
||||
{
|
||||
return (n / q) + select(n % q == 0, 0, 1);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
const static uint32_t digit_count = 8;
|
||||
const static uint32_t value_count = 1 << digit_count;
|
||||
|
||||
// Thread count per work group
|
||||
static const uint32_t WG_THREAD_COUNT = 256;
|
||||
|
||||
// Elements managed per thread for histo build
|
||||
static const uint32_t WE_HISTO_ELEMENTS = 16;
|
||||
|
||||
// Elements managed per workgroup for histo build
|
||||
static const uint32_t WG_HISTO_ELEMENT = WG_THREAD_COUNT * WE_HISTO_ELEMENTS;
|
||||
|
||||
struct IndirectArgs
|
||||
{
|
||||
uint32_t x;
|
||||
uint32_t y;
|
||||
uint32_t z;
|
||||
}
|
||||
|
||||
struct PassParams
|
||||
{
|
||||
uint32_t pass_index;
|
||||
uint32_t descending;
|
||||
uint32_t histogram_count;
|
||||
}
|
||||
|
||||
[vk::binding(0, 0)]
|
||||
RWStructuredBuffer<uint32_t> histograms;
|
||||
|
||||
[vk::binding(0, 1)]
|
||||
RWStructuredBuffer<uint32_t> key_buffer;
|
||||
[vk::binding(1, 1)]
|
||||
RWStructuredBuffer<uint32_t> value_buffer;
|
||||
|
||||
// Double buffering
|
||||
[vk::binding(0, 2)]
|
||||
RWStructuredBuffer<uint32_t> dest_key_buffer;
|
||||
[vk::binding(1, 2)]
|
||||
RWStructuredBuffer<uint32_t> dest_value_buffer;
|
||||
|
||||
[vk::binding(0, 3)]
|
||||
RWStructuredBuffer<uint32_t> indirect_element_count;
|
||||
[vk::binding(1, 3)]
|
||||
RWStructuredBuffer<IndirectArgs> indirect_workgroup_count;
|
||||
|
||||
[vk::push_constant]
|
||||
uniform PassParams params;
|
||||
|
||||
uint32_t extract_digit(uint32_t value, uint32_t digit_id, uint32_t descending)
|
||||
{
|
||||
let mask = ~(0xFFFFFFFF << digit_count);
|
||||
let digit = (value >> (digit_id * digit_count)) & mask;
|
||||
return select(descending != 0, digit ^ mask, digit);
|
||||
}
|
||||
|
||||
groupshared Atomic<uint32_t> local_histogram[value_count];
|
||||
|
||||
// groupshared uint32_t local_histogram[value_count];
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(WG_THREAD_COUNT, 1, 1)]
|
||||
void histogram_pass(
|
||||
uint32_t3 location: SV_DispatchThreadID,
|
||||
uint32_t3 local_location: SV_GroupThreadID,
|
||||
uint32_t3 group_location: SV_GroupID, )
|
||||
{
|
||||
if (local_location.x < value_count)
|
||||
{
|
||||
local_histogram[local_location.x] = 0;
|
||||
}
|
||||
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
// This coalesces read
|
||||
for (uint32_t index = group_location.x * WG_HISTO_ELEMENT + local_location.x;
|
||||
index < min(indirect_element_count[0], (group_location.x + 1) * WG_HISTO_ELEMENT);
|
||||
index += WG_THREAD_COUNT)
|
||||
{
|
||||
uint32_t key = key_buffer[index];
|
||||
uint32_t digit = extract_digit(key, params.pass_index, params.descending);
|
||||
local_histogram[digit].add(1);
|
||||
}
|
||||
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
if (local_location.x < value_count)
|
||||
{
|
||||
// histograms[local_location.x + group_location.x * value_count] = local_histogram[local_location.x].load();
|
||||
histograms[local_location.x * params.histogram_count + group_location.x] = local_histogram[local_location.x].load();
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t div_ceil(uint32_t n, uint32_t q)
|
||||
{
|
||||
return (n / q) + select(n % q == 0, 0, 1);
|
||||
}
|
||||
|
||||
// groupshared uint32_t local_total_histogram[value_count];
|
||||
groupshared uint32_t local_prefix[WG_THREAD_COUNT];
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(WG_THREAD_COUNT, 1, 1)]
|
||||
void prefix_sum_pass(
|
||||
uint32_t3 location: SV_DispatchThreadID,
|
||||
uint32_t3 local_location: SV_GroupThreadID,
|
||||
uint32_t3 group_location: SV_GroupID, )
|
||||
{
|
||||
// value_count is the number of possible values for a digit
|
||||
uint32_t value = group_location.x;
|
||||
uint32_t value_offset = value * params.histogram_count;
|
||||
uint32_t running_prefix = 0;
|
||||
|
||||
uint32_t start_offset = group_location.x * params.histogram_count;
|
||||
// uint32_t end_offset = start_offset + params.histogram_count;
|
||||
uint32_t end_offset = start_offset + indirect_workgroup_count[0].x + 1;
|
||||
|
||||
for (
|
||||
uint32_t slice_offset = start_offset;
|
||||
slice_offset < end_offset;
|
||||
slice_offset += WG_THREAD_COUNT)
|
||||
{
|
||||
uint32_t index = slice_offset + local_location.x;
|
||||
// Load data into lds
|
||||
if (index < end_offset - 1)
|
||||
{
|
||||
local_prefix[local_location.x] = histograms[index];
|
||||
}
|
||||
else
|
||||
{
|
||||
local_prefix[local_location.x] = 0;
|
||||
}
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
// Perform hillis steele
|
||||
|
||||
for (uint32_t offset = 1; offset < WG_THREAD_COUNT; offset *= 2)
|
||||
{
|
||||
uint32_t offset_value = select(local_location.x >= offset, local_prefix[local_location.x - offset], 0);
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
local_prefix[local_location.x] += offset_value;
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
// Accumulate runnig_prefix
|
||||
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
if (index < end_offset)
|
||||
{
|
||||
histograms[index] = select(local_location.x == 0, 0, local_prefix[local_location.x - 1]) + running_prefix;
|
||||
}
|
||||
running_prefix += local_prefix[WG_THREAD_COUNT - 1];
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
}
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(WG_THREAD_COUNT, 1, 1)]
|
||||
void total_prefix_sum_pass(
|
||||
uint32_t3 location: SV_DispatchThreadID,
|
||||
uint32_t3 local_location: SV_GroupThreadID,
|
||||
uint32_t3 group_location: SV_GroupID, )
|
||||
{
|
||||
if (local_location.x >= value_count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Load last histogram into lds
|
||||
local_prefix[local_location.x] = histograms[indirect_workgroup_count[0].x + params.histogram_count * local_location.x];
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
// Perform hillis steele
|
||||
for (uint32_t offset = 1; offset < WG_THREAD_COUNT; offset *= 2)
|
||||
{
|
||||
uint32_t offset_value = select(local_location.x >= offset, local_prefix[local_location.x - offset], 0);
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
local_prefix[local_location.x] += offset_value;
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
histograms[indirect_workgroup_count[0].x + params.histogram_count * local_location.x] =
|
||||
select(local_location.x == 0, 0, local_prefix[local_location.x - 1]);
|
||||
}
|
||||
|
||||
struct SortToken
|
||||
{
|
||||
uint32_t tk;
|
||||
|
||||
__init(uint32_t digit, uint32_t index)
|
||||
{
|
||||
tk = (digit << 16) | (index & 0xFFFF);
|
||||
}
|
||||
|
||||
property uint32_t digit
|
||||
{
|
||||
get {
|
||||
return tk >> 16;
|
||||
}
|
||||
}
|
||||
|
||||
property uint32_t index
|
||||
{
|
||||
get {
|
||||
return tk & 0xFFFF;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
groupshared SortToken sort_tokens[WG_HISTO_ELEMENT];
|
||||
|
||||
// groupshared uint32_t local_prefix[WG_THREAD_COUNT];
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(WG_THREAD_COUNT, 1, 1)]
|
||||
void scatter_pass(
|
||||
uint32_t3 location: SV_DispatchThreadID,
|
||||
uint32_t3 local_location: SV_GroupThreadID,
|
||||
uint32_t3 group_location: SV_GroupID, )
|
||||
{
|
||||
// uint32_t batch_index = 0;
|
||||
uint32_t start = group_location.x * WG_HISTO_ELEMENT + local_location.x;
|
||||
uint32_t end = min(indirect_element_count[0], (group_location.x + 1) * WG_HISTO_ELEMENT);
|
||||
uint32_t element_count = indirect_element_count[0] - group_location.x * WG_HISTO_ELEMENT;
|
||||
for (uint32_t index = start;
|
||||
index < (group_location.x + 1) * WG_HISTO_ELEMENT;
|
||||
index += WG_THREAD_COUNT)
|
||||
{
|
||||
uint32_t local_index = index - group_location.x * WG_HISTO_ELEMENT;
|
||||
if (index < end)
|
||||
{
|
||||
uint32_t key = key_buffer[index];
|
||||
uint32_t digit = extract_digit(key, params.pass_index, params.descending);
|
||||
sort_tokens[local_index] = SortToken(digit, local_index);
|
||||
}
|
||||
else
|
||||
{
|
||||
sort_tokens[local_index] = SortToken(0xFFFF, local_index);
|
||||
}
|
||||
}
|
||||
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
// Split sort
|
||||
SortToken thread_tokens[WE_HISTO_ELEMENTS];
|
||||
uint32_t thread_prefix[WE_HISTO_ELEMENTS];
|
||||
for (uint32_t radix_pass = 0; radix_pass < 8; radix_pass++)
|
||||
{
|
||||
// Load tokens
|
||||
for (uint32_t i = 0; i < WE_HISTO_ELEMENTS; i++)
|
||||
{
|
||||
thread_tokens[i] = sort_tokens[i + WE_HISTO_ELEMENTS * local_location.x];
|
||||
}
|
||||
|
||||
// Compute local prefix
|
||||
uint32_t sum = 0;
|
||||
for (uint32_t i = 0; i < WE_HISTO_ELEMENTS; i++)
|
||||
{
|
||||
uint32_t bin_digit = (thread_tokens[i].digit >> radix_pass) & 1;
|
||||
thread_prefix[i] = sum;
|
||||
sum += 1 - bin_digit; // Count number of zeroes
|
||||
}
|
||||
|
||||
// Publish sum
|
||||
local_prefix[local_location.x] = sum;
|
||||
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
// Perform hillis steele
|
||||
for (uint32_t offset = 1; offset < WG_THREAD_COUNT; offset *= 2)
|
||||
{
|
||||
uint32_t offset_value = select(local_location.x >= offset, local_prefix[local_location.x - offset], 0);
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
local_prefix[local_location.x] += offset_value;
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
uint32_t total_zeroes = local_prefix[WG_THREAD_COUNT - 1];
|
||||
|
||||
// Scatter sort tokens
|
||||
|
||||
// Exclusive zero rank of block
|
||||
uint32_t zero_rank = select(local_location.x == 0, 0, local_prefix[local_location.x - 1]);
|
||||
for (uint32_t i = 0; i < WE_HISTO_ELEMENTS; i++)
|
||||
{
|
||||
uint32_t bin_digit = (thread_tokens[i].digit >> radix_pass) & 1;
|
||||
uint32_t index = i + local_location.x * WE_HISTO_ELEMENTS;
|
||||
uint32_t scatter_index = select(bin_digit == 0,
|
||||
thread_prefix[i] + zero_rank,
|
||||
total_zeroes + index - (thread_prefix[i] + zero_rank));
|
||||
sort_tokens[scatter_index] = thread_tokens[i];
|
||||
}
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
// Tokens are now sorted in the LDS
|
||||
// Boundary detection
|
||||
for (
|
||||
uint32_t i = local_location.x * WE_HISTO_ELEMENTS;
|
||||
i < min((local_location.x + 1) * WE_HISTO_ELEMENTS, element_count);
|
||||
i++)
|
||||
{
|
||||
SortToken token = sort_tokens[i];
|
||||
uint32_t digit = token.digit;
|
||||
if (i == 0 || sort_tokens[i - 1].digit != digit)
|
||||
{
|
||||
local_prefix[digit] = i;
|
||||
}
|
||||
}
|
||||
|
||||
// For each digit, we now know where it starts within the buffer
|
||||
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
// Scatter keys
|
||||
for (
|
||||
uint32_t i = local_location.x * WE_HISTO_ELEMENTS;
|
||||
i < min((local_location.x + 1) * WE_HISTO_ELEMENTS, element_count);
|
||||
i++)
|
||||
{
|
||||
uint32_t digit = sort_tokens[i].digit;
|
||||
uint32_t index = sort_tokens[i].index + group_location.x * WG_HISTO_ELEMENT;
|
||||
uint32_t group_offset = histograms[group_location.x + digit * params.histogram_count];
|
||||
uint32_t digit_offset = histograms[indirect_workgroup_count[0].x + digit * params.histogram_count];
|
||||
|
||||
uint32_t destination_index = group_offset + digit_offset + (i - local_prefix[digit]);
|
||||
|
||||
// dest_key_buffer[i] = local_prefix[local_location.x];
|
||||
// dest_key_buffer[i] = destination_index;
|
||||
// dest_key_buffer[i] = local_prefix[local_location.x];
|
||||
|
||||
dest_key_buffer[destination_index] = key_buffer[index];
|
||||
dest_value_buffer[destination_index] = value_buffer[index];
|
||||
}
|
||||
}
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(1, 1, 1)]
|
||||
void compute_counts_pass(
|
||||
uint32_t3 location: SV_DispatchThreadID,
|
||||
uint32_t3 local_location: SV_GroupThreadID,
|
||||
uint32_t3 group_location: SV_GroupID, )
|
||||
{
|
||||
uint32_t element_count = indirect_element_count[0];
|
||||
if (params.pass_index != 0)
|
||||
{
|
||||
element_count = params.pass_index;
|
||||
indirect_element_count[0] = params.pass_index;
|
||||
}
|
||||
|
||||
indirect_workgroup_count[0].x = div_ceil(element_count, WG_HISTO_ELEMENT);
|
||||
indirect_workgroup_count[0].y = 1;
|
||||
indirect_workgroup_count[0].z = 1;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
module toroidal_structure_table;
|
||||
|
||||
import voxel_cache;
|
||||
import voxel_tracing;
|
||||
|
||||
/// Parameters for the fixed structure table
|
||||
public struct ToroidalStructureTable
|
||||
{
|
||||
RWStructuredBuffer<StructurePointer> structure_table_pointer;
|
||||
RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
|
||||
}
|
||||
|
||||
public struct ToroidalStructureTableChunksCursor
|
||||
{
|
||||
// Offset of the block of chuks
|
||||
int32_t3 offset;
|
||||
int32_t3 current_voxel;
|
||||
float3 t_off;
|
||||
float3 t;
|
||||
|
||||
Ray r;
|
||||
}
|
||||
|
||||
int32_t imod(int32_t x, int32_t n)
|
||||
{
|
||||
int32_t r = x % n;
|
||||
return r < 0 ? r + n : r;
|
||||
}
|
||||
|
||||
/// Uses a fixed structure table as a dense array of chunks
|
||||
public struct ToroidalStructureTableTracer : IStructure
|
||||
{
|
||||
typedef ToroidalStructureTableChunksCursor Cursor;
|
||||
|
||||
public ToroidalStructureTable structure_table;
|
||||
public uint32_t3 extent;
|
||||
|
||||
public ToroidalStructureTableChunksCursor begin(Ray worldRay, Span s)
|
||||
{
|
||||
ToroidalStructureTableChunksCursor cursor;
|
||||
// Now march inside chunk bounds
|
||||
let start_position = worldRay.origin;
|
||||
|
||||
// FVT clamp to block
|
||||
cursor.current_voxel = int32_t3(floor(start_position));
|
||||
cursor.offset = cursor.current_voxel - int32_t3(this.extent) / 2;
|
||||
|
||||
cursor.t_off = abs(worldRay.invDirection);
|
||||
|
||||
// Take t of next boundary
|
||||
cursor.t = select(
|
||||
worldRay.direction > 0.,
|
||||
cursor.current_voxel + int32_t3(1) - start_position,
|
||||
start_position - cursor.current_voxel) *
|
||||
cursor.t_off;
|
||||
|
||||
// Add camera offset
|
||||
cursor.r = worldRay;
|
||||
return cursor;
|
||||
}
|
||||
|
||||
public bool next(inout Cursor c, out Cell cell)
|
||||
{
|
||||
while (all(c.current_voxel >= c.offset) && all(c.current_voxel < c.offset + int32_t3(extent)))
|
||||
{
|
||||
// Current hit
|
||||
let off = c.t - c.t_off;
|
||||
let t_adv = max(max(off.x, max(off.y, off.z)), 0.);
|
||||
let local_voxel =
|
||||
int32_t3(
|
||||
imod(c.current_voxel.x, int32_t(this.extent.x)),
|
||||
imod(c.current_voxel.y, int32_t(this.extent.y)),
|
||||
imod(c.current_voxel.z, int32_t(this.extent.z)));
|
||||
let chunk_index = local_voxel.x + local_voxel.z * this.extent.x + local_voxel.y * this.extent.x * this.extent.z;
|
||||
let position = c.r.origin + c.r.direction * t_adv;
|
||||
|
||||
var hit = false;
|
||||
if (this.structure_table.structure_table_pointer[chunk_index].subdivided_valid())
|
||||
{
|
||||
cell.cache_pointer = this.structure_table.structure_table_pointer[chunk_index].pointer();
|
||||
cell.local_ray.origin = position - float3(c.current_voxel);
|
||||
cell.local_ray.direction = c.r.direction;
|
||||
cell.local_ray.invDirection = c.r.invDirection;
|
||||
cell.t = t_adv;
|
||||
hit = true;
|
||||
}
|
||||
else if (this.structure_table.structure_table_pointer[chunk_index].subdivided())
|
||||
{
|
||||
this.structure_table.structure_table_request_buffer[chunk_index].add(1);
|
||||
hit = false;
|
||||
}
|
||||
|
||||
// Advance
|
||||
let min_mask = min_mask(c.t);
|
||||
c.t += select(min_mask, c.t_off, float3(0.));
|
||||
c.current_voxel += select(min_mask, int32_t3(sign(c.r.direction)), int32_t3(0));
|
||||
|
||||
if (hit)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool3 min_mask(float3 val)
|
||||
{
|
||||
let min_val = min(val.x, min(val.y, val.z));
|
||||
return val == min_val;
|
||||
}
|
||||
|
||||
float2 box_intersect(float3 origin, float3 ray_direction, float3 box_min, float3 box_max)
|
||||
{
|
||||
let min_ts = (box_min - origin) / ray_direction;
|
||||
let max_ts = (box_max - origin) / ray_direction;
|
||||
|
||||
let far_ts = max(min_ts, max_ts);
|
||||
let near_ts = min(min_ts, max_ts);
|
||||
|
||||
let far_t = min(far_ts.x, min(far_ts.y, far_ts.z));
|
||||
let near_t = max(near_ts.x, max(near_ts.y, near_ts.z));
|
||||
return float2(near_t, far_t);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
// import ray_cast;
|
||||
import voxel_cache;
|
||||
import fixed_structure_table;
|
||||
import toroidal_structure_table;
|
||||
import voxel_tracing;
|
||||
import lod_policies;
|
||||
|
||||
struct PushConstants
|
||||
{
|
||||
float4x4 view_proj;
|
||||
float3 cam_pos;
|
||||
uint32_t frame_timestamp;
|
||||
uint32_t width;
|
||||
uint32_t height;
|
||||
|
||||
uint32_t chunk_width;
|
||||
uint32_t chunk_height;
|
||||
uint32_t chunk_alt;
|
||||
}
|
||||
|
||||
public struct VertexOutput
|
||||
{
|
||||
public float4 position : SV_Position;
|
||||
|
||||
[vk::location(0)]
|
||||
public float3 world_position;
|
||||
|
||||
[vk::location(1)]
|
||||
public nointerpolation uint32_t structure_id;
|
||||
|
||||
[vk::location(2)]
|
||||
public float3 cam_position;
|
||||
|
||||
[vk::location(3)]
|
||||
public float3 chunk_position;
|
||||
}
|
||||
|
||||
[[vk::push_constant]]
|
||||
uniform PushConstants constants;
|
||||
|
||||
ParameterBlock<VoxelCacheParameters<2>> cache_parameters;
|
||||
ParameterBlock<ToroidalStructureTable> table_parameters;
|
||||
|
||||
public struct ColorHit<let N : uint32_t> : IVoxelHit<N>
|
||||
{
|
||||
public __init() {};
|
||||
|
||||
public bool shouldHit(VoxelCacheParameters<N> cache, uint32_t node_index, uint32_t child_index)
|
||||
{
|
||||
return ByteColor(cache.attributes_pool[0][node_index * 64 + child_index]).byte_a != 0;
|
||||
}
|
||||
}
|
||||
|
||||
// [[vk::binding(0, 0)]]
|
||||
// RWStructuredBuffer<StructurePoolElement> structure_pool;
|
||||
// [[vk::binding(1, 0)]]
|
||||
// RWStructuredBuffer<RequestBufferElement> request_buffer;
|
||||
// [[vk::binding(2, 0)]]
|
||||
// RWStructuredBuffer<uint32_t> usage_buffer;
|
||||
// [[vk::binding(3, 0)]]
|
||||
// RWStructuredBuffer<uint32_t> attributes_pool[2];
|
||||
//
|
||||
// [[vk::binding(0, 1)]]
|
||||
// RWStructuredBuffer<StructurePointer> structure_table_pointer;
|
||||
// [[vk::binding(1, 1)]]
|
||||
// RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
|
||||
|
||||
ByteColor fetch_color(uint32_t index, uint32_t child_index)
|
||||
{
|
||||
return ByteColor(cache_parameters.attributes_pool[0][index * 64 + child_index]);
|
||||
}
|
||||
|
||||
float3 fetch_normal(uint32_t index, uint32_t child_index)
|
||||
{
|
||||
let a = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3]);
|
||||
let b = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3 + 1]);
|
||||
let c = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3 + 2]);
|
||||
return float3(a, b, c);
|
||||
}
|
||||
|
||||
bool3 min_mask(float3 val)
|
||||
{
|
||||
let min_val = min(val.x, min(val.y, val.z));
|
||||
return val == min_val;
|
||||
}
|
||||
|
||||
[[vk::binding(0, 2)]]
|
||||
[[format("rgba32f")]]
|
||||
WTexture2D<float4> gbuffer_position;
|
||||
|
||||
[[vk::binding(1, 2)]]
|
||||
[[format("rgba32f")]]
|
||||
WTexture2D<float4> gbuffer_albedo;
|
||||
|
||||
[[vk::binding(2, 2)]]
|
||||
[[format("rgba32f")]]
|
||||
WTexture2D<float4> gbuffer_normal;
|
||||
|
||||
float3 get_ray_direction(uint32_t2 pixel_loc)
|
||||
{
|
||||
let ndc_loc_x = (float)pixel_loc.x / (float)constants.width * 2. - 1.;
|
||||
let ndc_loc_y = 1. - (float)pixel_loc.y / (float)constants.height * 2.;
|
||||
var world_loc = mul(constants.view_proj, float4(ndc_loc_x, ndc_loc_y, 1., 1.));
|
||||
world_loc /= world_loc.w;
|
||||
return normalize(world_loc.xyz - constants.cam_pos);
|
||||
}
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(16, 16, 1)]
|
||||
void gi_march(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID)
|
||||
{
|
||||
if (location.x >= constants.width || location.y >= constants.height)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
groupshared VoxelTraceStack stacks[256];
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(16, 16, 1)]
|
||||
void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID)
|
||||
{
|
||||
if (location.x >= constants.width || location.y >= constants.height)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let stack_index = local_location.x + local_location.y * 16;
|
||||
|
||||
VoxelCacheTracer<2, ColorHit<2>> cache_tracer;
|
||||
cache_tracer.parameters = cache_parameters;
|
||||
cache_tracer.report_usage = true;
|
||||
cache_tracer.report_requests = true;
|
||||
cache_tracer.frame_timestamp = constants.frame_timestamp;
|
||||
cache_tracer.voxel_hit = ColorHit<2>();
|
||||
|
||||
ToroidalStructureTableTracer table_tracer;
|
||||
table_tracer.structure_table = table_parameters;
|
||||
table_tracer.extent = uint32_t3(constants.chunk_width, constants.chunk_alt, constants.chunk_width);
|
||||
|
||||
let ray_direction = get_ray_direction(location.xy);
|
||||
|
||||
Ray r;
|
||||
r.origin = constants.cam_pos;
|
||||
r.direction = ray_direction;
|
||||
r.invDirection = 1.f / ray_direction;
|
||||
|
||||
PixelFootprintLod lod = PixelFootprintLod.create((100.f * 3.14f) / 180.f, 1080.f, 2.f);
|
||||
|
||||
Tracer<ToroidalStructureTableTracer, VoxelCacheTracer<2, ColorHit<2>>, PixelFootprintLod> tracer;
|
||||
tracer.structure = table_tracer;
|
||||
tracer.cache = cache_tracer;
|
||||
tracer.lod = lod;
|
||||
|
||||
Hit h;
|
||||
Span s;
|
||||
bool hit = tracer.trace(stacks[stack_index], h, r, s);
|
||||
|
||||
ToroidalStructureTableTracer.Cursor cursor = table_tracer.begin(r, s);
|
||||
Cell cell;
|
||||
|
||||
if (hit)
|
||||
{
|
||||
// Gather
|
||||
let hit_pos = h.hit_location;
|
||||
|
||||
let hit_normal = fetch_normal(h.node_index, h.child_index);
|
||||
var hit_albedo = float4(0.);
|
||||
hit_albedo = fetch_color(h.node_index, h.child_index).float_color;
|
||||
// let hit_albedo = hit.color;
|
||||
|
||||
gbuffer_position.Store(location.xy, float4(hit_pos, 1.));
|
||||
gbuffer_normal.Store(location.xy, float4(hit_normal, 1.));
|
||||
gbuffer_albedo.Store(location.xy, hit_albedo);
|
||||
}
|
||||
else
|
||||
{
|
||||
gbuffer_albedo.Store(location.xy, float4(0.));
|
||||
}
|
||||
}
|
||||
|
||||
float2 box_intersect(float3 origin, float3 ray_direction, float3 box_min, float3 box_max)
|
||||
{
|
||||
let min_ts = (box_min - origin) / ray_direction;
|
||||
let max_ts = (box_max - origin) / ray_direction;
|
||||
|
||||
let far_ts = max(min_ts, max_ts);
|
||||
let near_ts = min(min_ts, max_ts);
|
||||
|
||||
let far_t = min(far_ts.x, min(far_ts.y, far_ts.z));
|
||||
let near_t = max(near_ts.x, max(near_ts.y, near_ts.z));
|
||||
return float2(near_t, far_t);
|
||||
}
|
||||
|
||||
@@ -1,685 +0,0 @@
|
||||
struct VertexOutput
|
||||
{
|
||||
@builtin(position) postion: vec4<f32>,
|
||||
@location(0) @interpolate(flat) chunk_index: u32,
|
||||
@location(1) ndc: vec4<f32>,
|
||||
@location(2) color: vec4<f32>,
|
||||
@location(3) cam_pos: vec3<f32>,
|
||||
@location(4) world_pos: vec3<f32>,
|
||||
@location(5) @interpolate(flat) structure_id: u32,
|
||||
@location(6) chunk_position: vec3<f32>,
|
||||
}
|
||||
|
||||
struct ChunkImmediate
|
||||
{
|
||||
view_proj: mat4x4<f32>,
|
||||
cam_pos: vec3<f32>,
|
||||
frame_timestamp: u32,
|
||||
width: u32,
|
||||
downsampling_factor: u32,
|
||||
}
|
||||
|
||||
var<immediate> constants: ChunkImmediate;
|
||||
//var<push_constant> constants: ChunkInfo;
|
||||
|
||||
struct CacheChunkObject
|
||||
{
|
||||
transform: mat4x4<f32>,
|
||||
color: vec4<f32>,
|
||||
id: u32,
|
||||
pointer: u32,
|
||||
}
|
||||
|
||||
|
||||
struct StructurePoolElement
|
||||
{
|
||||
pointers: array<u32, 64>
|
||||
}
|
||||
|
||||
struct RequestBufferElement
|
||||
{
|
||||
requests: array<atomic<u32>, 64>
|
||||
}
|
||||
|
||||
struct ColorPoolElement
|
||||
{
|
||||
colors: array<u32, 64>
|
||||
}
|
||||
|
||||
struct LocationPoolElement
|
||||
{
|
||||
structure_id: u32,
|
||||
structure_locator: u32
|
||||
}
|
||||
|
||||
struct SortedRequestsElement
|
||||
{
|
||||
node: u32,
|
||||
child: u32
|
||||
}
|
||||
|
||||
fn unpack_color(color: u32) -> vec4<f32>
|
||||
{
|
||||
return vec4<f32>(
|
||||
f32(color & 0xFF) / 255.,
|
||||
f32((color >> 8) & 0xFF) / 255.,
|
||||
f32((color >> 16) & 0xFF) / 255.,
|
||||
f32((color >> 24) & 0xFF) / 255.
|
||||
);
|
||||
}
|
||||
|
||||
@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(2) var<storage, read_write> location_pool: array<LocationPoolElement>;
|
||||
@group(0) @binding(3) var<storage, read_write> request_buffer: array<RequestBufferElement>;
|
||||
@group(0) @binding(4) var<storage, read_write> usage_buffer: array<atomic<u32>>;
|
||||
@group(0) @binding(5) var<storage, read_write> structure_table_pointer: array<u32>;
|
||||
@group(0) @binding(6) var<storage, read_write> structure_table_request_buffer: array<atomic<u32>>;
|
||||
|
||||
@group(1) @binding(0) var prepass_depth: texture_2d<f32>;
|
||||
|
||||
@vertex
|
||||
fn chunk(@builtin(vertex_index) index: u32, @location(0) position: vec3<f32>, @location(1) id: u32) -> VertexOutput
|
||||
{
|
||||
let cube_vertices = array<vec3<f32>, 8>(
|
||||
vec3<f32>(0., 0., 0.),
|
||||
vec3<f32>(0., 0., 1.),
|
||||
vec3<f32>(1., 0., 1.),
|
||||
vec3<f32>(1., 0., 0.),
|
||||
|
||||
vec3<f32>(0., 1., 0.),
|
||||
vec3<f32>(0., 1., 1.),
|
||||
vec3<f32>(1., 1., 1.),
|
||||
vec3<f32>(1., 1., 0.),
|
||||
);
|
||||
|
||||
let cube_faces = array<u32, 24>(
|
||||
// Bottom face
|
||||
1, 0, 2, 3,
|
||||
|
||||
// Top face
|
||||
4, 5, 7, 6,
|
||||
|
||||
// Side faces
|
||||
0, 1, 4, 5,
|
||||
1, 2, 5, 6,
|
||||
2, 3, 6, 7,
|
||||
3, 0, 7, 4,
|
||||
);
|
||||
|
||||
let quad_index = index / (3 * 2);
|
||||
let triangle_index = index % (3 * 2);
|
||||
let triangle_map = array<u32, 6>(
|
||||
0, 1, 2, 1, 3, 2
|
||||
);
|
||||
|
||||
|
||||
let vertex = cube_vertices[cube_faces[quad_index * 4 + triangle_map[triangle_index]]];
|
||||
let output_vertex = constants.view_proj * vec4<f32>(vertex + position, 1.0f);
|
||||
|
||||
var output: VertexOutput;
|
||||
output.postion = output_vertex;
|
||||
output.ndc = output_vertex / output_vertex.w;
|
||||
output.color = vec4(1.);
|
||||
output.chunk_index = 0;
|
||||
output.cam_pos = constants.cam_pos;
|
||||
output.world_pos = vertex + position;
|
||||
output.structure_id = id;
|
||||
output.chunk_position = position;
|
||||
|
||||
//let output = vec4<f32>(vertex, 1.0f);
|
||||
return output;
|
||||
}
|
||||
|
||||
|
||||
struct StructureElement
|
||||
{
|
||||
children: array<u32, 64>
|
||||
}
|
||||
|
||||
struct ColorElement
|
||||
{
|
||||
children: array<vec4<f32>, 64>
|
||||
}
|
||||
|
||||
struct LocationElement
|
||||
{
|
||||
children: array<vec4<f32>, 64>
|
||||
}
|
||||
|
||||
struct RequestElement
|
||||
{
|
||||
children: array<atomic<u32>, 64>
|
||||
}
|
||||
|
||||
fn box_inter(pos: vec3<f32>, ray_dir: vec3<f32>, box_min: vec3<f32>, box_max: vec3<f32>) -> vec2<f32>
|
||||
{
|
||||
let box_min_t = (box_min - pos) / ray_dir;
|
||||
let box_max_t = (box_max - pos) / ray_dir;
|
||||
|
||||
let near_ts = min(box_min_t, box_max_t);
|
||||
let far_ts = max(box_min_t, box_max_t);
|
||||
|
||||
let far_t = min(min(far_ts.x, far_ts.y), far_ts.z);
|
||||
let near_t = max(max(near_ts.x, near_ts.y), near_ts.z);
|
||||
|
||||
return vec2(near_t, far_t);
|
||||
}
|
||||
|
||||
fn sdf(voxel: vec3<i32>) -> bool
|
||||
{
|
||||
let len = length(vec3<f32>(voxel) - vec3(128)) / 128.;
|
||||
return len <= 1.;
|
||||
}
|
||||
|
||||
fn min_vec(x: vec3<f32>) -> f32
|
||||
{
|
||||
return min(x.x, min(x.y, x.z));
|
||||
}
|
||||
|
||||
fn min_mask(x: vec3<f32>) -> vec3<bool>
|
||||
{
|
||||
let min = min(x.x, min(x.y, x.z));
|
||||
|
||||
return vec3<bool>(min == x.x, min == x.y, min == x.z);
|
||||
}
|
||||
|
||||
fn node_subdivided(node: u32) -> bool
|
||||
{
|
||||
return ((node >> 31) & 1) != 0;
|
||||
}
|
||||
|
||||
fn node_pointer_valid(node: u32) -> bool
|
||||
{
|
||||
return ((node >> 30) & 1) != 0;
|
||||
}
|
||||
|
||||
fn node_pointer(node: u32) -> u32
|
||||
{
|
||||
return node & 0x3FFFFFFF;
|
||||
}
|
||||
|
||||
fn voxel_from_wall(position: vec3<f32>, ray_dir: vec3<f32>) -> vec3<i32>
|
||||
{
|
||||
let integers = round(position);
|
||||
let wall_mask = min_mask(abs(position - vec3<f32>(integers)));
|
||||
let offsets = select(vec3<f32>(-0.5), vec3<f32>(0.5), ray_dir > vec3(0.));
|
||||
return vec3<i32>(floor(position + select(vec3<f32>(0.), offsets, wall_mask)));
|
||||
}
|
||||
|
||||
struct HitResult
|
||||
{
|
||||
color: vec4<f32>,
|
||||
hit_pos: vec3<f32>
|
||||
}
|
||||
|
||||
fn new_traverse(ray_dir: vec3<f32>, ray_origin: vec3<f32>, root_id: u32, dist_offset: f32) -> HitResult
|
||||
{
|
||||
let max_depth = 5;
|
||||
let dist_offset_voxel = dist_offset * f32(1 << u32(max_depth * 2));
|
||||
let fovy_deg = 100. / f32(constants.width);
|
||||
let fovy_rad = (fovy_deg * 3.14) / 180.;
|
||||
let cone_factor = 1.414 * f32(constants.downsampling_factor) * (tan(fovy_rad / 2.) * 2.); // How many pixels per distance a voxel takes
|
||||
|
||||
let st_pointer = structure_table_pointer[root_id];
|
||||
|
||||
if (!node_subdivided(st_pointer))
|
||||
{
|
||||
discard;
|
||||
var result: HitResult;
|
||||
result.color = vec4(0., 1., 0., 1.);
|
||||
result.hit_pos = ray_origin;
|
||||
return result;
|
||||
}
|
||||
if(!node_pointer_valid(st_pointer))
|
||||
{
|
||||
// Node is subdivided, but not valid
|
||||
// Send request on structure table
|
||||
atomicAdd(&structure_table_request_buffer[root_id], 1);
|
||||
|
||||
discard;
|
||||
var result: HitResult;
|
||||
result.color = vec4(0., 1., 0., 1.);
|
||||
result.hit_pos = ray_origin;
|
||||
return result;
|
||||
}
|
||||
//var current_node = node_pointer(st_pointer);
|
||||
|
||||
// Record usage
|
||||
var dfs_stack = array<u32, 6>(node_pointer(st_pointer), 0, 0, 0, 0, 0);
|
||||
var current_depth = 0;
|
||||
|
||||
usage_buffer[dfs_stack[current_depth]] = constants.frame_timestamp;
|
||||
|
||||
// Start location
|
||||
//let voxel_dir = select(vec3(-1), vec3(1), ray_dir >= vec3(0.));
|
||||
var node_shift = (max_depth - current_depth) * 2;
|
||||
|
||||
var child_size = 1 << u32(node_shift - 2);
|
||||
var node_size = 1 << u32(node_shift);
|
||||
|
||||
var pos_origin = clamp(ray_origin * f32(1 << u32(max_depth * 2)), vec3(0.), vec3(f32(node_size) - 1.));
|
||||
var voxel = vec3<i32>(pos_origin);
|
||||
var far_t = 0.;
|
||||
var inv_ray_dir = 1. / ray_dir;
|
||||
var ray_positive = ray_dir > vec3(0.);
|
||||
var step_dir = select(vec3(-1), vec3(1), ray_positive);
|
||||
var min_child_size = cone_factor * dist_offset_voxel;
|
||||
|
||||
for(var iter = 0; iter < 400; iter ++)
|
||||
{
|
||||
// Compute child position
|
||||
node_shift = (max_depth - current_depth) * 2;
|
||||
child_size = 1 << u32(node_shift - 2);
|
||||
|
||||
var child_pos = (voxel >> vec3(u32(node_shift - 2))) & vec3(3);
|
||||
var child_index = child_pos.x + child_pos.y * 4 + child_pos.z * 4 * 4;
|
||||
var current_node = dfs_stack[current_depth];
|
||||
var pointer = structure_pool[current_node].pointers[child_index];
|
||||
|
||||
min_child_size = (length(vec3<f32>(voxel) - pos_origin) + dist_offset_voxel) * cone_factor;
|
||||
while(node_subdivided(pointer) &&
|
||||
f32(child_size) / 4 > min_child_size
|
||||
)
|
||||
{
|
||||
if(!node_pointer_valid(pointer) && node_subdivided(pointer))
|
||||
{
|
||||
// Record request
|
||||
atomicAdd(&request_buffer[current_node].requests[child_pos.x + child_pos.y * 4 + child_pos.z * 4 * 4], 1);
|
||||
break;
|
||||
}
|
||||
|
||||
// Descend
|
||||
current_depth += 1;
|
||||
|
||||
node_shift = (max_depth - current_depth) * 2;
|
||||
child_size = 1 << u32(node_shift - 2);
|
||||
child_pos = (voxel >> vec3(u32(node_shift - 2))) & vec3(3);
|
||||
child_index = child_pos.x + child_pos.y * 4 + child_pos.z * 4 * 4;
|
||||
current_node = node_pointer(pointer);
|
||||
dfs_stack[current_depth] = current_node;
|
||||
|
||||
pointer = structure_pool[current_node].pointers[child_index];
|
||||
|
||||
// Record usage
|
||||
usage_buffer[current_node] = constants.frame_timestamp;
|
||||
}
|
||||
|
||||
|
||||
// Check color
|
||||
let color = color_pool[current_node].colors[child_index];
|
||||
if(((color >> 24) & 0xFF) != 0)
|
||||
{
|
||||
var result: HitResult;
|
||||
result.color = unpack_color(color);
|
||||
//result.color = vec4<f32>(f32(iter) / 400.);
|
||||
//result.hit_pos = (far_t / f32(1 << u32(max_depth * 2))) * ray_dir + ray_origin;
|
||||
result.hit_pos = (far_t * ray_dir + pos_origin) / f32(1 << u32(max_depth * 2));
|
||||
return result;
|
||||
}
|
||||
|
||||
// Advance
|
||||
child_pos = voxel & vec3(i32(0xFFFFFFFF << u32(node_shift - 2)));
|
||||
let far_wall = child_pos + select(vec3(0), vec3(child_size), ray_positive);
|
||||
let far_wall_inter = (vec3<f32>(far_wall) - pos_origin) * inv_ray_dir;
|
||||
far_t = min(min(far_wall_inter.x, far_wall_inter.y), far_wall_inter.z);
|
||||
|
||||
// Perform dda step on the children scale
|
||||
//let next_child = select(child_pos, child_pos + select(vec3(-1), vec3(1), ray_dir > vec3(0.)) * vec3(child_size), vec3(far_t) == far_wall_inter);
|
||||
let next_child = select(child_pos, child_pos + step_dir * vec3(child_size), vec3(far_t) == far_wall_inter);
|
||||
|
||||
let previous_voxel = voxel;
|
||||
voxel = clamp(vec3<i32>(pos_origin + far_t * ray_dir), next_child, next_child + vec3(child_size) - vec3(1));
|
||||
|
||||
if any(voxel < vec3(0)) || any(voxel >= vec3(1 << u32((max_depth * 2))))
|
||||
{
|
||||
discard;
|
||||
}
|
||||
|
||||
// We touched a voxel as if we explored blocks sized by the child size of the current node.
|
||||
// But we might have exited the current node.
|
||||
|
||||
// If this is the case we have to walk back up the tree
|
||||
// And then back down to the next node over
|
||||
|
||||
// As such we find the lowest ancestor that can contain both the privous voxel (in node) and the new voxel (out of node)
|
||||
let bit_diffs = voxel ^ previous_voxel;
|
||||
let bit_diffs_lowest = bit_diffs.x | bit_diffs.y | bit_diffs.z;
|
||||
|
||||
let common_depth = ((countLeadingZeros(bit_diffs_lowest) - i32(32 - max_depth * 2)) / 2);
|
||||
|
||||
current_depth = common_depth;
|
||||
//current_node = dfs_stack[current_depth];
|
||||
}
|
||||
|
||||
// Iter max color
|
||||
var result: HitResult;
|
||||
result.color = vec4(1., 0., 1., 1.);
|
||||
result.hit_pos = (far_t / f32(1 << u32(max_depth * 2))) * ray_dir + ray_origin;
|
||||
return result;
|
||||
}
|
||||
|
||||
struct FragmentOutput {
|
||||
@location(0) color: vec4<f32>,
|
||||
@builtin(frag_depth) depth: f32, // Equivalent to gl_FragDepth
|
||||
}
|
||||
|
||||
struct FragmentPrepassOutput {
|
||||
@location(0) depth_prepass: f32, // Equivalent to gl_FragDepth
|
||||
//@builtin(frag_depth) depth: f32, // Equivalent to gl_FragDepth
|
||||
}
|
||||
|
||||
|
||||
//fn fragment_prepass(in: VertexOutput) -> @location(0) vec4<f32>
|
||||
|
||||
//@early_depth_test(less_equal)
|
||||
@fragment
|
||||
fn fragment_prepass(in: VertexOutput) -> FragmentPrepassOutput
|
||||
{
|
||||
let ray_dir = normalize(in.world_pos - in.cam_pos);
|
||||
let interp = box_inter(in.cam_pos, ray_dir, in.chunk_position + vec3(0.), in.chunk_position + vec3(1));
|
||||
let ray_origin = in.cam_pos + ray_dir * max(interp.x, 0.) - in.chunk_position;
|
||||
|
||||
let result = new_traverse(ray_dir, ray_origin, in.structure_id, length(in.cam_pos - (ray_origin + in.chunk_position)));
|
||||
let clip_pos = constants.view_proj * vec4(result.hit_pos + in.chunk_position, 1.);
|
||||
let depth = clip_pos.z / clip_pos.w;
|
||||
var frag_out: FragmentPrepassOutput;
|
||||
|
||||
//frag_out.color = result.color;
|
||||
//frag_out.depth_prepass = in.postion.z;
|
||||
frag_out.depth_prepass = length(ray_origin + in.chunk_position - in.cam_pos);
|
||||
//frag_out.depth_prepass = interp.x;
|
||||
//frag_out.depth_prepass = 100.;
|
||||
//frag_out.depth = depth;
|
||||
|
||||
//frag_out.depth = depth;
|
||||
//frag_out.depth_prepass = depth;
|
||||
return frag_out;
|
||||
}
|
||||
|
||||
@early_depth_test(less_equal)
|
||||
@fragment
|
||||
fn fragment(in: VertexOutput) -> FragmentOutput
|
||||
{
|
||||
let surface_depth = in.postion.z;
|
||||
let prepass_depth_sample = textureLoad(prepass_depth, vec2<i32>(in.postion.xy), 0).x;
|
||||
let lin_depth = (100. * 0.01) / (100. - surface_depth * (100. - 0.01));
|
||||
|
||||
if lin_depth < prepass_depth_sample || prepass_depth_sample == -1.
|
||||
{
|
||||
discard;
|
||||
}
|
||||
|
||||
//frag_out.color = vec4<f32>(2 * 0.01 / (100. + 0.01 - depth * (100. - 0.01)));
|
||||
let ray_dir = normalize(in.world_pos - in.cam_pos);
|
||||
let prepass_origin = in.cam_pos + ray_dir * max(prepass_depth_sample - 0.01, 0.);
|
||||
let interp = box_inter(prepass_origin, ray_dir, in.chunk_position + vec3(0.), in.chunk_position + vec3(1));
|
||||
let ray_origin = prepass_origin + ray_dir * max(interp.x, 0.) - in.chunk_position;
|
||||
//let ray_origin = in.cam_pos + ray_dir * (max(0., lin_depth - 0.1)) - in.chunk_position;
|
||||
//let ray_origin = in.cam_pos + ray_dir * max(interp.x, 0.) - in.chunk_position;
|
||||
//let ray_origin = in.cam_pos + ray_dir * max(prepass_depth, 0.) - in.chunk_position;
|
||||
//let space_ro = in.cam_pos + ray_dir * lin_depth;
|
||||
//let ray_origin = space_ro - in.chunk_position;
|
||||
|
||||
|
||||
let result = new_traverse(ray_dir, ray_origin, in.structure_id, length(in.cam_pos - (ray_origin + in.chunk_position)));
|
||||
let clip_pos = constants.view_proj * vec4(result.hit_pos + in.chunk_position, 1.);
|
||||
let depth = clip_pos.z / clip_pos.w;
|
||||
var frag_out: FragmentOutput;
|
||||
frag_out.color = result.color;
|
||||
//frag_out.color = vec4<f32>(vec3<f32>(prepass_depth_sample) / 100., 1.);
|
||||
//frag_out.color = vec4<f32>(smpl);
|
||||
//frag_out.color = vec4<f32>(ray_origin, 1.);
|
||||
//frag_out.color = result.color;
|
||||
//frag_out.color = vec4<f32>(ray_origin, 1.);
|
||||
//frag_out.color = vec4<f32>(vec3<f32>(lin_depth) / 100., 1.);
|
||||
frag_out.depth = depth;
|
||||
return frag_out;
|
||||
|
||||
//return vec4<f32>(ray_origin, 1.);
|
||||
//return frag_out;
|
||||
//return vec4(interp.y / 10.);
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn _fragment(in: VertexOutput) -> FragmentOutput
|
||||
{
|
||||
//frag_out.color = vec4<f32>(2 * 0.01 / (100. + 0.01 - depth * (100. - 0.01)));
|
||||
let ray_dir = normalize(in.world_pos - in.cam_pos);
|
||||
let interp = box_inter(in.cam_pos - in.chunk_position, ray_dir, vec3(0.), vec3(1));
|
||||
let ray_origin = (in.cam_pos - in.chunk_position) + ray_dir * (max(0., interp.x));
|
||||
|
||||
let result = new_traverse(ray_dir, ray_origin, in.structure_id, length(in.cam_pos - (ray_origin + in.chunk_position)));
|
||||
let clip_pos = constants.view_proj * vec4(result.hit_pos + in.chunk_position, 1.);
|
||||
let depth = clip_pos.z / clip_pos.w;
|
||||
var frag_out: FragmentOutput;
|
||||
//frag_out.color = result.color;
|
||||
frag_out.color = result.color;
|
||||
//frag_out.color = vec4<f32>(smpl);
|
||||
//frag_out.color = vec4<f32>((2. * 0.01 * 100.) / (0.01 + 100. - prepass_depth * (100. - 0.01)));
|
||||
//frag_out.depth = depth;
|
||||
return frag_out;
|
||||
|
||||
//return vec4<f32>(ray_origin, 1.);
|
||||
//return frag_out;
|
||||
//return vec4(interp.y / 10.);
|
||||
}
|
||||
|
||||
/*
|
||||
@fragment
|
||||
fn fragment(in: VertexOutput) -> @location(0) vec4<f32>
|
||||
{
|
||||
let st = structure_table_pointer[0];
|
||||
let subdivided = ((st >> 31) & 1) != 0;
|
||||
let pointer_valid = ((st >> 30) & 1) != 0;
|
||||
// Request stuff
|
||||
atomicAdd(&structure_table_request_buffer[0], 1);
|
||||
if(subdivided && !pointer_valid)
|
||||
{
|
||||
return vec4(0., 1., 0., 1.);
|
||||
}
|
||||
return vec4(1., 0., 0., 1.);
|
||||
}
|
||||
*/
|
||||
|
||||
/*
|
||||
fn traverse(ray_dir: vec3<f32>, ray_origin: vec3<f32>, root_id: u32, dist_offset: f32) -> vec4<f32>
|
||||
{
|
||||
let st_pointer = structure_table_pointer[root_id];
|
||||
|
||||
if (!node_subdivided(st_pointer))
|
||||
{
|
||||
discard;
|
||||
return vec4(0., 1., 0., 1.);
|
||||
}
|
||||
if(!node_pointer_valid(st_pointer))
|
||||
{
|
||||
atomicAdd(&structure_table_request_buffer[root_id], 1);
|
||||
discard;
|
||||
return vec4(0., 1., 0., 1.);
|
||||
}
|
||||
|
||||
let fovy_deg = 100.;
|
||||
let fovy = 3.14159 * (fovy_deg / 180.);
|
||||
let definition = 1920.;
|
||||
let cone_fovy = fovy / definition;
|
||||
|
||||
let factor = 1.;
|
||||
let cone_size_factor = 2. * tan(cone_fovy) * factor;
|
||||
|
||||
// Current depth of the node we are exploring
|
||||
var current_depth = 0;
|
||||
|
||||
// Index of the current node's data
|
||||
var current_node = u32(st_pointer & 0x3FFFFFFF);
|
||||
usage_buffer[current_node] = constants.frame_timestamp;
|
||||
var dfs_stack = array<u32, 6>(current_node, 0, 0, 0, 0, 0);
|
||||
|
||||
|
||||
|
||||
// Lut of the node_size per depth
|
||||
var node_size_lut = array<i32, 6>(
|
||||
4 * 4 * 4 * 4 * 4,
|
||||
4 * 4 * 4 * 4,
|
||||
4 * 4 * 4,
|
||||
4 * 4,
|
||||
4,
|
||||
1,
|
||||
);
|
||||
|
||||
let local_dist_offset = dist_offset * f32(node_size_lut[0]);
|
||||
|
||||
|
||||
// Current node size
|
||||
var node_size = node_size_lut[0]; // 128
|
||||
|
||||
// Size of a child of this node
|
||||
var child_size = node_size / 4;
|
||||
|
||||
// Simple FVT
|
||||
let t_off = abs(1. / ray_dir);
|
||||
|
||||
// Start location
|
||||
let voxel_dir = select(vec3(-1), vec3(1), ray_dir >= vec3(0.));
|
||||
var pos_origin = clamp(ray_origin * f32(node_size), vec3(0.), vec3(f32(node_size) - 1.));
|
||||
var voxel = vec3<i32>(pos_origin);
|
||||
var last_voxel = voxel;
|
||||
|
||||
let wall_offset = select(vec3(0), vec3(1), ray_dir > vec3(0.));
|
||||
|
||||
let max_depth = u32(5);
|
||||
var adaptive_depth = i32(max_depth);
|
||||
var far_t = 0.;
|
||||
|
||||
let ray_dir_inv = 1. / ray_dir;
|
||||
let fma_offset = - pos_origin * ray_dir_inv;
|
||||
|
||||
//let depth_limit = 3;
|
||||
for(var iter = 0; iter < 400; iter ++)
|
||||
{
|
||||
|
||||
// Our ray is currently touching a voxel.
|
||||
// Descend to the lowest node that contains this voxel
|
||||
|
||||
// Position of the child we are in
|
||||
var child_pos = (vec3<u32>(voxel) >> vec3<u32>((max_depth - u32(current_depth + 1)) * 2)) & vec3<u32>(3); // Hardcode for 4-tree
|
||||
var child_index = child_pos.x + child_pos.y * 4 + child_pos.z * 4 * 4;
|
||||
|
||||
// Current node has been used. report
|
||||
usage_buffer[current_node] = constants.frame_timestamp;
|
||||
|
||||
while(
|
||||
node_subdivided(structure_pool[current_node].pointers[child_index]) &&
|
||||
(local_dist_offset + far_t) * cone_size_factor < f32(node_size_lut[current_depth])
|
||||
)
|
||||
{
|
||||
if(!node_pointer_valid(structure_pool[current_node].pointers[child_index]))
|
||||
{
|
||||
atomicAdd(&request_buffer[current_node].requests[child_index], 1);
|
||||
break;
|
||||
}
|
||||
// Child node is subdivided, we go in, save position in stack
|
||||
current_node = node_pointer(structure_pool[current_node].pointers[child_index]);
|
||||
usage_buffer[current_node] = constants.frame_timestamp;
|
||||
current_depth += 1;
|
||||
dfs_stack[current_depth] = current_node;
|
||||
node_size = node_size_lut[current_depth];
|
||||
|
||||
child_pos = (vec3<u32>(voxel) >> vec3<u32>((max_depth - u32(current_depth + 1)) * 2)) & vec3<u32>(3); // Hardcode for 4-tree
|
||||
child_index = child_pos.x + child_pos.y * 4 + child_pos.z * 4 * 4;
|
||||
child_size = node_size / 4;
|
||||
}
|
||||
usage_buffer[current_node] = constants.frame_timestamp;
|
||||
|
||||
|
||||
|
||||
|
||||
// At this point current_depth is the depth of the node that contains the voxel
|
||||
// child_pos and child_index relate to the specific child of the node that contains this voxel
|
||||
// It is guaranteed that the child is leave
|
||||
|
||||
// Check current leave's color
|
||||
let color = unpack_color(color_pool[current_node].colors[child_index]);
|
||||
if(color.w != 0.) // Not transparent
|
||||
{
|
||||
/*
|
||||
let k = child_pos.x + child_pos.y + child_pos.z;
|
||||
let w = voxel.x + voxel.y + voxel.z;
|
||||
let x = select(0.5, 1., k % 2 == 0) * select(0.8, 1., w % 2 == 0);
|
||||
|
||||
var div = 1;
|
||||
var overlay = 1.;
|
||||
for(var i = 1; i <= 5; i++)
|
||||
{
|
||||
let x = (voxel.x / div + voxel.y / div + voxel.z / div) % 2 == 0;
|
||||
overlay -= select(0., 1. / (f32(i) * 2.5), x);
|
||||
div *= 4;
|
||||
}
|
||||
*/
|
||||
|
||||
return color;
|
||||
//return overlay * color;
|
||||
}
|
||||
|
||||
// Voxel and whole child containing it is empty
|
||||
|
||||
// Perform a step through the children of the node
|
||||
let child_position = (voxel / child_size) * child_size;
|
||||
let far_corner = child_position + wall_offset * child_size;
|
||||
//let far_ts = (vec3<f32>(far_corner) - pos_origin) / ray_dir; // TODO: Turn into fma
|
||||
let far_ts = fma(vec3<f32>(far_corner), ray_dir_inv, fma_offset);
|
||||
far_t = min(min(far_ts.x, far_ts.y), far_ts.z);
|
||||
|
||||
let next_child_min = select(child_position, child_position + voxel_dir * child_size, vec3(far_t) == far_ts);
|
||||
let next_child_max = next_child_min + vec3(child_size) - vec3(1);
|
||||
|
||||
// The ray (far_t) is now touching the new child to explore
|
||||
// Find out which actual voxel we are touching
|
||||
let previous_voxel = voxel;
|
||||
let float_voxel = clamp(vec3<i32>(pos_origin + far_t * ray_dir), next_child_min, next_child_max);
|
||||
/*
|
||||
voxel = vec3<i32>(
|
||||
floor(
|
||||
select(
|
||||
float_voxel - vec3(0.5),
|
||||
float_voxel + vec3(0.5),
|
||||
ray_dir > vec3(0.)
|
||||
))
|
||||
);
|
||||
*/
|
||||
//voxel = vec3<i32>(round(float_voxel));
|
||||
//voxel = voxel_from_wall(float_voxel, ray_dir);
|
||||
//voxel = voxel_from_wall(float_voxel, ray_dir);
|
||||
voxel = float_voxel;
|
||||
if(any(voxel < vec3(0)) || any(voxel >= vec3(node_size_lut[0])))
|
||||
{
|
||||
//return vec4(f32(iter) / 100.);
|
||||
discard;
|
||||
}
|
||||
|
||||
// We touched a voxel as if we explored blocks sized by the child size of the current node.
|
||||
// But we might have exited the current node.
|
||||
|
||||
// If this is the case we have to walk back up the tree
|
||||
// And then back down to the next node over
|
||||
|
||||
// As such we find the lowest ancestor that can contain both the privous voxel (in node) and the new voxel (out of node)
|
||||
let bit_diffs = voxel ^ previous_voxel;
|
||||
let bit_diffs_lowest = bit_diffs.x | bit_diffs.y | bit_diffs.z;
|
||||
|
||||
let flb = ((countLeadingZeros(bit_diffs_lowest) - i32(32 - max_depth * 2)) / 2);
|
||||
let common_depth = flb;
|
||||
|
||||
current_depth = common_depth;
|
||||
node_size = node_size_lut[current_depth];
|
||||
child_size = node_size / 4;
|
||||
current_node = dfs_stack[current_depth];
|
||||
|
||||
// Figure out current voxel position
|
||||
//voxel = vec3<i32>(ray_origin + ray_dir * t);
|
||||
|
||||
}
|
||||
return vec4<f32>(1., 0., 1., 1.);
|
||||
|
||||
}
|
||||
*/
|
||||
@@ -0,0 +1,264 @@
|
||||
import voxel_tracing;
|
||||
|
||||
public struct ByteColor
|
||||
{
|
||||
public uint32_t byte_color;
|
||||
|
||||
public property uint32_t byte_r
|
||||
{
|
||||
get {
|
||||
return byte_color & 0xFF;
|
||||
}
|
||||
}
|
||||
|
||||
public property uint32_t byte_g
|
||||
{
|
||||
get {
|
||||
return (byte_color >> 8) & 0xFF;
|
||||
}
|
||||
}
|
||||
|
||||
public property uint32_t byte_b
|
||||
{
|
||||
get {
|
||||
return (byte_color >> 16) & 0xFF;
|
||||
}
|
||||
}
|
||||
|
||||
public property uint32_t byte_a
|
||||
{
|
||||
get {
|
||||
return byte_color >> 24;
|
||||
}
|
||||
}
|
||||
|
||||
public property float4 float_color
|
||||
{
|
||||
get {
|
||||
return float4(
|
||||
float(byte_r) / 255.,
|
||||
float(byte_g) / 255.,
|
||||
float(byte_b) / 255.,
|
||||
float(byte_a) / 255.);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public struct StructurePointer
|
||||
{
|
||||
uint32_t value;
|
||||
|
||||
public bool subdivided()
|
||||
{
|
||||
return (this.value & 0x80000000) != 0;
|
||||
}
|
||||
|
||||
public bool pointer_valid()
|
||||
{
|
||||
return (this.value & 0x40000000) != 0;
|
||||
}
|
||||
|
||||
public bool subdivided_valid()
|
||||
{
|
||||
return (this.value & 0xC0000000) == 0xC0000000;
|
||||
}
|
||||
|
||||
public uint32_t pointer()
|
||||
{
|
||||
return this.value & 0x3FFFFFFF;
|
||||
}
|
||||
}
|
||||
|
||||
public struct StructureElement
|
||||
{
|
||||
public uint32_t occupancy_low;
|
||||
public uint32_t occupancy_high;
|
||||
public StructurePointer pointers[64];
|
||||
}
|
||||
|
||||
public struct RequestBufferElement
|
||||
{
|
||||
public Atomic<uint32_t> requests[64];
|
||||
}
|
||||
|
||||
/// Everything needed to trace within a voxelCache, to be used with a parameter block
|
||||
public struct VoxelCacheParameters<let N : uint>
|
||||
{
|
||||
public RWStructuredBuffer<StructureElement> structure_pool;
|
||||
public RWStructuredBuffer<RequestBufferElement> request_buffer;
|
||||
public RWStructuredBuffer<uint32_t> usage_buffer;
|
||||
public RWStructuredBuffer<uint32_t> attributes_pool[N];
|
||||
}
|
||||
|
||||
public struct VoxelTraceStack
|
||||
{
|
||||
public uint32_t stack[5];
|
||||
}
|
||||
|
||||
uint32_t3 get_children_pos(float3 position, uint32_t scale_exp)
|
||||
{
|
||||
return (asuint(position) >> scale_exp) & 3;
|
||||
}
|
||||
|
||||
uint32_t get_children_index(float3 position, uint32_t scale_exp)
|
||||
{
|
||||
// Get mantissa bits for this scale exp an retain bits for the specific children
|
||||
uint32_t3 cell_position = (asuint(position) >> scale_exp) & 3;
|
||||
return cell_position.x + cell_position.y * 4 + cell_position.z * 4 * 4;
|
||||
}
|
||||
|
||||
uint64_t get_child_mask(uint32_t low, uint32_t high)
|
||||
{
|
||||
return ((uint64_t)high << 32) | (uint64_t)low;
|
||||
}
|
||||
|
||||
float3 floor_scale(float3 position, uint32_t scale_exp)
|
||||
{
|
||||
uint32_t mask = ~0u << scale_exp;
|
||||
return asfloat(asuint(position) & mask);
|
||||
}
|
||||
|
||||
float node_size(uint32_t scale_exp)
|
||||
{
|
||||
let mantissa_mask = ~(~0u << 23);
|
||||
return asfloat(((1 << scale_exp) & mantissa_mask | (127 << 23))) - 1.f;
|
||||
}
|
||||
|
||||
ByteColor fetch_color<let N : int>(VoxelCacheParameters<N> p, uint32_t index, uint32_t child_index)
|
||||
{
|
||||
return ByteColor(p.attributes_pool[0][index * 64 + child_index]);
|
||||
}
|
||||
|
||||
public interface IVoxelHit<let N : uint32_t>
|
||||
{
|
||||
public bool shouldHit(VoxelCacheParameters<N> parameters, uint32_t node_index, uint32_t child_index);
|
||||
}
|
||||
|
||||
public struct VoxelCacheTracer<let N : int, H : IVoxelHit<N>> : IVoxelCache
|
||||
{
|
||||
typedef VoxelTraceStack GroupSharedData;
|
||||
|
||||
public bool report_usage;
|
||||
public bool report_requests;
|
||||
public uint32_t frame_timestamp;
|
||||
public H voxel_hit;
|
||||
public VoxelCacheParameters<N> parameters;
|
||||
|
||||
public bool trace<L : ILodPolicy>(uint32_t root, inout VoxelTraceStack stack, Ray r, L lod, float offset_t, out Hit v)
|
||||
{
|
||||
// Ray mirroring
|
||||
r.origin += float3(1.);
|
||||
r.origin = clamp(r.origin, float(1.), asfloat(0x3fffffff));
|
||||
r.origin = select(r.direction > 0., asfloat(asuint(r.origin) ^ 0x007fffff), r.origin);
|
||||
uint32_t child_mirror = 0;
|
||||
if (r.direction.x > 0.)
|
||||
{
|
||||
child_mirror |= 3;
|
||||
}
|
||||
if (r.direction.y > 0.)
|
||||
{
|
||||
child_mirror |= 3 << 2;
|
||||
}
|
||||
if (r.direction.z > 0.)
|
||||
{
|
||||
child_mirror |= 3 << 4;
|
||||
}
|
||||
|
||||
let ray_direction = -abs(r.direction);
|
||||
|
||||
float t = 0.;
|
||||
float3 pos = r.origin;
|
||||
uint32_t scale_exp = 23 - 2;
|
||||
uint32_t current_node_index = root;
|
||||
if (this.report_usage)
|
||||
{
|
||||
this.parameters.usage_buffer[current_node_index] = this.frame_timestamp;
|
||||
}
|
||||
stack.stack[10 - scale_exp / 2] = current_node_index;
|
||||
|
||||
[loop]
|
||||
for (uint32_t iter = 0; iter < 500; iter++)
|
||||
{
|
||||
uint32_t child_index = get_children_index(pos, scale_exp) ^ child_mirror;
|
||||
StructurePointer current_node = this.parameters.structure_pool[current_node_index].pointers[child_index];
|
||||
|
||||
while (current_node.subdivided_valid() && !lod.shouldStop(offset_t + t, node_size(scale_exp)))
|
||||
{
|
||||
scale_exp -= 2;
|
||||
current_node_index = current_node.pointer();
|
||||
stack.stack[10 - scale_exp / 2] = current_node_index;
|
||||
child_index = get_children_index(pos, scale_exp) ^ child_mirror;
|
||||
current_node = this.parameters.structure_pool[current_node_index].pointers[child_index];
|
||||
// Write usage
|
||||
if (this.report_usage)
|
||||
{
|
||||
this.parameters.usage_buffer[current_node_index] = frame_timestamp;
|
||||
}
|
||||
}
|
||||
|
||||
// Request subdiv
|
||||
if (this.report_requests && !lod.shouldStop(t + offset_t, node_size(scale_exp)) && current_node.subdivided() && !current_node.pointer_valid())
|
||||
{
|
||||
this.parameters.request_buffer[current_node_index].requests[child_index].add(1);
|
||||
}
|
||||
|
||||
uint64_t occupancy = get_child_mask(
|
||||
this.parameters.structure_pool[current_node_index].occupancy_low,
|
||||
this.parameters.structure_pool[current_node_index].occupancy_high);
|
||||
|
||||
let occupied = ((occupancy >> child_index) & 1) != 0;
|
||||
// if (fetch_color(this.parameters, current_node_index, child_index).byte_a != 0)
|
||||
// if (fetch_color(cache, current_node_index, child_index).byte_a != 0)
|
||||
if (occupied && voxel_hit.shouldHit(this.parameters, current_node_index, child_index))
|
||||
{
|
||||
v.hit = true;
|
||||
v.node_index = current_node_index;
|
||||
v.child_index = child_index;
|
||||
v.hit_location =
|
||||
select(
|
||||
r.direction > 0.,
|
||||
asfloat(asuint(pos) ^ 0x007fffff),
|
||||
pos) -
|
||||
float3(1.);
|
||||
return true;
|
||||
}
|
||||
|
||||
uint32_t adv_scale_exp = scale_exp;
|
||||
if (((occupancy >> (child_index & 0b101010)) & 0x00330033) == 0)
|
||||
{
|
||||
adv_scale_exp++;
|
||||
}
|
||||
|
||||
// Perform dda
|
||||
// Compute correct exponent, and shift it into the exponent part of floatt
|
||||
let child_pos : float3 = floor_scale(pos, adv_scale_exp);
|
||||
// Intersection t
|
||||
let inter_ts : float3 = (child_pos - r.origin) / ray_direction;
|
||||
float inter_t = min(inter_ts.x, min(inter_ts.y, inter_ts.z));
|
||||
t = inter_t;
|
||||
// return float4(inter_t);
|
||||
|
||||
// Perform dda step
|
||||
// let neighbor_max = asint(child_pos) + select(inter_t == inter_ts, -1, (1 << adv_scale_exp) - 1);
|
||||
let neighbor_max = asint(child_pos) + select(inter_t == inter_ts, -1, (1 << adv_scale_exp) - 1);
|
||||
pos = min(r.origin + ray_direction * inter_t, asfloat(neighbor_max));
|
||||
|
||||
// Find most common ancestor
|
||||
uint32_t3 diffs = asuint(child_pos) ^ asuint(pos);
|
||||
uint32_t diff = (diffs.x | diffs.y | diffs.z);
|
||||
|
||||
int32_t common_depth = (1 + (22 - firstbithigh(diff)) / 2) * 2;
|
||||
if (common_depth <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
scale_exp = 23 - common_depth;
|
||||
current_node_index = stack.stack[10 - scale_exp / 2];
|
||||
}
|
||||
|
||||
v.hit = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
module voxel_tracing;
|
||||
|
||||
public struct Ray
|
||||
{
|
||||
public float3 origin;
|
||||
public float3 direction;
|
||||
public float3 invDirection;
|
||||
}
|
||||
|
||||
public struct Span
|
||||
{
|
||||
public float t0;
|
||||
public float t1;
|
||||
}
|
||||
|
||||
public struct Cell
|
||||
{
|
||||
/// Entry pointer into the cache
|
||||
public uint32_t cache_pointer; // entry into the cache
|
||||
|
||||
/// Ray to be traced inside the cache
|
||||
public Ray local_ray;
|
||||
|
||||
/// How much distance from the camera
|
||||
public float t;
|
||||
}
|
||||
|
||||
public interface IStructure
|
||||
{
|
||||
/// A cursor structure to keep ray state
|
||||
public associatedtype Cursor;
|
||||
|
||||
/// Begins tracing a certain ray, with a span
|
||||
public Cursor begin(Ray worldRay, Span s);
|
||||
|
||||
/// Returns whether it hits, updating the state, and returning a cell structure if hit.
|
||||
public bool next(inout Cursor c, out Cell cell); // next populated cell along the ray
|
||||
}
|
||||
|
||||
public interface ILodPolicy
|
||||
{
|
||||
/// cone / pixel-footprint termination
|
||||
public bool shouldStop(float t, float nodeSize);
|
||||
}
|
||||
|
||||
public struct Hit
|
||||
{
|
||||
public bool hit;
|
||||
|
||||
// Cache location
|
||||
public uint32_t node_index;
|
||||
public uint32_t child_index;
|
||||
public float3 hit_location;
|
||||
}
|
||||
|
||||
public interface IVoxelCache
|
||||
{
|
||||
// The voxel cache tracer needs to store a small stack.
|
||||
// Keeping it in registers is wastefull thus using groupshared memory is the best option
|
||||
associatedtype GroupSharedData;
|
||||
public bool trace<L : ILodPolicy>(uint32_t root, inout GroupSharedData data, Ray r, L lod, float offset_t, out Hit v);
|
||||
}
|
||||
|
||||
public struct Tracer<S : IStructure, C : IVoxelCache, L : ILodPolicy>
|
||||
{
|
||||
|
||||
public S structure;
|
||||
public C cache;
|
||||
public L lod;
|
||||
|
||||
public bool trace(inout C.GroupSharedData gsData, out Hit h, Ray r, Span s)
|
||||
{
|
||||
/* loop: next cell -> cache.trace -> early out */
|
||||
S.Cursor cursor = this.structure.begin(r, s);
|
||||
Cell cell;
|
||||
|
||||
h.hit = false;
|
||||
h.hit_location = float3(0.f);
|
||||
h.child_index = 0;
|
||||
h.node_index = 0;
|
||||
|
||||
while (this.structure.next(cursor, cell))
|
||||
{
|
||||
if (cache.trace(cell.cache_pointer, gsData, cell.local_ray, lod, cell.t, h))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
root = "."
|
||||
@@ -15,7 +15,7 @@ use winit::window::Window;
|
||||
pub struct EguiRenderer
|
||||
{
|
||||
state: State,
|
||||
renderer: Renderer,
|
||||
pub renderer: Renderer,
|
||||
frame_started: bool,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
use crate::gi_pipeline::sparse_set::GpuSparseSet;
|
||||
use crate::voxel_cache::VoxelCache;
|
||||
use crate::voxel_cache::{self};
|
||||
|
||||
mod sparse_set;
|
||||
|
||||
pub struct VoxelGiPipeline<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
voxel_cache: VoxelCache<N>,
|
||||
|
||||
/// Keeps a set of the leaves present in the cache.
|
||||
/// Kept in correspondancy with the leaf list attribute within the cache
|
||||
leaf_list: GpuSparseSet,
|
||||
leaf_list_attribute: usize,
|
||||
}
|
||||
|
||||
impl<const N: usize> VoxelGiPipeline<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
cache_size: usize,
|
||||
cache_layout: &mut voxel_cache::CacheLayout,
|
||||
) -> Self
|
||||
{
|
||||
let leaf_list_attribute = cache_layout.add_attribute(voxel_cache::CacheAttribute {
|
||||
label: Some("VoxelGiPipeline::leaf_list_pointer"),
|
||||
word_count: 1,
|
||||
init: voxel_cache::CacheAttributeInit::External,
|
||||
});
|
||||
|
||||
cache_layout.add_attribute(voxel_cache::CacheAttribute {
|
||||
label: Some("VoxelGiPipeline::radiance"),
|
||||
word_count: 3,
|
||||
init: voxel_cache::CacheAttributeInit::DontTouch,
|
||||
});
|
||||
|
||||
let voxel_cache = VoxelCache::new(device, cache_size, cache_layout);
|
||||
|
||||
Self {
|
||||
voxel_cache,
|
||||
leaf_list: GpuSparseSet::new(device, cache_size),
|
||||
leaf_list_attribute,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::gpu::create_multi_buffers_bind_group;
|
||||
use crate::gpu::create_multi_buffers_bind_group_layout;
|
||||
|
||||
/// To keep a set of voxel nodes in the cache
|
||||
pub struct GpuSparseSet
|
||||
{
|
||||
/// Maximum size of the set
|
||||
size: usize,
|
||||
|
||||
/// Contains pointers to nodes in the cache
|
||||
pointers_buffer: wgpu::Buffer,
|
||||
|
||||
/// Amount of elements in the set
|
||||
count_buffer: wgpu::Buffer,
|
||||
|
||||
bind_group: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
impl GpuSparseSet
|
||||
{
|
||||
pub fn new(device: &wgpu::Device, size: usize) -> Self
|
||||
{
|
||||
let pointers_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("GpuSparseSet::pointers_buffer"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
contents: bytemuck::cast_slice(&vec![0u32; size]),
|
||||
});
|
||||
|
||||
let count_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("GpuSparseSet::count_buffer"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
contents: bytemuck::bytes_of(&0u32),
|
||||
});
|
||||
|
||||
let bind_group_layout = Self::create_bind_group_layout(device);
|
||||
let bind_group = create_multi_buffers_bind_group(
|
||||
device,
|
||||
&bind_group_layout,
|
||||
&[&pointers_buffer, &count_buffer],
|
||||
Some("GpuSparseSet::bind_group"),
|
||||
);
|
||||
|
||||
Self {
|
||||
size,
|
||||
pointers_buffer,
|
||||
count_buffer,
|
||||
bind_group,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout
|
||||
{
|
||||
create_multi_buffers_bind_group_layout(device, 2, Some("GpuSparseSet::bind_group_layout"))
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
// Main common gpu parallel algorithms
|
||||
pub mod buffer_compactor;
|
||||
pub mod indirect_buffer;
|
||||
pub mod radix_sort;
|
||||
|
||||
// Utilities
|
||||
pub fn create_multi_buffers_bind_group_layout(
|
||||
device: &wgpu::Device,
|
||||
count: u32,
|
||||
label: Option<&str>,
|
||||
) -> wgpu::BindGroupLayout
|
||||
{
|
||||
let entries = (0..count)
|
||||
.map(|i| wgpu::BindGroupLayoutEntry {
|
||||
binding: i,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label,
|
||||
entries: &entries,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn create_multi_buffers_bind_group(
|
||||
device: &wgpu::Device,
|
||||
layout: &wgpu::BindGroupLayout,
|
||||
buffers: &[&wgpu::Buffer],
|
||||
label: Option<&str>,
|
||||
) -> wgpu::BindGroup
|
||||
{
|
||||
let entries = buffers
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, buffer)| wgpu::BindGroupEntry {
|
||||
binding: i as u32,
|
||||
resource: buffer.as_entire_binding(),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label,
|
||||
layout,
|
||||
entries: &entries,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn create_multi_buffers_bg_bg_layout(
|
||||
device: &wgpu::Device,
|
||||
buffers: &[&wgpu::Buffer],
|
||||
label: Option<&str>,
|
||||
) -> (wgpu::BindGroupLayout, wgpu::BindGroup)
|
||||
{
|
||||
let layout = create_multi_buffers_bind_group_layout(device, buffers.len() as u32, label);
|
||||
let bg = create_multi_buffers_bind_group(device, &layout, buffers, label);
|
||||
(layout, bg)
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
use bytemuck::bytes_of;
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferSlice;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::Device;
|
||||
use wgpu::ShaderStages;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
pub struct NonZeroBufferCompactor
|
||||
{
|
||||
size: usize,
|
||||
block_count: usize,
|
||||
reduced_buffer: Buffer,
|
||||
sum_buffer: Buffer,
|
||||
count_buffer_bg_layout: BindGroupLayout,
|
||||
compaction_bg: BindGroup,
|
||||
|
||||
reduce_sum_pipeline: ComputePipeline,
|
||||
partial_sum_pipeline: ComputePipeline,
|
||||
scatter_pipeline: ComputePipeline,
|
||||
}
|
||||
|
||||
impl NonZeroBufferCompactor
|
||||
{
|
||||
const THREAD_COUNT: usize = 256;
|
||||
pub fn new(device: &Device, size: usize) -> Self
|
||||
{
|
||||
let block_count = size.div_ceil(Self::THREAD_COUNT * 2);
|
||||
let reduced_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("indirect_buffer_reduced"),
|
||||
contents: bytemuck::cast_slice(vec![0u32; block_count + 1].as_slice()),
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
});
|
||||
|
||||
let sum_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("indirect_buffer_sum"),
|
||||
contents: bytemuck::cast_slice(
|
||||
vec![0u32; block_count * Self::THREAD_COUNT * 2].as_slice(),
|
||||
),
|
||||
usage: BufferUsages::STORAGE,
|
||||
});
|
||||
|
||||
let count_buffer_bg_layout =
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("count_buffer_bg_layout"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// Optional compacted layout
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let compaction_bg_layout =
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("count_buffer_bg_layout"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let compaction_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("compaction_bg"),
|
||||
layout: &compaction_bg_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: reduced_buffer.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: sum_buffer.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let compaction_pipeline_layout =
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("compaction_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&count_buffer_bg_layout), Some(&compaction_bg_layout)],
|
||||
immediate_size: size_of::<u32>() as u32, // Bool : Write to compacted buffer ?
|
||||
});
|
||||
|
||||
let compaction_shader_module = unsafe {
|
||||
device.create_shader_module_trusted(
|
||||
wgpu::ShaderModuleDescriptor {
|
||||
label: Some("compaction_shader_layout"),
|
||||
source: wgpu::ShaderSource::SpirV(wgpu::__macro_helpers::Cow::Borrowed(
|
||||
wgpu::include_spirv_source!("../../shaders/out/compaction.spv"),
|
||||
)),
|
||||
},
|
||||
wgpu::ShaderRuntimeChecks {
|
||||
bounds_checks: false,
|
||||
force_loop_bounding: false,
|
||||
ray_query_initialization_tracking: false,
|
||||
task_shader_dispatch_tracking: false,
|
||||
mesh_shader_primitive_indices_clamp: false,
|
||||
int_div_checks: false,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
let reduce_sum_pipeline =
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("reduce_sum_pipeline"),
|
||||
layout: Some(&compaction_pipeline_layout),
|
||||
module: &compaction_shader_module,
|
||||
entry_point: Some("block_sum"),
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
cache: None,
|
||||
});
|
||||
let partial_sum_pipeline =
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("partial_sum_pipeline "),
|
||||
layout: Some(&compaction_pipeline_layout),
|
||||
module: &compaction_shader_module,
|
||||
entry_point: Some("linear_reduced_sum"),
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
cache: None,
|
||||
});
|
||||
let scatter_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("uniform_add_pipeline"),
|
||||
layout: Some(&compaction_pipeline_layout),
|
||||
module: &compaction_shader_module,
|
||||
entry_point: Some("scatter"),
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
NonZeroBufferCompactor {
|
||||
size,
|
||||
block_count,
|
||||
reduced_buffer,
|
||||
sum_buffer,
|
||||
count_buffer_bg_layout,
|
||||
compaction_bg,
|
||||
reduce_sum_pipeline,
|
||||
partial_sum_pipeline,
|
||||
scatter_pipeline,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn total_sum_buffer(&self) -> BufferSlice<'_>
|
||||
{
|
||||
self.reduced_buffer
|
||||
.slice(((size_of::<u32>() * self.block_count) as u64)..)
|
||||
}
|
||||
|
||||
pub fn copy_count_to_buffer(&self, encoder: &mut CommandEncoder, target: &Buffer)
|
||||
{
|
||||
encoder.copy_buffer_to_buffer(
|
||||
&self.reduced_buffer,
|
||||
(size_of::<u32>() * self.block_count) as u64,
|
||||
target,
|
||||
0,
|
||||
size_of::<u32>() as u64,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn compact_buffer(
|
||||
&self,
|
||||
device: &Device,
|
||||
encoder: &mut CommandEncoder,
|
||||
count_buffer: &Buffer,
|
||||
index_buffer: &Buffer,
|
||||
compact_buffer: Option<&Buffer>,
|
||||
)
|
||||
{
|
||||
let count_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("count_buffer_bind_group"),
|
||||
layout: &self.count_buffer_bg_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: count_buffer.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: index_buffer.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: compact_buffer.unwrap_or(&count_buffer).as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("buffer_compactor_compute_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
compute_pass.set_bind_group(0, &count_buffer_bind_group, &[]);
|
||||
compute_pass.set_bind_group(1, &self.compaction_bg, &[]);
|
||||
|
||||
// Perform local running sum, then reduce
|
||||
compute_pass.set_pipeline(&self.reduce_sum_pipeline);
|
||||
compute_pass.dispatch_workgroups(self.block_count as u32, 1, 1);
|
||||
|
||||
// Partial sums are now in the reuced sum buffer. Perform linear naive runnig sum on it
|
||||
compute_pass.set_pipeline(&self.partial_sum_pipeline);
|
||||
compute_pass.dispatch_workgroups(1, 1, 1);
|
||||
|
||||
// We can now reapply the partial running sum on the subblocks
|
||||
compute_pass.set_pipeline(&self.scatter_pipeline);
|
||||
compute_pass.set_immediates(
|
||||
0,
|
||||
if compact_buffer.is_some()
|
||||
{
|
||||
bytes_of(&1)
|
||||
}
|
||||
else
|
||||
{
|
||||
bytes_of(&0)
|
||||
},
|
||||
);
|
||||
compute_pass.dispatch_workgroups(self.block_count as u32, 1, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
use wgpu::Buffer;
|
||||
use wgpu::CommandEncoder;
|
||||
|
||||
/// Provides utility object to manage indirect dispatches workgroup count computations on the GPU
|
||||
|
||||
/// Takes in a single u32, and computes the amount of workgroups to dispatch given a workgroup size
|
||||
pub struct IndirectBuffer1D
|
||||
{
|
||||
/// Buffer used in the indirect dispatch command
|
||||
indirect_buffer: wgpu::Buffer,
|
||||
|
||||
/// Buffer visible from compute shaders to compute the amount
|
||||
indirect_storage: wgpu::Buffer,
|
||||
indirect_storage_bind_group: wgpu::BindGroup,
|
||||
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
compute_pipeline: wgpu::ComputePipeline,
|
||||
}
|
||||
|
||||
impl IndirectBuffer1D
|
||||
{
|
||||
pub fn new(device: &wgpu::Device) -> Self
|
||||
{
|
||||
let indirect_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("IndirectBuffer1D::indirect_buffer"),
|
||||
size: size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
|
||||
usage: wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let indirect_storage = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("IndirectBuffer1D::indirect_storage"),
|
||||
size: size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("IndirectBuffer1D::bind_group_layout"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
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 bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("IndirectBuffer1D::bind_group"),
|
||||
layout: &bind_group_layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: indirect_storage.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
|
||||
let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("IndirectBuffer1D::shader_module"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
"
|
||||
struct IndirectDispatchArgs
|
||||
{
|
||||
x: u32,
|
||||
y: u32,
|
||||
z: u32
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var<storage, read_write> indirect_storage: IndirectDispatchArgs;
|
||||
@group(1) @binding(0) var<storage, read_write> user_count: u32;
|
||||
|
||||
var<immediate> workgroup_size: u32;
|
||||
|
||||
@compute
|
||||
@workgroup_size(1, 1, 1)
|
||||
fn main()
|
||||
{
|
||||
let workgroup_count = (user_count / workgroup_size) + select(u32(1), u32(0), user_count % workgroup_size == 0);
|
||||
|
||||
var args: IndirectDispatchArgs;
|
||||
args.x = workgroup_count;
|
||||
args.y = 1;
|
||||
args.z = 1;
|
||||
indirect_storage = args;
|
||||
}
|
||||
".into(),
|
||||
),
|
||||
});
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("IndirectBuffer1D::pipeline_layout"),
|
||||
bind_group_layouts: &[
|
||||
// Group 0: indirect args buffer
|
||||
Some(&bind_group_layout),
|
||||
// Group 1: user count buffer
|
||||
Some(&bind_group_layout),
|
||||
],
|
||||
|
||||
// workgroup size
|
||||
immediate_size: size_of::<u32>() as u32,
|
||||
});
|
||||
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("IndirectBuffer1D::pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("main"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
indirect_buffer,
|
||||
indirect_storage,
|
||||
indirect_storage_bind_group: bind_group,
|
||||
bind_group_layout,
|
||||
compute_pipeline: pipeline,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn workgroup_count(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut CommandEncoder,
|
||||
count_buffer: &Buffer,
|
||||
workgroup_size: u32,
|
||||
) -> &Buffer
|
||||
{
|
||||
// Transient bind group
|
||||
let user_count_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("IndirectBuffer1D::bind_group"),
|
||||
layout: &self.bind_group_layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: count_buffer.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
|
||||
{
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("IndirectBuffer1D::compute_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
pass.set_pipeline(&self.compute_pipeline);
|
||||
pass.set_bind_group(0, &self.indirect_storage_bind_group, &[]);
|
||||
pass.set_bind_group(1, &user_count_bind_group, &[]);
|
||||
pass.set_immediates(0, bytemuck::bytes_of(&workgroup_size));
|
||||
|
||||
pass.dispatch_workgroups(1, 1, 1);
|
||||
}
|
||||
|
||||
encoder.copy_buffer_to_buffer(
|
||||
&self.indirect_storage,
|
||||
0,
|
||||
&self.indirect_buffer,
|
||||
0,
|
||||
Some(self.indirect_storage.size()),
|
||||
);
|
||||
|
||||
&self.indirect_buffer
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
use std::num::NonZero;
|
||||
|
||||
use itertools::Itertools;
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePass;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::Device;
|
||||
use wgpu::QuerySet;
|
||||
use wgpu::ShaderStages;
|
||||
use wgpu::include_spirv;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RadixSortDirection
|
||||
{
|
||||
Ascending,
|
||||
Descending,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
|
||||
#[repr(C)]
|
||||
struct PassParameters
|
||||
{
|
||||
pass_index: u32,
|
||||
descending: u32,
|
||||
digit_stride: u32,
|
||||
}
|
||||
|
||||
pub struct RadixSorter
|
||||
{
|
||||
max_size: usize,
|
||||
histogram_count: usize,
|
||||
histo_block_count: usize,
|
||||
|
||||
histograms: Buffer,
|
||||
histograms_bind_group: BindGroup,
|
||||
|
||||
data_bind_group_layout: BindGroupLayout,
|
||||
|
||||
double_buffer_keys: Buffer,
|
||||
double_buffer_values: Buffer,
|
||||
double_buffer_bind_group: BindGroup,
|
||||
|
||||
// Counts buffer
|
||||
element_counts_buffer: Buffer,
|
||||
indirect_counts_storage: Buffer,
|
||||
indirect_counts: Buffer,
|
||||
|
||||
histogram_pass: ComputePipeline,
|
||||
prefix_sum_pass: ComputePipeline,
|
||||
total_prefix_sum_pass: ComputePipeline,
|
||||
scatter_pass: ComputePipeline,
|
||||
compute_counts_pass: ComputePipeline,
|
||||
|
||||
timing_query_set: QuerySet,
|
||||
pub timing_buffer: Buffer,
|
||||
}
|
||||
|
||||
impl RadixSorter
|
||||
{
|
||||
// How many total digits u32 => 32
|
||||
const TOTAL_BIN_DIGIT_COUNT: usize = 32;
|
||||
|
||||
// The size of a digit sorted per pass
|
||||
const DIGIT_SIZE: usize = 8;
|
||||
|
||||
// The amounts of value for this digit size : base
|
||||
const VALUE_COUNT: usize = 1 << Self::DIGIT_SIZE;
|
||||
|
||||
// Numbers of passes for full sort
|
||||
const PASS_COUNT: usize = Self::TOTAL_BIN_DIGIT_COUNT / Self::DIGIT_SIZE;
|
||||
|
||||
// Thread count per work group
|
||||
const WG_THREAD_COUNT: usize = 256;
|
||||
|
||||
// Elements managed per thread for histo build
|
||||
const WE_HISTO_ELEMENTS: usize = 16;
|
||||
|
||||
// Elements managed per workgroup for histo build
|
||||
const WG_HISTO_ELEMENTS: usize = Self::WG_THREAD_COUNT * Self::WE_HISTO_ELEMENTS;
|
||||
|
||||
pub fn new(device: &Device, max_size: usize) -> Self
|
||||
{
|
||||
// How many blocks (workgroups) for histobuild
|
||||
let histo_block_count = max_size.div_ceil(Self::WG_HISTO_ELEMENTS);
|
||||
|
||||
// Number of histograms to allocate
|
||||
let histogram_count = histo_block_count + 1;
|
||||
|
||||
let histograms = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("histograms_buffer"),
|
||||
size: (histogram_count * size_of::<u32>() * Self::VALUE_COUNT) as u64,
|
||||
usage: BufferUsages::STORAGE,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let histograms_bind_group_layout =
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("RadixSorter::histograms_bind_group_layout"),
|
||||
entries: &[
|
||||
// Histrograms
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
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 histograms_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("RadixSorter::histograms_bind_group"),
|
||||
layout: &histograms_bind_group_layout,
|
||||
entries: &[
|
||||
// Histrograms
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: histograms.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let double_buffer_keys = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("RadixSorter::double_buffer_keys"),
|
||||
size: (size_of::<u32>() * max_size) as u64,
|
||||
usage: BufferUsages::STORAGE,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let double_buffer_values = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("RadixSorter::double_buffer_values"),
|
||||
size: (size_of::<u32>() * max_size) as u64,
|
||||
usage: BufferUsages::STORAGE,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let element_counts_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("RadixSorter::element_counts_buffer"),
|
||||
size: size_of::<u32>() as u64,
|
||||
usage: BufferUsages::STORAGE,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let indirect_counts_storage = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("RadixSorter::element_counts_buffer"),
|
||||
size: size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let indirect_counts = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("RadixSorter::element_counts_buffer"),
|
||||
size: size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
|
||||
usage: BufferUsages::INDIRECT | BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let data_bind_group_layout =
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("RadixSorter::data_bind_group_layout"),
|
||||
entries: &[
|
||||
// Keys
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
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,
|
||||
},
|
||||
// Values
|
||||
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: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let double_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("RadixSorter::double_buffer_bind_group"),
|
||||
layout: &data_bind_group_layout,
|
||||
entries: &[
|
||||
// Keys
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: double_buffer_keys.as_entire_binding(),
|
||||
},
|
||||
// Values
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: double_buffer_values.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let pipelines_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("RadixSorter::pipelines_layout"),
|
||||
bind_group_layouts: &[
|
||||
Some(&histograms_bind_group_layout),
|
||||
// Double buffering :
|
||||
// Source buffer
|
||||
Some(&data_bind_group_layout),
|
||||
// Dest buffer
|
||||
Some(&data_bind_group_layout),
|
||||
// Counts buffer
|
||||
Some(&data_bind_group_layout),
|
||||
],
|
||||
immediate_size: size_of::<PassParameters>() as u32, // for the pass number
|
||||
});
|
||||
|
||||
let radix_sort_shader_module =
|
||||
device.create_shader_module(include_spirv!("../../shaders/out/radix_sort.spv"));
|
||||
|
||||
let compilation_options = wgpu::PipelineCompilationOptions {
|
||||
zero_initialize_workgroup_memory: false,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let histogram_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("RadixSorter::histogram_pass"),
|
||||
layout: Some(&pipelines_layout),
|
||||
module: &radix_sort_shader_module,
|
||||
entry_point: Some("histogram_pass"),
|
||||
compilation_options: compilation_options.clone(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let prefix_sum_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("RadixSorter::prefix_sum_pass"),
|
||||
layout: Some(&pipelines_layout),
|
||||
module: &radix_sort_shader_module,
|
||||
entry_point: Some("prefix_sum_pass"),
|
||||
compilation_options: compilation_options.clone(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let total_prefix_sum_pass =
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("RadixSorter::total_prefix_sum_pass"),
|
||||
layout: Some(&pipelines_layout),
|
||||
module: &radix_sort_shader_module,
|
||||
entry_point: Some("total_prefix_sum_pass"),
|
||||
compilation_options: compilation_options.clone(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let scatter_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("RadixSorter::scatter_pass"),
|
||||
layout: Some(&pipelines_layout),
|
||||
module: &radix_sort_shader_module,
|
||||
entry_point: Some("scatter_pass"),
|
||||
compilation_options: compilation_options.clone(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let compute_counts_pass =
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("RadixSorter::compute_counts_pass"),
|
||||
layout: Some(&pipelines_layout),
|
||||
module: &radix_sort_shader_module,
|
||||
entry_point: Some("compute_counts_pass"),
|
||||
compilation_options: compilation_options.clone(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let timing_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("RadixSorter::timing_buffer"),
|
||||
size: (size_of::<u64>() * 2) as u64,
|
||||
usage: BufferUsages::QUERY_RESOLVE | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let timing_query_set = device.create_query_set(&wgpu::QuerySetDescriptor {
|
||||
label: Some("RadixSorter::timing_query_set"),
|
||||
ty: wgpu::QueryType::Timestamp,
|
||||
count: 2,
|
||||
});
|
||||
|
||||
RadixSorter {
|
||||
max_size,
|
||||
histo_block_count,
|
||||
histogram_count,
|
||||
histograms,
|
||||
histograms_bind_group,
|
||||
|
||||
data_bind_group_layout,
|
||||
|
||||
double_buffer_keys,
|
||||
double_buffer_values,
|
||||
double_buffer_bind_group,
|
||||
|
||||
element_counts_buffer,
|
||||
indirect_counts_storage,
|
||||
indirect_counts,
|
||||
|
||||
histogram_pass,
|
||||
prefix_sum_pass,
|
||||
total_prefix_sum_pass,
|
||||
scatter_pass,
|
||||
compute_counts_pass,
|
||||
|
||||
timing_buffer,
|
||||
timing_query_set,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sort(
|
||||
&self,
|
||||
device: &Device,
|
||||
keys: &Buffer,
|
||||
values: &Buffer,
|
||||
indirect: Option<&Buffer>,
|
||||
direct_length: Option<usize>,
|
||||
encoder: &mut CommandEncoder,
|
||||
sort_direction: RadixSortDirection,
|
||||
)
|
||||
{
|
||||
let data_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("RadixSorter::data_buffer_bind_group"),
|
||||
layout: &self.data_bind_group_layout,
|
||||
entries: &[
|
||||
// Keys
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: keys.as_entire_binding(),
|
||||
},
|
||||
// Values
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: values.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let counts_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("RadixSorter::double_buffer_bind_group"),
|
||||
layout: &self.data_bind_group_layout,
|
||||
entries: &[
|
||||
// Keys
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: indirect
|
||||
.unwrap_or(&self.element_counts_buffer)
|
||||
.as_entire_binding(),
|
||||
},
|
||||
// Values
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: self.indirect_counts_storage.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let bg = [&data_buffer_bind_group, &self.double_buffer_bind_group];
|
||||
|
||||
// Compute counts
|
||||
{
|
||||
let mut counts_compute_pass =
|
||||
encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("RadixSorter::counts_compute_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
let parameters = PassParameters {
|
||||
pass_index: if indirect.is_some()
|
||||
{
|
||||
0
|
||||
}
|
||||
else
|
||||
{
|
||||
direct_length.unwrap_or(self.max_size) as u32
|
||||
},
|
||||
descending: 0,
|
||||
digit_stride: 0,
|
||||
};
|
||||
let bytes = bytemuck::bytes_of(¶meters);
|
||||
|
||||
counts_compute_pass.set_pipeline(&self.compute_counts_pass);
|
||||
|
||||
counts_compute_pass.set_bind_group(0, &self.histograms_bind_group, &[]);
|
||||
counts_compute_pass.set_bind_group(1, bg[0], &[]);
|
||||
counts_compute_pass.set_bind_group(2, bg[1], &[]);
|
||||
counts_compute_pass.set_bind_group(3, &counts_bind_group, &[]);
|
||||
|
||||
counts_compute_pass.set_immediates(0, bytes);
|
||||
counts_compute_pass.dispatch_workgroups(1, 1, 1);
|
||||
}
|
||||
|
||||
// Copy indrect counts to indrect compatible buffer
|
||||
encoder.copy_buffer_to_buffer(
|
||||
&self.indirect_counts_storage,
|
||||
0,
|
||||
&self.indirect_counts,
|
||||
0,
|
||||
size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
|
||||
);
|
||||
|
||||
let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("RadixSorter::compute_pass"),
|
||||
timestamp_writes: Some(wgpu::ComputePassTimestampWrites {
|
||||
query_set: &self.timing_query_set,
|
||||
beginning_of_pass_write_index: Some(0),
|
||||
end_of_pass_write_index: Some(1),
|
||||
}),
|
||||
});
|
||||
|
||||
for i in 0..Self::PASS_COUNT
|
||||
{
|
||||
let parameters = PassParameters {
|
||||
pass_index: i as u32,
|
||||
descending: match sort_direction
|
||||
{
|
||||
RadixSortDirection::Ascending => 0,
|
||||
RadixSortDirection::Descending => 1,
|
||||
},
|
||||
digit_stride: self.histogram_count as u32,
|
||||
};
|
||||
let bytes = bytemuck::bytes_of(¶meters);
|
||||
|
||||
compute_pass.set_bind_group(0, &self.histograms_bind_group, &[]);
|
||||
compute_pass.set_bind_group(1, bg[i % 2], &[]);
|
||||
compute_pass.set_bind_group(2, bg[1 - (i % 2)], &[]);
|
||||
compute_pass.set_bind_group(3, &counts_bind_group, &[]);
|
||||
|
||||
// ~~ Histogram pass
|
||||
compute_pass.set_pipeline(&self.histogram_pass);
|
||||
compute_pass.set_immediates(0, bytes);
|
||||
compute_pass.dispatch_workgroups_indirect(&self.indirect_counts, 0);
|
||||
//compute_pass.dispatch_workgroups(self.histo_block_count as u32, 1, 1);
|
||||
|
||||
// ~~ Prefix sum pass
|
||||
compute_pass.set_pipeline(&self.prefix_sum_pass);
|
||||
compute_pass.set_immediates(0, bytes);
|
||||
compute_pass.dispatch_workgroups(Self::VALUE_COUNT as u32, 1, 1);
|
||||
|
||||
compute_pass.set_pipeline(&self.total_prefix_sum_pass);
|
||||
compute_pass.set_immediates(0, bytes);
|
||||
compute_pass.dispatch_workgroups(1, 1, 1);
|
||||
|
||||
// ~~ Scatter pass
|
||||
compute_pass.set_pipeline(&self.scatter_pass);
|
||||
compute_pass.set_immediates(0, bytes);
|
||||
compute_pass.dispatch_workgroups_indirect(&self.indirect_counts, 0);
|
||||
//compute_pass.dispatch_workgroups(self.histo_block_count as u32, 1, 1);
|
||||
}
|
||||
|
||||
// Even number of passes => data is in the user buffer
|
||||
drop(compute_pass);
|
||||
|
||||
encoder.resolve_query_set(&self.timing_query_set, 0..2, &self.timing_buffer, 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,715 @@
|
||||
use std::marker::PhantomData;
|
||||
use std::ops::Deref;
|
||||
use std::ops::DerefMut;
|
||||
|
||||
use egui::Ui;
|
||||
use egui::vec2;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePass;
|
||||
use wgpu::Device;
|
||||
use wgpu::QuerySet;
|
||||
use wgpu::Queue;
|
||||
|
||||
pub mod memory_profiler;
|
||||
|
||||
macro_rules! begin_frame {
|
||||
($encoder:ident) => {
|
||||
let mut $encoder = $encoder.begin_frame(None);
|
||||
};
|
||||
|
||||
($encoder:ident, $name:literal) => {
|
||||
let mut $encoder = $encoder.begin_frame(Some($name));
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! begin_scope {
|
||||
($scope:ident, $name:literal) => {
|
||||
let mut $scope = $scope.begin_scope($name);
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use begin_frame;
|
||||
pub(crate) use begin_scope;
|
||||
|
||||
pub struct ScopeEncoder<'enc, 'prof_enc, T>
|
||||
{
|
||||
encoder: &'prof_enc mut ProfilingEncoder<'enc>,
|
||||
scope_index: usize,
|
||||
_phantom: PhantomData<T>,
|
||||
}
|
||||
|
||||
pub struct Scope
|
||||
{
|
||||
name: &'static str,
|
||||
start_index: QuerySetHandle,
|
||||
end_index: Option<QuerySetHandle>,
|
||||
children: Vec<usize>,
|
||||
}
|
||||
|
||||
pub struct ProfilingEncoder<'enc>
|
||||
{
|
||||
device: Device,
|
||||
encoder: &'enc mut CommandEncoder,
|
||||
query_set_allocator: QuerySetAllocator,
|
||||
scopes: Vec<Scope>,
|
||||
index_stack: Vec<usize>,
|
||||
|
||||
// Stores a compute pass when currently in one
|
||||
compute_pass: Option<(usize, ComputePass<'static>)>,
|
||||
}
|
||||
|
||||
pub struct GpuProfile
|
||||
{
|
||||
scopes: Vec<Scope>,
|
||||
timestamps: Buffer,
|
||||
}
|
||||
|
||||
pub struct Frame
|
||||
{
|
||||
pub name: &'static str,
|
||||
pub children: Vec<usize>,
|
||||
|
||||
pub start_timestamp: u64,
|
||||
pub end_timestamp: u64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Profile
|
||||
{
|
||||
pub frames: Vec<Frame>,
|
||||
}
|
||||
|
||||
impl<'enc> ProfilingEncoder<'enc>
|
||||
{
|
||||
pub fn new(device: &Device, encoder: &'enc mut CommandEncoder) -> Self
|
||||
{
|
||||
Self {
|
||||
encoder,
|
||||
query_set_allocator: QuerySetAllocator::new(device),
|
||||
scopes: Vec::new(),
|
||||
device: device.clone(),
|
||||
index_stack: Vec::new(),
|
||||
compute_pass: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn begin_frame<'prof_enc>(
|
||||
&'prof_enc mut self,
|
||||
frame_name: Option<&'static str>,
|
||||
) -> ScopeEncoder<'enc, 'prof_enc, CommandEncoder>
|
||||
{
|
||||
let scope_index = self.begin_scope(None, frame_name.unwrap_or("Frame"));
|
||||
self.index_stack.push(scope_index);
|
||||
ScopeEncoder {
|
||||
encoder: self,
|
||||
scope_index,
|
||||
_phantom: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn begin_scope(&mut self, scope_index: Option<usize>, name: &'static str) -> usize
|
||||
{
|
||||
let begin_query = self.query_set_allocator.allocate();
|
||||
|
||||
if let Some((_, pass)) = &mut self.compute_pass
|
||||
{
|
||||
self.query_set_allocator
|
||||
.write_compute_timestamp(pass, &begin_query);
|
||||
}
|
||||
else
|
||||
{
|
||||
self.query_set_allocator
|
||||
.write_timestamp(self.encoder, &begin_query);
|
||||
}
|
||||
|
||||
let scope = Scope {
|
||||
name,
|
||||
start_index: begin_query,
|
||||
end_index: None,
|
||||
children: Vec::new(),
|
||||
};
|
||||
|
||||
let new_scope_index = self.scopes.len();
|
||||
self.scopes.push(scope);
|
||||
self.index_stack.push(new_scope_index);
|
||||
|
||||
// Add this new stack to parent
|
||||
if let Some(scope_index) = scope_index
|
||||
{
|
||||
self.scopes[scope_index].children.push(new_scope_index);
|
||||
}
|
||||
|
||||
new_scope_index
|
||||
}
|
||||
|
||||
fn end_scope(&mut self, scope_index: usize)
|
||||
{
|
||||
let end_query = self.query_set_allocator.allocate();
|
||||
if let Some((_, pass)) = &mut self.compute_pass
|
||||
{
|
||||
self.query_set_allocator
|
||||
.write_compute_timestamp(pass, &end_query);
|
||||
}
|
||||
else
|
||||
{
|
||||
self.query_set_allocator
|
||||
.write_timestamp(self.encoder, &end_query);
|
||||
}
|
||||
let scope = &mut self.scopes[scope_index];
|
||||
let pop = self.index_stack.pop().unwrap();
|
||||
|
||||
assert_eq!(
|
||||
pop, scope_index,
|
||||
"Scopes must be defined in a stack fashion."
|
||||
);
|
||||
|
||||
scope.end_index = Some(end_query);
|
||||
}
|
||||
|
||||
pub fn finish_profiler(self) -> GpuProfile
|
||||
{
|
||||
let timestamp_count = self.query_set_allocator.allocated_count();
|
||||
let resolve_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("ProfilingEncoder::resolve_buffer"),
|
||||
size: size_of::<u64>() as u64 * timestamp_count as u64,
|
||||
usage: BufferUsages::QUERY_RESOLVE | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
self.query_set_allocator
|
||||
.resolve_all(self.encoder, &resolve_buffer);
|
||||
|
||||
GpuProfile {
|
||||
scopes: self.scopes,
|
||||
timestamps: resolve_buffer,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc, CommandEncoder>
|
||||
{
|
||||
pub fn begin_profiled_compute_pass<'scope>(
|
||||
&'scope mut self,
|
||||
label: &'static str,
|
||||
) -> ScopeEncoder<'enc, 'scope, ComputePass<'static>>
|
||||
{
|
||||
let new_scope = self.encoder.begin_scope(Some(self.scope_index), label);
|
||||
let compute_pass = self
|
||||
.encoder
|
||||
.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some(label),
|
||||
timestamp_writes: None,
|
||||
})
|
||||
.forget_lifetime();
|
||||
|
||||
self.encoder.compute_pass = Some((new_scope, compute_pass));
|
||||
|
||||
ScopeEncoder {
|
||||
encoder: self.encoder,
|
||||
scope_index: new_scope,
|
||||
_phantom: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn begin_scope<'scope>(
|
||||
&'scope mut self,
|
||||
name: &'static str,
|
||||
) -> ScopeEncoder<'enc, 'scope, CommandEncoder>
|
||||
where
|
||||
'prof_enc: 'scope,
|
||||
{
|
||||
let scope_index = self.encoder.begin_scope(Some(self.scope_index), name);
|
||||
ScopeEncoder {
|
||||
encoder: self.encoder,
|
||||
scope_index,
|
||||
_phantom: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn end_scope(self)
|
||||
{
|
||||
drop(self);
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc, ComputePass<'static>>
|
||||
{
|
||||
pub fn begin_scope<'scope>(
|
||||
&'scope mut self,
|
||||
name: &'static str,
|
||||
) -> ScopeEncoder<'enc, 'scope, ComputePass<'static>>
|
||||
where
|
||||
'prof_enc: 'scope,
|
||||
{
|
||||
let scope_index = self.encoder.begin_scope(Some(self.scope_index), name);
|
||||
ScopeEncoder {
|
||||
encoder: self.encoder,
|
||||
scope_index,
|
||||
_phantom: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn end_scope(self)
|
||||
{
|
||||
drop(self);
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc, 'prof_enc, T> Drop for ScopeEncoder<'enc, 'prof_enc, T>
|
||||
{
|
||||
fn drop(&mut self)
|
||||
{
|
||||
if let Some((parent_scope, _)) = self.encoder.compute_pass
|
||||
&& parent_scope == self.scope_index
|
||||
{
|
||||
// Finish compute pass by droping it
|
||||
self.encoder.compute_pass = None;
|
||||
}
|
||||
self.encoder.end_scope(self.scope_index);
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc, 'prof_enc> DerefMut for ScopeEncoder<'enc, 'prof_enc, CommandEncoder>
|
||||
{
|
||||
fn deref_mut(&mut self) -> &mut Self::Target
|
||||
{
|
||||
&mut *self.encoder
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc, 'prof_enc> Deref for ScopeEncoder<'enc, 'prof_enc, CommandEncoder>
|
||||
{
|
||||
type Target = CommandEncoder;
|
||||
fn deref(&self) -> &Self::Target
|
||||
{
|
||||
&*self.encoder
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc, 'prof_enc> DerefMut for ScopeEncoder<'enc, 'prof_enc, ComputePass<'static>>
|
||||
{
|
||||
fn deref_mut(&mut self) -> &mut Self::Target
|
||||
{
|
||||
&mut self.encoder.compute_pass.as_mut().unwrap().1
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc, 'prof_enc> Deref for ScopeEncoder<'enc, 'prof_enc, ComputePass<'static>>
|
||||
{
|
||||
type Target = ComputePass<'static>;
|
||||
fn deref(&self) -> &Self::Target
|
||||
{
|
||||
&self.encoder.compute_pass.as_ref().unwrap().1
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc> DerefMut for ProfilingEncoder<'enc>
|
||||
{
|
||||
fn deref_mut(&mut self) -> &mut Self::Target
|
||||
{
|
||||
self.encoder
|
||||
}
|
||||
}
|
||||
|
||||
impl<'enc> Deref for ProfilingEncoder<'enc>
|
||||
{
|
||||
type Target = CommandEncoder;
|
||||
fn deref(&self) -> &Self::Target
|
||||
{
|
||||
self.encoder
|
||||
}
|
||||
}
|
||||
|
||||
struct QuerySetAllocator
|
||||
{
|
||||
device: Device,
|
||||
current_size: u32,
|
||||
current_id: u32,
|
||||
query_sets: Vec<(u32, u32, QuerySet)>,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
struct QuerySetHandle(usize, u32, u32);
|
||||
|
||||
impl QuerySetHandle
|
||||
{
|
||||
pub fn index(&self) -> usize
|
||||
{
|
||||
self.2 as usize
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for QuerySetHandle
|
||||
{
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering>
|
||||
{
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for QuerySetHandle
|
||||
{
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering
|
||||
{
|
||||
match self.0.cmp(&other.0)
|
||||
{
|
||||
core::cmp::Ordering::Equal =>
|
||||
{}
|
||||
ord => return ord,
|
||||
}
|
||||
self.1.cmp(&other.1)
|
||||
}
|
||||
}
|
||||
|
||||
impl QuerySetAllocator
|
||||
{
|
||||
pub fn new(device: &Device) -> Self
|
||||
{
|
||||
let current_size = 32;
|
||||
let query_sets = vec![(
|
||||
0,
|
||||
current_size,
|
||||
Self::new_query_set(device, current_size, 0),
|
||||
)];
|
||||
QuerySetAllocator {
|
||||
query_sets,
|
||||
current_size,
|
||||
current_id: 0,
|
||||
device: device.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn allocated_count(&self) -> u32
|
||||
{
|
||||
self.query_sets
|
||||
.iter()
|
||||
.map(|(allocated, _, _)| *allocated)
|
||||
.sum()
|
||||
}
|
||||
|
||||
pub fn resolve_all(&self, encoder: &mut CommandEncoder, target: &Buffer)
|
||||
{
|
||||
let mut offset = 0;
|
||||
for (allocated, _, query_set) in self.query_sets.iter()
|
||||
{
|
||||
encoder.resolve_query_set(query_set, 0..*allocated, target, offset);
|
||||
|
||||
offset += *allocated as u64 * size_of::<u64>() as u64;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn allocate(&mut self) -> QuerySetHandle
|
||||
{
|
||||
// Check if allocation is possible
|
||||
if self
|
||||
.query_sets
|
||||
.last()
|
||||
.is_some_and(|(allocated, available, _)| allocated == available)
|
||||
{
|
||||
// No more room, allocate new query set
|
||||
self.current_size *= 2;
|
||||
self.query_sets.push((
|
||||
0,
|
||||
self.current_size,
|
||||
Self::new_query_set(&self.device, self.current_size, self.query_sets.len()),
|
||||
));
|
||||
}
|
||||
|
||||
// Last allocation is guaranteed to have room
|
||||
let (allocated, _available, _query_set) = self.query_sets.last_mut().unwrap();
|
||||
|
||||
let query_index = *allocated;
|
||||
*allocated += 1;
|
||||
|
||||
let query_set_index = self.query_sets.len() - 1;
|
||||
|
||||
let id = self.current_id;
|
||||
self.current_id += 1;
|
||||
|
||||
QuerySetHandle(query_set_index, query_index, id)
|
||||
}
|
||||
|
||||
fn new_query_set(device: &Device, size: u32, index: usize) -> QuerySet
|
||||
{
|
||||
device.create_query_set(&wgpu::QuerySetDescriptor {
|
||||
label: Some(format!("QuerySetAllocator::query_set_{index}").as_str()),
|
||||
ty: wgpu::QueryType::Timestamp,
|
||||
count: size,
|
||||
})
|
||||
}
|
||||
|
||||
fn write_timestamp(&mut self, encoder: &mut CommandEncoder, handle: &QuerySetHandle)
|
||||
{
|
||||
let query_set = &self.query_sets[handle.0].2;
|
||||
encoder.write_timestamp(query_set, handle.1);
|
||||
}
|
||||
|
||||
fn write_compute_timestamp(&mut self, pass: &mut ComputePass, handle: &QuerySetHandle)
|
||||
{
|
||||
let query_set = &self.query_sets[handle.0].2;
|
||||
pass.write_timestamp(query_set, handle.1);
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuProfile
|
||||
{
|
||||
pub fn read_back(
|
||||
self,
|
||||
device: &Device,
|
||||
queue: &Queue,
|
||||
mut callback: impl FnMut(Profile) + Send + Sync + 'static,
|
||||
)
|
||||
{
|
||||
// Readback timestamps
|
||||
wgpu::util::DownloadBuffer::read_buffer(
|
||||
device,
|
||||
queue,
|
||||
&self.timestamps.slice(..),
|
||||
move |buffer| {
|
||||
let buffer = buffer.unwrap();
|
||||
let timestamps: Vec<u64> = bytemuck::pod_collect_to_vec(&buffer);
|
||||
let start = timestamps.first().copied().unwrap_or(0);
|
||||
let frames = self
|
||||
.scopes
|
||||
.into_iter()
|
||||
.map(|scope| Frame {
|
||||
name: scope.name,
|
||||
children: scope.children,
|
||||
start_timestamp: timestamps[scope.start_index.index()] - start,
|
||||
end_timestamp: timestamps[scope.end_index.unwrap().index()] - start,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
callback(Profile { frames });
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl Profile
|
||||
{
|
||||
pub fn to_display_string(&self, q: f32) -> String
|
||||
{
|
||||
let mut str = String::new();
|
||||
self.frames[0].build_string(&self.frames, 0, q, &mut str);
|
||||
str
|
||||
}
|
||||
|
||||
pub fn show(&self, ui: &mut Ui, q: f32)
|
||||
{
|
||||
if !self.frames.is_empty()
|
||||
{
|
||||
self.frames[0].show(ui, q, &self.frames);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Frame
|
||||
{
|
||||
fn time(&self, q: f32) -> f32
|
||||
{
|
||||
(self.end_timestamp - self.start_timestamp) as f32 * q
|
||||
}
|
||||
|
||||
fn start(&self, q: f32) -> f32
|
||||
{
|
||||
self.start_timestamp as f32 * q
|
||||
}
|
||||
|
||||
fn end(&self, q: f32) -> f32
|
||||
{
|
||||
self.end_timestamp as f32 * q
|
||||
}
|
||||
|
||||
fn build_string(&self, frames: &Vec<Frame>, depth: usize, q: f32, str: &mut String)
|
||||
{
|
||||
let mut depth_string = String::new();
|
||||
(0..depth).for_each(|_| depth_string.push_str(" "));
|
||||
|
||||
let time = (self.end_timestamp - self.start_timestamp) as f32 * q;
|
||||
str.push_str(&format!("{depth_string}{}: {:.2}\n", self.name, time));
|
||||
|
||||
self.children
|
||||
.iter()
|
||||
.for_each(|c| frames[*c].build_string(frames, depth + 1, q, str));
|
||||
}
|
||||
|
||||
pub fn show(&self, ui: &mut Ui, q: f32, frames: &Vec<Frame>)
|
||||
{
|
||||
let id = ui.make_persistent_id(self.name);
|
||||
egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true)
|
||||
.show_header(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(self.name);
|
||||
|
||||
// Right-aligned label, laid out first from the right edge
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.label(format!("{:.2}ms", self.time(q)));
|
||||
|
||||
// Whatever space remains between the two labels:
|
||||
// draw a thin line across it, vertically centered.
|
||||
let rect = ui.available_rect_before_wrap();
|
||||
let y = rect.center().y;
|
||||
ui.painter().hline(
|
||||
rect.x_range(),
|
||||
y,
|
||||
ui.visuals().widgets.noninteractive.bg_stroke,
|
||||
);
|
||||
});
|
||||
});
|
||||
})
|
||||
.body(|ui| {
|
||||
self.children
|
||||
.iter()
|
||||
.for_each(|i| frames[*i].show(ui, q, frames));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Profile
|
||||
{
|
||||
// Clauderies
|
||||
pub fn show_flamegraph(&self, id: egui::Id, q: f32, ui: &mut Ui) -> egui::Response
|
||||
{
|
||||
if self.frames.is_empty()
|
||||
{
|
||||
return ui.label("empty");
|
||||
}
|
||||
let row_height = 20.;
|
||||
// Full time range and max depth of the tree.
|
||||
let mut full = (f64::INFINITY, f64::NEG_INFINITY);
|
||||
let mut max_depth = 0usize;
|
||||
let mut stack: Vec<(usize, usize)> = [0].iter().map(|&r| (r, 0)).collect();
|
||||
while let Some((i, d)) = stack.pop()
|
||||
{
|
||||
let s = &self.frames[i];
|
||||
full = (full.0.min(s.start(q) as f64), full.1.max(s.end(q) as f64));
|
||||
max_depth = max_depth.max(d);
|
||||
stack.extend(s.children.iter().map(|&c| (c, d + 1)));
|
||||
}
|
||||
if full.0 >= full.1
|
||||
{
|
||||
full = (0.0, 1.0); // empty or degenerate input
|
||||
}
|
||||
|
||||
// The view is stored as fractions of the full range (not absolute times), so it
|
||||
// stays valid when the data changes from frame to frame.
|
||||
let fspan = full.1 - full.0;
|
||||
let norm: (f64, f64) = ui.data_mut(|d| d.get_temp(id)).unwrap_or((0.0, 1.0));
|
||||
let mut view = (full.0 + norm.0 * fspan, full.0 + norm.1 * fspan);
|
||||
if !(view.1 > view.0) || !view.0.is_finite() || !view.1.is_finite()
|
||||
{
|
||||
view = full;
|
||||
}
|
||||
|
||||
let size = vec2(ui.available_width(), (max_depth + 1) as f32 * row_height);
|
||||
let (resp, painter) = ui.allocate_painter(size, egui::Sense::click_and_drag());
|
||||
let rect = resp.rect;
|
||||
let w = rect.width().max(1.0) as f64;
|
||||
|
||||
// --- interaction ---
|
||||
let mut span = view.1 - view.0;
|
||||
if resp.dragged()
|
||||
{
|
||||
let dt = -(resp.drag_delta().x as f64) / w * span;
|
||||
view = (view.0 + dt, view.1 + dt);
|
||||
}
|
||||
if let Some(p) = resp.hover_pos()
|
||||
{
|
||||
let (zoom, scroll) = ui.input(|i| (i.zoom_delta(), i.smooth_scroll_delta.y));
|
||||
let z = zoom as f64 * (scroll as f64 * 0.005).exp();
|
||||
if (z - 1.0).abs() > 1e-6
|
||||
{
|
||||
let frac = ((p.x - rect.left()) as f64 / w).clamp(0.0, 1.0);
|
||||
let t_cursor = view.0 + frac * span;
|
||||
span = (span / z).clamp((full.1 - full.0) * 1e-6, (full.1 - full.0) * 10.0);
|
||||
view = (t_cursor - frac * span, t_cursor + (1.0 - frac) * span);
|
||||
}
|
||||
}
|
||||
if resp.double_clicked()
|
||||
{
|
||||
view = full;
|
||||
}
|
||||
//ui.data_mut(|d| d.insert_temp(id, view));
|
||||
ui.data_mut(|d| d.insert_temp(id, ((view.0 - full.0) / fspan, (view.1 - full.0) / fspan)));
|
||||
|
||||
let span = view.1 - view.0;
|
||||
|
||||
let to_x = |t: f64| rect.left() + ((t - view.0) / span) as f32 * rect.width();
|
||||
|
||||
// --- drawing ---
|
||||
painter.rect_filled(rect, 0.0, ui.visuals().extreme_bg_color);
|
||||
let font = egui::FontId::proportional(12.0);
|
||||
let hover = resp.hover_pos();
|
||||
let mut hovered: Option<usize> = None;
|
||||
|
||||
let mut stack: Vec<(usize, usize)> = [0].iter().map(|&r| (r, 0)).collect();
|
||||
while let Some((i, depth)) = stack.pop()
|
||||
{
|
||||
let s = &self.frames[i];
|
||||
let start = s.start(q) as f64;
|
||||
let end = s.end(q) as f64;
|
||||
if end < view.0 || start > view.1
|
||||
{
|
||||
continue; // off-screen: children are inside the parent, skip them too
|
||||
}
|
||||
let (x0, x1) = (to_x(start).max(rect.left()), to_x(end).min(rect.right()));
|
||||
if x1 - x0 < 0.5
|
||||
{
|
||||
continue; // too thin to see
|
||||
}
|
||||
let y = rect.top() + depth as f32 * row_height;
|
||||
let r = egui::Rect::from_min_max(egui::pos2(x0, y), egui::pos2(x1, y + row_height))
|
||||
.shrink2(vec2(0.5, 0.5));
|
||||
|
||||
let is_hovered = hover.is_some_and(|p| r.contains(p));
|
||||
if is_hovered
|
||||
{
|
||||
hovered = Some(i);
|
||||
}
|
||||
let mut color = color_for(&s.name);
|
||||
if is_hovered
|
||||
{
|
||||
color = color.gamma_multiply(1.15);
|
||||
}
|
||||
painter.rect_filled(r, 2.0, color);
|
||||
if r.width() > 24.0
|
||||
{
|
||||
painter.with_clip_rect(r).text(
|
||||
r.left_center() + vec2(3.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
&s.name,
|
||||
font.clone(),
|
||||
egui::Color32::BLACK,
|
||||
);
|
||||
}
|
||||
stack.extend(s.children.iter().map(|&c| (c, depth + 1)));
|
||||
}
|
||||
|
||||
if let Some(i) = hovered
|
||||
{
|
||||
let s = &self.frames[i];
|
||||
let start = s.start(q) as f64;
|
||||
let end = s.end(q) as f64;
|
||||
resp.clone().on_hover_ui_at_pointer(|ui| {
|
||||
ui.strong(s.name);
|
||||
ui.label(format!("duration: {:.3}", end - start));
|
||||
ui.label(format!("start: {:.3} end: {:.3}", start, end));
|
||||
});
|
||||
}
|
||||
resp
|
||||
}
|
||||
}
|
||||
|
||||
/// Stable pastel color derived from the scope name.
|
||||
fn color_for(name: &str) -> egui::Color32
|
||||
{
|
||||
let mut h: u32 = 2166136261; // FNV-1a
|
||||
for b in name.bytes()
|
||||
{
|
||||
h = (h ^ b as u32).wrapping_mul(16777619);
|
||||
}
|
||||
egui::ecolor::Hsva::new((h % 360) as f32 / 360.0, 0.45, 0.9, 1.0).into()
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
use std::ops::Deref;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
pub struct Buffer
|
||||
{
|
||||
pub label: String,
|
||||
pub size: usize,
|
||||
}
|
||||
|
||||
pub struct Group
|
||||
{
|
||||
pub label: &'static str,
|
||||
size: Option<usize>,
|
||||
pub buffers: Vec<Buffer>,
|
||||
pub sub_groups: Vec<Group>,
|
||||
}
|
||||
|
||||
impl Group
|
||||
{
|
||||
pub fn new(label: &'static str) -> Self
|
||||
{
|
||||
Self {
|
||||
label,
|
||||
size: None,
|
||||
buffers: Vec::new(),
|
||||
sub_groups: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn size(&self) -> usize
|
||||
{
|
||||
self.size.unwrap_or_else(|| {
|
||||
self.buffers.iter().map(|b| b.size).sum::<usize>()
|
||||
+ self.sub_groups.iter().map(Self::size).sum::<usize>()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn size_mut(&mut self) -> usize
|
||||
{
|
||||
*self.size.get_or_insert_with(|| {
|
||||
self.buffers.iter().map(|b| b.size).sum::<usize>()
|
||||
+ self
|
||||
.sub_groups
|
||||
.iter_mut()
|
||||
.map(Self::size_mut)
|
||||
.sum::<usize>()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MemoryProfile
|
||||
{
|
||||
stack: Vec<Group>,
|
||||
}
|
||||
|
||||
pub struct Device<'a>
|
||||
{
|
||||
device: wgpu::Device,
|
||||
profile: &'a mut MemoryProfile,
|
||||
}
|
||||
|
||||
impl<'a> Device<'a>
|
||||
{
|
||||
pub fn create_buffer(&mut self, desc: &wgpu::BufferDescriptor) -> wgpu::Buffer
|
||||
{
|
||||
let buffer = self.device.create_buffer(desc);
|
||||
self.profile.add_buffer(Buffer {
|
||||
label: desc.label.unwrap_or("Unnamed").into(),
|
||||
size: desc.size as usize,
|
||||
});
|
||||
buffer
|
||||
}
|
||||
|
||||
pub fn create_buffer_init(&mut self, desc: &wgpu::util::BufferInitDescriptor) -> wgpu::Buffer
|
||||
{
|
||||
let buffer = self.device.create_buffer_init(desc);
|
||||
self.profile.add_buffer(Buffer {
|
||||
label: desc.label.unwrap_or("Unnamed").into(),
|
||||
size: desc.contents.len(),
|
||||
});
|
||||
buffer
|
||||
}
|
||||
|
||||
pub fn group<'b>(&'b mut self, group_label: &'static str) -> Device<'b>
|
||||
where
|
||||
'a: 'b,
|
||||
{
|
||||
self.profile.open_group(group_label);
|
||||
Device {
|
||||
device: self.device.clone(),
|
||||
profile: self.profile,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Drop for Device<'a>
|
||||
{
|
||||
fn drop(&mut self)
|
||||
{
|
||||
self.profile.close_group();
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Device<'_>
|
||||
{
|
||||
type Target = wgpu::Device;
|
||||
|
||||
fn deref(&self) -> &Self::Target
|
||||
{
|
||||
&self.device
|
||||
}
|
||||
}
|
||||
|
||||
impl MemoryProfile
|
||||
{
|
||||
pub fn new(label: &'static str) -> Self
|
||||
{
|
||||
Self {
|
||||
stack: vec![Group::new(label)],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn begin(&mut self, device: &wgpu::Device) -> Device
|
||||
{
|
||||
Device {
|
||||
device: device.clone(),
|
||||
profile: self,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn terminate(mut self) -> Group
|
||||
{
|
||||
self.stack.pop().unwrap()
|
||||
}
|
||||
|
||||
fn open_group(&mut self, label: &'static str)
|
||||
{
|
||||
self.stack.push(Group::new(label));
|
||||
}
|
||||
|
||||
fn close_group(&mut self)
|
||||
{
|
||||
let mut group = self.stack.pop().unwrap();
|
||||
let _ = group.size_mut();
|
||||
|
||||
// Add it to parent if it exists
|
||||
if let Some(parent) = self.stack.last_mut()
|
||||
{
|
||||
parent.sub_groups.push(group);
|
||||
}
|
||||
else
|
||||
{
|
||||
self.stack.push(group);
|
||||
}
|
||||
}
|
||||
|
||||
fn add_buffer(&mut self, buffer: Buffer)
|
||||
{
|
||||
self.stack.last_mut().unwrap().buffers.push(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
use std::fmt;
|
||||
|
||||
impl fmt::Display for Group
|
||||
{
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
|
||||
{
|
||||
self.fmt_with_indent(f, 0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Group
|
||||
{
|
||||
fn fmt_with_indent(&self, f: &mut fmt::Formatter<'_>, indent: usize) -> fmt::Result
|
||||
{
|
||||
let prefix = " ".repeat(indent);
|
||||
|
||||
writeln!(
|
||||
f,
|
||||
"{}{} ({} bytes)",
|
||||
prefix,
|
||||
self.label,
|
||||
self.size.unwrap_or_else(|| self.size())
|
||||
)?;
|
||||
|
||||
// Print buffers
|
||||
for buffer in &self.buffers
|
||||
{
|
||||
writeln!(
|
||||
f,
|
||||
"{} ├── {} ({} bytes)",
|
||||
prefix, buffer.label, buffer.size
|
||||
)?;
|
||||
}
|
||||
|
||||
// Print subgroups
|
||||
for (i, group) in self.sub_groups.iter().enumerate()
|
||||
{
|
||||
group.fmt_with_indent(f, indent + 1)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+1184
-587
File diff suppressed because it is too large
Load Diff
+249
-157
@@ -3,12 +3,14 @@ use std::path::Path;
|
||||
|
||||
use glam::Vec3;
|
||||
use itertools::Itertools;
|
||||
use rayon::iter::IntoParallelRefMutIterator;
|
||||
use rayon::iter::ParallelIterator;
|
||||
use noise::Cylinders;
|
||||
use noise::Fbm;
|
||||
use noise::NoiseFn;
|
||||
use noise::Simplex;
|
||||
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<const N: usize>
|
||||
{
|
||||
@@ -30,7 +32,7 @@ pub trait Producer<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ExplicitNTreeNode<N>;
|
||||
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ProducedChunk<N>;
|
||||
}
|
||||
|
||||
impl<const N: usize> BallGenerator<N>
|
||||
@@ -47,7 +49,7 @@ impl<const N: usize> Producer<N> for BallGenerator<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ExplicitNTreeNode<N>
|
||||
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ProducedChunk<N>
|
||||
{
|
||||
let node_size = N.pow((self.chunk_power - depth) as u32);
|
||||
let child_size = node_size / N;
|
||||
@@ -55,6 +57,7 @@ where
|
||||
|
||||
let mut children = vec![];
|
||||
let mut children_color = vec![];
|
||||
let mut children_normal = vec![];
|
||||
|
||||
let gnx = nx * node_size;
|
||||
let gny = ny * node_size;
|
||||
@@ -75,35 +78,27 @@ 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(ChildInformation::new(subdivided, subdivided || alpha != 0.));
|
||||
children_normal.push((0., 0., 0.));
|
||||
children_color.push(Color(
|
||||
gvx as f32 / global_size as f32,
|
||||
gvy as f32 / global_size as f32,
|
||||
@@ -112,124 +107,10 @@ where
|
||||
));
|
||||
}
|
||||
|
||||
ExplicitNTreeNode {
|
||||
structure: std::array::from_fn(|i| children[i]),
|
||||
colors: std::array::from_fn(|i| children_color[i]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SineGenerator<const N: usize>
|
||||
{
|
||||
chunk_power: usize,
|
||||
}
|
||||
|
||||
impl<const N: usize> SineGenerator<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(chunk_power: usize) -> Self
|
||||
{
|
||||
Self { chunk_power }
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> Producer<N> for SineGenerator<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ExplicitNTreeNode<N>
|
||||
{
|
||||
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_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_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]),
|
||||
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()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -312,7 +193,7 @@ where
|
||||
let heightmap_max = heightmap.iter().copied().reduce(f32::max).unwrap();
|
||||
|
||||
heightmap
|
||||
.par_iter_mut()
|
||||
.iter_mut()
|
||||
.filter(|x| **x == -9999.)
|
||||
.for_each(|x| *x = heightmap_min);
|
||||
|
||||
@@ -419,14 +300,15 @@ where
|
||||
ny: usize,
|
||||
nz: usize,
|
||||
chunk_pos: (usize, usize, usize),
|
||||
) -> ExplicitNTreeNode<N>
|
||||
) -> ProducedChunk<N>
|
||||
{
|
||||
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];
|
||||
|
||||
let gnx = chunk_pos.0 * global_size + nx * node_size;
|
||||
let gny = chunk_pos.1 * global_size + ny * node_size;
|
||||
@@ -532,28 +414,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)
|
||||
{
|
||||
@@ -565,17 +439,30 @@ where
|
||||
};
|
||||
}
|
||||
|
||||
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]),
|
||||
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<const N: usize>
|
||||
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<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
@@ -587,5 +474,210 @@ where
|
||||
ny: usize,
|
||||
nz: usize,
|
||||
chunk_pos: (usize, usize, usize),
|
||||
) -> ExplicitNTreeNode<N>;
|
||||
) -> ProducedChunk<N>;
|
||||
}
|
||||
|
||||
pub struct SdfGenerator<const N: usize>
|
||||
{
|
||||
chunk_power: usize,
|
||||
perlin: Fbm<Simplex>,
|
||||
//perlin: Cylinders,
|
||||
}
|
||||
|
||||
impl<const N: usize> SdfGenerator<N>
|
||||
{
|
||||
pub fn new(chunk_power: usize) -> Self
|
||||
{
|
||||
Self {
|
||||
chunk_power,
|
||||
perlin: Fbm::new(67),
|
||||
//perlin: Cylinders::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> ChunkedProducer<N> for SdfGenerator<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
fn produce_node(
|
||||
&self,
|
||||
depth: usize,
|
||||
nx: usize,
|
||||
ny: usize,
|
||||
nz: usize,
|
||||
chunk_pos: (usize, usize, usize),
|
||||
) -> ProducedChunk<N>
|
||||
{
|
||||
fn hash(mut p: [f32; 3]) -> f32
|
||||
{
|
||||
p[0] = (p[0] * 127.1 + p[1] * 311.7 + p[2] * 74.7).sin() * 43758.5453123;
|
||||
p[0].fract()
|
||||
}
|
||||
|
||||
// let sdf = |x: f32, y: f32, z: f32| {
|
||||
// Vec3::new((x % 1024.) - 512., (y % 1024.) - 512., (z % 1024.) - 512.).length() - 512.
|
||||
// };
|
||||
|
||||
// let sdf = |mut x: f32, mut y: f32, mut z: f32| {
|
||||
// // x = -5000. * 1024.;
|
||||
// // z = -5000. * 1024.;
|
||||
// y -= 1024.;
|
||||
// let scale = 2048.;
|
||||
// let tx = x / scale;
|
||||
// let ty = y / scale;
|
||||
// let tz = z / scale;
|
||||
//
|
||||
// let val = (self.perlin.get([tx as f64, tz as f64, ty as f64]) + 0.5) * 0.23;
|
||||
// let dist = val * scale as f64;
|
||||
// return (dist as f32).max(ty);
|
||||
// };
|
||||
|
||||
// let sdf = |x: f32, y: f32, z: f32| {
|
||||
// let scale = 1024. * 10.;
|
||||
// let domain = 1.;
|
||||
// let tx = map(x, 0., scale, -domain, domain);
|
||||
// let ty = map(y, 0., scale, -domain, domain);
|
||||
// let tz = map(z, 0., scale, -domain, domain);
|
||||
// nebula_sdf(tx, ty, tz) * 0.2 * scale / domain
|
||||
// };
|
||||
|
||||
let sdf = |x: f32, y: f32, z: f32| {
|
||||
let scale = 10. * 1024.;
|
||||
let height = 5000.;
|
||||
let tx = x / scale;
|
||||
let tz = z / scale;
|
||||
let ty = y;
|
||||
let val = map(
|
||||
self.perlin.get([tx as f64, tz as f64]) as f32,
|
||||
-1.,
|
||||
1.,
|
||||
1.,
|
||||
height,
|
||||
);
|
||||
|
||||
// Trees
|
||||
let tree_space = 10.;
|
||||
let mx = x.rem_euclid(tree_space);
|
||||
let mz = z.rem_euclid(tree_space);
|
||||
|
||||
let tree_x = x.div_euclid(tree_space);
|
||||
let tree_z = z.div_euclid(tree_space);
|
||||
let h1 = hash([tree_x, tree_z, 1.]);
|
||||
let h2 = hash([tree_z, tree_x, 1.]);
|
||||
let h3 = hash([tree_z, tree_x, tree_z]);
|
||||
|
||||
let d = Vec3::new(
|
||||
mx + h1 * 3. - tree_space * 0.5,
|
||||
(ty - val) * 0.2,
|
||||
mz + h2 * 3. - tree_space * 0.5,
|
||||
)
|
||||
.length()
|
||||
- 4. * map(h3, 0., 1., 0.8, 1.2);
|
||||
|
||||
let bound = 1. / scale * height;
|
||||
|
||||
((ty - val) / (1. + bound.powf(2.)).sqrt()).min(d)
|
||||
};
|
||||
|
||||
let node_size = N.pow((self.chunk_power - depth) as u32);
|
||||
let child_size = node_size / N;
|
||||
let global_size = N.pow(self.chunk_power as u32);
|
||||
|
||||
let mut children = vec![];
|
||||
let mut children_color = vec![];
|
||||
let mut children_normals = vec![];
|
||||
|
||||
let cx = chunk_pos.0 * global_size;
|
||||
let cy = chunk_pos.1 * global_size;
|
||||
let cz = chunk_pos.2 * global_size;
|
||||
let gnx = nx * node_size + cx;
|
||||
let gny = ny * node_size + cy;
|
||||
let gnz = nz * node_size + cz;
|
||||
// Iterate on children of this node
|
||||
for ((cz, cy), cx) in (0..N).cartesian_product(0..N).cartesian_product(0..N)
|
||||
{
|
||||
let gvx = gnx + cx * child_size + (child_size / 2);
|
||||
let gvy = gny + cy * child_size + (child_size / 2);
|
||||
let gvz = gnz + cz * child_size + (child_size / 2);
|
||||
|
||||
let dist = sdf(gvx as f32, gvy as f32, gvz as f32);
|
||||
let child_diagonal_length = (child_size as f32 / 2.) * f32::sqrt(3.);
|
||||
|
||||
let alpha;
|
||||
let subdivided;
|
||||
if dist.abs() < child_diagonal_length
|
||||
{
|
||||
//children.push(StructurePointer::new(depth <= 3, false, 0));
|
||||
subdivided = depth < (self.chunk_power - 1);
|
||||
alpha = if dist >= 0. { 0. } else { 1. };
|
||||
//alpha = 0.;
|
||||
}
|
||||
else if dist >= 0.
|
||||
{
|
||||
subdivided = false;
|
||||
alpha = 0.;
|
||||
}
|
||||
else
|
||||
{
|
||||
subdivided = false;
|
||||
alpha = 1.;
|
||||
}
|
||||
|
||||
let offset = 1. * (child_size as f32 / 2.);
|
||||
|
||||
let a = sdf(
|
||||
gvx as f32 + offset,
|
||||
gvy as f32 - offset,
|
||||
gvz as f32 - offset,
|
||||
);
|
||||
let b = sdf(
|
||||
gvx as f32 - offset,
|
||||
gvy as f32 - offset,
|
||||
gvz as f32 + offset,
|
||||
);
|
||||
let c = sdf(
|
||||
gvx as f32 - offset,
|
||||
gvy as f32 + offset,
|
||||
gvz as f32 - offset,
|
||||
);
|
||||
let d = sdf(
|
||||
gvx as f32 + offset,
|
||||
gvy as f32 + offset,
|
||||
gvz as f32 + offset,
|
||||
);
|
||||
|
||||
let normal = Vec3::new(a - b - c + d, -a - b + c + d, -a + b - c + d);
|
||||
|
||||
let normal = if normal.length() <= f32::EPSILON
|
||||
{
|
||||
Vec3::new(1., 0., 0.)
|
||||
}
|
||||
else
|
||||
{
|
||||
normal.normalize()
|
||||
};
|
||||
|
||||
let color = (normal.dot(Vec3::new(0., 1., 0.)) + 1.) * 0.5;
|
||||
|
||||
// let alpha = 1.;
|
||||
// children_color.push(Color(
|
||||
// (gvx - cx) as f32 / global_size as f32,
|
||||
// (gvy - cy) as f32 / global_size as f32,
|
||||
// (gvz - cz) as f32 / global_size as f32,
|
||||
// alpha,
|
||||
// ));
|
||||
children.push(ChildInformation::new(subdivided, subdivided || alpha != 0.));
|
||||
children_color.push(Color(color + random::<f32>() * 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));
|
||||
}
|
||||
|
||||
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.)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+11
-3
@@ -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).clamp(0., 255.0) as u32;
|
||||
let mapped_g = (self.1 * 255.0).clamp(0., 255.0) as u32;
|
||||
let mapped_b = (self.2 * 255.0).clamp(0., 255.0) as u32;
|
||||
let mapped_a = (self.3 * 255.0).clamp(0., 255.0) as u32;
|
||||
mapped_r | (mapped_g << 8) | (mapped_b << 16) | (mapped_a << 24)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -348,6 +354,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
pub fn as_explicit_structure(&self) -> (Color, Vec<ExplicitNTreeNode<N>>)
|
||||
{
|
||||
let root = self.map.get(&NTreeNodeLocator::root()).unwrap();
|
||||
@@ -391,6 +398,7 @@ where
|
||||
|
||||
(root.color, explicit_structure)
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
fn base_trailing_zeroes<const N: usize>(mut number: usize) -> Option<u32>
|
||||
|
||||
+277
@@ -0,0 +1,277 @@
|
||||
use std::iter::FusedIterator;
|
||||
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
use glam::Vec3;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::include_wgsl;
|
||||
|
||||
use crate::gpu::create_multi_buffers_bind_group_layout;
|
||||
use crate::voxel_cache;
|
||||
use crate::voxel_cache::tables::FixedStructureTable;
|
||||
|
||||
/// A torroidal structure table for "infinite" world purposes.
|
||||
/// Allows rendering a X*Y*Z block of chunks arround a position, like for example arround a player.
|
||||
///
|
||||
/// When the player moves, crossing a chunk boundary, chunks behind disapear, chunks in front
|
||||
/// appear. The torroidal nature of the table (modulo on the coordinates) allows reusing the
|
||||
/// disapearing chunks for the new chunks appearing in front.
|
||||
pub struct ToroidalStructureTable
|
||||
{
|
||||
/// Size of the torroidal structure : how many chunks in each direction can be rendered at once
|
||||
extent: (usize, usize, usize),
|
||||
|
||||
fixed_structure_table: FixedStructureTable,
|
||||
position: Vec3,
|
||||
current_offset: (isize, isize, isize),
|
||||
|
||||
invalidation_pass: wgpu::ComputePipeline,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
struct ToroidalInvalidationImmediates
|
||||
{
|
||||
extent: [u32; 3],
|
||||
_pad1: u32,
|
||||
previous_offset: [i32; 3],
|
||||
_pad2: u32,
|
||||
offset: [i32; 3],
|
||||
_pad3: u32,
|
||||
}
|
||||
|
||||
impl ToroidalStructureTable
|
||||
{
|
||||
pub fn new(device: &wgpu::Device, extent: (usize, usize, usize), initial_position: Vec3)
|
||||
-> Self
|
||||
{
|
||||
let size = extent.0 * extent.1 * extent.2;
|
||||
assert!(size <= (u32::MAX as usize));
|
||||
|
||||
let current_offset = Self::offset_from_center(extent, initial_position);
|
||||
|
||||
let bind_group_layout = create_multi_buffers_bind_group_layout(
|
||||
device,
|
||||
1,
|
||||
Some("ToroidalStructureTable::bind_group_layout"),
|
||||
);
|
||||
|
||||
let invalidation_pipeline_layout =
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("ToroidalStructureTable::invalidation_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&bind_group_layout)],
|
||||
immediate_size: size_of::<ToroidalInvalidationImmediates>() as u32,
|
||||
});
|
||||
|
||||
let shader_module =
|
||||
device.create_shader_module(include_wgsl!("./terrain/shaders/toroidal_structure.wgsl"));
|
||||
|
||||
let invalidation_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("ToroidalStructureTable::invalidation_pass"),
|
||||
layout: Some(&invalidation_pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("invalidate_new"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
ToroidalStructureTable {
|
||||
extent,
|
||||
fixed_structure_table: FixedStructureTable::new(device, size),
|
||||
position: initial_position,
|
||||
current_offset,
|
||||
invalidation_pass,
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the center position to `new_position`.
|
||||
/// This requires updating to structure table to remove disapearing chunks
|
||||
pub fn move_position(&mut self, encoder: &mut CommandEncoder, new_position: Vec3)
|
||||
{
|
||||
let previous_offset = self.current_offset;
|
||||
self.current_offset = Self::offset_from_center(self.extent, new_position);
|
||||
self.position = new_position;
|
||||
|
||||
let invalidation_parameters = ToroidalInvalidationImmediates {
|
||||
extent: [
|
||||
self.extent.0 as u32,
|
||||
self.extent.1 as u32,
|
||||
self.extent.2 as u32,
|
||||
],
|
||||
_pad1: 0,
|
||||
previous_offset: [
|
||||
previous_offset.0 as i32,
|
||||
previous_offset.1 as i32,
|
||||
previous_offset.2 as i32,
|
||||
],
|
||||
_pad2: 0,
|
||||
offset: [
|
||||
self.current_offset.0 as i32,
|
||||
self.current_offset.1 as i32,
|
||||
self.current_offset.2 as i32,
|
||||
],
|
||||
_pad3: 0,
|
||||
};
|
||||
|
||||
let mut invalidation_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("ToroidalStructureTable::invalidation_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
invalidation_pass.set_pipeline(&self.invalidation_pass);
|
||||
invalidation_pass.set_bind_group(0, self.fixed_structure_table.pointers_bind_group(), &[]);
|
||||
invalidation_pass.set_immediates(0, bytemuck::bytes_of(&invalidation_parameters));
|
||||
invalidation_pass.dispatch_workgroups(
|
||||
self.extent.0.div_ceil(4) as u32,
|
||||
self.extent.1.div_ceil(4) as u32,
|
||||
self.extent.2.div_ceil(4) as u32,
|
||||
);
|
||||
}
|
||||
|
||||
/// Given the structure id, returns the position of the requesting chunk
|
||||
pub fn get_request_position(&self, structure_id: u32) -> (isize, isize, isize)
|
||||
{
|
||||
let (ex, ey, ez) = (
|
||||
self.extent.0 as isize,
|
||||
self.extent.1 as isize,
|
||||
self.extent.2 as isize,
|
||||
);
|
||||
let id = structure_id as isize;
|
||||
|
||||
let sx = id % ex;
|
||||
let sz = (id / ex) % ez;
|
||||
let sy = id / (ex * ez);
|
||||
|
||||
let (ox, oy, oz) = self.current_offset;
|
||||
|
||||
(
|
||||
ox + (sx - ox).rem_euclid(ex),
|
||||
oy + (sy - oy).rem_euclid(ey),
|
||||
oz + (sz - oz).rem_euclid(ez),
|
||||
)
|
||||
}
|
||||
|
||||
fn offset_from_center(extent: (usize, usize, usize), position: Vec3) -> (isize, isize, isize)
|
||||
{
|
||||
(
|
||||
position.x.floor() as isize - (extent.0 as isize / 2),
|
||||
position.y.floor() as isize - (extent.1 as isize / 2),
|
||||
position.z.floor() as isize - (extent.2 as isize / 2),
|
||||
)
|
||||
}
|
||||
|
||||
// Function calls through to fixed_structure_table
|
||||
|
||||
pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup
|
||||
{
|
||||
self.fixed_structure_table.raytrace_bind_group()
|
||||
}
|
||||
|
||||
pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout
|
||||
{
|
||||
self.fixed_structure_table.raytrace_bind_group_layout()
|
||||
}
|
||||
|
||||
pub fn insert<const N: usize>(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut crate::gpu_profiler::ScopeEncoder<wgpu::CommandEncoder>,
|
||||
insertion: &voxel_cache::insertion::CacheInsertionData<N>,
|
||||
request: &voxel_cache::requests::CacheRequestBuffer,
|
||||
) where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
self.fixed_structure_table
|
||||
.insert(device, encoder, insertion, request);
|
||||
}
|
||||
|
||||
pub fn gather_requests(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut crate::gpu_profiler::ScopeEncoder<wgpu::CommandEncoder>,
|
||||
request_buffer: &voxel_cache::requests::CacheRequestBuffer,
|
||||
)
|
||||
{
|
||||
self.fixed_structure_table
|
||||
.gather_requests(device, encoder, request_buffer);
|
||||
}
|
||||
}
|
||||
|
||||
impl voxel_cache::CacheInvalidable for ToroidalStructureTable
|
||||
{
|
||||
fn invalidate(
|
||||
&mut self,
|
||||
encoder: &mut crate::gpu_profiler::ScopeEncoder<CommandEncoder>,
|
||||
cache_evictor: &voxel_cache::eviction::CacheEvictor,
|
||||
invalid_timestamp: u32,
|
||||
)
|
||||
{
|
||||
self.fixed_structure_table
|
||||
.invalidate(encoder, cache_evictor, invalid_timestamp);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CenterChunkIter
|
||||
{
|
||||
center_chunk: (isize, isize, isize),
|
||||
extent: (usize, usize, usize),
|
||||
block_corner: (isize, isize, isize),
|
||||
current: usize,
|
||||
length: usize,
|
||||
}
|
||||
|
||||
impl CenterChunkIter
|
||||
{
|
||||
pub fn new(center_chunk: (isize, isize, isize), extent: (usize, usize, usize)) -> Self
|
||||
{
|
||||
let half_extent = (extent.0 / 2, extent.1 / 2, extent.2 / 2);
|
||||
let block_corner = (
|
||||
center_chunk.0 - half_extent.0 as isize,
|
||||
center_chunk.1 - half_extent.1 as isize,
|
||||
center_chunk.2 - half_extent.2 as isize,
|
||||
);
|
||||
|
||||
Self {
|
||||
center_chunk,
|
||||
extent,
|
||||
block_corner,
|
||||
current: 0,
|
||||
length: extent.0 * extent.1 * extent.2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FusedIterator for CenterChunkIter {}
|
||||
impl ExactSizeIterator for CenterChunkIter {}
|
||||
|
||||
impl Iterator for CenterChunkIter
|
||||
{
|
||||
type Item = (isize, isize, isize);
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item>
|
||||
{
|
||||
if self.current >= self.length
|
||||
{
|
||||
None
|
||||
}
|
||||
else
|
||||
{
|
||||
let x = self.current % self.extent.0;
|
||||
let y = (self.current / self.extent.0) % self.extent.1;
|
||||
let z = self.current / (self.extent.0 * self.extent.1);
|
||||
self.current += 1;
|
||||
|
||||
Some((
|
||||
x as isize + self.block_corner.0,
|
||||
y as isize + self.block_corner.1,
|
||||
z as isize + self.block_corner.2,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>)
|
||||
{
|
||||
let remaining = self.length - self.current;
|
||||
(remaining, Some(remaining))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
@group(0) @binding(0) var<storage, read_write> table_pointers: array<u32>;
|
||||
|
||||
struct InvalidationImmediates
|
||||
{
|
||||
extent: vec3<u32>,
|
||||
pevious_offset: vec3<i32>,
|
||||
offset: vec3<i32>,
|
||||
}
|
||||
|
||||
var<immediate> immediates: InvalidationImmediates;
|
||||
|
||||
|
||||
@compute
|
||||
@workgroup_size(4, 4, 4)
|
||||
fn invalidate_new(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
if(any(gid >= immediates.extent))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Check whether this invocation lies within a pointer to be renewed
|
||||
let igid = vec3<i32>(gid);
|
||||
let previous_pos = get_position(igid, immediates.pevious_offset);
|
||||
let pos = get_position(igid, immediates.offset);
|
||||
|
||||
if(any(previous_pos != pos))
|
||||
{
|
||||
// Invalidate pointer
|
||||
let index = gid.x + gid.z * immediates.extent.x + gid.y * immediates.extent.x * immediates.extent.z;
|
||||
table_pointers[index] = u32(1) << 31;
|
||||
}
|
||||
}
|
||||
|
||||
fn get_position(block_position: vec3<i32>, offset: vec3<i32>) -> vec3<i32>
|
||||
{
|
||||
return offset + imodv((block_position - offset), vec3<i32>(immediates.extent));
|
||||
}
|
||||
|
||||
fn imod(x: i32, n: i32) -> i32 {
|
||||
return ((x % n) + n) % n;
|
||||
}
|
||||
|
||||
fn imodv(x: vec3<i32>, n: vec3<i32>) -> vec3<i32> {
|
||||
return vec3<i32>(imod(x.x, n.x), imod(x.y, n.y), imod(x.z, n.z));
|
||||
}
|
||||
+343
-840
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,96 @@
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
|
||||
use crate::gpu_profiler::memory_profiler;
|
||||
use crate::voxel_cache::layout::CacheLayout;
|
||||
|
||||
/// Contains instanciated gpu buffers to hold data for cache attributes
|
||||
pub struct CacheAttributes<const N: usize>
|
||||
{
|
||||
attribute_buffers: Vec<wgpu::Buffer>,
|
||||
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
bind_group: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheAttributes<N>
|
||||
{
|
||||
pub fn from_cache_layout(
|
||||
device: &mut memory_profiler::Device,
|
||||
layout: &CacheLayout,
|
||||
page_count: usize,
|
||||
) -> Self
|
||||
{
|
||||
let attribute_buffers = layout
|
||||
.attributes
|
||||
.iter()
|
||||
.map(|attribute| {
|
||||
attribute.create_buffer_profiled(
|
||||
device,
|
||||
N * N * N,
|
||||
page_count,
|
||||
BufferUsages::STORAGE,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let bind_group_layout = Self::create_bind_group_layout(device, layout);
|
||||
|
||||
let bind_group_bindings = attribute_buffers
|
||||
.iter()
|
||||
.map(|buffer| buffer.as_entire_buffer_binding())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("CacheAttributes::bind_group"),
|
||||
layout: &bind_group_layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::BufferArray(&bind_group_bindings),
|
||||
}],
|
||||
});
|
||||
|
||||
CacheAttributes {
|
||||
attribute_buffers,
|
||||
bind_group_layout,
|
||||
bind_group,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_bind_group_layout(device: &wgpu::Device, layout: &CacheLayout)
|
||||
-> BindGroupLayout
|
||||
{
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("CacheAttributes::bind_group_layout"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
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(
|
||||
std::num::NonZero::new(layout.attributes.len() as u32)
|
||||
.expect("Cannot create cache attributes with no attributes"),
|
||||
),
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
pub fn bind_group_layout(&self) -> &wgpu::BindGroupLayout
|
||||
{
|
||||
&self.bind_group_layout
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &wgpu::BindGroup
|
||||
{
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
pub fn attribute_buffers(&self) -> &[Buffer]
|
||||
{
|
||||
&self.attribute_buffers
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
use wgpu::Buffer;
|
||||
|
||||
use crate::sparse_tree::Color;
|
||||
|
||||
#[derive(Clone, Copy, Zeroable, Pod, Debug)]
|
||||
#[repr(C)]
|
||||
pub struct CacheNodeRequest
|
||||
{
|
||||
// Requested ressource
|
||||
pub structure_id: u32,
|
||||
pub structure_locator: u32,
|
||||
|
||||
// Write back info
|
||||
pub node_index: u32,
|
||||
pub child_index: u32,
|
||||
}
|
||||
|
||||
pub struct RequestBufferElement<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
request_count: [u32; N * N * N],
|
||||
}
|
||||
|
||||
pub struct StructurePoolElement<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pointers: [StructurePointer; N * N * N],
|
||||
}
|
||||
|
||||
pub struct DestinationElement
|
||||
{
|
||||
pub node: u32,
|
||||
pub child: u32,
|
||||
}
|
||||
|
||||
pub struct ColorBytes(pub u8, pub u8, pub u8, pub u8);
|
||||
|
||||
impl From<Color> for ColorBytes
|
||||
{
|
||||
fn from(value: Color) -> Self
|
||||
{
|
||||
Self(
|
||||
(value.0 * 255.) as u8,
|
||||
(value.1 * 255.) as u8,
|
||||
(value.2 * 255.) as u8,
|
||||
(value.3 * 255.) as u8,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ColorPoolElement<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
colors: [ColorBytes; N * N * N],
|
||||
}
|
||||
|
||||
pub struct LocationPoolElement
|
||||
{
|
||||
pub structure_id: u32,
|
||||
pub structure_locator: u32,
|
||||
}
|
||||
|
||||
pub struct CacheResponse
|
||||
{
|
||||
// Each buffer contains the same amount of elements (structure of arrays style)
|
||||
|
||||
// Cache data to bring in
|
||||
pub structure_nodes: Buffer,
|
||||
pub color_nodes: Buffer,
|
||||
pub locations: Buffer,
|
||||
|
||||
// Which nodes this extends : node_index + child_index
|
||||
pub parents: Buffer,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Pod, Zeroable)]
|
||||
#[repr(transparent)]
|
||||
pub struct StructurePointer(pub u32);
|
||||
|
||||
impl StructurePointer
|
||||
{
|
||||
pub fn new(subdivided: bool, pointer_valid: bool, pointer: u32) -> Self
|
||||
{
|
||||
assert!(pointer >> 30 == 0);
|
||||
StructurePointer((subdivided as u32) << 31 | (pointer_valid as u32) << 30 | pointer)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct ExplicitNTreeNode<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub structure: [StructurePointer; N * N * N],
|
||||
pub colors: [Color; N * N * N],
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
/// Contains structure and logic related to eviction logic in the cache.
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::include_wgsl;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::gpu::create_multi_buffers_bind_group;
|
||||
use crate::gpu::radix_sort;
|
||||
use crate::gpu_profiler::ScopeEncoder;
|
||||
use crate::gpu_profiler::memory_profiler;
|
||||
use crate::gpu_profiler::{self};
|
||||
use crate::voxel_cache::CacheRessources;
|
||||
use crate::voxel_cache::create_multi_buffers_bind_group_layout;
|
||||
use crate::voxel_cache::structure::CacheStructure;
|
||||
|
||||
/// Retains usage information about pages in the cache under the form of timestamps.
|
||||
/// Produces a list of LRU eviction order, from which the cache can pull pages to recycle
|
||||
pub struct CacheEvictor
|
||||
{
|
||||
page_count: usize,
|
||||
|
||||
/// Contains a u32 timestamp per page, so that we know when a page was last used
|
||||
timestamp_pages: wgpu::Buffer,
|
||||
|
||||
/// Contains indices in LRU order, after sorting
|
||||
lru_list: wgpu::Buffer,
|
||||
|
||||
/// When reusing pages, count of lru pages consumed
|
||||
consumed_count: wgpu::Buffer,
|
||||
|
||||
/// To reset lru indices between insertions
|
||||
reset_lru_pass: wgpu::ComputePipeline,
|
||||
|
||||
/// To copy corresponding timestamp values after first depth sort
|
||||
indirect_copy_pass: wgpu::ComputePipeline,
|
||||
pipelines_dispatch_count: u32,
|
||||
|
||||
// For external passes
|
||||
bind_group_layout: BindGroupLayout,
|
||||
bind_group: BindGroup,
|
||||
}
|
||||
|
||||
impl CacheEvictor
|
||||
{
|
||||
pub fn new(
|
||||
device: &mut memory_profiler::Device,
|
||||
page_count: usize,
|
||||
initial_timestamp: u32,
|
||||
) -> Self
|
||||
{
|
||||
let timestamp_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheUsage::timestamp_pages"),
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
|
||||
contents: bytemuck::cast_slice(&vec![initial_timestamp; page_count]),
|
||||
});
|
||||
|
||||
let lru_list = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheUsage::lru_list"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
size: (page_count * size_of::<u32>()) as u64,
|
||||
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 bind_group_layout = Self::create_bind_group_layout(device);
|
||||
let bind_group = create_multi_buffers_bind_group(
|
||||
device,
|
||||
&bind_group_layout,
|
||||
&[×tamp_pages, &lru_list, &consumed_count],
|
||||
Some("CacheEvictor::bind_group"),
|
||||
);
|
||||
|
||||
let pipelines_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("CacheEvictor::reset_lru_list_pipeline_layout"),
|
||||
bind_group_layouts: &[
|
||||
Some(&bind_group_layout),
|
||||
Some(&CacheStructure::<1>::create_bind_group_layout(device)),
|
||||
Some(&CacheRessources::<1>::create_scratch_buffer_bind_group_layout(device)),
|
||||
],
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let shader_module = device.create_shader_module(include_wgsl!("./shaders/eviction.wgsl"));
|
||||
|
||||
let reset_lru_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("CacheEvictor::reset_lru_pass"),
|
||||
layout: Some(&pipelines_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("reset_lru_list"),
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let indirect_copy_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("CacheEvictor::indirect_copy_pass"),
|
||||
layout: Some(&pipelines_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("indirect_copy"),
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
page_count,
|
||||
timestamp_pages,
|
||||
lru_list,
|
||||
consumed_count,
|
||||
|
||||
reset_lru_pass,
|
||||
indirect_copy_pass,
|
||||
pipelines_dispatch_count: page_count.div_ceil(256) as u32,
|
||||
|
||||
bind_group_layout,
|
||||
bind_group,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn prepare_eviction_list<const N: usize>(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
ressources: &CacheRessources<N>,
|
||||
structure: &CacheStructure<N>,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
) where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "CacheEvictor::prepare_eviction_list");
|
||||
// Reset lru list
|
||||
{
|
||||
let mut reset_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("CacheEvictor::reset_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
reset_pass.set_bind_group(0, Some(&self.bind_group), &[]);
|
||||
reset_pass.set_bind_group(1, Some(structure.bind_group()), &[]);
|
||||
reset_pass.set_bind_group(2, Some(ressources.scratch_buffer_bind_group()), &[]);
|
||||
reset_pass.set_pipeline(&self.reset_lru_pass);
|
||||
reset_pass.dispatch_workgroups(self.pipelines_dispatch_count, 1, 1);
|
||||
}
|
||||
|
||||
// First sort nodes per depth
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "depth radix");
|
||||
encoder.copy_buffer_to_buffer(
|
||||
structure.depth_pages(),
|
||||
0,
|
||||
&ressources.scratch_buffer,
|
||||
0,
|
||||
structure.depth_pages().size(),
|
||||
);
|
||||
|
||||
ressources.radix_sorter.sort(
|
||||
device,
|
||||
&ressources.scratch_buffer,
|
||||
&self.lru_list,
|
||||
None,
|
||||
Some(self.page_count),
|
||||
&mut encoder,
|
||||
radix_sort::RadixSortDirection::Ascending,
|
||||
);
|
||||
}
|
||||
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "indirect copy");
|
||||
let mut indirect_copy_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("CacheEvictor::indirect_copy_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
indirect_copy_pass.set_bind_group(0, Some(&self.bind_group), &[]);
|
||||
indirect_copy_pass.set_bind_group(1, Some(structure.bind_group()), &[]);
|
||||
indirect_copy_pass.set_bind_group(2, Some(ressources.scratch_buffer_bind_group()), &[]);
|
||||
indirect_copy_pass.set_pipeline(&self.indirect_copy_pass);
|
||||
indirect_copy_pass.dispatch_workgroups(self.pipelines_dispatch_count, 1, 1);
|
||||
}
|
||||
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "timestamp radix");
|
||||
ressources.radix_sorter.sort(
|
||||
device,
|
||||
&ressources.scratch_buffer,
|
||||
&self.lru_list,
|
||||
None,
|
||||
Some(self.page_count),
|
||||
&mut encoder,
|
||||
radix_sort::RadixSortDirection::Ascending,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &BindGroup
|
||||
{
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout
|
||||
{
|
||||
create_multi_buffers_bind_group_layout(device, 3, Some("CacheEvictor::bind_group_layout"))
|
||||
}
|
||||
|
||||
pub fn timestamp_pages_buffer(&self) -> &wgpu::Buffer
|
||||
{
|
||||
&self.timestamp_pages
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
use std::num::NonZero;
|
||||
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::ShaderStages;
|
||||
|
||||
use crate::voxel_cache::layout::CacheLayout;
|
||||
use crate::voxel_cache::schema::InsertionInformation;
|
||||
use crate::voxel_cache::schema::LocationPage;
|
||||
|
||||
/// Data to be inserted in a cache insertion operation
|
||||
pub struct CacheInsertionData<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
/// The amount of pages to insert this structure can hold
|
||||
max_page_count: usize,
|
||||
|
||||
/// Amount of pages that the structure actually contains
|
||||
page_count_buffer: wgpu::Buffer,
|
||||
|
||||
/// Information about inserted pages : dense array of [`InsertionInformation<N>`] structs
|
||||
insertion_information: wgpu::Buffer,
|
||||
|
||||
/// Location of the new nodes : dense array of [`LocationPage`] structs
|
||||
location_pages: wgpu::Buffer,
|
||||
|
||||
/// Contains the attributes to import in the cache.
|
||||
attributes: Vec<wgpu::Buffer>,
|
||||
|
||||
/// Contains the indicies of the page in which the data was written
|
||||
destination_indices: wgpu::Buffer,
|
||||
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
bind_group: wgpu::BindGroup,
|
||||
bind_group_no_attributes: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheInsertionData<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &wgpu::Device, max_page_count: usize, layout: &CacheLayout) -> Self
|
||||
{
|
||||
let page_count_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheInsertionData::page_count_buffer"),
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
size: size_of::<u32>() as u64,
|
||||
});
|
||||
|
||||
let insertion_information = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheInsertionData::insertion_information"),
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
size: (size_of::<InsertionInformation<N>>() * max_page_count) as u64,
|
||||
});
|
||||
|
||||
let location_pages = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheInsertionData::location_pages"),
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
size: (size_of::<LocationPage>() * max_page_count) as u64,
|
||||
});
|
||||
|
||||
let destination_indices = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheInsertionData::destination_indices"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
mapped_at_creation: false,
|
||||
size: (size_of::<u32>() * max_page_count) as u64,
|
||||
});
|
||||
|
||||
let attributes = layout
|
||||
.attributes
|
||||
.iter()
|
||||
.map(|attribute| {
|
||||
attribute.create_buffer(
|
||||
device,
|
||||
N * N * N,
|
||||
max_page_count,
|
||||
BufferUsages::STORAGE | BufferUsages::COPY_DST,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let bind_group_bindings = attributes
|
||||
.iter()
|
||||
.map(|buffer| buffer.as_entire_buffer_binding())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let mut entries = vec![
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: page_count_buffer.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: insertion_information.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: location_pages.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: destination_indices.as_entire_binding(),
|
||||
},
|
||||
];
|
||||
|
||||
let bind_group_layout_no_attributes = Self::create_bind_group_layout(device, None);
|
||||
let bind_group_no_attributes = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("CacheInsertionData::bind_group_no_attributes"),
|
||||
layout: &bind_group_layout_no_attributes,
|
||||
entries: &entries,
|
||||
});
|
||||
entries.push(wgpu::BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: wgpu::BindingResource::BufferArray(&bind_group_bindings),
|
||||
});
|
||||
|
||||
let bind_group_layout = Self::create_bind_group_layout(device, Some(layout));
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("CacheInsertionData::bind_group"),
|
||||
layout: &bind_group_layout,
|
||||
entries: &entries,
|
||||
});
|
||||
|
||||
Self {
|
||||
page_count_buffer,
|
||||
max_page_count,
|
||||
insertion_information,
|
||||
location_pages,
|
||||
destination_indices,
|
||||
attributes,
|
||||
|
||||
bind_group_layout,
|
||||
bind_group,
|
||||
bind_group_no_attributes,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a bindgroup layout to bind the insertion data :
|
||||
/// - Page count buffer (u32)
|
||||
/// - Insertion information
|
||||
/// - Location pages
|
||||
/// - Destination indicies
|
||||
/// - (Optional) attributes
|
||||
///
|
||||
/// An applcation that does not need the the attributes can pass `None` to layout.
|
||||
/// It can then use [`CacheInsertionData::<_>::bind_group_no_attributes(...)`] to get the
|
||||
/// corresponding bind group, otherwise use [`CacheInsertionData::<_>::bind_group(...)`]
|
||||
///
|
||||
pub fn create_bind_group_layout(
|
||||
device: &wgpu::Device,
|
||||
layout: Option<&CacheLayout>,
|
||||
) -> BindGroupLayout
|
||||
{
|
||||
let mut entries = vec![
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 3,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
];
|
||||
|
||||
if let Some(layout) = layout
|
||||
{
|
||||
entries.push(wgpu::BindGroupLayoutEntry {
|
||||
binding: 4,
|
||||
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()),
|
||||
});
|
||||
}
|
||||
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("CacheInsertionData::bind_group_layout"),
|
||||
entries: &entries,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &wgpu::BindGroup
|
||||
{
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
pub fn bind_group_no_attributes(&self) -> &wgpu::BindGroup
|
||||
{
|
||||
&self.bind_group_no_attributes
|
||||
}
|
||||
|
||||
pub fn page_count(&self) -> usize
|
||||
{
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
use wgpu::BufferUsages;
|
||||
|
||||
use crate::gpu_profiler::memory_profiler;
|
||||
|
||||
/// Defines how a [`VoxelCache`]'s attribute is populated upon populating a page
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CacheAttributeInit
|
||||
{
|
||||
/// Attribute is external : it is copied from the insertion operation
|
||||
External,
|
||||
|
||||
/// Attribute will not be touched by the cache mechanism. It is left to the discrecy of the
|
||||
/// cache user.
|
||||
///
|
||||
/// Some applications requires pieces of data into the resident data of the cache that are
|
||||
/// computed on the fly : e.g. global illumination
|
||||
DontTouch,
|
||||
}
|
||||
|
||||
/// Describes an attribute of a [`VoxelCache`]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct CacheAttribute
|
||||
{
|
||||
pub label: Option<&'static str>,
|
||||
pub word_count: u32,
|
||||
pub init: CacheAttributeInit,
|
||||
}
|
||||
|
||||
impl CacheAttribute
|
||||
{
|
||||
pub fn create_buffer_profiled(
|
||||
&self,
|
||||
device: &mut memory_profiler::Device,
|
||||
child_count: usize,
|
||||
page_count: usize,
|
||||
usage: wgpu::BufferUsages,
|
||||
) -> wgpu::Buffer
|
||||
{
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(
|
||||
format!(
|
||||
"VoxelCacheAttribute ({}) {} word(s)",
|
||||
self.label.unwrap_or("no-name"),
|
||||
self.word_count
|
||||
)
|
||||
.as_str(),
|
||||
),
|
||||
size: (self.word_count as usize * page_count * child_count * size_of::<u32>()) as u64,
|
||||
usage,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates the wgpu buffer necessary to store this attribute in the cache
|
||||
pub fn create_buffer(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
child_count: usize,
|
||||
page_count: usize,
|
||||
usage: wgpu::BufferUsages,
|
||||
) -> wgpu::Buffer
|
||||
{
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(
|
||||
format!(
|
||||
"VoxelCacheAttribute ({}) {} word(s)",
|
||||
self.label.unwrap_or("no-name"),
|
||||
self.word_count
|
||||
)
|
||||
.as_str(),
|
||||
),
|
||||
size: (self.word_count as usize * page_count * child_count * size_of::<u32>()) as u64,
|
||||
usage,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct CacheLayout
|
||||
{
|
||||
pub(super) attributes: Vec<CacheAttribute>,
|
||||
}
|
||||
|
||||
impl CacheLayout
|
||||
{
|
||||
/// Adds a new [`VoxelCacheAttribute`] in the layout
|
||||
///
|
||||
/// Attributes are added starting from 0 counting up
|
||||
///
|
||||
/// Returns the index of the new added attirbute
|
||||
pub fn add_attribute(&mut self, attribute: CacheAttribute) -> usize
|
||||
{
|
||||
let index = self.attributes.len();
|
||||
self.attributes.push(attribute);
|
||||
index
|
||||
}
|
||||
|
||||
/// Produces a wgsl declaration describing this layout :
|
||||
///
|
||||
/// ```wgsl
|
||||
///
|
||||
/// const ATTRIBUTE_COUNT: u32 = /* attribute count */;
|
||||
/// const ATTRIBUTE_WORD_COUNTS: array<u32, ...> = {
|
||||
/// /* word count for attribute 0 */,
|
||||
/// /* word count for attribute 1 */,
|
||||
/// ...
|
||||
/// };
|
||||
///
|
||||
/// const ATTRIBUTE_COPY: array<bool, ...> = {
|
||||
/// /* external? for attribute 0 */,
|
||||
/// /* external? for attribute 1 */,
|
||||
/// ...
|
||||
/// };
|
||||
///
|
||||
/// ```
|
||||
pub fn wgsl_layout_decl(&self) -> String
|
||||
{
|
||||
let mut decl = String::new();
|
||||
|
||||
decl += &format!("const ATTRIBUTE_COUNT: u32 = {};", self.attributes.len());
|
||||
|
||||
// Word counts
|
||||
decl += &format!(
|
||||
"const ATTRIBUTE_WORD_COUNTS: array<u32, {}> = array<u32, {}>(",
|
||||
self.attributes.len(),
|
||||
self.attributes.len()
|
||||
);
|
||||
|
||||
for attribute in self.attributes.iter()
|
||||
{
|
||||
decl += &format!(" {},", attribute.word_count);
|
||||
}
|
||||
|
||||
decl += ");";
|
||||
|
||||
// Copy
|
||||
decl += &format!(
|
||||
"const ATTRIBUTE_COPY: array<bool, {}> = array<bool, {}>(",
|
||||
self.attributes.len(),
|
||||
self.attributes.len()
|
||||
);
|
||||
|
||||
for attribute in self.attributes.iter()
|
||||
{
|
||||
decl += &format!(" {},", attribute.init == CacheAttributeInit::External);
|
||||
}
|
||||
|
||||
decl += ");";
|
||||
|
||||
decl
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
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;
|
||||
use crate::voxel_cache::requests::CacheRequestBuffer;
|
||||
use crate::voxel_cache::requests::CacheRequestHandler;
|
||||
use crate::voxel_cache::structure::CacheStructure;
|
||||
|
||||
macro_rules! programmatic_common_wgsl {
|
||||
($children_count:ident, $page_count:ident, $cache_layout:ident) => {
|
||||
format!(
|
||||
"
|
||||
const CHILDREN_COUNT: u32 = u32({});
|
||||
const PAGE_COUNT: u32 = u32({});
|
||||
|
||||
// Cache layout
|
||||
{}
|
||||
",
|
||||
$children_count * $children_count * $children_count,
|
||||
$page_count,
|
||||
$cache_layout.wgsl_layout_decl()
|
||||
)
|
||||
.as_str()
|
||||
};
|
||||
}
|
||||
|
||||
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/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 {
|
||||
label: Some($path),
|
||||
source: wgpu::ShaderSource::Wgsl(full_shader.into()),
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
pub(super) use include_cache_wgsl;
|
||||
|
||||
pub struct WriteRequestsPass<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pipeline: ComputePipeline,
|
||||
// To compute indirect dispatch count from request count
|
||||
indirect_buffer: IndirectBuffer1D,
|
||||
}
|
||||
|
||||
impl<const N: usize> WriteRequestsPass<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, cache_layout: &CacheLayout) -> Self
|
||||
{
|
||||
// Binds
|
||||
// - structure
|
||||
// - request buffer
|
||||
|
||||
let bindings = [
|
||||
// To get the location information
|
||||
Some(&CacheStructure::<N>::create_bind_group_layout(device)),
|
||||
// To get which pages have had a request issued on them
|
||||
Some(&CacheRequestHandler::<N>::create_bind_group_layout(device)),
|
||||
// To write the request information to target
|
||||
Some(&CacheRequestBuffer::create_bind_group_layout(device)),
|
||||
];
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("WriteRequestsPass::pipeline_layout"),
|
||||
bind_group_layouts: &bindings,
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let shader_module = device.create_shader_module(include_cache_wgsl!(
|
||||
"./shaders/write_requests.wgsl",
|
||||
N,
|
||||
page_count,
|
||||
cache_layout
|
||||
));
|
||||
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("WriteRequestsPass::pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("write_requests"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
pipeline,
|
||||
indirect_buffer: IndirectBuffer1D::new(device),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode(
|
||||
&self,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
device: &Device,
|
||||
cache_structure: &CacheStructure<N>,
|
||||
cache_request_handler: &CacheRequestHandler<N>,
|
||||
target_request_buffer: &CacheRequestBuffer,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "WriteRequests");
|
||||
|
||||
let indirect_dispatch_buffer = self.indirect_buffer.workgroup_count(
|
||||
device,
|
||||
&mut encoder,
|
||||
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,
|
||||
});
|
||||
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_bind_group(0, cache_structure.bind_group(), &[]);
|
||||
pass.set_bind_group(1, cache_request_handler.bind_group(), &[]);
|
||||
pass.set_bind_group(2, target_request_buffer.bind_group(), &[]);
|
||||
|
||||
pass.dispatch_workgroups_indirect(indirect_dispatch_buffer, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts new pages in the cache
|
||||
pub struct CacheInsertionPass<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
/// 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<const N: usize> CacheInsertionPass<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self
|
||||
{
|
||||
// Binds
|
||||
// - 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::<N>::create_bind_group_layout(
|
||||
device, layout,
|
||||
)),
|
||||
// To write the new locations, pointers
|
||||
Some(&CacheStructure::<N>::create_bind_group_layout(device)),
|
||||
// New incoming attributes
|
||||
Some(&CacheInsertionData::<N>::create_bind_group_layout(
|
||||
device,
|
||||
Some(layout),
|
||||
)),
|
||||
// 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,
|
||||
|
||||
// To pass the new timestamp
|
||||
immediate_size: size_of::<u32>() as u32,
|
||||
});
|
||||
|
||||
let shader_module = device.create_shader_module(include_cache_wgsl!(
|
||||
"./shaders/insertion.wgsl",
|
||||
N,
|
||||
page_count,
|
||||
layout
|
||||
));
|
||||
|
||||
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"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
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<CommandEncoder>,
|
||||
cache_attributes: &CacheAttributes<N>,
|
||||
cache_structure: &CacheStructure<N>,
|
||||
insertion_data: &CacheInsertionData<N>,
|
||||
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_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, &[]);
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// Invalidates pointers that are pointing to recycled pages
|
||||
pub struct CacheInvalidationPass<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
workgroup_count: u32,
|
||||
pipeline: ComputePipeline,
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheInvalidationPass<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self
|
||||
{
|
||||
// Binds
|
||||
// - structure
|
||||
// - request buffer
|
||||
|
||||
let bindings = [
|
||||
// To find where pages are pointing
|
||||
Some(&CacheStructure::<N>::create_bind_group_layout(device)),
|
||||
// To read timestamp on which invalidation is marked
|
||||
Some(&CacheEvictor::create_bind_group_layout(device)),
|
||||
];
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("CacheInvalidationPass::pipeline_layout"),
|
||||
bind_group_layouts: &bindings,
|
||||
|
||||
// For setting the correct timestamp after invalidation
|
||||
immediate_size: size_of::<u32>() as u32,
|
||||
});
|
||||
|
||||
let shader_module = device.create_shader_module(include_cache_wgsl!(
|
||||
"./shaders/invalidation.wgsl",
|
||||
N,
|
||||
page_count,
|
||||
layout
|
||||
));
|
||||
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("CacheInvalidationPass::pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("invalidation"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
workgroup_count: page_count.div_ceil(256) as u32,
|
||||
pipeline,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode(
|
||||
&self,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
cache_structure: &CacheStructure<N>,
|
||||
cache_evictor: &CacheEvictor,
|
||||
timestamp: u32,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "CacheInvalidation");
|
||||
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("CacheInvalidationPass::pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
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_immediates(0, bytemuck::bytes_of(×tamp));
|
||||
|
||||
pass.dispatch_workgroups(self.workgroup_count, 1, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Points the pages to the newly cached pages
|
||||
pub struct WritePointersPass<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pipeline: ComputePipeline,
|
||||
indirect_buffer: IndirectBuffer1D,
|
||||
}
|
||||
|
||||
impl<const N: usize> WritePointersPass<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self
|
||||
{
|
||||
let bindings = [
|
||||
// To find where pages are pointing
|
||||
Some(&CacheStructure::<N>::create_bind_group_layout(device)),
|
||||
// To find where the requests came from
|
||||
Some(&CacheRequestBuffer::create_bind_group_layout(device)),
|
||||
// To find where the request's response went
|
||||
Some(&CacheInsertionData::<N>::create_bind_group_layout(
|
||||
device,
|
||||
Some(layout),
|
||||
)),
|
||||
];
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("WritePointersPass::pipeline_layout"),
|
||||
bind_group_layouts: &bindings,
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let shader_module = device.create_shader_module(include_cache_wgsl!(
|
||||
"./shaders/write_pointers.wgsl",
|
||||
N,
|
||||
page_count,
|
||||
layout
|
||||
));
|
||||
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("WritePointersPass::pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader_module,
|
||||
entry_point: Some("write_pointers"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
pipeline,
|
||||
indirect_buffer: IndirectBuffer1D::new(device),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode(
|
||||
&self,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
device: &Device,
|
||||
cache_structure: &CacheStructure<N>,
|
||||
request_buffer: &CacheRequestBuffer,
|
||||
cache_insertion_data: &CacheInsertionData<N>,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "WritePointers");
|
||||
|
||||
let indirect_buffer = self.indirect_buffer.workgroup_count(
|
||||
device,
|
||||
&mut encoder,
|
||||
cache_insertion_data.page_count_buffer(),
|
||||
256,
|
||||
);
|
||||
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("WritePointersPass::pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_bind_group(0, cache_structure.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);
|
||||
}
|
||||
}
|
||||
@@ -1,369 +0,0 @@
|
||||
// The cache emits requests, and receives answer to these requests
|
||||
// The cache producer interface provides the necessary buffers to contains
|
||||
// these, so that use applications can fullfill the requests
|
||||
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::BindGroupEntry;
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::BindGroupLayoutEntry;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::Device;
|
||||
use wgpu::Queue;
|
||||
use wgpu::util::DownloadBuffer;
|
||||
|
||||
use crate::voxel_cache::data::ColorPoolElement;
|
||||
use crate::voxel_cache::data::LocationPoolElement;
|
||||
use crate::voxel_cache::data::StructurePoolElement;
|
||||
|
||||
#[derive(Clone, Copy, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct CacheRequest
|
||||
{
|
||||
pub structure_id: u32,
|
||||
pub locator: u32,
|
||||
pub child_index: u32,
|
||||
}
|
||||
|
||||
pub(super) struct CacheRequestWbInfo
|
||||
{
|
||||
node_index: u32,
|
||||
child_index: u32,
|
||||
}
|
||||
|
||||
pub struct CacheProducerInterface<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
// Request emissions
|
||||
pub(super) size: usize,
|
||||
|
||||
// Contains the specific node being requested
|
||||
pub(super) requests: Buffer,
|
||||
|
||||
// Contains how many request have effectively been emitted
|
||||
pub(super) request_count: Buffer,
|
||||
|
||||
// Contains on which node the request was done
|
||||
pub(super) requests_wb_info: Buffer,
|
||||
// Request fullfillment
|
||||
pub(super) structure_nodes: Buffer,
|
||||
pub(super) color_nodes: Buffer,
|
||||
pub(super) location_nodes: Buffer,
|
||||
|
||||
pub(super) request_side_bind_group_layout: BindGroupLayout,
|
||||
pub(super) request_side_bind_group: BindGroup,
|
||||
|
||||
pub(super) producer_side_bind_group_layout: BindGroupLayout,
|
||||
pub(super) producer_side_bind_group: BindGroup,
|
||||
}
|
||||
impl<const N: usize> CacheProducerInterface<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(size: usize, device: &Device) -> Self
|
||||
{
|
||||
let requests = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("cache_interface_request_buffer"),
|
||||
size: (size_of::<CacheRequest>() * size) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let requests_wb_info = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("cache_interface_writeback_info"),
|
||||
size: (size_of::<CacheRequestWbInfo>() * size) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let structure_nodes = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("cache_interface_structure_nodes"),
|
||||
size: (size_of::<StructurePoolElement<N>>() * size) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST,
|
||||
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,
|
||||
});
|
||||
|
||||
let location_nodes = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("cache_interface_structure_nodes"),
|
||||
size: (size_of::<LocationPoolElement>() * size) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let request_count = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("cache_interface_request_count"),
|
||||
size: (size_of::<u32>()) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let request_side_bind_group_layout = Self::request_side_bind_group_layout(device);
|
||||
let producer_side_bind_group_layout =
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("cache_interface_producer_side_bind_group_layout"),
|
||||
entries: &[
|
||||
// Reqests
|
||||
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,
|
||||
},
|
||||
// Request count
|
||||
BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
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,
|
||||
},
|
||||
// Structure nodes
|
||||
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,
|
||||
},
|
||||
// Color nodes
|
||||
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,
|
||||
},
|
||||
// Location nodes
|
||||
BindGroupLayoutEntry {
|
||||
binding: 4,
|
||||
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,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// Bind groups
|
||||
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,
|
||||
entries: &[
|
||||
BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: requests.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: requests_wb_info.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: request_count.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: structure_nodes.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: color_nodes.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 5,
|
||||
resource: location_nodes.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let producer_side_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("cache_interface_producer_side_bind_group"),
|
||||
layout: &producer_side_bind_group_layout,
|
||||
entries: &[
|
||||
BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: requests.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: request_count.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: structure_nodes.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: color_nodes.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: location_nodes.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
Self {
|
||||
size,
|
||||
requests,
|
||||
request_count,
|
||||
requests_wb_info,
|
||||
structure_nodes,
|
||||
color_nodes,
|
||||
location_nodes,
|
||||
|
||||
request_side_bind_group_layout,
|
||||
request_side_bind_group,
|
||||
producer_side_bind_group_layout,
|
||||
producer_side_bind_group,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn requests_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.requests
|
||||
}
|
||||
|
||||
pub fn structure_nodes_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.structure_nodes
|
||||
}
|
||||
|
||||
pub fn color_nodes_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.color_nodes
|
||||
}
|
||||
|
||||
pub fn location_nodes_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.location_nodes
|
||||
}
|
||||
|
||||
pub fn total_request_count(&self, device: &Device, queue: &Queue) -> u32
|
||||
{
|
||||
let (tx, rx) = std::sync::mpsc::sync_channel(1);
|
||||
wgpu::util::DownloadBuffer::read_buffer(
|
||||
device,
|
||||
queue,
|
||||
&self.request_count.slice(0..),
|
||||
move |download_buffer| {
|
||||
let vec = download_buffer.unwrap().to_vec();
|
||||
let value = u32::from_ne_bytes(std::array::from_fn(|i| vec[i]));
|
||||
let _ = tx.try_send(value);
|
||||
},
|
||||
);
|
||||
|
||||
loop
|
||||
{
|
||||
if let Ok(value) = rx.try_recv()
|
||||
{
|
||||
return value;
|
||||
}
|
||||
device.poll(wgpu::wgt::PollType::Poll).unwrap();
|
||||
}
|
||||
|
||||
//panic!("Could not retrieve total request count.");
|
||||
}
|
||||
|
||||
pub fn request_side_bind_group_layout(device: &Device) -> BindGroupLayout
|
||||
{
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("cache_interface_request_side_bind_group_layout"),
|
||||
entries: &[
|
||||
// Reqests
|
||||
BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
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,
|
||||
},
|
||||
// Requests writeback
|
||||
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: None,
|
||||
},
|
||||
// Request count
|
||||
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,
|
||||
},
|
||||
// Structure nodes
|
||||
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,
|
||||
},
|
||||
// Color nodes
|
||||
BindGroupLayoutEntry {
|
||||
binding: 4,
|
||||
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,
|
||||
},
|
||||
// Location nodes
|
||||
BindGroupLayoutEntry {
|
||||
binding: 5,
|
||||
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,
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,644 +0,0 @@
|
||||
use bytemuck::bytes_of;
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::BindGroupEntry;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::Device;
|
||||
use wgpu::ShaderStages;
|
||||
|
||||
use crate::voxel_cache::data::RequestBufferElement;
|
||||
|
||||
pub struct RequestBuffer<const N: usize>
|
||||
{
|
||||
pub cache_size: usize,
|
||||
pub request_buffer: Buffer,
|
||||
pub request_count_buffer: Buffer,
|
||||
pub indirect_count_storage: Buffer,
|
||||
pub element_sort_count_buffer: Buffer,
|
||||
pub indirect_count: Buffer,
|
||||
pub sort_buffer: Buffer,
|
||||
pub reset_pipeline: ComputePipeline,
|
||||
pub sort_pipeline: ComputePipeline,
|
||||
pub bindgroup: BindGroup,
|
||||
pub device: Device,
|
||||
|
||||
pub compaction_pipeline: ComputePipeline,
|
||||
pub running_sum_pipeline: ComputePipeline,
|
||||
}
|
||||
|
||||
impl<const N: usize> RequestBuffer<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub fn new(cache_size: usize, device: Device) -> Self
|
||||
{
|
||||
let request_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(format!("request_buffer_{N}").as_str()),
|
||||
size: (size_of::<RequestBufferElement<N>>() * cache_size) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let request_count_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Request_count_buffer"),
|
||||
size: size_of::<u32>() as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let indirect_count = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("indirect_count_buffer"),
|
||||
usage: BufferUsages::INDIRECT | BufferUsages::COPY_DST,
|
||||
size: size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let indirect_count_storage = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("indirect_count_storage_buffer"),
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
size: size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let element_sort_count_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("indirect_count_storage_buffer"),
|
||||
usage: BufferUsages::STORAGE,
|
||||
size: size_of::<u32>() as u64,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
// One element number per child entry
|
||||
// One number to identify node, one to identify sub child
|
||||
let sort_buffer_count = cache_size * N * N * N;
|
||||
let sort_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(format!("request_sort_buffer_{N}").as_str()),
|
||||
size: (size_of::<(u32, u32)>() * sort_buffer_count) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: true,
|
||||
});
|
||||
|
||||
let init_data = (0..(cache_size as u32))
|
||||
.flat_map(|i| (0..((N * N * N) as u32)).map(move |j| (i, j)))
|
||||
.flat_map(|(i, j)| [i, j]) // Because bytemuck does not like tuples ...
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
sort_buffer
|
||||
.get_mapped_range_mut(0..)
|
||||
.unwrap()
|
||||
.copy_from_slice(bytemuck::cast_slice(&init_data));
|
||||
sort_buffer.unmap();
|
||||
|
||||
let bindgroup_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("request_sort_pipeline_bing_group_layout"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 3,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 4,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let bindgroup = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("request_sort_pipeline_bindgroup"),
|
||||
layout: &bindgroup_layout,
|
||||
entries: &[
|
||||
BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: request_buffer.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: sort_buffer.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: request_count_buffer.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: indirect_count_storage.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: element_sort_count_buffer.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let pipeline_layouts = &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("request_buffer_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&bindgroup_layout)],
|
||||
immediate_size: size_of::<u32>() as u32,
|
||||
});
|
||||
|
||||
let children_count = N * N * N;
|
||||
let sort_pipeline =
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("Sort node request"),
|
||||
layout: Some(pipeline_layouts),
|
||||
module: &device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("clear_chunk_requests shader module"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
format!("
|
||||
struct RequestElement
|
||||
{{
|
||||
children: array<u32, {children_count}>
|
||||
}}
|
||||
|
||||
struct SortElement
|
||||
{{
|
||||
node: u32,
|
||||
child: u32
|
||||
}}
|
||||
|
||||
var<immediate> both_phase: u32;
|
||||
|
||||
@group(0) @binding(0) var<storage, read_write> request_buffer: array<RequestElement>;
|
||||
@group(0) @binding(1) var<storage, read_write> sort_indirection: array<SortElement>;
|
||||
@group(0) @binding(2) var<storage, read_write> request_count: u32;
|
||||
@group(0) @binding(3) var<storage, read_write> indirect_count: vec3<u32>;
|
||||
@group(0) @binding(4) var<storage, read_write> element_sort_count: u32;
|
||||
|
||||
fn big_fusion(index: u32, phase_size: u32) -> vec2<u32>
|
||||
{{
|
||||
// Find out in which block index this invocation pertains
|
||||
let block_index = index / (phase_size / 2);
|
||||
let element_index = index % (phase_size / 2);
|
||||
|
||||
let offset = block_index * phase_size;
|
||||
let a = offset + element_index;
|
||||
let b = offset + phase_size - 1 - element_index;
|
||||
return vec2<u32>(a, b);
|
||||
}}
|
||||
|
||||
fn small_fusion(index: u32, phase: u32, sub_phase: u32) -> vec2<u32>
|
||||
{{
|
||||
let phase_size = u32(1 << (phase - sub_phase + 1));
|
||||
|
||||
let block_index = index / (phase_size / 2);
|
||||
let element_index = index % (phase_size / 2);
|
||||
|
||||
let offset = block_index * phase_size;
|
||||
let a = offset + element_index;
|
||||
let b = a + (phase_size / 2);
|
||||
return vec2<u32>(a, b);
|
||||
}}
|
||||
|
||||
|
||||
@compute
|
||||
@workgroup_size(64)
|
||||
fn main(
|
||||
@builtin(global_invocation_id) global_invocation_id: vec3<u32>
|
||||
)
|
||||
{{
|
||||
|
||||
let index = global_invocation_id.x;
|
||||
let total = arrayLength(&sort_indirection);
|
||||
|
||||
let sub_phase = (both_phase >> 16) & 0xFFFF;
|
||||
let phase = both_phase & 0xFFFF;
|
||||
let phase_total_width = u32(1 << (phase + 1));
|
||||
|
||||
|
||||
// Check if phase is last
|
||||
/*
|
||||
if(phase == sub_phase)
|
||||
{{
|
||||
let next_phase_width = phase_total_width * 2;
|
||||
if(next_phase_width >= element_sort_count && phase_total_width >= element_sort_count)
|
||||
{{
|
||||
// This was the final phase, stop
|
||||
indirect_count = vec3<u32>(0);
|
||||
}}
|
||||
}}
|
||||
*/
|
||||
|
||||
if(phase == 0)
|
||||
{{
|
||||
let a = index * 2;
|
||||
let b = a + 1;
|
||||
sort_indirection[a].child = a % {children_count};
|
||||
sort_indirection[b].child = b % {children_count};
|
||||
}}
|
||||
|
||||
var swap_indices = vec2<u32>(0, 0);
|
||||
|
||||
if(sub_phase == 0)
|
||||
{{
|
||||
// Bitonic fusion
|
||||
swap_indices = big_fusion(index, phase_total_width);
|
||||
}}else
|
||||
{{
|
||||
swap_indices = small_fusion(index, phase, sub_phase);
|
||||
}}
|
||||
|
||||
// Do swap
|
||||
|
||||
//if(swap_indices.y >= request_count_round_up)
|
||||
if(swap_indices.y >= element_sort_count)
|
||||
{{
|
||||
// Suppose that swap_indices.y is -inf, dont swap
|
||||
return;
|
||||
}}
|
||||
|
||||
let av = request_buffer[sort_indirection[swap_indices.x].node].children[sort_indirection[swap_indices.x].child];
|
||||
let bv = request_buffer[sort_indirection[swap_indices.y].node].children[sort_indirection[swap_indices.y].child];
|
||||
|
||||
if(bv > av)
|
||||
{{
|
||||
let temp = sort_indirection[swap_indices.x];
|
||||
sort_indirection[swap_indices.x] = sort_indirection[swap_indices.y];
|
||||
sort_indirection[swap_indices.y] = temp;
|
||||
}}
|
||||
}}
|
||||
")
|
||||
.into(),
|
||||
),
|
||||
}),
|
||||
entry_point: Some("main"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let running_sum_pipeline =
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("running_sum_pipeline"),
|
||||
layout: Some(pipeline_layouts),
|
||||
module: &device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("running_sum shader module"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
format!("
|
||||
struct RequestElement
|
||||
{{
|
||||
children: array<u32, {children_count}>
|
||||
}}
|
||||
|
||||
struct SortElement
|
||||
{{
|
||||
node: u32,
|
||||
child: u32
|
||||
}}
|
||||
|
||||
var<immediate> phase: u32;
|
||||
|
||||
@group(0) @binding(0) var<storage, read_write> request_buffer: array<RequestElement>;
|
||||
@group(0) @binding(1) var<storage, read_write> sort_indirection: array<SortElement>;
|
||||
@group(0) @binding(2) var<storage, read_write> request_counts: atomic<u32>;
|
||||
@group(0) @binding(3) var<storage, read_write> indirect_count: u32;
|
||||
@group(0) @binding(4) var<storage, read_write> node_sort_count: u32;
|
||||
|
||||
@compute
|
||||
@workgroup_size(64)
|
||||
fn main(
|
||||
@builtin(global_invocation_id) global_invocation_id: vec3<u32>
|
||||
)
|
||||
{{
|
||||
let index = global_invocation_id.x;
|
||||
let len = arrayLength(&request_buffer);
|
||||
if(index > len) {{ return; }}
|
||||
let sindex = index * {children_count};
|
||||
|
||||
if(phase == 0)
|
||||
{{
|
||||
var count = 0;
|
||||
for(var i = 0; i < {children_count}; i++)
|
||||
{{
|
||||
count += select(0, 1, request_buffer[index].children[i] != 0);
|
||||
}}
|
||||
|
||||
sort_indirection[sindex].child = select(u32(0), u32(1), count != 0);
|
||||
if count != 0
|
||||
{{
|
||||
atomicAdd(&request_counts, 1);
|
||||
}}
|
||||
return;
|
||||
}}
|
||||
|
||||
if(phase == 0xFFFFFFFF)
|
||||
{{
|
||||
// Double buffering bring back
|
||||
sort_indirection[sindex].child = sort_indirection[sindex].node;
|
||||
}}
|
||||
|
||||
// Phase is not zero, running sum part
|
||||
let running_sum_phase = phase - 1;
|
||||
let running_sum_offset = u32((1 << running_sum_phase) * {children_count});
|
||||
|
||||
var add = u32(0);
|
||||
// Double buffering
|
||||
if(running_sum_phase % 2 == 0)
|
||||
{{
|
||||
if(sindex >= running_sum_offset)
|
||||
{{
|
||||
add = sort_indirection[sindex - running_sum_offset].child;
|
||||
}}
|
||||
sort_indirection[sindex].node = sort_indirection[sindex].child + add;
|
||||
}}
|
||||
else
|
||||
{{
|
||||
if(sindex >= running_sum_offset)
|
||||
{{
|
||||
add = sort_indirection[sindex - running_sum_offset].node;
|
||||
}}
|
||||
sort_indirection[sindex].child = sort_indirection[sindex].node + add;
|
||||
}}
|
||||
}}
|
||||
")
|
||||
.into(),
|
||||
),
|
||||
}),
|
||||
entry_point: Some("main"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let compaction_pipeline =
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("compaction_pipeline"),
|
||||
layout: Some(pipeline_layouts),
|
||||
module: &device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("compaction shader module"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
format!("
|
||||
struct RequestElement
|
||||
{{
|
||||
children: array<u32, {children_count}>
|
||||
}}
|
||||
|
||||
struct SortElement
|
||||
{{
|
||||
node: u32,
|
||||
child: u32
|
||||
}}
|
||||
|
||||
var<immediate> phase: u32;
|
||||
|
||||
@group(0) @binding(0) var<storage, read_write> request_buffer: array<RequestElement>;
|
||||
@group(0) @binding(1) var<storage, read_write> sort_indirection: array<SortElement>;
|
||||
@group(0) @binding(2) var<storage, read_write> request_counts: atomic<u32>;
|
||||
@group(0) @binding(3) var<storage, read_write> indirect_count: vec3<u32>;
|
||||
@group(0) @binding(4) var<storage, read_write> element_sort_count: u32;
|
||||
|
||||
@compute
|
||||
@workgroup_size(64)
|
||||
fn main(
|
||||
@builtin(global_invocation_id) global_invocation_id: vec3<u32>
|
||||
)
|
||||
{{
|
||||
let index = global_invocation_id.x;
|
||||
let sindex = index * {children_count};
|
||||
let len = arrayLength(&request_buffer);
|
||||
|
||||
element_sort_count = sort_indirection[(len - 1) * {children_count}].child * {children_count};
|
||||
let invocation_count = (element_sort_count / 2) + select(u32(0), u32(1), element_sort_count % 2 != 0);
|
||||
indirect_count = vec3(
|
||||
(invocation_count / 64) + select(u32(0), u32(1), invocation_count % 64 != 0),
|
||||
1, 1
|
||||
);
|
||||
let destination_index = sort_indirection[sindex].child - 1;
|
||||
|
||||
var count = u32(0);
|
||||
for(var i = 0; i < {children_count}; i++)
|
||||
{{
|
||||
count += request_buffer[index].children[i];
|
||||
}}
|
||||
|
||||
if(count != 0) // Keep ?
|
||||
{{
|
||||
for(var i = u32(0); i < u32({children_count}); i++)
|
||||
{{
|
||||
sort_indirection[destination_index * u32({children_count}) + i].node = index;
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
")
|
||||
.into(),
|
||||
),
|
||||
}),
|
||||
entry_point: Some("main"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let reset_pipeline =
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("reset_node_requests"),
|
||||
layout: Some(pipeline_layouts),
|
||||
module: &device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("clear_chunk_requests shader module"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
format!("
|
||||
struct RequestElement
|
||||
{{
|
||||
children: array<u32, {children_count}>
|
||||
}}
|
||||
|
||||
@group(0) @binding(0) var<storage, read_write> request_buffer: array<RequestElement>;
|
||||
@group(0) @binding(1) var<storage, read_write> _ignore: array<u32>;
|
||||
@group(0) @binding(2) var<storage, read_write> request_count: u32;
|
||||
@group(0) @binding(4) var<storage, read_write> node_sort_count: u32;
|
||||
|
||||
@compute
|
||||
@workgroup_size(64)
|
||||
fn main(
|
||||
@builtin(global_invocation_id) global_invocation_id: vec3<u32>
|
||||
)
|
||||
{{
|
||||
let index = global_invocation_id.x;
|
||||
let total = arrayLength(&request_buffer);
|
||||
if(index >= total)
|
||||
{{ return; }}
|
||||
|
||||
if(index < total)
|
||||
{{
|
||||
for(var i = 0; i < {children_count}; i += 1)
|
||||
{{
|
||||
/*
|
||||
if(request_buffer[index].children[i] != 0)
|
||||
{{
|
||||
atomicAdd(&request_count, 1);
|
||||
}}
|
||||
*/
|
||||
request_buffer[index].children[i] = 0;
|
||||
}}
|
||||
request_count = 0;
|
||||
}}
|
||||
}}
|
||||
")
|
||||
.into(),
|
||||
),
|
||||
}),
|
||||
entry_point: Some("main"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
cache_size,
|
||||
request_buffer,
|
||||
request_count_buffer,
|
||||
indirect_count,
|
||||
indirect_count_storage,
|
||||
element_sort_count_buffer,
|
||||
running_sum_pipeline,
|
||||
sort_buffer,
|
||||
sort_pipeline,
|
||||
reset_pipeline,
|
||||
compaction_pipeline,
|
||||
bindgroup,
|
||||
device,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn request_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.request_buffer
|
||||
}
|
||||
|
||||
pub fn request_count_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.request_count_buffer
|
||||
}
|
||||
|
||||
pub fn sort_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.sort_buffer
|
||||
}
|
||||
|
||||
pub fn reset_requests(&self, encoder: &mut CommandEncoder)
|
||||
{
|
||||
let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("request_buffer_reset_compute_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
compute_pass.set_bind_group(0, Some(&self.bindgroup), &[]);
|
||||
compute_pass.set_pipeline(&self.reset_pipeline);
|
||||
|
||||
let shader_invocations = self.cache_size; // one invocation per element
|
||||
let workgroup_invocations = shader_invocations.div_ceil(64);
|
||||
compute_pass.dispatch_workgroups(workgroup_invocations as u32, 1, 1);
|
||||
}
|
||||
|
||||
pub fn sort_requests(&self, encoder: &mut CommandEncoder)
|
||||
{
|
||||
let mut compaction_compute_pass =
|
||||
encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("request_buffer_compaction_compute_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
compaction_compute_pass.set_bind_group(0, Some(&self.bindgroup), &[]);
|
||||
let request_element_count = self.cache_size; // Each child slot is sorted
|
||||
let workgroups_invocations = request_element_count.div_ceil(64);
|
||||
|
||||
// = Perform list compaction
|
||||
|
||||
// == Running sum
|
||||
compaction_compute_pass.set_pipeline(&self.running_sum_pipeline);
|
||||
|
||||
// Phase 0: Put ones in correct location
|
||||
compaction_compute_pass.set_immediates(0, bytes_of(&0));
|
||||
compaction_compute_pass.dispatch_workgroups(workgroups_invocations as u32, 1, 1);
|
||||
// Phase _: running sum
|
||||
// Running sum phase
|
||||
let running_sum_steps = request_element_count.next_power_of_two().ilog2();
|
||||
for i in 1..=running_sum_steps
|
||||
{
|
||||
compaction_compute_pass.set_immediates(0, bytes_of(&i));
|
||||
compaction_compute_pass.dispatch_workgroups(workgroups_invocations as u32, 1, 1);
|
||||
}
|
||||
|
||||
if !running_sum_steps.is_multiple_of(2)
|
||||
{
|
||||
// Bring back double buffer
|
||||
compaction_compute_pass.set_immediates(0, bytes_of(&0xFFFFFFFF_u32));
|
||||
compaction_compute_pass.dispatch_workgroups(workgroups_invocations as u32, 1, 1);
|
||||
}
|
||||
|
||||
// == Stream compaction
|
||||
compaction_compute_pass.set_pipeline(&self.compaction_pipeline);
|
||||
compaction_compute_pass.dispatch_workgroups(workgroups_invocations as u32, 1, 1);
|
||||
drop(compaction_compute_pass);
|
||||
|
||||
// == Copy count into indirect buffer
|
||||
|
||||
// = Sort
|
||||
|
||||
// == Bitonic sort
|
||||
let sort_element_count = self.cache_size * N * N * N;
|
||||
let phases_upper_bound = sort_element_count.next_power_of_two().ilog2();
|
||||
|
||||
// Phase 0 dispatch all
|
||||
for i in 0..=phases_upper_bound
|
||||
{
|
||||
encoder.copy_buffer_to_buffer(
|
||||
&self.indirect_count_storage,
|
||||
0,
|
||||
&self.indirect_count,
|
||||
0,
|
||||
Some(size_of::<wgpu::util::DispatchIndirectArgs>() as u64),
|
||||
);
|
||||
let mut sort_compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some(format!("request_buffer_sort_compute_pass_{}", 0).as_str()),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
sort_compute_pass.set_bind_group(0, Some(&self.bindgroup), &[]);
|
||||
sort_compute_pass.set_pipeline(&self.sort_pipeline);
|
||||
for j in 0..=i
|
||||
{
|
||||
sort_compute_pass.set_immediates(0, bytemuck::bytes_of(&(i | (j << 16))));
|
||||
sort_compute_pass.dispatch_workgroups_indirect(&self.indirect_count, 0);
|
||||
}
|
||||
drop(sort_compute_pass);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::Device;
|
||||
use wgpu::include_wgsl;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::gpu::buffer_compactor::NonZeroBufferCompactor;
|
||||
use crate::gpu::create_multi_buffers_bind_group;
|
||||
use crate::gpu::radix_sort::{self};
|
||||
use crate::gpu_profiler::ScopeEncoder;
|
||||
use crate::gpu_profiler::memory_profiler;
|
||||
use crate::gpu_profiler::{self};
|
||||
use crate::voxel_cache::CacheRessources;
|
||||
use crate::voxel_cache::create_multi_buffers_bg_bg_layout;
|
||||
use crate::voxel_cache::create_multi_buffers_bind_group_layout;
|
||||
use crate::voxel_cache::schema::RequestInformation;
|
||||
use crate::voxel_cache::schema::RequestMeta;
|
||||
|
||||
/// Records, handles, and produces a list of requested data inside the cache
|
||||
pub struct CacheRequestHandler<const N: usize>
|
||||
{
|
||||
/// Contains a u32 per pointer of the cache, that records an amount of request by the cache user.
|
||||
/// This can then be used to prioritize request based on demand
|
||||
request_counts_pages: wgpu::Buffer,
|
||||
|
||||
/// Ultimately contains sorted requests
|
||||
sorted_requests: wgpu::Buffer,
|
||||
|
||||
/// Number of requests
|
||||
request_count: wgpu::Buffer,
|
||||
|
||||
compactor: NonZeroBufferCompactor,
|
||||
|
||||
// Pass to reset the requests
|
||||
reset_pass_bind_group: BindGroup,
|
||||
reset_pass: ComputePipeline,
|
||||
reset_pass_dispatch: u32,
|
||||
|
||||
// External bind group
|
||||
bind_group_layout: BindGroupLayout,
|
||||
bind_group: BindGroup,
|
||||
}
|
||||
|
||||
/// Records requests made by the cache
|
||||
pub struct CacheRequestBuffer
|
||||
{
|
||||
pub max_requests: usize,
|
||||
|
||||
/// Buffer containing the amount of requests made by the cache, under max requsets
|
||||
pub request_count: wgpu::Buffer,
|
||||
|
||||
/// Buffer containing the requsets made by the cache, a dense array of [`voxel_cache::schema::RequestInformation`]
|
||||
pub request_informations: wgpu::Buffer,
|
||||
|
||||
/// Buffer containing the meta information about the requests, a dense array of [`voxel_cache::schema::RequestMeta`]
|
||||
request_meta: wgpu::Buffer,
|
||||
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
bind_group: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheRequestHandler<N>
|
||||
{
|
||||
pub fn new(device: &mut memory_profiler::Device, page_count: usize) -> Self
|
||||
{
|
||||
let request_counts_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheRequestHandler::request_counts_pages"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
contents: bytemuck::cast_slice(&vec![0u32; page_count * N * N * N]),
|
||||
});
|
||||
|
||||
let sorted_requests = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheRequestHandler::sorted_requests"),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
contents: bytemuck::cast_slice(&vec![0u32; page_count * N * N * N]),
|
||||
});
|
||||
|
||||
let request_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheRequestHandler::request_count"),
|
||||
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],
|
||||
Some("CacheRequestHandler::reset_pass_bind_group"),
|
||||
);
|
||||
|
||||
let reset_pass_pipeline_layout =
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("CacheRequestHandler::reset_pass_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&reset_pass_bg_layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let reset_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("CacheRequestHandler::reset_pass"),
|
||||
layout: Some(&reset_pass_pipeline_layout),
|
||||
module: &device.create_shader_module(include_wgsl!("./shaders/requests.wgsl")),
|
||||
entry_point: Some("reset_requests"),
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let bind_group_layout = Self::create_bind_group_layout(device);
|
||||
let bind_group = create_multi_buffers_bind_group(
|
||||
device,
|
||||
&bind_group_layout,
|
||||
&[&request_count, &sorted_requests],
|
||||
Some("CacheRequestHandler::bind_group"),
|
||||
);
|
||||
|
||||
Self {
|
||||
request_counts_pages,
|
||||
sorted_requests,
|
||||
request_count,
|
||||
compactor: NonZeroBufferCompactor::new(device, page_count * N * N * N),
|
||||
|
||||
reset_pass_bind_group,
|
||||
reset_pass,
|
||||
reset_pass_dispatch: ((page_count * N * N * N) as u32).div_ceil(256),
|
||||
|
||||
bind_group_layout,
|
||||
bind_group,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sorts the requests currently held by the request handler in order to process them.
|
||||
///
|
||||
/// Uses both the sorter and the scratch buffer in the ressources
|
||||
///
|
||||
/// The `request_count` buffer will contain the amount of request produced this time.
|
||||
pub fn sort_requests(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
ressources: &CacheRessources<N>,
|
||||
encoder: &mut ScopeEncoder<CommandEncoder>,
|
||||
)
|
||||
{
|
||||
gpu_profiler::begin_scope!(encoder, "RequestHandler::sort_requests");
|
||||
|
||||
// First perform a fast compaction sort
|
||||
{
|
||||
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);
|
||||
|
||||
// State:
|
||||
// At this point the `sorted_requests` buffer contains the compacted indices of the request counts
|
||||
// and the scratch buffer contains the associated values
|
||||
|
||||
// The indices can now be sorted using `sorted_requests` as values and
|
||||
// `ressources.scratch_buffer` as keys for a sort operation
|
||||
|
||||
// We use the amount of non zero request as the indirect count so that we can sort only the
|
||||
// compacted, non-null requests
|
||||
{
|
||||
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
|
||||
{
|
||||
create_multi_buffers_bind_group_layout(
|
||||
device,
|
||||
2,
|
||||
Some("CacheRequestHandler::bind_group_layout"),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &BindGroup
|
||||
{
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
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<CommandEncoder>)
|
||||
{
|
||||
let mut compute_pass = encoder.begin_profiled_compute_pass("CacheRequestHandler::reset");
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
impl CacheRequestBuffer
|
||||
{
|
||||
/// Creates a request buffer that can contain at most `max_amount` requests
|
||||
pub fn new(device: &Device, max_requests: usize) -> Self
|
||||
{
|
||||
let request_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheRequestBuffer::request_count"),
|
||||
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 | wgpu::BufferUsages::COPY_SRC,
|
||||
size: (size_of::<RequestInformation>() * 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 | wgpu::BufferUsages::COPY_SRC,
|
||||
size: (size_of::<RequestMeta>() * max_requests) as u64,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let bind_group_layout = Self::create_bind_group_layout(device);
|
||||
let bind_group = create_multi_buffers_bind_group(
|
||||
device,
|
||||
&bind_group_layout,
|
||||
&[&request_count, &request_informations, &request_meta],
|
||||
Some("CacheRequestBuffer::bind_group"),
|
||||
);
|
||||
|
||||
Self {
|
||||
max_requests,
|
||||
request_count,
|
||||
request_informations,
|
||||
request_meta,
|
||||
|
||||
bind_group_layout,
|
||||
bind_group,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_bind_group_layout(device: &Device) -> BindGroupLayout
|
||||
{
|
||||
create_multi_buffers_bind_group_layout(
|
||||
device,
|
||||
3,
|
||||
Some("CacheRequestBuffer::bind_group_layout"),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &BindGroup
|
||||
{
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
pub fn host_download_requests<F: FnMut(&[RequestInformation]) + Send + Sync + 'static>(
|
||||
&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<RequestInformation> =
|
||||
bytemuck::pod_collect_to_vec(&mapped_buffer);
|
||||
|
||||
request_map_state_2
|
||||
.lock()
|
||||
.unwrap()
|
||||
.set_request_infos(request_infos);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
struct RequestMapState<F: FnMut(&[RequestInformation]) -> () + Send + Sync + 'static>
|
||||
{
|
||||
request_count: Option<usize>,
|
||||
request_infos: Option<Vec<RequestInformation>>,
|
||||
callback: F,
|
||||
}
|
||||
|
||||
impl<F: FnMut(&[RequestInformation]) -> () + Send + Sync + 'static> RequestMapState<F>
|
||||
{
|
||||
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<RequestInformation>)
|
||||
{
|
||||
self.request_infos = Some(request_infos);
|
||||
self.try_callback();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
/// Contains definitions of the data layouts for the cache
|
||||
use std::ops::BitOr;
|
||||
|
||||
use bytemuck::Pod;
|
||||
use bytemuck::Zeroable;
|
||||
|
||||
/// CachePointer represents a pointer in the [`VoxelCache`]
|
||||
///
|
||||
/// Pointers are used in the structure pool of the cache and encodes the N-tree itself
|
||||
///
|
||||
/// Three states are possible :
|
||||
///
|
||||
/// - unsubdivisable: This children of the node cannot be subdivided further
|
||||
/// - subdivisable: This children of the node can be subdivided further ...
|
||||
/// - unavailable: ... but is not currently available in the cache
|
||||
/// - available: ... is currently available in the cache and the pointer is valid
|
||||
///
|
||||
///
|
||||
/// The layout is the following
|
||||
///
|
||||
/// - bit 31: subdivisable?
|
||||
/// - bit 30: available?
|
||||
/// - bit 0..29: pointer (only relevant if available is 1)
|
||||
///
|
||||
#[derive(Clone, Copy, Debug, Zeroable, Pod)]
|
||||
#[repr(transparent)]
|
||||
pub struct CachePointer(u32);
|
||||
|
||||
impl CachePointer
|
||||
{
|
||||
/// First option represents subdivisability
|
||||
/// Second option represents availability
|
||||
///
|
||||
/// None -> unsubdivisable
|
||||
/// Some(None) -> subdivisable not available
|
||||
/// Some(Some(ptr)) -> subdivisable, available a pointer ptr
|
||||
pub fn new(value: Option<Option<u32>>) -> Self
|
||||
{
|
||||
CachePointer(match value
|
||||
{
|
||||
Some(available) => match available
|
||||
{
|
||||
Some(pointer) =>
|
||||
{
|
||||
assert_eq!(
|
||||
pointer >> 30,
|
||||
0,
|
||||
"Provided pointer is to big and does not fit in CachePointer. Last two bits must be null."
|
||||
);
|
||||
(1 << 31) | (1 << 30) | pointer
|
||||
}
|
||||
None => 1 << 31,
|
||||
},
|
||||
None => 0,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn as_option(&self) -> Option<Option<u32>>
|
||||
{
|
||||
let subdivisable = (self.0 >> 31) != 0;
|
||||
let available = ((self.0 >> 30) & 1) != 0;
|
||||
let pointer = self.0 & 0x3FFFFFFF;
|
||||
|
||||
match (subdivisable, available)
|
||||
{
|
||||
(false, true) => panic!("Invalid cache pointer. (not subdivisable and available)"),
|
||||
(false, _) if pointer != 0 =>
|
||||
{
|
||||
panic!("Invalid cache pointer. (non null unsubdivisable pointer)")
|
||||
}
|
||||
(false, _) => None,
|
||||
(true, false) => Some(None),
|
||||
(true, true) => Some(Some(pointer)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u32> for CachePointer
|
||||
{
|
||||
fn from(value: u32) -> Self
|
||||
{
|
||||
CachePointer(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct StructurePage<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub occupancy_mask: u64,
|
||||
pub pointers: [CachePointer; N * N * N],
|
||||
}
|
||||
|
||||
// SAFETY: u64, then packed u32s ([`CachePointer`]s), so no padding, all bit patterns are allowed
|
||||
unsafe impl<const N: usize> Pod for StructurePage<N> where [(); N * N * N]: {}
|
||||
|
||||
/// Data stored alongside cache structure so that application can locate a
|
||||
/// particular request
|
||||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct LocationPage
|
||||
{
|
||||
/// Identifier for the structure to which the node pertains
|
||||
pub structure_id: u32,
|
||||
|
||||
/// Identifier for locating this particular node within the structure
|
||||
pub node_id: u32,
|
||||
}
|
||||
|
||||
/// Page storing the depth of the current node related to its root.
|
||||
/// - 0xFFFFFFFF: Page unused
|
||||
/// - 0..0xFFFFFFFF(excl): Depth
|
||||
///
|
||||
/// An external insertion gets the 0 depth.
|
||||
/// Internal insertions get the parent's depth plus one.
|
||||
///
|
||||
/// As such, when inserting pages in the cache, we first sort the lru pages
|
||||
/// by depth. This prevents replacing a high page that pointed to a deeper tree strucutre
|
||||
/// effectively invalidating the minimum amount of data.
|
||||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct DepthPage(pub u32);
|
||||
|
||||
impl DepthPage
|
||||
{
|
||||
pub const PAGE_UNUSED: Self = DepthPage(u32::MAX);
|
||||
}
|
||||
|
||||
/// When the cache requests some information, it produces this structure,
|
||||
/// which contains the node on which a subdivision is requested, as well which particular
|
||||
/// children is needed
|
||||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct RequestInformation
|
||||
{
|
||||
/// Identifier for the structure to which the node pertains
|
||||
pub structure_id: u32,
|
||||
|
||||
/// Identifier for locating this particular node within the structure
|
||||
pub node_id: u32,
|
||||
|
||||
/// The index of the children on which the request was issued
|
||||
pub children_index: u32,
|
||||
}
|
||||
|
||||
/// Metainformation kept along each request, to know which node made the demand
|
||||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct RequestMeta
|
||||
{
|
||||
/// The page on which the request was issued, with the special value 0xFFFFFFFF if the request
|
||||
/// is external
|
||||
pub page_index: u32,
|
||||
|
||||
/// The children on which the request was issued
|
||||
pub children_index: u32,
|
||||
|
||||
/// The depth on which the request was issued
|
||||
pub depth: u32,
|
||||
}
|
||||
|
||||
/// Structure information about the children of a node.
|
||||
/// Used when inserting data in the cache, to setup structure pointers
|
||||
///
|
||||
/// A specific child of a node being inserted can be in four state by
|
||||
///
|
||||
/// Whether it can be subdivided further or not
|
||||
/// Whether it is considered occupied or not
|
||||
/// 31st bit : subdivisable?
|
||||
/// 30th bit : occupied?
|
||||
#[derive(Clone, Copy, Debug, Zeroable, Pod)]
|
||||
#[repr(transparent)]
|
||||
pub struct ChildInformation(u32);
|
||||
|
||||
impl ChildInformation
|
||||
{
|
||||
pub const NONE: Self = Self(0);
|
||||
pub const SUBDIVISABLE: Self = Self(1 << 31);
|
||||
pub const OCCUPIED: Self = Self(1 << 30);
|
||||
|
||||
pub fn new(subdivisable: bool, occupied: bool) -> Self
|
||||
{
|
||||
let mut n = Self::NONE;
|
||||
if subdivisable
|
||||
{
|
||||
n = n | Self::SUBDIVISABLE;
|
||||
}
|
||||
|
||||
if occupied
|
||||
{
|
||||
n = n | Self::OCCUPIED;
|
||||
}
|
||||
|
||||
n
|
||||
}
|
||||
}
|
||||
|
||||
impl BitOr for ChildInformation
|
||||
{
|
||||
type Output = Self;
|
||||
|
||||
fn bitor(self, rhs: Self) -> Self::Output
|
||||
{
|
||||
Self(self.0 | rhs.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Information given for an page insertion operation
|
||||
#[derive(Debug, Clone, Copy, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct InsertionInformation<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
/// Information to setup structure pointers
|
||||
pub children: [ChildInformation; N * N * N],
|
||||
}
|
||||
|
||||
// SAFETY: Packed array of u32, no padding, all bit patterns allowed
|
||||
unsafe impl<const N: usize> Pod for InsertionInformation<N> where [(); N * N * N]: {}
|
||||
@@ -0,0 +1,23 @@
|
||||
// For things that depend upon the cache layout/children count
|
||||
|
||||
struct PointerPage
|
||||
{
|
||||
occupancy_low: u32,
|
||||
occupancy_high: u32,
|
||||
pointers: array<u32, CHILDREN_COUNT>,
|
||||
}
|
||||
|
||||
struct InsertionInformation
|
||||
{
|
||||
/// [`ChildInformation`] in schema.rs
|
||||
children: array<u32, CHILDREN_COUNT>
|
||||
}
|
||||
|
||||
// Takes index of pointer and gives cache index
|
||||
fn pointer_index_to_cache_index(request_index: u32) -> CacheIndex
|
||||
{
|
||||
var cache_index: CacheIndex;
|
||||
cache_index.page_index = request_index / CHILDREN_COUNT;
|
||||
cache_index.children_index = request_index % CHILDREN_COUNT;
|
||||
return cache_index;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
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,
|
||||
depth: u32
|
||||
}
|
||||
|
||||
struct AttributeArray
|
||||
{
|
||||
values: array<u32>
|
||||
}
|
||||
|
||||
struct LocationPage
|
||||
{
|
||||
structure_id: u32,
|
||||
node_id: 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;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/// Group 0: Lru list
|
||||
@group(0) @binding(0) var<storage, read_write> timestamp_pages: array<u32>;
|
||||
@group(0) @binding(1) var<storage, read_write> lru_list: array<u32>;
|
||||
@group(0) @binding(2) var<storage, read_write> consumed_count: u32;
|
||||
|
||||
/// Group 1: Cache structure
|
||||
@group(1) @binding(0) var<storage, read_write> structure_pointer_pages: array<u32>; // UNUSED
|
||||
@group(1) @binding(1) var<storage, read_write> structure_location_pages: array<u32>; // UNUSED
|
||||
@group(1) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
|
||||
|
||||
/// Group 2: Scratch buffer
|
||||
@group(2) @binding(0) var<storage, read_write> scratch_buffer: array<u32>;
|
||||
|
||||
/// Resets the lru list
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn reset_lru_list(@builtin(global_invocation_id) global_invocation_id: vec3<u32>)
|
||||
{
|
||||
let index = global_invocation_id.x;
|
||||
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
|
||||
lru_list[index] = index;
|
||||
consumed_count = 0;
|
||||
}
|
||||
|
||||
/// Indirect copy, in between the depth sort and the timestamp sort
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn indirect_copy(@builtin(global_invocation_id) global_invocation_id: vec3<u32>)
|
||||
{
|
||||
let index = global_invocation_id.x;
|
||||
if(index >= arrayLength(&lru_list))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Index sorted by depth
|
||||
let gather_index = lru_list[index];
|
||||
|
||||
// Fetch corresponding timestamp
|
||||
let ts = timestamp_pages[gather_index];
|
||||
|
||||
// Copy to corresponding locatoin
|
||||
scratch_buffer[index] = ts;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Group 0: Table pointers
|
||||
@group(0) @binding(0) var<storage, read_write> fixed_table_pointers: array<u32>; // Request count
|
||||
|
||||
// Group 1: Cache insertion data
|
||||
@group(1) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
|
||||
@group(1) @binding(1) var<storage, read_write> insertion_data_information: array<u32>; // UNUSED
|
||||
@group(1) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
|
||||
@group(1) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
|
||||
@group(1) @binding(4) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
|
||||
|
||||
/// Group 2: Request buffer
|
||||
@group(2) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
|
||||
@group(2) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
|
||||
@group(2) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn insertion(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
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]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/// Group 0: Table pointers
|
||||
@group(0) @binding(0) var<storage, read_write> fixed_table_pointers: array<u32>; // Request count
|
||||
|
||||
// Group 1: Cache evictor
|
||||
@group(1) @binding(0) var<storage, read_write> cache_evictor_timestamps: array<u32>;
|
||||
@group(1) @binding(1) var<storage, read_write> cache_evictor_lru_pages: array<u32>;
|
||||
@group(1) @binding(2) var<storage, read_write> cache_evictor_consumed_count: u32;
|
||||
|
||||
var<immediate> new_timestamp: u32;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn invalidation(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/// Group 0: Cache request handler
|
||||
@group(0) @binding(0) var<storage, read_write> request_handler_count: u32; // Request count
|
||||
@group(0) @binding(1) var<storage, read_write> request_handler_requests: array<u32>;
|
||||
|
||||
/// Group 1: Request buffer
|
||||
@group(1) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
|
||||
@group(1) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
|
||||
@group(1) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let index = gid.x;
|
||||
request_buffer_count = min(request_handler_count, arrayLength(&request_buffer_informations));
|
||||
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;
|
||||
// u32s wrap arround
|
||||
request_meta.depth = 0xFFFFFFFF;
|
||||
|
||||
request_buffer_informations[index] = request_info;
|
||||
request_buffer_meta[index] = request_meta;
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
|
||||
// Group 0: cache_attributes
|
||||
@group(0) @binding(0) var<storage, read_write> cache_attributes: binding_array<AttributeArray>;
|
||||
|
||||
/// Group 1: Cache structure
|
||||
@group(1) @binding(0) var<storage, read_write> structure_pointer_pages: array<PointerPage>;
|
||||
@group(1) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
|
||||
@group(1) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
|
||||
|
||||
// Group 2: Cache insertion data
|
||||
@group(2) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
|
||||
@group(2) @binding(1) var<storage, read_write> insertion_data_information: array<InsertionInformation>;
|
||||
@group(2) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
|
||||
@group(2) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
|
||||
@group(2) @binding(4) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
|
||||
|
||||
// Group 3: Cache evictor
|
||||
@group(3) @binding(0) var<storage, read_write> cache_evictor_timestamps: array<u32>;
|
||||
@group(3) @binding(1) var<storage, read_write> cache_evictor_lru_pages: array<u32>;
|
||||
@group(3) @binding(2) var<storage, read_write> cache_evictor_consumed_count: u32;
|
||||
|
||||
// Group 4: Inserted count
|
||||
@group(4) @binding(0) var<storage, read_write> pass_inserted_count: atomic<u32>;
|
||||
|
||||
var<immediate> 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<u32>)
|
||||
{
|
||||
// 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<u32>)
|
||||
{
|
||||
let index = gid.x;
|
||||
//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 + 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_pointer_pages[page_index] = new_pointers;
|
||||
|
||||
// Mark page as dirty for invalidation
|
||||
cache_evictor_timestamps[page_index] = new_timestamp;
|
||||
|
||||
// Set default depth
|
||||
structure_depth_pages[page_index] = 0;
|
||||
|
||||
// Copy attributes
|
||||
for(var attribute_index = u32(0); attribute_index < ATTRIBUTE_COUNT; attribute_index ++)
|
||||
{
|
||||
if(!ATTRIBUTE_COPY[attribute_index])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
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 = u32(0); word < page_stride; word ++)
|
||||
{
|
||||
cache_attributes[attribute_index].values[dest_offset + word] = insertion_data_attributes[attribute_index].values[src_offset + word];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn insertion_info_to_pointer_page(info: InsertionInformation) -> PointerPage
|
||||
{
|
||||
var page: PointerPage;
|
||||
|
||||
var occupancy_low = u32(0);
|
||||
var occupancy_high = u32(0);
|
||||
for(var i = u32(0); i < CHILDREN_COUNT; i++)
|
||||
{
|
||||
let insert_info = info.children[i];
|
||||
|
||||
// Pointer
|
||||
page.pointers[i] = child_pointer_empty(child_information_subdivided(insert_info));
|
||||
|
||||
// Occupancy
|
||||
var bit = select(u32(0), u32(1), child_information_occupied(insert_info));
|
||||
|
||||
// Dispatch set bit on low or high word
|
||||
bit = bit << (i % u32(32));
|
||||
if(i < 32)
|
||||
{
|
||||
occupancy_low |= bit;
|
||||
}
|
||||
else
|
||||
{
|
||||
occupancy_high |= bit;
|
||||
}
|
||||
}
|
||||
|
||||
page.occupancy_low = occupancy_low;
|
||||
page.occupancy_high = occupancy_high;
|
||||
|
||||
return page;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/// Group 0: Cache structure
|
||||
@group(0) @binding(0) var<storage, read_write> structure_pointer_pages: array<PointerPage>;
|
||||
@group(0) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
|
||||
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
|
||||
|
||||
// Group 1: Cache evictor
|
||||
@group(1) @binding(0) var<storage, read_write> cache_evictor_timestamps: array<u32>;
|
||||
@group(1) @binding(1) var<storage, read_write> cache_evictor_lru_pages: array<u32>;
|
||||
@group(1) @binding(2) var<storage, read_write> cache_evictor_consumed_count: u32;
|
||||
|
||||
var<immediate> new_timestamp: u32;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn invalidation(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let index = gid.x;
|
||||
if(index >= arrayLength(&structure_pointer_pages)) { return; }
|
||||
|
||||
for(var i = u32(0); i < CHILDREN_COUNT; i++)
|
||||
{
|
||||
if(pointer_invalid(structure_pointer_pages[index].pointers[i]))
|
||||
{
|
||||
pointer_invalidate(index, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
let new_pointer = child_pointer_empty(child_pointer_subdivided(pointer));
|
||||
structure_pointer_pages[page_index].pointers[child_index] = new_pointer;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
@group(0) @binding(0) var<storage, read_write> request_count_pages: array<u32>;
|
||||
|
||||
/// Resets the requests
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn reset_requests(@builtin(global_invocation_id) global_invocation_id: vec3<u32>)
|
||||
{
|
||||
let index = global_invocation_id.x;
|
||||
if(index >= arrayLength(&request_count_pages))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
request_count_pages[index] = 0;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/// Group 0: Cache structure
|
||||
@group(0) @binding(0) var<storage, read_write> structure_pointer_pages: array<PointerPage>;
|
||||
@group(0) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
|
||||
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
|
||||
|
||||
/// Group 1: Request buffer
|
||||
@group(1) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
|
||||
@group(1) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
|
||||
@group(1) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
|
||||
|
||||
// Group 2: Cache insertion data
|
||||
@group(2) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
|
||||
@group(2) @binding(1) var<storage, read_write> insertion_data_information: array<InsertionInformation>;
|
||||
@group(2) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
|
||||
@group(2) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
|
||||
@group(2) @binding(4) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn write_pointers(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let index = gid.x;
|
||||
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_inf = request_buffer_meta[index];
|
||||
let page_index = insertion_data_destination_indices[index];
|
||||
|
||||
if(page_index != 0xFFFFFFFF)
|
||||
{
|
||||
structure_pointer_pages[meta_inf.page_index].pointers[meta_inf.children_index]
|
||||
= child_pointer_make_available(page_index);
|
||||
structure_depth_pages[page_index] = meta_inf.depth + 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/// Pipeline to write the requests out in to the request buffer
|
||||
|
||||
/// Group 0: Cache structure
|
||||
@group(0) @binding(0) var<storage, read_write> structure_pointer_pages: array<PointerPage>;
|
||||
@group(0) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
|
||||
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
|
||||
|
||||
/// Group 1: Cache request handler
|
||||
@group(1) @binding(0) var<storage, read_write> request_handler_count: u32; // Request count
|
||||
@group(1) @binding(1) var<storage, read_write> request_handler_requests: array<u32>;
|
||||
|
||||
/// Group 3: Request buffer
|
||||
@group(2) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
|
||||
@group(2) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
|
||||
@group(2) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
{
|
||||
let index = gid.x;
|
||||
|
||||
// Max size of request buffer and request count
|
||||
let max_requests =
|
||||
min(arrayLength(&request_buffer_informations), request_handler_count);
|
||||
if(index >= max_requests) { return; }
|
||||
|
||||
|
||||
let request_index = request_handler_requests[index];
|
||||
let request_location = pointer_index_to_cache_index(request_index);
|
||||
let page_index = request_location.page_index;
|
||||
|
||||
// Fill out request information
|
||||
var request_information: RequestInformation;
|
||||
request_information.structure_id = structure_location_pages[page_index].structure_id;
|
||||
request_information.node_id = structure_location_pages[page_index].node_id;
|
||||
request_information.children_index = request_location.children_index;
|
||||
|
||||
// Fill out request meta information
|
||||
var request_meta: RequestMeta;
|
||||
request_meta.page_index = page_index;
|
||||
request_meta.children_index = request_location.children_index;
|
||||
request_meta.depth = structure_depth_pages[page_index];
|
||||
|
||||
// Write them to request buffer
|
||||
request_buffer_informations[index] = request_information;
|
||||
request_buffer_meta[index] = request_meta;
|
||||
|
||||
// Write request count
|
||||
request_buffer_count = max_requests;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::BindGroupLayout;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
|
||||
use crate::gpu::create_multi_buffers_bind_group;
|
||||
use crate::gpu::create_multi_buffers_bind_group_layout;
|
||||
use crate::gpu_profiler::memory_profiler;
|
||||
use crate::voxel_cache::schema::DepthPage;
|
||||
use crate::voxel_cache::schema::StructurePage;
|
||||
|
||||
/// Contains the instanciated buffers relevant to the structure of the trees
|
||||
pub struct CacheStructure<const N: usize>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pointer_pages: Buffer,
|
||||
location_pages: Buffer,
|
||||
depth_pages: Buffer,
|
||||
|
||||
bind_group_layout: BindGroupLayout,
|
||||
bind_group: BindGroup,
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheStructure<N>
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
pub const POINTER_PAGES_BINDING: u32 = 0;
|
||||
pub const LOCATION_PAGES_BINDING: u32 = 1;
|
||||
pub const DEPTH_PAGES_BINDING: u32 = 2;
|
||||
|
||||
pub fn new(device: &mut memory_profiler::Device, page_count: usize) -> Self
|
||||
{
|
||||
let pointer_pages = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheStructure::pointer_pages"),
|
||||
size: (size_of::<StructurePage<N>>() * page_count) as u64,
|
||||
usage: BufferUsages::STORAGE,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let location_pages = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CacheStructure::location_pages"),
|
||||
size: (size_of::<StructurePage<N>>() * page_count) as u64,
|
||||
usage: BufferUsages::STORAGE,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
// Depth pages need to be initialized to unused, this prioritizes them in the
|
||||
// depth sort used in the eviction pass
|
||||
let depth_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("CacheStructure::depth_pages"),
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
contents: bytemuck::cast_slice(&vec![DepthPage::PAGE_UNUSED; page_count]),
|
||||
});
|
||||
|
||||
let bind_group_layout = Self::create_bind_group_layout(device);
|
||||
let bind_group = create_multi_buffers_bind_group(
|
||||
device,
|
||||
&bind_group_layout,
|
||||
&[&pointer_pages, &location_pages, &depth_pages],
|
||||
Some("CacheStructure::bind_group"),
|
||||
);
|
||||
|
||||
CacheStructure {
|
||||
pointer_pages,
|
||||
location_pages,
|
||||
depth_pages,
|
||||
|
||||
bind_group_layout,
|
||||
bind_group,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout
|
||||
{
|
||||
create_multi_buffers_bind_group_layout(device, 3, Some("CacheStructure::bind_group_layout"))
|
||||
}
|
||||
|
||||
pub fn bind_group_layout(&self) -> &BindGroupLayout
|
||||
{
|
||||
&self.bind_group_layout
|
||||
}
|
||||
|
||||
pub fn bind_group(&self) -> &BindGroup
|
||||
{
|
||||
&self.bind_group
|
||||
}
|
||||
|
||||
pub fn pointer_pages(&self) -> &Buffer
|
||||
{
|
||||
&self.pointer_pages
|
||||
}
|
||||
|
||||
pub fn depth_pages(&self) -> &Buffer
|
||||
{
|
||||
&self.depth_pages
|
||||
}
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
use std::num::NonZero;
|
||||
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::Device;
|
||||
use wgpu::Queue;
|
||||
use wgpu::util::StagingBelt;
|
||||
|
||||
use crate::voxel_cache::data::StructurePointer;
|
||||
use crate::voxel_cache::request_buffer::RequestBuffer;
|
||||
|
||||
// Stores root pointers to the cache
|
||||
pub struct StructureTable
|
||||
{
|
||||
pub(crate) device: Device,
|
||||
pub(crate) queue: Queue,
|
||||
pub(crate) allocation_table: Vec<bool>,
|
||||
pub(crate) available_slots: usize,
|
||||
pub(crate) pointer_table: Buffer,
|
||||
pub(crate) request_buffer: RequestBuffer<1>,
|
||||
pub(crate) write_staging: StagingBelt,
|
||||
}
|
||||
|
||||
impl StructureTable
|
||||
{
|
||||
pub fn new(device: Device, queue: Queue) -> Self
|
||||
{
|
||||
let pointer_table = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("structure_table_pointer_table"),
|
||||
size: size_of::<u32>() as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
StructureTable {
|
||||
request_buffer: RequestBuffer::new(1, device.clone()),
|
||||
write_staging: StagingBelt::new(device.clone(), size_of::<u32>() as u64),
|
||||
device,
|
||||
queue,
|
||||
allocation_table: vec![false],
|
||||
available_slots: 1,
|
||||
pointer_table,
|
||||
}
|
||||
}
|
||||
|
||||
fn double_capacity(&mut self, encoder: &mut CommandEncoder)
|
||||
{
|
||||
self.available_slots += self.allocation_table.len();
|
||||
self.allocation_table
|
||||
.extend(vec![false; self.allocation_table.len()]);
|
||||
|
||||
// Copy buffers into bigger buffers
|
||||
let pointer_table = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("structure_table_pointer_table"),
|
||||
size: size_of::<u32>() as u64 * self.allocation_table.len() as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC | BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
encoder.copy_buffer_to_buffer(
|
||||
&self.pointer_table,
|
||||
0,
|
||||
&pointer_table,
|
||||
0,
|
||||
self.pointer_table.size(),
|
||||
);
|
||||
|
||||
self.pointer_table = pointer_table;
|
||||
self.request_buffer = RequestBuffer::new(self.allocation_table.len(), self.device.clone());
|
||||
}
|
||||
|
||||
pub fn request_buffer(&self) -> &RequestBuffer<1>
|
||||
{
|
||||
&self.request_buffer
|
||||
}
|
||||
|
||||
pub fn request_buffer_mut(&mut self) -> &mut RequestBuffer<1>
|
||||
{
|
||||
&mut self.request_buffer
|
||||
}
|
||||
|
||||
pub fn free_structure(&mut self, structure_id: u32)
|
||||
{
|
||||
self.available_slots += 1;
|
||||
self.allocation_table[structure_id as usize] = false;
|
||||
}
|
||||
|
||||
// Returns a structure Id
|
||||
pub fn allocate_structure(&mut self, subdivided: bool) -> u32
|
||||
{
|
||||
let mut encoder = self
|
||||
.device
|
||||
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("structure_table_resize_encoder"),
|
||||
});
|
||||
|
||||
// Get first available element
|
||||
if self.available_slots == 0
|
||||
{
|
||||
self.double_capacity(&mut encoder);
|
||||
}
|
||||
let (first_id, _) = self
|
||||
.allocation_table
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, allocated)| !**allocated)
|
||||
.unwrap();
|
||||
self.allocation_table[first_id] = true;
|
||||
self.available_slots -= 1;
|
||||
|
||||
// Write empty pointer to new pointer
|
||||
self.write_staging
|
||||
.write_buffer(
|
||||
&mut encoder,
|
||||
&self.pointer_table,
|
||||
size_of::<u32>() as u64 * first_id as u64,
|
||||
NonZero::new(size_of::<u32>() as u64).unwrap(),
|
||||
)
|
||||
.copy_from_slice(bytemuck::bytes_of(
|
||||
&StructurePointer::new(subdivided, false, 0).0,
|
||||
));
|
||||
self.write_staging.finish_and_recall_on_submit(&encoder);
|
||||
self.queue.submit([encoder.finish()]);
|
||||
|
||||
first_id as u32
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::gpu::indirect_buffer::IndirectBuffer1D;
|
||||
use crate::gpu_profiler::ScopeEncoder;
|
||||
use crate::gpu_profiler::memory_profiler::MemoryProfile;
|
||||
use crate::voxel_cache::CacheInvalidable;
|
||||
use crate::voxel_cache::CacheRessources;
|
||||
use crate::voxel_cache::create_multi_buffers_bg_bg_layout;
|
||||
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) -> 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 mut memory_profile = MemoryProfile::new("FixedStructureTable");
|
||||
let mut mem_device = memory_profile.begin(device);
|
||||
|
||||
let request_handler =
|
||||
CacheRequestHandler::<1>::new(&mut mem_device.group("CacheRequestHandler"), size);
|
||||
let common_ressources =
|
||||
CacheRessources::new(&mut mem_device.group("CacheRessources"), size);
|
||||
drop(mem_device);
|
||||
drop(memory_profile);
|
||||
|
||||
let (pointers_bind_group_layout, pointers_bind_group) = create_multi_buffers_bg_bg_layout(
|
||||
device,
|
||||
&[&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::<u32>() 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, None,
|
||||
)),
|
||||
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,
|
||||
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<wgpu::CommandEncoder>,
|
||||
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<const N: usize>(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
|
||||
insertion: &CacheInsertionData<N>,
|
||||
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_no_attributes(), &[]);
|
||||
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
|
||||
}
|
||||
|
||||
pub fn pointers_buffer(&self) -> &wgpu::Buffer
|
||||
{
|
||||
&self.pointers
|
||||
}
|
||||
|
||||
pub fn pointers_bind_group(&self) -> &wgpu::BindGroup
|
||||
{
|
||||
&self.pointers_bind_group
|
||||
}
|
||||
}
|
||||
|
||||
impl CacheInvalidable for FixedStructureTable
|
||||
{
|
||||
fn invalidate(
|
||||
&mut self,
|
||||
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
use bytemuck::bytes_of;
|
||||
use wgpu::BindGroup;
|
||||
use wgpu::BindGroupEntry;
|
||||
use wgpu::Buffer;
|
||||
use wgpu::BufferUsages;
|
||||
use wgpu::CommandEncoder;
|
||||
use wgpu::ComputePipeline;
|
||||
use wgpu::Device;
|
||||
use wgpu::ShaderStages;
|
||||
|
||||
pub struct UsageBuffer
|
||||
{
|
||||
pub cache_size: usize,
|
||||
pub current_timestamp: u32,
|
||||
pub usage_buffer: Buffer,
|
||||
pub sort_buffer: Buffer,
|
||||
pub sort_pipeline: ComputePipeline,
|
||||
pub bindgroup: BindGroup,
|
||||
pub device: Device,
|
||||
}
|
||||
|
||||
impl UsageBuffer
|
||||
{
|
||||
pub fn new(cache_size: usize, device: Device) -> Self
|
||||
{
|
||||
let initial_timestamp = 0;
|
||||
let usage_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Usage buffer"),
|
||||
size: (size_of::<u32>() * cache_size) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: true,
|
||||
});
|
||||
let sort_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("usage_sort_buffer"),
|
||||
size: (size_of::<u32>() * cache_size) as u64,
|
||||
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: true,
|
||||
});
|
||||
|
||||
usage_buffer
|
||||
.get_mapped_range_mut(0..)
|
||||
.unwrap()
|
||||
.copy_from_slice(bytemuck::cast_slice(
|
||||
vec![initial_timestamp; cache_size].as_slice(),
|
||||
));
|
||||
usage_buffer.unmap();
|
||||
|
||||
sort_buffer
|
||||
.get_mapped_range_mut(0..)
|
||||
.unwrap()
|
||||
.copy_from_slice(bytemuck::cast_slice(
|
||||
&(0..(cache_size as u32)).collect::<Vec<_>>(),
|
||||
));
|
||||
sort_buffer.unmap();
|
||||
|
||||
let bindgroup_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("usage_sort_pipeline_bing_group_layout"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let bindgroup = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("usage_sort_pipeline_bindgroup"),
|
||||
layout: &bindgroup_layout,
|
||||
entries: &[
|
||||
BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: usage_buffer.as_entire_binding(),
|
||||
},
|
||||
BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: sort_buffer.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let pipeline_layouts = &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("usage_buffer_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&bindgroup_layout)],
|
||||
immediate_size: size_of::<u32>() as u32,
|
||||
});
|
||||
|
||||
let sort_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("Sort node request"),
|
||||
layout: Some(pipeline_layouts),
|
||||
module: &device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("clear_chunk_requests shader module"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
"
|
||||
|
||||
@group(0) @binding(0) var<storage, read_write> usage_buffer: array<u32>;
|
||||
@group(0) @binding(1) var<storage, read_write> sort_buffer: array<u32>;
|
||||
var<immediate> both_phase: u32;
|
||||
|
||||
fn big_fusion(index: u32, phase_size: u32) -> vec2<u32>
|
||||
{{
|
||||
// Find out in which block index this invocation pertains
|
||||
let block_index = index / (phase_size / 2);
|
||||
let element_index = index % (phase_size / 2);
|
||||
|
||||
let offset = block_index * phase_size;
|
||||
let a = offset + element_index;
|
||||
let b = offset + phase_size - 1 - element_index;
|
||||
return vec2<u32>(a, b);
|
||||
}}
|
||||
|
||||
fn small_fusion(index: u32, phase: u32, sub_phase: u32) -> vec2<u32>
|
||||
{{
|
||||
let phase_size = u32(1 << (phase - sub_phase + 1));
|
||||
|
||||
let block_index = index / (phase_size / 2);
|
||||
let element_index = index % (phase_size / 2);
|
||||
|
||||
let offset = block_index * phase_size;
|
||||
let a = offset + element_index;
|
||||
let b = a + (phase_size / 2);
|
||||
return vec2<u32>(a, b);
|
||||
}}
|
||||
|
||||
|
||||
@compute
|
||||
@workgroup_size(64)
|
||||
fn main(
|
||||
@builtin(global_invocation_id) global_invocation_id: vec3<u32>
|
||||
)
|
||||
{{
|
||||
|
||||
let length = arrayLength(&sort_buffer);
|
||||
let index = global_invocation_id.x;
|
||||
let sub_phase = (both_phase >> 16) & 0xFFFF;
|
||||
let phase = both_phase & 0xFFFF;
|
||||
let phase_total_width = u32(1 << (phase + 1));
|
||||
|
||||
var swap_indices = vec2<u32>(0, 0);
|
||||
|
||||
if(sub_phase == 0)
|
||||
{{
|
||||
// Bitonic fusion
|
||||
swap_indices = big_fusion(index, phase_total_width);
|
||||
}}else
|
||||
{{
|
||||
swap_indices = small_fusion(index, phase, sub_phase);
|
||||
}}
|
||||
|
||||
// Do swap
|
||||
if(swap_indices.y >= length)
|
||||
{{
|
||||
// Suppose that swap_indices.y is -inf, dont swap
|
||||
return;
|
||||
}}
|
||||
|
||||
let av = usage_buffer[sort_buffer[swap_indices.x]];
|
||||
let bv = usage_buffer[sort_buffer[swap_indices.y]];
|
||||
|
||||
if(bv < av)
|
||||
{{
|
||||
let temp = sort_buffer[swap_indices.x];
|
||||
sort_buffer[swap_indices.x] = sort_buffer[swap_indices.y];
|
||||
sort_buffer[swap_indices.y] = temp;
|
||||
}}
|
||||
}}
|
||||
"
|
||||
.into(),
|
||||
),
|
||||
}),
|
||||
entry_point: Some("main"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
cache_size,
|
||||
current_timestamp: initial_timestamp,
|
||||
usage_buffer,
|
||||
sort_buffer,
|
||||
sort_pipeline,
|
||||
bindgroup,
|
||||
device,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn timestamp(&self) -> u32
|
||||
{
|
||||
self.current_timestamp
|
||||
}
|
||||
|
||||
pub fn next_frame(&mut self)
|
||||
{
|
||||
let (new_timestamp, _) = self.current_timestamp.overflowing_add(1);
|
||||
self.current_timestamp = new_timestamp;
|
||||
}
|
||||
|
||||
pub fn usage_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.usage_buffer
|
||||
}
|
||||
|
||||
pub fn sort_buffer(&self) -> &Buffer
|
||||
{
|
||||
&self.sort_buffer
|
||||
}
|
||||
|
||||
pub fn sort_usage(&self, encoder: &mut CommandEncoder)
|
||||
{
|
||||
let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("usage_buffer_sort_compute_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
compute_pass.set_bind_group(0, Some(&self.bindgroup), &[]);
|
||||
compute_pass.set_pipeline(&self.sort_pipeline);
|
||||
|
||||
// Compute required shader invocations
|
||||
let sort_steps = self.cache_size.next_power_of_two().ilog2(); // Each element is sorted
|
||||
let shader_invocations = self.cache_size.div_ceil(2); // bitonic sorting :
|
||||
// half as many shaders
|
||||
// per element
|
||||
let workgroup_invocations = shader_invocations.div_ceil(64);
|
||||
|
||||
for i in 0..=sort_steps
|
||||
{
|
||||
for j in 0..=i
|
||||
{
|
||||
compute_pass.set_immediates(0, bytes_of(&(j << 16 | i)));
|
||||
compute_pass.dispatch_workgroups(workgroup_invocations as u32, 1, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
LFS
BIN
Binary file not shown.
Reference in New Issue
Block a user