feat: Good bvh traversal

This commit is contained in:
2026-11-15 12:00:08 +01:00
parent 4581538c66
commit dd32c772e5
8 changed files with 552 additions and 247 deletions
+262 -98
View File
@@ -37,21 +37,38 @@ public struct BvhObject
uint32_t _pad2;
}
/// Traversal state for a single ray.
///
/// The BVH is traversed with a restart trail instead of a stack: one bit per
/// tree level records what has already been processed, and every restart
/// re-walks from the root steered by that trail. [`BvhCursor::trail`] is the
/// only traversal state that survives between calls to [`Bvh::next`].
///
/// Trail invariant: bits `0 .. leaf_depth-1` encode the path to the current
/// leaf (`0` = near child, `1` = far child); all deeper bits are clear.
/// A 64 bit trail supports trees up to 64 levels deep.
public struct BvhCursor
{
Ray ray;
// One bit per level, bit 0 means left child unexplored, bit one, child explored
uint64_t bit_stack;
public Ray ray;
// Where to write the node when descending
uint32_t stack_head;
uint32_t stack_count;
/// Reciprocal of [`Ray::direction`]; computed once per ray and reused for
/// every node test.
public float3 inv_direction;
uint32_t current_object;
uint32_t current_node;
/// Restart trail, see the struct documentation.
public uint64_t trail;
uint32_t depth;
float t;
/// Objects of the leaf currently being drained.
public uint32_t leaf_first;
public uint32_t leaf_count;
public uint32_t leaf_next;
public uint32_t leaf_depth;
/// True while [`Self::leaf_next`] still points into a valid leaf.
public bool have_leaf;
/// Set once the whole tree has been processed.
public bool done;
}
public struct BvhParameters
@@ -62,141 +79,288 @@ public struct BvhParameters
RWStructuredBuffer<Atomic<uint32_t>> requests;
}
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];
public struct Bvh : IStructure
{
typedef BvhCursor Cursor;
public BvhParameters parameters;
public uint32_t thread_index;
/// Kept for compatibility with the existing call sites. The restart
/// traversal does not need per-thread storage, so this is unused.
public uint32_t thread_index;
public BvhCursor begin(Ray world_ray)
{
BvhCursor c;
c.ray = world_ray;
c.bit_stack = 0;
c.stack_head = 0;
c.stack_count = 0;
c.current_object = 0;
c.current_node = 0;
c.depth = 0;
c.inv_direction = safe_reciprocal(world_ray.direction);
c.trail = uint64_t(0);
c.leaf_first = 0;
c.leaf_count = 0;
c.leaf_next = 0;
c.leaf_depth = 0;
c.have_leaf = false;
// Early out when the ray misses the whole scene.
let root = this.parameters.nodes[0];
let root_t = intersect_aabb(
world_ray.origin,
c.inv_direction,
root.aabb.min,
root.aabb.max);
c.done = !(root_t.y >= max(root_t.x, 0.));
this.push(0, c);
return c;
}
public bool next(inout BvhCursor c, out Cell cell)
{
uint32_t outer_bound = 0;
while (outer_bound < 300)
// The out parameter is only meaningful on a `true` return, but
// initialising it keeps the compiler's definite-assignment analysis
// happy on all early-outs.
cell.cache_pointer = 0;
cell.local_ray.origin = float3(0.);
cell.local_ray.direction = float3(0.);
cell.t = 0.;
if (c.done)
{
outer_bound++;
return false;
}
uint32_t inner_bound = 0;
if (parameters.nodes[c.current_node].is_internal() && inner_bound < 300)
[loop]
for (;;)
{
// 1. Drain the objects of the leaf we are currently in.
[loop]
while (c.leaf_next < c.leaf_count)
{
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);
let object_index = c.leaf_first + c.leaf_next;
c.leaf_next += 1;
bool left_hit = left.y >= left.x && left.y >= 0.;
bool right_hit = right.y >= right.x && right.y >= 0.;
if (left_hit && right_hit)
Cell candidate;
if (this.object_hit(object_index, c.ray, candidate))
{
// 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;
}
else if (left_hit || right_hit)
{
c.current_node = select(left_hit, left_index, left_index + 1);
c.bit_stack |= 1 << c.depth;
c.depth += 1;
}
else
{
if (!this.pop(c.current_node, c))
{
return false;
}
cell = candidate;
return true;
}
}
if (parameters.nodes[c.current_node].is_leaf())
// 2. The leaf is exhausted: advance the trail past it.
if (c.have_leaf)
{
// 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)
c.have_leaf = false;
if (!advance_trail(c, c.leaf_depth))
{
if (objectHit(offset + c.current_object, c.ray, cell))
{
return true;
}
c.current_object += 1;
c.done = true;
return false;
}
}
// 3. Restart: descend from the root, steered by the trail.
uint32_t node = 0;
uint32_t level = 0;
bool dead = false;
[loop]
for (;;)
{
let n = this.parameters.nodes[node];
if (n.is_leaf())
{
c.leaf_first = n.first_or_left;
c.leaf_count = n.count;
c.leaf_next = 0;
c.leaf_depth = level;
c.have_leaf = true;
break;
}
// Finisehd objects of this node
c.current_object = 0;
if (!this.pop(c.current_node, c))
let left = n.first_or_left;
let right = left + 1;
let t_left = intersect_aabb(
c.ray.origin,
c.inv_direction,
this.parameters.nodes[left].aabb.min,
this.parameters.nodes[left].aabb.max);
let t_right = intersect_aabb(
c.ray.origin,
c.inv_direction,
this.parameters.nodes[right].aabb.min,
this.parameters.nodes[right].aabb.max);
let hit_left = t_left.y >= max(t_left.x, 0.);
let hit_right = t_right.y >= max(t_right.x, 0.);
if (hit_left && hit_right)
{
// Trail bit 0 means "near child first", 1 means "far".
// The near/far decision is deterministic for a fixed ray,
// so it stays consistent across restarts.
let left_is_near = t_left.x <= t_right.x;
let go_far = ((c.trail >> level) & uint64_t(1)) != uint64_t(0);
if (left_is_near)
{
node = go_far ? right : left;
}
else
{
node = go_far ? left : right;
}
level += 1;
}
else if (hit_left)
{
// The far child has no work; mark this level processed so
// a later restart does not try to enter it.
c.trail |= (uint64_t(1) << level);
node = left;
level += 1;
}
else if (hit_right)
{
c.trail |= (uint64_t(1) << level);
node = right;
level += 1;
}
else
{
dead = true;
break;
}
if (level >= 64)
{
// The trail cannot represent anything deeper.
c.done = true;
return false;
}
}
if (dead)
{
// No child of this node is hit: move on to the next
// unprocessed part of the tree.
if (!advance_trail(c, level))
{
c.done = true;
return false;
}
}
}
return true;
}
bool objectHit(uint32_t object_index, Ray r, out Cell c)
/// Tests a leaf object and, if it can be traced, fills its cache cell.
bool object_hit(uint32_t object_index, Ray world_ray, out Cell cell)
{
// Project direction and view in local space
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));
cell.cache_pointer = 0;
cell.local_ray.origin = float3(0.);
cell.local_ray.direction = float3(0.);
cell.t = 0.;
float2 intersection = box_intersect(origin.xyz, direction.xyz, float3(0.), float3(1.));
return intersection.y >= intersection.x && intersection.y >= 0.;
}
let object = this.parameters.objects[object_index];
void push(uint32_t node, inout BvhCursor c)
{
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 += 1;
}
// Transform the ray to the object's local space, where the voxel
// chunk is the unit cube.
let local_origin = mul(object.world_to_local, float4(world_ray.origin, 1.)).xyz;
let local_direction = mul(object.world_to_local, float4(world_ray.direction, 0.)).xyz;
bool pop(out uint32_t node, inout BvhCursor c)
{
if (c.stack_count == 0)
let t = intersect_aabb(
local_origin,
safe_reciprocal(local_direction),
float3(0.),
float3(1.));
if (t.y < max(t.x, 0.))
{
return false;
}
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;
let pointer = this.parameters.slots[object.table_slot];
if (pointer.subdivided_valid())
{
let entry_t = max(t.x, 0.);
cell.cache_pointer = pointer.pointer();
cell.local_ray.origin = local_origin + local_direction * entry_t;
cell.local_ray.direction = local_direction;
cell.t = entry_t;
return true;
}
if (pointer.subdivided())
{
// The root of this object is requested but not available yet.
this.parameters.requests[object.table_slot].add(1);
}
return false;
}
}
float2 box_intersect(float3 origin, float3 ray_direction, float3 box_min, float3 box_max)
/// Moves the trail to the next unprocessed part of the tree.
///
/// Finds the nearest ancestor with a pending far child, marks it processed
/// and clears the path below it. Returns false when the whole tree has been
/// visited.
bool advance_trail(inout BvhCursor c, uint32_t depth)
{
let min_ts = (box_min - origin) / ray_direction;
let max_ts = (box_max - origin) / ray_direction;
uint32_t level = depth;
uint64_t trail = (~c.trail) & ((1 << uint64_t(level)) - 1);
int32_t fbh = firstbithigh(trail);
if (trail == 0)
{
return false;
}
let far_ts = max(min_ts, max_ts);
let near_ts = min(min_ts, max_ts);
level = fbh;
c.trail |= (uint64_t(1) << level);
// Keep the path bits up to and including this level, drop the
// stale path below it.
c.trail &= (uint64_t(2) << level) - uint64_t(1);
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));
// [loop]
// while (level > 0)
// {
// level -= 1;
// if (((c.trail >> level) & uint64_t(1)) == uint64_t(0))
// {
// c.trail |= (uint64_t(1) << level);
// // Keep the path bits up to and including this level, drop the
// // stale path below it.
// c.trail &= (uint64_t(2) << level) - uint64_t(1);
// return true;
// }
// }
return float2(near_t, far_t);
return true;
}
/// Slab test against an axis aligned box, using a precomputed reciprocal.
///
/// Returns `(t_near, t_far)`. A hit is `t_far >= max(t_near, 0)`.
float2 intersect_aabb(float3 origin, float3 inv_direction, float3 box_min, float3 box_max)
{
let t0 = (box_min - origin) * inv_direction;
let t1 = (box_max - origin) * inv_direction;
let t_near = min(t0, t1);
let t_far = max(t0, t1);
return float2(
max(t_near.x, max(t_near.y, t_near.z)),
min(t_far.x, min(t_far.y, t_far.z)));
}
/// Reciprocal that avoids `0 * inf = NaN` for rays parallel to a slab.
///
/// A component that is (near) zero is replaced by a tiny positive value. The
/// slab test stays correct: the resulting huge `t` values either do not
/// constrain the interval or reject the box, depending on which side of the
/// slab the origin lies.
float3 safe_reciprocal(float3 direction)
{
let tiny = abs(direction) < float3(1e-8);
return 1. / select(tiny, float3(1e-8), direction);
}