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//! 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 lod::{select_lod, Lod, LodThresholds};
49pub use streaming::{ChunkGenerator, StreamRadius};
50
51/// XY size of one chunk in voxels. The plan locks 128 — keeps
52/// chunks compact (~2 MB worst-case dense-slab footprint inside
53/// each `Vxl`) and divides cleanly into voxlap's 2048 reference
54/// world size.
55pub const CHUNK_SIZE_XY: u32 = 128;
56
57/// Z size of one chunk in voxels. Locked at 256 to preserve
58/// voxlap's existing slab byte format unchanged inside each chunk
59/// — the per-chunk renderer doesn't need to know it's living
60/// inside a scene-graph.
61pub const CHUNK_SIZE_Z: u32 = 256;
62
63/// Stable identifier for a grid registered in a [`Scene`]. Issued
64/// by [`Scene::add_grid`]; persists across edits but a removed
65/// grid's id is not reissued.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
67pub struct GridId(u32);
68
69impl GridId {
70    /// The integer wire form. Useful for serde / debug output.
71    #[must_use]
72    pub const fn raw(self) -> u32 {
73        self.0
74    }
75}
76
77/// f64 world placement of one grid: position + orientation.
78///
79/// `origin` is the grid's local-space origin in world coords —
80/// chunk `(0, 0, 0)`'s `(0, 0, 0)` voxel maps to
81/// `origin + rotation * vec3(0, 0, 0)` (i.e. just `origin`).
82/// Voxel size is fixed at 1 world unit / voxel for v1.
83#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
84pub struct GridTransform {
85    pub origin: DVec3,
86    pub rotation: DQuat,
87}
88
89impl GridTransform {
90    /// Identity transform at world origin. Useful as a default for
91    /// the first grid added to an otherwise empty scene.
92    #[must_use]
93    pub fn identity() -> Self {
94        Self {
95            origin: DVec3::ZERO,
96            rotation: DQuat::IDENTITY,
97        }
98    }
99
100    /// Axis-aligned grid placed at `origin` with no rotation.
101    #[must_use]
102    pub fn at(origin: DVec3) -> Self {
103        Self {
104            origin,
105            rotation: DQuat::IDENTITY,
106        }
107    }
108}
109
110impl Default for GridTransform {
111    fn default() -> Self {
112        Self::identity()
113    }
114}
115
116/// Address of one voxel inside a scene: which grid it belongs to,
117/// which chunk within that grid, and the voxel's offset inside
118/// that chunk.
119///
120/// `chunk` is signed (`IVec3`) because chunks are centred on the
121/// grid's local origin and may extend in either direction. `voxel`
122/// is unsigned and must satisfy
123/// `(voxel.x, voxel.y) < CHUNK_SIZE_XY` and `voxel.z < CHUNK_SIZE_Z`.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
125pub struct GridAddr {
126    pub grid: GridId,
127    pub chunk: IVec3,
128    pub voxel: UVec3,
129}
130
131/// One independent voxel grid in a scene. Holds its world placement
132/// and a sparse map of populated chunks. Empty chunk slots are
133/// implicit air and skipped during rendering / raycasts.
134///
135/// Each chunk is internally a [`Vxl`] with `vsid = CHUNK_SIZE_XY`
136/// — the existing per-chunk renderer (opticast + grouscan +
137/// sprites + lighting in `roxlap-core`) runs on each chunk
138/// unchanged. Vertical worlds are built by stacking chunks along
139/// grid-local `+z`.
140#[derive(Debug)]
141pub struct Grid {
142    /// World placement (origin + rotation).
143    pub transform: GridTransform,
144    /// Sparse chunk storage keyed by `(chx, chy, chz)` chunk
145    /// coordinates. A missing entry means the chunk is fully air.
146    pub chunks: HashMap<IVec3, Vxl>,
147    /// Whether sky pixels rendered for this grid should be
148    /// composited into the final framebuffer. `true` is the
149    /// historical "grid owns its own sky" behaviour: ray misses
150    /// inside this grid's frustum paint sky_color into the temp
151    /// buffer. Set `false` for grids that are a foreground object
152    /// (e.g. a ship) — the sky is owned by a single "world" grid
153    /// (the ground) and other grids should not contribute sky
154    /// pixels, otherwise their grid-local-frame sky lookup
155    /// rotates with the grid and visibly fights the world's sky
156    /// during compose. See [`crate::render::render_scene_composed`]
157    /// for the masking implementation.
158    pub render_sky: bool,
159    /// Override [`roxlap_core::opticast::OpticastSettings::mip_levels`]
160    /// for this grid. `None` ⇒ use the caller's value. `Some(n)`
161    /// ⇒ cap at `n` (clamped to `[1, settings.mip_levels]`). Use
162    /// to disable multi-mip on a per-grid basis — small grids
163    /// (rotating ships, billboards) don't benefit from deep mips
164    /// and CAN trigger the
165    /// `[[project_axis_aligned_mip_beams]]`-style cf-cancellation
166    /// artifact when near-axis-aligned rays hit the rotated grid.
167    /// `Some(1)` = mip-0 only, byte-stable to single-mip.
168    pub mip_levels_override: Option<u32>,
169    /// World-distance thresholds for per-grid LOD tier selection
170    /// (S6.0). Defaults to [`LodThresholds::always_near`], so a
171    /// freshly-constructed grid always renders at full voxel (the
172    /// S5-and-earlier byte-stable behaviour). S6.1 plugs `Mid` into
173    /// the existing multi-mip path; S6.3 plugs `Far` into the
174    /// billboard impostor cache. See [`crate::lod`].
175    pub lod_thresholds: LodThresholds,
176    /// Lazy [`BillboardCache`] for the `Lod::Far` tier (S6.2).
177    /// `None` until the first time S6.3's render dispatch needs
178    /// it; populated then via [`BillboardCache::build`] and
179    /// cleared by edits ([`Self::set_voxel`] / [`Self::set_rect`]
180    /// / [`Self::set_sphere`]) to force a rebuild on next Far use.
181    /// Callers may also force-invalidate via direct assignment.
182    pub billboards: Option<BillboardCache>,
183    /// Optional procedural generator (S7.0). When set,
184    /// [`Self::ensure_chunk_generated`] uses it to materialise
185    /// chunks that are still absent from [`Self::chunks`].
186    ///
187    /// Streaming layers (S7.1+) walk the active radius around the
188    /// camera and call `ensure_chunk_generated` for missing chunks;
189    /// later stages dispatch this onto a background rayon pool. The
190    /// trait bound is `Send + Sync` (needed for S7.3 async
191    /// dispatch) + `Debug` (needed so [`Grid`] keeps deriving
192    /// `Debug`).
193    ///
194    /// `None` is the default — a grid without a generator behaves
195    /// exactly like the pre-S7 grids: absent chunks stay absent.
196    ///
197    /// `Arc` (not `Box`) so S7.3's async dispatch can clone the
198    /// generator into background rayon tasks without moving it out
199    /// of the grid. Trait bound `Send + Sync` (required at S7.0)
200    /// already makes `Arc<dyn ChunkGenerator>` `Send + Sync`.
201    pub generator: Option<Arc<dyn ChunkGenerator>>,
202    /// Streaming activity / eviction radii used by
203    /// [`Scene::pump_streaming_sync`] (S7.1). Defaults to
204    /// [`StreamRadius::DISABLED`] so existing grids see no change
205    /// in behaviour until the caller opts in.
206    pub stream_radius: StreamRadius,
207    /// Per-chunk edit version counter (S7.2). Each user edit
208    /// through [`Self::set_voxel`] / [`Self::set_rect`] /
209    /// [`Self::set_sphere`] bumps the counter for every chunk it
210    /// actually wrote to. [`Self::ensure_chunk_generated`] does
211    /// NOT bump — a freshly generated chunk has no edits and
212    /// reads as version 0.
213    ///
214    /// Wired up here so the S7.3 async dispatch can detect "an
215    /// edit happened while a chunk was being generated in the
216    /// background" and discard the now-stale result: each
217    /// background task captures the dispatch-time version and
218    /// only installs its result iff the current version still
219    /// matches.
220    ///
221    /// Missing entries read as `0` via [`Self::chunk_version`].
222    /// Evictions in [`Scene::pump_streaming_sync`] drop the
223    /// corresponding entry so the map stays bounded.
224    pub chunk_versions: HashMap<IVec3, u64>,
225    /// In-flight background generation tasks (S7.3).
226    ///
227    /// Populated by [`Scene::pump_streaming`] when it dispatches a
228    /// generator call onto the streaming rayon pool, drained when
229    /// the corresponding [`ChunkResult`] is received and processed
230    /// (either installed or discarded). The set is consulted to
231    /// avoid re-dispatching the same chunk while a previous task
232    /// is still running.
233    ///
234    /// Stays empty when only the synchronous
235    /// [`Scene::pump_streaming_sync`] is used — that path generates
236    /// inline on the calling thread.
237    ///
238    /// [`ChunkResult`]: streaming::ChunkResult
239    pub pending_gen: HashSet<IVec3>,
240}
241
242impl Grid {
243    /// New empty grid at the given transform — no chunks populated,
244    /// `render_sky = true`, LOD thresholds default to
245    /// [`LodThresholds::always_near`], no billboard cache.
246    #[must_use]
247    pub fn new(transform: GridTransform) -> Self {
248        Self {
249            transform,
250            chunks: HashMap::new(),
251            render_sky: true,
252            mip_levels_override: None,
253            lod_thresholds: LodThresholds::always_near(),
254            billboards: None,
255            generator: None,
256            stream_radius: StreamRadius::DISABLED,
257            chunk_versions: HashMap::new(),
258            pending_gen: HashSet::new(),
259        }
260    }
261
262    /// Current per-chunk edit version (S7.2). Returns `0` for any
263    /// chunk that hasn't been edited yet (including absent chunks
264    /// and chunks materialised only via
265    /// [`Self::ensure_chunk_generated`]).
266    ///
267    /// Used by S7.3's async generation dispatch to detect "edit
268    /// happened while we were generating" — the dispatcher
269    /// snapshots this value, the background task carries it, and
270    /// the result is discarded on install if the live counter has
271    /// since moved.
272    #[must_use]
273    pub fn chunk_version(&self, chunk_idx: IVec3) -> u64 {
274        self.chunk_versions.get(&chunk_idx).copied().unwrap_or(0)
275    }
276
277    /// Bump the edit version of `chunk_idx` (S7.2). Saturating add
278    /// at `u64::MAX` — a chunk would need 10^11 edits per second
279    /// for ~5 years to wrap, so saturation is a defensive cap, not
280    /// a realistic concern.
281    ///
282    /// Called by the edit API ([`Self::set_voxel`] /
283    /// [`Self::set_rect`] / [`Self::set_sphere`]) after a chunk
284    /// has actually been written to. Pure no-op edit paths
285    /// (carving from an air chunk that doesn't exist yet) skip
286    /// the bump.
287    pub(crate) fn bump_chunk_version(&mut self, chunk_idx: IVec3) {
288        let entry = self.chunk_versions.entry(chunk_idx).or_insert(0);
289        *entry = entry.saturating_add(1);
290    }
291
292    /// Attach (or detach) the procedural generator used by
293    /// [`Self::ensure_chunk_generated`] (S7.0).
294    ///
295    /// Pass `Some(Arc::new(generator))` to enable on-demand chunk
296    /// generation; pass `None` to revert to the "absent stays
297    /// absent" behaviour. Replacing an existing generator drops the
298    /// previous `Arc` clone without touching already-materialised
299    /// chunks. Any background tasks dispatched by a prior
300    /// [`Scene::pump_streaming`] hold their own clones of the old
301    /// generator and finish naturally.
302    pub fn set_generator(&mut self, generator: Option<Arc<dyn ChunkGenerator>>) {
303        self.generator = generator;
304    }
305
306    /// Materialise the chunk at `chunk_idx` by running [`Self::generator`]
307    /// if (a) the chunk is not already present and (b) a generator
308    /// is attached. Returns `true` iff a chunk was newly generated.
309    ///
310    /// No-ops in all other cases:
311    /// - chunk already present (caller edits / a previous
312    ///   `ensure_chunk_generated` call already populated it),
313    /// - no generator attached (the chunk stays implicit-air per
314    ///   the existing convention — does NOT fall through to
315    ///   [`Self::ensure_chunk`]'s empty-chunk constructor).
316    ///
317    /// This is the synchronous S7.0 path. S7.3 will add an async
318    /// counterpart that dispatches the generator call to a
319    /// dedicated rayon pool and installs the result on the next
320    /// `pump_streaming` call.
321    pub fn ensure_chunk_generated(&mut self, chunk_idx: IVec3) -> bool {
322        if self.chunks.contains_key(&chunk_idx) {
323            return false;
324        }
325        let Some(generator) = self.generator.as_ref() else {
326            return false;
327        };
328        // S7.6+: generator may decline specific indices (e.g. a
329        // single-z-layer generator skipping placeholder bedrock
330        // chunks at chz != 0). Respect the filter so we don't
331        // materialise an unwanted chunk.
332        if !generator.should_generate(chunk_idx) {
333            return false;
334        }
335        let chunk = generator.generate(chunk_idx);
336        self.chunks.insert(chunk_idx, chunk);
337        // S7.4: a fresh chunk grows the populated AABB → the
338        // bounding sphere shifts/expands → existing impostor
339        // projections become wrong. Match the eviction (S7.1) +
340        // edit (S6.2) invalidation contract and drop the cache.
341        // Next Far-tier render rebuilds lazily.
342        self.billboards = None;
343        true
344    }
345
346    /// Bounding-sphere radius of the populated chunk set in
347    /// grid-local space.
348    ///
349    /// Walks the sparse chunk map once, computes the chunk-index
350    /// AABB, converts to voxel-space half-extent, returns its
351    /// Euclidean length. Empty grid → `0.0`.
352    ///
353    /// Conservative — bounds the full chunk volume, not just its
354    /// populated voxels (a chunk containing one voxel still
355    /// contributes `CHUNK_SIZE_XY × CHUNK_SIZE_XY × CHUNK_SIZE_Z`
356    /// to the bbox). For LOD picking that's fine: an over-bound
357    /// sphere errs on the side of `Near`.
358    ///
359    /// Cost: `O(chunks.len())`; recomputed on every call. Callers
360    /// who need this every frame should memoize at the
361    /// [`Scene`]-level cache (added when S6.2 needs it).
362    #[must_use]
363    pub fn bounding_radius(&self) -> f64 {
364        if self.chunks.is_empty() {
365            return 0.0;
366        }
367        let mut min = IVec3::splat(i32::MAX);
368        let mut max = IVec3::splat(i32::MIN);
369        for &idx in self.chunks.keys() {
370            min = min.min(idx);
371            max = max.max(idx);
372        }
373        // Chunk-index bbox → voxel-space half-extent. `+1` on max
374        // converts inclusive chunk index to exclusive voxel upper
375        // bound (chunk `idx` covers voxels `[idx*size, (idx+1)*size)`).
376        let sx = f64::from(CHUNK_SIZE_XY);
377        let sz = f64::from(CHUNK_SIZE_Z);
378        let lo = DVec3::new(
379            f64::from(min.x) * sx,
380            f64::from(min.y) * sx,
381            f64::from(min.z) * sz,
382        );
383        let hi = DVec3::new(
384            f64::from(max.x + 1) * sx,
385            f64::from(max.y + 1) * sx,
386            f64::from(max.z + 1) * sz,
387        );
388        let half_extent = (hi - lo) * 0.5;
389        half_extent.length()
390    }
391
392    /// Pick this grid's LOD tier for the given world-space camera
393    /// position. Convenience wrapper around [`crate::select_lod`]
394    /// that pulls [`Self::lod_thresholds`] from the grid.
395    #[must_use]
396    pub fn select_lod(&self, camera_world_pos: DVec3) -> Lod {
397        select_lod(camera_world_pos, &self.transform, self.lod_thresholds)
398    }
399}
400
401/// Top-level scene container. Holds a flat collection of grids
402/// keyed by [`GridId`].
403///
404/// S2.0 only exposes registration / removal / lookup. Address math
405/// helpers (S2.x), edit API (S2.x), and rendering composition (S3)
406/// land in later sub-substages.
407#[derive(Debug, Default)]
408pub struct Scene {
409    grids: HashMap<GridId, Grid>,
410    next_grid_id: u32,
411    /// S7.3: per-scene streaming pool + result channel. Stored on
412    /// the `Scene` so `pump_streaming` can dispatch background
413    /// tasks and drain results across pump calls. `cfg`-gated out
414    /// on wasm32 where `pump_streaming` short-circuits to
415    /// `pump_streaming_sync` (no rayon pool there).
416    #[cfg(not(target_arch = "wasm32"))]
417    streaming: streaming::StreamingState,
418}
419
420impl Scene {
421    /// New empty scene — no grids.
422    #[must_use]
423    pub fn new() -> Self {
424        Self::default()
425    }
426
427    /// Number of grids currently registered.
428    #[must_use]
429    pub fn grid_count(&self) -> usize {
430        self.grids.len()
431    }
432
433    /// Register a new grid. Returns its fresh, unique [`GridId`].
434    pub fn add_grid(&mut self, transform: GridTransform) -> GridId {
435        let id = GridId(self.next_grid_id);
436        self.next_grid_id += 1;
437        self.grids.insert(id, Grid::new(transform));
438        id
439    }
440
441    /// Remove a grid by id. Returns the removed [`Grid`] (so the
442    /// caller can reclaim its chunks) or `None` if the id wasn't
443    /// registered. Removed ids are not reissued.
444    pub fn remove_grid(&mut self, id: GridId) -> Option<Grid> {
445        self.grids.remove(&id)
446    }
447
448    /// Borrow a registered grid.
449    #[must_use]
450    pub fn grid(&self, id: GridId) -> Option<&Grid> {
451        self.grids.get(&id)
452    }
453
454    /// Mutably borrow a registered grid.
455    pub fn grid_mut(&mut self, id: GridId) -> Option<&mut Grid> {
456        self.grids.get_mut(&id)
457    }
458
459    /// Iterator over all `(id, grid)` pairs in registration order
460    /// is **not** guaranteed — the underlying map is a `HashMap`.
461    /// Callers that need a stable order must sort by [`GridId`].
462    pub fn grids(&self) -> impl Iterator<Item = (GridId, &Grid)> {
463        self.grids.iter().map(|(id, g)| (*id, g))
464    }
465
466    /// Mutable iterator over all `(id, grid)` pairs. Yield order
467    /// is not guaranteed (HashMap-backed).
468    pub fn grids_mut(&mut self) -> impl Iterator<Item = (GridId, &mut Grid)> {
469        self.grids.iter_mut().map(|(id, g)| (*id, g))
470    }
471
472    /// Configure the number of worker threads in the dedicated
473    /// streaming pool (S7.3).
474    ///
475    /// Lazily applied — the pool itself is constructed on the first
476    /// [`Self::pump_streaming`] call. If the pool was already built
477    /// (i.e. a previous `pump_streaming` already dispatched at
478    /// least one task), it gets dropped and rebuilt. Dropping the
479    /// old pool blocks until all of its in-flight tasks finish
480    /// (rayon's contract); any results those tasks sent are still
481    /// drained by the next `pump_streaming` because the channel
482    /// survives the rebuild.
483    ///
484    /// The streaming pool is separate from rayon's global pool
485    /// (which R12 multicore rendering uses), so chunk generation
486    /// doesn't compete with render threads. Sensible values are 1
487    /// to ~4 — generation work is CPU-bound but should leave most
488    /// of the box for everything else.
489    ///
490    /// On wasm32 this is a no-op (no rayon pool available);
491    /// `pump_streaming` runs synchronously there.
492    ///
493    /// # Panics
494    /// Panics on native if `n == 0` (zero-thread pools are not
495    /// supported; the scene crate's S7.1 helper already disallows
496    /// the equivalent for `StreamRadius::r_active < 0`).
497    #[cfg(not(target_arch = "wasm32"))]
498    pub fn set_streaming_threads(&mut self, n: usize) {
499        self.streaming.set_thread_count(n);
500    }
501
502    /// wasm32 no-op companion of [`Self::set_streaming_threads`].
503    /// Lets cross-target code call this unconditionally.
504    #[cfg(target_arch = "wasm32")]
505    pub fn set_streaming_threads(&mut self, _n: usize) {
506        // No streaming pool on wasm32 — see `pump_streaming` docs.
507    }
508
509    /// Asynchronous streaming pump (S7.3).
510    ///
511    /// On native, dispatches missing-chunk generations onto a
512    /// dedicated rayon pool, drains any results that arrived since
513    /// the last pump, runs the eviction pass, and tracks in-flight
514    /// tasks in each grid's [`Grid::pending_gen`] set. The drain
515    /// uses the per-chunk version counter from S7.2 to discard
516    /// results whose chunk was edited mid-generation.
517    ///
518    /// On wasm32 this short-circuits to [`Self::pump_streaming_sync`]
519    /// — no thread pool is available there, but the same per-grid
520    /// stream-in / evict semantics apply.
521    ///
522    /// Call once per frame from the render thread. Cheap when
523    /// nothing changed (early-exit on disabled grids, try_recv
524    /// loops empty fast).
525    pub fn pump_streaming(&mut self, camera_world_pos: DVec3) {
526        #[cfg(target_arch = "wasm32")]
527        {
528            self.pump_streaming_sync(camera_world_pos);
529        }
530        #[cfg(not(target_arch = "wasm32"))]
531        {
532            self.pump_streaming_native(camera_world_pos);
533        }
534    }
535
536    /// Native implementation of [`Self::pump_streaming`].
537    #[cfg(not(target_arch = "wasm32"))]
538    fn pump_streaming_native(&mut self, camera_world_pos: DVec3) {
539        // 1. Drain inbox — install fresh results, drop stale.
540        while let Ok(result) = self.streaming.rx.try_recv() {
541            let Some(grid) = self.grids.get_mut(&result.grid_id) else {
542                // Grid was removed while a generation task was
543                // in-flight. Drop silently.
544                continue;
545            };
546            // Clearing pending_gen here both for "result delivered"
547            // and "we shouldn't try to re-dispatch this chunk just
548            // because it's missing".
549            let was_pending = grid.pending_gen.remove(&result.chunk_idx);
550            if !was_pending {
551                // Either the chunk was evicted (pending cleared in
552                // the eviction pass below in some prior call), or a
553                // duplicate result for an already-handled chunk.
554                continue;
555            }
556            if grid.chunks.contains_key(&result.chunk_idx) {
557                // Some other path (e.g. `ensure_chunk_generated`
558                // sync helper, or a manual edit's `ensure_chunk`)
559                // already populated the slot. Don't overwrite.
560                continue;
561            }
562            if grid.chunk_version(result.chunk_idx) != result.version_at_dispatch {
563                // S7.2 stale-result discard: chunk was edited mid-
564                // generation.
565                continue;
566            }
567            grid.chunks.insert(result.chunk_idx, result.vxl);
568            // S7.4: same invalidation contract as the sync
569            // `ensure_chunk_generated` path — installing a new
570            // chunk can grow the bounding sphere, so the
571            // billboard impostor cache must be rebuilt on next
572            // Far entry. Lazy: only one cache wipe per drain
573            // batch, the Far render rebuilds afterwards.
574            grid.billboards = None;
575        }
576
577        // 2. Per-grid: eviction first, then dispatch. Doing evict
578        //    before dispatch means a chunk that's just left
579        //    r_active doesn't get re-dispatched on the same pump.
580        self.streaming.ensure_pool();
581        // Disjoint sub-field borrows: pool/tx via `&self.streaming.*`,
582        // grids via `&mut self.grids`. Hold both at once.
583        let pool: &rayon::ThreadPool = self.streaming.pool.as_ref().expect("ensure_pool just ran");
584        let tx_template = &self.streaming.tx;
585        for (grid_id, grid) in &mut self.grids {
586            evict_grid_chunks(grid, camera_world_pos);
587            dispatch_grid_async(*grid_id, grid, camera_world_pos, pool, tx_template);
588        }
589    }
590
591    /// Synchronous streaming pump (S7.1).
592    ///
593    /// For each grid with a non-[`StreamRadius::DISABLED`] policy:
594    /// 1. Project the world-space camera into grid-local coords
595    ///    (inverse rotation + origin subtract).
596    /// 2. Stream in any chunk whose AABB-to-camera distance is
597    ///    `<= r_active`, calling [`Grid::ensure_chunk_generated`].
598    ///    No-ops gracefully if the grid has no generator attached
599    ///    (so callers can use the eviction half of streaming on a
600    ///    purely-edited grid).
601    /// 3. Evict any chunk whose AABB-to-camera distance exceeds
602    ///    `r_evict` from the grid's chunk map. Eviction also
603    ///    clears the cached [`BillboardCache`] (the bounding sphere
604    ///    may shrink, invalidating impostor projections; the next
605    ///    Far-tier render rebuilds lazily).
606    ///
607    /// Both passes use the f64 grid-local position so rotation
608    /// + non-axis-aligned grids stream and evict correctly. The
609    /// generate path is blocking — S7.3 will move it to a
610    /// background rayon pool with `pump_streaming` (non-blocking).
611    /// Callers that want the async variant in S7.0/S7.1 stages
612    /// should keep `r_active` small.
613    pub fn pump_streaming_sync(&mut self, camera_world_pos: DVec3) {
614        for grid in self.grids.values_mut() {
615            pump_grid_streaming_sync(grid, camera_world_pos);
616        }
617    }
618}
619
620/// S7.1 helper — drives one grid's synchronous streaming pass.
621/// Stream-in pass uses [`Grid::ensure_chunk_generated`] (blocking
622/// inline generation); eviction pass shared with the S7.3 async
623/// path through [`evict_grid_chunks`].
624fn pump_grid_streaming_sync(grid: &mut Grid, camera_world_pos: DVec3) {
625    let radius = grid.stream_radius;
626    if radius.is_disabled() {
627        return;
628    }
629    let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
630
631    // --- Pass 1: stream in active chunks (sync) ---------------
632    if radius.r_active > 0.0 && grid.generator.is_some() {
633        for_each_chunk_in_radius(cam_local, radius.r_active, |idx| {
634            grid.ensure_chunk_generated(idx);
635        });
636    }
637
638    // --- Pass 2: evict chunks past r_evict --------------------
639    evict_grid_chunks_with_cam(grid, cam_local);
640}
641
642/// Eviction pass shared by [`pump_grid_streaming_sync`] and the
643/// S7.3 async path. Public-ish so the async driver can call it
644/// before dispatching to avoid generating chunks that are about
645/// to be evicted. `cfg`-gated to native: on wasm32 the only
646/// caller (`pump_streaming_native`) doesn't compile, so this
647/// helper would warn as dead code.
648#[cfg(not(target_arch = "wasm32"))]
649fn evict_grid_chunks(grid: &mut Grid, camera_world_pos: DVec3) {
650    let radius = grid.stream_radius;
651    if radius.is_disabled() {
652        return;
653    }
654    let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
655    evict_grid_chunks_with_cam(grid, cam_local);
656}
657
658/// Eviction inner — assumes `cam_local` is already computed (the
659/// dispatcher and sync pump both have it on hand).
660fn evict_grid_chunks_with_cam(grid: &mut Grid, cam_local: DVec3) {
661    let radius = grid.stream_radius;
662    if !radius.r_evict.is_finite() {
663        return;
664    }
665    let r_sq = radius.r_evict * radius.r_evict;
666    let to_evict: Vec<IVec3> = grid
667        .chunks
668        .keys()
669        .filter(|&&idx| streaming::chunk_aabb_dist_sq(cam_local, idx) > r_sq)
670        .copied()
671        .collect();
672    // S7.3: also evict pending in-flight tasks past r_evict so the
673    // drain pass doesn't install a chunk that's no longer wanted.
674    // We don't have a way to cancel the rayon task, but we can
675    // drop the pending_gen entry so the result is dropped on
676    // arrival.
677    let to_evict_pending: Vec<IVec3> = grid
678        .pending_gen
679        .iter()
680        .filter(|&&idx| streaming::chunk_aabb_dist_sq(cam_local, idx) > r_sq)
681        .copied()
682        .collect();
683    if to_evict.is_empty() && to_evict_pending.is_empty() {
684        return;
685    }
686    for idx in &to_evict {
687        grid.chunks.remove(idx);
688        // S7.2: keep chunk_versions in sync with chunks so the
689        // map stays bounded. A future re-stream of the same idx
690        // restarts at 0 — that's fine because any in-flight
691        // gen-result tagged with the pre-eviction version is
692        // unreachable (no chunk to install onto) and gets
693        // discarded by the new "version still 0" check anyway.
694        grid.chunk_versions.remove(idx);
695        // S7.3: drop pending entry for the same chunk too. If a
696        // background task is still running, its result will be
697        // dropped on arrival (was_pending = false).
698        grid.pending_gen.remove(idx);
699    }
700    for idx in &to_evict_pending {
701        grid.pending_gen.remove(idx);
702    }
703    if !to_evict.is_empty() {
704        // Bounding sphere can shrink → impostor projections would
705        // be wrong on next Far render. Clear lazily; the next
706        // Far-tier pass repopulates via BillboardCache::build.
707        grid.billboards = None;
708    }
709}
710
711/// Walk every chunk index whose AABB falls within `r_active` of
712/// `cam_local` and invoke `f` on it. Shared between the S7.1 sync
713/// stream-in and the S7.3 async dispatch.
714fn for_each_chunk_in_radius<F>(cam_local: DVec3, r_active: f64, mut f: F)
715where
716    F: FnMut(IVec3),
717{
718    let r_sq = r_active * r_active;
719    let sxy = f64::from(CHUNK_SIZE_XY);
720    let sz = f64::from(CHUNK_SIZE_Z);
721    // Half-extent in chunk units; ceil to be conservative so any
722    // chunk whose AABB clips the radius gets considered. `+1`
723    // covers the half-open chunk-AABB upper edge plus the case
724    // where the camera sits exactly on a chunk boundary and the
725    // closest chunk is one index off.
726    #[allow(clippy::cast_possible_truncation)]
727    let r_chunks_xy = (r_active / sxy).ceil() as i32 + 1;
728    #[allow(clippy::cast_possible_truncation)]
729    let r_chunks_z = (r_active / sz).ceil() as i32 + 1;
730    #[allow(clippy::cast_possible_truncation)]
731    let cx_chunk = (cam_local.x / sxy).floor() as i32;
732    #[allow(clippy::cast_possible_truncation)]
733    let cy_chunk = (cam_local.y / sxy).floor() as i32;
734    #[allow(clippy::cast_possible_truncation)]
735    let cz_chunk = (cam_local.z / sz).floor() as i32;
736    for chz in (cz_chunk - r_chunks_z)..=(cz_chunk + r_chunks_z) {
737        for chy in (cy_chunk - r_chunks_xy)..=(cy_chunk + r_chunks_xy) {
738            for chx in (cx_chunk - r_chunks_xy)..=(cx_chunk + r_chunks_xy) {
739                let idx = IVec3::new(chx, chy, chz);
740                if streaming::chunk_aabb_dist_sq(cam_local, idx) <= r_sq {
741                    f(idx);
742                }
743            }
744        }
745    }
746}
747
748/// S7.3 async dispatch — schedule generation for every chunk in
749/// `r_active` that's not already present and not already in
750/// flight. Each dispatch clones the grid's generator `Arc` and a
751/// sender clone, then spawns the closure on the streaming rayon
752/// pool. The closure does the generate + send; the main thread
753/// drains results on the next pump.
754#[cfg(not(target_arch = "wasm32"))]
755fn dispatch_grid_async(
756    grid_id: GridId,
757    grid: &mut Grid,
758    camera_world_pos: DVec3,
759    pool: &rayon::ThreadPool,
760    tx: &crossbeam_channel::Sender<streaming::ChunkResult>,
761) {
762    let radius = grid.stream_radius;
763    if radius.is_disabled() || radius.r_active <= 0.0 {
764        return;
765    }
766    let Some(generator) = grid.generator.as_ref().map(Arc::clone) else {
767        return;
768    };
769    let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
770    for_each_chunk_in_radius(cam_local, radius.r_active, |idx| {
771        if grid.chunks.contains_key(&idx) {
772            return; // already present
773        }
774        if grid.pending_gen.contains(&idx) {
775            return; // already in flight
776        }
777        // S7.6+: respect the generator's per-chunk filter — same
778        // contract as `Grid::ensure_chunk_generated` (sync helper).
779        // Lets a generator decline to materialise specific indices
780        // (e.g. `HillsChunkGenerator` skipping placeholder bedrock
781        // chunks at chz != 0 so the camera-above-grid path doesn't
782        // create chz < 0 entries that would shift `origin_chunk_z`
783        // and trigger the S4B.6.j cross-chunk look-down bug).
784        if !generator.should_generate(idx) {
785            return;
786        }
787        grid.pending_gen.insert(idx);
788        let version_at_dispatch = grid.chunk_version(idx);
789        let tx_clone = tx.clone();
790        let gen_clone = Arc::clone(&generator);
791        pool.spawn(move || {
792            let vxl = gen_clone.generate(idx);
793            // Send is non-blocking on unbounded channel; if the
794            // receiver was dropped (Scene drop), the send fails
795            // silently — that's fine.
796            let _ = tx_clone.send(streaming::ChunkResult {
797                grid_id,
798                chunk_idx: idx,
799                version_at_dispatch,
800                vxl,
801            });
802        });
803    });
804}
805
806#[cfg(test)]
807mod tests {
808    use super::*;
809
810    #[test]
811    fn empty_scene_has_no_grids() {
812        let scene = Scene::new();
813        assert_eq!(scene.grid_count(), 0);
814        assert!(scene.grids().next().is_none());
815    }
816
817    #[test]
818    fn add_grid_returns_fresh_ids() {
819        let mut scene = Scene::new();
820        let a = scene.add_grid(GridTransform::identity());
821        let b = scene.add_grid(GridTransform::at(DVec3::new(100.0, 0.0, 0.0)));
822        assert_ne!(a, b);
823        assert_eq!(a.raw(), 0);
824        assert_eq!(b.raw(), 1);
825        assert_eq!(scene.grid_count(), 2);
826    }
827
828    #[test]
829    fn grid_lookup_round_trips() {
830        let mut scene = Scene::new();
831        let id = scene.add_grid(GridTransform::at(DVec3::new(10.0, 20.0, 30.0)));
832        let g = scene.grid(id).expect("grid registered");
833        assert_eq!(g.transform.origin, DVec3::new(10.0, 20.0, 30.0));
834        assert_eq!(g.transform.rotation, DQuat::IDENTITY);
835        assert!(g.chunks.is_empty());
836    }
837
838    #[test]
839    fn remove_grid_drops_it_from_scene() {
840        let mut scene = Scene::new();
841        let id = scene.add_grid(GridTransform::identity());
842        let removed = scene.remove_grid(id);
843        assert!(removed.is_some());
844        assert_eq!(scene.grid_count(), 0);
845        assert!(scene.grid(id).is_none());
846        // Re-adding does NOT reuse the dropped id.
847        let id2 = scene.add_grid(GridTransform::identity());
848        assert_ne!(id, id2);
849        assert_eq!(id2.raw(), 1);
850    }
851
852    #[test]
853    fn remove_unknown_grid_is_none() {
854        let mut scene = Scene::new();
855        let bogus = GridId(999);
856        assert!(scene.remove_grid(bogus).is_none());
857    }
858
859    #[test]
860    fn grid_mut_can_modify_transform() {
861        let mut scene = Scene::new();
862        let id = scene.add_grid(GridTransform::identity());
863        scene.grid_mut(id).unwrap().transform.origin = DVec3::new(1.0, 2.0, 3.0);
864        assert_eq!(
865            scene.grid(id).unwrap().transform.origin,
866            DVec3::new(1.0, 2.0, 3.0)
867        );
868    }
869
870    #[test]
871    fn chunk_size_constants_match_plan() {
872        // Plan locks these values; bumping either breaks the slab
873        // byte format (Z) or the worst-case chunk footprint budget
874        // (XY). Pin them so a future refactor that drifts them
875        // shows up in CI.
876        assert_eq!(CHUNK_SIZE_XY, 128);
877        assert_eq!(CHUNK_SIZE_Z, 256);
878    }
879
880    // ---- S6.0: bounding_radius + Grid::select_lod ----
881
882    #[test]
883    fn new_grid_defaults_to_always_near_lod() {
884        // Byte-identity contract for the staged S6 rollout: a
885        // grid built through `new` must never trigger the Mid/Far
886        // branches by accident, even when bounding_radius would
887        // imply otherwise.
888        let g = Grid::new(GridTransform::identity());
889        assert_eq!(g.lod_thresholds.r_near, f64::INFINITY);
890        assert_eq!(g.lod_thresholds.r_mid, f64::INFINITY);
891        assert_eq!(g.select_lod(DVec3::new(1e9, 0.0, 0.0)), Lod::Near);
892    }
893
894    #[test]
895    fn bounding_radius_empty_grid_is_zero() {
896        let g = Grid::new(GridTransform::identity());
897        assert_eq!(g.bounding_radius(), 0.0);
898    }
899
900    #[test]
901    fn bounding_radius_single_chunk_at_origin() {
902        // One chunk at (0, 0, 0): bbox is [0, 128) × [0, 128) × [0, 256).
903        // Half-extent = (64, 64, 128); length = sqrt(64² + 64² + 128²)
904        //   = sqrt(4096 + 4096 + 16384) = sqrt(24576) ≈ 156.7747...
905        let mut scene = Scene::new();
906        let id = scene.add_grid(GridTransform::identity());
907        let g = scene.grid_mut(id).unwrap();
908        // Populate chunk (0, 0, 0) via the edit API.
909        g.set_voxel(IVec3::new(0, 0, 0), Some(0x80_88_88_88));
910        let r = g.bounding_radius();
911        let expected = ((64.0_f64).powi(2) * 2.0 + (128.0_f64).powi(2)).sqrt();
912        assert!(
913            (r - expected).abs() < 1e-9,
914            "bounding_radius={r} expected={expected}"
915        );
916    }
917
918    #[test]
919    fn bounding_radius_grows_with_chunk_extent() {
920        // Two chunks at (0,0,0) and (3,0,0): x extent is 4 chunks =
921        // 512 voxels; y/z are 1 chunk each. Half-extent = (256, 64, 128);
922        // length = sqrt(256² + 64² + 128²) = sqrt(65536+4096+16384)
923        //        = sqrt(86016) ≈ 293.2848.
924        let mut scene = Scene::new();
925        let id = scene.add_grid(GridTransform::identity());
926        let g = scene.grid_mut(id).unwrap();
927        // Stamp one voxel in chunk (0,0,0).
928        g.set_voxel(IVec3::new(0, 0, 0), Some(0x80_88_88_88));
929        // Stamp one voxel in chunk (3,0,0): grid-local x = 3*128 = 384.
930        g.set_voxel(IVec3::new(384, 0, 0), Some(0x80_88_88_88));
931        assert_eq!(g.chunks.len(), 2);
932        let r = g.bounding_radius();
933        let expected = (256.0_f64.powi(2) + 64.0_f64.powi(2) + 128.0_f64.powi(2)).sqrt();
934        assert!(
935            (r - expected).abs() < 1e-9,
936            "bounding_radius={r} expected={expected}"
937        );
938    }
939
940    #[test]
941    fn grid_select_lod_respects_lod_thresholds_field() {
942        // Set a non-default threshold and verify the helper picks
943        // the right tier for known distances.
944        let mut scene = Scene::new();
945        let id = scene.add_grid(GridTransform::at(DVec3::new(100.0, 0.0, 0.0)));
946        let g = scene.grid_mut(id).unwrap();
947        g.lod_thresholds = LodThresholds {
948            r_near: 50.0,
949            r_mid: 200.0,
950            ..LodThresholds::always_near()
951        };
952        // Camera 25 units from grid origin → Near.
953        assert_eq!(g.select_lod(DVec3::new(125.0, 0.0, 0.0)), Lod::Near);
954        // 100 units → Mid.
955        assert_eq!(g.select_lod(DVec3::new(200.0, 0.0, 0.0)), Lod::Mid);
956        // 500 units → Far.
957        assert_eq!(g.select_lod(DVec3::new(600.0, 0.0, 0.0)), Lod::Far);
958    }
959}