Compare commits

...
Author SHA1 Message Date
octagonal 9af63cf2bd Starting scatter pass 2026-10-02 17:35:26 +02:00
octagonal 7dfcfe56e9 Fixing fast radix 2026-10-01 22:55:04 +02:00
octagonal 41feb52ab5 Starting faster radix 2026-09-29 23:57:48 +02:00
octagonal 3124978e3f shitty radix 2026-09-28 23:01:31 +02:00
octagonal e673c6dc0d Better shader org, prep for gi 2026-09-21 23:12:26 +02:00
octagonal a332ac08ed Adding attribute system to the cache 2026-09-19 15:41:23 +02:00
octagonal 306b01b44c Smart compaction goes brrrrr 2026-09-17 23:01:29 +02:00
octagonal f34550e692 working buffer compactor 2026-09-17 20:52:09 +02:00
octagonal 7c78085b61 starting compaction stuff 2026-09-16 20:49:44 +02:00
octagonal 5ed2f67324 adding sort that actually stops when finshed 2026-09-15 22:27:26 +02:00
octagonal 532580b9bd more occup 2026-09-15 13:39:56 +02:00
octagonal d1f76fe9f0 WTF 2026-09-13 23:06:00 +02:00
octagonal 59e3ed5f87 Faster coalescing 2026-09-13 15:48:27 +02:00
octagonal 9015ed85d6 slang fast 2026-09-12 16:16:21 +02:00
octagonal 3835a6fa78 lfs WITH files out of gitignore 2026-09-11 17:23:31 +02:00
octagonal a342643ab7 Test lfs 2026-09-11 17:17:22 +02:00
octagonal 54c5e91a7f Fix RT timer 2026-09-11 17:12:38 +02:00
35 changed files with 3255 additions and 1597 deletions
+3
View File
@@ -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
-4
View File
@@ -1,11 +1,7 @@
/target
Cargo.lock
img.jpg
img.png
img_low.jpg
imgs.tar.gz
vxls_height.tif
# Added by cargo
#
+2 -1
View File
@@ -16,9 +16,10 @@ glam = "0.33.5"
image = "0.25.10"
indicatif = "0.18.6"
itertools = "0.15.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"
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
all: clean voxel.spv compaction.spv gi.spv radix_sort.spv radix_reduce.spv
clean:
rm -f *.spv
%.spv: %.slang
slangc $< -O3 -fvk-use-entrypoint-name -target spirv -o $@
-334
View File
@@ -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()
}
+137
View File
@@ -0,0 +1,137 @@
[[vk::binding(0, 0)]]
RWStructuredBuffer<uint32_t> count_buffer;
[[vk::binding(1, 0)]]
RWStructuredBuffer<uint32_t> index_buffer;
[[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];
}
[numthreads(1, 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();
// 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;
}
}
[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;
}
}
Binary file not shown.
-2
View File
@@ -1,2 +0,0 @@
module example;
+265
View File
@@ -0,0 +1,265 @@
import ray_cast;
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;
struct ByteColor
{
uint32_t byte_color;
property uint32_t byte_r
{
get {
return byte_color & 0xFF;
}
}
property uint32_t byte_g
{
get {
return (byte_color >> 8) & 0xFF;
}
}
property uint32_t byte_b
{
get {
return (byte_color >> 16) & 0xFF;
}
}
property uint32_t byte_a
{
get {
return byte_color >> 24;
}
}
property float4 float_color
{
get {
return float4(
float(byte_r) / 255.,
float(byte_g) / 255.,
float(byte_b) / 255.,
float(byte_a) / 255.);
}
}
}
[[vk::binding(0, 0)]]
RWStructuredBuffer<StructurePoolElement> structure_pool;
[[vk::binding(1, 0)]]
RWStructuredBuffer<uint32_t> attributes_pool[2];
[[vk::binding(2, 0)]]
RWStructuredBuffer<LocationPoolElement> location_pool;
[[vk::binding(3, 0)]]
RWStructuredBuffer<RequestBufferElement> request_buffer;
[[vk::binding(4, 0)]]
RWStructuredBuffer<uint32_t> usage_buffer;
[[vk::binding(5, 0)]]
RWStructuredBuffer<StructurePointer> structure_table_pointer;
[[vk::binding(6, 0)]]
RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
ByteColor fetch_color(uint32_t index, uint32_t child_index)
{
return ByteColor(attributes_pool[0][index * 64 + child_index]);
}
float3 fetch_normal(uint32_t index, uint32_t child_index)
{
let a = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3]);
let b = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3 + 1]);
let c = asfloat(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, 1)]]
[[format("rgba32f")]]
WTexture2D<float4> target_texture;
[[vk::binding(1, 1)]]
[[format("rgba32f")]]
RWTexture2D<float4> gbuffer_position;
[[vk::binding(2, 1)]]
[[format("rgba32f")]]
RWTexture2D<float4> gbuffer_albedo;
[[vk::binding(3, 1)]]
[[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;
let illumination = dot(float3(0., 1., 0.), normal.xyz);
let view_dir = pos.xyz - constants.cam_pos;
// let ray_dir = normalize(reflect(view_dir, normal.xyz));
let ray_dir = sampleHemisphere(normal.xyz, constants.frame_timestamp, 6767 + (location.x * 67) + (location.y * 91));
if (any(isinf(ray_dir)) || any(isnan(ray_dir)))
{
target_texture.Store(location.xy, albedo);
return;
}
let stack_index = local_location.x + local_location.y * 16;
var voxel_cache : VoxelCache;
voxel_cache.structure_pool = structure_pool;
voxel_cache.attributes_pool = attributes_pool;
voxel_cache.location_pool = location_pool;
voxel_cache.request_buffer = request_buffer;
voxel_cache.usage_buffer = usage_buffer;
voxel_cache.structure_table_pointer = structure_table_pointer;
voxel_cache.structure_table_request_buffer = structure_table_request_buffer;
var ray_cast_context : RayCastContext;
ray_cast_context.ray_direction = ray_dir;
ray_cast_context.ray_origin = pos.xyz + normal.xyz * 0.1;
ray_cast_context.bounds = uint32_t3(constants.chunk_width, constants.chunk_alt, constants.chunk_width);
ray_cast_context.frame_timestamp = constants.frame_timestamp;
ray_cast_context.cache_report = true;
let hit = ray_cast(voxel_cache, ray_cast_context, stack_index);
if (hit.hit)
{
// Gather
let smpl_albedo = fetch_color(hit.node_index, hit.child_index).float_color;
target_texture.Store(location.xy, albedo * smpl_albedo);
}
else
{
target_texture.Store(location.xy, float4(float3(illumination), 1.));
}
}
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);
}
// Returns a cosine-weighted random direction in the hemisphere
// oriented around `normal`.
//
// `frame` should change every frame/sample sequence.
// `seed` can be a per-pixel or per-path identifier.
float3 sampleHemisphere(float3 normal, uint frame, uint seed)
{
// Hash to get two uniform random numbers in [0, 1).
uint state = seed ^ (frame * 0x9E3779B9u);
state ^= state >> 16;
state *= 0x7FEB352Du;
state ^= state >> 15;
state *= 0x846CA68Bu;
state ^= state >> 16;
float u1 = float(state) * (1.0 / 4294967296.0);
state ^= state >> 16;
state *= 0x7FEB352Du;
state ^= state >> 15;
state *= 0x846CA68Bu;
state ^= state >> 16;
float u2 = float(state) * (1.0 / 4294967296.0);
// Cosine-weighted hemisphere sampling.
float r = sqrt(u1);
float phi = 2.0 * 3.14159 * u2;
float x = r * cos(phi);
float y = r * sin(phi);
float z = sqrt(max(0.0, 1.0 - u1));
// Build an orthonormal basis around the normal.
float3 tangent;
if (abs(normal.z) < 0.999)
tangent = normalize(cross(float3(0.0, 0.0, 1.0), normal));
else
tangent = normalize(cross(float3(0.0, 1.0, 0.0), normal));
float3 bitangent = cross(normal, tangent);
// Transform from local hemisphere space to world space.
return normalize(
tangent * x +
bitangent * y +
normal * z);
}
BIN
View File
Binary file not shown.
+158
View File
@@ -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);
}
Binary file not shown.
+300
View File
@@ -0,0 +1,300 @@
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::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(key_buffer.getCount(), (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;
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[(params.histogram_count - 1) + 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[(params.histogram_count - 1) + 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;
for (uint32_t index = group_location.x * WG_HISTO_ELEMENT + local_location.x;
index < min(key_buffer.getCount(), (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);
uint32_t local_index = index - group_location.x * WG_HISTO_ELEMENT;
sort_tokens[local_index] = SortToken(digit, 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) ^ 1;
thread_prefix[i] = sum;
sum += bin_digit;
}
// 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
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 scatter_index = select(bin_digit == 0,
thread_prefix[i] + zero_rank,
total_zeroes + local_location.x - (thread_prefix[i] + zero_rank));
sort_tokens[scatter_index] = thread_tokens[i];
}
GroupMemoryBarrierWithGroupSync();
}
// Scatter to main memory
// Compute local offset by boundary detection
if (local_location.x == 0 || sort_tokens[local_location.x].digit != sort_tokens[local_location.x - 1].digit)
{
local_prefix[sort_tokens[local_location.x].digit] = local_location.x;
}
GroupMemoryBarrierWithGroupSync();
// Scatter keys
uint32_t offset = local_location.x * WE_HISTO_ELEMENTS;
for (uint32_t i = 0; i < WE_HISTO_ELEMENTS; i++)
{
uint32_t digit = sort_tokens[offset + i].digit;
uint32_t index = sort_tokens[offset + i].index;
uint32_t group_offset = histograms[group_location.x + digit * params.histogram_count];
uint32_t digit_offset = histograms[(params.histogram_count) + digit * params.histogram_count];
uint32_t destination_index = group_offset + digit_offset + (local_location.x - local_prefix[digit]);
dest_key_buffer[destination_index] = key_buffer[index];
dest_value_buffer[destination_index] = value_buffer[index];
}
}
Binary file not shown.
+394
View File
@@ -0,0 +1,394 @@
module ray_cast;
struct ByteColor
{
uint32_t byte_color;
property uint32_t byte_r
{
get {
return byte_color & 0xFF;
}
}
property uint32_t byte_g
{
get {
return (byte_color >> 8) & 0xFF;
}
}
property uint32_t byte_b
{
get {
return (byte_color >> 16) & 0xFF;
}
}
property uint32_t byte_a
{
get {
return byte_color >> 24;
}
}
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;
bool subdivided()
{
return (this.value & 0x80000000) != 0;
}
bool pointer_valid()
{
return (this.value & 0x40000000) != 0;
}
bool subdivided_valid()
{
return (this.value & 0xC0000000) == 0xC0000000;
}
uint32_t pointer()
{
return this.value & 0x3FFFFFFF;
}
}
public struct StructurePoolElement
{
public uint32_t occupancy_low;
public uint32_t occupancy_high;
public StructurePointer pointers[64];
}
public struct RequestBufferElement
{
public Atomic<uint32_t> requests[64];
}
public struct LocationPoolElement
{
public uint32_t structure_id;
public uint32_t structure_locator;
}
public struct VoxelCache
{
public RWStructuredBuffer<StructurePoolElement> structure_pool;
public RWStructuredBuffer<uint32_t> attributes_pool[2];
public RWStructuredBuffer<LocationPoolElement> location_pool;
public RWStructuredBuffer<RequestBufferElement> request_buffer;
public RWStructuredBuffer<uint32_t> usage_buffer;
public RWStructuredBuffer<StructurePointer> structure_table_pointer;
public RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
}
ByteColor fetch_color(VoxelCache cache, uint32_t index, uint32_t child_index)
{
return ByteColor(cache.attributes_pool[0][index * 64 + child_index]);
}
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);
}
public struct HitInformation
{
public bool hit;
public float3 hit_pos;
public uint32_t node_index;
public uint32_t child_index;
public float4 color;
}
groupshared uint32_t stack[256 * 5];
HitInformation chunk_ray_march(
VoxelCache cache,
float3 real_ray_direction,
float3 ray_origin,
uint32_t root_id,
float dist_offset,
uint32_t stack_index,
uint32_t frame_timestamp,
bool report, )
{
// Cone tracing info
float fov_deg = 100. / 1920.;
float fov_rad = (float.getPi() * fov_deg) / 180.;
float cone_factor = tan(fov_rad / 2.) * 2; // Horizontal size of pixel
let st_pointer = cache.structure_table_pointer[root_id];
if (!st_pointer.subdivided())
{
var hit : HitInformation;
hit.hit = false;
return hit;
}
if (!st_pointer.pointer_valid())
{
// Record request
if (report)
{
cache.structure_table_request_buffer[root_id].add(1);
}
var hit : HitInformation;
hit.hit = false;
return hit;
}
// Ray mirroring
ray_origin += float3(1.);
ray_origin = clamp(ray_origin, float(1.), asfloat(0x3fffffff));
ray_origin = select(real_ray_direction > 0., asfloat(asuint(ray_origin) ^ 0x007fffff), ray_origin);
uint32_t child_mirror = 0;
if (real_ray_direction.x > 0.)
{
child_mirror |= 3;
}
if (real_ray_direction.y > 0.)
{
child_mirror |= 3 << 2;
}
if (real_ray_direction.z > 0.)
{
child_mirror |= 3 << 4;
}
let ray_direction = -abs(real_ray_direction);
float3 pos = ray_origin;
uint32_t scale_exp = 23 - 2;
uint32_t current_node_index = cache.structure_table_pointer[root_id].pointer();
if (report)
{
cache.usage_buffer[current_node_index] = frame_timestamp;
}
stack[stack_index * 5 + 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 = cache.structure_pool[current_node_index].pointers[child_index];
// Scale computations
let cone_size = (length(ray_origin - pos) + dist_offset) * cone_factor;
let exponent =
select(
cone_size == 0.,
0,
23 - (127 - (asuint(cone_size) >> 23)));
while (
current_node.subdivided_valid() &&
scale_exp - 2 > exponent)
{
scale_exp -= 2;
current_node_index = current_node.pointer();
stack[stack_index * 5 + 10 - scale_exp / 2] = current_node_index;
child_index = get_children_index(pos, scale_exp) ^ child_mirror;
current_node = cache.structure_pool[current_node_index].pointers[child_index];
// Write usage
if (report)
{
cache.usage_buffer[current_node_index] = frame_timestamp;
}
}
// Request subdiv
if (report && current_node.subdivided() && !current_node.pointer_valid())
{
cache.request_buffer[current_node_index].requests[child_index].add(1);
}
uint64_t occupancy = get_child_mask(cache.structure_pool[current_node_index].occupancy_low, cache.structure_pool[current_node_index].occupancy_high);
let occupied = ((occupancy >> child_index) & 1) != 0;
// if (occupied)
if (fetch_color(cache, current_node_index, child_index).byte_a != 0)
{
var hit : HitInformation;
hit.hit = true;
hit.node_index = current_node_index;
hit.child_index = child_index;
hit.hit_pos =
select(
real_ray_direction > 0.,
asfloat(asuint(pos) ^ 0x007fffff),
pos) -
float3(1.);
return hit;
}
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 - ray_origin) / ray_direction;
float inter_t = min(inter_ts.x, min(inter_ts.y, inter_ts.z));
// 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(ray_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_index * 5 + 10 - scale_exp / 2];
}
var hit : HitInformation;
hit.hit = false;
return hit;
}
public struct RayCastContext
{
public float3 ray_direction;
public float3 ray_origin;
public uint32_t3 bounds;
public uint32_t frame_timestamp;
public bool cache_report;
}
public HitInformation ray_cast(
VoxelCache cache,
RayCastContext context,
uint32_t thread_id)
{
let stack_index = thread_id;
// Intersect with bounds
var inter = box_intersect(context.ray_origin, context.ray_direction, float3(0.), float3(context.bounds.x, context.bounds.y, context.bounds.z));
// No hit if out of box
if (inter.y <= inter.x || inter.y <= 0.)
{
var hit : HitInformation;
hit.hit = false;
return hit;
}
inter.x = max(0., inter.x);
// Now march inside chunk bounds
let start_position = inter.x * context.ray_direction + context.ray_origin;
// FVT
int32_t3 current_voxel = clamp(
int32_t3(floor(start_position)),
int32_t3(0),
int32_t3(context.bounds.x - 1, context.bounds.y - 1, context.bounds.z - 1));
// int32_t3 offset = int32_t3(sign(ray_direction));
// float3 delta = abs(1. / ray_direction);
float3 t = select(
context.ray_direction > 0.,
current_voxel + int32_t3(1) - start_position,
start_position - current_voxel) /
abs(context.ray_direction);
t += inter.x;
[loop]
while (true)
{
if (any(current_voxel < 0) || any(current_voxel >= int32_t3(context.bounds.x, context.bounds.y, context.bounds.z)))
{
var hit : HitInformation;
hit.hit = false;
return hit;
}
{
let off = t - abs(1. / context.ray_direction);
let t_adv = max(max(off.x, max(off.y, off.z)), 0.);
let chunk_index = current_voxel.y + current_voxel.z * context.bounds.y + current_voxel.x * context.bounds.y * context.bounds.z;
let position = context.ray_origin + context.ray_direction * t_adv;
var hit = chunk_ray_march(
cache,
context.ray_direction,
position - float3(current_voxel),
chunk_index,
t_adv,
stack_index,
context.frame_timestamp,
context.cache_report);
if (hit.hit)
{
hit.hit_pos += float3(current_voxel);
return hit;
}
}
let min_mask = min_mask(t);
t += select(min_mask, abs(1. / context.ray_direction), float3(0.));
current_voxel += select(min_mask, int32_t3(sign(context.ray_direction)), int32_t3(0));
}
}
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);
}
+205
View File
@@ -0,0 +1,205 @@
import ray_cast;
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;
struct ByteColor
{
uint32_t byte_color;
property uint32_t byte_r
{
get {
return byte_color & 0xFF;
}
}
property uint32_t byte_g
{
get {
return (byte_color >> 8) & 0xFF;
}
}
property uint32_t byte_b
{
get {
return (byte_color >> 16) & 0xFF;
}
}
property uint32_t byte_a
{
get {
return byte_color >> 24;
}
}
property float4 float_color
{
get {
return float4(
float(byte_r) / 255.,
float(byte_g) / 255.,
float(byte_b) / 255.,
float(byte_a) / 255.);
}
}
}
[[vk::binding(0, 0)]]
RWStructuredBuffer<StructurePoolElement> structure_pool;
[[vk::binding(1, 0)]]
RWStructuredBuffer<uint32_t> attributes_pool[2];
[[vk::binding(2, 0)]]
RWStructuredBuffer<LocationPoolElement> location_pool;
[[vk::binding(3, 0)]]
RWStructuredBuffer<RequestBufferElement> request_buffer;
[[vk::binding(4, 0)]]
RWStructuredBuffer<uint32_t> usage_buffer;
[[vk::binding(5, 0)]]
RWStructuredBuffer<StructurePointer> structure_table_pointer;
[[vk::binding(6, 0)]]
RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
ByteColor fetch_color(uint32_t index, uint32_t child_index)
{
return ByteColor(attributes_pool[0][index * 64 + child_index]);
}
float3 fetch_normal(uint32_t index, uint32_t child_index)
{
let a = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3]);
let b = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3 + 1]);
let c = asfloat(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, 1)]]
[[format("rgba32f")]]
WTexture2D<float4> gbuffer_position;
[[vk::binding(1, 1)]]
[[format("rgba32f")]]
WTexture2D<float4> gbuffer_albedo;
[[vk::binding(2, 1)]]
[[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;
}
}
[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;
var voxel_cache : VoxelCache;
voxel_cache.structure_pool = structure_pool;
voxel_cache.attributes_pool = attributes_pool;
voxel_cache.location_pool = location_pool;
voxel_cache.request_buffer = request_buffer;
voxel_cache.usage_buffer = usage_buffer;
voxel_cache.structure_table_pointer = structure_table_pointer;
voxel_cache.structure_table_request_buffer = structure_table_request_buffer;
let ray_direction = get_ray_direction(location.xy);
var ray_cast_context : RayCastContext;
ray_cast_context.ray_direction = ray_direction;
ray_cast_context.ray_origin = constants.cam_pos;
ray_cast_context.bounds = uint32_t3(constants.chunk_width, constants.chunk_alt, constants.chunk_width);
ray_cast_context.frame_timestamp = constants.frame_timestamp;
ray_cast_context.cache_report = true;
let hit = ray_cast(voxel_cache, ray_cast_context, stack_index);
if (hit.hit)
{
// Gather
let hit_pos = hit.hit_pos;
let hit_normal = fetch_normal(hit.node_index, hit.child_index);
let hit_albedo = fetch_color(hit.node_index, hit.child_index).float_color;
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);
}
BIN
View File
Binary file not shown.
-591
View File
@@ -1,591 +0,0 @@
struct VertexOutput
{
@builtin(position) postion: vec4<f32>,
@location(0) @interpolate(flat) chunk_index: u32,
@location(1) color: vec4<f32>,
@location(2) cam_pos: vec3<f32>,
@location(3) world_pos: vec3<f32>,
@location(4) @interpolate(flat) structure_id: u32,
@location(5) chunk_position: vec3<f32>
}
struct ChunkImmediate
{
view_proj: mat4x4<f32>,
cam_pos: vec3<f32>,
frame_timestamp: 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>>;
struct FragmentOutput {
@location(0) color: vec4<f32>,
@builtin(frag_depth) depth: f32, // Equivalent to gl_FragDepth
}
@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.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. / 1920.;
let fovy_rad = (fovy_deg * 3.14) / 180.;
let cone_factor = tan(fovy_rad / 2.) * 2.;
let st_pointer = structure_table_pointer[root_id];
if (!node_subdivided(st_pointer))
{
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);
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);
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 pointer = structure_pool[dfs_stack[current_depth]].pointers[child_pos.x + child_pos.y * 4 + child_pos.z * 4 * 4];
let 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[dfs_stack[current_depth]].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);
dfs_stack[current_depth] = node_pointer(pointer);
pointer = structure_pool[dfs_stack[current_depth]].pointers[child_pos.x + child_pos.y * 4 + child_pos.z * 4 * 4];
// Record usage
usage_buffer[dfs_stack[current_depth]] = constants.frame_timestamp;
}
// Check color
let color = color_pool[dfs_stack[current_depth]].colors[child_pos.x + child_pos.y * 4 + child_pos.z * 4 * 4];
if(((color >> 24) & 0xFF) != 0)
{
var result: HitResult;
result.color = unpack_color(color);
result.hit_pos = (far_t / f32(1 << u32(max_depth * 2))) * ray_dir + ray_origin;
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;
}
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))
{
return vec4(0., 1., 0., 1.);
}
if(!node_pointer_valid(st_pointer))
{
atomicAdd(&structure_table_request_buffer[root_id], 1);
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.);
}
@early_depth_test(less_equal)
@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.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.);
}
*/
-1
View File
@@ -1 +0,0 @@
root = "."
+1 -1
View File
@@ -15,7 +15,7 @@ use winit::window::Window;
pub struct EguiRenderer
{
state: State,
renderer: Renderer,
pub renderer: Renderer,
frame_started: bool,
}
+2
View File
@@ -0,0 +1,2 @@
// Main common gpu parallel algorithms
pub mod radix_sort;
+362
View File
@@ -0,0 +1,362 @@
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,
histogram_pass: ComputePipeline,
prefix_sum_pass: ComputePipeline,
total_prefix_sum_pass: ComputePipeline,
scatter_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 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),
// (Two buffers same layout as histograms)
// Sort count buffer, indirect 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/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 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,
histogram_pass,
prefix_sum_pass,
total_prefix_sum_pass,
scatter_pass,
timing_buffer,
timing_query_set,
}
}
pub fn sort(
&self,
device: &Device,
keys: &Buffer,
values: &Buffer,
encoder: &mut CommandEncoder,
sort_direction: RadixSortDirection,
)
{
dbg!(self.histogram_count);
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 bg = [&data_buffer_bind_group, &self.double_buffer_bind_group];
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(&parameters);
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)], &[]);
// ~~ Histogram pass
compute_pass.set_pipeline(&self.histogram_pass);
compute_pass.set_immediates(0, bytes);
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);
//compute_pass.dispatch_workgroups_indirect(&self., 0);
compute_pass.set_pipeline(&self.scatter_pass);
compute_pass.set_immediates(0, bytes);
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);
}
}
+15
View File
@@ -0,0 +1,15 @@
// Contains useful facilities to render data streamed in from the host
// Can produce a voxel given
// - Its depth
// - Its position within the chunk
// - The chunks position
pub trait ChunkVoxelProducer
{
fn produce_voxel(
&mut self,
depth: usize,
chunk_position: (usize, usize, usize),
voxel_position: (usize, usize, usize),
);
}
+674 -108
View File
File diff suppressed because it is too large Load Diff
+174 -24
View File
@@ -1,8 +1,16 @@
use std::f32::EPSILON;
use std::f32::INFINITY;
use std::fs::File;
use std::path::Path;
use glam::Vec3;
use itertools::Itertools;
use noise::Fbm;
use noise::NoiseFn;
use noise::Perlin;
use noise::Simplex;
use noise::Worley;
use rand::random;
use crate::sparse_tree::Color;
use crate::voxel_cache::data::ExplicitNTreeNode;
@@ -53,6 +61,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;
@@ -73,35 +82,29 @@ where
let child_diagonal_length = (child_size as f32 / 2.) * f32::sqrt(3.);
let alpha;
let subdivided;
if (dist - (global_size as f32 / 2.)).abs() <= child_diagonal_length
{
//children.push(StructurePointer::new(depth <= 3, false, 0));
children.push(StructurePointer(
if depth < (self.chunk_power - 1)
{
0xFFFFFFFF
}
else
{
0
},
));
subdivided = depth < (self.chunk_power - 1);
alpha = if dist > 128. { 0. } else { 1. };
}
else if dist > (global_size as f32 / 2.)
{
children.push(StructurePointer(0));
subdivided = false;
alpha = 0.;
}
else
{
children.push(StructurePointer(0));
subdivided = false;
alpha = 1.;
}
// let alpha = 1.;
// children.push(StructurePointer::new(depth <= 3, false, 0));
children.push(StructurePointer::new(subdivided, subdivided || alpha != 0.));
children_normal.push((0., 0., 0.));
children_color.push(Color(
gvx as f32 / global_size as f32,
gvy as f32 / global_size as f32,
@@ -113,6 +116,7 @@ where
ExplicitNTreeNode {
structure: std::array::from_fn(|i| children[i]),
colors: std::array::from_fn(|i| children_color[i]),
normals: std::array::from_fn(|i| children_normal[i]),
}
}
}
@@ -143,6 +147,7 @@ where
let global_size = N.pow(self.chunk_power as u32);
let mut children = vec![];
let mut children_normal = vec![];
let mut children_color = vec![];
let gnx = nx * node_size;
@@ -217,6 +222,7 @@ where
};
}
children_normal.push((0., 0., 0.));
children_color.push(Color(
(gcx + child_size / 2) as f32 / global_size as f32,
(gcy + child_size / 2) as f32 / global_size as f32,
@@ -228,6 +234,7 @@ where
ExplicitNTreeNode {
structure: std::array::from_fn(|i| children[i]),
colors: std::array::from_fn(|i| children_color[i]),
normals: std::array::from_fn(|i| children_normal[i]),
}
}
}
@@ -425,6 +432,7 @@ where
let mut children = vec![StructurePointer(0); 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;
@@ -530,28 +538,20 @@ where
let gcy = gny + cy * child_size;
let index = cz * N * N + cy * N + cx;
let alpha;
let subdivided;
if gcy > sample_max
{
children[index] = StructurePointer(0);
subdivided = false;
alpha = 0.;
}
else if gcy + child_size < sample_min
{
children[index] = StructurePointer(0);
subdivided = false;
alpha = 1.;
}
else
{
children[index] = StructurePointer(
if depth < (self.chunk_power - 1)
{
0xFFFFFFFF
}
else
{
0
},
);
subdivided = depth < (self.chunk_power - 1);
//children.push(StructurePointer(0));
alpha = if (sample_max + sample_min / 2) > gcy + (child_size / 2)
{
@@ -563,13 +563,17 @@ where
};
}
children[index] = StructurePointer::new(subdivided, subdivided || alpha != 0.);
children_normals[index] = (0., 0., 0.);
children_color[index] = Color(color_avg.0, color_avg.1, color_avg.2, alpha);
//children_color[index] = Color(1., 1., 1., alpha);
}
}
ExplicitNTreeNode {
structure: std::array::from_fn(|i| children[i]),
colors: std::array::from_fn(|i| children_color[i]),
normals: std::array::from_fn(|i| children_normals[i]),
}
}
}
@@ -587,3 +591,149 @@ where
chunk_pos: (usize, usize, usize),
) -> ExplicitNTreeNode<N>;
}
pub struct SdfGenerator<const N: usize>
{
chunk_power: usize,
perlin: Perlin,
}
impl<const N: usize> SdfGenerator<N>
{
pub fn new(chunk_power: usize) -> Self
{
Self {
chunk_power,
perlin: Perlin::new(67),
}
}
}
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),
) -> ExplicitNTreeNode<N>
{
// let sdf = |x: f32, y: f32, z: f32| {
// Vec3::new((x % 1024.) - 512., (y % 1024.) - 512., (z % 1024.) - 512.).length() - 512.
// };
let sdf = |x: f32, y: f32, z: f32| {
let tx = x / 512.;
let ty = y / 512.;
let tz = z / 512.;
let val = self.perlin.get([tx as f64, ty as f64, tz as f64]);
let dist = val * 128.;
return dist as f32;
};
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(StructurePointer::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));
}
ExplicitNTreeNode {
structure: std::array::from_fn(|i| children[i]),
colors: std::array::from_fn(|i| children_color[i]),
normals: std::array::from_fn(|i| children_normals[i]),
//normals: std::array::from_fn(|i| (1., 0., 0.)),
}
}
}
+2
View File
@@ -348,6 +348,7 @@ where
}
}
/*
pub fn as_explicit_structure(&self) -> (Color, Vec<ExplicitNTreeNode<N>>)
{
let root = self.map.get(&NTreeNodeLocator::root()).unwrap();
@@ -391,6 +392,7 @@ where
(root.color, explicit_structure)
}
*/
}
fn base_trailing_zeroes<const N: usize>(mut number: usize) -> Option<u32>
+157 -54
View File
@@ -1,5 +1,7 @@
use std::num::NonZero;
use bytemuck::Zeroable;
use wgpu::{BindGroup, BindGroupLayout, Buffer, BufferUsages, CommandEncoder, ComputePipeline, Device, Queue, ShaderStages};
use wgpu::{BindGroup, BindGroupLayout, Buffer, BufferUsages, CommandEncoder, ComputePipeline, Device, Queue, ShaderStages, util::DeviceExt};
use crate::voxel_cache::{data::{CacheNodeRequest, CacheResponse, ColorPoolElement, LocationPoolElement, StructurePoolElement}, producer_interface::CacheProducerInterface, request_buffer::RequestBuffer, structure_table::StructureTable, usage_buffer::UsageBuffer};
@@ -8,6 +10,7 @@ pub mod request_buffer;
pub mod structure_table;
pub mod usage_buffer;
pub mod producer_interface;
pub mod indirect_buffer;
pub mod data;
@@ -17,8 +20,9 @@ pub struct VoxelCache<const N: usize>
device: Device,
queue: Queue,
structure_pool: Buffer,
color_pool: Buffer,
location_pool: Buffer,
depth_pool: Buffer,
attributes_pools: Vec<Buffer>,
pub structure_table: StructureTable,
@@ -40,6 +44,12 @@ pub struct VoxelCache<const N: usize>
pub usage_buffer: UsageBuffer,
}
#[derive(Clone, Copy)]
pub struct VoxelAttribute
{
pub word_count: u32
}
#[derive(Zeroable, bytemuck::Pod, Clone, Copy)]
#[repr(C)]
@@ -59,7 +69,7 @@ impl<const N: usize> VoxelCache<N>
where
[(); N * N * N]:,
{
pub fn new(cache_size: usize, device: Device, queue: Queue) -> Self
pub fn new(cache_size: usize, device: Device, queue: Queue, attributes: Vec<VoxelAttribute>) -> Self
{
let structure_pool = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Structure pool"),
@@ -75,17 +85,29 @@ where
mapped_at_creation: false,
});
let color_pool = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Color pool"),
size: (size_of::<ColorPoolElement<N>>() * cache_size) as u64,
let depth_pool = device.create_buffer_init(&wgpu::util::BufferInitDescriptor{
label: Some("Depth pool"),
contents: bytemuck::cast_slice(&vec![0xFFFFFFFFu32; cache_size]),
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
});
// Create attribttues
let attributes_pools =
attributes.iter().enumerate()
.map(|(i, x)|
device.create_buffer(&wgpu::BufferDescriptor
{
label: Some(format!("VoxelCache<{N}>::attributes[{i}]").as_str()),
size: ((x.word_count as usize) * N * N * N * cache_size * size_of::<u32>()) as u64,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
})
).collect::<Vec<_>>();
let request_buffer = RequestBuffer::new(cache_size, device.clone());
let usage_buffer = UsageBuffer::new(cache_size, device.clone());
let request_interface_bind_group_layout = CacheProducerInterface::<N>::request_side_bind_group_layout(&device);
let request_interface_bind_group_layout = CacheProducerInterface::<N>::request_side_bind_group_layout(&device, &attributes);
// Rendering bing group layouts
let voxel_cache_render_bind_group_layout =
@@ -95,7 +117,7 @@ where
// Structure pool
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::FRAGMENT,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
@@ -103,21 +125,21 @@ where
},
count: None,
},
// Color pool
// Attributes pool
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::FRAGMENT,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
count: Some(NonZero::new(attributes.len() as u32).unwrap()),
},
// Location pool
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: ShaderStages::FRAGMENT,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
@@ -128,7 +150,7 @@ where
// Request buffer
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: ShaderStages::FRAGMENT,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
@@ -139,7 +161,7 @@ where
// Usage buffer
wgpu::BindGroupLayoutEntry {
binding: 4,
visibility: ShaderStages::FRAGMENT,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
@@ -152,7 +174,7 @@ where
// Structure table pointers
wgpu::BindGroupLayoutEntry {
binding: 5,
visibility: ShaderStages::FRAGMENT,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
@@ -164,7 +186,7 @@ where
// Structure table request buffer
wgpu::BindGroupLayoutEntry {
binding: 6,
visibility: ShaderStages::FRAGMENT,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
@@ -190,7 +212,7 @@ where
},
count: None,
},
// Color pool
// Attributes pool
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::COMPUTE,
@@ -199,7 +221,7 @@ where
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
count: Some(NonZero::new(attributes.len() as u32).unwrap()),
},
// Location pool
wgpu::BindGroupLayoutEntry {
@@ -212,18 +234,18 @@ where
},
count: None,
},
// Sorted requests
// Depth pool
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// LRU List
// Sorted requests
wgpu::BindGroupLayoutEntry {
binding: 4,
visibility: ShaderStages::COMPUTE,
@@ -234,10 +256,21 @@ where
},
count: None,
},
// Usage buffer
// LRU List
wgpu::BindGroupLayoutEntry {
binding: 5,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// Usage buffer
wgpu::BindGroupLayoutEntry {
binding: 6,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
@@ -247,7 +280,7 @@ where
},
// pools request count
wgpu::BindGroupLayoutEntry {
binding: 6,
binding: 7,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
@@ -259,6 +292,7 @@ where
],
});
let attributes_bindings = attributes_pools.iter().map(|x| x.as_entire_buffer_binding()).collect::<Vec<wgpu::BufferBinding<'_>>>();
let voxel_cache_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("voxel_cache_bind_group"),
layout: &voxel_cache_bind_group_layout,
@@ -268,34 +302,41 @@ where
binding: 0,
resource: structure_pool.as_entire_binding(),
},
// Color pool
// Attributes pool
wgpu::BindGroupEntry {
binding: 1,
resource: color_pool.as_entire_binding(),
resource: wgpu::BindingResource::BufferArray(
attributes_bindings.as_slice()
),
},
// Location pool
wgpu::BindGroupEntry {
binding: 2,
resource: location_pool.as_entire_binding(),
},
// Sorted requests
// Depth pool
wgpu::BindGroupEntry {
binding: 3,
resource: request_buffer.sort_buffer().as_entire_binding(),
resource: depth_pool.as_entire_binding(),
},
// Sorted requests
wgpu::BindGroupEntry {
binding: 4,
resource: request_buffer.index_buffer().as_entire_binding(),
},
// LRU list
wgpu::BindGroupEntry {
binding: 4,
binding: 5,
resource: usage_buffer.sort_buffer().as_entire_binding(),
},
// Usage buffer
wgpu::BindGroupEntry {
binding: 5,
binding: 6,
resource: usage_buffer.usage_buffer().as_entire_binding(),
},
// Pools request count
wgpu::BindGroupEntry {
binding: 6,
binding: 7,
resource: request_buffer.request_count_buffer().as_entire_binding(),
},
],
@@ -342,10 +383,15 @@ where
});
let children_count = N*N*N;
let attribute_count = attributes.len();
let wgsl_bindings =
format!("
enable wgpu_binding_array;
struct StructurePoolElement
{{
occupancy_low: atomic<u32>,
occupancy_high: atomic<u32>,
pointers: array<u32, {children_count}>
}}
@@ -366,16 +412,22 @@ where
child: u32
}}
struct AttributeArray
{{
values: array<u32>,
}}
@group(0) @binding(0) var<storage, read_write> structure_pool: array<StructurePoolElement>;
@group(0) @binding(1) var<storage, read_write> color_pool: array<ColorPoolElement>;
@group(0) @binding(1) var<storage, read_write> attributes_pools: binding_array<AttributeArray, {attribute_count}>;
@group(0) @binding(2) var<storage, read_write> location_pool: array<LocationPoolElement>;
@group(0) @binding(3) var<storage, read> sorted_requests: array<SortedRequestsElement>;
@group(0) @binding(4) var<storage, read> lru_list: array<u32>;
@group(0) @binding(5) var<storage, read_write> usage_buffer: array<u32>;
@group(0) @binding(6) var<storage, read> pools_request_count: u32;
@group(0) @binding(3) var<storage, read_write> depth_pool: array<u32>;
@group(0) @binding(4) var<storage, read> sorted_requests: array<u32>;
@group(0) @binding(5) var<storage, read> lru_list: array<u32>;
@group(0) @binding(6) var<storage, read_write> usage_buffer: array<u32>;
@group(0) @binding(7) var<storage, read> pools_request_count: u32;
@group(1) @binding(0) var<storage, read_write> structure_table_pointers: array<u32>;
@group(1) @binding(1) var<storage, read_write> structure_table_sorted_requests: array<SortedRequestsElement>;
@group(1) @binding(1) var<storage, read_write> structure_table_sorted_requests: array<u32>;
@group(1) @binding(2) var<storage, read_write> structure_table_request_count: u32;
");
@@ -442,7 +494,7 @@ where
{{
var request: CacheInterfaceRequest;
// Index in structure table IS structure id
request.structure_id = structure_table_sorted_requests[index].node;
request.structure_id = structure_table_sorted_requests[index];
request.locator = 0; // Root request -> locator 0
request.child_index = 0xFFFFFFFF; // child index u32::MAX ->
@@ -457,16 +509,19 @@ where
}}
let pool_index = index - structure_table_request_count;
let sorted_requests_node = sorted_requests[pool_index] / 64;
let sorted_requests_child = sorted_requests[pool_index] % 64;
// Request location comes from location pool
var request: CacheInterfaceRequest;
request.structure_id = location_pool[sorted_requests[pool_index].node].structure_id;
request.locator = location_pool[sorted_requests[pool_index].node].structure_locator;
request.child_index = sorted_requests[pool_index].child;
request.structure_id = location_pool[sorted_requests_node].structure_id;
request.locator = location_pool[sorted_requests_node].structure_locator;
request.child_index = sorted_requests_child;
var request_wb: CacheInterfaceRequestWb;
request_wb.node_index = sorted_requests[pool_index].node;
request_wb.child_index = sorted_requests[pool_index].child;
request_wb.node_index = sorted_requests_node;
request_wb.child_index = sorted_requests_child;
// Write request
requests[index] = request;
@@ -489,7 +544,7 @@ where
let caching_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("caching_pipelien_layout"),
label: Some("caching_pipeline_layout"),
bind_group_layouts: &[
Some(&voxel_cache_bind_group_layout),
Some(&structure_table_bind_group_layout),
@@ -498,6 +553,23 @@ where
immediate_size: size_of::<CachingPipelineImmediates>() as u32, // Current frame timestamp
});
// Generate attributes copy loops
let mut copy_loops = String::new();
for (attribute_index, attribute) in attributes.iter().enumerate()
{
let node_size = attribute.word_count * children_count as u32;
let word_count = attribute.word_count;
copy_loops += format!("
for(var i = 0u; i < {children_count}; i++){{
for(var j = 0u; j < {word_count}; j++){{
let offset = i * {word_count} + j;
attributes_pools[{attribute_index}].values[overwritten_element * {node_size} + offset]
= attributes_nodes[{attribute_index}].values[index * {node_size} + offset];
}}
}}
").as_str();
}
let children_count = N * N * N;
let caching_pipeline =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
@@ -507,6 +579,7 @@ where
label: Some("caching_pipeline_shader_module"),
source: wgpu::ShaderSource::Wgsl(
format!("
{wgsl_bindings}
struct DestinationElement
{{
@@ -520,7 +593,6 @@ where
write_pointers: u32
}}
{wgsl_bindings}
var<immediate> parameters: CachingPipelineImmediates;
@@ -542,7 +614,7 @@ where
@group(2) @binding(2) var<storage, read_write> request_count: u32;
@group(2) @binding(3) var<storage, read_write> structure_nodes: array<StructurePoolElement>;
@group(2) @binding(4) var<storage, read_write> color_nodes: array<ColorPoolElement>;
@group(2) @binding(4) var<storage, read_write> attributes_nodes: binding_array<AttributeArray, {attribute_count}>;
@group(2) @binding(5) var<storage, read_write> locations: array<LocationPoolElement>;
@compute
@@ -565,15 +637,43 @@ where
{{
// Phase 1
// Copy into cache page
var occupancy_high = u32(0);
var occupancy_low = u32(0);
for(var i = 0; i < {children_count}; i++)
{{
structure_pool[overwritten_element].pointers[i] = select(u32(0), u32(1)<<31, structure_nodes[index].pointers[i] != 0);
structure_pool[overwritten_element].pointers[i] =
select(u32(0), u32(1)<<31, (structure_nodes[index].pointers[i] >> 31) != 0);
var bit = u32(1);
if(i % ({children_count} / 2) != 0)
{{
bit = u32(u32(1) << u32(i % ({children_count} / 2)));
}}
let turn_on_bit =
select(
u32(0),
bit,
((structure_nodes[index].pointers[i] >> 30) & 1) != 0
);
if(i >= {children_count} / 2)
{{
occupancy_high |= turn_on_bit;
}}else
{{
occupancy_low |= turn_on_bit;
}}
}}
color_pool[overwritten_element] = color_nodes[index];
atomicStore(&structure_pool[overwritten_element].occupancy_low, occupancy_low);
atomicStore(&structure_pool[overwritten_element].occupancy_high, occupancy_high);
{copy_loops}
location_pool[overwritten_element] = locations[index];
// Mark dirty/correct timestamp
usage_buffer[overwritten_element] = parameters.frame_timestamp + 1;
usage_buffer[overwritten_element] = parameters.frame_timestamp + 1;
}}
if(parameters.write_pointers != 0 && usage_buffer[overwritten_element] != parameters.frame_timestamp)
@@ -585,9 +685,11 @@ where
if(requests_wb[index].child_index == 0xFFFFFFFF)
{{
structure_table_pointers[requests_wb[index].node_index] = new_pointer;
depth_pool[overwritten_element] = 0;
}}else if usage_buffer[requests_wb[index].node_index] != parameters.frame_timestamp + 1
{{
structure_pool[requests_wb[index].node_index].pointers[requests_wb[index].child_index] = new_pointer;
depth_pool[overwritten_element] = depth_pool[requests_wb[index].node_index] + 1;
}}
}}
@@ -688,7 +790,8 @@ where
queue,
device,
structure_pool,
color_pool,
attributes_pools,
depth_pool,
location_pool,
request_buffer,
usage_buffer,
@@ -715,6 +818,7 @@ where
pub fn bind_group(&self) -> BindGroup
{
let attributes_bindings = self.attributes_pools.iter().map(|x| x.as_entire_buffer_binding()).collect::<Vec<wgpu::BufferBinding<'_>>>();
self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("voxel_cache_render_bind_group"),
layout: &self.voxel_cache_render_bind_group_layout,
@@ -727,7 +831,7 @@ where
// Color pool
wgpu::BindGroupEntry {
binding: 1,
resource: self.color_pool.as_entire_binding(),
resource: wgpu::BindingResource::BufferArray(attributes_bindings.as_slice()),
},
// Location pool
wgpu::BindGroupEntry {
@@ -775,7 +879,7 @@ where
wgpu::BindGroupEntry
{
binding: 1,
resource: self.structure_table.request_buffer.sort_buffer().as_entire_binding(),
resource: self.structure_table.request_buffer.index_buffer().as_entire_binding(),
},
wgpu::BindGroupEntry
{
@@ -791,7 +895,6 @@ where
// Sort requests, reset request buffers to count requests
self.usage_buffer.sort_usage(encoder);
self.request_buffer.sort_requests(encoder);
self.structure_table
.request_buffer_mut()
.sort_requests(encoder);
+7 -4
View File
@@ -24,11 +24,14 @@ where
request_count: [u32; N * N * N],
}
#[repr(C)]
pub struct StructurePoolElement<const N: usize>
where
[(); N * N * N]:,
{
pointers: [StructurePointer; N * N * N],
pub occupancy_low: u32,
pub occupancy_high: u32,
pub pointers: [StructurePointer; N * N * N],
}
pub struct DestinationElement
@@ -84,10 +87,9 @@ pub struct StructurePointer(pub u32);
impl StructurePointer
{
pub fn new(subdivided: bool, pointer_valid: bool, pointer: u32) -> Self
pub fn new(subdivided: bool, occupied: bool) -> Self
{
assert!(pointer >> 30 == 0);
StructurePointer((subdivided as u32) << 31 | (pointer_valid as u32) << 30 | pointer)
StructurePointer(((subdivided as u32) << 31) | ((occupied as u32) << 30))
}
}
@@ -99,4 +101,5 @@ where
{
pub structure: [StructurePointer; N * N * N],
pub colors: [Color; N * N * N],
pub normals: [(f32, f32, f32); N * N * N],
}
+240
View File
@@ -0,0 +1,240 @@
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,
},
],
});
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: 0,
});
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/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,
)
{
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(),
},
],
});
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.dispatch_workgroups(self.block_count as u32, 1, 1);
}
}
+37 -19
View File
@@ -2,6 +2,8 @@
// The cache producer interface provides the necessary buffers to contains
// these, so that use applications can fullfill the requests
use std::num::NonZero;
use bytemuck::Pod;
use bytemuck::Zeroable;
use wgpu::BindGroup;
@@ -15,6 +17,7 @@ use wgpu::Device;
use wgpu::Queue;
use wgpu::util::DownloadBuffer;
use crate::voxel_cache::VoxelAttribute;
use crate::voxel_cache::data::ColorPoolElement;
use crate::voxel_cache::data::LocationPoolElement;
use crate::voxel_cache::data::StructurePoolElement;
@@ -51,7 +54,7 @@ where
pub(super) requests_wb_info: Buffer,
// Request fullfillment
pub(super) structure_nodes: Buffer,
pub(super) color_nodes: Buffer,
pub(super) attributes_nodes: Vec<Buffer>,
pub(super) location_nodes: Buffer,
pub(super) request_side_bind_group_layout: BindGroupLayout,
@@ -64,7 +67,7 @@ impl<const N: usize> CacheProducerInterface<N>
where
[(); N * N * N]:,
{
pub fn new(size: usize, device: &Device) -> Self
pub fn new(size: usize, device: &Device, attributes: Vec<VoxelAttribute>) -> Self
{
let requests = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("cache_interface_request_buffer"),
@@ -87,12 +90,19 @@ where
mapped_at_creation: false,
});
let color_nodes = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("cache_interface_structure_nodes"),
size: (size_of::<ColorPoolElement<N>>() * size) as u64,
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST,
mapped_at_creation: false,
});
// Create attributes
let attributes_nodes = attributes
.iter()
.enumerate()
.map(|(i, x)| {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(format!("VoxelCache<{N}>::attributes[{i}]").as_str()),
size: ((x.word_count as usize) * N * N * N * size * size_of::<u32>()) as u64,
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST,
mapped_at_creation: false,
})
})
.collect::<Vec<_>>();
let location_nodes = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("cache_interface_structure_nodes"),
@@ -108,7 +118,8 @@ where
mapped_at_creation: false,
});
let request_side_bind_group_layout = Self::request_side_bind_group_layout(device);
let request_side_bind_group_layout =
Self::request_side_bind_group_layout(device, &attributes);
let producer_side_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("cache_interface_producer_side_bind_group_layout"),
@@ -146,7 +157,7 @@ where
},
count: None,
},
// Color nodes
// Attributes nodes
BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::COMPUTE,
@@ -155,7 +166,7 @@ where
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
count: Some(NonZero::new(attributes.len() as u32).unwrap()),
},
// Location nodes
BindGroupLayoutEntry {
@@ -172,6 +183,10 @@ where
});
// Bind groups
let attributes_bindings = attributes_nodes
.iter()
.map(|x| x.as_entire_buffer_binding())
.collect::<Vec<wgpu::BufferBinding<'_>>>();
let request_side_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("cache_interface_request_side_bind_group"),
layout: &request_side_bind_group_layout,
@@ -194,7 +209,7 @@ where
},
BindGroupEntry {
binding: 4,
resource: color_nodes.as_entire_binding(),
resource: wgpu::BindingResource::BufferArray(&attributes_bindings),
},
BindGroupEntry {
binding: 5,
@@ -221,7 +236,7 @@ where
},
BindGroupEntry {
binding: 3,
resource: color_nodes.as_entire_binding(),
resource: wgpu::BindingResource::BufferArray(&attributes_bindings),
},
BindGroupEntry {
binding: 4,
@@ -236,7 +251,7 @@ where
request_count,
requests_wb_info,
structure_nodes,
color_nodes,
attributes_nodes,
location_nodes,
request_side_bind_group_layout,
@@ -256,9 +271,9 @@ where
&self.structure_nodes
}
pub fn color_nodes_buffer(&self) -> &Buffer
pub fn attributes_buffers(&self) -> &[Buffer]
{
&self.color_nodes
&self.attributes_nodes
}
pub fn location_nodes_buffer(&self) -> &Buffer
@@ -292,7 +307,10 @@ where
//panic!("Could not retrieve total request count.");
}
pub fn request_side_bind_group_layout(device: &Device) -> BindGroupLayout
pub fn request_side_bind_group_layout(
device: &Device,
attributes: &[VoxelAttribute],
) -> BindGroupLayout
{
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("cache_interface_request_side_bind_group_layout"),
@@ -341,7 +359,7 @@ where
},
count: None,
},
// Color nodes
// Attributes nodes
BindGroupLayoutEntry {
binding: 4,
visibility: wgpu::ShaderStages::COMPUTE,
@@ -350,7 +368,7 @@ where
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
count: Some(NonZero::new(attributes.len() as u32).unwrap()),
},
// Location nodes
BindGroupLayoutEntry {
+103 -453
View File
@@ -8,24 +8,27 @@ use wgpu::ComputePipeline;
use wgpu::Device;
use wgpu::ShaderStages;
use crate::gpu::radix_sort;
use crate::gpu::radix_sort::RadixSorter;
use crate::voxel_cache::data::RequestBufferElement;
use crate::voxel_cache::indirect_buffer::NonZeroBufferCompactor;
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 cache_size: usize,
pub compaction_pipeline: ComputePipeline,
pub running_sum_pipeline: ComputePipeline,
pub request_buffer: Buffer,
pub keys_buffer: Buffer,
pub index_buffer: Buffer,
pub request_count: Buffer,
pub sorter: RadixSorter,
pub buffer_compactor: NonZeroBufferCompactor,
pub bindgroup: BindGroup,
pub reset_pass: ComputePipeline,
pub copy_pass: ComputePipeline,
}
impl<const N: usize> RequestBuffer<N>
@@ -34,64 +37,41 @@ where
{
pub fn new(cache_size: usize, device: Device) -> Self
{
let buffer_sizes = (size_of::<u32>() * cache_size * N * N * N) as u64;
// Contains request counts
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,
size: buffer_sizes,
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,
// Contains indices compacted by compactor, and later sorted
let index_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some(format!("request_index_buffer_{N}").as_str()),
size: buffer_sizes,
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 {
// Used as keys for the sorter
let keys_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,
size: buffer_sizes,
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
mapped_at_creation: true,
mapped_at_creation: false,
});
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();
// Amount of requests produced by non zero compactor
let request_count = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("request_count_storage_buffer"),
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC | BufferUsages::COPY_DST,
size: size_of::<u32>() as u64,
mapped_at_creation: false,
});
let bindgroup_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("request_sort_pipeline_bing_group_layout"),
label: Some("RequestCount::bindgroup_layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
@@ -133,21 +113,11 @@ where
},
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"),
label: Some("RequestCount::bindgroup"),
layout: &bindgroup_layout,
entries: &[
BindGroupEntry {
@@ -156,19 +126,15 @@ where
},
BindGroupEntry {
binding: 1,
resource: sort_buffer.as_entire_binding(),
resource: index_buffer.as_entire_binding(),
},
BindGroupEntry {
binding: 2,
resource: request_count_buffer.as_entire_binding(),
resource: keys_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(),
resource: request_count.as_entire_binding(),
},
],
});
@@ -179,125 +145,29 @@ where
immediate_size: size_of::<u32>() as u32,
});
let children_count = N * N * N;
let sort_pipeline =
let reset_pass =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("Sort node request"),
label: Some("RequestBuffer::reset_pass"),
layout: Some(pipeline_layouts),
module: &device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("clear_chunk_requests shader module"),
label: Some("RequestBuffer::reset_pass_module"),
source: wgpu::ShaderSource::Wgsl(
#[allow(clippy::useless_format)]
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);
}}
@group(0) @binding(0) var<storage, read_write> request_buffer: array<u32>;
@group(0) @binding(1) var<storage, read_write> index_buffer: array<u32>;
@group(0) @binding(2) var<storage, read_write> keys_buffer: array<u32>;
@group(0) @binding(3) var<storage, read_write> request_count: u32;
@compute
@workgroup_size(64)
@workgroup_size(256, 1, 1)
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;
}}
let total = arrayLength(&request_buffer);
if(global_invocation_id.x >= total) {{return;}}
request_buffer[global_invocation_id.x] = 0;
}}
")
.into(),
@@ -308,209 +178,30 @@ where
cache: None,
});
let running_sum_pipeline =
// This pipeline handles copying the request counts into the key buffer
// according to the compacted index_buffer
let copy_pass =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("running_sum_pipeline"),
label: Some("RequestBuffer::copy_pass"),
layout: Some(pipeline_layouts),
module: &device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("running_sum shader module"),
label: Some("RequestBuffer::copy_pass_module"),
source: wgpu::ShaderSource::Wgsl(
#[allow(clippy::useless_format)]
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;
@group(0) @binding(0) var<storage, read_write> request_buffer: array<u32>;
@group(0) @binding(1) var<storage, read_write> index_buffer: array<u32>;
@group(0) @binding(2) var<storage, read_write> keys_buffer: array<u32>;
@group(0) @binding(3) var<storage, read_write> request_count: u32;
@compute
@workgroup_size(64)
@workgroup_size(256, 1, 1)
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;
}}
if(global_invocation_id.x >= request_count) {{return;}}
keys_buffer[global_invocation_id.x] = request_buffer[index_buffer[global_invocation_id.x]];
}}
")
.into(),
@@ -524,16 +215,14 @@ where
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,
index_buffer,
keys_buffer,
request_count,
reset_pass,
copy_pass,
bindgroup,
buffer_compactor: NonZeroBufferCompactor::new(&device, cache_size * N * N * N),
sorter: RadixSorter::new(&device, cache_size * N * N * N),
device,
}
}
@@ -545,12 +234,12 @@ where
pub fn request_count_buffer(&self) -> &Buffer
{
&self.request_count_buffer
&self.request_count
}
pub fn sort_buffer(&self) -> &Buffer
pub fn index_buffer(&self) -> &Buffer
{
&self.sort_buffer
&self.index_buffer
}
pub fn reset_requests(&self, encoder: &mut CommandEncoder)
@@ -561,84 +250,45 @@ where
});
compute_pass.set_bind_group(0, Some(&self.bindgroup), &[]);
compute_pass.set_pipeline(&self.reset_pipeline);
compute_pass.set_pipeline(&self.reset_pass);
let shader_invocations = self.cache_size; // one invocation per element
let workgroup_invocations = shader_invocations.div_ceil(64);
let shader_invocations = self.cache_size * N * N * N; // one invocation per element
let workgroup_invocations = shader_invocations.div_ceil(256);
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,
});
// Compact list
self.buffer_compactor.compact_buffer(
&self.device,
encoder,
&self.request_buffer,
&self.index_buffer,
);
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);
self.buffer_compactor
.copy_count_to_buffer(encoder, &self.request_count);
// = Perform list compaction
let mut copy_keys_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("RequestBuffer::copy_keys_pass"),
timestamp_writes: None,
});
// == Running sum
compaction_compute_pass.set_pipeline(&self.running_sum_pipeline);
copy_keys_pass.set_bind_group(0, Some(&self.bindgroup), &[]);
copy_keys_pass.set_pipeline(&self.copy_pass);
let shader_invocations = self.cache_size * N * N * N; // one invocation per element
let workgroup_invocations = shader_invocations.div_ceil(256) as u32;
copy_keys_pass.dispatch_workgroups(workgroup_invocations, 1, 1);
drop(copy_keys_pass);
// 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);
}
self.sorter.sort(
&self.device,
&self.keys_buffer,
&self.index_buffer,
//Some(&self.request_count),
encoder,
radix_sort::RadixSortDirection::Descending,
);
}
}
+1 -1
View File
@@ -119,7 +119,7 @@ impl StructureTable
NonZero::new(size_of::<u32>() as u64).unwrap(),
)
.copy_from_slice(bytemuck::bytes_of(
&StructurePointer::new(subdivided, false, 0).0,
&StructurePointer::new(subdivided, false).0,
));
self.write_staging.finish_and_recall_on_submit(&encoder);
self.queue.submit([encoder.finish()]);
BIN
View File
Binary file not shown.