roxlap_scene/lib.rs
1//! roxlap scene-graph layer — many independent chunked voxel
2//! grids in a single 3D scene.
3//!
4//! See `PORTING-SCENE.md` at the workspace root for the substage
5//! roadmap. This crate is the layer **above** voxlap's per-chunk
6//! renderer (`roxlap-core`): a [`Scene`] holds a sparse set of
7//! [`Grid`]s, each with its own f64 world position + arbitrary 3D
8//! rotation. Future stages will add per-grid raycast composition
9//! (S3), cross-chunk gline within a grid (S4), per-grid rotation
10//! (S5), far-LOD billboards / planet proxies (S6), and streaming +
11//! procedural generation (S7).
12//!
13//! S2.0 lands the **type skeleton + grid registration only**.
14//! S2.1 adds the [`addr`] module — world ↔ grid-local ↔ chunk +
15//! voxel-in-chunk decomposition, the canonical f64↔i32 boundary
16//! helper called out by risk R5 in `PORTING-SCENE.md`. S2.2 adds
17//! the [`chunks`] module (sparse storage with on-demand chunk
18//! allocation) and the [`Grid`] edit API ([`Grid::set_voxel`],
19//! [`Grid::set_rect`], [`Grid::set_sphere`]) which decompose
20//! multi-chunk operations and delegate to
21//! [`roxlap_formats::edit`]. S2.3 adds the [`snapshot`] module —
22//! a serde-friendly view of the scene that round-trips through
23//! `Serialize` + `Deserialize` (chunks encode via
24//! [`roxlap_formats::vxl::serialize`] / [`parse`]). Rendering
25//! composition is still owed (S3+).
26//!
27//! [`parse`]: roxlap_formats::vxl::parse
28
29pub mod addr;
30pub mod billboard;
31pub mod cavegen;
32pub mod chunks;
33pub mod edit;
34pub mod lod;
35pub mod render;
36pub mod snapshot;
37pub mod streaming;
38
39use std::collections::{HashMap, HashSet};
40use std::sync::Arc;
41
42use glam::{DQuat, DVec3, IVec3, UVec3};
43use roxlap_formats::vxl::Vxl;
44use serde::{Deserialize, Serialize};
45
46pub use addr::{grid_local_to_world, voxel_global, voxel_split, world_to_grid_local, GridLocalPos};
47pub use billboard::{canonical_viewpoints, BillboardCache, BillboardSnapshot};
48pub use edit::SpanOp;
49pub use lod::{select_lod, Lod, LodThresholds};
50pub use streaming::{ChunkGenerator, StreamRadius};
51
52/// XY size of one chunk in voxels. The plan locks 128 — keeps
53/// chunks compact (~2 MB worst-case dense-slab footprint inside
54/// each `Vxl`) and divides cleanly into voxlap's 2048 reference
55/// world size.
56pub const CHUNK_SIZE_XY: u32 = 128;
57
58/// Z size of one chunk in voxels. Locked at 256 to preserve
59/// voxlap's existing slab byte format unchanged inside each chunk
60/// — the per-chunk renderer doesn't need to know it's living
61/// inside a scene-graph.
62pub const CHUNK_SIZE_Z: u32 = 256;
63
64/// Stable identifier for a grid registered in a [`Scene`]. Issued
65/// by [`Scene::add_grid`]; persists across edits but a removed
66/// grid's id is not reissued.
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
68pub struct GridId(u32);
69
70impl GridId {
71 /// The integer wire form. Useful for serde / debug output.
72 #[must_use]
73 pub const fn raw(self) -> u32 {
74 self.0
75 }
76}
77
78/// A solid-voxel hit from [`Scene::raycast`].
79#[derive(Debug, Clone, Copy, PartialEq)]
80pub struct RayHit {
81 /// The grid the ray hit.
82 pub grid: GridId,
83 /// Grid-local integer voxel coordinate of the hit cell.
84 pub voxel: IVec3,
85 /// World-space hit point (`origin + t · normalize(dir)`).
86 pub world: DVec3,
87 /// World distance from the ray origin to the hit.
88 pub t: f64,
89 /// Packed colour of the hit voxel, or `None` if it's an untextured
90 /// (bedrock / interior) cell. See [`Grid::voxel_color`].
91 pub color: Option<u32>,
92}
93
94/// Voxel DDA (Amanatides-Woo) in a grid's local space. `lo` / `ld` are
95/// the ray origin + unit direction already transformed into grid-local
96/// coords. Returns the first [`Grid::voxel_solid`] cell and its world-
97/// equal distance `t`, or `None` past `max_t`. The step budget is
98/// `~3·max_t` so a near-axis ray through empty space still terminates.
99fn voxel_dda(grid: &Grid, lo: DVec3, ld: DVec3, max_t: f64) -> Option<(IVec3, f64)> {
100 #[allow(clippy::cast_possible_truncation)]
101 let mut p = IVec3::new(
102 lo.x.floor() as i32,
103 lo.y.floor() as i32,
104 lo.z.floor() as i32,
105 );
106 if grid.voxel_solid(p) {
107 return Some((p, 0.0)); // origin already inside a solid voxel
108 }
109 let sign = |d: f64| -> i32 {
110 if d > 0.0 {
111 1
112 } else if d < 0.0 {
113 -1
114 } else {
115 0
116 }
117 };
118 let step = IVec3::new(sign(ld.x), sign(ld.y), sign(ld.z));
119 // Distance to advance one whole voxel along each axis (∞ if parallel).
120 let t_delta = DVec3::new(
121 if ld.x == 0.0 {
122 f64::INFINITY
123 } else {
124 (1.0 / ld.x).abs()
125 },
126 if ld.y == 0.0 {
127 f64::INFINITY
128 } else {
129 (1.0 / ld.y).abs()
130 },
131 if ld.z == 0.0 {
132 f64::INFINITY
133 } else {
134 (1.0 / ld.z).abs()
135 },
136 );
137 // Distance to the first voxel boundary on each axis.
138 let boundary = |o: f64, d: f64| -> f64 {
139 if d > 0.0 {
140 (o.floor() + 1.0 - o) / d
141 } else if d < 0.0 {
142 (o - o.floor()) / -d
143 } else {
144 f64::INFINITY
145 }
146 };
147 let mut t_max = DVec3::new(
148 boundary(lo.x, ld.x),
149 boundary(lo.y, ld.y),
150 boundary(lo.z, ld.z),
151 );
152 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
153 let max_steps = (max_t * 3.0) as u64 + 8;
154 for _ in 0..max_steps {
155 // Advance across the nearest voxel boundary.
156 let t = if t_max.x <= t_max.y && t_max.x <= t_max.z {
157 p.x += step.x;
158 let t = t_max.x;
159 t_max.x += t_delta.x;
160 t
161 } else if t_max.y <= t_max.z {
162 p.y += step.y;
163 let t = t_max.y;
164 t_max.y += t_delta.y;
165 t
166 } else {
167 p.z += step.z;
168 let t = t_max.z;
169 t_max.z += t_delta.z;
170 t
171 };
172 if t > max_t {
173 return None;
174 }
175 if grid.voxel_solid(p) {
176 return Some((p, t));
177 }
178 }
179 None
180}
181
182/// f64 world placement of one grid: position + orientation.
183///
184/// `origin` is the grid's local-space origin in world coords —
185/// chunk `(0, 0, 0)`'s `(0, 0, 0)` voxel maps to
186/// `origin + rotation * vec3(0, 0, 0)` (i.e. just `origin`).
187/// Voxel size is fixed at 1 world unit / voxel for v1.
188#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
189pub struct GridTransform {
190 pub origin: DVec3,
191 pub rotation: DQuat,
192}
193
194impl GridTransform {
195 /// Identity transform at world origin. Useful as a default for
196 /// the first grid added to an otherwise empty scene.
197 #[must_use]
198 pub fn identity() -> Self {
199 Self {
200 origin: DVec3::ZERO,
201 rotation: DQuat::IDENTITY,
202 }
203 }
204
205 /// Axis-aligned grid placed at `origin` with no rotation.
206 #[must_use]
207 pub fn at(origin: DVec3) -> Self {
208 Self {
209 origin,
210 rotation: DQuat::IDENTITY,
211 }
212 }
213}
214
215impl Default for GridTransform {
216 fn default() -> Self {
217 Self::identity()
218 }
219}
220
221/// Address of one voxel inside a scene: which grid it belongs to,
222/// which chunk within that grid, and the voxel's offset inside
223/// that chunk.
224///
225/// `chunk` is signed (`IVec3`) because chunks are centred on the
226/// grid's local origin and may extend in either direction. `voxel`
227/// is unsigned and must satisfy
228/// `(voxel.x, voxel.y) < CHUNK_SIZE_XY` and `voxel.z < CHUNK_SIZE_Z`.
229#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
230pub struct GridAddr {
231 pub grid: GridId,
232 pub chunk: IVec3,
233 pub voxel: UVec3,
234}
235
236/// One independent voxel grid in a scene. Holds its world placement
237/// and a sparse map of populated chunks. Empty chunk slots are
238/// implicit air and skipped during rendering / raycasts.
239///
240/// Each chunk is internally a [`Vxl`] with `vsid = CHUNK_SIZE_XY`
241/// — the existing per-chunk renderer (opticast + grouscan +
242/// sprites + lighting in `roxlap-core`) runs on each chunk
243/// unchanged. Vertical worlds are built by stacking chunks along
244/// grid-local `+z`.
245#[derive(Debug)]
246pub struct Grid {
247 /// World placement (origin + rotation).
248 pub transform: GridTransform,
249 /// Sparse chunk storage keyed by `(chx, chy, chz)` chunk
250 /// coordinates. A missing entry means the chunk is fully air.
251 pub chunks: HashMap<IVec3, Vxl>,
252 /// Whether sky pixels rendered for this grid should be
253 /// composited into the final framebuffer. `true` is the
254 /// historical "grid owns its own sky" behaviour: ray misses
255 /// inside this grid's frustum paint sky_color into the temp
256 /// buffer. Set `false` for grids that are a foreground object
257 /// (e.g. a ship) — the sky is owned by a single "world" grid
258 /// (the ground) and other grids should not contribute sky
259 /// pixels, otherwise their grid-local-frame sky lookup
260 /// rotates with the grid and visibly fights the world's sky
261 /// during compose. See [`crate::render::render_scene_composed`]
262 /// for the masking implementation.
263 pub render_sky: bool,
264 /// Override [`roxlap_core::opticast::OpticastSettings::mip_levels`]
265 /// for this grid. `None` ⇒ use the caller's value. `Some(n)`
266 /// ⇒ cap at `n` (clamped to `[1, settings.mip_levels]`). Use
267 /// to disable multi-mip on a per-grid basis — small grids
268 /// (rotating ships, billboards) don't benefit from deep mips
269 /// and CAN trigger the
270 /// `[[project_axis_aligned_mip_beams]]`-style cf-cancellation
271 /// artifact when near-axis-aligned rays hit the rotated grid.
272 /// `Some(1)` = mip-0 only, byte-stable to single-mip.
273 pub mip_levels_override: Option<u32>,
274 /// World-distance thresholds for per-grid LOD tier selection
275 /// (S6.0). Defaults to [`LodThresholds::always_near`], so a
276 /// freshly-constructed grid always renders at full voxel (the
277 /// S5-and-earlier byte-stable behaviour). S6.1 plugs `Mid` into
278 /// the existing multi-mip path; S6.3 plugs `Far` into the
279 /// billboard impostor cache. See [`crate::lod`].
280 pub lod_thresholds: LodThresholds,
281 /// Lazy [`BillboardCache`] for the `Lod::Far` tier (S6.2).
282 /// `None` until the first time S6.3's render dispatch needs
283 /// it; populated then via [`BillboardCache::build`] and
284 /// cleared by edits ([`Self::set_voxel`] / [`Self::set_rect`]
285 /// / [`Self::set_sphere`]) to force a rebuild on next Far use.
286 /// Callers may also force-invalidate via direct assignment.
287 pub billboards: Option<BillboardCache>,
288 /// Optional procedural generator (S7.0). When set,
289 /// [`Self::ensure_chunk_generated`] uses it to materialise
290 /// chunks that are still absent from [`Self::chunks`].
291 ///
292 /// Streaming layers (S7.1+) walk the active radius around the
293 /// camera and call `ensure_chunk_generated` for missing chunks;
294 /// later stages dispatch this onto a background rayon pool. The
295 /// trait bound is `Send + Sync` (needed for S7.3 async
296 /// dispatch) + `Debug` (needed so [`Grid`] keeps deriving
297 /// `Debug`).
298 ///
299 /// `None` is the default — a grid without a generator behaves
300 /// exactly like the pre-S7 grids: absent chunks stay absent.
301 ///
302 /// `Arc` (not `Box`) so S7.3's async dispatch can clone the
303 /// generator into background rayon tasks without moving it out
304 /// of the grid. Trait bound `Send + Sync` (required at S7.0)
305 /// already makes `Arc<dyn ChunkGenerator>` `Send + Sync`.
306 pub generator: Option<Arc<dyn ChunkGenerator>>,
307 /// Streaming activity / eviction radii used by
308 /// [`Scene::pump_streaming_sync`] (S7.1). Defaults to
309 /// [`StreamRadius::DISABLED`] so existing grids see no change
310 /// in behaviour until the caller opts in.
311 pub stream_radius: StreamRadius,
312 /// Per-chunk edit version counter (S7.2). Each user edit
313 /// through [`Self::set_voxel`] / [`Self::set_rect`] /
314 /// [`Self::set_sphere`] bumps the counter for every chunk it
315 /// actually wrote to. [`Self::ensure_chunk_generated`] does
316 /// NOT bump — a freshly generated chunk has no edits and
317 /// reads as version 0.
318 ///
319 /// Wired up here so the S7.3 async dispatch can detect "an
320 /// edit happened while a chunk was being generated in the
321 /// background" and discard the now-stale result: each
322 /// background task captures the dispatch-time version and
323 /// only installs its result iff the current version still
324 /// matches.
325 ///
326 /// Missing entries read as `0` via [`Self::chunk_version`].
327 /// Evictions in [`Scene::pump_streaming_sync`] drop the
328 /// corresponding entry so the map stays bounded.
329 pub chunk_versions: HashMap<IVec3, u64>,
330 /// In-flight background generation tasks (S7.3).
331 ///
332 /// Populated by [`Scene::pump_streaming`] when it dispatches a
333 /// generator call onto the streaming rayon pool, drained when
334 /// the corresponding [`ChunkResult`] is received and processed
335 /// (either installed or discarded). The set is consulted to
336 /// avoid re-dispatching the same chunk while a previous task
337 /// is still running.
338 ///
339 /// Stays empty when only the synchronous
340 /// [`Scene::pump_streaming_sync`] is used — that path generates
341 /// inline on the calling thread.
342 ///
343 /// [`ChunkResult`]: streaming::ChunkResult
344 pub pending_gen: HashSet<IVec3>,
345 /// Cross-frame DDA brick-occupancy cache (Substage DDA.7 perf).
346 /// Keyed by `(chunk, mip)` + the chunk's edit version, so a static
347 /// chunk's brick map is built once and reused every frame. Skipped
348 /// entirely on the voxlap render path. Not serialised.
349 pub dda_brick_cache: roxlap_core::BrickCache,
350}
351
352impl Grid {
353 /// New empty grid at the given transform — no chunks populated,
354 /// `render_sky = true`, LOD thresholds default to
355 /// [`LodThresholds::always_near`], no billboard cache.
356 #[must_use]
357 pub fn new(transform: GridTransform) -> Self {
358 Self {
359 transform,
360 chunks: HashMap::new(),
361 render_sky: true,
362 mip_levels_override: None,
363 lod_thresholds: LodThresholds::always_near(),
364 billboards: None,
365 generator: None,
366 stream_radius: StreamRadius::DISABLED,
367 chunk_versions: HashMap::new(),
368 pending_gen: HashSet::new(),
369 dda_brick_cache: roxlap_core::BrickCache::new(),
370 }
371 }
372
373 /// Ensure the DDA brick cache holds current mip-`requested_mip`
374 /// occupancy maps for every populated chunk, rebuilding only chunks
375 /// whose edit version changed (Substage DDA.7). Clamps the mip to a
376 /// level every chunk has built (so coarse rendering never holes) and
377 /// returns that effective mip. Evicts cache entries for chunks no
378 /// longer present. Call once per frame before the DDA render.
379 pub fn ensure_dda_bricks(&mut self, requested_mip: u32) -> u32 {
380 // Split-borrow disjoint fields so the cache mutates while the
381 // chunks + versions are read.
382 let Self {
383 chunks,
384 chunk_versions,
385 dda_brick_cache,
386 ..
387 } = self;
388 // Effective uniform mip: min built mip across chunks, capped.
389 let mut mip = requested_mip;
390 if requested_mip > 0 {
391 for vxl in chunks.values() {
392 mip = mip.min(vxl.mip_count().saturating_sub(1));
393 }
394 }
395 for (idx, vxl) in chunks.iter() {
396 let version = chunk_versions.get(idx).copied().unwrap_or(0);
397 let view = roxlap_core::GridView::from_single_vxl(vxl);
398 dda_brick_cache.ensure([idx.x, idx.y, idx.z], mip, version, &view);
399 }
400 dda_brick_cache.retain_chunks(|c| chunks.contains_key(&IVec3::new(c[0], c[1], c[2])));
401 mip
402 }
403
404 /// Current per-chunk edit version (S7.2). Returns `0` for any
405 /// chunk that hasn't been edited yet (including absent chunks
406 /// and chunks materialised only via
407 /// [`Self::ensure_chunk_generated`]).
408 ///
409 /// Used by S7.3's async generation dispatch to detect "edit
410 /// happened while we were generating" — the dispatcher
411 /// snapshots this value, the background task carries it, and
412 /// the result is discarded on install if the live counter has
413 /// since moved.
414 #[must_use]
415 pub fn chunk_version(&self, chunk_idx: IVec3) -> u64 {
416 self.chunk_versions.get(&chunk_idx).copied().unwrap_or(0)
417 }
418
419 /// Bump the edit version of `chunk_idx` (S7.2). Saturating add
420 /// at `u64::MAX` — a chunk would need 10^11 edits per second
421 /// for ~5 years to wrap, so saturation is a defensive cap, not
422 /// a realistic concern.
423 ///
424 /// Called by the edit API ([`Self::set_voxel`] /
425 /// [`Self::set_rect`] / [`Self::set_sphere`]) after a chunk
426 /// has actually been written to. Pure no-op edit paths
427 /// (carving from an air chunk that doesn't exist yet) skip
428 /// the bump.
429 ///
430 /// Exposed as `pub` (vs the historical `pub(crate)`) so hosts
431 /// that mutate `grid.chunks` directly — e.g.
432 /// `roxlap-scene-demo`'s `StreamingBakeTracker` writing
433 /// lightmode-1 alphas via `apply_lighting_with_cache` — can
434 /// signal "this chunk's slab changed" to downstream consumers
435 /// like the GPU dirty-chunk poller.
436 pub fn bump_chunk_version(&mut self, chunk_idx: IVec3) {
437 let entry = self.chunk_versions.entry(chunk_idx).or_insert(0);
438 *entry = entry.saturating_add(1);
439 }
440
441 /// Attach (or detach) the procedural generator used by
442 /// [`Self::ensure_chunk_generated`] (S7.0).
443 ///
444 /// Pass `Some(Arc::new(generator))` to enable on-demand chunk
445 /// generation; pass `None` to revert to the "absent stays
446 /// absent" behaviour. Replacing an existing generator drops the
447 /// previous `Arc` clone without touching already-materialised
448 /// chunks. Any background tasks dispatched by a prior
449 /// [`Scene::pump_streaming`] hold their own clones of the old
450 /// generator and finish naturally.
451 pub fn set_generator(&mut self, generator: Option<Arc<dyn ChunkGenerator>>) {
452 self.generator = generator;
453 }
454
455 /// Materialise the chunk at `chunk_idx` by running [`Self::generator`]
456 /// if (a) the chunk is not already present and (b) a generator
457 /// is attached. Returns `true` iff a chunk was newly generated.
458 ///
459 /// No-ops in all other cases:
460 /// - chunk already present (caller edits / a previous
461 /// `ensure_chunk_generated` call already populated it),
462 /// - no generator attached (the chunk stays implicit-air per
463 /// the existing convention — does NOT fall through to
464 /// [`Self::ensure_chunk`]'s empty-chunk constructor).
465 ///
466 /// This is the synchronous S7.0 path. S7.3 will add an async
467 /// counterpart that dispatches the generator call to a
468 /// dedicated rayon pool and installs the result on the next
469 /// `pump_streaming` call.
470 pub fn ensure_chunk_generated(&mut self, chunk_idx: IVec3) -> bool {
471 if self.chunks.contains_key(&chunk_idx) {
472 return false;
473 }
474 let Some(generator) = self.generator.as_ref() else {
475 return false;
476 };
477 // S7.6+: generator may decline specific indices (e.g. a
478 // single-z-layer generator skipping placeholder bedrock
479 // chunks at chz != 0). Respect the filter so we don't
480 // materialise an unwanted chunk.
481 if !generator.should_generate(chunk_idx) {
482 return false;
483 }
484 let chunk = generator.generate(chunk_idx);
485 self.chunks.insert(chunk_idx, chunk);
486 // S7.4: a fresh chunk grows the populated AABB → the
487 // bounding sphere shifts/expands → existing impostor
488 // projections become wrong. Match the eviction (S7.1) +
489 // edit (S6.2) invalidation contract and drop the cache.
490 // Next Far-tier render rebuilds lazily.
491 self.billboards = None;
492 true
493 }
494
495 /// Bounding-sphere radius of the populated chunk set in
496 /// grid-local space.
497 ///
498 /// Walks the sparse chunk map once, computes the chunk-index
499 /// AABB, converts to voxel-space half-extent, returns its
500 /// Euclidean length. Empty grid → `0.0`.
501 ///
502 /// Conservative — bounds the full chunk volume, not just its
503 /// populated voxels (a chunk containing one voxel still
504 /// contributes `CHUNK_SIZE_XY × CHUNK_SIZE_XY × CHUNK_SIZE_Z`
505 /// to the bbox). For LOD picking that's fine: an over-bound
506 /// sphere errs on the side of `Near`.
507 ///
508 /// Cost: `O(chunks.len())`; recomputed on every call. Callers
509 /// who need this every frame should memoize at the
510 /// [`Scene`]-level cache (added when S6.2 needs it).
511 #[must_use]
512 pub fn bounding_radius(&self) -> f64 {
513 if self.chunks.is_empty() {
514 return 0.0;
515 }
516 let mut min = IVec3::splat(i32::MAX);
517 let mut max = IVec3::splat(i32::MIN);
518 for &idx in self.chunks.keys() {
519 min = min.min(idx);
520 max = max.max(idx);
521 }
522 // Chunk-index bbox → voxel-space half-extent. `+1` on max
523 // converts inclusive chunk index to exclusive voxel upper
524 // bound (chunk `idx` covers voxels `[idx*size, (idx+1)*size)`).
525 let sx = f64::from(CHUNK_SIZE_XY);
526 let sz = f64::from(CHUNK_SIZE_Z);
527 let lo = DVec3::new(
528 f64::from(min.x) * sx,
529 f64::from(min.y) * sx,
530 f64::from(min.z) * sz,
531 );
532 let hi = DVec3::new(
533 f64::from(max.x + 1) * sx,
534 f64::from(max.y + 1) * sx,
535 f64::from(max.z + 1) * sz,
536 );
537 let half_extent = (hi - lo) * 0.5;
538 half_extent.length()
539 }
540
541 /// Pick this grid's LOD tier for the given world-space camera
542 /// position. Convenience wrapper around [`crate::select_lod`]
543 /// that pulls [`Self::lod_thresholds`] from the grid.
544 #[must_use]
545 pub fn select_lod(&self, camera_world_pos: DVec3) -> Lod {
546 select_lod(camera_world_pos, &self.transform, self.lod_thresholds)
547 }
548}
549
550/// Top-level scene container. Holds a flat collection of grids
551/// keyed by [`GridId`].
552///
553/// S2.0 only exposes registration / removal / lookup. Address math
554/// helpers (S2.x), edit API (S2.x), and rendering composition (S3)
555/// land in later sub-substages.
556#[derive(Debug, Default)]
557pub struct Scene {
558 grids: HashMap<GridId, Grid>,
559 next_grid_id: u32,
560 /// S7.3: per-scene streaming pool + result channel. Stored on
561 /// the `Scene` so `pump_streaming` can dispatch background
562 /// tasks and drain results across pump calls. `cfg`-gated out
563 /// on wasm32 where `pump_streaming` short-circuits to
564 /// `pump_streaming_sync` (no rayon pool there).
565 #[cfg(not(target_arch = "wasm32"))]
566 streaming: streaming::StreamingState,
567}
568
569impl Scene {
570 /// New empty scene — no grids.
571 #[must_use]
572 pub fn new() -> Self {
573 Self::default()
574 }
575
576 /// Number of grids currently registered.
577 #[must_use]
578 pub fn grid_count(&self) -> usize {
579 self.grids.len()
580 }
581
582 /// Register a new grid. Returns its fresh, unique [`GridId`].
583 pub fn add_grid(&mut self, transform: GridTransform) -> GridId {
584 let id = GridId(self.next_grid_id);
585 self.next_grid_id += 1;
586 self.grids.insert(id, Grid::new(transform));
587 id
588 }
589
590 /// Remove a grid by id. Returns the removed [`Grid`] (so the
591 /// caller can reclaim its chunks) or `None` if the id wasn't
592 /// registered. Removed ids are not reissued.
593 pub fn remove_grid(&mut self, id: GridId) -> Option<Grid> {
594 self.grids.remove(&id)
595 }
596
597 /// Borrow a registered grid.
598 #[must_use]
599 pub fn grid(&self, id: GridId) -> Option<&Grid> {
600 self.grids.get(&id)
601 }
602
603 /// Mutably borrow a registered grid.
604 pub fn grid_mut(&mut self, id: GridId) -> Option<&mut Grid> {
605 self.grids.get_mut(&id)
606 }
607
608 /// Iterator over all `(id, grid)` pairs in registration order
609 /// is **not** guaranteed — the underlying map is a `HashMap`.
610 /// Callers that need a stable order must sort by [`GridId`].
611 pub fn grids(&self) -> impl Iterator<Item = (GridId, &Grid)> {
612 self.grids.iter().map(|(id, g)| (*id, g))
613 }
614
615 /// Mutable iterator over all `(id, grid)` pairs. Yield order
616 /// is not guaranteed (HashMap-backed).
617 pub fn grids_mut(&mut self) -> impl Iterator<Item = (GridId, &mut Grid)> {
618 self.grids.iter_mut().map(|(id, g)| (*id, g))
619 }
620
621 /// Resolve a world-space surface hit to the owning grid + its
622 /// grid-local voxel — the picking back half. `ray_dir` is the view
623 /// direction the hit was found along (need not be normalised); the
624 /// point is nudged half a voxel along it, past the surface and into
625 /// the solid cell, before each grid's [`Grid::voxel_solid`] test.
626 /// Returns the first grid that is solid there (transform-correct
627 /// for rotated/translated grids), or `None` if none claims it.
628 ///
629 /// Backend-agnostic: pair with a renderer depth read to turn a
630 /// click into a voxel — `world = cam.pos + t · normalize(ray_dir)`,
631 /// then `resolve_voxel(world, ray_dir)`. `roxlap-render`'s
632 /// `SceneRenderer::pick` wires exactly that.
633 #[must_use]
634 pub fn resolve_voxel(&self, world: DVec3, ray_dir: DVec3) -> Option<(GridId, IVec3)> {
635 let len = ray_dir.length();
636 if len < 1e-9 {
637 return None;
638 }
639 let inside = world + ray_dir * (0.5 / len); // half a voxel inward
640 for (id, grid) in self.grids() {
641 let glp = addr::world_to_grid_local(inside, &grid.transform);
642 let v = addr::voxel_global(glp.chunk, glp.voxel);
643 if grid.voxel_solid(v) {
644 return Some((id, v));
645 }
646 }
647 None
648 }
649
650 /// Cast a world-space ray and return the nearest solid voxel hit
651 /// across all grids, or `None` if nothing solid lies within
652 /// `max_dist`. Renderer-independent (no depth buffer, no camera) —
653 /// the primitive for line-of-sight, projectiles, AI probing, and
654 /// off-screen / backend-agnostic picking.
655 ///
656 /// `dir` need not be normalised. Each grid's ray is transformed
657 /// into the grid's local frame (so rotated / translated grids are
658 /// handled exactly) and marched with a voxel DDA against
659 /// [`Grid::voxel_solid`]; the closest hit by world distance `t`
660 /// wins. The step budget is bounded by `max_dist`, so empty space
661 /// is safe but not free — a chunk-level skip is a future
662 /// optimisation if hot.
663 #[must_use]
664 pub fn raycast(&self, origin: DVec3, dir: DVec3, max_dist: f64) -> Option<RayHit> {
665 let len = dir.length();
666 if len < 1e-12 || max_dist <= 0.0 {
667 return None;
668 }
669 let dn = dir / len; // unit world direction → t is world distance
670 let mut best: Option<RayHit> = None;
671 for (id, grid) in self.grids() {
672 // World ray → grid-local: undo translation + rotation. The
673 // inverse rotation preserves length, so `t` stays in world
674 // units and is comparable across grids.
675 let inv = grid.transform.rotation.inverse();
676 let lo = inv * (origin - grid.transform.origin);
677 let ld = inv * dn;
678 if let Some((voxel, t)) = voxel_dda(grid, lo, ld, max_dist) {
679 if best.as_ref().map_or(true, |b| t < b.t) {
680 best = Some(RayHit {
681 grid: id,
682 voxel,
683 world: origin + dn * t,
684 t,
685 color: grid.voxel_color(voxel),
686 });
687 }
688 }
689 }
690 best
691 }
692
693 /// Configure the number of worker threads in the dedicated
694 /// streaming pool (S7.3).
695 ///
696 /// Lazily applied — the pool itself is constructed on the first
697 /// [`Self::pump_streaming`] call. If the pool was already built
698 /// (i.e. a previous `pump_streaming` already dispatched at
699 /// least one task), it gets dropped and rebuilt. Dropping the
700 /// old pool blocks until all of its in-flight tasks finish
701 /// (rayon's contract); any results those tasks sent are still
702 /// drained by the next `pump_streaming` because the channel
703 /// survives the rebuild.
704 ///
705 /// The streaming pool is separate from rayon's global pool
706 /// (which R12 multicore rendering uses), so chunk generation
707 /// doesn't compete with render threads. Sensible values are 1
708 /// to ~4 — generation work is CPU-bound but should leave most
709 /// of the box for everything else.
710 ///
711 /// On wasm32 this is a no-op (no rayon pool available);
712 /// `pump_streaming` runs synchronously there.
713 ///
714 /// # Panics
715 /// Panics on native if `n == 0` (zero-thread pools are not
716 /// supported; the scene crate's S7.1 helper already disallows
717 /// the equivalent for `StreamRadius::r_active < 0`).
718 #[cfg(not(target_arch = "wasm32"))]
719 pub fn set_streaming_threads(&mut self, n: usize) {
720 self.streaming.set_thread_count(n);
721 }
722
723 /// wasm32 no-op companion of [`Self::set_streaming_threads`].
724 /// Lets cross-target code call this unconditionally.
725 #[cfg(target_arch = "wasm32")]
726 pub fn set_streaming_threads(&mut self, _n: usize) {
727 // No streaming pool on wasm32 — see `pump_streaming` docs.
728 }
729
730 /// Asynchronous streaming pump (S7.3).
731 ///
732 /// On native, dispatches missing-chunk generations onto a
733 /// dedicated rayon pool, drains any results that arrived since
734 /// the last pump, runs the eviction pass, and tracks in-flight
735 /// tasks in each grid's [`Grid::pending_gen`] set. The drain
736 /// uses the per-chunk version counter from S7.2 to discard
737 /// results whose chunk was edited mid-generation.
738 ///
739 /// On wasm32 this short-circuits to [`Self::pump_streaming_sync`]
740 /// — no thread pool is available there, but the same per-grid
741 /// stream-in / evict semantics apply.
742 ///
743 /// Call once per frame from the render thread. Cheap when
744 /// nothing changed (early-exit on disabled grids, try_recv
745 /// loops empty fast).
746 pub fn pump_streaming(&mut self, camera_world_pos: DVec3) {
747 #[cfg(target_arch = "wasm32")]
748 {
749 self.pump_streaming_sync(camera_world_pos);
750 }
751 #[cfg(not(target_arch = "wasm32"))]
752 {
753 self.pump_streaming_native(camera_world_pos);
754 }
755 }
756
757 /// Native implementation of [`Self::pump_streaming`].
758 #[cfg(not(target_arch = "wasm32"))]
759 fn pump_streaming_native(&mut self, camera_world_pos: DVec3) {
760 // 1. Drain inbox — install fresh results, drop stale.
761 while let Ok(result) = self.streaming.rx.try_recv() {
762 let Some(grid) = self.grids.get_mut(&result.grid_id) else {
763 // Grid was removed while a generation task was
764 // in-flight. Drop silently.
765 continue;
766 };
767 // Clearing pending_gen here both for "result delivered"
768 // and "we shouldn't try to re-dispatch this chunk just
769 // because it's missing".
770 let was_pending = grid.pending_gen.remove(&result.chunk_idx);
771 if !was_pending {
772 // Either the chunk was evicted (pending cleared in
773 // the eviction pass below in some prior call), or a
774 // duplicate result for an already-handled chunk.
775 continue;
776 }
777 if grid.chunks.contains_key(&result.chunk_idx) {
778 // Some other path (e.g. `ensure_chunk_generated`
779 // sync helper, or a manual edit's `ensure_chunk`)
780 // already populated the slot. Don't overwrite.
781 continue;
782 }
783 if grid.chunk_version(result.chunk_idx) != result.version_at_dispatch {
784 // S7.2 stale-result discard: chunk was edited mid-
785 // generation.
786 continue;
787 }
788 grid.chunks.insert(result.chunk_idx, result.vxl);
789 // S7.4: same invalidation contract as the sync
790 // `ensure_chunk_generated` path — installing a new
791 // chunk can grow the bounding sphere, so the
792 // billboard impostor cache must be rebuilt on next
793 // Far entry. Lazy: only one cache wipe per drain
794 // batch, the Far render rebuilds afterwards.
795 grid.billboards = None;
796 }
797
798 // 2. Per-grid: eviction first, then dispatch. Doing evict
799 // before dispatch means a chunk that's just left
800 // r_active doesn't get re-dispatched on the same pump.
801 self.streaming.ensure_pool();
802 // Disjoint sub-field borrows: pool/tx via `&self.streaming.*`,
803 // grids via `&mut self.grids`. Hold both at once.
804 let pool: &rayon::ThreadPool = self.streaming.pool.as_ref().expect("ensure_pool just ran");
805 let tx_template = &self.streaming.tx;
806 for (grid_id, grid) in &mut self.grids {
807 evict_grid_chunks(grid, camera_world_pos);
808 dispatch_grid_async(*grid_id, grid, camera_world_pos, pool, tx_template);
809 }
810 }
811
812 /// Synchronous streaming pump (S7.1).
813 ///
814 /// For each grid with a non-[`StreamRadius::DISABLED`] policy:
815 /// 1. Project the world-space camera into grid-local coords
816 /// (inverse rotation + origin subtract).
817 /// 2. Stream in any chunk whose AABB-to-camera distance is
818 /// `<= r_active`, calling [`Grid::ensure_chunk_generated`].
819 /// No-ops gracefully if the grid has no generator attached
820 /// (so callers can use the eviction half of streaming on a
821 /// purely-edited grid).
822 /// 3. Evict any chunk whose AABB-to-camera distance exceeds
823 /// `r_evict` from the grid's chunk map. Eviction also
824 /// clears the cached [`BillboardCache`] (the bounding sphere
825 /// may shrink, invalidating impostor projections; the next
826 /// Far-tier render rebuilds lazily).
827 ///
828 /// Both passes use the f64 grid-local position so rotation +
829 /// non-axis-aligned grids stream and evict correctly. The
830 /// generate path is blocking — S7.3 will move it to a
831 /// background rayon pool with `pump_streaming` (non-blocking).
832 /// Callers that want the async variant in S7.0/S7.1 stages
833 /// should keep `r_active` small.
834 pub fn pump_streaming_sync(&mut self, camera_world_pos: DVec3) {
835 for grid in self.grids.values_mut() {
836 pump_grid_streaming_sync(grid, camera_world_pos);
837 }
838 }
839}
840
841/// S7.1 helper — drives one grid's synchronous streaming pass.
842/// Stream-in pass uses [`Grid::ensure_chunk_generated`] (blocking
843/// inline generation); eviction pass shared with the S7.3 async
844/// path through [`evict_grid_chunks`].
845fn pump_grid_streaming_sync(grid: &mut Grid, camera_world_pos: DVec3) {
846 let radius = grid.stream_radius;
847 if radius.is_disabled() {
848 return;
849 }
850 let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
851
852 // --- Pass 1: stream in active chunks (sync) ---------------
853 if radius.r_active > 0.0 && grid.generator.is_some() {
854 for_each_chunk_in_radius(cam_local, radius.r_active, |idx| {
855 grid.ensure_chunk_generated(idx);
856 });
857 }
858
859 // --- Pass 2: evict chunks past r_evict --------------------
860 evict_grid_chunks_with_cam(grid, cam_local);
861}
862
863/// Eviction pass shared by [`pump_grid_streaming_sync`] and the
864/// S7.3 async path. Public-ish so the async driver can call it
865/// before dispatching to avoid generating chunks that are about
866/// to be evicted. `cfg`-gated to native: on wasm32 the only
867/// caller (`pump_streaming_native`) doesn't compile, so this
868/// helper would warn as dead code.
869#[cfg(not(target_arch = "wasm32"))]
870fn evict_grid_chunks(grid: &mut Grid, camera_world_pos: DVec3) {
871 let radius = grid.stream_radius;
872 if radius.is_disabled() {
873 return;
874 }
875 let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
876 evict_grid_chunks_with_cam(grid, cam_local);
877}
878
879/// Eviction inner — assumes `cam_local` is already computed (the
880/// dispatcher and sync pump both have it on hand).
881fn evict_grid_chunks_with_cam(grid: &mut Grid, cam_local: DVec3) {
882 let radius = grid.stream_radius;
883 if !radius.r_evict.is_finite() {
884 return;
885 }
886 let r_sq = radius.r_evict * radius.r_evict;
887 let to_evict: Vec<IVec3> = grid
888 .chunks
889 .keys()
890 .filter(|&&idx| streaming::chunk_aabb_dist_sq(cam_local, idx) > r_sq)
891 .copied()
892 .collect();
893 // S7.3: also evict pending in-flight tasks past r_evict so the
894 // drain pass doesn't install a chunk that's no longer wanted.
895 // We don't have a way to cancel the rayon task, but we can
896 // drop the pending_gen entry so the result is dropped on
897 // arrival.
898 let to_evict_pending: Vec<IVec3> = grid
899 .pending_gen
900 .iter()
901 .filter(|&&idx| streaming::chunk_aabb_dist_sq(cam_local, idx) > r_sq)
902 .copied()
903 .collect();
904 if to_evict.is_empty() && to_evict_pending.is_empty() {
905 return;
906 }
907 for idx in &to_evict {
908 grid.chunks.remove(idx);
909 // S7.2: keep chunk_versions in sync with chunks so the
910 // map stays bounded. A future re-stream of the same idx
911 // restarts at 0 — that's fine because any in-flight
912 // gen-result tagged with the pre-eviction version is
913 // unreachable (no chunk to install onto) and gets
914 // discarded by the new "version still 0" check anyway.
915 grid.chunk_versions.remove(idx);
916 // S7.3: drop pending entry for the same chunk too. If a
917 // background task is still running, its result will be
918 // dropped on arrival (was_pending = false).
919 grid.pending_gen.remove(idx);
920 }
921 for idx in &to_evict_pending {
922 grid.pending_gen.remove(idx);
923 }
924 if !to_evict.is_empty() {
925 // Bounding sphere can shrink → impostor projections would
926 // be wrong on next Far render. Clear lazily; the next
927 // Far-tier pass repopulates via BillboardCache::build.
928 grid.billboards = None;
929 }
930}
931
932/// Walk every chunk index whose AABB falls within `r_active` of
933/// `cam_local` and invoke `f` on it. Shared between the S7.1 sync
934/// stream-in and the S7.3 async dispatch.
935fn for_each_chunk_in_radius<F>(cam_local: DVec3, r_active: f64, mut f: F)
936where
937 F: FnMut(IVec3),
938{
939 let r_sq = r_active * r_active;
940 let sxy = f64::from(CHUNK_SIZE_XY);
941 let sz = f64::from(CHUNK_SIZE_Z);
942 // Half-extent in chunk units; ceil to be conservative so any
943 // chunk whose AABB clips the radius gets considered. `+1`
944 // covers the half-open chunk-AABB upper edge plus the case
945 // where the camera sits exactly on a chunk boundary and the
946 // closest chunk is one index off.
947 #[allow(clippy::cast_possible_truncation)]
948 let r_chunks_xy = (r_active / sxy).ceil() as i32 + 1;
949 #[allow(clippy::cast_possible_truncation)]
950 let r_chunks_z = (r_active / sz).ceil() as i32 + 1;
951 #[allow(clippy::cast_possible_truncation)]
952 let cx_chunk = (cam_local.x / sxy).floor() as i32;
953 #[allow(clippy::cast_possible_truncation)]
954 let cy_chunk = (cam_local.y / sxy).floor() as i32;
955 #[allow(clippy::cast_possible_truncation)]
956 let cz_chunk = (cam_local.z / sz).floor() as i32;
957 for chz in (cz_chunk - r_chunks_z)..=(cz_chunk + r_chunks_z) {
958 for chy in (cy_chunk - r_chunks_xy)..=(cy_chunk + r_chunks_xy) {
959 for chx in (cx_chunk - r_chunks_xy)..=(cx_chunk + r_chunks_xy) {
960 let idx = IVec3::new(chx, chy, chz);
961 if streaming::chunk_aabb_dist_sq(cam_local, idx) <= r_sq {
962 f(idx);
963 }
964 }
965 }
966 }
967}
968
969/// S7.3 async dispatch — schedule generation for every chunk in
970/// `r_active` that's not already present and not already in
971/// flight. Each dispatch clones the grid's generator `Arc` and a
972/// sender clone, then spawns the closure on the streaming rayon
973/// pool. The closure does the generate + send; the main thread
974/// drains results on the next pump.
975#[cfg(not(target_arch = "wasm32"))]
976fn dispatch_grid_async(
977 grid_id: GridId,
978 grid: &mut Grid,
979 camera_world_pos: DVec3,
980 pool: &rayon::ThreadPool,
981 tx: &crossbeam_channel::Sender<streaming::ChunkResult>,
982) {
983 let radius = grid.stream_radius;
984 if radius.is_disabled() || radius.r_active <= 0.0 {
985 return;
986 }
987 let Some(generator) = grid.generator.as_ref().map(Arc::clone) else {
988 return;
989 };
990 let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
991 for_each_chunk_in_radius(cam_local, radius.r_active, |idx| {
992 if grid.chunks.contains_key(&idx) {
993 return; // already present
994 }
995 if grid.pending_gen.contains(&idx) {
996 return; // already in flight
997 }
998 // S7.6+: respect the generator's per-chunk filter — same
999 // contract as `Grid::ensure_chunk_generated` (sync helper).
1000 // Lets a generator decline to materialise specific indices
1001 // (e.g. `HillsChunkGenerator` skipping placeholder bedrock
1002 // chunks at chz != 0 so the camera-above-grid path doesn't
1003 // create chz < 0 entries that would shift `origin_chunk_z`
1004 // and trigger the S4B.6.j cross-chunk look-down bug).
1005 if !generator.should_generate(idx) {
1006 return;
1007 }
1008 grid.pending_gen.insert(idx);
1009 let version_at_dispatch = grid.chunk_version(idx);
1010 let tx_clone = tx.clone();
1011 let gen_clone = Arc::clone(&generator);
1012 pool.spawn(move || {
1013 let vxl = gen_clone.generate(idx);
1014 // Send is non-blocking on unbounded channel; if the
1015 // receiver was dropped (Scene drop), the send fails
1016 // silently — that's fine.
1017 let _ = tx_clone.send(streaming::ChunkResult {
1018 grid_id,
1019 chunk_idx: idx,
1020 version_at_dispatch,
1021 vxl,
1022 });
1023 });
1024 });
1025}
1026
1027#[cfg(test)]
1028mod tests {
1029 use super::*;
1030
1031 #[test]
1032 fn empty_scene_has_no_grids() {
1033 let scene = Scene::new();
1034 assert_eq!(scene.grid_count(), 0);
1035 assert!(scene.grids().next().is_none());
1036 }
1037
1038 #[test]
1039 fn raycast_hits_axis_aligned_voxel() {
1040 let mut scene = Scene::new();
1041 let id = scene.add_grid(GridTransform::identity());
1042 scene
1043 .grid_mut(id)
1044 .unwrap()
1045 .set_voxel(IVec3::new(5, 5, 10), Some(0x80_aa_bb_cc));
1046
1047 // Straight down the +z column through (5,5): hits z=10 at t≈10.
1048 let hit = scene
1049 .raycast(DVec3::new(5.5, 5.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1050 .expect("ray hits the voxel");
1051 assert_eq!(hit.grid, id);
1052 assert_eq!(hit.voxel, IVec3::new(5, 5, 10));
1053 assert!((hit.t - 10.0).abs() < 1e-6, "t≈10, got {}", hit.t);
1054 assert!(hit.color.is_some(), "textured voxel has a colour");
1055
1056 // A column with no voxel misses.
1057 assert!(
1058 scene
1059 .raycast(DVec3::new(0.5, 0.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1060 .is_none(),
1061 "empty column → no hit",
1062 );
1063 }
1064
1065 #[test]
1066 fn raycast_respects_grid_transform() {
1067 // A translated grid: the hit voxel is reported in GRID-LOCAL
1068 // coords, and the world hit point is back in world space — so a
1069 // host gets the true voxel regardless of where the grid sits.
1070 let mut scene = Scene::new();
1071 let id = scene.add_grid(GridTransform::at(DVec3::new(100.0, 0.0, 0.0)));
1072 scene
1073 .grid_mut(id)
1074 .unwrap()
1075 .set_voxel(IVec3::new(5, 5, 10), Some(0x80_11_22_33));
1076
1077 let hit = scene
1078 .raycast(DVec3::new(105.5, 5.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1079 .expect("ray hits the translated voxel");
1080 assert_eq!(hit.voxel, IVec3::new(5, 5, 10), "grid-local voxel");
1081 assert!((hit.world.x - 105.5).abs() < 1e-6, "world x preserved");
1082 assert!((hit.t - 10.0).abs() < 1e-6, "t≈10, got {}", hit.t);
1083 }
1084
1085 #[test]
1086 fn raycast_picks_nearest_grid() {
1087 // Two grids with a voxel each along the same world column; the
1088 // raycast must return the closer one.
1089 let mut scene = Scene::new();
1090 let near = scene.add_grid(GridTransform::identity());
1091 let far = scene.add_grid(GridTransform::identity());
1092 scene
1093 .grid_mut(near)
1094 .unwrap()
1095 .set_voxel(IVec3::new(1, 1, 20), Some(0x80_00_ff_00));
1096 scene
1097 .grid_mut(far)
1098 .unwrap()
1099 .set_voxel(IVec3::new(1, 1, 40), Some(0x80_ff_00_00));
1100
1101 let hit = scene
1102 .raycast(DVec3::new(1.5, 1.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1103 .expect("hits the nearer voxel");
1104 assert_eq!(hit.grid, near);
1105 assert_eq!(hit.voxel, IVec3::new(1, 1, 20));
1106 }
1107
1108 #[test]
1109 fn add_grid_returns_fresh_ids() {
1110 let mut scene = Scene::new();
1111 let a = scene.add_grid(GridTransform::identity());
1112 let b = scene.add_grid(GridTransform::at(DVec3::new(100.0, 0.0, 0.0)));
1113 assert_ne!(a, b);
1114 assert_eq!(a.raw(), 0);
1115 assert_eq!(b.raw(), 1);
1116 assert_eq!(scene.grid_count(), 2);
1117 }
1118
1119 #[test]
1120 fn grid_lookup_round_trips() {
1121 let mut scene = Scene::new();
1122 let id = scene.add_grid(GridTransform::at(DVec3::new(10.0, 20.0, 30.0)));
1123 let g = scene.grid(id).expect("grid registered");
1124 assert_eq!(g.transform.origin, DVec3::new(10.0, 20.0, 30.0));
1125 assert_eq!(g.transform.rotation, DQuat::IDENTITY);
1126 assert!(g.chunks.is_empty());
1127 }
1128
1129 #[test]
1130 fn remove_grid_drops_it_from_scene() {
1131 let mut scene = Scene::new();
1132 let id = scene.add_grid(GridTransform::identity());
1133 let removed = scene.remove_grid(id);
1134 assert!(removed.is_some());
1135 assert_eq!(scene.grid_count(), 0);
1136 assert!(scene.grid(id).is_none());
1137 // Re-adding does NOT reuse the dropped id.
1138 let id2 = scene.add_grid(GridTransform::identity());
1139 assert_ne!(id, id2);
1140 assert_eq!(id2.raw(), 1);
1141 }
1142
1143 #[test]
1144 fn remove_unknown_grid_is_none() {
1145 let mut scene = Scene::new();
1146 let bogus = GridId(999);
1147 assert!(scene.remove_grid(bogus).is_none());
1148 }
1149
1150 #[test]
1151 fn grid_mut_can_modify_transform() {
1152 let mut scene = Scene::new();
1153 let id = scene.add_grid(GridTransform::identity());
1154 scene.grid_mut(id).unwrap().transform.origin = DVec3::new(1.0, 2.0, 3.0);
1155 assert_eq!(
1156 scene.grid(id).unwrap().transform.origin,
1157 DVec3::new(1.0, 2.0, 3.0)
1158 );
1159 }
1160
1161 #[test]
1162 fn chunk_size_constants_match_plan() {
1163 // Plan locks these values; bumping either breaks the slab
1164 // byte format (Z) or the worst-case chunk footprint budget
1165 // (XY). Pin them so a future refactor that drifts them
1166 // shows up in CI.
1167 assert_eq!(CHUNK_SIZE_XY, 128);
1168 assert_eq!(CHUNK_SIZE_Z, 256);
1169 }
1170
1171 // ---- S6.0: bounding_radius + Grid::select_lod ----
1172
1173 #[test]
1174 fn new_grid_defaults_to_always_near_lod() {
1175 // Byte-identity contract for the staged S6 rollout: a
1176 // grid built through `new` must never trigger the Mid/Far
1177 // branches by accident, even when bounding_radius would
1178 // imply otherwise.
1179 let g = Grid::new(GridTransform::identity());
1180 assert_eq!(g.lod_thresholds.r_near, f64::INFINITY);
1181 assert_eq!(g.lod_thresholds.r_mid, f64::INFINITY);
1182 assert_eq!(g.select_lod(DVec3::new(1e9, 0.0, 0.0)), Lod::Near);
1183 }
1184
1185 #[test]
1186 fn bounding_radius_empty_grid_is_zero() {
1187 let g = Grid::new(GridTransform::identity());
1188 assert_eq!(g.bounding_radius(), 0.0);
1189 }
1190
1191 #[test]
1192 fn bounding_radius_single_chunk_at_origin() {
1193 // One chunk at (0, 0, 0): bbox is [0, 128) × [0, 128) × [0, 256).
1194 // Half-extent = (64, 64, 128); length = sqrt(64² + 64² + 128²)
1195 // = sqrt(4096 + 4096 + 16384) = sqrt(24576) ≈ 156.7747...
1196 let mut scene = Scene::new();
1197 let id = scene.add_grid(GridTransform::identity());
1198 let g = scene.grid_mut(id).unwrap();
1199 // Populate chunk (0, 0, 0) via the edit API.
1200 g.set_voxel(IVec3::new(0, 0, 0), Some(0x80_88_88_88));
1201 let r = g.bounding_radius();
1202 let expected = ((64.0_f64).powi(2) * 2.0 + (128.0_f64).powi(2)).sqrt();
1203 assert!(
1204 (r - expected).abs() < 1e-9,
1205 "bounding_radius={r} expected={expected}"
1206 );
1207 }
1208
1209 #[test]
1210 fn bounding_radius_grows_with_chunk_extent() {
1211 // Two chunks at (0,0,0) and (3,0,0): x extent is 4 chunks =
1212 // 512 voxels; y/z are 1 chunk each. Half-extent = (256, 64, 128);
1213 // length = sqrt(256² + 64² + 128²) = sqrt(65536+4096+16384)
1214 // = sqrt(86016) ≈ 293.2848.
1215 let mut scene = Scene::new();
1216 let id = scene.add_grid(GridTransform::identity());
1217 let g = scene.grid_mut(id).unwrap();
1218 // Stamp one voxel in chunk (0,0,0).
1219 g.set_voxel(IVec3::new(0, 0, 0), Some(0x80_88_88_88));
1220 // Stamp one voxel in chunk (3,0,0): grid-local x = 3*128 = 384.
1221 g.set_voxel(IVec3::new(384, 0, 0), Some(0x80_88_88_88));
1222 assert_eq!(g.chunks.len(), 2);
1223 let r = g.bounding_radius();
1224 let expected = (256.0_f64.powi(2) + 64.0_f64.powi(2) + 128.0_f64.powi(2)).sqrt();
1225 assert!(
1226 (r - expected).abs() < 1e-9,
1227 "bounding_radius={r} expected={expected}"
1228 );
1229 }
1230
1231 #[test]
1232 fn grid_select_lod_respects_lod_thresholds_field() {
1233 // Set a non-default threshold and verify the helper picks
1234 // the right tier for known distances.
1235 let mut scene = Scene::new();
1236 let id = scene.add_grid(GridTransform::at(DVec3::new(100.0, 0.0, 0.0)));
1237 let g = scene.grid_mut(id).unwrap();
1238 g.lod_thresholds = LodThresholds {
1239 r_near: 50.0,
1240 r_mid: 200.0,
1241 ..LodThresholds::always_near()
1242 };
1243 // Camera 25 units from grid origin → Near.
1244 assert_eq!(g.select_lod(DVec3::new(125.0, 0.0, 0.0)), Lod::Near);
1245 // 100 units → Mid.
1246 assert_eq!(g.select_lod(DVec3::new(200.0, 0.0, 0.0)), Lod::Mid);
1247 // 500 units → Far.
1248 assert_eq!(g.select_lod(DVec3::new(600.0, 0.0, 0.0)), Lod::Far);
1249 }
1250}