Skip to main content

roxlap_scene/
chunks.rs

1//! Sparse chunk storage helpers.
2//!
3//! A grid's [`Grid::chunks`] map holds populated chunks keyed by
4//! their `(chx, chy, chz)` index. A missing entry is an implicit
5//! all-air chunk; this module provides the constructor for fresh
6//! all-air chunks plus the `chunk` / `chunk_mut` / `ensure_chunk`
7//! lookup API.
8//!
9//! [`Grid::chunks`]: crate::Grid::chunks
10
11use glam::IVec3;
12use roxlap_formats::edit::{set_spans, Vspan};
13use roxlap_formats::vxl::Vxl;
14
15use crate::{Grid, CHUNK_SIZE_XY, CHUNK_SIZE_Z};
16
17/// Bytes of edit-pool headroom reserved per chunk on creation.
18/// 256 bytes/column × 128² columns ≈ 4 MiB; a generous budget for
19/// runtime edits within a single chunk before [`voxalloc`] starts
20/// returning out-of-space. Tunable later if memory becomes an
21/// issue.
22///
23/// [`voxalloc`]: roxlap_formats::vxl::Vxl::voxalloc
24const CHUNK_EDIT_HEADROOM_PER_COLUMN: usize = 256;
25
26/// Construct a fresh all-air [`Vxl`] sized for one chunk
27/// (`vsid = CHUNK_SIZE_XY`).
28///
29/// Strategy mirrors `roxlap_cavegen::pack_dense_grid_to_vxl`: seed
30/// each column with one solid voxel at z=0 + implicit-solid below
31/// (the voxlap "loadnul" shape), then carve the entire z range to
32/// air via [`set_spans`]. Finishes with [`Vxl::reserve_edit_capacity`]
33/// so subsequent runtime edits don't need a separate upgrade pass.
34///
35/// This is the canonical empty-chunk constructor — every code
36/// path that materialises a sparse chunk goes through it (see
37/// [`Grid::ensure_chunk`]).
38pub(crate) fn empty_chunk_vxl() -> Vxl {
39    let vsid = CHUNK_SIZE_XY;
40    let n_cols = (vsid as usize) * (vsid as usize);
41
42    // 1. Seed: every column = 4-byte slab header + 1 colour. Colour
43    //    is irrelevant — the whole column gets carved below.
44    let mut data: Vec<u8> = Vec::with_capacity(n_cols * 8);
45    let mut column_offset: Vec<u32> = Vec::with_capacity(n_cols + 1);
46    for _ in 0..n_cols {
47        column_offset.push(u32::try_from(data.len()).expect("offset fits in u32"));
48        data.extend_from_slice(&[0, 0, 0, 0]); // header
49        data.extend_from_slice(&[0, 0, 0, 0]); // 1 placeholder colour
50    }
51    column_offset.push(u32::try_from(data.len()).expect("offset fits in u32"));
52
53    let mut vxl = Vxl {
54        vsid,
55        // Per-grid placement lives on `GridTransform`; the per-chunk
56        // Vxl's intrinsic camera fields are unused at this layer.
57        ipo: [0.0; 3],
58        ist: [1.0, 0.0, 0.0],
59        ihe: [0.0, 0.0, 1.0],
60        ifo: [0.0, 1.0, 0.0],
61        data: data.into_boxed_slice(),
62        column_offset: column_offset.into_boxed_slice(),
63        mip_base_offsets: Box::new([0, n_cols + 1]),
64        vbit: Box::new([]),
65        vbiti: 0,
66    };
67    vxl.reserve_edit_capacity(n_cols * CHUNK_EDIT_HEADROOM_PER_COLUMN);
68
69    // 2. Carve [0, 255] in every column to make it all-air.
70    //    `Vspan.z1` is inclusive per voxlap's vspans convention.
71    let mut spans: Vec<Vspan> = Vec::with_capacity(n_cols);
72    for y in 0..vsid {
73        for x in 0..vsid {
74            spans.push(Vspan {
75                x,
76                y,
77                z0: 0,
78                z1: u8::MAX,
79            });
80        }
81    }
82    set_spans(&mut vxl, &spans, None);
83
84    vxl
85}
86
87/// True if voxel `(x, y, z)` is solid within one chunk's [`Vxl`] —
88/// i.e. covered by a solid run in column `(x, y)`. `(x, y)` are
89/// `< CHUNK_SIZE_XY`, `z < CHUNK_SIZE_Z`.
90///
91/// PF.6 — walks the slab chain in place with an early-out at `z`,
92/// mirroring `expandrle`'s run derivation ONE RUN AT A TIME instead of
93/// heap-allocating a 516-int buffer and decoding the whole column per
94/// query (this sits on every CPU shadow-ray step and every
95/// `Scene::raycast` step). Run k spans `[top_k, bot_k)` where `top_0 =
96/// slab[1]`, each following non-degenerate slab header closes the
97/// previous run at `slab[v+3]` and opens the next at `slab[v+1]`, and
98/// the final run extends to the column bottom — exactly the list
99/// `expandrle` would emit.
100#[allow(clippy::cast_possible_wrap)]
101pub(crate) fn vxl_voxel_solid(vxl: &Vxl, x: u32, y: u32, z: u32) -> bool {
102    let idx = (y * vxl.vsid + x) as usize;
103    let slab = vxl.column_data(idx);
104    let z = z as i32;
105    let mut top = i32::from(slab[1]);
106    let mut v = 0usize;
107    while slab[v] != 0 {
108        v += usize::from(slab[v]) * 4;
109        if slab[v + 3] >= slab[v + 1] {
110            // Degenerate slab (no air gap above): merges into the
111            // current run — same skip `expandrle` takes.
112            continue;
113        }
114        let bot = i32::from(slab[v + 3]);
115        if z < bot {
116            // z is above this run's bottom: solid iff inside the run
117            // (below `top` would be the preceding air gap).
118            return z >= top;
119        }
120        top = i32::from(slab[v + 1]);
121    }
122    // Last run extends to the column bottom (bedrock).
123    z >= top
124}
125
126/// PF.6 — chunk-cached solid sampler for DDA marches. Consecutive steps
127/// almost always stay inside one chunk; caching the last `chunks`
128/// HashMap probe turns the per-step cost into one compare + the in-place
129/// slab walk. `chunk_at` exposes presence so callers can skip absent
130/// (all-air) chunks wholesale.
131pub(crate) struct SolidSampler<'a> {
132    grid: &'a Grid,
133    cached_idx: IVec3,
134    cached: Option<&'a Vxl>,
135    primed: bool,
136}
137
138impl<'a> SolidSampler<'a> {
139    /// The chunk holding grid-local voxel-space chunk index `chunk_idx`,
140    /// through the one-entry cache.
141    pub(crate) fn chunk_at(&mut self, chunk_idx: IVec3) -> Option<&'a Vxl> {
142        if !self.primed || chunk_idx != self.cached_idx {
143            self.cached = self.grid.chunk(chunk_idx);
144            self.cached_idx = chunk_idx;
145            self.primed = true;
146        }
147        self.cached
148    }
149}
150
151/// What [`Grid::bake`] / [`Grid::bake_bbox`] write into the per-voxel
152/// brightness byte (QE-B6 — replaces the voxlap magic-`u32` lightmode).
153#[derive(Debug, Clone, Copy, PartialEq)]
154pub enum BakeMode {
155    /// Directional estnorm shading (voxlap lightmode 1) — the classic
156    /// standalone look for hosts that don't run a dynamic light rig.
157    Directional,
158    /// Ambient occlusion (lightmode 3): crevices and inner corners
159    /// darken. The right bake *under* a runtime `LightRig`, which
160    /// reads the byte as its ambient/AO fill. Carries its tuning
161    /// parameters — unlike the deprecated `bake_lightmode_bbox`,
162    /// [`Grid::bake_bbox`] honours them.
163    AmbientOcclusion(roxlap_core::AoParams),
164}
165
166impl BakeMode {
167    /// The voxlap wire value the bake internals consume.
168    fn lightmode(self) -> u32 {
169        match self {
170            Self::Directional => 1,
171            Self::AmbientOcclusion(_) => 3,
172        }
173    }
174
175    /// The AO parameters (defaults for the non-AO mode, where the
176    /// bake ignores them).
177    fn ao(self) -> roxlap_core::AoParams {
178        match self {
179            Self::Directional => roxlap_core::AoParams::default(),
180            Self::AmbientOcclusion(ao) => ao,
181        }
182    }
183}
184
185impl Grid {
186    /// True if the grid-local integer voxel `voxel` is solid (inside a
187    /// solid run of its chunk). An implicit-air or absent chunk reads
188    /// as `false`. `voxel` is a grid-local voxel coordinate
189    /// (pre-transform) — get one from a world point via
190    /// [`crate::world_to_grid_local`] + [`crate::voxel_global`]. Useful
191    /// for picking, collision, and world queries.
192    #[must_use]
193    pub fn voxel_solid(&self, voxel: IVec3) -> bool {
194        let (chunk_idx, in_chunk) = crate::voxel_split(voxel);
195        match self.chunk(chunk_idx) {
196            Some(vxl) => vxl_voxel_solid(vxl, in_chunk.x, in_chunk.y, in_chunk.z),
197            None => false,
198        }
199    }
200
201    /// PF.6 — a chunk-cached [`SolidSampler`] over this grid, for DDA
202    /// marches that issue many [`Self::voxel_solid`]-style queries with
203    /// strong chunk locality (shadow rays, `Scene::raycast`).
204    pub(crate) fn solid_sampler(&self) -> SolidSampler<'_> {
205        SolidSampler {
206            grid: self,
207            cached_idx: IVec3::ZERO,
208            cached: None,
209            primed: false,
210        }
211    }
212
213    /// Packed BGRA colour of the textured voxel at grid-local `voxel`,
214    /// or `None` for air / untextured cells. Thin wrapper over
215    /// [`roxlap_formats::vxl::Vxl::voxel_color`] after the chunk split —
216    /// the colour-inspection companion to [`Self::voxel_solid`]. Use it
217    /// to read back what a pick / raycast hit looks like.
218    #[must_use]
219    pub fn voxel_color(&self, voxel: IVec3) -> Option<roxlap_formats::color::VoxColor> {
220        let (chunk_idx, in_chunk) = crate::voxel_split(voxel);
221        self.chunk(chunk_idx)?
222            .voxel_color(in_chunk.x, in_chunk.y, in_chunk.z)
223    }
224
225    /// Borrow the chunk at `chunk_idx` if it has been materialised.
226    /// `None` means the chunk is implicitly all-air.
227    #[must_use]
228    pub fn chunk(&self, chunk_idx: IVec3) -> Option<&Vxl> {
229        self.chunks.get(&chunk_idx)
230    }
231
232    /// Bake per-voxel lighting (voxlap `updatevxl`/`estnorm` shading)
233    /// into every materialised chunk's brightness bytes, in place.
234    /// Both the CPU rasteriser and the GPU marcher read these
235    /// pre-baked brightness bytes, so call this once after building a
236    /// grid and again over edited chunks after a carve (then bump
237    /// their versions so the GPU re-uploads — edits already do, via
238    /// [`Grid::set_voxel`] &c.). For small runtime edits prefer
239    /// [`Self::bake_bbox`] — it re-bakes only the touched columns.
240    ///
241    /// Each chunk is baked neighbour-aware in all three axes: estnorm's
242    /// (and AO's) ±2-voxel padding that crosses a chunk face reads the
243    /// actual neighbour chunk (when populated) — XY neighbours and, for
244    /// stacked grids, the chunks above/below on `chz±1` — so brightness
245    /// / occlusion is continuous across every seam. Point lights aren't
246    /// applied (directional-only) — matching the demos' bake. No-op for
247    /// an empty grid.
248    pub fn bake(&mut self, mode: BakeMode) {
249        self.bake_u32(mode.lightmode(), mode.ao());
250    }
251
252    /// QE-B6 — magic `u32` lightmode; use [`Self::bake`] with a typed
253    /// [`BakeMode`] instead (`1` → `BakeMode::Directional`, `3` →
254    /// `BakeMode::AmbientOcclusion(AoParams::default())`).
255    #[deprecated(since = "0.23.0", note = "use `bake(BakeMode::..)`")]
256    pub fn bake_lightmode(&mut self, lightmode: u32) {
257        self.bake_u32(lightmode, roxlap_core::AoParams::default());
258    }
259
260    /// QE-B6 — use [`Self::bake`] with
261    /// `BakeMode::AmbientOcclusion(ao)` instead.
262    #[deprecated(since = "0.23.0", note = "use `bake(BakeMode::AmbientOcclusion(ao))`")]
263    pub fn bake_lightmode_with_ao(&mut self, lightmode: u32, ao: roxlap_core::AoParams) {
264        self.bake_u32(lightmode, ao);
265    }
266
267    fn bake_u32(&mut self, lightmode: u32, ao: roxlap_core::AoParams) {
268        if lightmode == 0 {
269            return;
270        }
271        #[allow(clippy::cast_possible_wrap)]
272        let cs_xy = CHUNK_SIZE_XY as i32;
273        #[allow(clippy::cast_possible_wrap)]
274        let cs_z = CHUNK_SIZE_Z as i32;
275        let chunk_idxs: Vec<IVec3> = self.chunks.keys().copied().collect();
276        // PF.11 — wave-parallel cache phase: each chunk's estnorm cache
277        // reads the grid immutably and is independent of the others, so a
278        // wave of `current_num_threads` caches builds in parallel; the
279        // apply phase (itself row-parallel inside
280        // `apply_lighting_with_cache`) then runs per chunk. Waves bound
281        // the resident cache memory. Byte-identical to the serial bake —
282        // caches are pure functions of the (unmodified-during-the-wave)
283        // grid, and each apply writes only its own chunk.
284        use rayon::prelude::*;
285        let wave = rayon::current_num_threads().max(1);
286        for batch in chunk_idxs.chunks(wave) {
287            let caches: Vec<(IVec3, roxlap_core::EstNormCache)> = batch
288                .par_iter()
289                .map(|&chunk_idx| {
290                    (
291                        chunk_idx,
292                        self.build_chunk_estnorm_cache(chunk_idx, 0, 0, cs_xy, cs_xy),
293                    )
294                })
295                .collect();
296            for (chunk_idx, cache) in caches {
297                let target = self.chunks.get_mut(&chunk_idx).expect("populated chunk");
298                roxlap_core::apply_lighting_with_cache(
299                    &mut target.data,
300                    &target.column_offset,
301                    CHUNK_SIZE_XY,
302                    0,
303                    0,
304                    0,
305                    cs_xy,
306                    cs_xy,
307                    cs_z,
308                    &cache,
309                    lightmode,
310                    &[],
311                    ao,
312                );
313            }
314        }
315    }
316
317    /// PF.11 — re-bake lighting over just the grid-local voxel bbox
318    /// `[lo, hi]` (inclusive), neighbour-aware across chunk seams in all
319    /// three axes: the write region is padded by `±ESTNORMRAD` internally
320    /// (an edit changes the estnorm of nearby voxels too — pass only the
321    /// geometric edit extent, mirroring `update_lighting`'s convention),
322    /// and any chunk the padded region touches gets its strip re-baked.
323    /// Touched chunks get their versions bumped so the GPU re-uploads.
324    ///
325    /// This is the runtime-edit primitive the full-grid
326    /// [`Self::bake_lightmode`] is far too heavy for: a bullet-hole
327    /// rebake touches a few hundred columns instead of a whole chunk
328    /// (the cave demo measured ~0.04 ms vs 4–7 ms). Mip regeneration is
329    /// NOT performed — near-field renders read mip 0; callers streaming
330    /// distant edited chunks should remip as they already do for edits.
331    #[allow(clippy::cast_possible_wrap)]
332    pub fn bake_bbox(&mut self, lo: IVec3, hi: IVec3, mode: BakeMode) {
333        self.bake_bbox_u32(lo, hi, mode.lightmode(), mode.ao());
334    }
335
336    /// QE-B6 — magic `u32` lightmode, and this variant silently baked
337    /// AO with default params. Use [`Self::bake_bbox`] with a typed
338    /// [`BakeMode`] (which honours `AmbientOcclusion`'s params).
339    #[deprecated(since = "0.23.0", note = "use `bake_bbox(lo, hi, BakeMode::..)`")]
340    pub fn bake_lightmode_bbox(&mut self, lo: IVec3, hi: IVec3, lightmode: u32) {
341        self.bake_bbox_u32(lo, hi, lightmode, roxlap_core::AoParams::default());
342    }
343
344    #[allow(clippy::cast_possible_wrap)]
345    fn bake_bbox_u32(&mut self, lo: IVec3, hi: IVec3, lightmode: u32, ao: roxlap_core::AoParams) {
346        if lightmode == 0 {
347            return;
348        }
349        let cs_xy = CHUNK_SIZE_XY as i32;
350        let cs_z = CHUNK_SIZE_Z as i32;
351        let pad = roxlap_core::ESTNORMRAD;
352        // Padded half-open apply region in grid-local voxel coords.
353        let a_lo = IVec3::new(lo.x - pad, lo.y - pad, lo.z - pad);
354        let a_hi = IVec3::new(hi.x + pad + 1, hi.y + pad + 1, hi.z + pad + 1);
355        if a_lo.x >= a_hi.x || a_lo.y >= a_hi.y || a_lo.z >= a_hi.z {
356            return;
357        }
358        // Chunk range the padded region touches (inclusive).
359        let c_lo = IVec3::new(
360            a_lo.x.div_euclid(cs_xy),
361            a_lo.y.div_euclid(cs_xy),
362            a_lo.z.div_euclid(cs_z),
363        );
364        let c_hi = IVec3::new(
365            (a_hi.x - 1).div_euclid(cs_xy),
366            (a_hi.y - 1).div_euclid(cs_xy),
367            (a_hi.z - 1).div_euclid(cs_z),
368        );
369        for chz in c_lo.z..=c_hi.z {
370            for chy in c_lo.y..=c_hi.y {
371                for chx in c_lo.x..=c_hi.x {
372                    let chunk_idx = IVec3::new(chx, chy, chz);
373                    if !self.chunks.contains_key(&chunk_idx) {
374                        continue;
375                    }
376                    // Clip the padded region to this chunk, chunk-local.
377                    let base = IVec3::new(chx * cs_xy, chy * cs_xy, chz * cs_z);
378                    let lx0 = (a_lo.x - base.x).max(0);
379                    let ly0 = (a_lo.y - base.y).max(0);
380                    let lz0 = (a_lo.z - base.z).max(0);
381                    let lx1 = (a_hi.x - base.x).min(cs_xy);
382                    let ly1 = (a_hi.y - base.y).min(cs_xy);
383                    let lz1 = (a_hi.z - base.z).min(cs_z);
384                    if lx0 >= lx1 || ly0 >= ly1 || lz0 >= lz1 {
385                        continue;
386                    }
387                    let cache = self.build_chunk_estnorm_cache(chunk_idx, lx0, ly0, lx1, ly1);
388                    let target = self.chunks.get_mut(&chunk_idx).expect("populated chunk");
389                    roxlap_core::apply_lighting_with_cache(
390                        &mut target.data,
391                        &target.column_offset,
392                        CHUNK_SIZE_XY,
393                        lx0,
394                        ly0,
395                        lz0,
396                        lx1,
397                        ly1,
398                        lz1,
399                        &cache,
400                        lightmode,
401                        &[],
402                        ao,
403                    );
404                    // PF.12 — brightness bytes changed within the clipped
405                    // region only.
406                    self.bump_chunk_version_bbox(
407                        chunk_idx,
408                        IVec3::new(lx0, ly0, lz0),
409                        IVec3::new(lx1 - 1, ly1 - 1, lz1 - 1),
410                    );
411                }
412            }
413        }
414    }
415
416    /// PF.11 — build the neighbour-aware estnorm cache for a chunk-local
417    /// region of `chunk_idx` from an immutable grid borrow: the reader
418    /// resolves a chunk-local `(px, py)` (which may extend `±ESTNORMRAD`
419    /// outside the region / the target chunk) into the neighbour chunk
420    /// owning that column, and `chz_delta` walks the stacked neighbour in
421    /// z (continuous AO + estnorm across every seam). Padding over an
422    /// unpopulated neighbour returns `None` (= treated as air).
423    #[allow(clippy::cast_possible_wrap)]
424    fn build_chunk_estnorm_cache(
425        &self,
426        chunk_idx: IVec3,
427        x0: i32,
428        y0: i32,
429        x1: i32,
430        y1: i32,
431    ) -> roxlap_core::EstNormCache {
432        let cs_xy = CHUNK_SIZE_XY as i32;
433        let reader = |px: i32, py: i32, chz_delta: i32| -> Option<&[u8]> {
434            let nb_chx = chunk_idx.x + px.div_euclid(cs_xy);
435            let nb_chy = chunk_idx.y + py.div_euclid(cs_xy);
436            let in_x = px.rem_euclid(cs_xy);
437            let in_y = py.rem_euclid(cs_xy);
438            let chunk = self.chunk(IVec3::new(nb_chx, nb_chy, chunk_idx.z + chz_delta))?;
439            let col_idx = (in_y as u32) * CHUNK_SIZE_XY + (in_x as u32);
440            let off = chunk.column_offset[col_idx as usize] as usize;
441            Some(&chunk.data[off..])
442        };
443        roxlap_core::EstNormCache::build_with_reader_z(reader, x0, y0, x1, y1)
444    }
445
446    /// Mutably borrow a materialised chunk. Returns `None` for
447    /// implicit-air chunks; use [`Grid::ensure_chunk`] when you
448    /// need a `&mut Vxl` for an edit that may write voxels.
449    pub fn chunk_mut(&mut self, chunk_idx: IVec3) -> Option<&mut Vxl> {
450        self.chunks.get_mut(&chunk_idx)
451    }
452
453    /// Borrow `chunk_idx`'s [`Vxl`], creating an empty all-air
454    /// chunk first if it doesn't exist yet. The returned `&mut`
455    /// is valid for editing via [`roxlap_formats::edit`] — the new
456    /// chunk has [`Vxl::reserve_edit_capacity`] already applied.
457    pub fn ensure_chunk(&mut self, chunk_idx: IVec3) -> &mut Vxl {
458        // PF.13 (H9) — materialising a chunk mutates the chunk set.
459        if !self.chunks.contains_key(&chunk_idx) {
460            self.note_chunk_set_changed();
461        }
462        self.chunks.entry(chunk_idx).or_insert_with(empty_chunk_vxl)
463    }
464
465    /// Number of materialised chunks. Implicit-air chunks don't
466    /// count.
467    #[must_use]
468    pub fn chunk_count(&self) -> usize {
469        self.chunks.len()
470    }
471
472    /// S4B.2.c.3: build a per-chunk [`roxlap_core::GridView`] table
473    /// over this grid's XY chunk footprint at `chz = 0`.
474    ///
475    /// Returns `None` if no chz=0 chunk is populated (the entire
476    /// grid would render as implicit air anyway).
477    ///
478    /// Iterates `chunks` once to find the chx/chy bounding box,
479    /// then a second time to fill the row-major
480    /// `Vec<Option<GridView<'_>>>`. Empty XY slots (implicit-air
481    /// chunks inside the box) get `None`.
482    ///
483    /// Pair with [`roxlap_core::ChunkGrid`] + [`roxlap_core::
484    /// GridView::from_chunk_grid`] to drive the Approach B render
485    /// path:
486    ///
487    /// ```ignore
488    /// let backing = grid.chunk_xy_backing().unwrap();
489    /// let cg = roxlap_core::ChunkGrid {
490    ///     chunks: &backing.chunks,
491    ///     origin_chunk_xy: backing.origin_chunk_xy,
492    ///     chunks_x: backing.chunks_x,
493    ///     chunks_y: backing.chunks_y,
494    /// };
495    /// let view = roxlap_core::GridView::from_chunk_grid(
496    ///     &cg, crate::CHUNK_SIZE_XY,
497    /// );
498    /// ```
499    ///
500    /// Only chz=0 chunks contribute (multi-z handoff lands in
501    /// S4B.3); higher-chz chunks in [`Self::chunks`] are ignored
502    /// here.
503    #[must_use]
504    pub fn chunk_xy_backing(&self) -> Option<ChunkXyBacking<'_>> {
505        let mut min_x = i32::MAX;
506        let mut min_y = i32::MAX;
507        let mut max_x = i32::MIN;
508        let mut max_y = i32::MIN;
509        let mut any = false;
510        for chunk_idx in self.chunks.keys() {
511            if chunk_idx.z != 0 {
512                continue;
513            }
514            min_x = min_x.min(chunk_idx.x);
515            min_y = min_y.min(chunk_idx.y);
516            max_x = max_x.max(chunk_idx.x);
517            max_y = max_y.max(chunk_idx.y);
518            any = true;
519        }
520        if !any {
521            return None;
522        }
523        #[allow(clippy::cast_sign_loss)]
524        let chunks_x = (max_x - min_x + 1) as u32;
525        #[allow(clippy::cast_sign_loss)]
526        let chunks_y = (max_y - min_y + 1) as u32;
527        let mut table: Vec<Option<roxlap_core::GridView<'_>>> =
528            vec![None; (chunks_x * chunks_y) as usize];
529        for (chunk_idx, vxl) in &self.chunks {
530            if chunk_idx.z != 0 {
531                continue;
532            }
533            let dx = chunk_idx.x - min_x;
534            let dy = chunk_idx.y - min_y;
535            #[allow(clippy::cast_sign_loss)]
536            let i = (dy as u32 * chunks_x + dx as u32) as usize;
537            table[i] = Some(roxlap_core::GridView::from_single_vxl(vxl));
538        }
539        Some(ChunkXyBacking {
540            chunks: table,
541            origin_chunk_xy: [min_x, min_y],
542            origin_chunk_z: 0,
543            chunks_x,
544            chunks_y,
545            chunks_z: 1,
546        })
547    }
548
549    /// S4B.6.a: 3D-aware version of [`Self::chunk_xy_backing`].
550    /// Enumerates ALL chunks across the chx/chy/chz bounding box
551    /// (not just `chz=0`) so a stacked grid can be rendered once
552    /// S4B.6.c switches the rasterizer to a chunk-z-aware column
553    /// walker.
554    ///
555    /// Iterates `chunks` once for the XYZ bbox, then a second time
556    /// to fill the row-major-per-z `Vec<Option<GridView<'_>>>`.
557    /// Index layout: `[(dz * chunks_y + dy) * chunks_x + dx]` —
558    /// matches [`roxlap_core::ChunkGrid`]'s indexing exactly.
559    ///
560    /// Returns `None` for empty grids.
561    #[must_use]
562    pub fn chunk_xyz_backing(&self) -> Option<ChunkXyBacking<'_>> {
563        let mut min_x = i32::MAX;
564        let mut min_y = i32::MAX;
565        let mut min_z = i32::MAX;
566        let mut max_x = i32::MIN;
567        let mut max_y = i32::MIN;
568        let mut max_z = i32::MIN;
569        let mut any = false;
570        for chunk_idx in self.chunks.keys() {
571            min_x = min_x.min(chunk_idx.x);
572            min_y = min_y.min(chunk_idx.y);
573            min_z = min_z.min(chunk_idx.z);
574            max_x = max_x.max(chunk_idx.x);
575            max_y = max_y.max(chunk_idx.y);
576            max_z = max_z.max(chunk_idx.z);
577            any = true;
578        }
579        if !any {
580            return None;
581        }
582        #[allow(clippy::cast_sign_loss)]
583        let chunks_x = (max_x - min_x + 1) as u32;
584        #[allow(clippy::cast_sign_loss)]
585        let chunks_y = (max_y - min_y + 1) as u32;
586        #[allow(clippy::cast_sign_loss)]
587        let chunks_z = (max_z - min_z + 1) as u32;
588        let mut table: Vec<Option<roxlap_core::GridView<'_>>> =
589            vec![None; (chunks_x * chunks_y * chunks_z) as usize];
590        for (chunk_idx, vxl) in &self.chunks {
591            let dx = chunk_idx.x - min_x;
592            let dy = chunk_idx.y - min_y;
593            let dz = chunk_idx.z - min_z;
594            #[allow(clippy::cast_sign_loss)]
595            let (dx, dy, dz) = (dx as u32, dy as u32, dz as u32);
596            let i = ((dz * chunks_y + dy) * chunks_x + dx) as usize;
597            table[i] = Some(roxlap_core::GridView::from_single_vxl(vxl));
598        }
599        Some(ChunkXyBacking {
600            chunks: table,
601            origin_chunk_xy: [min_x, min_y],
602            origin_chunk_z: min_z,
603            chunks_x,
604            chunks_y,
605            chunks_z,
606        })
607    }
608}
609
610/// S4B.2.c.3: chx/chy chunk table built from a [`Grid`].
611///
612/// Owns the `Vec<Option<GridView>>` so [`roxlap_core::ChunkGrid`]
613/// (which borrows the table) can live alongside the GridView
614/// constructed from it. Used by the Approach B render path —
615/// see [`Grid::chunk_xy_backing`].
616///
617/// S4B.6.a: gained `chunks_z` + `origin_chunk_z` for tall-world
618/// support. Pre-S4B.6.a `chunk_xy_backing` always populates these
619/// as `chunks_z=1 origin_chunk_z=0` (= chz=0 only); S4B.6.c will
620/// switch the render path to `chunk_xyz_backing` once the
621/// rasterizer is stack-aware.
622pub struct ChunkXyBacking<'a> {
623    /// Per-chunk views over the chx/chy/chz extent.
624    /// Length `chunks_x * chunks_y * chunks_z`; index layout
625    /// `[(dz * chunks_y + dy) * chunks_x + dx]`. `None` for
626    /// implicit-air chunks inside the bbox.
627    pub chunks: Vec<Option<roxlap_core::GridView<'a>>>,
628    /// XY index of the chunk at `chunks[0]` — the minimum chx/chy
629    /// among populated chunks at `chz = origin_chunk_z`.
630    pub origin_chunk_xy: [i32; 2],
631    /// Z index of the chunk at `chunks[0]`.
632    pub origin_chunk_z: i32,
633    /// Number of chunks along the X axis. Row stride.
634    pub chunks_x: u32,
635    /// Number of chunks along the Y axis.
636    pub chunks_y: u32,
637    /// Number of chunks along the Z axis. `1` from
638    /// [`Grid::chunk_xy_backing`]; `>1` only via the S4B.6.a
639    /// [`Grid::chunk_xyz_backing`].
640    pub chunks_z: u32,
641}
642
643#[cfg(test)]
644pub(crate) mod tests {
645    use super::*;
646    use crate::{GridTransform, CHUNK_SIZE_Z};
647    use roxlap_formats::color::VoxColor;
648
649    /// Decode `column`'s slab bytes and return `true` iff `z` is
650    /// covered by any solid run. Mirrors voxlap's column-walk
651    /// semantics — the b2 buffer is `[top0, bot0, top1, bot1, ...,
652    /// MAXZDIM_sentinel]`, with each `[top, bot)` pair denoting a
653    /// solid range.
654    pub(crate) fn voxel_is_solid(vxl: &Vxl, x: u32, y: u32, z: u32) -> bool {
655        super::vxl_voxel_solid(vxl, x, y, z)
656    }
657
658    #[test]
659    fn voxel_solid_reflects_set_voxel() {
660        // Grid::voxel_solid (the public picking query) reads back an
661        // edit: the set voxel is solid, its neighbour is air, and an
662        // unmaterialised chunk reads as air.
663        let mut g = Grid::new(GridTransform::identity());
664        g.set_voxel(IVec3::new(5, 6, 7), Some(VoxColor(0x80_aa_bb_cc)));
665        assert!(g.voxel_solid(IVec3::new(5, 6, 7)), "set voxel is solid");
666        assert!(!g.voxel_solid(IVec3::new(5, 6, 8)), "neighbour is air");
667        assert!(
668            !g.voxel_solid(IVec3::new(900, 900, 7)),
669            "absent chunk reads as air",
670        );
671    }
672
673    #[test]
674    fn voxel_solid_handles_negative_coords() {
675        // Negative grid-local voxels decompose via div_euclid (addr
676        // semantics); the query must follow the same split.
677        let mut g = Grid::new(GridTransform::identity());
678        g.set_voxel(IVec3::new(-1, -1, 10), Some(VoxColor(0x80_11_22_33)));
679        assert!(g.voxel_solid(IVec3::new(-1, -1, 10)));
680        assert!(!g.voxel_solid(IVec3::new(-1, -1, 11)));
681    }
682
683    #[test]
684    fn empty_chunk_has_correct_vsid() {
685        let vxl = empty_chunk_vxl();
686        assert_eq!(vxl.vsid, CHUNK_SIZE_XY);
687    }
688
689    #[test]
690    fn empty_chunk_is_all_air() {
691        let vxl = empty_chunk_vxl();
692        // Sample a few representative voxels — full coverage is in
693        // `empty_chunk_no_voxel_solid_anywhere` below.
694        for &(x, y, z) in &[
695            (0u32, 0u32, 0u32),
696            (0, 0, 100),
697            (0, 0, 200),
698            (CHUNK_SIZE_XY - 1, CHUNK_SIZE_XY - 1, 0),
699            (64, 64, 128),
700        ] {
701            assert!(
702                !voxel_is_solid(&vxl, x, y, z),
703                "voxel ({x}, {y}, {z}) should be air"
704            );
705        }
706    }
707
708    #[test]
709    fn empty_chunk_air_above_bedrock_on_grid_sample() {
710        // Stride 16 across the chunk catches structural breakage
711        // (a corner column wrong, a z-band wrong, etc.) without the
712        // 4M-query cost of a brute-force scan in debug mode.
713        // Voxlap's slab format keeps z=255 solid as the "below the
714        // world" sentinel; the renderer's `treat_z_max_as_air` flag
715        // handles displaying it as transparent. See
716        // `project_below_bedrock_all_sky.md` for the S1.X fix.
717        let vxl = empty_chunk_vxl();
718        let bedrock_z = CHUNK_SIZE_Z - 1;
719        for y in (0..CHUNK_SIZE_XY).step_by(16) {
720            for x in (0..CHUNK_SIZE_XY).step_by(16) {
721                for z in (0..bedrock_z).step_by(16) {
722                    assert!(
723                        !voxel_is_solid(&vxl, x, y, z),
724                        "voxel ({x}, {y}, {z}) leaked solid in empty chunk"
725                    );
726                }
727                // bedrock z is solid (placeholder).
728                assert!(voxel_is_solid(&vxl, x, y, bedrock_z));
729            }
730        }
731    }
732
733    #[test]
734    fn empty_chunk_keeps_bedrock_placeholder() {
735        // Voxlap's invariant: every column carries an implicit
736        // solid voxel at z = MAXZDIM-1 = 255 even after a full
737        // carve. The renderer reads this as the bedrock placeholder.
738        let vxl = empty_chunk_vxl();
739        assert!(voxel_is_solid(&vxl, 0, 0, CHUNK_SIZE_Z - 1));
740        assert!(voxel_is_solid(&vxl, 64, 64, CHUNK_SIZE_Z - 1));
741    }
742
743    #[test]
744    fn ensure_chunk_creates_when_missing() {
745        let mut g = Grid::new(GridTransform::identity());
746        assert_eq!(g.chunk_count(), 0);
747        assert!(g.chunk(IVec3::ZERO).is_none());
748        let _ = g.ensure_chunk(IVec3::ZERO);
749        assert_eq!(g.chunk_count(), 1);
750        assert!(g.chunk(IVec3::ZERO).is_some());
751    }
752
753    #[test]
754    fn ensure_chunk_returns_existing() {
755        // Calling ensure_chunk a second time on the same index
756        // doesn't replace the chunk. Verify by writing through the
757        // first call and reading through the second.
758        let mut g = Grid::new(GridTransform::identity());
759        let chunk = IVec3::new(2, -1, 0);
760        g.ensure_chunk(chunk);
761        // Voxel local (5, 6, 7) inside chunk (2, -1, 0) is
762        // grid-local global (2*128 + 5, -1*128 + 6, 0*256 + 7) =
763        // (261, -122, 7).
764        g.set_voxel(IVec3::new(261, -122, 7), Some(VoxColor(0x80_aa_bb_cc)));
765        let vxl = g.ensure_chunk(chunk);
766        assert!(voxel_is_solid(vxl, 5, 6, 7));
767        assert_eq!(g.chunk_count(), 1);
768    }
769
770    #[test]
771    fn chunk_mut_returns_none_for_missing() {
772        let mut g = Grid::new(GridTransform::identity());
773        assert!(g.chunk_mut(IVec3::ZERO).is_none());
774    }
775
776    /// S4B.6.a: legacy `chunk_xy_backing` ignores chz!=0 chunks and
777    /// always returns `chunks_z=1 origin_chunk_z=0`. Sanity-check
778    /// the new field defaults so pre-S4B.6 render path stays
779    /// byte-identical.
780    #[test]
781    fn chunk_xy_backing_returns_chunks_z_one() {
782        let mut g = Grid::new(GridTransform::identity());
783        g.ensure_chunk(IVec3::new(0, 0, 0));
784        g.ensure_chunk(IVec3::new(1, 0, 0));
785        // Add a chunk at chz=1 — chunk_xy_backing should ignore it.
786        g.ensure_chunk(IVec3::new(0, 0, 1));
787        let backing = g.chunk_xy_backing().expect("two chz=0 chunks present");
788        assert_eq!(backing.chunks_z, 1);
789        assert_eq!(backing.origin_chunk_z, 0);
790        assert_eq!(backing.chunks_x, 2);
791        assert_eq!(backing.chunks_y, 1);
792        assert_eq!(backing.chunks.len(), 2);
793    }
794
795    /// S4B.6.a: new `chunk_xyz_backing` enumerates ALL chunks
796    /// including chz!=0. Indexing layout must match
797    /// `roxlap_core::ChunkGrid`: row-major per z slab.
798    #[test]
799    fn chunk_xyz_backing_with_stacked_chunks_enumerates_all_z() {
800        let mut g = Grid::new(GridTransform::identity());
801        g.ensure_chunk(IVec3::new(0, 0, 0));
802        g.ensure_chunk(IVec3::new(1, 0, 0));
803        g.ensure_chunk(IVec3::new(0, 0, 1));
804        // Leave (1, 0, 1) implicit-air.
805        let backing = g.chunk_xyz_backing().expect("at least one chunk");
806        assert_eq!(backing.chunks_x, 2);
807        assert_eq!(backing.chunks_y, 1);
808        assert_eq!(backing.chunks_z, 2);
809        assert_eq!(backing.origin_chunk_xy, [0, 0]);
810        assert_eq!(backing.origin_chunk_z, 0);
811        assert_eq!(backing.chunks.len(), 4); // dims [2, 1, 2]
812                                             // Index layout: [(dz * chunks_y + dy) * chunks_x + dx]
813                                             // (0, 0, 0) → dx=0, dy=0, dz=0 → 0
814                                             // (1, 0, 0) → dx=1, dy=0, dz=0 → 1
815                                             // (0, 0, 1) → dx=0, dy=0, dz=1 → 2
816                                             // (1, 0, 1) → dx=1, dy=0, dz=1 → 3 (implicit-air → None)
817        assert!(backing.chunks[0].is_some(), "(0, 0, 0) present");
818        assert!(backing.chunks[1].is_some(), "(1, 0, 0) present");
819        assert!(backing.chunks[2].is_some(), "(0, 0, 1) present");
820        assert!(backing.chunks[3].is_none(), "(1, 0, 1) implicit-air");
821    }
822
823    /// S4B.6.a: chunk_xyz_backing with negative chz origin —
824    /// origin_chunk_z = min_z must reflect the actual minimum chz.
825    #[test]
826    fn chunk_xyz_backing_with_negative_origin_chunk_z() {
827        let mut g = Grid::new(GridTransform::identity());
828        g.ensure_chunk(IVec3::new(0, 0, -2));
829        g.ensure_chunk(IVec3::new(0, 0, 0));
830        let backing = g.chunk_xyz_backing().expect("at least one chunk");
831        assert_eq!(backing.chunks_z, 3); // chz range [-2, 0]
832        assert_eq!(backing.origin_chunk_z, -2);
833        assert!(backing.chunks[0].is_some(), "chz=-2 → dz=0");
834        assert!(backing.chunks[1].is_none(), "chz=-1 → dz=1 implicit-air");
835        assert!(backing.chunks[2].is_some(), "chz=0 → dz=2");
836    }
837
838    /// PF.11 — `bake_lightmode_bbox` around an edit must reproduce, byte
839    /// for byte, what a full-grid re-bake would write: the padded write
840    /// region covers every voxel whose estnorm the edit could change
841    /// (±ESTNORMRAD), including strips in neighbour chunks across seams.
842    #[test]
843    fn bbox_rebake_matches_full_rebake() {
844        // Terrain spanning a 2×2 chunk seam, with relief so estnorm is
845        // non-trivial around the edit.
846        let build = || {
847            let mut g = Grid::new(GridTransform::identity());
848            g.set_rect(
849                IVec3::new(0, 0, 160),
850                IVec3::new(255, 255, 255),
851                Some(VoxColor(0x80_66_77_88)),
852            );
853            for i in 0..10 {
854                let (x, y) = (23 * i % 240 + 8, 37 * i % 240 + 8);
855                g.set_sphere(IVec3::new(x, y, 165), 6, None);
856            }
857            g.bake(BakeMode::Directional);
858            g
859        };
860        let mut full = build();
861        let mut bbox = build();
862
863        // Identical edit in both, straddling the chunk (0,0)/(1,0) seam
864        // so the neighbour-strip rebake is exercised.
865        let (lo, hi) = (IVec3::new(120, 60, 158), IVec3::new(136, 76, 200));
866        full.set_rect(lo, hi, None);
867        bbox.set_rect(lo, hi, None);
868
869        // Ground truth: full re-bake. Candidate: bbox-only re-bake.
870        full.bake(BakeMode::Directional);
871        bbox.bake_bbox(lo, hi, BakeMode::Directional);
872
873        for (idx, a) in &full.chunks {
874            let b = bbox.chunks.get(idx).expect("same chunk set");
875            assert_eq!(
876                a.data, b.data,
877                "chunk {idx:?} bytes diverge between full and bbox rebake",
878            );
879        }
880    }
881
882    /// PF.12 — `remip_bbox` must be byte-identical to a full
883    /// `generate_mips` when the bbox covers the edits: data bytes,
884    /// column offsets, and the mip table all match — across repeated
885    /// incremental rounds, corner-of-chunk edits, and voxalloc-scattered
886    /// columns.
887    #[test]
888    fn remip_bbox_matches_generate_mips() {
889        use roxlap_formats::edit::{set_sphere_with_colfunc, SpanOp};
890
891        // Realistic chunk: terrain + caves, then a full initial ladder.
892        let mut g = Grid::new(GridTransform::identity());
893        g.set_rect(
894            IVec3::new(0, 0, 150),
895            IVec3::new(127, 127, 255),
896            Some(VoxColor(0x80_66_77_88)),
897        );
898        for i in 0..8 {
899            let (x, y) = (29 * i % 100 + 12, 41 * i % 100 + 12);
900            g.set_sphere(IVec3::new(x, y, 158), 5, None);
901        }
902        let base = g.chunks.get_mut(&IVec3::ZERO).expect("chunk");
903        base.generate_mips(6);
904
905        let mut full = base.clone();
906        let mut inc = base.clone();
907
908        // Round 1: a carve straddling brick/column-group boundaries plus
909        // a corner edit (exercises clamping at the chunk edge).
910        let edits: [(IVec3, u32); 3] = [
911            (IVec3::new(63, 64, 170), 7),
912            (IVec3::new(0, 0, 155), 4),
913            (IVec3::new(126, 100, 165), 5),
914        ];
915        for round in 0..2 {
916            let mut lo = IVec3::splat(i32::MAX);
917            let mut hi = IVec3::splat(i32::MIN);
918            for (k, &(c, r)) in edits.iter().enumerate() {
919                if k % 2 != round % 2 {
920                    continue; // vary the edit set per round
921                }
922                #[allow(clippy::cast_possible_wrap)]
923                let ri = r as i32;
924                for v in [&mut full, &mut inc] {
925                    set_sphere_with_colfunc(v, c.into(), r, SpanOp::Carve, |_, _, _| {
926                        VoxColor(0x80_31_41_59)
927                    });
928                }
929                lo = lo.min(c - IVec3::splat(ri));
930                hi = hi.max(c + IVec3::splat(ri));
931            }
932            full.generate_mips(6);
933            inc.remip_bbox(lo.x, lo.y, hi.x, hi.y, 6);
934
935            assert_eq!(
936                full.mip_base_offsets, inc.mip_base_offsets,
937                "round {round}: mip tables diverge",
938            );
939            assert_eq!(
940                full.column_offset, inc.column_offset,
941                "round {round}: column offsets diverge",
942            );
943            assert_eq!(full.data, inc.data, "round {round}: data bytes diverge");
944        }
945    }
946
947    /// PF.6 — the in-place slab walk in `vxl_voxel_solid` must agree
948    /// with the `expandrle` run list (the pre-PF.6 reference decoder)
949    /// for every z, on columns with multiple slabs (caves), single
950    /// slabs, and untouched bedrock.
951    #[test]
952    fn vxl_voxel_solid_matches_expandrle_reference() {
953        use roxlap_formats::edit::expandrle;
954
955        let mut g = Grid::new(GridTransform::identity());
956        // Carve two separate air pockets into one column (multi-slab)
957        // plus a sphere for varied neighbours.
958        g.set_rect(IVec3::new(3, 4, 40), IVec3::new(4, 5, 60), None);
959        g.set_rect(IVec3::new(3, 4, 100), IVec3::new(4, 5, 140), None);
960        g.set_voxel(IVec3::new(3, 4, 120), Some(VoxColor(0x80_11_22_33))); // island inside the pocket
961        g.set_sphere(IVec3::new(8, 8, 80), 6, None);
962        let vxl = g.chunk(IVec3::ZERO).expect("chunk materialised");
963
964        let maxzdim = CHUNK_SIZE_Z as i32;
965        for (x, y) in [(3u32, 4u32), (8, 8), (0, 0), (8, 2), (12, 8)] {
966            // Reference: full expandrle decode → run-list scan.
967            let column = vxl.column_data((y * vxl.vsid + x) as usize);
968            let mut b2 = vec![maxzdim; 2 * (CHUNK_SIZE_Z as usize) + 4];
969            expandrle(column, &mut b2);
970            for z in 0..CHUNK_SIZE_Z {
971                let zi = z as i32;
972                let mut reference = false;
973                let mut i = 0;
974                while b2[i] < maxzdim {
975                    if zi >= b2[i] && zi < b2[i + 1] {
976                        reference = true;
977                        break;
978                    }
979                    i += 2;
980                }
981                assert_eq!(
982                    vxl_voxel_solid(vxl, x, y, z),
983                    reference,
984                    "column ({x}, {y}) z={z} disagrees with expandrle",
985                );
986            }
987        }
988    }
989}