Skip to main content

roxlap_scene/
lib.rs

1//! roxlap scene-graph layer — many independent chunked voxel
2//! grids in a single 3D scene.
3//!
4//! New to roxlap? **[The roxlap book](https://ncrashed.github.io/roxlap/)**
5//! is the guide — its scene-graph chapter walks this crate end to end;
6//! this page is the API reference.
7//!
8//! This crate is the layer **above** the per-chunk renderer
9//! (`roxlap-core`): a [`Scene`] holds a sparse set of [`Grid`]s, each
10//! with its own f64 world position + arbitrary 3D rotation
11//! ([`GridTransform`]). Around that core sit:
12//!
13//! - [`addr`] — world ↔ grid-local ↔ chunk + voxel-in-chunk
14//!   decomposition, the canonical f64↔i32 boundary helpers;
15//! - [`chunks`] — sparse chunk storage with on-demand materialisation,
16//!   plus the [`Grid`] edit API ([`Grid::set_voxel`],
17//!   [`Grid::set_rect`], [`Grid::set_sphere`], …) which decomposes
18//!   multi-chunk operations and delegates to [`roxlap_formats::edit`];
19//! - [`render`] — multi-grid raycast composition for the CPU renderer;
20//! - [`snapshot`] — save/load: the versioned wire format
21//!   ([`Scene::save_snapshot`] / [`Scene::load_snapshot`], QE.5b)
22//!   plus the underlying serde-friendly [`snapshot::SceneSnapshot`]
23//!   value (chunks encode via [`roxlap_formats::vxl::serialize`] /
24//!   [`parse`]);
25//! - [`streaming`] — chunk streaming + procedural generation
26//!   ([`streaming::ChunkGenerator`], radius-driven install/evict,
27//!   async generation on a rayon pool) and persistence for edited
28//!   chunks ([`streaming::ChunkStore`], QE.5a);
29//! - [`lod`] / [`billboard`] / [`occluder`] — far-LOD billboards and
30//!   render culling helpers;
31//! - world queries — [`Scene::raycast`], [`Scene::resolve_voxel`],
32//!   [`Grid::voxel_solid`] / [`Grid::voxel_color`].
33//!
34//! `docs/porting/PORTING-SCENE.md` in the repository records the
35//! original substage roadmap (S1..S7, all landed).
36//!
37//! [`parse`]: roxlap_formats::vxl::parse
38
39pub mod addr;
40pub mod billboard;
41pub mod cavegen;
42/// Character controller (stage CC) — a walking body over the scene;
43/// see `docs/porting/PORTING-CONTROLLER.md`.
44pub mod character;
45pub mod chunks;
46/// Collision query layer (stage CC) — box-vs-voxel overlap over a
47/// scene; see `docs/porting/PORTING-CONTROLLER.md`.
48pub mod collide;
49pub mod edit;
50pub mod lod;
51pub mod occluder;
52pub mod render;
53pub mod snapshot;
54pub mod streaming;
55
56use std::collections::{HashMap, HashSet};
57use std::sync::Arc;
58
59use glam::{DQuat, DVec3, IVec3, UVec3};
60use roxlap_formats::vxl::Vxl;
61use serde::{Deserialize, Serialize};
62
63pub use addr::{grid_local_to_world, voxel_global, voxel_split, world_to_grid_local, GridLocalPos};
64pub use billboard::{canonical_viewpoints, BillboardCache, BillboardSnapshot};
65pub use character::{CharacterBody, CharacterDef, MoveMode, WalkInput};
66pub use chunks::{BakeLight, BakeMode};
67pub use collide::{box_overlaps_solid, grid_box_overlaps_solid, point_overlaps_solid, Solidity};
68pub use edit::SpanOp;
69pub use lod::{select_lod, Lod, LodThresholds};
70pub use roxlap_core::AoParams;
71pub use roxlap_formats::color::{OverlayColor, Rgb, VoxColor};
72pub use streaming::{ChunkGenerator, ChunkStore, StreamRadius};
73
74/// XY size of one chunk in voxels. The plan locks 128 — keeps
75/// chunks compact (~2 MB worst-case dense-slab footprint inside
76/// each `Vxl`) and divides cleanly into voxlap's 2048 reference
77/// world size.
78pub const CHUNK_SIZE_XY: u32 = 128;
79
80/// Z size of one chunk in voxels. Locked at 256 to preserve
81/// voxlap's existing slab byte format unchanged inside each chunk
82/// — the per-chunk renderer doesn't need to know it's living
83/// inside a scene-graph.
84pub const CHUNK_SIZE_Z: u32 = 256;
85
86/// Stable identifier for a grid registered in a [`Scene`]. Issued
87/// by [`Scene::add_grid`]; persists across edits but a removed
88/// grid's id is not reissued.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
90pub struct GridId(u32);
91
92impl GridId {
93    /// The integer wire form. Useful for serde / debug output.
94    #[must_use]
95    pub const fn raw(self) -> u32 {
96        self.0
97    }
98}
99
100/// A solid-voxel hit from [`Scene::raycast`].
101#[derive(Debug, Clone, Copy, PartialEq)]
102pub struct RayHit {
103    /// The grid the ray hit.
104    pub grid: GridId,
105    /// Grid-local integer voxel coordinate of the hit cell.
106    pub voxel: IVec3,
107    /// World-space hit point (`origin + t · normalize(dir)`).
108    pub world: DVec3,
109    /// World distance from the ray origin to the hit.
110    pub t: f64,
111    /// Packed colour of the hit voxel, or `None` if it's an untextured
112    /// (bedrock / interior) cell. See [`Grid::voxel_color`].
113    pub color: Option<VoxColor>,
114}
115
116/// Ray/AABB slab intersection in f64 (`[lo, hi)` box). Returns the
117/// entry/exit ray parameters, or `None` on a miss. PF.6 helper for the
118/// raycast pre-clip + absent-chunk exit.
119fn ray_box(o: DVec3, d: DVec3, blo: DVec3, bhi: DVec3) -> Option<(f64, f64)> {
120    let mut tmin = f64::NEG_INFINITY;
121    let mut tmax = f64::INFINITY;
122    for a in 0..3 {
123        if d[a].abs() < 1e-12 {
124            if o[a] < blo[a] || o[a] > bhi[a] {
125                return None;
126            }
127        } else {
128            let inv = 1.0 / d[a];
129            let (t0, t1) = ((blo[a] - o[a]) * inv, (bhi[a] - o[a]) * inv);
130            tmin = tmin.max(t0.min(t1));
131            tmax = tmax.min(t0.max(t1));
132            if tmin > tmax {
133                return None;
134            }
135        }
136    }
137    Some((tmin, tmax))
138}
139
140/// The populated chunk extent of `grid` as a grid-local voxel-space AABB
141/// `[lo, hi)`, or `None` for an empty grid. O(chunks) HashMap key walk —
142/// fine for per-call raycast use.
143fn grid_voxel_aabb_f64(grid: &Grid) -> Option<(DVec3, DVec3)> {
144    let mut min = IVec3::splat(i32::MAX);
145    let mut max = IVec3::splat(i32::MIN);
146    let mut any = false;
147    for idx in grid.chunks.keys() {
148        any = true;
149        min = min.min(*idx);
150        max = max.max(*idx);
151    }
152    if !any {
153        return None;
154    }
155    let (cs_xy, cs_z) = (
156        i64::from(CHUNK_SIZE_XY as i32),
157        i64::from(CHUNK_SIZE_Z as i32),
158    );
159    #[allow(clippy::cast_precision_loss)]
160    let v = |i: IVec3, add: i64| {
161        DVec3::new(
162            ((i64::from(i.x) + add) * cs_xy) as f64,
163            ((i64::from(i.y) + add) * cs_xy) as f64,
164            ((i64::from(i.z) + add) * cs_z) as f64,
165        )
166    };
167    Some((v(min, 0), v(max, 1)))
168}
169
170/// Voxel DDA (Amanatides-Woo) in a grid's local space. `lo` / `ld` are
171/// the ray origin + unit direction already transformed into grid-local
172/// coords. Returns the first [`Grid::voxel_solid`] cell and its world-
173/// equal distance `t`, or `None` past `max_t`.
174///
175/// PF.6 — three upgrades over the naive from-origin march:
176/// - the ray is pre-clipped to the grid's populated chunk AABB (a miss
177///   costs one slab test; a distant grid is marched AT the box, not from
178///   the origin);
179/// - chunk lookups go through the chunk-cached [`SolidSampler`]-style
180///   probe (one HashMap hit per chunk crossing) and the solid test walks
181///   the slab chain in place (no per-step allocation);
182/// - a voxel in an absent (all-air) chunk fast-forwards the march to
183///   that chunk's exit face instead of stepping its up-to-128 voxels.
184#[allow(clippy::cast_possible_truncation)]
185fn voxel_dda(grid: &Grid, lo: DVec3, ld: DVec3, max_t: f64) -> Option<(IVec3, f64)> {
186    // Clip to the populated chunk AABB: everything outside is air.
187    let (blo, bhi) = grid_voxel_aabb_f64(grid)?;
188    let (t0, t1) = ray_box(lo, ld, blo, bhi)?;
189    let t_enter = t0.max(0.0);
190    let t_exit = t1.min(max_t);
191    if t_enter > t_exit {
192        return None;
193    }
194
195    let step = IVec3::new(
196        i32::from(ld.x > 0.0) - i32::from(ld.x < 0.0),
197        i32::from(ld.y > 0.0) - i32::from(ld.y < 0.0),
198        i32::from(ld.z > 0.0) - i32::from(ld.z < 0.0),
199    );
200    // Distance to advance one whole voxel along each axis (∞ if parallel).
201    let inv_abs = |d: f64| {
202        if d == 0.0 {
203            f64::INFINITY
204        } else {
205            (1.0 / d).abs()
206        }
207    };
208    let t_delta = DVec3::new(inv_abs(ld.x), inv_abs(ld.y), inv_abs(ld.z));
209    // Absolute-`t` of the next voxel boundary from cell `p`, per axis
210    // (also the re-seed after an absent-chunk jump).
211    let seed_t_max = |p: IVec3| -> DVec3 {
212        let axis = |pa: i32, oa: f64, da: f64| -> f64 {
213            if da > 0.0 {
214                (f64::from(pa) + 1.0 - oa) / da
215            } else if da < 0.0 {
216                (f64::from(pa) - oa) / da
217            } else {
218                f64::INFINITY
219            }
220        };
221        DVec3::new(
222            axis(p.x, lo.x, ld.x),
223            axis(p.y, lo.y, ld.y),
224            axis(p.z, lo.z, ld.z),
225        )
226    };
227
228    // Start at the AABB entry (t stays measured from the true origin;
229    // t_enter == 0 ⇒ the original from-origin start, bit-identical).
230    let start = lo + ld * t_enter;
231    let mut p = IVec3::new(
232        start.x.floor() as i32,
233        start.y.floor() as i32,
234        start.z.floor() as i32,
235    );
236    let mut t_max = seed_t_max(p);
237    let mut t_curr = t_enter;
238    let mut sampler = grid.solid_sampler();
239
240    #[allow(clippy::cast_sign_loss)]
241    let max_steps = (max_t * 3.0) as u64 + 8;
242    let (cs_xy, cs_z) = (
243        f64::from(CHUNK_SIZE_XY as i32),
244        f64::from(CHUNK_SIZE_Z as i32),
245    );
246    for _ in 0..max_steps {
247        let (chunk_idx, in_chunk) = voxel_split(p);
248        if let Some(vxl) = sampler.chunk_at(chunk_idx) {
249            if chunks::vxl_voxel_solid(vxl, in_chunk.x, in_chunk.y, in_chunk.z) {
250                return Some((p, t_curr));
251            }
252            // Advance across the nearest voxel boundary.
253            let t = if t_max.x <= t_max.y && t_max.x <= t_max.z {
254                p.x += step.x;
255                let t = t_max.x;
256                t_max.x += t_delta.x;
257                t
258            } else if t_max.y <= t_max.z {
259                p.y += step.y;
260                let t = t_max.y;
261                t_max.y += t_delta.y;
262                t
263            } else {
264                p.z += step.z;
265                let t = t_max.z;
266                t_max.z += t_delta.z;
267                t
268            };
269            if t > t_exit {
270                return None;
271            }
272            t_curr = t;
273        } else {
274            // Absent chunk ⇒ guaranteed air: jump to its exit face.
275            let clo = DVec3::new(
276                f64::from(chunk_idx.x) * cs_xy,
277                f64::from(chunk_idx.y) * cs_xy,
278                f64::from(chunk_idx.z) * cs_z,
279            );
280            let chi = clo + DVec3::new(cs_xy, cs_xy, cs_z);
281            let exit = match ray_box(lo, ld, clo, chi) {
282                // Nudge past the face so the floor lands in the next chunk.
283                Some((_, t1)) => t1.max(t_curr) + 1e-4,
284                None => return None, // degenerate (shouldn't happen: p is inside)
285            };
286            if exit > t_exit {
287                return None;
288            }
289            let q = lo + ld * exit;
290            p = IVec3::new(q.x.floor() as i32, q.y.floor() as i32, q.z.floor() as i32);
291            t_max = seed_t_max(p);
292            t_curr = exit;
293        }
294    }
295    None
296}
297
298/// f64 world placement of one grid: position + orientation.
299///
300/// `origin` is the grid's local-space origin in world coords — a
301/// grid-local point `p` (in voxel units) maps to
302/// `origin + rotation * (p * voxel_world_size)`.
303///
304/// SC — `voxel_world_size` is the grid's **world units per voxel**
305/// (`1.0` = the classic 1:1). A coarse planet grid might use `4.0`
306/// (big voxels) and a finely detailed ship `0.25`, so they coexist at
307/// the right relative sizes in one scene. The scale enters ONLY at the
308/// world↔grid-local boundary (`crate::world_to_grid_local` /
309/// `crate::grid_local_to_world`, `Scene::raycast`, shadows); the
310/// per-grid voxel storage, marchers and bakes are scale-agnostic. Only
311/// a uniform scalar is supported (anisotropic scale would break the
312/// ray-length invariant the raycast/shadow `t` conversion relies on).
313#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
314pub struct GridTransform {
315    /// The grid's local-space origin, in world coordinates.
316    pub origin: DVec3,
317    /// The grid's orientation about `origin`.
318    pub rotation: DQuat,
319    /// SC — world units per voxel (`1.0` = 1:1). See the type docs.
320    /// **`#[serde(skip)]`**: this field is NOT part of `GridTransform`'s
321    /// wire form (which stays frozen for snapshot back-compat). The
322    /// snapshot persists it as a trailing field on
323    /// [`crate::snapshot::GridSnapshot`] instead, so old saves — which
324    /// predate it — still load (defaulting to `1.0`). A standalone
325    /// `GridTransform` deserialize also defaults it to `1.0`.
326    #[serde(skip, default = "one_f64")]
327    pub voxel_world_size: f64,
328}
329
330/// serde default for [`GridTransform::voxel_world_size`].
331fn one_f64() -> f64 {
332    1.0
333}
334
335impl GridTransform {
336    /// Identity transform at world origin, 1 world unit per voxel.
337    /// Useful as a default for the first grid added to an otherwise
338    /// empty scene.
339    #[must_use]
340    pub fn identity() -> Self {
341        Self {
342            origin: DVec3::ZERO,
343            rotation: DQuat::IDENTITY,
344            voxel_world_size: 1.0,
345        }
346    }
347
348    /// Axis-aligned grid placed at `origin` with no rotation, 1 world
349    /// unit per voxel.
350    #[must_use]
351    pub fn at(origin: DVec3) -> Self {
352        Self {
353            origin,
354            rotation: DQuat::IDENTITY,
355            voxel_world_size: 1.0,
356        }
357    }
358
359    /// SC — axis-aligned grid at `origin` with `voxel_world_size` world
360    /// units per voxel (no rotation). `1.0` = the classic 1:1.
361    ///
362    /// `voxel_world_size` must be finite and `> 0`: it scales every
363    /// world↔grid boundary, and a `0` collapses the GPU marcher's
364    /// `chunk_dim` to zero → `floor(origin / 0)` = NaN (garbage geometry),
365    /// worse than the CPU's divide. Debug-asserted here; release builds
366    /// trust the caller.
367    #[must_use]
368    pub fn at_scale(origin: DVec3, voxel_world_size: f64) -> Self {
369        debug_assert!(
370            voxel_world_size.is_finite() && voxel_world_size > 0.0,
371            "voxel_world_size must be finite and > 0, got {voxel_world_size}"
372        );
373        Self {
374            origin,
375            rotation: DQuat::IDENTITY,
376            voxel_world_size,
377        }
378    }
379}
380
381impl Default for GridTransform {
382    fn default() -> Self {
383        Self::identity()
384    }
385}
386
387/// Address of one voxel inside a scene: which grid it belongs to,
388/// which chunk within that grid, and the voxel's offset inside
389/// that chunk.
390///
391/// `chunk` is signed (`IVec3`) because chunks are centred on the
392/// grid's local origin and may extend in either direction. `voxel`
393/// is unsigned and must satisfy
394/// `(voxel.x, voxel.y) < CHUNK_SIZE_XY` and `voxel.z < CHUNK_SIZE_Z`.
395#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
396pub struct GridAddr {
397    /// The owning grid.
398    pub grid: GridId,
399    /// Signed chunk index within the grid.
400    pub chunk: IVec3,
401    /// Voxel offset inside `chunk` (see the bounds above).
402    pub voxel: UVec3,
403}
404
405/// One independent voxel grid in a scene. Holds its world placement
406/// and a sparse map of populated chunks. Empty chunk slots are
407/// implicit air and skipped during rendering / raycasts.
408///
409/// Each chunk is internally a [`Vxl`] with `vsid = CHUNK_SIZE_XY`
410/// — the existing per-chunk renderer (opticast + grouscan +
411/// sprites + lighting in `roxlap-core`) runs on each chunk
412/// unchanged. Vertical worlds are built by stacking chunks along
413/// grid-local `+z`.
414#[derive(Debug)]
415pub struct Grid {
416    /// World placement (origin + rotation).
417    pub transform: GridTransform,
418    /// Sparse chunk storage keyed by `(chx, chy, chz)` chunk
419    /// coordinates. A missing entry means the chunk is fully air.
420    pub chunks: HashMap<IVec3, Vxl>,
421    /// Whether sky pixels rendered for this grid should be
422    /// composited into the final framebuffer. `true` is the
423    /// historical "grid owns its own sky" behaviour: ray misses
424    /// inside this grid's frustum paint sky_color into the temp
425    /// buffer. Set `false` for grids that are a foreground object
426    /// (e.g. a ship) — the sky is owned by a single "world" grid
427    /// (the ground) and other grids should not contribute sky
428    /// pixels, otherwise their grid-local-frame sky lookup
429    /// rotates with the grid and visibly fights the world's sky
430    /// during compose. See [`crate::render::render_scene_composed`]
431    /// for the masking implementation.
432    pub render_sky: bool,
433    /// Override [`roxlap_core::opticast::OpticastSettings::mip_levels`]
434    /// for this grid. `None` ⇒ use the caller's value. `Some(n)`
435    /// ⇒ cap at `n` (clamped to `[1, settings.mip_levels]`). Use
436    /// to disable multi-mip on a per-grid basis — small grids
437    /// (rotating ships, billboards) don't benefit from deep mips
438    /// and CAN trigger the
439    /// `[[project_axis_aligned_mip_beams]]`-style cf-cancellation
440    /// artifact when near-axis-aligned rays hit the rotated grid.
441    /// `Some(1)` = mip-0 only, byte-stable to single-mip.
442    pub mip_levels_override: Option<u32>,
443    /// World-distance thresholds for per-grid LOD tier selection
444    /// (S6.0). Defaults to [`LodThresholds::always_near`], so a
445    /// freshly-constructed grid always renders at full voxel (the
446    /// S5-and-earlier byte-stable behaviour). S6.1 plugs `Mid` into
447    /// the existing multi-mip path; S6.3 plugs `Far` into the
448    /// billboard impostor cache. See [`crate::lod`].
449    pub lod_thresholds: LodThresholds,
450    /// Lazy [`BillboardCache`] for the `Lod::Far` tier (S6.2).
451    /// `None` until the first time S6.3's render dispatch needs
452    /// it; populated then via [`BillboardCache::build`] and
453    /// cleared by edits ([`Self::set_voxel`] / [`Self::set_rect`]
454    /// / [`Self::set_sphere`]) to force a rebuild on next Far use.
455    /// Callers may also force-invalidate via direct assignment.
456    pub billboards: Option<BillboardCache>,
457    /// Optional procedural generator (S7.0). When set,
458    /// [`Self::ensure_chunk_generated`] uses it to materialise
459    /// chunks that are still absent from [`Self::chunks`].
460    ///
461    /// Streaming layers (S7.1+) walk the active radius around the
462    /// camera and call `ensure_chunk_generated` for missing chunks;
463    /// later stages dispatch this onto a background rayon pool. The
464    /// trait bound is `Send + Sync` (needed for S7.3 async
465    /// dispatch) + `Debug` (needed so [`Grid`] keeps deriving
466    /// `Debug`).
467    ///
468    /// `None` is the default — a grid without a generator behaves
469    /// exactly like the pre-S7 grids: absent chunks stay absent.
470    ///
471    /// `Arc` (not `Box`) so S7.3's async dispatch can clone the
472    /// generator into background rayon tasks without moving it out
473    /// of the grid. Trait bound `Send + Sync` (required at S7.0)
474    /// already makes `Arc<dyn ChunkGenerator>` `Send + Sync`.
475    pub generator: Option<Arc<dyn ChunkGenerator>>,
476    /// QE.5b - optional host-assigned tag, carried through snapshots.
477    /// Grid ids are runtime-opaque, so a save/load cycle gives hosts
478    /// nothing to rebind their own per-grid data (generators, stores,
479    /// gameplay state) against; a stable name closes that gap. Not
480    /// interpreted by the engine.
481    pub name: Option<String>,
482    /// QE.5a - optional persistence for edited streamed chunks: the
483    /// eviction pass hands every `chunk_version != 0` chunk to
484    /// [`ChunkStore::store`] before dropping it, and stream-in asks
485    /// [`ChunkStore::load`] before running the generator. `None` (the
486    /// default) keeps the pre-QE.5 behaviour: evicting an edited
487    /// chunk discards the edits.
488    pub store: Option<Arc<dyn ChunkStore>>,
489    /// Streaming activity / eviction radii used by
490    /// [`Scene::pump_streaming_sync`] (S7.1). Defaults to
491    /// [`StreamRadius::DISABLED`] so existing grids see no change
492    /// in behaviour until the caller opts in.
493    pub stream_radius: StreamRadius,
494    /// EV.3 — baked point lights ([`BakeLight`], grid-local voxel
495    /// coords) consumed by [`BakeMode::PointLights`]: [`Grid::bake`]
496    /// and [`Grid::bake_bbox`] write each light's Lambertian pool
497    /// into the brightness bytes, so incremental carve relights keep
498    /// their glow. Authoring state only — editing this list does
499    /// **not** rebake by itself (call [`Grid::bake`] after) and it is
500    /// not carried through snapshots (the baked bytes are; re-set the
501    /// list after a load if you keep editing). Ignored by the other
502    /// bake modes and by the dynamic `LightRig`.
503    pub bake_lights: Vec<BakeLight>,
504    /// Per-chunk edit version counter (S7.2). Each user edit
505    /// through [`Self::set_voxel`] / [`Self::set_rect`] /
506    /// [`Self::set_sphere`] bumps the counter for every chunk it
507    /// actually wrote to. [`Self::ensure_chunk_generated`] does
508    /// NOT bump — a freshly generated chunk has no edits and
509    /// reads as version 0.
510    ///
511    /// Wired up here so the S7.3 async dispatch can detect "an
512    /// edit happened while a chunk was being generated in the
513    /// background" and discard the now-stale result: each
514    /// background task captures the dispatch-time version and
515    /// only installs its result iff the current version still
516    /// matches.
517    ///
518    /// Missing entries read as `0` via [`Self::chunk_version`].
519    /// Evictions in [`Scene::pump_streaming_sync`] drop the
520    /// corresponding entry so the map stays bounded.
521    ///
522    /// QE.3b — private: every mutation goes through
523    /// [`Self::bump_chunk_version`] / [`Self::bump_chunk_version_bbox`]
524    /// / the crate-internal tracking helpers, so the
525    /// version/extent/counter triple can never desync. Read via
526    /// [`Self::chunk_version`] / [`Self::chunk_versions`].
527    chunk_versions: HashMap<IVec3, u64>,
528    /// In-flight background generation tasks (S7.3).
529    ///
530    /// Populated by [`Scene::pump_streaming`] when it dispatches a
531    /// generator call onto the streaming rayon pool, drained when
532    /// the corresponding `ChunkResult` is received and processed
533    /// (either installed or discarded). The set is consulted to
534    /// avoid re-dispatching the same chunk while a previous task
535    /// is still running.
536    ///
537    /// Stays empty when only the synchronous
538    /// [`Scene::pump_streaming_sync`] is used — that path generates
539    /// inline on the calling thread.
540    pub pending_gen: HashSet<IVec3>,
541    /// Cross-frame DDA brick-occupancy cache (Substage DDA.7 perf).
542    /// Keyed by `(chunk, mip)` + the chunk's edit version, so a static
543    /// chunk's brick map is built once and reused every frame. Skipped
544    /// entirely on the voxlap render path. Not serialised.
545    pub dda_brick_cache: roxlap_core::BrickCache,
546    /// PF.12 — per-chunk change extent accumulated since a consumer
547    /// last [`Self::take_chunk_dirty`]'d it: the partial-refresh /
548    /// incremental-remip companion to [`Self::chunk_versions`]. Bounded
549    /// by the chunk count (one merged entry per chunk). Not serialised.
550    chunk_dirty: HashMap<IVec3, DirtyExtent>,
551    /// PF.13 (H9) — monotonic counter bumped by EVERY chunk-set /
552    /// chunk-content mutation (edits, installs, evictions). Per-frame
553    /// consumers (the GPU dirty poll, the brick-cache sweep) compare it
554    /// against their last-seen value and skip their O(all chunks) scans
555    /// outright on quiet frames. Not serialised.
556    mutations: u64,
557    /// PF.13 (H9) — `(mutation counter, requested mip, effective mip)`
558    /// of the last [`Self::ensure_dda_bricks`] sweep; a matching pair
559    /// skips the whole per-chunk ensure + retain pass.
560    last_bricks: Option<(u64, u32, u32)>,
561}
562
563/// PF.12 — how much of a chunk changed since a consumer last synced it.
564#[derive(Debug, Clone, Copy, PartialEq, Eq)]
565pub enum DirtyExtent {
566    /// Unknown / whole-chunk change (installs, wholesale replaces,
567    /// extent-less [`Grid::bump_chunk_version`] calls).
568    Full,
569    /// Inclusive CHUNK-LOCAL voxel bbox covering every change.
570    Bbox(IVec3, IVec3),
571}
572
573impl Grid {
574    /// New empty grid at the given transform — no chunks populated,
575    /// `render_sky = true`, LOD thresholds default to
576    /// [`LodThresholds::always_near`], no billboard cache.
577    #[must_use]
578    pub fn new(transform: GridTransform) -> Self {
579        Self {
580            transform,
581            chunks: HashMap::new(),
582            render_sky: true,
583            mip_levels_override: None,
584            lod_thresholds: LodThresholds::always_near(),
585            billboards: None,
586            generator: None,
587            name: None,
588            store: None,
589            stream_radius: StreamRadius::DISABLED,
590            bake_lights: Vec::new(),
591            chunk_versions: HashMap::new(),
592            pending_gen: HashSet::new(),
593            dda_brick_cache: roxlap_core::BrickCache::new(),
594            chunk_dirty: HashMap::new(),
595            mutations: 0,
596            last_bricks: None,
597        }
598    }
599
600    /// Ensure the DDA brick cache holds current mip-`requested_mip`
601    /// occupancy maps for every populated chunk, rebuilding only chunks
602    /// whose edit version changed (Substage DDA.7). Clamps the mip to a
603    /// level every chunk has built (so coarse rendering never holes) and
604    /// returns that effective mip. Evicts cache entries for chunks no
605    /// longer present. Call once per frame before the DDA render.
606    pub fn ensure_dda_bricks(&mut self, requested_mip: u32) -> u32 {
607        // Split-borrow disjoint fields so the cache mutates while the
608        // chunks + versions are read.
609        // PF.13 (H9) — quiet frame at the same requested mip ⇒ nothing
610        // in the cache can be stale: skip the whole O(chunks) sweep.
611        if let Some((counter, req, eff)) = self.last_bricks {
612            if counter == self.mutations && req == requested_mip {
613                return eff;
614            }
615        }
616        let mutations = self.mutations;
617        let Self {
618            chunks,
619            chunk_versions,
620            dda_brick_cache,
621            ..
622        } = self;
623        // Effective uniform mip: min built mip across chunks, capped.
624        let mut mip = requested_mip;
625        if requested_mip > 0 {
626            for vxl in chunks.values() {
627                mip = mip.min(vxl.mip_count().saturating_sub(1));
628            }
629        }
630        for (idx, vxl) in chunks.iter() {
631            let version = chunk_versions.get(idx).copied().unwrap_or(0);
632            let view = roxlap_core::GridView::from_single_vxl(vxl);
633            dda_brick_cache.ensure([idx.x, idx.y, idx.z], mip, version, &view);
634        }
635        dda_brick_cache.retain_chunks(|c| chunks.contains_key(&IVec3::new(c[0], c[1], c[2])));
636        self.last_bricks = Some((mutations, requested_mip, mip));
637        mip
638    }
639
640    /// Current per-chunk edit version (S7.2). Returns `0` for any
641    /// chunk that hasn't been edited yet (including absent chunks
642    /// and chunks materialised only via
643    /// [`Self::ensure_chunk_generated`]).
644    ///
645    /// Used by S7.3's async generation dispatch to detect "edit
646    /// happened while we were generating" — the dispatcher
647    /// snapshots this value, the background task carries it, and
648    /// the result is discarded on install if the live counter has
649    /// since moved.
650    #[must_use]
651    pub fn chunk_version(&self, chunk_idx: IVec3) -> u64 {
652        self.chunk_versions.get(&chunk_idx).copied().unwrap_or(0)
653    }
654
655    /// Bump the edit version of `chunk_idx` (S7.2). Saturating add
656    /// at `u64::MAX` — a chunk would need 10^11 edits per second
657    /// for ~5 years to wrap, so saturation is a defensive cap, not
658    /// a realistic concern.
659    ///
660    /// Called by the edit API ([`Self::set_voxel`] /
661    /// [`Self::set_rect`] / [`Self::set_sphere`]) after a chunk
662    /// has actually been written to. Pure no-op edit paths
663    /// (carving from an air chunk that doesn't exist yet) skip
664    /// the bump.
665    ///
666    /// Exposed as `pub` (vs the historical `pub(crate)`) so hosts
667    /// that mutate `grid.chunks` directly — e.g.
668    /// `roxlap-scene-demo`'s `StreamingBakeTracker` writing
669    /// lightmode-1 alphas via `apply_lighting_with_cache` — can
670    /// signal "this chunk's slab changed" to downstream consumers
671    /// like the GPU dirty-chunk poller.
672    pub fn bump_chunk_version(&mut self, chunk_idx: IVec3) {
673        let entry = self.chunk_versions.entry(chunk_idx).or_insert(0);
674        *entry = entry.saturating_add(1);
675        // PF.12 — no extent information ⇒ the whole chunk must be
676        // treated as changed by partial-refresh consumers.
677        self.chunk_dirty.insert(chunk_idx, DirtyExtent::Full);
678        self.mutations = self.mutations.wrapping_add(1);
679    }
680
681    /// PF.13 (H9) — the grid's monotonic mutation counter: bumped by
682    /// every chunk edit, install, and eviction. Per-frame consumers
683    /// snapshot it to skip their whole-grid scans on quiet frames.
684    #[must_use]
685    pub fn mutation_counter(&self) -> u64 {
686        self.mutations
687    }
688
689    /// PF.12 — [`Self::bump_chunk_version`] with the edit's CHUNK-LOCAL
690    /// voxel extent (inclusive), so partial-refresh consumers (the GPU
691    /// facade) and incremental re-mip know how little actually changed.
692    /// Extents accumulate (bbox union) until a consumer
693    /// [`Self::take_chunk_dirty`]s them; an extent-less bump upgrades
694    /// the entry to [`DirtyExtent::Full`].
695    pub fn bump_chunk_version_bbox(&mut self, chunk_idx: IVec3, lo: IVec3, hi: IVec3) {
696        let entry = self.chunk_versions.entry(chunk_idx).or_insert(0);
697        *entry = entry.saturating_add(1);
698        let merged = match self.chunk_dirty.get(&chunk_idx) {
699            Some(DirtyExtent::Full) => DirtyExtent::Full,
700            Some(DirtyExtent::Bbox(l, h)) => DirtyExtent::Bbox(l.min(lo), h.max(hi)),
701            None => DirtyExtent::Bbox(lo, hi),
702        };
703        self.chunk_dirty.insert(chunk_idx, merged);
704        self.mutations = self.mutations.wrapping_add(1);
705    }
706
707    /// PF.12 — take (and clear) the extent accumulated for `chunk_idx`
708    /// since the last take. `None` ⇒ no recorded change (a consumer that
709    /// still observed a version bump should treat that as
710    /// [`DirtyExtent::Full`] — e.g. a change recorded before the
711    /// consumer first synced the chunk).
712    pub fn take_chunk_dirty(&mut self, chunk_idx: IVec3) -> Option<DirtyExtent> {
713        self.chunk_dirty.remove(&chunk_idx)
714    }
715
716    /// The full per-chunk edit-version map (QE.3b — the read half of
717    /// the previously `pub` field). Consumers seeding a sync tracker
718    /// iterate this; per-chunk reads go through
719    /// [`Self::chunk_version`].
720    #[must_use]
721    pub fn chunk_versions(&self) -> &HashMap<IVec3, u64> {
722        &self.chunk_versions
723    }
724
725    /// QE.3b — record a chunk-**set** mutation (materialise / install /
726    /// evict) on the PF.13 quiet-frame counter. The single entry point
727    /// for the counter besides the version bumps above; per-frame
728    /// consumers compare [`Self::mutation_counter`] snapshots.
729    pub(crate) fn note_chunk_set_changed(&mut self) {
730        self.mutations = self.mutations.wrapping_add(1);
731    }
732
733    /// QE.3b — drop `chunk_idx`'s per-chunk tracking on eviction, so
734    /// both maps stay bounded by the live chunk count. (Also clears any
735    /// accumulated [`DirtyExtent`] — pre-QE.3b that entry leaked until
736    /// a consumer happened to take it.) A future re-stream of the same
737    /// index restarts at version 0.
738    pub(crate) fn forget_chunk_tracking(&mut self, chunk_idx: IVec3) {
739        self.chunk_versions.remove(&chunk_idx);
740        self.chunk_dirty.remove(&chunk_idx);
741    }
742
743    /// QE.3b — seat a restored per-chunk version verbatim (the
744    /// [`snapshot`] load path; not an edit, so no extent / counter
745    /// side-effects).
746    pub(crate) fn restore_chunk_version(&mut self, chunk_idx: IVec3, version: u64) {
747        self.chunk_versions.insert(chunk_idx, version);
748    }
749
750    /// Attach (or detach) the procedural generator used by
751    /// [`Self::ensure_chunk_generated`] (S7.0).
752    ///
753    /// Pass `Some(Arc::new(generator))` to enable on-demand chunk
754    /// generation; pass `None` to revert to the "absent stays
755    /// absent" behaviour. Replacing an existing generator drops the
756    /// previous `Arc` clone without touching already-materialised
757    /// chunks. Any background tasks dispatched by a prior
758    /// [`Scene::pump_streaming`] hold their own clones of the old
759    /// generator and finish naturally.
760    pub fn set_generator(&mut self, generator: Option<Arc<dyn ChunkGenerator>>) {
761        self.generator = generator;
762    }
763
764    /// Attach (or detach) the persistence store for edited streamed
765    /// chunks (QE.5a; see [`ChunkStore`]). Without one, evicting an
766    /// edited chunk **discards the edits** — the pre-QE.5 default.
767    pub fn set_chunk_store(&mut self, store: Option<Arc<dyn ChunkStore>>) {
768        self.store = store;
769    }
770
771    /// Materialise the chunk at `chunk_idx` by running [`Self::generator`]
772    /// if (a) the chunk is not already present and (b) a generator
773    /// is attached. Returns `true` iff a chunk was newly generated.
774    ///
775    /// No-ops in all other cases:
776    /// - chunk already present (caller edits / a previous
777    ///   `ensure_chunk_generated` call already populated it),
778    /// - no generator attached (the chunk stays implicit-air per
779    ///   the existing convention — does NOT fall through to
780    ///   [`Self::ensure_chunk`]'s empty-chunk constructor).
781    ///
782    /// This is the synchronous S7.0 path; [`Scene::pump_streaming`]
783    /// is the async counterpart (generation + store loads on a
784    /// dedicated rayon pool).
785    ///
786    /// QE.5a: with a [`ChunkStore`] attached, a stored chunk is
787    /// installed (with its persisted edit version) **before** the
788    /// generator is consulted — including for indices the generator's
789    /// [`ChunkGenerator::should_generate`] declines, since edits can
790    /// materialise chunks the generator never would.
791    pub fn ensure_chunk_generated(&mut self, chunk_idx: IVec3) -> bool {
792        if self.chunks.contains_key(&chunk_idx) {
793            return false;
794        }
795        // QE.5a — persisted edits win over regeneration.
796        if let Some((vxl, version)) = self.store.as_ref().and_then(|store| store.load(chunk_idx)) {
797            self.chunks.insert(chunk_idx, vxl);
798            self.restore_chunk_version(chunk_idx, version);
799            self.note_chunk_set_changed();
800            self.billboards = None; // same invalidation as below
801            return true;
802        }
803        let Some(generator) = self.generator.as_ref() else {
804            return false;
805        };
806        // S7.6+: generator may decline specific indices (e.g. a
807        // single-z-layer generator skipping placeholder bedrock
808        // chunks at chz != 0). Respect the filter so we don't
809        // materialise an unwanted chunk.
810        if !generator.should_generate(chunk_idx) {
811            return false;
812        }
813        let chunk = generator.generate(chunk_idx);
814        self.chunks.insert(chunk_idx, chunk);
815        self.note_chunk_set_changed();
816        // S7.4: a fresh chunk grows the populated AABB → the
817        // bounding sphere shifts/expands → existing impostor
818        // projections become wrong. Match the eviction (S7.1) +
819        // edit (S6.2) invalidation contract and drop the cache.
820        // Next Far-tier render rebuilds lazily.
821        self.billboards = None;
822        true
823    }
824
825    /// Bounding-sphere radius of the populated chunk set in
826    /// **world** space (SC.3 — the voxel half-extent is scaled by
827    /// `voxel_world_size`, so it pairs directly with the world-distance
828    /// LOD thresholds in [`crate::LodThresholds::from_radius`]).
829    ///
830    /// Walks the sparse chunk map once, computes the chunk-index
831    /// AABB, converts to voxel-space half-extent, returns its
832    /// Euclidean length. Empty grid → `0.0`.
833    ///
834    /// Conservative — bounds the full chunk volume, not just its
835    /// populated voxels (a chunk containing one voxel still
836    /// contributes `CHUNK_SIZE_XY × CHUNK_SIZE_XY × CHUNK_SIZE_Z`
837    /// to the bbox). For LOD picking that's fine: an over-bound
838    /// sphere errs on the side of `Near`.
839    ///
840    /// Cost: `O(chunks.len())`; recomputed on every call. Callers
841    /// who need this every frame should memoize at the
842    /// [`Scene`]-level cache (added when S6.2 needs it).
843    #[must_use]
844    pub fn bounding_radius(&self) -> f64 {
845        if self.chunks.is_empty() {
846            return 0.0;
847        }
848        let mut min = IVec3::splat(i32::MAX);
849        let mut max = IVec3::splat(i32::MIN);
850        for &idx in self.chunks.keys() {
851            min = min.min(idx);
852            max = max.max(idx);
853        }
854        // Chunk-index bbox → voxel-space half-extent. `+1` on max
855        // converts inclusive chunk index to exclusive voxel upper
856        // bound (chunk `idx` covers voxels `[idx*size, (idx+1)*size)`).
857        let sx = f64::from(CHUNK_SIZE_XY);
858        let sz = f64::from(CHUNK_SIZE_Z);
859        let lo = DVec3::new(
860            f64::from(min.x) * sx,
861            f64::from(min.y) * sx,
862            f64::from(min.z) * sz,
863        );
864        let hi = DVec3::new(
865            f64::from(max.x + 1) * sx,
866            f64::from(max.y + 1) * sx,
867            f64::from(max.z + 1) * sz,
868        );
869        let half_extent = (hi - lo) * 0.5;
870        // SC.3 — voxel half-extent → world radius (byte-identical at vws==1).
871        half_extent.length() * self.transform.voxel_world_size
872    }
873
874    /// Pick this grid's LOD tier for the given world-space camera
875    /// position. Convenience wrapper around [`crate::select_lod`]
876    /// that pulls [`Self::lod_thresholds`] from the grid.
877    #[must_use]
878    pub fn select_lod(&self, camera_world_pos: DVec3) -> Lod {
879        select_lod(camera_world_pos, &self.transform, self.lod_thresholds)
880    }
881}
882
883/// Top-level scene container. Holds a flat collection of grids
884/// keyed by [`GridId`].
885///
886/// S2.0 only exposes registration / removal / lookup. Address math
887/// helpers (S2.x), edit API (S2.x), and rendering composition (S3)
888/// land in later sub-substages.
889#[derive(Debug, Default)]
890pub struct Scene {
891    grids: HashMap<GridId, Grid>,
892    next_grid_id: u32,
893    /// S7.3: per-scene streaming pool + result channel. Stored on
894    /// the `Scene` so `pump_streaming` can dispatch background
895    /// tasks and drain results across pump calls. `cfg`-gated out
896    /// on wasm32 where `pump_streaming` short-circuits to
897    /// `pump_streaming_sync` (no rayon pool there).
898    #[cfg(not(target_arch = "wasm32"))]
899    streaming: streaming::StreamingState,
900}
901
902impl Scene {
903    /// New empty scene — no grids.
904    #[must_use]
905    pub fn new() -> Self {
906        Self::default()
907    }
908
909    /// Number of grids currently registered.
910    #[must_use]
911    pub fn grid_count(&self) -> usize {
912        self.grids.len()
913    }
914
915    /// Register a new grid. Returns its fresh, unique [`GridId`].
916    ///
917    /// SC — debug-asserts `transform.voxel_world_size` is finite and `> 0`
918    /// (catches a direct `GridTransform { .. }` literal that bypasses
919    /// [`GridTransform::at_scale`]); a `0` breaks the scaled marcher.
920    pub fn add_grid(&mut self, transform: GridTransform) -> GridId {
921        debug_assert!(
922            transform.voxel_world_size.is_finite() && transform.voxel_world_size > 0.0,
923            "grid voxel_world_size must be finite and > 0, got {}",
924            transform.voxel_world_size
925        );
926        let id = GridId(self.next_grid_id);
927        self.next_grid_id += 1;
928        self.grids.insert(id, Grid::new(transform));
929        id
930    }
931
932    /// Remove a grid by id. Returns the removed [`Grid`] (so the
933    /// caller can reclaim its chunks) or `None` if the id wasn't
934    /// registered. Removed ids are not reissued.
935    pub fn remove_grid(&mut self, id: GridId) -> Option<Grid> {
936        self.grids.remove(&id)
937    }
938
939    /// Borrow a registered grid.
940    #[must_use]
941    pub fn grid(&self, id: GridId) -> Option<&Grid> {
942        self.grids.get(&id)
943    }
944
945    /// Mutably borrow a registered grid.
946    pub fn grid_mut(&mut self, id: GridId) -> Option<&mut Grid> {
947        self.grids.get_mut(&id)
948    }
949
950    /// Iterator over all `(id, grid)` pairs in registration order
951    /// is **not** guaranteed — the underlying map is a `HashMap`.
952    /// Callers that need a stable order must sort by [`GridId`].
953    pub fn grids(&self) -> impl Iterator<Item = (GridId, &Grid)> {
954        self.grids.iter().map(|(id, g)| (*id, g))
955    }
956
957    /// Mutable iterator over all `(id, grid)` pairs. Yield order
958    /// is not guaranteed (HashMap-backed).
959    pub fn grids_mut(&mut self) -> impl Iterator<Item = (GridId, &mut Grid)> {
960        self.grids.iter_mut().map(|(id, g)| (*id, g))
961    }
962
963    /// Resolve a world-space surface hit to the owning grid + its
964    /// grid-local voxel — the picking back half. `ray_dir` is the view
965    /// direction the hit was found along (need not be normalised); the
966    /// point is nudged half a voxel along it, past the surface and into
967    /// the solid cell, before each grid's [`Grid::voxel_solid`] test.
968    /// Returns the first grid that is solid there (transform-correct
969    /// for rotated/translated grids), or `None` if none claims it.
970    ///
971    /// Backend-agnostic: pair with a renderer depth read to turn a
972    /// click into a voxel — `world = cam.pos + t · normalize(ray_dir)`,
973    /// then `resolve_voxel(world, ray_dir)`. `roxlap-render`'s
974    /// `SceneRenderer::pick` wires exactly that.
975    #[must_use]
976    pub fn resolve_voxel(&self, world: DVec3, ray_dir: DVec3) -> Option<(GridId, IVec3)> {
977        let len = ray_dir.length();
978        if len < 1e-9 {
979            return None;
980        }
981        let inside = world + ray_dir * (0.5 / len); // half a voxel inward
982        for (id, grid) in self.grids() {
983            let glp = addr::world_to_grid_local(inside, &grid.transform);
984            let v = addr::voxel_global(glp.chunk, glp.voxel);
985            if grid.voxel_solid(v) {
986                return Some((id, v));
987            }
988        }
989        None
990    }
991
992    /// Cast a world-space ray and return the nearest solid voxel hit
993    /// across all grids, or `None` if nothing solid lies within
994    /// `max_dist`. Renderer-independent (no depth buffer, no camera) —
995    /// the primitive for line-of-sight, projectiles, AI probing, and
996    /// off-screen / backend-agnostic picking.
997    ///
998    /// `dir` need not be normalised. Each grid's ray is transformed
999    /// into the grid's local frame (so rotated / translated grids are
1000    /// handled exactly) and marched with a voxel DDA against
1001    /// [`Grid::voxel_solid`]; the closest hit by world distance `t`
1002    /// wins. The step budget is bounded by `max_dist`, so empty space
1003    /// is safe but not free — a chunk-level skip is a future
1004    /// optimisation if hot.
1005    #[must_use]
1006    pub fn raycast(&self, origin: DVec3, dir: DVec3, max_dist: f64) -> Option<RayHit> {
1007        let len = dir.length();
1008        if len < 1e-12 || max_dist <= 0.0 {
1009            return None;
1010        }
1011        let dn = dir / len; // unit world direction → t is world distance
1012        let mut best: Option<RayHit> = None;
1013        for (id, grid) in self.grids() {
1014            // World ray → grid-local voxel space. `ld = inv * dn` stays
1015            // UNIT (rotation preserves length), so `voxel_dda` marches
1016            // in voxel units and returns a voxel-distance `t`. SC — the
1017            // grid's `voxel_world_size` scales the boundary both ways:
1018            // the origin divides into voxel coords, the world march cap
1019            // divides into voxel units, and the returned voxel `t`
1020            // multiplies back to a WORLD distance so it stays
1021            // comparable across grids of different scale. `vws == 1.0`
1022            // is the pre-SC path, bit-for-bit.
1023            let inv = grid.transform.rotation.inverse();
1024            let vws = grid.transform.voxel_world_size;
1025            let lo = (inv * (origin - grid.transform.origin)) / vws;
1026            let ld = inv * dn;
1027            if let Some((voxel, t_local)) = voxel_dda(grid, lo, ld, max_dist / vws) {
1028                let t = t_local * vws;
1029                if best.as_ref().is_none_or(|b| t < b.t) {
1030                    best = Some(RayHit {
1031                        grid: id,
1032                        voxel,
1033                        world: origin + dn * t,
1034                        t,
1035                        color: grid.voxel_color(voxel),
1036                    });
1037                }
1038            }
1039        }
1040        best
1041    }
1042
1043    /// Configure the number of worker threads in the dedicated
1044    /// streaming pool (S7.3).
1045    ///
1046    /// Lazily applied — the pool itself is constructed on the first
1047    /// [`Self::pump_streaming`] call. If the pool was already built
1048    /// (i.e. a previous `pump_streaming` already dispatched at
1049    /// least one task), it gets dropped and rebuilt. Dropping the
1050    /// old pool blocks until all of its in-flight tasks finish
1051    /// (rayon's contract); any results those tasks sent are still
1052    /// drained by the next `pump_streaming` because the channel
1053    /// survives the rebuild.
1054    ///
1055    /// The streaming pool is separate from rayon's global pool
1056    /// (which R12 multicore rendering uses), so chunk generation
1057    /// doesn't compete with render threads. Sensible values are 1
1058    /// to ~4 — generation work is CPU-bound but should leave most
1059    /// of the box for everything else.
1060    ///
1061    /// On wasm32 this is a no-op (no rayon pool available);
1062    /// `pump_streaming` runs synchronously there.
1063    ///
1064    /// # Panics
1065    /// Panics on native if `n == 0` (zero-thread pools are not
1066    /// supported; the scene crate's S7.1 helper already disallows
1067    /// the equivalent for `StreamRadius::r_active < 0`).
1068    #[cfg(not(target_arch = "wasm32"))]
1069    pub fn set_streaming_threads(&mut self, n: usize) {
1070        self.streaming.set_thread_count(n);
1071    }
1072
1073    /// wasm32 no-op companion of [`Self::set_streaming_threads`].
1074    /// Lets cross-target code call this unconditionally.
1075    #[cfg(target_arch = "wasm32")]
1076    pub fn set_streaming_threads(&mut self, _n: usize) {
1077        // No streaming pool on wasm32 — see `pump_streaming` docs.
1078    }
1079
1080    /// Asynchronous streaming pump (S7.3).
1081    ///
1082    /// On native, dispatches missing-chunk generations onto a
1083    /// dedicated rayon pool, drains any results that arrived since
1084    /// the last pump, runs the eviction pass, and tracks in-flight
1085    /// tasks in each grid's [`Grid::pending_gen`] set. The drain
1086    /// uses the per-chunk version counter from S7.2 to discard
1087    /// results whose chunk was edited mid-generation.
1088    ///
1089    /// On wasm32 this short-circuits to [`Self::pump_streaming_sync`]
1090    /// — no thread pool is available there, but the same per-grid
1091    /// stream-in / evict semantics apply.
1092    ///
1093    /// Call once per frame from the render thread. Cheap when
1094    /// nothing changed (early-exit on disabled grids, try_recv
1095    /// loops empty fast).
1096    pub fn pump_streaming(&mut self, camera_world_pos: DVec3) {
1097        #[cfg(target_arch = "wasm32")]
1098        {
1099            self.pump_streaming_sync(camera_world_pos);
1100        }
1101        #[cfg(not(target_arch = "wasm32"))]
1102        {
1103            self.pump_streaming_native(camera_world_pos);
1104        }
1105    }
1106
1107    /// Native implementation of [`Self::pump_streaming`].
1108    #[cfg(not(target_arch = "wasm32"))]
1109    fn pump_streaming_native(&mut self, camera_world_pos: DVec3) {
1110        // 1. Drain inbox — install fresh results, drop stale.
1111        while let Ok(result) = self.streaming.rx.try_recv() {
1112            let Some(grid) = self.grids.get_mut(&result.grid_id) else {
1113                // Grid was removed while a generation task was
1114                // in-flight. Drop silently.
1115                continue;
1116            };
1117            // Clearing pending_gen here both for "result delivered"
1118            // and "we shouldn't try to re-dispatch this chunk just
1119            // because it's missing".
1120            let was_pending = grid.pending_gen.remove(&result.chunk_idx);
1121            if !was_pending {
1122                // Either the chunk was evicted (pending cleared in
1123                // the eviction pass below in some prior call), or a
1124                // duplicate result for an already-handled chunk.
1125                continue;
1126            }
1127            if grid.chunks.contains_key(&result.chunk_idx) {
1128                // Some other path (e.g. `ensure_chunk_generated`
1129                // sync helper, or a manual edit's `ensure_chunk`)
1130                // already populated the slot. Don't overwrite.
1131                continue;
1132            }
1133            if grid.chunk_version(result.chunk_idx) != result.version_at_dispatch {
1134                // S7.2 stale-result discard: chunk was edited mid-
1135                // generation.
1136                continue;
1137            }
1138            let Some(vxl) = result.vxl else {
1139                // QE.5a — nothing to install (store miss + generator
1140                // declined); the pending entry is already cleared.
1141                continue;
1142            };
1143            grid.chunks.insert(result.chunk_idx, vxl);
1144            if let Some(version) = result.restored_version {
1145                // QE.5a — a store-restored chunk keeps its persisted
1146                // edit version (consumers see it as edited content).
1147                grid.restore_chunk_version(result.chunk_idx, version);
1148            }
1149            grid.note_chunk_set_changed();
1150            // S7.4: same invalidation contract as the sync
1151            // `ensure_chunk_generated` path — installing a new
1152            // chunk can grow the bounding sphere, so the
1153            // billboard impostor cache must be rebuilt on next
1154            // Far entry. Lazy: only one cache wipe per drain
1155            // batch, the Far render rebuilds afterwards.
1156            grid.billboards = None;
1157        }
1158
1159        // 2. Per-grid: eviction first, then dispatch. Doing evict
1160        //    before dispatch means a chunk that's just left
1161        //    r_active doesn't get re-dispatched on the same pump.
1162        self.streaming.ensure_pool();
1163        // Disjoint sub-field borrows: pool/tx via `&self.streaming.*`,
1164        // grids via `&mut self.grids`. Hold both at once.
1165        let pool: &rayon::ThreadPool = self.streaming.pool.as_ref().expect("ensure_pool just ran");
1166        let tx_template = &self.streaming.tx;
1167        for (grid_id, grid) in &mut self.grids {
1168            evict_grid_chunks(grid, camera_world_pos);
1169            dispatch_grid_async(*grid_id, grid, camera_world_pos, pool, tx_template);
1170        }
1171    }
1172
1173    /// Synchronous streaming pump (S7.1).
1174    ///
1175    /// For each grid with a non-[`StreamRadius::DISABLED`] policy:
1176    /// 1. Project the world-space camera into grid-local coords
1177    ///    (inverse rotation + origin subtract).
1178    /// 2. Stream in any chunk whose AABB-to-camera distance is
1179    ///    `<= r_active`, calling [`Grid::ensure_chunk_generated`].
1180    ///    No-ops gracefully if the grid has no generator attached
1181    ///    (so callers can use the eviction half of streaming on a
1182    ///    purely-edited grid).
1183    /// 3. Evict any chunk whose AABB-to-camera distance exceeds
1184    ///    `r_evict` from the grid's chunk map. Eviction also
1185    ///    clears the cached [`BillboardCache`] (the bounding sphere
1186    ///    may shrink, invalidating impostor projections; the next
1187    ///    Far-tier render rebuilds lazily).
1188    ///
1189    /// Both passes use the f64 grid-local position so rotation +
1190    /// non-axis-aligned grids stream and evict correctly. The
1191    /// generate path is blocking — S7.3 will move it to a
1192    /// background rayon pool with `pump_streaming` (non-blocking).
1193    /// Callers that want the async variant in S7.0/S7.1 stages
1194    /// should keep `r_active` small.
1195    pub fn pump_streaming_sync(&mut self, camera_world_pos: DVec3) {
1196        for grid in self.grids.values_mut() {
1197            pump_grid_streaming_sync(grid, camera_world_pos);
1198        }
1199    }
1200}
1201
1202/// S7.1 helper — drives one grid's synchronous streaming pass.
1203/// Stream-in pass uses [`Grid::ensure_chunk_generated`] (blocking
1204/// inline generation); eviction pass shared with the S7.3 async
1205/// path through [`evict_grid_chunks`].
1206fn pump_grid_streaming_sync(grid: &mut Grid, camera_world_pos: DVec3) {
1207    let radius = grid.stream_radius;
1208    if radius.is_disabled() {
1209        return;
1210    }
1211    let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
1212
1213    // --- Pass 1: stream in active chunks (sync) ---------------
1214    // QE.5a — a ChunkStore alone (no generator) still restores
1215    // persisted edited chunks.
1216    if radius.r_active > 0.0 && (grid.generator.is_some() || grid.store.is_some()) {
1217        for_each_chunk_in_radius(cam_local, radius.r_active, |idx| {
1218            grid.ensure_chunk_generated(idx);
1219        });
1220    }
1221
1222    // --- Pass 2: evict chunks past r_evict --------------------
1223    evict_grid_chunks_with_cam(grid, cam_local);
1224}
1225
1226/// Eviction pass shared by [`pump_grid_streaming_sync`] and the
1227/// S7.3 async path. Public-ish so the async driver can call it
1228/// before dispatching to avoid generating chunks that are about
1229/// to be evicted. `cfg`-gated to native: on wasm32 the only
1230/// caller (`pump_streaming_native`) doesn't compile, so this
1231/// helper would warn as dead code.
1232#[cfg(not(target_arch = "wasm32"))]
1233fn evict_grid_chunks(grid: &mut Grid, camera_world_pos: DVec3) {
1234    let radius = grid.stream_radius;
1235    if radius.is_disabled() {
1236        return;
1237    }
1238    let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
1239    evict_grid_chunks_with_cam(grid, cam_local);
1240}
1241
1242/// Eviction inner — assumes `cam_local` is already computed (the
1243/// dispatcher and sync pump both have it on hand).
1244fn evict_grid_chunks_with_cam(grid: &mut Grid, cam_local: DVec3) {
1245    let radius = grid.stream_radius;
1246    if !radius.r_evict.is_finite() {
1247        return;
1248    }
1249    let r_sq = radius.r_evict * radius.r_evict;
1250    let to_evict: Vec<IVec3> = grid
1251        .chunks
1252        .keys()
1253        .filter(|&&idx| streaming::chunk_aabb_dist_sq(cam_local, idx) > r_sq)
1254        .copied()
1255        .collect();
1256    // S7.3: also evict pending in-flight tasks past r_evict so the
1257    // drain pass doesn't install a chunk that's no longer wanted.
1258    // We don't have a way to cancel the rayon task, but we can
1259    // drop the pending_gen entry so the result is dropped on
1260    // arrival.
1261    let to_evict_pending: Vec<IVec3> = grid
1262        .pending_gen
1263        .iter()
1264        .filter(|&&idx| streaming::chunk_aabb_dist_sq(cam_local, idx) > r_sq)
1265        .copied()
1266        .collect();
1267    if to_evict.is_empty() && to_evict_pending.is_empty() {
1268        return;
1269    }
1270    for idx in &to_evict {
1271        // QE.5a — an edited chunk (version != 0) is handed to the
1272        // ChunkStore before it drops, so the edits survive evict +
1273        // re-stream. Pristine generator output (version 0) is
1274        // regenerable and skips the store.
1275        if let Some(store) = grid.store.as_ref() {
1276            let version = grid.chunk_version(*idx);
1277            if version != 0 {
1278                if let Some(vxl) = grid.chunks.get(idx) {
1279                    store.store(*idx, vxl, version);
1280                }
1281            }
1282        }
1283        grid.chunks.remove(idx);
1284        grid.note_chunk_set_changed();
1285        // S7.2/QE.3b: drop the chunk's version + dirty-extent tracking
1286        // so both maps stay bounded. A future re-stream of the same idx
1287        // restarts at 0 — that's fine because any in-flight gen-result
1288        // tagged with the pre-eviction version is unreachable (no chunk
1289        // to install onto) and gets discarded by the new "version
1290        // still 0" check anyway. (A stored edited chunk re-enters with
1291        // its persisted version via the QE.5a load path instead.)
1292        grid.forget_chunk_tracking(*idx);
1293        // S7.3: drop pending entry for the same chunk too. If a
1294        // background task is still running, its result will be
1295        // dropped on arrival (was_pending = false).
1296        grid.pending_gen.remove(idx);
1297    }
1298    for idx in &to_evict_pending {
1299        grid.pending_gen.remove(idx);
1300    }
1301    if !to_evict.is_empty() {
1302        // Bounding sphere can shrink → impostor projections would
1303        // be wrong on next Far render. Clear lazily; the next
1304        // Far-tier pass repopulates via BillboardCache::build.
1305        grid.billboards = None;
1306    }
1307}
1308
1309/// Walk every chunk index whose AABB falls within `r_active` of
1310/// `cam_local` and invoke `f` on it. Shared between the S7.1 sync
1311/// stream-in and the S7.3 async dispatch.
1312fn for_each_chunk_in_radius<F>(cam_local: DVec3, r_active: f64, mut f: F)
1313where
1314    F: FnMut(IVec3),
1315{
1316    let r_sq = r_active * r_active;
1317    let sxy = f64::from(CHUNK_SIZE_XY);
1318    let sz = f64::from(CHUNK_SIZE_Z);
1319    // Half-extent in chunk units; ceil to be conservative so any
1320    // chunk whose AABB clips the radius gets considered. `+1`
1321    // covers the half-open chunk-AABB upper edge plus the case
1322    // where the camera sits exactly on a chunk boundary and the
1323    // closest chunk is one index off.
1324    #[allow(clippy::cast_possible_truncation)]
1325    let r_chunks_xy = (r_active / sxy).ceil() as i32 + 1;
1326    #[allow(clippy::cast_possible_truncation)]
1327    let r_chunks_z = (r_active / sz).ceil() as i32 + 1;
1328    #[allow(clippy::cast_possible_truncation)]
1329    let cx_chunk = (cam_local.x / sxy).floor() as i32;
1330    #[allow(clippy::cast_possible_truncation)]
1331    let cy_chunk = (cam_local.y / sxy).floor() as i32;
1332    #[allow(clippy::cast_possible_truncation)]
1333    let cz_chunk = (cam_local.z / sz).floor() as i32;
1334    for chz in (cz_chunk - r_chunks_z)..=(cz_chunk + r_chunks_z) {
1335        for chy in (cy_chunk - r_chunks_xy)..=(cy_chunk + r_chunks_xy) {
1336            for chx in (cx_chunk - r_chunks_xy)..=(cx_chunk + r_chunks_xy) {
1337                let idx = IVec3::new(chx, chy, chz);
1338                if streaming::chunk_aabb_dist_sq(cam_local, idx) <= r_sq {
1339                    f(idx);
1340                }
1341            }
1342        }
1343    }
1344}
1345
1346/// S7.3 async dispatch — schedule generation for every chunk in
1347/// `r_active` that's not already present and not already in
1348/// flight. Each dispatch clones the grid's generator `Arc` and a
1349/// sender clone, then spawns the closure on the streaming rayon
1350/// pool. The closure does the generate + send; the main thread
1351/// drains results on the next pump.
1352#[cfg(not(target_arch = "wasm32"))]
1353fn dispatch_grid_async(
1354    grid_id: GridId,
1355    grid: &mut Grid,
1356    camera_world_pos: DVec3,
1357    pool: &rayon::ThreadPool,
1358    tx: &crossbeam_channel::Sender<streaming::ChunkResult>,
1359) {
1360    let radius = grid.stream_radius;
1361    if radius.is_disabled() || radius.r_active <= 0.0 {
1362        return;
1363    }
1364    // QE.5a — a ChunkStore alone (no generator) still restores
1365    // persisted edited chunks on the background pool.
1366    let generator = grid.generator.as_ref().map(Arc::clone);
1367    let store = grid.store.as_ref().map(Arc::clone);
1368    if generator.is_none() && store.is_none() {
1369        return;
1370    }
1371    let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
1372    for_each_chunk_in_radius(cam_local, radius.r_active, |idx| {
1373        if grid.chunks.contains_key(&idx) {
1374            return; // already present
1375        }
1376        if grid.pending_gen.contains(&idx) {
1377            return; // already in flight
1378        }
1379        // S7.6+: respect the generator's per-chunk filter — same
1380        // contract as `Grid::ensure_chunk_generated` (sync helper).
1381        // Lets a generator decline to materialise specific indices
1382        // (e.g. `HillsChunkGenerator` skipping placeholder bedrock
1383        // chunks at chz != 0 so the camera-above-grid path doesn't
1384        // create chz < 0 entries that would shift `origin_chunk_z`
1385        // and trigger the S4B.6.j cross-chunk look-down bug).
1386        // QE.5a — with a store attached the chunk is still
1387        // dispatched: a persisted edit wins over the decline (edits
1388        // can materialise chunks the generator never would); the
1389        // background task falls back to "nothing" on a store miss.
1390        let declined = !generator.as_ref().is_some_and(|g| g.should_generate(idx));
1391        if declined && store.is_none() {
1392            return;
1393        }
1394        grid.pending_gen.insert(idx);
1395        let version_at_dispatch = grid.chunk_version(idx);
1396        let tx_clone = tx.clone();
1397        let gen_clone = generator.clone();
1398        let store_clone = store.clone();
1399        pool.spawn(move || {
1400            // QE.5a — persisted edits win over regeneration; the
1401            // store load runs here on the pool so blocking IO never
1402            // stalls the render thread.
1403            let (vxl, restored_version) = match store_clone.as_ref().and_then(|s| s.load(idx)) {
1404                Some((vxl, version)) => (Some(vxl), Some(version)),
1405                None if declined => (None, None),
1406                None => (gen_clone.map(|g| g.generate(idx)), None),
1407            };
1408            // Send is non-blocking on unbounded channel; if the
1409            // receiver was dropped (Scene drop), the send fails
1410            // silently — that's fine.
1411            let _ = tx_clone.send(streaming::ChunkResult {
1412                grid_id,
1413                chunk_idx: idx,
1414                version_at_dispatch,
1415                vxl,
1416                restored_version,
1417            });
1418        });
1419    });
1420}
1421
1422#[cfg(test)]
1423mod tests {
1424    use super::*;
1425
1426    #[test]
1427    fn empty_scene_has_no_grids() {
1428        let scene = Scene::new();
1429        assert_eq!(scene.grid_count(), 0);
1430        assert!(scene.grids().next().is_none());
1431    }
1432
1433    #[test]
1434    fn raycast_hits_axis_aligned_voxel() {
1435        let mut scene = Scene::new();
1436        let id = scene.add_grid(GridTransform::identity());
1437        scene
1438            .grid_mut(id)
1439            .unwrap()
1440            .set_voxel(IVec3::new(5, 5, 10), Some(VoxColor(0x80_aa_bb_cc)));
1441
1442        // Straight down the +z column through (5,5): hits z=10 at t≈10.
1443        let hit = scene
1444            .raycast(DVec3::new(5.5, 5.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1445            .expect("ray hits the voxel");
1446        assert_eq!(hit.grid, id);
1447        assert_eq!(hit.voxel, IVec3::new(5, 5, 10));
1448        assert!((hit.t - 10.0).abs() < 1e-6, "t≈10, got {}", hit.t);
1449        assert!(hit.color.is_some(), "textured voxel has a colour");
1450
1451        // A column with no voxel misses.
1452        assert!(
1453            scene
1454                .raycast(DVec3::new(0.5, 0.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1455                .is_none(),
1456            "empty column → no hit",
1457        );
1458    }
1459
1460    #[test]
1461    fn raycast_respects_grid_transform() {
1462        // A translated grid: the hit voxel is reported in GRID-LOCAL
1463        // coords, and the world hit point is back in world space — so a
1464        // host gets the true voxel regardless of where the grid sits.
1465        let mut scene = Scene::new();
1466        let id = scene.add_grid(GridTransform::at(DVec3::new(100.0, 0.0, 0.0)));
1467        scene
1468            .grid_mut(id)
1469            .unwrap()
1470            .set_voxel(IVec3::new(5, 5, 10), Some(VoxColor(0x80_11_22_33)));
1471
1472        let hit = scene
1473            .raycast(DVec3::new(105.5, 5.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1474            .expect("ray hits the translated voxel");
1475        assert_eq!(hit.voxel, IVec3::new(5, 5, 10), "grid-local voxel");
1476        assert!((hit.world.x - 105.5).abs() < 1e-6, "world x preserved");
1477        assert!((hit.t - 10.0).abs() < 1e-6, "t≈10, got {}", hit.t);
1478    }
1479
1480    #[test]
1481    fn raycast_picks_nearest_grid() {
1482        // Two grids with a voxel each along the same world column; the
1483        // raycast must return the closer one.
1484        let mut scene = Scene::new();
1485        let near = scene.add_grid(GridTransform::identity());
1486        let far = scene.add_grid(GridTransform::identity());
1487        scene
1488            .grid_mut(near)
1489            .unwrap()
1490            .set_voxel(IVec3::new(1, 1, 20), Some(VoxColor(0x80_00_ff_00)));
1491        scene
1492            .grid_mut(far)
1493            .unwrap()
1494            .set_voxel(IVec3::new(1, 1, 40), Some(VoxColor(0x80_ff_00_00)));
1495
1496        let hit = scene
1497            .raycast(DVec3::new(1.5, 1.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1498            .expect("hits the nearer voxel");
1499        assert_eq!(hit.grid, near);
1500        assert_eq!(hit.voxel, IVec3::new(1, 1, 20));
1501    }
1502
1503    #[test]
1504    fn raycast_into_scaled_grid_returns_world_t() {
1505        // SC — a grid at voxel_world_size 2.0: the voxel at grid-local
1506        // (5,5,10) sits at WORLD z = 20 (10 voxels × 2 units). The ray
1507        // must hit at world t ≈ 20 and report the grid-local voxel.
1508        let mut scene = Scene::new();
1509        let id = scene.add_grid(GridTransform::at_scale(DVec3::ZERO, 2.0));
1510        scene
1511            .grid_mut(id)
1512            .unwrap()
1513            .set_voxel(IVec3::new(5, 5, 10), Some(VoxColor(0x80_aa_bb_cc)));
1514        // World column through grid-local (5,5): world x/y = 11 (5.5 vox × 2).
1515        let hit = scene
1516            .raycast(DVec3::new(11.0, 11.0, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1517            .expect("ray hits the scaled voxel");
1518        assert_eq!(hit.voxel, IVec3::new(5, 5, 10), "grid-local voxel");
1519        assert!((hit.t - 20.0).abs() < 1e-4, "world t≈20, got {}", hit.t);
1520        assert!((hit.world.z - 20.0).abs() < 1e-4, "world hit z≈20");
1521    }
1522
1523    #[test]
1524    fn raycast_nearest_is_by_world_distance_across_scales() {
1525        // SC — the two metrics DISAGREE, so a missing `* vws` on `t`
1526        // flips the winner. Both voxels on the world column at xy = 1.0:
1527        //  - grid A (vws 2.0): voxel (0,0,6) → WORLD z 12, voxel-LOCAL 6.
1528        //  - grid B (vws 0.5): voxel (2,2,20) → WORLD z 10, voxel-LOCAL 20.
1529        // Correct (world t): B(10) < A(12) → hit B.
1530        // Broken (voxel-local t, no `* vws`): A(6) < B(20) → hit A.
1531        // So `hit.grid == B` bites iff the conversion is applied.
1532        let mut scene = Scene::new();
1533        let a = scene.add_grid(GridTransform::at_scale(DVec3::ZERO, 2.0));
1534        let b = scene.add_grid(GridTransform::at_scale(DVec3::ZERO, 0.5));
1535        scene
1536            .grid_mut(a)
1537            .unwrap()
1538            .set_voxel(IVec3::new(0, 0, 6), Some(VoxColor(0x80_ff_00_00)));
1539        scene
1540            .grid_mut(b)
1541            .unwrap()
1542            .set_voxel(IVec3::new(2, 2, 20), Some(VoxColor(0x80_00_ff_00)));
1543        let hit = scene
1544            .raycast(DVec3::new(1.0, 1.0, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1545            .expect("hits the world-nearer voxel");
1546        assert_eq!(
1547            hit.grid, b,
1548            "grid B is nearer in WORLD units (10 < 12) though FARTHER in \
1549             voxel-local units (20 > 6) — the t-conversion must decide by world"
1550        );
1551        assert!((hit.t - 10.0).abs() < 1e-4, "world t≈10, got {}", hit.t);
1552    }
1553
1554    #[test]
1555    fn add_grid_returns_fresh_ids() {
1556        let mut scene = Scene::new();
1557        let a = scene.add_grid(GridTransform::identity());
1558        let b = scene.add_grid(GridTransform::at(DVec3::new(100.0, 0.0, 0.0)));
1559        assert_ne!(a, b);
1560        assert_eq!(a.raw(), 0);
1561        assert_eq!(b.raw(), 1);
1562        assert_eq!(scene.grid_count(), 2);
1563    }
1564
1565    #[test]
1566    fn grid_lookup_round_trips() {
1567        let mut scene = Scene::new();
1568        let id = scene.add_grid(GridTransform::at(DVec3::new(10.0, 20.0, 30.0)));
1569        let g = scene.grid(id).expect("grid registered");
1570        assert_eq!(g.transform.origin, DVec3::new(10.0, 20.0, 30.0));
1571        assert_eq!(g.transform.rotation, DQuat::IDENTITY);
1572        assert!(g.chunks.is_empty());
1573    }
1574
1575    #[test]
1576    fn remove_grid_drops_it_from_scene() {
1577        let mut scene = Scene::new();
1578        let id = scene.add_grid(GridTransform::identity());
1579        let removed = scene.remove_grid(id);
1580        assert!(removed.is_some());
1581        assert_eq!(scene.grid_count(), 0);
1582        assert!(scene.grid(id).is_none());
1583        // Re-adding does NOT reuse the dropped id.
1584        let id2 = scene.add_grid(GridTransform::identity());
1585        assert_ne!(id, id2);
1586        assert_eq!(id2.raw(), 1);
1587    }
1588
1589    #[test]
1590    fn remove_unknown_grid_is_none() {
1591        let mut scene = Scene::new();
1592        let bogus = GridId(999);
1593        assert!(scene.remove_grid(bogus).is_none());
1594    }
1595
1596    #[test]
1597    fn grid_mut_can_modify_transform() {
1598        let mut scene = Scene::new();
1599        let id = scene.add_grid(GridTransform::identity());
1600        scene.grid_mut(id).unwrap().transform.origin = DVec3::new(1.0, 2.0, 3.0);
1601        assert_eq!(
1602            scene.grid(id).unwrap().transform.origin,
1603            DVec3::new(1.0, 2.0, 3.0)
1604        );
1605    }
1606
1607    #[test]
1608    fn chunk_size_constants_match_plan() {
1609        // Plan locks these values; bumping either breaks the slab
1610        // byte format (Z) or the worst-case chunk footprint budget
1611        // (XY). Pin them so a future refactor that drifts them
1612        // shows up in CI.
1613        assert_eq!(CHUNK_SIZE_XY, 128);
1614        assert_eq!(CHUNK_SIZE_Z, 256);
1615    }
1616
1617    // ---- S6.0: bounding_radius + Grid::select_lod ----
1618
1619    #[test]
1620    fn new_grid_defaults_to_always_near_lod() {
1621        // Byte-identity contract for the staged S6 rollout: a
1622        // grid built through `new` must never trigger the Mid/Far
1623        // branches by accident, even when bounding_radius would
1624        // imply otherwise.
1625        let g = Grid::new(GridTransform::identity());
1626        assert_eq!(g.lod_thresholds.r_near, f64::INFINITY);
1627        assert_eq!(g.lod_thresholds.r_mid, f64::INFINITY);
1628        assert_eq!(g.select_lod(DVec3::new(1e9, 0.0, 0.0)), Lod::Near);
1629    }
1630
1631    #[test]
1632    fn bounding_radius_empty_grid_is_zero() {
1633        let g = Grid::new(GridTransform::identity());
1634        assert_eq!(g.bounding_radius(), 0.0);
1635    }
1636
1637    #[test]
1638    fn bounding_radius_single_chunk_at_origin() {
1639        // One chunk at (0, 0, 0): bbox is [0, 128) × [0, 128) × [0, 256).
1640        // Half-extent = (64, 64, 128); length = sqrt(64² + 64² + 128²)
1641        //   = sqrt(4096 + 4096 + 16384) = sqrt(24576) ≈ 156.7747...
1642        let mut scene = Scene::new();
1643        let id = scene.add_grid(GridTransform::identity());
1644        let g = scene.grid_mut(id).unwrap();
1645        // Populate chunk (0, 0, 0) via the edit API.
1646        g.set_voxel(IVec3::new(0, 0, 0), Some(VoxColor(0x80_88_88_88)));
1647        let r = g.bounding_radius();
1648        let expected = ((64.0_f64).powi(2) * 2.0 + (128.0_f64).powi(2)).sqrt();
1649        assert!(
1650            (r - expected).abs() < 1e-9,
1651            "bounding_radius={r} expected={expected}"
1652        );
1653    }
1654
1655    #[test]
1656    fn sc3_bounding_radius_is_world_scaled() {
1657        // SC.3 — bounding_radius returns WORLD units, so a vws=3.0 grid's
1658        // radius is 3× the voxel half-extent. This pairs with the
1659        // world-distance LOD thresholds so a scaled grid picks the right tier.
1660        let mut scene = Scene::new();
1661        let id = scene.add_grid(crate::GridTransform::at_scale(DVec3::ZERO, 3.0));
1662        let g = scene.grid_mut(id).unwrap();
1663        g.set_voxel(IVec3::new(0, 0, 0), Some(VoxColor(0x80_88_88_88)));
1664        let voxel_half = ((64.0_f64).powi(2) * 2.0 + (128.0_f64).powi(2)).sqrt();
1665        let r = g.bounding_radius();
1666        assert!(
1667            (r - voxel_half * 3.0).abs() < 1e-9,
1668            "world radius must be voxel half-extent × vws: got {r}"
1669        );
1670        // select_lod uses world distance vs world thresholds. from_radius(r)
1671        // sets r_near = r; a camera just inside/outside it flips Near↔Mid.
1672        g.lod_thresholds = crate::LodThresholds::from_radius(r);
1673        assert_eq!(
1674            g.select_lod(DVec3::new(r * 0.5, 0.0, 0.0)),
1675            crate::Lod::Near
1676        );
1677        assert_eq!(
1678            g.select_lod(DVec3::new(r * 2.0, 0.0, 0.0)),
1679            crate::Lod::Mid,
1680            "tier must flip at the WORLD (scaled) distance"
1681        );
1682    }
1683
1684    #[test]
1685    fn bounding_radius_grows_with_chunk_extent() {
1686        // Two chunks at (0,0,0) and (3,0,0): x extent is 4 chunks =
1687        // 512 voxels; y/z are 1 chunk each. Half-extent = (256, 64, 128);
1688        // length = sqrt(256² + 64² + 128²) = sqrt(65536+4096+16384)
1689        //        = sqrt(86016) ≈ 293.2848.
1690        let mut scene = Scene::new();
1691        let id = scene.add_grid(GridTransform::identity());
1692        let g = scene.grid_mut(id).unwrap();
1693        // Stamp one voxel in chunk (0,0,0).
1694        g.set_voxel(IVec3::new(0, 0, 0), Some(VoxColor(0x80_88_88_88)));
1695        // Stamp one voxel in chunk (3,0,0): grid-local x = 3*128 = 384.
1696        g.set_voxel(IVec3::new(384, 0, 0), Some(VoxColor(0x80_88_88_88)));
1697        assert_eq!(g.chunks.len(), 2);
1698        let r = g.bounding_radius();
1699        let expected = (256.0_f64.powi(2) + 64.0_f64.powi(2) + 128.0_f64.powi(2)).sqrt();
1700        assert!(
1701            (r - expected).abs() < 1e-9,
1702            "bounding_radius={r} expected={expected}"
1703        );
1704    }
1705
1706    #[test]
1707    fn grid_select_lod_respects_lod_thresholds_field() {
1708        // Set a non-default threshold and verify the helper picks
1709        // the right tier for known distances.
1710        let mut scene = Scene::new();
1711        let id = scene.add_grid(GridTransform::at(DVec3::new(100.0, 0.0, 0.0)));
1712        let g = scene.grid_mut(id).unwrap();
1713        g.lod_thresholds = LodThresholds {
1714            r_near: 50.0,
1715            r_mid: 200.0,
1716            ..LodThresholds::always_near()
1717        };
1718        // Camera 25 units from grid origin → Near.
1719        assert_eq!(g.select_lod(DVec3::new(125.0, 0.0, 0.0)), Lod::Near);
1720        // 100 units → Mid.
1721        assert_eq!(g.select_lod(DVec3::new(200.0, 0.0, 0.0)), Lod::Mid);
1722        // 500 units → Far.
1723        assert_eq!(g.select_lod(DVec3::new(600.0, 0.0, 0.0)), Lod::Far);
1724    }
1725}