feat: bad bvh

This commit is contained in:
2026-11-14 16:15:19 +01:00
parent e7fbeb7887
commit 4581538c66
8 changed files with 81 additions and 185 deletions
+54 -157
View File
@@ -3,27 +3,11 @@ import voxel_cache;
public struct Aabb
{
public float min_x;
public float min_y;
public float min_z;
public float3 min;
uint32_t _pad0; // std430 aligns float3 to 16 bytes
uint32_t _pad0;
public float max_x;
public float max_y;
public float max_z;
uint32_t _pad1;
public float3 min()
{
return float3(this.min_x, this.min_y, this.min_z);
}
public float3 max()
{
return float3(this.max_x, this.max_y, this.max_z);
}
public float3 max;
uint32_t _pad1;
}
public struct BvhNode
@@ -67,6 +51,7 @@ public struct BvhCursor
uint32_t current_node;
uint32_t depth;
float t;
}
public struct BvhParameters
@@ -77,8 +62,8 @@ public struct BvhParameters
RWStructuredBuffer<Atomic<uint32_t>> requests;
}
static const uint32_t STACK_SIZE = 4;
static const uint32_t STACK_MASK = 0b11;
static const uint32_t STACK_SIZE = 8;
static const uint32_t STACK_MASK = 7;
groupshared uint32_t stack[STACK_SIZE * 256];
groupshared uint32_t stack_depth[STACK_SIZE * 256];
@@ -105,63 +90,68 @@ public struct Bvh : IStructure
public bool next(inout BvhCursor c, out Cell cell)
{
uint32_t node_index = 0;
uint64_t out_b = 0;
while (true && out_b < 80)
uint32_t outer_bound = 0;
while (outer_bound < 300)
{
out_b += 1;
uint32_t b = 0;
while (parameters.nodes[node_index].is_internal() && b < 80)
outer_bound++;
uint32_t inner_bound = 0;
if (parameters.nodes[c.current_node].is_internal() && inner_bound < 300)
{
b++;
uint32_t left = parameters.nodes[node_index].first_or_left;
float2 inter1 = box_intersect(c.ray.origin, c.ray.direction, parameters.nodes[left].aabb.min(), parameters.nodes[left].aabb.max());
float2 inter2 = box_intersect(c.ray.origin, c.ray.direction, parameters.nodes[left + 1].aabb.min(), parameters.nodes[left + 1].aabb.max());
inner_bound++;
let left_index = parameters.nodes[c.current_node].first_or_left;
float2 left = box_intersect(c.ray.origin, c.ray.direction, parameters.nodes[left_index].aabb.min, parameters.nodes[left_index].aabb.max);
float2 right = box_intersect(c.ray.origin, c.ray.direction, parameters.nodes[left_index + 1].aabb.min, parameters.nodes[left_index + 1].aabb.max);
bool hit1 = inter1.x <= inter1.y && inter1.y >= 0;
bool hit2 = inter2.x <= inter2.y && inter2.y >= 0;
bool left_hit = left.y >= left.x && left.y >= 0.;
bool right_hit = right.y >= right.x && right.y >= 0.;
if (hit1 && hit2)
if (left_hit && right_hit)
{
let near = select(inter1.x < inter2.x, left, left + 1);
let far = select(inter1.x < inter2.x, left + 1, left);
// Push far
this.push(far, c);
// Go to near
// Select closest
let go_left = left.y < right.y;
c.current_node = select(go_left, left_index, left_index + 1);
this.push(select(go_left, left_index + 1, left_index), c);
c.depth += 1;
node_index = near;
}
else if (hit1 || hit2)
else if (left_hit || right_hit)
{
// Go to hit
c.current_node = select(left_hit, left_index, left_index + 1);
c.bit_stack |= 1 << c.depth;
c.depth += 1;
node_index = select(hit1, left, left + 1);
}
else
{
// none hit, go to next
if (!this.pop(node_index, c))
if (!this.pop(c.current_node, c))
{
return false;
}
}
}
if (parameters.nodes[node_index].is_leaf())
if (parameters.nodes[c.current_node].is_leaf())
{
let first = parameters.nodes[node_index].first_or_left;
for (uint32_t i = first; i < first + parameters.nodes[node_index].count; i++)
// We are on a leaf
uint32_t offset = parameters.nodes[c.current_node].first_or_left;
uint32_t count = parameters.nodes[c.current_node].count;
while (c.current_object < count)
{
if (this.objectHit(i, c.ray, cell))
if (objectHit(offset + c.current_object, c.ray, cell))
{
return true;
}
c.current_object += 1;
}
// Finisehd objects of this node
c.current_object = 0;
if (!this.pop(c.current_node, c))
{
return false;
}
}
}
return false;
return true;
}
bool objectHit(uint32_t object_index, Ray r, out Cell c)
@@ -170,122 +160,28 @@ public struct Bvh : IStructure
let direction = mul(parameters.objects[object_index].world_to_local, float4(r.direction, 0));
let origin = mul(parameters.objects[object_index].world_to_local, float4(r.origin, 1));
float2 inter = box_intersect(origin.xyz, direction.xyz, float3(0.), float3(1.));
return inter.x <= inter.y && inter.y >= 0.;
float2 intersection = box_intersect(origin.xyz, direction.xyz, float3(0.), float3(1.));
return intersection.y >= intersection.x && intersection.y >= 0.;
}
void push(uint32_t node, inout BvhCursor c)
{
stack[(c.stack_head & STACK_MASK) * 256 + this.thread_index] = node;
stack_depth[(c.stack_head & STACK_MASK) * 256 + this.thread_index] = c.depth;
stack[c.stack_head * 256 + this.thread_index] = node;
stack_depth[c.stack_head * 256 + this.thread_index] = c.depth;
c.stack_head += 1;
c.stack_count = max(c.stack_count + 1, STACK_SIZE);
c.stack_count += 1;
}
bool pop(out uint32_t node, inout BvhCursor c)
{
if (c.stack_count > 0)
if (c.stack_count == 0)
{
c.stack_head -= 1;
c.stack_count -= 1;
node = stack[(c.stack_head & STACK_MASK) * 256 + this.thread_index];
c.depth = stack_depth[(c.stack_head & STACK_MASK) * 256 + this.thread_index];
// This node is done, mark it ok, remove bits of deeper levels, they're done
c.bit_stack = (c.bit_stack | 1 << c.depth) & ((2 << c.depth) - 1);
return true;
}
return false;
// Stack is underflowed, we need to restart
uint64_t above = (~c.bit_stack) & ((1 << c.depth) - 1);
if (above == 0)
{
// Then all upper levels are one, meaning they've been popped once
// Meaning we were in a far->far->far... ->far path.
// so we have explored everything
return false;
}
// Select the depth at which we want to go back down, which is the first 0
// bit
uint32_t return_depth = firstbithigh(above);
// Since we visited that level, we mark it visited
c.bit_stack = (c.bit_stack | 1 << return_depth) & ((2 << return_depth) - 1);
// Reset stack
c.stack_head = 0;
c.stack_count = 0;
// Travel back down to level using the bit stack
node = 0;
for (uint32_t l = 0; l < return_depth; l++)
{
bool go_far = ((c.bit_stack >> l) & 1) == 1;
uint32_t left = parameters.nodes[node].first_or_left;
float2 inter1 = box_intersect(c.ray.origin, c.ray.direction, parameters.nodes[left].aabb.min(), parameters.nodes[left].aabb.max());
float2 inter2 = box_intersect(c.ray.origin, c.ray.direction, parameters.nodes[left + 1].aabb.min(), parameters.nodes[left + 1].aabb.max());
bool hit1 = inter1.x <= inter1.y && inter1.y >= 0;
bool hit2 = inter2.x <= inter2.y && inter2.y >= 0;
if (hit1 && hit2)
{
let near = select(inter1.x < inter2.x, left, left + 1);
let far = select(inter1.x < inter2.x, left + 1, left);
node = select(go_far, far, near);
if (!go_far)
{
this.push(far, c);
}
}
else if (hit1 || hit2)
{
// At this level, we must have chosen the one that hit
node = select(hit1, left, left + 1);
}
}
// Hit the far node
{
uint32_t left = parameters.nodes[node].first_or_left;
float2 inter1 = box_intersect(c.ray.origin, c.ray.direction, parameters.nodes[left].aabb.min(), parameters.nodes[left].aabb.max());
float2 inter2 = box_intersect(c.ray.origin, c.ray.direction, parameters.nodes[left + 1].aabb.min(), parameters.nodes[left + 1].aabb.max());
bool hit1 = inter1.x <= inter1.y && inter1.y >= 0;
bool hit2 = inter2.x <= inter2.y && inter2.y >= 0;
if (hit1 && hit2)
{
node = select(inter1.x < inter2.x, left + 1, left);
}
else if (hit1 || hit2)
{
// At this level, we must have chosen the one that hit
node = select(hit1, left, left + 1);
}
else
{
// Not hit, we can pop
if (c.stack_count == 0)
{
return false;
}
else
{
c.stack_head -= 1;
c.stack_count -= 1;
node = stack[(c.stack_head & STACK_MASK) * 256 + this.thread_index];
c.depth = stack_depth[(c.stack_head & STACK_MASK) * 256 + this.thread_index];
// This node is done, mark it ok, remove bits of deeper levels, they're done
c.bit_stack = (c.bit_stack | 1 << c.depth) & ((2 << c.depth) - 1);
}
}
}
c.stack_head -= 1;
c.stack_count -= 1;
node = stack[c.stack_head * 256 + this.thread_index];
c.depth = stack_depth[c.stack_head * 256 + this.thread_index];
return true;
}
}
@@ -300,6 +196,7 @@ float2 box_intersect(float3 origin, float3 ray_direction, float3 box_min, float3
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);
}
Binary file not shown.
+1 -1
View File
@@ -146,7 +146,7 @@ void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_
Bvh bvh;
bvh.parameters = table_parameters;
bvh.thread_index = local_location.x;
bvh.thread_index = stack_index;
BvhCursor c = bvh.begin(r);
Cell cell;
+1
View File
@@ -63,6 +63,7 @@ impl From<BvhNode> for GpuBvhNode
aabb: value.aabb.into(),
count: value.count,
first_or_left: value.first_or_left,
_pad2: [0; 2],
}
}
}
+3 -2
View File
@@ -4,9 +4,10 @@ use glam::Mat4;
use wgpu::BlendState;
// debug.wgsl mirrors the GPU structs manually. Keep the array strides in sync:
// WGSL would otherwise round them up to 16-byte alignment.
// WGSL rounds structs containing vec3 up to a 16-byte alignment, so a node's
// 40 bytes of data become a 48-byte array stride.
const _: () = {
assert!(size_of::<crate::bvh::gpu::GpuBvhNode>() == 40);
assert!(size_of::<crate::bvh::gpu::GpuBvhNode>() == 48);
assert!(size_of::<crate::bvh::gpu::GpuObject>() == 144);
};
+8 -12
View File
@@ -5,19 +5,15 @@
struct GpuBvhNode
{
// Kept as scalar fields on purpose. WGSL rounds structs containing vec3/vec4
// up to a 16-byte alignment (48-byte array stride), while the Rust side is
// a 40-byte `#[repr(C)]` struct.
min_x: f32,
min_y: f32,
min_z: f32,
_pad0: f32,
max_x: f32,
max_y: f32,
max_z: f32,
// vec3 members align to 16 bytes, so this struct has a 48-byte array
// stride. The Rust `GpuBvhNode` is padded to the same size.
min: vec3<f32>,
_pad0: u32,
max: vec3<f32>,
_pad1: u32,
count: u32,
first_or_left: u32,
_pad2: vec2<u32>,
};
struct GpuObject
@@ -111,8 +107,8 @@ fn vs_lines(
}
let node = nodes[instance_index];
let min_corner = vec3<f32>(node.min_x, node.min_y, node.min_z);
let max_corner = vec3<f32>(node.max_x, node.max_y, node.max_z);
let min_corner = node.min;
let max_corner = node.max;
let world_position = corner_position(
min_corner,
max_corner,
+5
View File
@@ -16,6 +16,10 @@ pub struct GpuAabb
}
/// Follow the same documentation as [`BvhNode`]
///
/// The trailing padding keeps the array stride at 48 bytes. On the GPU a struct
/// containing `vec3` has a 16-byte alignment, so the shader rounds the 40 bytes
/// of data up to a 48-byte stride.
#[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
#[repr(C)]
pub struct GpuBvhNode
@@ -23,6 +27,7 @@ pub struct GpuBvhNode
pub aabb: GpuAabb,
pub count: u32,
pub first_or_left: u32,
pub(crate) _pad2: [u32; 2],
}
/// To be a leaf of a GPU BVH
+9 -13
View File
@@ -1192,14 +1192,7 @@ impl State
encoder.write_timestamp(&timestamp_query, 0);
{
gpu_profiler::begin_scope!(encoder, "Compute render pass");
let mut renderpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("compute_render_pass"),
timestamp_writes: Some(wgpu::ComputePassTimestampWrites {
query_set: &timestamp_query,
beginning_of_pass_write_index: Some(2),
end_of_pass_write_index: Some(3),
}),
});
let mut renderpass = encoder.begin_profiled_compute_pass("compute_render_pass");
renderpass.set_pipeline(&self.pipeline);
renderpass.set_bind_group(0, self.voxel_cache.lock().raytrace_bind_group(), &[]);
@@ -1229,11 +1222,14 @@ impl State
table_base_slot,
}];
renderpass.set_immediates(0, unsafe { as_raw_bytes(&imm) });
renderpass.dispatch_workgroups(
self.size.width.div_ceil(16),
self.size.height.div_ceil(16),
1,
);
{
gpu_profiler::begin_scope!(renderpass, "RT");
renderpass.dispatch_workgroups(
self.size.width.div_ceil(16),
self.size.height.div_ceil(16),
1,
);
}
renderpass.set_pipeline(&self.gi_pipeline);
renderpass.set_immediates(0, unsafe { as_raw_bytes(&imm) });
renderpass.set_bind_group(2, Some(&gi_surface_bg), &[]);