StructureID separate from chunk 'anchor'
This commit is contained in:
+20
-25
@@ -1,7 +1,6 @@
|
||||
#![feature(generic_const_exprs)]
|
||||
#![feature(float_algebraic)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::marker::PhantomData;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
@@ -20,7 +19,6 @@ use glam::Mat4;
|
||||
use glam::Vec3;
|
||||
use glam::Vec4;
|
||||
use itertools::Itertools;
|
||||
use rayon::iter::IndexedParallelIterator;
|
||||
use rayon::iter::IntoParallelRefIterator;
|
||||
use rayon::iter::ParallelIterator;
|
||||
use wgpu::BindGroupLayout;
|
||||
@@ -48,20 +46,16 @@ use winit::event_loop::ActiveEventLoop;
|
||||
use winit::event_loop::ControlFlow;
|
||||
use winit::event_loop::EventLoop;
|
||||
use winit::event_loop::OwnedDisplayHandle;
|
||||
use winit::platform::x11::EventLoopBuilderExtX11;
|
||||
use winit::window::Window;
|
||||
use winit::window::WindowId;
|
||||
|
||||
use crate::camera::Camera;
|
||||
use crate::egui_renderer::EguiRenderer;
|
||||
use crate::gpu::radix_sort;
|
||||
use crate::gpu::radix_sort::RadixSorter;
|
||||
use crate::gpu_profiler::Frame;
|
||||
use crate::gpu_profiler::Profile;
|
||||
use crate::gpu_profiler::ProfilingEncoder;
|
||||
use crate::producers::ChunkedProducer;
|
||||
use crate::producers::SdfGenerator;
|
||||
use crate::producers::TerrainGenerator;
|
||||
use crate::production::request_queue::FrameId;
|
||||
use crate::production::request_queue::IncomingRequest;
|
||||
use crate::production::request_queue::QueueConfig;
|
||||
@@ -75,12 +69,7 @@ use crate::voxel_cache::VoxelCacheInsertion;
|
||||
use crate::voxel_cache::insertion::CacheInsertionData;
|
||||
use crate::voxel_cache::requests::CacheRequestBuffer;
|
||||
use crate::voxel_cache::schema::InsertionInformation;
|
||||
use crate::voxel_cache::schema::InsertionParent;
|
||||
use crate::voxel_cache::schema::LocationPage;
|
||||
use crate::voxel_cache::schema::NO_PARENT_PAGE;
|
||||
use crate::voxel_cache::schema::RequestInformation;
|
||||
use crate::voxel_cache::schema::RequestMeta;
|
||||
use crate::voxel_cache::tables::FixedStructureTable;
|
||||
|
||||
mod camera;
|
||||
mod egui_renderer;
|
||||
@@ -145,7 +134,6 @@ struct State
|
||||
structure_table: Arc<Mutex<ToroidalStructureTable>>,
|
||||
structure_table_request_buffer: Arc<CacheRequestBuffer>,
|
||||
structure_table_cache_insertion: Arc<CacheInsertionData<4>>,
|
||||
chunk_pos_map: Arc<HashMap<u32, (usize, usize, usize)>>,
|
||||
instance_buffer: Buffer,
|
||||
instance_count: usize,
|
||||
usage_vec: Arc<Mutex<Vec<usize>>>,
|
||||
@@ -214,6 +202,7 @@ impl State
|
||||
.request_adapter(&wgpu::RequestAdapterOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
println!("{:#?}", adapter.get_info());
|
||||
let (device, queue) = adapter
|
||||
.request_device(&wgpu::DeviceDescriptor {
|
||||
required_features: Features::IMMEDIATES
|
||||
@@ -419,7 +408,6 @@ impl State
|
||||
terrain_width * terrain_height * terrain_alt
|
||||
);
|
||||
|
||||
let mut chunk_pos_map = HashMap::new();
|
||||
let total_chunk_count = terrain_height * terrain_width * terrain_alt;
|
||||
|
||||
let structure_table_request_buffer = CacheRequestBuffer::new(&device, 128);
|
||||
@@ -443,7 +431,6 @@ impl State
|
||||
//dbg!(chunk_id);
|
||||
let chunk_id = y * terrain_width * terrain_height + z * terrain_width + x;
|
||||
|
||||
chunk_pos_map.insert(chunk_id as u32, (x, y, z));
|
||||
InstanceAttribute {
|
||||
x: x as f32,
|
||||
y: y as f32,
|
||||
@@ -720,7 +707,6 @@ impl State
|
||||
let d = fullfill_request(
|
||||
&terrain_generator,
|
||||
&work_item.key,
|
||||
&Default::default(),
|
||||
&structure_table_1,
|
||||
);
|
||||
(
|
||||
@@ -795,7 +781,6 @@ impl State
|
||||
camera: Default::default(),
|
||||
instance_buffer,
|
||||
instance_count,
|
||||
chunk_pos_map: chunk_pos_map.into(),
|
||||
rm_time: Arc::new(Mutex::new(0.)),
|
||||
frame_time: Arc::new(Mutex::new(0.)),
|
||||
terrain_width,
|
||||
@@ -1107,9 +1092,19 @@ impl State
|
||||
let mut prof_command_encoder = ProfilingEncoder::new(&self.device, &mut command_encoder);
|
||||
|
||||
{
|
||||
self.structure_table
|
||||
.lock()
|
||||
.move_position(&mut prof_command_encoder, self.camera.position);
|
||||
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 structure in retired
|
||||
{
|
||||
request_queue.invalidate_structure(structure);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
@@ -1369,7 +1364,6 @@ impl State
|
||||
self.insertion_debounce = true;
|
||||
let frame_id: FrameId = self.voxel_cache.lock().current_timestamp().into();
|
||||
let cloned_queue = self.queue.clone();
|
||||
let cloned_map = self.chunk_pos_map.clone();
|
||||
let finished = Arc::new(AtomicU32::new(0));
|
||||
|
||||
// Cache requests
|
||||
@@ -1474,7 +1468,6 @@ impl State
|
||||
);
|
||||
|
||||
let cloned_queue = self.queue.clone();
|
||||
let cloned_map = self.chunk_pos_map.clone();
|
||||
|
||||
// Structure table requests
|
||||
let cloned_st_insertion_data = self.structure_table_cache_insertion.clone();
|
||||
@@ -1752,7 +1745,6 @@ pub struct ChunkImmediate
|
||||
fn fullfill_request<const N: usize>(
|
||||
generator: &dyn ChunkedProducer<N>,
|
||||
request: &RequestKey,
|
||||
map: &HashMap<u32, (usize, usize, usize)>,
|
||||
table: &Arc<Mutex<ToroidalStructureTable>>,
|
||||
) -> (
|
||||
[u32; N * N * N],
|
||||
@@ -1763,9 +1755,10 @@ fn fullfill_request<const N: usize>(
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
{
|
||||
// Unpack structure id
|
||||
//let (chunk_x, chunk_y, chunk_z) = *map.get(&request.structure_id).unwrap();
|
||||
let (chunk_x, chunk_y, chunk_z) = table.lock().get_request_position(request.structure_id.0);
|
||||
// Unpack structure identity: the anchor is the table-defined content
|
||||
// identity, independent of the table slot that currently holds it.
|
||||
let anchor = request.anchor;
|
||||
let (chunk_x, chunk_y, chunk_z) = table.lock().position_for_anchor(anchor);
|
||||
|
||||
// let (chunk_x, chunk_y, chunk_z) = (
|
||||
// (u32::MAX as isize + chunk_x) as usize,
|
||||
@@ -1795,6 +1788,7 @@ where
|
||||
structure_id: request.structure_id.0,
|
||||
node_id: NTreeNodeLocator::<4>::root().as_usize() as u32,
|
||||
producer_id: request.producer_id.0,
|
||||
anchor,
|
||||
};
|
||||
}
|
||||
else
|
||||
@@ -1826,6 +1820,7 @@ where
|
||||
structure_id: request.structure_id.0,
|
||||
node_id: child_locator.as_usize() as u32,
|
||||
producer_id: request.producer_id.0,
|
||||
anchor,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+8
-1
@@ -3,6 +3,8 @@ use bytemuck::Zeroable;
|
||||
|
||||
use crate::voxel_cache::schema::InsertionInformation;
|
||||
|
||||
pub use crate::voxel_cache::schema::StructureAnchor;
|
||||
|
||||
/// A structure locator format to locate node within an ntree
|
||||
pub mod tree_locator;
|
||||
|
||||
@@ -53,11 +55,16 @@ where
|
||||
type Output: VoxelAttributes<N>;
|
||||
|
||||
/// A pure function that can produce a voxel node based on the owner produer id, requesting structure, and the
|
||||
/// requesting location within the structure
|
||||
/// requesting location within the structure.
|
||||
///
|
||||
/// `anchor` is the table-defined content identity of the structure. Producers
|
||||
/// must derive world position/content from it rather than from `id` or any
|
||||
/// table slot: slots are placement and may change while `id` stays stable.
|
||||
fn produce(
|
||||
&self,
|
||||
producer_id: ProducerId,
|
||||
id: StructureId,
|
||||
anchor: StructureAnchor,
|
||||
locator: StructureLocator,
|
||||
) -> (InsertionInformation<N>, [Self::Output; N * N * N]);
|
||||
}
|
||||
|
||||
@@ -58,6 +58,7 @@ where
|
||||
let (info, attributes) = self.producer.produce(
|
||||
super::ProducerId(0),
|
||||
super::StructureId(request.structure_id),
|
||||
request.anchor,
|
||||
super::StructureLocator(request.node_id),
|
||||
);
|
||||
|
||||
|
||||
+212
-19
@@ -7,8 +7,10 @@ use crate::production::StructureId;
|
||||
use crate::production::StructureLocator;
|
||||
use crate::voxel_cache::schema::InsertionParent;
|
||||
use crate::voxel_cache::schema::NO_PARENT_PAGE;
|
||||
use crate::voxel_cache::schema::NO_TABLE_SLOT;
|
||||
use crate::voxel_cache::schema::RequestInformation;
|
||||
use crate::voxel_cache::schema::RequestMeta;
|
||||
use crate::voxel_cache::schema::StructureAnchor;
|
||||
|
||||
/// Monotonic frame counter owned by the host. Using `u64` avoids concerns about
|
||||
/// the cache's `u32` timestamp wrapping.
|
||||
@@ -34,21 +36,31 @@ pub enum RequestTarget
|
||||
}
|
||||
|
||||
/// Unique identity of an outstanding request.
|
||||
///
|
||||
/// The structure-table slot is deliberately absent: it is placement metadata,
|
||||
/// not identity. Excluding it lets an in-flight root job survive a slot move
|
||||
/// while the same anchor stays in view.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
|
||||
pub struct RequestKey
|
||||
{
|
||||
pub producer_id: ProducerId,
|
||||
pub structure_id: StructureId,
|
||||
pub anchor: StructureAnchor,
|
||||
pub target: RequestTarget,
|
||||
}
|
||||
|
||||
impl RequestKey
|
||||
{
|
||||
pub fn root(producer_id: ProducerId, structure_id: StructureId) -> Self
|
||||
pub fn root(
|
||||
producer_id: ProducerId,
|
||||
structure_id: StructureId,
|
||||
anchor: StructureAnchor,
|
||||
) -> Self
|
||||
{
|
||||
Self {
|
||||
producer_id,
|
||||
structure_id,
|
||||
anchor,
|
||||
target: RequestTarget::Root,
|
||||
}
|
||||
}
|
||||
@@ -56,6 +68,7 @@ impl RequestKey
|
||||
pub fn child(
|
||||
producer_id: ProducerId,
|
||||
structure_id: StructureId,
|
||||
anchor: StructureAnchor,
|
||||
parent: StructureLocator,
|
||||
children_index: u32,
|
||||
) -> Self
|
||||
@@ -63,6 +76,7 @@ impl RequestKey
|
||||
Self {
|
||||
producer_id,
|
||||
structure_id,
|
||||
anchor,
|
||||
target: RequestTarget::Child {
|
||||
parent,
|
||||
children_index,
|
||||
@@ -144,6 +158,10 @@ pub struct IncomingRequest
|
||||
|
||||
/// Parent page information captured at the latest emission.
|
||||
pub meta: RequestMeta,
|
||||
|
||||
/// Latest table slot reported for an external root; [`NO_TABLE_SLOT`]
|
||||
/// otherwise. Refreshed on every re-emission.
|
||||
pub table_slot: u32,
|
||||
}
|
||||
|
||||
impl IncomingRequest
|
||||
@@ -155,11 +173,12 @@ impl IncomingRequest
|
||||
{
|
||||
let producer_id = ProducerId(request.producer_id);
|
||||
let structure_id = StructureId(request.structure_id);
|
||||
let anchor = request.anchor;
|
||||
|
||||
let (key, priority) = if meta.page_index == NO_PARENT_PAGE
|
||||
{
|
||||
(
|
||||
RequestKey::root(producer_id, structure_id),
|
||||
RequestKey::root(producer_id, structure_id, anchor),
|
||||
RequestPriority::root(request.demand),
|
||||
)
|
||||
}
|
||||
@@ -169,6 +188,7 @@ impl IncomingRequest
|
||||
RequestKey::child(
|
||||
producer_id,
|
||||
structure_id,
|
||||
anchor,
|
||||
StructureLocator(request.node_id),
|
||||
request.children_index,
|
||||
),
|
||||
@@ -176,10 +196,20 @@ impl IncomingRequest
|
||||
)
|
||||
};
|
||||
|
||||
let table_slot = if key.is_root()
|
||||
{
|
||||
request.table_slot
|
||||
}
|
||||
else
|
||||
{
|
||||
NO_TABLE_SLOT
|
||||
};
|
||||
|
||||
Self {
|
||||
key,
|
||||
priority,
|
||||
meta: *meta,
|
||||
table_slot,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -208,6 +238,7 @@ pub struct ReadyItem<T>
|
||||
{
|
||||
pub key: RequestKey,
|
||||
pub meta: RequestMeta,
|
||||
pub table_slot: u32,
|
||||
pub payload: T,
|
||||
}
|
||||
|
||||
@@ -221,7 +252,12 @@ impl<T> ReadyItem<T>
|
||||
{
|
||||
RequestTarget::Root =>
|
||||
{
|
||||
InsertionParent::external(self.key.structure_id.0, self.key.producer_id.0)
|
||||
InsertionParent::external(
|
||||
self.key.structure_id.0,
|
||||
self.key.producer_id.0,
|
||||
self.key.anchor,
|
||||
self.table_slot,
|
||||
)
|
||||
}
|
||||
RequestTarget::Child {
|
||||
parent,
|
||||
@@ -240,6 +276,7 @@ impl<T> ReadyItem<T>
|
||||
self.key.structure_id.0,
|
||||
parent.0,
|
||||
self.key.producer_id.0,
|
||||
self.key.anchor,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -320,6 +357,9 @@ struct Job<T>
|
||||
first_seen: FrameId,
|
||||
last_seen: FrameId,
|
||||
meta: RequestMeta,
|
||||
/// Latest slot reported for an external root. Refreshed even while the job
|
||||
/// is in flight or ready so a produced root can follow a slot move.
|
||||
table_slot: u32,
|
||||
generation: u64,
|
||||
attempt: u32,
|
||||
payload: Option<T>,
|
||||
@@ -440,6 +480,7 @@ impl<T> RequestQueue<T>
|
||||
|
||||
job.priority = request.priority;
|
||||
job.meta = request.meta;
|
||||
job.table_slot = request.table_slot;
|
||||
job.last_seen = frame;
|
||||
|
||||
match job.state
|
||||
@@ -496,6 +537,7 @@ impl<T> RequestQueue<T>
|
||||
first_seen: frame,
|
||||
last_seen: frame,
|
||||
meta: request.meta,
|
||||
table_slot: request.table_slot,
|
||||
generation,
|
||||
attempt: 0,
|
||||
payload: None,
|
||||
@@ -680,6 +722,7 @@ impl<T> RequestQueue<T>
|
||||
result.push(ReadyItem {
|
||||
key: job.key,
|
||||
meta: job.meta,
|
||||
table_slot: job.table_slot,
|
||||
payload,
|
||||
});
|
||||
}
|
||||
@@ -690,8 +733,9 @@ impl<T> RequestQueue<T>
|
||||
|
||||
/// Removes every job belonging to a structure.
|
||||
///
|
||||
/// Used when a structure slot is invalidated or reused (for example when
|
||||
/// the toroidal structure table moves).
|
||||
/// Correctness is enforced on the GPU by validating the insertion against
|
||||
/// the current anchor/id/slot. Invalidation only cancels speculative work
|
||||
/// and avoids wasted production.
|
||||
pub fn invalidate_structure(&mut self, structure: StructureId) -> usize
|
||||
{
|
||||
self.invalidate_matching(|key| key.structure_id == structure)
|
||||
@@ -703,6 +747,12 @@ impl<T> RequestQueue<T>
|
||||
self.invalidate_matching(|key| key.producer_id == producer)
|
||||
}
|
||||
|
||||
/// Removes every job whose anchor matches.
|
||||
pub fn invalidate_anchor(&mut self, anchor: StructureAnchor) -> usize
|
||||
{
|
||||
self.invalidate_matching(|key| key.anchor == anchor)
|
||||
}
|
||||
|
||||
fn invalidate_matching<F>(&mut self, mut predicate: F) -> usize
|
||||
where
|
||||
F: FnMut(&RequestKey) -> bool,
|
||||
@@ -815,6 +865,7 @@ mod tests
|
||||
|
||||
const PRODUCER: ProducerId = ProducerId(0);
|
||||
const STRUCTURE: StructureId = StructureId(1);
|
||||
const ANCHOR: StructureAnchor = StructureAnchor::ZERO;
|
||||
|
||||
fn meta(page: u32, child: u32, depth: u32) -> RequestMeta
|
||||
{
|
||||
@@ -827,7 +878,13 @@ mod tests
|
||||
|
||||
fn child_key(parent: u32, child: u32) -> RequestKey
|
||||
{
|
||||
RequestKey::child(PRODUCER, STRUCTURE, StructureLocator(parent), child)
|
||||
RequestKey::child(
|
||||
PRODUCER,
|
||||
STRUCTURE,
|
||||
ANCHOR,
|
||||
StructureLocator(parent),
|
||||
child,
|
||||
)
|
||||
}
|
||||
|
||||
fn incoming(key: RequestKey, priority: RequestPriority) -> IncomingRequest
|
||||
@@ -836,9 +893,11 @@ mod tests
|
||||
key,
|
||||
priority,
|
||||
meta: meta(0, 0, 0),
|
||||
table_slot: NO_TABLE_SLOT,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn wire(
|
||||
structure: u32,
|
||||
node: u32,
|
||||
@@ -847,6 +906,8 @@ mod tests
|
||||
demand: u32,
|
||||
parent_page: u32,
|
||||
depth: u32,
|
||||
anchor: StructureAnchor,
|
||||
table_slot: u32,
|
||||
) -> (RequestInformation, RequestMeta)
|
||||
{
|
||||
(
|
||||
@@ -856,6 +917,8 @@ mod tests
|
||||
children_index: child,
|
||||
producer_id: producer,
|
||||
demand,
|
||||
anchor,
|
||||
table_slot,
|
||||
},
|
||||
RequestMeta {
|
||||
page_index: parent_page,
|
||||
@@ -880,7 +943,7 @@ mod tests
|
||||
fn root_and_root_child_zero_do_not_collide()
|
||||
{
|
||||
let mut q = queue(8, 1, 8);
|
||||
let root = RequestKey::root(PRODUCER, STRUCTURE);
|
||||
let root = RequestKey::root(PRODUCER, STRUCTURE, ANCHOR);
|
||||
let child = child_key(0, 0);
|
||||
|
||||
q.ingest(
|
||||
@@ -899,16 +962,29 @@ mod tests
|
||||
#[test]
|
||||
fn from_wire_distinguishes_root_from_root_child_zero()
|
||||
{
|
||||
let (root_info, root_meta) = wire(STRUCTURE.0, 0, 0, PRODUCER.0, 7, u32::MAX, u32::MAX);
|
||||
let (child_info, child_meta) = wire(STRUCTURE.0, 0, 0, PRODUCER.0, 7, 3, 0);
|
||||
let (root_info, root_meta) = wire(
|
||||
STRUCTURE.0,
|
||||
0,
|
||||
0,
|
||||
PRODUCER.0,
|
||||
7,
|
||||
u32::MAX,
|
||||
u32::MAX,
|
||||
ANCHOR,
|
||||
3,
|
||||
);
|
||||
let (child_info, child_meta) =
|
||||
wire(STRUCTURE.0, 0, 0, PRODUCER.0, 7, 3, 0, ANCHOR, NO_TABLE_SLOT);
|
||||
|
||||
let root = IncomingRequest::from_wire(&root_info, &root_meta);
|
||||
let child = IncomingRequest::from_wire(&child_info, &child_meta);
|
||||
|
||||
assert_eq!(root.key, RequestKey::root(PRODUCER, STRUCTURE));
|
||||
assert_eq!(root.key, RequestKey::root(PRODUCER, STRUCTURE, ANCHOR));
|
||||
assert_eq!(root.table_slot, 3);
|
||||
assert_eq!(child.table_slot, NO_TABLE_SLOT);
|
||||
assert_eq!(
|
||||
child.key,
|
||||
RequestKey::child(PRODUCER, STRUCTURE, StructureLocator(0), 0)
|
||||
RequestKey::child(PRODUCER, STRUCTURE, ANCHOR, StructureLocator(0), 0)
|
||||
);
|
||||
assert_ne!(root.key, child.key);
|
||||
}
|
||||
@@ -916,7 +992,17 @@ mod tests
|
||||
#[test]
|
||||
fn from_wire_carries_demand_and_depth_into_priority()
|
||||
{
|
||||
let (info, meta) = wire(STRUCTURE.0, 5, 2, PRODUCER.0, 11, 9, 3);
|
||||
let (info, meta) = wire(
|
||||
STRUCTURE.0,
|
||||
5,
|
||||
2,
|
||||
PRODUCER.0,
|
||||
11,
|
||||
9,
|
||||
3,
|
||||
ANCHOR,
|
||||
NO_TABLE_SLOT,
|
||||
);
|
||||
let request = IncomingRequest::from_wire(&info, &meta);
|
||||
|
||||
assert_eq!(request.priority, RequestPriority::child(11, 3));
|
||||
@@ -928,17 +1014,23 @@ mod tests
|
||||
fn ready_item_builds_stateless_insertion_parent()
|
||||
{
|
||||
let mut q = queue(8, 2, 8);
|
||||
let root = RequestKey::root(PRODUCER, STRUCTURE);
|
||||
let root = RequestKey::root(PRODUCER, STRUCTURE, ANCHOR);
|
||||
let child = child_key(4, 2);
|
||||
|
||||
q.ingest(
|
||||
0,
|
||||
[
|
||||
incoming(root, RequestPriority::root(1)),
|
||||
IncomingRequest {
|
||||
key: root,
|
||||
priority: RequestPriority::root(1),
|
||||
meta: meta(0, 0, 0),
|
||||
table_slot: 5,
|
||||
},
|
||||
IncomingRequest {
|
||||
key: child,
|
||||
priority: RequestPriority::child(1, 3),
|
||||
meta: meta(7, 2, 3),
|
||||
table_slot: NO_TABLE_SLOT,
|
||||
},
|
||||
],
|
||||
);
|
||||
@@ -956,6 +1048,8 @@ mod tests
|
||||
assert_eq!(external.page_index, NO_PARENT_PAGE);
|
||||
assert_eq!(external.structure_id, STRUCTURE.0);
|
||||
assert_eq!(external.producer_id, PRODUCER.0);
|
||||
assert_eq!(external.anchor, ANCHOR);
|
||||
assert_eq!(external.table_slot, 5);
|
||||
|
||||
let internal = ready[1].insertion_parent();
|
||||
assert!(internal.is_internal());
|
||||
@@ -964,6 +1058,8 @@ mod tests
|
||||
assert_eq!(internal.depth, 3);
|
||||
assert_eq!(internal.node_id, 4);
|
||||
assert_eq!(internal.structure_id, STRUCTURE.0);
|
||||
assert_eq!(internal.anchor, ANCHOR);
|
||||
assert_eq!(internal.table_slot, NO_TABLE_SLOT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -978,6 +1074,7 @@ mod tests
|
||||
key: child,
|
||||
priority: RequestPriority::child(1, 3),
|
||||
meta: meta(7, 5, 3),
|
||||
table_slot: NO_TABLE_SLOT,
|
||||
}],
|
||||
);
|
||||
|
||||
@@ -995,8 +1092,8 @@ mod tests
|
||||
fn producer_id_disambiguates_identical_structure_keys()
|
||||
{
|
||||
let mut q = queue(8, 1, 8);
|
||||
let a = RequestKey::child(ProducerId(0), STRUCTURE, StructureLocator(7), 3);
|
||||
let b = RequestKey::child(ProducerId(1), STRUCTURE, StructureLocator(7), 3);
|
||||
let a = RequestKey::child(ProducerId(0), STRUCTURE, ANCHOR, StructureLocator(7), 3);
|
||||
let b = RequestKey::child(ProducerId(1), STRUCTURE, ANCHOR, StructureLocator(7), 3);
|
||||
|
||||
q.ingest(
|
||||
0,
|
||||
@@ -1048,7 +1145,7 @@ mod tests
|
||||
fn roots_outrank_children()
|
||||
{
|
||||
let mut q = queue(8, 8, 8);
|
||||
let root = RequestKey::root(PRODUCER, STRUCTURE);
|
||||
let root = RequestKey::root(PRODUCER, STRUCTURE, ANCHOR);
|
||||
let child = child_key(0, 0);
|
||||
|
||||
q.ingest(
|
||||
@@ -1324,8 +1421,8 @@ mod tests
|
||||
fn invalidate_producer_only_removes_that_producer()
|
||||
{
|
||||
let mut q = queue(8, 8, 8);
|
||||
let a = RequestKey::child(ProducerId(0), STRUCTURE, StructureLocator(1), 0);
|
||||
let b = RequestKey::child(ProducerId(1), STRUCTURE, StructureLocator(1), 0);
|
||||
let a = RequestKey::child(ProducerId(0), STRUCTURE, ANCHOR, StructureLocator(1), 0);
|
||||
let b = RequestKey::child(ProducerId(1), STRUCTURE, ANCHOR, StructureLocator(1), 0);
|
||||
|
||||
q.ingest(
|
||||
0,
|
||||
@@ -1348,4 +1445,100 @@ mod tests
|
||||
assert_eq!(stats.dropped, 1);
|
||||
assert!(q.is_empty());
|
||||
}
|
||||
|
||||
fn root_incoming(slot: u32) -> IncomingRequest
|
||||
{
|
||||
IncomingRequest {
|
||||
key: RequestKey::root(PRODUCER, STRUCTURE, ANCHOR),
|
||||
priority: RequestPriority::root(1),
|
||||
meta: meta(NO_PARENT_PAGE, 0, NO_PARENT_PAGE),
|
||||
table_slot: slot,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_job_refreshes_table_slot_while_in_flight()
|
||||
{
|
||||
let mut q = queue(8, 1, 8);
|
||||
|
||||
q.ingest(0, [root_incoming(1)]);
|
||||
let item = q.pop().unwrap();
|
||||
|
||||
// The same anchor reappears at a new slot before the result is drained.
|
||||
q.ingest(0, [root_incoming(2)]);
|
||||
|
||||
assert_eq!(q.complete(item, 7), CompleteOutcome::Accepted);
|
||||
let ready = q.drain_ready_matching(0, 8, |_| true);
|
||||
assert_eq!(ready.len(), 1);
|
||||
|
||||
let parent = ready[0].insertion_parent();
|
||||
assert!(parent.is_external());
|
||||
assert_eq!(parent.table_slot, 2);
|
||||
assert_eq!(parent.anchor, ANCHOR);
|
||||
assert_eq!(parent.structure_id, STRUCTURE.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_key_is_stable_across_slot_moves()
|
||||
{
|
||||
let mut q = queue(8, 1, 8);
|
||||
|
||||
q.ingest(0, [root_incoming(1)]);
|
||||
q.ingest(1, [root_incoming(9)]);
|
||||
|
||||
// Same producer/id/anchor: one job, refreshed in place, not duplicated.
|
||||
assert_eq!(q.len(), 1);
|
||||
assert!(q.contains(&RequestKey::root(PRODUCER, STRUCTURE, ANCHOR)));
|
||||
|
||||
let item = q.pop().unwrap();
|
||||
q.complete(item, 1);
|
||||
let ready = q.drain_ready_matching(1, 8, |_| true);
|
||||
assert_eq!(ready[0].table_slot, 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_anchors_with_same_structure_are_distinct()
|
||||
{
|
||||
// A correct table never does this, but the queue must not merge them.
|
||||
let mut q = queue(8, 1, 8);
|
||||
let a = RequestKey::child(PRODUCER, STRUCTURE, ANCHOR, StructureLocator(1), 0);
|
||||
let b = RequestKey::child(
|
||||
PRODUCER,
|
||||
STRUCTURE,
|
||||
StructureAnchor::from_world(1, 2, 3, 0),
|
||||
StructureLocator(1),
|
||||
0,
|
||||
);
|
||||
|
||||
q.ingest(
|
||||
0,
|
||||
[
|
||||
incoming(a, RequestPriority::child(1, 0)),
|
||||
incoming(b, RequestPriority::child(1, 0)),
|
||||
],
|
||||
);
|
||||
|
||||
assert_eq!(q.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalidate_anchor_removes_matching_jobs()
|
||||
{
|
||||
let mut q = queue(8, 8, 8);
|
||||
let anchor = StructureAnchor::from_world(4, 5, 6, 0);
|
||||
let a = RequestKey::child(PRODUCER, STRUCTURE, anchor, StructureLocator(1), 0);
|
||||
let b = child_key(1, 0);
|
||||
|
||||
q.ingest(
|
||||
0,
|
||||
[
|
||||
incoming(a, RequestPriority::child(1, 0)),
|
||||
incoming(b, RequestPriority::child(1, 0)),
|
||||
],
|
||||
);
|
||||
|
||||
assert_eq!(q.invalidate_anchor(anchor), 1);
|
||||
assert!(q.contains(&b));
|
||||
assert!(!q.contains(&a));
|
||||
}
|
||||
}
|
||||
|
||||
+41
-20
@@ -7,7 +7,9 @@ use wgpu::CommandEncoder;
|
||||
use wgpu::include_wgsl;
|
||||
|
||||
use crate::gpu::create_multi_buffers_bind_group_layout;
|
||||
use crate::production::StructureId;
|
||||
use crate::voxel_cache;
|
||||
use crate::voxel_cache::schema::StructureAnchor;
|
||||
use crate::voxel_cache::tables::FixedStructureTable;
|
||||
|
||||
/// A torroidal structure table for "infinite" world purposes.
|
||||
@@ -55,6 +57,15 @@ impl ToroidalStructureTable
|
||||
|
||||
let current_offset = Self::offset_from_center(extent, initial_position);
|
||||
|
||||
// Initial anchor of every slot is its world position in the starting
|
||||
// window. Structure ids are table-internal and start at `0..size`.
|
||||
let anchors = (0..size)
|
||||
.map(|slot| {
|
||||
let (x, y, z) = Self::position_for_offset(extent, slot, current_offset);
|
||||
StructureAnchor::from_world(x as i32, y as i32, z as i32, 0)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let bind_group_layout = create_multi_buffers_bind_group_layout(
|
||||
device,
|
||||
1,
|
||||
@@ -82,11 +93,12 @@ impl ToroidalStructureTable
|
||||
|
||||
ToroidalStructureTable {
|
||||
extent,
|
||||
fixed_structure_table: FixedStructureTable::new(
|
||||
fixed_structure_table: FixedStructureTable::new_with_anchors(
|
||||
device,
|
||||
size,
|
||||
max_requests,
|
||||
producer_id,
|
||||
anchors,
|
||||
),
|
||||
position: initial_position,
|
||||
current_offset,
|
||||
@@ -95,35 +107,43 @@ impl ToroidalStructureTable
|
||||
}
|
||||
|
||||
/// Moves the center position to `new_position`.
|
||||
/// This requires updating to structure table to remove disapearing chunks.
|
||||
/// This requires updating the structure table to remove disapearing chunks.
|
||||
///
|
||||
/// Returns the structure slots whose world position changed. The host must
|
||||
/// invalidate any pending request/insertion work for those slots before it
|
||||
/// batches insertions for this frame.
|
||||
/// Slots whose world position changed get a new anchor. Anchors that remain
|
||||
/// in view keep their [`StructureId`]; anchors that leave are retired. The
|
||||
/// invalidation pass resets the pointers of moved slots so their roots are
|
||||
/// requested again.
|
||||
///
|
||||
/// Returns the retired structure ids. The host may use them to cancel
|
||||
/// speculative queue work; correctness does not depend on it because GPU
|
||||
/// insertion validates the anchor/id/slot.
|
||||
pub fn move_position(
|
||||
&mut self,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut CommandEncoder,
|
||||
new_position: Vec3,
|
||||
) -> Vec<u32>
|
||||
) -> Vec<StructureId>
|
||||
{
|
||||
let previous_offset = self.current_offset;
|
||||
let new_offset = Self::offset_from_center(self.extent, new_position);
|
||||
self.current_offset = new_offset;
|
||||
self.position = new_position;
|
||||
|
||||
let mut invalidated = Vec::new();
|
||||
let mut retired = Vec::new();
|
||||
if previous_offset != new_offset
|
||||
{
|
||||
let size = self.extent.0 * self.extent.1 * self.extent.2;
|
||||
for id in 0..size
|
||||
{
|
||||
let previous = Self::position_for_offset(self.extent, id, previous_offset);
|
||||
let current = Self::position_for_offset(self.extent, id, new_offset);
|
||||
if previous != current
|
||||
{
|
||||
invalidated.push(id as u32);
|
||||
}
|
||||
}
|
||||
let new_anchors: Vec<StructureAnchor> = (0..size)
|
||||
.map(|slot| {
|
||||
let (x, y, z) = Self::position_for_offset(self.extent, slot, new_offset);
|
||||
StructureAnchor::from_world(x as i32, y as i32, z as i32, 0)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let (_assignments, retired_ids) = self
|
||||
.fixed_structure_table
|
||||
.reassign_slots(queue, &new_anchors);
|
||||
retired = retired_ids;
|
||||
}
|
||||
|
||||
let invalidation_parameters = ToroidalInvalidationImmediates {
|
||||
@@ -161,13 +181,14 @@ impl ToroidalStructureTable
|
||||
self.extent.2.div_ceil(4) as u32,
|
||||
);
|
||||
|
||||
invalidated
|
||||
retired
|
||||
}
|
||||
|
||||
/// Given the structure id, returns the position of the requesting chunk
|
||||
pub fn get_request_position(&self, structure_id: u32) -> (isize, isize, isize)
|
||||
/// Returns the world position encoded in a table anchor.
|
||||
pub fn position_for_anchor(&self, anchor: StructureAnchor) -> (isize, isize, isize)
|
||||
{
|
||||
Self::position_for_offset(self.extent, structure_id as usize, self.current_offset)
|
||||
let (x, y, z, _version) = anchor.world();
|
||||
(x as isize, y as isize, z as isize)
|
||||
}
|
||||
|
||||
fn position_for_offset(
|
||||
|
||||
+105
-1
@@ -99,6 +99,60 @@ where
|
||||
// SAFETY: u64, then packed u32s ([`CachePointer`]s), so no padding, all bit patterns are allowed
|
||||
unsafe impl<const N: usize> Pod for StructurePage<N> where [(); N * N * N]: {}
|
||||
|
||||
/// Number of `u32` words in a [`StructureAnchor`].
|
||||
pub const ANCHOR_WORDS: usize = 4;
|
||||
|
||||
/// Sentinel used in [`RequestInformation::table_slot`] and
|
||||
/// [`InsertionParent::table_slot`] to mark an insertion that is not attached to
|
||||
/// a structure-table slot (internal requests).
|
||||
pub const NO_TABLE_SLOT: u32 = u32::MAX;
|
||||
|
||||
/// Sentinel reserved so that a structure id is never allocated. Structure ids
|
||||
/// are monotonic per producer and a value is never reused for another anchor.
|
||||
pub const NO_STRUCTURE_ID: u32 = u32::MAX;
|
||||
|
||||
/// Opaque, table-defined identity of a structure's *content*.
|
||||
///
|
||||
/// The cache and the request queue never interpret these words. A table decides
|
||||
/// what an anchor means (for example a world position plus a version) and is
|
||||
/// responsible for never exposing two live slots with the same anchor. The
|
||||
/// anchor travels on the wire so producers stay stateless and so stale
|
||||
/// insertions can be rejected against the current table state.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)]
|
||||
#[repr(C)]
|
||||
pub struct StructureAnchor
|
||||
{
|
||||
pub words: [u32; ANCHOR_WORDS],
|
||||
}
|
||||
|
||||
impl StructureAnchor
|
||||
{
|
||||
/// Convenience anchor used by tests and by tables that do not need a
|
||||
/// distinguishable identity at startup.
|
||||
#[allow(dead_code)]
|
||||
pub const ZERO: Self = Self {
|
||||
words: [0; ANCHOR_WORDS],
|
||||
};
|
||||
|
||||
/// Table-defined helper for world-position anchors: `(x, y, z, version)`.
|
||||
pub fn from_world(x: i32, y: i32, z: i32, version: u32) -> Self
|
||||
{
|
||||
Self {
|
||||
words: [x as u32, y as u32, z as u32, version],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn world(self) -> (i32, i32, i32, u32)
|
||||
{
|
||||
(
|
||||
self.words[0] as i32,
|
||||
self.words[1] as i32,
|
||||
self.words[2] as i32,
|
||||
self.words[3],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Data stored alongside cache structure so that application can locate a
|
||||
/// particular request
|
||||
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
|
||||
@@ -113,6 +167,9 @@ pub struct LocationPage
|
||||
|
||||
/// Identifier of the producer that owns this node
|
||||
pub producer_id: u32,
|
||||
|
||||
/// Opaque content identity inherited from the root request.
|
||||
pub anchor: StructureAnchor,
|
||||
}
|
||||
|
||||
/// Page storing the depth of the current node related to its root.
|
||||
@@ -159,6 +216,13 @@ pub struct RequestInformation
|
||||
|
||||
/// The amount of times this request was emitted this frame. Higher means more urgent.
|
||||
pub demand: u32,
|
||||
|
||||
/// Opaque content identity of the structure this request belongs to.
|
||||
pub anchor: StructureAnchor,
|
||||
|
||||
/// Table slot for an external root request; [`NO_TABLE_SLOT`] for internal
|
||||
/// requests.
|
||||
pub table_slot: u32,
|
||||
}
|
||||
|
||||
/// Metainformation kept along each request, to know which node made the demand
|
||||
@@ -228,6 +292,13 @@ pub struct InsertionParent
|
||||
|
||||
/// Producer that owns the parent.
|
||||
pub producer_id: u32,
|
||||
|
||||
/// Opaque content identity of the structure the parent belongs to.
|
||||
pub anchor: StructureAnchor,
|
||||
|
||||
/// Table slot of an external root; [`NO_TABLE_SLOT`] for internal
|
||||
/// insertions.
|
||||
pub table_slot: u32,
|
||||
}
|
||||
|
||||
impl InsertionParent
|
||||
@@ -238,6 +309,7 @@ impl InsertionParent
|
||||
structure_id: u32,
|
||||
node_id: u32,
|
||||
producer_id: u32,
|
||||
anchor: StructureAnchor,
|
||||
) -> Self
|
||||
{
|
||||
Self {
|
||||
@@ -248,11 +320,18 @@ impl InsertionParent
|
||||
structure_id,
|
||||
node_id,
|
||||
producer_id,
|
||||
anchor,
|
||||
table_slot: NO_TABLE_SLOT,
|
||||
}
|
||||
}
|
||||
|
||||
/// Parent information for the root of an external structure.
|
||||
pub fn external(structure_id: u32, producer_id: u32) -> Self
|
||||
pub fn external(
|
||||
structure_id: u32,
|
||||
producer_id: u32,
|
||||
anchor: StructureAnchor,
|
||||
table_slot: u32,
|
||||
) -> Self
|
||||
{
|
||||
Self {
|
||||
kind: InsertionParentKind::EXTERNAL.raw(),
|
||||
@@ -262,6 +341,8 @@ impl InsertionParent
|
||||
structure_id,
|
||||
node_id: 0,
|
||||
producer_id,
|
||||
anchor,
|
||||
table_slot,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,3 +416,26 @@ where
|
||||
|
||||
// SAFETY: Packed array of u32, no padding, all bit patterns allowed
|
||||
unsafe impl<const N: usize> Pod for InsertionInformation<N> where [(); N * N * N]: {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests
|
||||
{
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn wire_layout_sizes_are_stable()
|
||||
{
|
||||
assert_eq!(size_of::<StructureAnchor>(), 16);
|
||||
assert_eq!(size_of::<RequestInformation>(), 40);
|
||||
assert_eq!(size_of::<LocationPage>(), 28);
|
||||
assert_eq!(size_of::<InsertionParent>(), 48);
|
||||
assert_eq!(size_of::<RequestMeta>(), 12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anchor_world_round_trips_negative_coordinates()
|
||||
{
|
||||
let anchor = StructureAnchor::from_world(-17, 42, -3, 7);
|
||||
assert_eq!(anchor.world(), (-17, 42, -3, 7));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,13 +5,35 @@ struct CacheIndex
|
||||
page_index: u32,
|
||||
children_index: u32,
|
||||
}
|
||||
|
||||
const ANCHOR_WORDS: u32 = 4u;
|
||||
|
||||
struct StructureAnchor
|
||||
{
|
||||
words: array<u32, 4>
|
||||
}
|
||||
|
||||
fn anchor_eq(a: StructureAnchor, b: StructureAnchor) -> bool
|
||||
{
|
||||
for(var i = 0u; i < ANCHOR_WORDS; i++)
|
||||
{
|
||||
if(a.words[i] != b.words[i])
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
struct RequestInformation
|
||||
{
|
||||
structure_id: u32,
|
||||
node_id: u32,
|
||||
children_index: u32,
|
||||
producer_id: u32,
|
||||
demand: u32
|
||||
demand: u32,
|
||||
anchor: StructureAnchor,
|
||||
table_slot: u32
|
||||
}
|
||||
|
||||
struct RequestMeta
|
||||
@@ -25,6 +47,8 @@ struct RequestMeta
|
||||
const NO_PARENT_PAGE: u32 = 0xFFFFFFFFu;
|
||||
const INSERTION_PARENT_INTERNAL: u32 = 0u;
|
||||
const INSERTION_PARENT_EXTERNAL: u32 = 1u;
|
||||
// No structure-table slot (internal request/insertion).
|
||||
const NO_TABLE_SLOT: u32 = 0xFFFFFFFFu;
|
||||
|
||||
struct InsertionParent
|
||||
{
|
||||
@@ -35,6 +59,8 @@ struct InsertionParent
|
||||
structure_id: u32,
|
||||
node_id: u32,
|
||||
producer_id: u32,
|
||||
anchor: StructureAnchor,
|
||||
table_slot: u32
|
||||
}
|
||||
|
||||
struct AttributeArray
|
||||
@@ -47,6 +73,7 @@ struct LocationPage
|
||||
structure_id: u32,
|
||||
node_id: u32,
|
||||
producer_id: u32,
|
||||
anchor: StructureAnchor
|
||||
}
|
||||
|
||||
fn child_information_occupied(info: u32) -> bool
|
||||
|
||||
@@ -10,8 +10,24 @@
|
||||
@group(1) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
|
||||
@group(1) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
|
||||
|
||||
// Group 2: Slot metadata
|
||||
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
|
||||
@group(2) @binding(1) var<storage, read_write> fixed_table_structure_ids: array<u32>;
|
||||
|
||||
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
|
||||
|
||||
fn slot_matches(parent: InsertionParent) -> bool
|
||||
{
|
||||
let slot = parent.table_slot;
|
||||
if(slot == NO_TABLE_SLOT || slot >= arrayLength(&fixed_table_anchors))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return parent.structure_id == fixed_table_structure_ids[slot]
|
||||
&& anchor_eq(parent.anchor, fixed_table_anchors[slot]);
|
||||
}
|
||||
|
||||
@compute
|
||||
@workgroup_size(256, 1, 1)
|
||||
fn insertion(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
@@ -35,17 +51,25 @@ fn insertion(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
return;
|
||||
}
|
||||
|
||||
if(parent.structure_id >= arrayLength(&fixed_table_pointers))
|
||||
// Re-check identity and pointer state after allocation. A slot move between
|
||||
// validation and insertion must not link the wrong tree.
|
||||
if(!slot_matches(parent))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let slot = parent.table_slot;
|
||||
if(slot >= arrayLength(&fixed_table_pointers))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Re-check that the slot is still waiting for this root.
|
||||
let pointer = fixed_table_pointers[parent.structure_id];
|
||||
let pointer = fixed_table_pointers[slot];
|
||||
if(!child_pointer_subdivided(pointer) || child_pointer_available(pointer))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
fixed_table_pointers[parent.structure_id] = child_pointer_make_available(destination);
|
||||
fixed_table_pointers[slot] = child_pointer_make_available(destination);
|
||||
}
|
||||
|
||||
@@ -10,8 +10,27 @@
|
||||
@group(1) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
|
||||
@group(1) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
|
||||
|
||||
// Group 2: Slot metadata
|
||||
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
|
||||
@group(2) @binding(1) var<storage, read_write> fixed_table_structure_ids: array<u32>;
|
||||
|
||||
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
|
||||
|
||||
/// The slot named by the parent still holds the same anchor and structure id.
|
||||
/// This is what makes queue invalidation optional: a stale root response for a
|
||||
/// retired or reused slot can no longer win.
|
||||
fn slot_matches(parent: InsertionParent) -> bool
|
||||
{
|
||||
let slot = parent.table_slot;
|
||||
if(slot == NO_TABLE_SLOT || slot >= arrayLength(&fixed_table_anchors))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return parent.structure_id == fixed_table_structure_ids[slot]
|
||||
&& anchor_eq(parent.anchor, fixed_table_anchors[slot]);
|
||||
}
|
||||
|
||||
/// Validates external root insertions against the structure table.
|
||||
///
|
||||
/// A root is still wanted while its table slot is subdivisible but not yet
|
||||
@@ -40,17 +59,23 @@ fn validate_external(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
return;
|
||||
}
|
||||
|
||||
if(parent.structure_id >= arrayLength(&fixed_table_pointers))
|
||||
if(!slot_matches(parent))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let pointer = fixed_table_pointers[parent.structure_id];
|
||||
let slot = parent.table_slot;
|
||||
if(slot >= arrayLength(&fixed_table_pointers))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let pointer = fixed_table_pointers[slot];
|
||||
if(!child_pointer_subdivided(pointer) || child_pointer_available(pointer))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let slot = atomicAdd(&insertion_data_valid_count, 1u);
|
||||
insertion_data_valid_indices[slot] = index;
|
||||
let valid_slot = atomicAdd(&insertion_data_valid_count, 1u);
|
||||
insertion_data_valid_indices[valid_slot] = index;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,10 @@
|
||||
@group(1) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
|
||||
@group(1) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
|
||||
|
||||
/// Group 2: Slot metadata (current anchor/id assignment)
|
||||
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
|
||||
@group(2) @binding(1) var<storage, read_write> fixed_table_structure_ids: array<u32>;
|
||||
|
||||
var<immediate> table_producer_id: u32;
|
||||
|
||||
@compute
|
||||
@@ -21,14 +25,22 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
return;
|
||||
}
|
||||
|
||||
let structure_id = request_handler_requests[index];
|
||||
// The request handler emits a slot index; resolve its current assignment so
|
||||
// the request carries stable identity plus the current placement.
|
||||
let slot = request_handler_requests[index];
|
||||
if(slot >= arrayLength(&fixed_table_anchors))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var request_info: RequestInformation;
|
||||
request_info.structure_id = structure_id;
|
||||
request_info.structure_id = fixed_table_structure_ids[slot];
|
||||
request_info.node_id = 0;
|
||||
request_info.children_index = 0;
|
||||
request_info.producer_id = table_producer_id;
|
||||
request_info.demand = request_handler_counts[structure_id];
|
||||
request_info.demand = request_handler_counts[slot];
|
||||
request_info.anchor = fixed_table_anchors[slot];
|
||||
request_info.table_slot = slot;
|
||||
|
||||
var request_meta: RequestMeta;
|
||||
// External requests have no parent page.
|
||||
|
||||
@@ -46,7 +46,8 @@ fn internal_parent_is_valid(parent: InsertionParent) -> bool
|
||||
let location = structure_location_pages[parent.page_index];
|
||||
if(location.structure_id != parent.structure_id ||
|
||||
location.node_id != parent.node_id ||
|
||||
location.producer_id != parent.producer_id)
|
||||
location.producer_id != parent.producer_id ||
|
||||
!anchor_eq(location.anchor, parent.anchor))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -52,7 +52,8 @@ fn write_pointers(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
let location = structure_location_pages[parent.page_index];
|
||||
if(location.structure_id != parent.structure_id ||
|
||||
location.node_id != parent.node_id ||
|
||||
location.producer_id != parent.producer_id)
|
||||
location.producer_id != parent.producer_id ||
|
||||
!anchor_eq(location.anchor, parent.anchor))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -38,6 +38,8 @@ fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
|
||||
request_information.children_index = request_location.children_index;
|
||||
request_information.producer_id = structure_location_pages[page_index].producer_id;
|
||||
request_information.demand = request_handler_counts[request_index];
|
||||
request_information.anchor = structure_location_pages[page_index].anchor;
|
||||
request_information.table_slot = NO_TABLE_SLOT;
|
||||
|
||||
// Fill out request meta information
|
||||
var request_meta: RequestMeta;
|
||||
|
||||
@@ -3,6 +3,7 @@ use wgpu::util::DeviceExt;
|
||||
use crate::gpu::indirect_buffer::IndirectBuffer1D;
|
||||
use crate::gpu_profiler::ScopeEncoder;
|
||||
use crate::gpu_profiler::memory_profiler::MemoryProfile;
|
||||
use crate::production::StructureId;
|
||||
use crate::voxel_cache::CacheInvalidable;
|
||||
use crate::voxel_cache::CacheRessources;
|
||||
use crate::voxel_cache::create_multi_buffers_bg_bg_layout;
|
||||
@@ -12,6 +13,8 @@ use crate::voxel_cache::layout::CacheLayout;
|
||||
use crate::voxel_cache::requests::CacheRequestBuffer;
|
||||
use crate::voxel_cache::requests::CacheRequestHandler;
|
||||
use crate::voxel_cache::schema::CachePointer;
|
||||
use crate::voxel_cache::schema::NO_STRUCTURE_ID;
|
||||
use crate::voxel_cache::schema::StructureAnchor;
|
||||
|
||||
use super::pipelines::include_cache_wgsl;
|
||||
|
||||
@@ -37,6 +40,78 @@ macro_rules! include_table_wgsl {
|
||||
}};
|
||||
}
|
||||
|
||||
/// One slot whose anchor or structure id changed during a reassignment.
|
||||
///
|
||||
/// Returned for diagnostics and optional host-side cancellation. Correctness
|
||||
/// does not depend on callers reading these fields; the GPU validates the
|
||||
/// current slot metadata before accepting an insertion.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[allow(dead_code)]
|
||||
pub struct SlotAssignment
|
||||
{
|
||||
pub slot: u32,
|
||||
pub previous_anchor: StructureAnchor,
|
||||
pub previous_structure: StructureId,
|
||||
pub anchor: StructureAnchor,
|
||||
pub structure: StructureId,
|
||||
}
|
||||
|
||||
/// Reuses ids for anchors that are still present, allocates fresh ids for
|
||||
/// anchors entering the table, and returns the ids that are no longer used.
|
||||
///
|
||||
/// A structure id is never reused for a different anchor. Exhaustion is a fatal
|
||||
/// error rather than a wrap, because wrapping would silently alias identities.
|
||||
fn plan_slot_reassignment(
|
||||
old_anchors: &[StructureAnchor],
|
||||
old_ids: &[StructureId],
|
||||
new_anchors: &[StructureAnchor],
|
||||
next_structure_id: &mut u32,
|
||||
) -> (Vec<StructureId>, Vec<StructureId>)
|
||||
{
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
assert_eq!(old_anchors.len(), old_ids.len());
|
||||
assert!(
|
||||
new_anchors.iter().collect::<HashSet<_>>().len() == new_anchors.len(),
|
||||
"a structure table must not expose two live slots with the same anchor"
|
||||
);
|
||||
|
||||
let mut by_anchor = HashMap::with_capacity(old_anchors.len());
|
||||
for (&anchor, &id) in old_anchors.iter().zip(old_ids)
|
||||
{
|
||||
by_anchor.insert(anchor, id);
|
||||
}
|
||||
|
||||
let mut new_ids = Vec::with_capacity(new_anchors.len());
|
||||
for &anchor in new_anchors
|
||||
{
|
||||
if let Some(&id) = by_anchor.get(&anchor)
|
||||
{
|
||||
new_ids.push(id);
|
||||
}
|
||||
else
|
||||
{
|
||||
assert_ne!(
|
||||
*next_structure_id, NO_STRUCTURE_ID,
|
||||
"structure id space exhausted"
|
||||
);
|
||||
new_ids.push(StructureId(*next_structure_id));
|
||||
*next_structure_id += 1;
|
||||
}
|
||||
}
|
||||
|
||||
let live: HashSet<StructureAnchor> = new_anchors.iter().copied().collect();
|
||||
let retired = old_anchors
|
||||
.iter()
|
||||
.zip(old_ids)
|
||||
.filter(|(anchor, _)| !live.contains(anchor))
|
||||
.map(|(_, id)| *id)
|
||||
.collect();
|
||||
|
||||
(new_ids, retired)
|
||||
}
|
||||
|
||||
/// A structure table with a fixed length
|
||||
pub struct FixedStructureTable
|
||||
{
|
||||
@@ -47,6 +122,17 @@ pub struct FixedStructureTable
|
||||
common_ressources: CacheRessources<1>,
|
||||
request_handler: CacheRequestHandler<1>,
|
||||
|
||||
/// Slot-indexed opaque anchors.
|
||||
anchors: wgpu::Buffer,
|
||||
/// Slot-indexed stable structure ids.
|
||||
structure_ids: wgpu::Buffer,
|
||||
metadata_bind_group: wgpu::BindGroup,
|
||||
|
||||
/// Host mirrors used to preserve identity across slot moves.
|
||||
slot_anchors: Vec<StructureAnchor>,
|
||||
slot_structure_ids: Vec<StructureId>,
|
||||
next_structure_id: u32,
|
||||
|
||||
/// Producer that owns the root structures stored by this table
|
||||
producer_id: u32,
|
||||
|
||||
@@ -64,6 +150,11 @@ pub struct FixedStructureTable
|
||||
|
||||
impl FixedStructureTable
|
||||
{
|
||||
/// Creates a static table with one distinct anchor per slot.
|
||||
///
|
||||
/// Retained for callers that do not move slots; [`Self::new_with_anchors`]
|
||||
/// is the general constructor.
|
||||
#[allow(dead_code)]
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
size: usize,
|
||||
@@ -71,6 +162,55 @@ impl FixedStructureTable
|
||||
producer_id: u32,
|
||||
) -> Self
|
||||
{
|
||||
let anchors = (0..size)
|
||||
.map(|slot| StructureAnchor {
|
||||
words: [slot as u32, 0, 0, 0],
|
||||
})
|
||||
.collect();
|
||||
Self::new_with_anchors(device, size, max_requests, producer_id, anchors)
|
||||
}
|
||||
|
||||
/// Creates a table whose slots start with the given anchors.
|
||||
///
|
||||
/// Initial structure ids are `0..size`; later anchors receive ids from a
|
||||
/// monotonic counter that never reuses a value.
|
||||
pub fn new_with_anchors(
|
||||
device: &wgpu::Device,
|
||||
size: usize,
|
||||
max_requests: usize,
|
||||
producer_id: u32,
|
||||
anchors: Vec<StructureAnchor>,
|
||||
) -> Self
|
||||
{
|
||||
assert_eq!(anchors.len(), size);
|
||||
assert!(
|
||||
size < NO_STRUCTURE_ID as usize,
|
||||
"structure id space exhausted"
|
||||
);
|
||||
|
||||
let structure_ids: Vec<u32> = (0..size as u32).collect();
|
||||
let slot_structure_ids: Vec<StructureId> =
|
||||
structure_ids.iter().copied().map(StructureId).collect();
|
||||
|
||||
let anchors_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("FixedStructureTable::anchors"),
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
contents: bytemuck::cast_slice(&anchors),
|
||||
});
|
||||
|
||||
let structure_ids_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("FixedStructureTable::structure_ids"),
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
contents: bytemuck::cast_slice(&structure_ids),
|
||||
});
|
||||
|
||||
let (metadata_bind_group_layout, metadata_bind_group) =
|
||||
create_multi_buffers_bg_bg_layout(
|
||||
device,
|
||||
&[&anchors_buffer, &structure_ids_buffer],
|
||||
Some("FixedStructureTable::metadata"),
|
||||
);
|
||||
|
||||
let pointer = CachePointer::new(Some(None));
|
||||
let pointers = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("FixedStructureTable::pointers"),
|
||||
@@ -101,6 +241,7 @@ impl FixedStructureTable
|
||||
let write_requests_bindings = [
|
||||
Some(&CacheRequestHandler::<1>::create_bind_group_layout(device)),
|
||||
Some(&CacheRequestBuffer::create_bind_group_layout(device)),
|
||||
Some(&metadata_bind_group_layout),
|
||||
];
|
||||
|
||||
let write_requests_pipeline_layout =
|
||||
@@ -162,6 +303,7 @@ impl FixedStructureTable
|
||||
Some(&CacheInsertionData::<1>::create_bind_group_layout(
|
||||
device, None,
|
||||
)),
|
||||
Some(&metadata_bind_group_layout),
|
||||
];
|
||||
|
||||
let insertion_pipeline_layout =
|
||||
@@ -202,6 +344,12 @@ impl FixedStructureTable
|
||||
pointers_bind_group,
|
||||
common_ressources,
|
||||
request_handler,
|
||||
anchors: anchors_buffer,
|
||||
structure_ids: structure_ids_buffer,
|
||||
metadata_bind_group,
|
||||
slot_anchors: anchors,
|
||||
slot_structure_ids,
|
||||
next_structure_id: size as u32,
|
||||
producer_id,
|
||||
indirect_buffer: IndirectBuffer1D::new(device),
|
||||
write_requests_pass,
|
||||
@@ -214,6 +362,88 @@ impl FixedStructureTable
|
||||
}
|
||||
}
|
||||
|
||||
/// Changes the anchor of every slot while preserving structure ids for
|
||||
/// anchors that remain present.
|
||||
///
|
||||
/// Returns the changed assignments and the ids that are no longer used.
|
||||
/// Retired ids are suitable for cancelling speculative queue work; they are
|
||||
/// never reassigned to a different anchor.
|
||||
pub fn reassign_slots(
|
||||
&mut self,
|
||||
queue: &wgpu::Queue,
|
||||
new_anchors: &[StructureAnchor],
|
||||
) -> (Vec<SlotAssignment>, Vec<StructureId>)
|
||||
{
|
||||
assert_eq!(new_anchors.len(), self.size);
|
||||
|
||||
let (new_ids, retired) = plan_slot_reassignment(
|
||||
&self.slot_anchors,
|
||||
&self.slot_structure_ids,
|
||||
new_anchors,
|
||||
&mut self.next_structure_id,
|
||||
);
|
||||
|
||||
let mut assignments = Vec::new();
|
||||
for slot in 0..self.size
|
||||
{
|
||||
let previous_anchor = self.slot_anchors[slot];
|
||||
let previous_structure = self.slot_structure_ids[slot];
|
||||
let anchor = new_anchors[slot];
|
||||
let structure = new_ids[slot];
|
||||
|
||||
if previous_anchor == anchor && previous_structure == structure
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
self.slot_anchors[slot] = anchor;
|
||||
self.slot_structure_ids[slot] = structure;
|
||||
|
||||
queue.write_buffer(
|
||||
&self.anchors,
|
||||
(slot * size_of::<StructureAnchor>()) as u64,
|
||||
bytemuck::bytes_of(&anchor),
|
||||
);
|
||||
queue.write_buffer(
|
||||
&self.structure_ids,
|
||||
(slot * size_of::<u32>()) as u64,
|
||||
bytemuck::bytes_of(&structure.0),
|
||||
);
|
||||
|
||||
assignments.push(SlotAssignment {
|
||||
slot: slot as u32,
|
||||
previous_anchor,
|
||||
previous_structure,
|
||||
anchor,
|
||||
structure,
|
||||
});
|
||||
}
|
||||
|
||||
(assignments, retired)
|
||||
}
|
||||
|
||||
/// Returns the current slot for an anchor, if it is in the table.
|
||||
#[allow(dead_code)]
|
||||
pub fn slot_for_anchor(&self, anchor: &StructureAnchor) -> Option<u32>
|
||||
{
|
||||
self.slot_anchors
|
||||
.iter()
|
||||
.position(|candidate| candidate == anchor)
|
||||
.map(|slot| slot as u32)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn slot_anchor(&self, slot: u32) -> Option<StructureAnchor>
|
||||
{
|
||||
self.slot_anchors.get(slot as usize).copied()
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn slot_structure_id(&self, slot: u32) -> Option<StructureId>
|
||||
{
|
||||
self.slot_structure_ids.get(slot as usize).copied()
|
||||
}
|
||||
|
||||
pub fn gather_requests(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
@@ -255,6 +485,7 @@ impl FixedStructureTable
|
||||
write_requests_pass.set_pipeline(&self.write_requests_pass);
|
||||
write_requests_pass.set_bind_group(0, self.request_handler.bind_group(), &[]);
|
||||
write_requests_pass.set_bind_group(1, request_buffer.bind_group(), &[]);
|
||||
write_requests_pass.set_bind_group(2, &self.metadata_bind_group, &[]);
|
||||
write_requests_pass.set_immediates(0, bytemuck::bytes_of(&self.producer_id));
|
||||
write_requests_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0);
|
||||
}
|
||||
@@ -290,6 +521,7 @@ impl FixedStructureTable
|
||||
|
||||
insertion_pass.set_bind_group(0, &self.pointers_bind_group, &[]);
|
||||
insertion_pass.set_bind_group(1, insertion.bind_group_no_attributes(), &[]);
|
||||
insertion_pass.set_bind_group(2, &self.metadata_bind_group, &[]);
|
||||
|
||||
insertion_pass.set_pipeline(&self.insertion_pass);
|
||||
insertion_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0);
|
||||
@@ -317,6 +549,73 @@ impl FixedStructureTable
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests
|
||||
{
|
||||
use super::*;
|
||||
|
||||
fn anchor(x: i32) -> StructureAnchor
|
||||
{
|
||||
StructureAnchor::from_world(x, 0, 0, 0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permuted_anchors_keep_their_ids()
|
||||
{
|
||||
let old_anchors = [anchor(0), anchor(1), anchor(2)];
|
||||
let old_ids = [StructureId(10), StructureId(11), StructureId(12)];
|
||||
let new_anchors = [anchor(2), anchor(0), anchor(1)];
|
||||
let mut next = 20;
|
||||
|
||||
let (ids, retired) =
|
||||
plan_slot_reassignment(&old_anchors, &old_ids, &new_anchors, &mut next);
|
||||
|
||||
assert_eq!(ids, vec![StructureId(12), StructureId(10), StructureId(11)]);
|
||||
assert!(retired.is_empty());
|
||||
assert_eq!(next, 20);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entering_anchor_gets_a_fresh_id_and_leaving_anchor_retires()
|
||||
{
|
||||
let old_anchors = [anchor(0), anchor(1)];
|
||||
let old_ids = [StructureId(10), StructureId(11)];
|
||||
let new_anchors = [anchor(1), anchor(2)];
|
||||
let mut next = 12;
|
||||
|
||||
let (ids, retired) =
|
||||
plan_slot_reassignment(&old_anchors, &old_ids, &new_anchors, &mut next);
|
||||
|
||||
assert_eq!(ids, vec![StructureId(11), StructureId(12)]);
|
||||
assert_eq!(retired, vec![StructureId(10)]);
|
||||
assert_eq!(next, 13);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_are_never_reused_across_round_trips()
|
||||
{
|
||||
let mut next = 1;
|
||||
let mut anchors = [anchor(0)];
|
||||
let mut ids = [StructureId(0)];
|
||||
|
||||
let (new_ids, _) = plan_slot_reassignment(&anchors, &ids, &[anchor(5)], &mut next);
|
||||
anchors = [anchor(5)];
|
||||
ids = [new_ids[0]];
|
||||
|
||||
let (new_ids, _) = plan_slot_reassignment(&anchors, &ids, &[anchor(0)], &mut next);
|
||||
assert_eq!(new_ids[0], StructureId(2));
|
||||
assert_eq!(next, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "structure id space exhausted")]
|
||||
fn allocator_exhaustion_is_fatal()
|
||||
{
|
||||
let mut next = NO_STRUCTURE_ID;
|
||||
let _ = plan_slot_reassignment(&[], &[], &[anchor(0)], &mut next);
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> CacheInvalidable<N> for FixedStructureTable
|
||||
where
|
||||
[(); N * N * N]:,
|
||||
@@ -341,6 +640,7 @@ where
|
||||
|
||||
validate_pass.set_bind_group(0, &self.pointers_bind_group, &[]);
|
||||
validate_pass.set_bind_group(1, insertion.bind_group_no_attributes(), &[]);
|
||||
validate_pass.set_bind_group(2, &self.metadata_bind_group, &[]);
|
||||
|
||||
validate_pass.set_pipeline(&self.validation_pass);
|
||||
validate_pass.dispatch_workgroups_indirect(workgroup_count_buffer, 0);
|
||||
|
||||
Reference in New Issue
Block a user