From dd32c772e56ac9782924291a576df132d4baf255 Mon Sep 17 00:00:00 2001 From: Albin Chaboissier Date: Sun, 15 Nov 2026 12:00:08 +0100 Subject: [PATCH] feat: Good bvh traversal --- shaders/bvh.slang | 360 ++++++++++++++++++++++++++---------- shaders/gi.slang | 4 + shaders/out/voxel.spv | Bin 9204 -> 22876 bytes shaders/voxel.slang | 103 +++++------ shaders/voxel_cache.slang | 3 + shaders/voxel_tracing.slang | 61 +++++- src/bvh.rs | 68 +++++++ src/main.rs | 200 +++++++++++--------- 8 files changed, 552 insertions(+), 247 deletions(-) diff --git a/shaders/bvh.slang b/shaders/bvh.slang index 831681a..a76ab0f 100644 --- a/shaders/bvh.slang +++ b/shaders/bvh.slang @@ -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> 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); } diff --git a/shaders/gi.slang b/shaders/gi.slang index d9d881a..658670c 100644 --- a/shaders/gi.slang +++ b/shaders/gi.slang @@ -75,6 +75,10 @@ void gi(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_Gr let pos = gbuffer_position.Load(location.xy); let normal = gbuffer_normal.Load(location.xy); let albedo = gbuffer_albedo.Load(location.xy); + + // let floored_pos = floor(pos); + // let c = (floored_pos.x + floored_pos.y + floored_pos.z) % 2; + // target_texture.Store(location.xy, albedo * select(c == 0, 0.5, 1.)); target_texture.Store(location.xy, albedo); return; } diff --git a/shaders/out/voxel.spv b/shaders/out/voxel.spv index 26de80264930557e09c14cca5c478d842d37c929..e4f42e59411b4e1cfb5069296a41b4ef604f86b7 100644 GIT binary patch literal 22876 zcmai+2bh)B)wTzQ4hkrCMHCx~y;r~nDhh(J$8i`&KnDhA27452F^N&rj7dz?^u!bs zO>f5Z-h1yonqrGd`0o2X`x!Qq-|K%rR@Pe2diL6Dmv`@T4*0bXpFX;6aSPiKF>ZO6BbYO~GU z`HSc8(?76upMwtGPkht1R&rw#+s3qwL=Q)nt>{?U+1Irkvtf)tPi)(&iOcEhys|~; z=;~d$dd)z0;f+F%M#dmxk#UGMPe3+7Hbo{PlaR@Xc{gkPQBA*M#uRIsMBVl`6mO?0 z^U4`XZ=0hRuIXQXT<@y>fzDL}{Y=5qgAQ!QIEoy`eJ)$keR;>~zTS(m%`9$?uFjPm zt9$#wMmLyqa8Y09%I=PV6)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t?=U*S_d$zq`;K_S=~4$YRzew>B|#dGvQJ zHtVrI^XhB9b#RCI^f?t0GhW$qwG#Vj$dlkb=*kx$uY#QKbh!S;h5zZ9zq0>, PixelFootprintLod> tracer; + tracer.structure = bvh; + tracer.cache = cache_tracer; + tracer.lod = lod; + + Hit h; + // Closest hit at or past tMin. Re-trace past a hit with: + // t_min = h.t + 1e-4; + // hit = tracer.trace(stack_index, t_min, h, r); + bool hit = tracer.trace(stack_index, 0., h, r); + + // ToroidalStructureTableTracer.Cursor cursor = table_tracer.begin(r); + // Cell cell; + + if (hit) { - gbuffer_albedo.Store(location.xy, float4(0., 1., 0., 1.)); - return; + // Gather + let hit_pos = h.hit_location; + + let hit_normal = fetch_normal(h.node_index, h.child_index); + var hit_albedo = float4(0.); + hit_albedo = fetch_color(h.node_index, h.child_index).float_color; + // let hit_albedo = hit.color; + + gbuffer_position.Store(location.xy, float4(hit_pos, 1.)); + gbuffer_normal.Store(location.xy, float4(hit_normal, 1.)); + gbuffer_albedo.Store(location.xy, hit_albedo); + } + else + { + gbuffer_albedo.Store(location.xy, float4(0.)); } - //} - gbuffer_albedo.Store(location.xy, float4(0.)); - - /* - ToroidalStructureTableTracer table_tracer; - table_tracer.structure_table = table_parameters; - table_tracer.extent = - uint32_t3(constants.chunk_width, constants.chunk_alt, constants.chunk_height); - table_tracer.base_slot = uint32_t3( - constants.table_base_slot_x, - constants.table_base_slot_y, - constants.table_base_slot_z); - - - - PixelFootprintLod lod = PixelFootprintLod.create((100.f * 3.14f) / 180.f, 1080.f, 2.f); - - Tracer>, PixelFootprintLod> tracer; - tracer.structure = table_tracer; - tracer.cache = cache_tracer; - tracer.lod = lod; - - Hit h; - bool hit = tracer.trace(stack_index, h, r); - - ToroidalStructureTableTracer.Cursor cursor = table_tracer.begin(r); - Cell cell; - - if (hit) - { - // Gather - let hit_pos = h.hit_location; - - let hit_normal = fetch_normal(h.node_index, h.child_index); - var hit_albedo = float4(0.); - hit_albedo = fetch_color(h.node_index, h.child_index).float_color; - // let hit_albedo = hit.color; - - gbuffer_position.Store(location.xy, float4(hit_pos, 1.)); - gbuffer_normal.Store(location.xy, float4(hit_normal, 1.)); - gbuffer_albedo.Store(location.xy, hit_albedo); - } - else - { - gbuffer_albedo.Store(location.xy, float4(0.)); - } - */ } float2 box_intersect(float3 origin, float3 ray_direction, float3 box_min, float3 box_max) diff --git a/shaders/voxel_cache.slang b/shaders/voxel_cache.slang index efc2769..cc269ab 100644 --- a/shaders/voxel_cache.slang +++ b/shaders/voxel_cache.slang @@ -142,6 +142,8 @@ public struct VoxelCacheTracer> : IVoxelCache public bool trace(uint32_t root, uint32_t thread_id, Ray r, L lod, float offset_t, out Hit v) { + v.t = 0.; + // Ray mirroring r.origin += float3(1.); r.origin = clamp(r.origin, float(1.), asfloat(0x3fffffff)); @@ -216,6 +218,7 @@ public struct VoxelCacheTracer> : IVoxelCache asfloat(asuint(pos) ^ 0x007fffff), pos) - float3(1.); + v.t = offset_t + t; return true; } diff --git a/shaders/voxel_tracing.slang b/shaders/voxel_tracing.slang index 58d3aa6..9387632 100644 --- a/shaders/voxel_tracing.slang +++ b/shaders/voxel_tracing.slang @@ -44,6 +44,10 @@ public struct Hit public uint32_t node_index; public uint32_t child_index; public float3 hit_location; + + /// Distance of the hit from the ray origin, in the units of the ray + /// direction. Used to order hits and to restart the traversal past a hit. + public float t; } public interface IVoxelCache @@ -60,23 +64,66 @@ public struct Tracer public C cache; public L lod; - public bool trace(uint32_t thread_id, out Hit h, Ray r) + /// Traces the closest hit at or past `t_min`. + /// + /// The structure may return cells in any order (the BVH restart trail is + /// not distance ordered). Instead of returning on the first cache hit, we + /// keep the closest hit found so far and skip cells that start beyond it: + /// every hit inside a cell is at least `cell.t` away, so a cell with + /// `entry >= best_t` cannot improve the result. + public bool trace(uint32_t thread_id, float t_min, out Hit h, Ray r) { - /* loop: next cell -> cache.trace -> early out */ - S.Cursor cursor = this.structure.begin(r); - Cell cell; - h.hit = false; h.hit_location = float3(0.f); h.child_index = 0; h.node_index = 0; + h.t = 0.f; + // Start just past the previous hit. + Ray adjusted = r; + adjusted.origin += r.direction * t_min; + + float best_t = asfloat(0x7f7fffff); // FLT_MAX + Hit best_hit = h; + bool found = false; + + S.Cursor cursor = this.structure.begin(adjusted); + Cell cell; + + [loop] while (this.structure.next(cursor, cell)) { - if (cache.trace(cell.cache_pointer, thread_id, cell.local_ray, lod, cell.t, h)) + // `cell.t` is relative to the advanced origin, `best_t` is not. + float cell_t = t_min + cell.t; + + // No hit inside this cell can be closer than the current best. + if (cell_t >= best_t) { - return true; + continue; } + + Hit candidate = h; + if (cache.trace( + cell.cache_pointer, + thread_id, + cell.local_ray, + lod, + cell_t, + candidate)) + { + if (candidate.t < best_t) + { + best_t = candidate.t; + best_hit = candidate; + found = true; + } + } + } + + if (found) + { + h = best_hit; + return true; } return false; diff --git a/src/bvh.rs b/src/bvh.rs index 0a171d3..60fb681 100644 --- a/src/bvh.rs +++ b/src/bvh.rs @@ -12,8 +12,13 @@ use crate::bvh::build::BvhPrimitive; use crate::bvh::build::build_bvh; use crate::bvh::gpu::GpuBvhNode; use crate::bvh::gpu::GpuObject; +use crate::gpu_profiler::ScopeEncoder; use crate::production::ProducerId; use crate::production::StructureAnchor; +use crate::voxel_cache::CacheInvalidable; +use crate::voxel_cache::eviction::CacheEvictor; +use crate::voxel_cache::insertion::CacheInsertionData; +use crate::voxel_cache::requests::CacheRequestBuffer; use crate::voxel_cache::tables::DynamicStructureTable; pub mod aabb; @@ -305,6 +310,69 @@ impl BvhStructureTable { &self.raytrace_bind_group } + + /// Gathers the root requests emitted by the inner structure table into + /// `request_buffer`. + pub fn gather_requests( + &self, + device: &wgpu::Device, + encoder: &mut ScopeEncoder, + request_buffer: &CacheRequestBuffer, + ) + { + self.structure_table + .gather_requests(device, encoder, request_buffer); + } + + /// Writes the cache page pointers produced by an external insertion into + /// the inner structure table. + pub fn insert( + &self, + device: &wgpu::Device, + encoder: &mut ScopeEncoder, + insertion: &CacheInsertionData, + ) where + [(); N * N * N]:, + { + self.structure_table.insert(device, encoder, insertion); + } + + pub fn get(&self, handle: &BvhHandle) -> Option<&BvhObject> + { + self.objects.get(handle) + } + + pub fn get_mut(&mut self, handle: &BvhHandle) -> Option<&mut BvhObject> + { + self.objects.get_mut(handle) + } +} + +impl CacheInvalidable for BvhStructureTable +where + [(); N * N * N]:, +{ + fn validate_insertion( + &mut self, + device: &wgpu::Device, + encoder: &mut ScopeEncoder, + insertion: &CacheInsertionData, + ) + { + self.structure_table + .validate_insertion(device, encoder, insertion); + } + + fn invalidate( + &mut self, + encoder: &mut ScopeEncoder, + cache_evictor: &CacheEvictor, + invalid_timestamp: u32, + ) + { + self.structure_table + .invalidate(encoder, cache_evictor, invalid_timestamp); + } } fn create_bvh_buffer(device: &wgpu::Device, capacity: usize, label: &str) -> wgpu::Buffer diff --git a/src/main.rs b/src/main.rs index bb264a5..afe190b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -54,9 +54,11 @@ use winit::event_loop::OwnedDisplayHandle; use winit::window::Window; use winit::window::WindowId; +use crate::bvh::BvhHandle; use crate::bvh::BvhObject; use crate::bvh::BvhStructureTable; use crate::bvh::aabb::Aabb; +use crate::bvh::build::Bvh; use crate::bvh::debug::BvhDebugPipeline; use crate::camera::Camera; use crate::egui_renderer::EguiRenderer; @@ -148,8 +150,9 @@ struct State request_buffer: Arc, cache_insertion: Arc>, + structure_table: Arc>, //structure_table: Arc>, - structure_table: Arc>, + //structure_table: Arc>, structure_table_request_buffer: Arc, structure_table_cache_insertion: Arc>, usage_vec: Arc>>, @@ -170,8 +173,8 @@ struct State // Producers workers wakeup: Sender<()>, - bvh: BvhStructureTable, bvh_debug: BvhDebugPipeline, + bvh_objs: Vec<(BvhHandle, Vec3)>, } pub unsafe fn as_raw_bytes(slice: &[T]) -> &[u8] @@ -445,19 +448,74 @@ impl State let total_chunk_count = terrain_height * terrain_width * terrain_alt; let structure_table_request_buffer = CacheRequestBuffer::new(&device, 128); + + let mut bvh = BvhStructureTable::new(&device, 128, 128); + let extent = Aabb::new(-10. * Vec3::ONE, 10. * Vec3::ONE); + let mut bvh_objs = Vec::new(); + for _ in 0..1000 + { + let transform = Mat4::from_rotation_translation( + Quat::from_euler( + glam::EulerRot::XYZ, + random_range(-3.1..3.1), + random_range(-3.1..3.1), + random_range(-3.1..3.1), + ), + Vec3::new( + random_range(extent.min().x..extent.max().x), + random_range(extent.min().y..extent.max().y), + random_range(extent.min().z..extent.max().z), + ), + ); + + let handle = bvh.add( + &device, + &queue, + BvhObject { + anchor: StructureAnchor::zeroed(), + producer_id: ProducerId(0), + transform, + bounding_box: Aabb::CHUNK, + }, + ); + + bvh_objs.push(( + handle, + Vec3::new( + random_range(-1.0..1.0), + random_range(-1.0..1.0), + random_range(-1.0..1.0), + ) + .normalize(), + )); + } + + let now = Instant::now(); + bvh.rebuild(&device, &queue); + let time = Instant::now() - now; + + println!("Bvh build time : {}ms", time.as_millis()); + + let bvh_debug = BvhDebugPipeline::new( + &device, + surface_format.add_srgb_suffix(), + wgpu::TextureFormat::Depth24PlusStencil8, + ); + // let structure_table = FixedStructureTable::new( // &device, // total_chunk_count, // structure_table_request_buffer.max_requests, // 0, // ); - let structure_table = ToroidalStructureTable::new( - &device, - (terrain_width, terrain_alt, terrain_height), - Vec3::ZERO, - structure_table_request_buffer.max_requests, - 0, - ); + // let structure_table = ToroidalStructureTable::new( + // &device, + // (terrain_width, terrain_alt, terrain_height), + // Vec3::ZERO, + // structure_table_request_buffer.max_requests, + // 0, + // ); + let structure_table = bvh; let structure_table_insertion_data = CacheInsertionData::new(&device, 128, &layout); let chunk_instances = (0..terrain_alt) .cartesian_product(0..terrain_height) @@ -523,48 +581,6 @@ impl State // ) // }; - let mut bvh = BvhStructureTable::new(&device, 128, 128); - let extent = Aabb::new(-10. * Vec3::ONE, 10. * Vec3::ONE); - for _ in 0..100 - { - let transform = Mat4::from_rotation_translation( - Quat::from_euler( - glam::EulerRot::XYZ, - random_range(-3.1..3.1), - random_range(-3.1..3.1), - random_range(-3.1..3.1), - ), - Vec3::new( - random_range(extent.min().x..extent.max().x), - random_range(extent.min().y..extent.max().y), - random_range(extent.min().z..extent.max().z), - ), - ); - - bvh.add( - &device, - &queue, - BvhObject { - anchor: StructureAnchor::zeroed(), - producer_id: ProducerId(0), - transform, - bounding_box: Aabb::CHUNK, - }, - ); - } - - let now = Instant::now(); - bvh.rebuild(&device, &queue); - let time = Instant::now() - now; - - println!("Bvh build time : {}ms", time.as_millis()); - - let bvh_debug = BvhDebugPipeline::new( - &device, - surface_format.add_srgb_suffix(), - wgpu::TextureFormat::Depth24PlusStencil8, - ); - let shader_module = unsafe { device.create_shader_module_passthrough({ wgpu::ShaderModuleDescriptorPassthrough { @@ -706,8 +722,7 @@ impl State bind_group_layouts: &[ Some(voxel_cache.raytrace_bind_group_layout()), - //Some(structure_table.raytrace_bind_group_layout()), - Some(bvh.raytrace_bind_group_layout()), + Some(structure_table.raytrace_bind_group_layout()), Some(&ray_march_bind_group_layout), ], immediate_size: size_of::() as u32, @@ -867,8 +882,8 @@ impl State insert_profile: Arc::new(Mutex::new(Profile::default())), cursor_grabed: true, wakeup: wakeup_tx, - bvh, bvh_debug, + bvh_objs, }; // Configure surface for the first time @@ -1070,6 +1085,28 @@ impl State { self.camera.update(); + let mut locked_table = self.structure_table.lock(); + for (hndl, dir) in self.bvh_objs.iter_mut() + { + let obj = locked_table.get_mut(hndl); + if let Some(obj) = obj + { + let (scale, mut rot, mut trans) = obj.transform.to_scale_rotation_translation(); + let speed = 0.01; + rot = rot.mul_quat(Quat::from_axis_angle(*dir, speed)); + trans += *dir * speed; + *dir += Vec3::new( + random_range(-speed..speed), + random_range(-speed..speed), + random_range(-speed..speed), + ); + obj.transform = Mat4::from_scale_rotation_translation(scale, rot, trans); + } + } + locked_table.mark_dirty(); + locked_table.rebuild_if_dirty(&self.device, &self.queue); + drop(locked_table); + // Create texture view. // NOTE: We must handle Timeout because the surface may be unavailable // (e.g., when the window is occluded on macOS). @@ -1170,22 +1207,6 @@ impl State let mut command_encoder = self.device.create_command_encoder(&Default::default()); let mut prof_command_encoder = ProfilingEncoder::new(&self.device, &mut command_encoder); - { - let retired = self.structure_table.lock().move_position( - &self.queue, - &mut prof_command_encoder, - self.camera.position, - ); - - // Cancellation is only an optimisation: stale insertions are - // rejected by the GPU because they no longer match the slot. - let mut request_queue = self.request_queue.lock(); - for anchor in retired - { - request_queue.invalidate_anchor(anchor); - } - } - { let mut encoder = prof_command_encoder.begin_frame(Some("Main frame")); @@ -1196,14 +1217,13 @@ impl State renderpass.set_pipeline(&self.pipeline); renderpass.set_bind_group(0, self.voxel_cache.lock().raytrace_bind_group(), &[]); - renderpass.set_bind_group(1, self.bvh.raytrace_bind_group(), &[]); - // renderpass.set_bind_group( - // 1, - // self.structure_table.lock().raytrace_bind_group(), - // &[], - // ); + renderpass.set_bind_group( + 1, + self.structure_table.lock().raytrace_bind_group(), + &[], + ); renderpass.set_bind_group(2, Some(&surface_bg), &[]); - let table_base_slot = self.structure_table.lock().base_slot(); + let table_base_slot = [0; 3]; let imm = [Immediates { view_proj: self.camera.view_proj().inverse(), cam_pos: self.camera.position, @@ -1257,18 +1277,20 @@ impl State self.target_blitter .copy(&self.device, &mut encoder, target_view, &texture_view); - self.bvh_debug.render( - &self.device, - &self.queue, - &mut encoder, - &texture_view, - &self.depth_buffer.1, - self.camera.view_proj(), - self.bvh.bvh_nodes(), - self.bvh.bvh_objects(), - self.bvh.node_count(), - 2, - ); + let structure_table = self.structure_table.lock(); + // self.bvh_debug.render( + // &self.device, + // &self.queue, + // &mut encoder, + // &texture_view, + // &self.depth_buffer.1, + // self.camera.view_proj(), + // structure_table.bvh_nodes(), + // structure_table.bvh_objects(), + // structure_table.node_count(), + // 2, + // ); + drop(structure_table); // ~~ EGUI Render pass ~~ {