Skip to main content

roxlap_core/
dda.rs

1//! Per-pixel 3D-DDA + brickmap CPU renderer (Substage DDA).
2//!
3//! This is the clean-room replacement for the voxlap-derived
4//! column-coherent opticast pipeline (`opticast` + `grouscan` +
5//! `scan_loops`). Every pixel casts one independent ray, so none of
6//! the column/row-coherence stitching artifacts of the 2.5D voxlap
7//! renderer can occur (silhouette notch, floor hairlines, axis-aligned
8//! mip beams, cross-chunk virtual-column complexity). See
9//! `PORTING-DDA.md` for the full stage plan.
10//!
11//! **Stage status — DDA.6 (per-grid distance mip) + DDA.7 (tile
12//! parallelism).** Each pixel casts one ray over the grid's full voxel
13//! box ([`GridView::voxel_bounds`], spanning every chunk in XY **and**
14//! Z) via a 3D-DDA (Amanatides–Woo). A uniform render mip (chosen per
15//! grid by LOD distance, clamped by [`effective_mip`] to a level every
16//! chunk has built) coarsens the cell size to `2^mip` mip-0 voxels and
17//! samples mip-`mip` data — the ray stays in mip-0 units so depth and
18//! fog are exact. `BrickMaps` (one occupancy map per populated chunk,
19//! at the render mip) are built once per frame and shared immutably; a
20//! `Sampler` resolves each cell to its chunk
21//! ([`GridView::chunk_at_xyz`]) and brick-gates the
22//! [`GridView::surface_color_mip`] slab walk, caching the current chunk
23//! so air costs an O(1) bit test. [`render_dda_parallel`] splits the
24//! frame into disjoint rayon bands — bit-identical to sequential since
25//! pixels are independent. Hits are shaded by baked brightness
26//! (`shade`) + [`DdaEnv::side_shades`] face tint, fogged toward
27//! [`DdaEnv::fog_color`] (`apply_fog`); misses sample the
28//! [`DdaEnv::sky`] panorama (`sample_sky`) or keep the solid pre-fill.
29//!
30//! Buffer conventions match the rest of the engine so this backend is
31//! colour is packed `0x80RRGGBB`; depth is perpendicular distance from
32//! the camera with **smaller = closer** (so the scene compositor's
33//! min-z merge works directly on the z-buffer this writes).
34
35use std::collections::HashMap;
36
37use rayon::prelude::*;
38
39use crate::camera_math::{self, CameraState};
40use crate::grid_view::GridView;
41use crate::opticast::OpticastSettings;
42use crate::raster_target::RasterTarget;
43use crate::sky::Sky;
44use crate::Camera;
45use roxlap_formats::material::{material_for_color, Material, MaterialTable};
46use roxlap_formats::Rgb;
47
48/// Per-frame environment for DDA shading (Substage DDA.5): a textured
49/// sky panorama, distance fog, and per-face side shading.
50///
51/// [`DdaEnv::default`] disables all three — flat baked-brightness hits
52/// and a caller-pre-filled solid sky — so the brickmap/dense equivalence
53/// tests run against an unchanged pipeline.
54#[derive(Clone, Copy)]
55pub struct DdaEnv<'a> {
56    /// Textured sky sampled per-ray-direction on a miss. `None` leaves
57    /// the destination untouched (caller's solid sky pre-fill shows).
58    pub sky: Option<&'a Sky>,
59    /// Fog target colour (`0x__RRGGBB`); hits blend toward it with
60    /// distance. Typically the sky colour so terrain fades into the sky.
61    pub fog_color: u32,
62    /// Depth at which fog is fully opaque. `<= 0` disables fog.
63    pub fog_max_dist: f32,
64    /// Per-face brightness reduction `[x-, x+, y-, y+, z-, z+]`, applied
65    /// to the hit face (voxlap `setsideshades`). All-zero = off.
66    pub side_shades: [i8; 6],
67    /// TV: global voxel-material palette (id → opacity + blend mode). `None`
68    /// keeps terrain fully opaque (the first-hit path, bit-identical).
69    pub materials: Option<&'a MaterialTable>,
70    /// TV: terrain colour→material map (`(rgb, material_id)`). A hit voxel's
71    /// colour is looked up here for its material. **Empty** (the default) ⇒
72    /// every voxel is opaque, so the march returns the first hit unchanged.
73    pub terrain_materials: &'a [(Rgb, u8)],
74    /// CPU.1 — dynamic lighting (stage DL on the CPU): sun + point lights +
75    /// stylized cel/ramp, evaluated flat per voxel. Disabled by default ⇒ the
76    /// hit uses the baked-byte `shade` path, byte-identical to pre-DL. Lights
77    /// here are already in the grid's **local** frame (the scene renderer
78    /// transforms them per grid). Shadows: see [`Self::world_shadow`].
79    pub lights: CpuLights<'a>,
80    /// XS.1 — when set, shadow rays test the **whole scene** (all grids +
81    /// sprites) via this world-space occluder + the current grid's
82    /// local→world transform, instead of the single-grid `SamplerShadow`.
83    /// `None` ⇒ single-grid shadows (the direct `render_dda` path / tests).
84    pub world_shadow: Option<WorldShadowCtx<'a>>,
85}
86
87/// CPU.1 — one point light in a grid's local frame for the CPU renderer.
88#[derive(Clone, Copy)]
89pub struct CpuPointLight {
90    /// Grid-local position (world/voxel units).
91    pub pos: [f32; 3],
92    /// Linear RGB, 0..1.
93    pub color: [f32; 3],
94    /// Scalar multiplier on `color` — the light's contribution is
95    /// `albedo · color · intensity · N·L · falloff` per channel.
96    /// `1.0` is nominal; values above it over-drive (the sum clamps at
97    /// pack time).
98    pub intensity: f32,
99    /// Hard cutoff distance (world/voxel units).
100    pub radius: f32,
101    /// CPU.2 — whether this light casts a hard shadow (a shadow ray
102    /// marches to the light through the grid's voxels). Mirrors the
103    /// GPU's per-light `casts_shadow`; the renderer applies the same
104    /// caster cap before building the CPU rig.
105    pub casts_shadow: bool,
106    /// SL — spot (cone) axis: grid-local unit direction the light shines
107    /// **along**. Ignored for a pure point light (see [`Self::cos_outer`]).
108    pub spot_dir: [f32; 3],
109    /// SL — cosine of the inner cone half-angle (full brightness within it).
110    pub cos_inner: f32,
111    /// SL — cosine of the outer cone half-angle (zero past it; soft
112    /// `smoothstep` between the two). `-1.0` (a 180° cone) ⇒ a pure point
113    /// light: the cone mask is skipped entirely and the light is omnidirectional.
114    pub cos_outer: f32,
115}
116
117/// CPU.1 — the per-frame dynamic-light environment for one grid (grid-local).
118/// Mirror of the GPU `shade_lit` inputs. `enabled == false` (the default)
119/// keeps the baked-byte path. CPU.2 adds hard voxel shadows (sun + flagged
120/// point lights) via a per-(voxel,face) shadow march; `shadow_strength == 0`
121/// (the [`Default`]) leaves the lighting diffuse-only.
122#[derive(Clone, Copy, Default)]
123pub struct CpuLights<'a> {
124    /// Whether dynamic lighting is active this frame (else the baked path).
125    pub enabled: bool,
126    /// Whether the sun is present.
127    pub sun: bool,
128    /// Grid-local unit direction **to** the sun.
129    pub sun_dir: [f32; 3],
130    /// Sun colour, linear RGB 0..1.
131    pub sun_color: [f32; 3],
132    /// Scalar multiplier on `sun_color` (the sun term is
133    /// `albedo · sun_color · sun_intensity · key`). `1.0` is nominal.
134    pub sun_intensity: f32,
135    /// CPU.2 — whether the sun casts a hard shadow.
136    pub sun_casts_shadow: bool,
137    /// Grid-local point lights.
138    pub points: &'a [CpuPointLight],
139    /// Ambient multiplier on the baked byte (smooth mode's fill).
140    pub ambient: [f32; 3],
141    /// Cel band count: 0 = smooth, ≥1 = quantize + gradient-map (stylized).
142    pub bands: u32,
143    /// Stylized ramp's cool unlit-end tint (used when `bands > 0`).
144    pub shadow_tint: [f32; 3],
145    /// CPU.2 — fraction of a caster's light removed where a shadow ray is
146    /// occluded (`0` ⇒ shadows off, `1` ⇒ full black). A shadowed sample
147    /// keeps `1 - shadow_strength` of that caster.
148    pub shadow_strength: f32,
149    /// CPU.2 — shadow-ray origin bias along the surface normal, voxel
150    /// units (kills self-shadow acne). ~1.5 is a good default.
151    pub shadow_bias: f32,
152    /// CPU.2 — sun shadow-ray length cap, voxel units (point-light rays
153    /// stop at the light instead).
154    pub shadow_max_dist: f32,
155}
156
157impl Default for DdaEnv<'_> {
158    fn default() -> Self {
159        Self {
160            sky: None,
161            fog_color: 0,
162            fog_max_dist: 0.0,
163            side_shades: [0; 6],
164            materials: None,
165            terrain_materials: &[],
166            lights: CpuLights::default(),
167            world_shadow: None,
168        }
169    }
170}
171
172/// Per-pixel output target for the DDA renderer.
173///
174/// Abstracts "where does a ray hit go" so the traversal core stays
175/// free of framebuffer mechanics. The production impl is
176/// [`RasterSink`] (raw fb/zb pointers); tests use a recording sink.
177/// Only *hits* are reported — misses (sky) leave the destination
178/// untouched, matching the caller-pre-fills-sky convention.
179pub trait PixelSink {
180    /// Record a ray hit at framebuffer index `idx` (`py * pitch + px`)
181    /// with packed ARGB `color` and perpendicular `dist` (smaller =
182    /// closer).
183    fn put(&mut self, idx: usize, color: u32, dist: f32);
184}
185
186/// [`PixelSink`] over a borrowed `(framebuffer, zbuffer)` pair.
187///
188/// Wraps a [`RasterTarget`] so the DDA path writes through the same
189/// raw-pointer mechanism the scalar rasterizer uses — which keeps the
190/// door open for the same strip/tile-disjoint parallel writes in
191/// DDA.7.
192pub struct RasterSink<'a> {
193    target: RasterTarget<'a>,
194    len: usize,
195}
196
197impl<'a> RasterSink<'a> {
198    /// Build a sink from exclusive framebuffer + zbuffer borrows.
199    /// Both slices must have the same length (the pixel count).
200    #[must_use]
201    pub fn new(framebuffer: &'a mut [u32], zbuffer: &'a mut [f32]) -> Self {
202        debug_assert_eq!(framebuffer.len(), zbuffer.len());
203        let len = framebuffer.len();
204        Self {
205            target: RasterTarget::new(framebuffer, zbuffer),
206            len,
207        }
208    }
209}
210
211impl PixelSink for RasterSink<'_> {
212    fn put(&mut self, idx: usize, color: u32, dist: f32) {
213        if idx < self.len {
214            // SAFETY: bounds checked above; single-threaded writer in
215            // DDA.0 so the disjoint-write invariant holds trivially.
216            unsafe {
217                self.target.write_color(idx, color);
218                self.target.write_depth(idx, dist);
219            }
220        }
221    }
222}
223
224/// A resolved ray hit: surface colour + perpendicular distance.
225#[derive(Debug, Clone, Copy)]
226struct Hit {
227    color: u32,
228    dist: f32,
229}
230
231/// Test-only per-thread traversal counters for the perf bench.
232#[cfg(test)]
233pub(crate) mod prof {
234    use std::cell::Cell;
235    thread_local! {
236        pub static CELLS: Cell<u64> = const { Cell::new(0) };
237        pub static BRICKS: Cell<u64> = const { Cell::new(0) };
238        pub static SURF: Cell<u64> = const { Cell::new(0) };
239    }
240    pub fn reset() {
241        CELLS.with(|x| x.set(0));
242        BRICKS.with(|x| x.set(0));
243        SURF.with(|x| x.set(0));
244    }
245    pub fn read() -> (u64, u64, u64) {
246        (
247            CELLS.with(Cell::get),
248            BRICKS.with(Cell::get),
249            SURF.with(Cell::get),
250        )
251    }
252}
253
254/// Apply the voxel's baked directional brightness (Substage DDA.5).
255///
256/// Voxlap (and the GPU marcher, `grid_dda.wgsl`) store per-voxel
257/// brightness in the colour's high byte on a `0..128` scale — `0x80`
258/// is full brightness — written by `Grid::bake_lightmode` (estnorm
259/// directional shading). The shaded channel is `c · a / 128`, so the
260/// DDA matches the GPU look; an unbaked / full-bright voxel (`a =
261/// 0x80`) passes through unchanged. Output alpha is normalised to
262/// `0x80` (the standard "lit" flag; the present blit ignores it).
263///
264/// The renderer only *reads* the baked byte — it computes no normals
265/// itself, so per-impact relight is free (re-bake the chunk and the
266/// byte updates). The estnorm bake that produces the byte is the
267/// voxlap-derived piece slated for a clean-room rewrite in DDA.10.
268///
269/// `bright_sub` is the per-face `side_shades` reduction (DDA.5): voxlap
270/// subtracts it from the brightness byte before the multiply, so a
271/// shaded face is uniformly darker. `0` = no side shading.
272#[inline]
273pub(crate) fn shade(color: u32, bright_sub: u32) -> u32 {
274    let a = ((color >> 24) & 0xff).saturating_sub(bright_sub);
275    let ch = |shift: u32| -> u32 { ((((color >> shift) & 0xff) * a) >> 7).min(255) };
276    0x8000_0000 | (ch(16) << 16) | (ch(8) << 8) | ch(0)
277}
278
279/// EV.1 — shade an **emissive** voxel: the baked brightness byte, the
280/// per-face side shade and the dynamic rig are all ignored; the albedo
281/// is scaled by `(128 + (emissive >> 1)) / 128` on the same `>> 7`
282/// fixed-point ladder as [`shade`] — ~1.0× at `emissive = 0..=1` up to
283/// ~2.0× over-bright (channel-clamped) at `255`. Fog is applied by the
284/// caller as for any other hit.
285#[inline]
286pub(crate) fn emissive_shade(color: u32, emissive: u8) -> u32 {
287    let a = 128 + u32::from(emissive >> 1);
288    let ch = |shift: u32| -> u32 { ((((color >> shift) & 0xff) * a) >> 7).min(255) };
289    0x8000_0000 | (ch(16) << 16) | (ch(8) << 8) | ch(0)
290}
291
292// CPU.1 — cel quantization: snap a 0..1 factor to `bands + 1` levels.
293#[inline]
294fn cel_band(x: f32, bands: u32) -> f32 {
295    let b = bands as f32;
296    ((x * b).round() / b).clamp(0.0, 1.0)
297}
298
299// CPU.1 — point-light distance falloff (mirror of the GPU's): smooth
300// quadratic from 1 at the light to 0 at `radius`, hard-cut beyond.
301#[inline]
302fn point_falloff(d: f32, radius: f32) -> f32 {
303    let x = (1.0 - d / radius).clamp(0.0, 1.0);
304    x * x
305}
306
307// SL — Hermite `smoothstep` (mirror of WGSL's), with a defined hard-edge case:
308// when `edge0 == edge1` WGSL is undefined, so we step at the shared threshold.
309#[inline]
310fn smoothstep_scalar(edge0: f32, edge1: f32, x: f32) -> f32 {
311    if edge1 <= edge0 {
312        return if x < edge0 { 0.0 } else { 1.0 };
313    }
314    let t = ((x - edge0) / (edge1 - edge0)).clamp(0.0, 1.0);
315    t * t * (3.0 - 2.0 * t)
316}
317
318// SL — spot (cone) angular mask (mirror of the shaders' `spot_cone`). `ldir` is
319// the unit direction from the surface TO the light; `axis` the cone axis (the
320// way the light shines). Returns 1.0 for a pure point light (`cos_outer <=
321// -0.999`, the 180° degenerate); else a soft `smoothstep` from 0 at the outer
322// half-angle to 1 at the inner (hard step when the two coincide).
323#[inline]
324fn spot_cone(ldir: [f32; 3], axis: [f32; 3], cos_inner: f32, cos_outer: f32) -> f32 {
325    if cos_outer <= -0.999 {
326        return 1.0;
327    }
328    let cd = -dot3(ldir, axis);
329    smoothstep_scalar(cos_outer, cos_inner, cd)
330}
331
332// CPU.1 — face normal (grid-local) from the crossed axis + step: points back
333// toward the incoming ray. `axis == 3` (entry voxel, no face) falls back to up
334// (-z, voxlap z-down).
335#[inline]
336fn face_normal_cpu(axis: usize, step: [i32; 3]) -> [f32; 3] {
337    let mut n = [0.0f32; 3];
338    if axis < 3 {
339        n[axis] = -(step[axis] as f32);
340    } else {
341        n[2] = -1.0;
342    }
343    n
344}
345
346#[inline]
347fn dot3(a: [f32; 3], b: [f32; 3]) -> f32 {
348    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
349}
350
351/// CPU.2 — a hard-shadow occlusion test for the dynamic-lighting shade.
352/// `occluded(origin, dir, max_t)` returns `true` if a solid voxel blocks
353/// the segment from `origin` (grid-local, already biased off the surface)
354/// in unit direction `dir` within `max_t` voxel units. Terrain hits pass
355/// a [`SamplerShadow`] (marches the current grid only) or a
356/// [`WorldShadow`] (cross-grid + sprites, XS.1/XS.2); sprites that don't
357/// cast/receive shadows pass `None`.
358pub(crate) trait ShadowTester {
359    fn occluded(&mut self, origin: [f32; 3], dir: [f32; 3], max_t: f32) -> bool;
360}
361
362/// XS.1 — a **world-space** occlusion oracle over the whole scene (all grids,
363/// and sprites in XS.2). Implemented in `roxlap-scene` (it needs the grid /
364/// sprite stores); the CPU DDA reaches it through [`DdaEnv::world_shadow`] so
365/// shadow rays cross grid + object boundaries instead of stopping at the
366/// current grid. `occluded_world(origin, dir, max_t)` is in **world** voxel
367/// units: `true` iff any solid voxel anywhere blocks the segment.
368///
369/// `Sync` because [`DdaEnv`] (which borrows it) is shared across the
370/// rayon strip workers in [`render_dda_parallel`]; the occluder is a
371/// read-only borrow of the scene, so this holds.
372pub trait WorldOccluder: Sync {
373    /// `true` iff any solid voxel in the scene blocks the segment from
374    /// world-space `origin` in unit direction `dir` within `max_t`
375    /// world voxel units.
376    fn occluded_world(&self, origin: [f32; 3], dir: [f32; 3], max_t: f32) -> bool;
377}
378
379/// XS.1 — per-grid context for a cross-scene shadow query: the scene-wide
380/// [`WorldOccluder`] plus the **current grid's** local→world transform, so a
381/// grid-local shadow ray (the frame `shade_dynamic` works in) can be lifted
382/// to world space before the scene-wide test. `cols[i]` is the world-space
383/// image of grid-local axis `i` (the grid rotation's columns); `origin` is the
384/// grid's world origin.
385#[derive(Clone, Copy)]
386pub struct WorldShadowCtx<'a> {
387    /// The scene-wide occlusion oracle every lifted shadow ray is
388    /// tested against.
389    pub occluder: &'a dyn WorldOccluder,
390    /// The current grid's world-space origin — the translation part of
391    /// its local→world transform (added to rotated positions;
392    /// directions skip it).
393    pub origin: [f32; 3],
394    /// Columns of the grid's local→world rotation: `cols[i]` is the
395    /// world-space image of grid-local axis `i`. Assumed orthonormal
396    /// so grid-local ray lengths equal world lengths.
397    pub cols: [[f32; 3]; 3],
398}
399
400impl<'a> WorldShadowCtx<'a> {
401    /// Identity transform — for shading already in world space (sprites): the
402    /// grid-local ray IS the world ray.
403    #[must_use]
404    pub fn identity(occluder: &'a dyn WorldOccluder) -> Self {
405        Self {
406            occluder,
407            origin: [0.0; 3],
408            cols: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
409        }
410    }
411}
412
413/// XS.2 — a [`WorldOccluder`] that ORs two others (e.g. the grid occluder +
414/// the sprite occluder), so a single shadow query covers both. `true` if
415/// either blocks the ray.
416pub struct CompositeOccluder<'a> {
417    /// First occluder — queried first (short-circuits `b` on a hit).
418    pub a: &'a dyn WorldOccluder,
419    /// Second occluder — queried only when `a` reports no hit.
420    pub b: &'a dyn WorldOccluder,
421}
422
423impl WorldOccluder for CompositeOccluder<'_> {
424    fn occluded_world(&self, origin: [f32; 3], dir: [f32; 3], max_t: f32) -> bool {
425        self.a.occluded_world(origin, dir, max_t) || self.b.occluded_world(origin, dir, max_t)
426    }
427}
428
429/// XS.1 — [`ShadowTester`] that lifts a grid-local shadow ray to world space
430/// (via [`WorldShadowCtx`]) and queries the scene-wide [`WorldOccluder`], so
431/// occlusion crosses grid + sprite boundaries. Sprites (already world-space)
432/// use an identity [`WorldShadowCtx`] (see [`WorldShadowCtx::identity`]).
433pub(crate) struct WorldShadow<'a> {
434    pub ctx: WorldShadowCtx<'a>,
435}
436
437impl ShadowTester for WorldShadow<'_> {
438    fn occluded(&mut self, origin: [f32; 3], dir: [f32; 3], max_t: f32) -> bool {
439        let c = &self.ctx.cols;
440        // world = grid_origin + R · local (R columns = `cols`); dir rotates only.
441        let wo = [
442            self.ctx.origin[0] + c[0][0] * origin[0] + c[1][0] * origin[1] + c[2][0] * origin[2],
443            self.ctx.origin[1] + c[0][1] * origin[0] + c[1][1] * origin[1] + c[2][1] * origin[2],
444            self.ctx.origin[2] + c[0][2] * origin[0] + c[1][2] * origin[1] + c[2][2] * origin[2],
445        ];
446        let wd = [
447            c[0][0] * dir[0] + c[1][0] * dir[1] + c[2][0] * dir[2],
448            c[0][1] * dir[0] + c[1][1] * dir[1] + c[2][1] * dir[2],
449            c[0][2] * dir[0] + c[1][2] * dir[1] + c[2][2] * dir[2],
450        ];
451        self.ctx.occluder.occluded_world(wo, wd, max_t)
452    }
453}
454
455/// CPU.1 — dynamic-lighting shade for a terrain voxel (the CPU mirror of the
456/// GPU `shade_lit`): raw albedo × (ambient/AO + sun + point lights), evaluated
457/// **flat per voxel** (at the voxel centre, so a whole face reads one tone —
458/// the retro look). `bands > 0` quantizes (cel) and gradient-maps the sun key
459/// from `shadow_tint` (cool) to the sun colour (warm). **No shadows.** Returns
460/// a packed `0x80RRGGBB` colour (same convention as [`shade`]).
461fn shade_lit_cpu(
462    color: u32,
463    bright_sub: u32,
464    axis: usize,
465    step: [i32; 3],
466    cellc: [i32; 3],
467    cell_size: f32,
468    l: &CpuLights<'_>,
469    shadow: Option<&mut dyn ShadowTester>,
470) -> u32 {
471    let a_b = ((color >> 24) & 0xff).saturating_sub(bright_sub);
472    let ao = a_b as f32 / 128.0;
473    let albedo = [
474        ((color >> 16) & 0xff) as f32 / 255.0,
475        ((color >> 8) & 0xff) as f32 / 255.0,
476        (color & 0xff) as f32 / 255.0,
477    ];
478    let n = face_normal_cpu(axis, step);
479    // Voxel centre (grid-local) — flat per-voxel sample point.
480    let center = [
481        (cellc[0] as f32 + 0.5) * cell_size,
482        (cellc[1] as f32 + 0.5) * cell_size,
483        (cellc[2] as f32 + 0.5) * cell_size,
484    ];
485    shade_dynamic(albedo, ao, n, center, l, shadow)
486}
487
488/// CPU.1/DL.7 — the shared dynamic-lighting core (terrain + sprites): raw
489/// `albedo` × (ambient/AO + sun + point lights), sampled **flat per voxel**
490/// at `sample` with surface normal `n`. `bands > 0` quantizes (cel) and
491/// gradient-maps the sun key from `shadow_tint` (cool) to the sun colour
492/// (warm). **No shadows** (GPU-only). Returns a packed `0x80RRGGBB` colour.
493pub(crate) fn shade_dynamic(
494    albedo: [f32; 3],
495    ao: f32,
496    n: [f32; 3],
497    sample: [f32; 3],
498    l: &CpuLights<'_>,
499    shadow: Option<&mut dyn ShadowTester>,
500) -> u32 {
501    let styled = l.bands > 0;
502    // CPU.2 — shadow ray origin: bias off the surface along the normal to
503    // avoid self-shadow acne (shared by every caster). Light kept in
504    // shadow = `1 - shadow_strength` (1.0 ⇒ shadows effectively off).
505    let mut shadow = shadow;
506    let shadow_origin = [
507        sample[0] + n[0] * l.shadow_bias,
508        sample[1] + n[1] * l.shadow_bias,
509        sample[2] + n[2] * l.shadow_bias,
510    ];
511    let in_shadow = 1.0 - l.shadow_strength;
512
513    // Sun key (0..1): N·L × shadow factor.
514    let sun_key = if l.sun {
515        let ndl = dot3(n, l.sun_dir).max(0.0);
516        if ndl > 0.0 && l.sun_casts_shadow {
517            let occ = shadow
518                .as_deref_mut()
519                .is_some_and(|s| s.occluded(shadow_origin, l.sun_dir, l.shadow_max_dist));
520            if occ {
521                ndl * in_shadow
522            } else {
523                ndl
524            }
525        } else {
526            ndl
527        }
528    } else {
529        0.0
530    };
531
532    // Base term: ambient + sun. Smooth = additive; stylized = gradient map.
533    let mut lit = if styled {
534        let key = cel_band(sun_key, l.bands);
535        let m = |i: usize| {
536            let warm = l.sun_color[i] * l.sun_intensity;
537            (l.shadow_tint[i] + (warm - l.shadow_tint[i]) * key) * ao
538        };
539        [albedo[0] * m(0), albedo[1] * m(1), albedo[2] * m(2)]
540    } else {
541        let base = |i: usize| {
542            albedo[i] * l.ambient[i] * ao + albedo[i] * l.sun_color[i] * l.sun_intensity * sun_key
543        };
544        [base(0), base(1), base(2)]
545    };
546
547    // Point lights (flat per voxel). CPU.2 — a flagged caster's shadow ray
548    // marches to the light; an occluded sample keeps `in_shadow` of it.
549    for p in l.points {
550        let d3 = [
551            p.pos[0] - sample[0],
552            p.pos[1] - sample[1],
553            p.pos[2] - sample[2],
554        ];
555        // PF.7 (C4) — squared-distance reject first: the sqrt only runs
556        // for lights actually within radius (same thresholds squared).
557        let d2 = d3[0] * d3[0] + d3[1] * d3[1] + d3[2] * d3[2];
558        if d2 < p.radius * p.radius && d2 > 1e-8 {
559            let dist = d2.sqrt();
560            let inv = 1.0 / dist;
561            let ldir = [d3[0] * inv, d3[1] * inv, d3[2] * inv];
562            let ndl = dot3(n, ldir).max(0.0);
563            // SL — spot cone mask (1.0 for a pure point light). Computed
564            // before the shadow march so an off-cone spot skips it entirely.
565            let cone = spot_cone(ldir, p.spot_dir, p.cos_inner, p.cos_outer);
566            if ndl > 0.0 && cone > 0.0 {
567                // Shadow ray marches from the surface to the light (`dist`).
568                let sh = if p.casts_shadow
569                    && shadow
570                        .as_deref_mut()
571                        .is_some_and(|s| s.occluded(shadow_origin, ldir, dist))
572                {
573                    in_shadow
574                } else {
575                    1.0
576                };
577                let mut f = ndl * point_falloff(dist, p.radius) * cone * sh;
578                if styled {
579                    f = cel_band(f, l.bands);
580                }
581                for i in 0..3 {
582                    lit[i] += albedo[i] * p.color[i] * p.intensity * f;
583                }
584            }
585        }
586    }
587
588    let pack = |v: f32| -> u32 { (v.clamp(0.0, 1.0) * 255.0) as u32 };
589    0x8000_0000 | (pack(lit[0]) << 16) | (pack(lit[1]) << 8) | pack(lit[2])
590}
591
592/// Blend `color` toward `env.fog_color` by perpendicular `depth`
593/// (linear, fully fogged at `env.fog_max_dist`). No-op when fog is
594/// disabled (`fog_max_dist <= 0`).
595#[inline]
596fn apply_fog(color: u32, depth: f32, env: &DdaEnv<'_>) -> u32 {
597    if env.fog_max_dist <= 0.0 {
598        return color;
599    }
600    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
601    let f = ((depth / env.fog_max_dist).clamp(0.0, 1.0) * 256.0) as u32; // 0..256
602    let g = 256 - f;
603    let fog = env.fog_color;
604    let mix = |shift: u32| -> u32 {
605        let src = (color >> shift) & 0xff;
606        let dst = (fog >> shift) & 0xff;
607        ((src * g + dst * f) >> 8).min(255)
608    };
609    0x8000_0000 | (mix(16) << 16) | (mix(8) << 8) | mix(0)
610}
611
612/// Composite premultiplied `accum` (+ remaining `trans`) over a packed
613/// background colour → packed `0x80RRGGBB`.
614#[inline]
615fn composite_over(accum: [f32; 3], trans: f32, bg: u32) -> u32 {
616    let b = rgb_to_f32(bg);
617    f32_to_rgb([
618        accum[0] + trans * b[0],
619        accum[1] + trans * b[1],
620        accum[2] + trans * b[2],
621    ])
622}
623
624/// Finalize a translucent terrain ray that exited the grid (sky). Returns
625/// `None` when nothing was accumulated (the opaque first-hit path — the
626/// caller's sky handling stands, bit-identical), else the accumulated
627/// layers composited over the sky at `dist`.
628#[inline]
629fn finalize_exit(
630    touched: bool,
631    accum: [f32; 3],
632    trans: f32,
633    env: &DdaEnv<'_>,
634    dir: [f32; 3],
635    dist: f32,
636) -> Option<Hit> {
637    if !touched {
638        return None;
639    }
640    let bg = match env.sky {
641        Some(s) => sample_sky(s, dir),
642        None => 0x8000_0000 | (env.fog_color & 0x00ff_ffff),
643    };
644    Some(Hit {
645        color: composite_over(accum, trans, bg),
646        dist,
647    })
648}
649
650/// Unpack `0x__RRGGBB` to `0..1` float channels (RGB; the high byte is
651/// dropped — it has already been folded into the colour by `shade`/`fog`).
652#[inline]
653#[allow(clippy::cast_precision_loss)]
654fn rgb_to_f32(c: u32) -> [f32; 3] {
655    [
656        ((c >> 16) & 0xff) as f32 / 255.0,
657        ((c >> 8) & 0xff) as f32 / 255.0,
658        (c & 0xff) as f32 / 255.0,
659    ]
660}
661
662/// Repack `0..1` float channels (clamped) into `0x80RRGGBB`.
663#[inline]
664#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
665fn f32_to_rgb(c: [f32; 3]) -> u32 {
666    let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u32;
667    0x8000_0000 | (q(c[0]) << 16) | (q(c[1]) << 8) | q(c[2])
668}
669
670/// Sample the sky panorama in ray direction `dir` (need not be
671/// normalised), returning a packed `0x80RRGGBB` colour.
672///
673/// Clean-room equirectangular mapping (not voxlap's `lng`/`lat` asm
674/// search): the texture's x axis is elevation (`asin` of the vertical
675/// component), the y axis is azimuth (`atan2` around the vertical). A
676/// `ysiz == 1` panorama (e.g. [`Sky::blue_gradient`]) is a pure
677/// horizon→zenith gradient.
678#[allow(
679    clippy::cast_possible_truncation,
680    clippy::cast_sign_loss,
681    clippy::cast_precision_loss
682)]
683fn sample_sky(sky: &Sky, dir: [f32; 3]) -> u32 {
684    let len = (dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]).sqrt();
685    if len < 1e-9 {
686        return 0x8000_0000;
687    }
688    let d = [dir[0] / len, dir[1] / len, dir[2] / len];
689    let xsiz_full = sky.lat.len().max(1) as i32; // original column count
690    let pi = std::f32::consts::PI;
691    // Elevation → x, matching the GPU `sky_color` (scene_dda.wgsl): z is
692    // down, so `acos(-z)` is 0 at the zenith (looking up) and π at the nadir
693    // (looking down); `/π` puts the zenith at x=0 and the nadir at x=xsiz.
694    let elev01 = (-d[2]).clamp(-1.0, 1.0).acos() / pi; // 0 (up) .. 1 (down)
695    let x = (elev01 * xsiz_full as f32) as i32;
696    let x = x.clamp(0, xsiz_full - 1);
697    // Azimuth → y (wrapped).
698    let y = if sky.ysiz <= 1 {
699        0
700    } else {
701        let az = d[1].atan2(d[0]); // -pi..pi
702        let yf = ((az / (pi * 2.0)) + 0.5) * sky.ysiz as f32;
703        (yf as i32).rem_euclid(sky.ysiz)
704    };
705    let idx = (y * xsiz_full + x) as usize;
706    let px = sky.pixels.get(idx).copied().unwrap_or(0) as u32;
707    0x8000_0000 | (px & 0x00ff_ffff)
708}
709
710/// Fill the panorama [`Sky`] into every **background** pixel — one whose
711/// z-buffer entry is still `+∞` (no grid/terrain hit). The per-grid DDA only
712/// samples the sky inside each grid's screen rect (and only its sky-owning
713/// grid); pixels outside any grid — most of a sprite/effect-only view, or the
714/// margins around a small world grid — would otherwise keep the caller's flat
715/// clear colour. This paints the real panorama there while leaving terrain
716/// (finite z) and composited translucent pixels untouched. The z-buffer is
717/// not modified. `cam`/`settings` are the same per-frame projection the
718/// renderer used.
719#[allow(clippy::cast_possible_truncation)]
720pub fn render_sky_fill(
721    fb: &mut [u32],
722    zb: &[f32],
723    pitch_pixels: usize,
724    width: u32,
725    height: u32,
726    cam: &CameraState,
727    settings: &OpticastSettings,
728    sky: &Sky,
729) {
730    // PF.7 (C6) — rayon rows: this was a full-frame single-threaded pass
731    // with an `acos` + `atan2` per background pixel (an entire serial
732    // frame on sky-dominant views). Rows are disjoint (`by_ref` chunks of
733    // the framebuffer); `zb` is read-only. Bit-identical.
734    fb.par_chunks_mut(pitch_pixels)
735        .take(height as usize)
736        .enumerate()
737        .for_each(|(py, frow)| {
738            let row = py * pitch_pixels;
739            #[allow(clippy::cast_possible_truncation)]
740            let py = py as u32;
741            for px in 0..width {
742                let idx = row + px as usize;
743                if zb[idx].is_finite() {
744                    continue; // a grid/terrain hit owns this pixel
745                }
746                let (_origin, dir) = pixel_ray(cam, settings, px, py);
747                frow[px as usize] = sample_sky(sky, dir);
748            }
749        });
750}
751
752/// World-space ray for screen pixel `(px, py)` under opticast's
753/// pinhole: origin is the camera position, direction is
754/// `(px - hx)·right + (py - hy)·down + hz·forward`.
755///
756/// This is the exact ray `camera_math::derive` bakes into its corner
757/// vectors (`corn[0]` is `pixel (0, 0)`'s direction), so the DDA
758/// renderer samples the same rays the voxlap path's frustum is built
759/// from. The direction is **not** normalised — callers that need a
760/// unit ray (and a true Euclidean distance) normalise themselves;
761/// DDA.1 will track perpendicular distance via the forward-projection
762/// instead, matching the engine's z-buffer convention.
763#[must_use]
764pub fn pixel_ray(
765    cs: &CameraState,
766    settings: &OpticastSettings,
767    px: u32,
768    py: u32,
769) -> ([f32; 3], [f32; 3]) {
770    // u32 → f32 is exact for any realistic screen coordinate.
771    #[allow(clippy::cast_precision_loss)]
772    let sx = px as f32 - settings.hx;
773    #[allow(clippy::cast_precision_loss)]
774    let sy = py as f32 - settings.hy;
775    let dir = [
776        sx * cs.right[0] + sy * cs.down[0] + settings.hz * cs.forward[0],
777        sx * cs.right[1] + sy * cs.down[1] + settings.hz * cs.forward[1],
778        sx * cs.right[2] + sy * cs.down[2] + settings.hz * cs.forward[2],
779    ];
780    (cs.pos, dir)
781}
782
783/// Ray ↔ axis-aligned box `[lo, hi]` slab test. Returns the
784/// `(t_enter, t_exit)` parameter interval along `dir` (already clamped
785/// so `t_enter >= 0`, i.e. a camera inside the box starts at `t = 0`),
786/// or `None` if the ray misses the box. `dir` need not be normalised —
787/// `t` is in units of `|dir|`.
788pub(crate) fn intersect_aabb(
789    o: [f32; 3],
790    dir: [f32; 3],
791    lo: [f32; 3],
792    hi: [f32; 3],
793) -> Option<(f32, f32)> {
794    let mut t0 = 0.0f32;
795    let mut t1 = f32::INFINITY;
796    for a in 0..3 {
797        if dir[a].abs() < 1e-9 {
798            // Ray parallel to this slab — must already be inside it.
799            if o[a] < lo[a] || o[a] > hi[a] {
800                return None;
801            }
802        } else {
803            let inv = 1.0 / dir[a];
804            let mut ta = (lo[a] - o[a]) * inv;
805            let mut tb = (hi[a] - o[a]) * inv;
806            if ta > tb {
807                core::mem::swap(&mut ta, &mut tb);
808            }
809            t0 = t0.max(ta);
810            t1 = t1.min(tb);
811            if t0 > t1 {
812                return None;
813            }
814        }
815    }
816    Some((t0, t1))
817}
818
819/// Brick edge length in voxels — one occupancy bit per `BRICK³` block.
820const BRICK: i32 = 8;
821
822/// Per-chunk brick occupancy map for two-level DDA empty-space skip
823/// (Substage DDA.3).
824///
825/// One bit per `BRICK³` block of the active chunk, set iff any voxel in
826/// the block is solid. The ray steps the coarse brick grid (8× longer
827/// strides) and only descends into a per-voxel walk inside occupied
828/// bricks, so a ray through open air crosses ~`length / 8` empty bricks
829/// instead of `length` air voxels — each of which would otherwise walk
830/// the column slab chain via `surface_color`.
831///
832/// Built per frame from a [`GridView`] in [`render_dda`]. A persistent
833/// per-chunk cache with edit-driven invalidation (locked decision #2 in
834/// `PORTING-DDA.md`) is a later perf refinement.
835#[derive(Debug)]
836pub(crate) struct BrickMap {
837    /// Brick counts along x / y / z (one entry per `BRICK³` cells).
838    nb: [i32; 3],
839    /// Brick occupancy bitset; brick `(bx, by, bz)` is bit
840    /// `(bz * nb[1] + by) * nb[0] + bx`.
841    bits: Vec<u64>,
842    /// Super-brick counts (one entry per `BRICK³` *bricks* = `SUPER³`
843    /// cells), `ceil(nb / BRICK)`.
844    ns: [i32; 3],
845    /// Super-brick occupancy (DDA.7 perf): a coarse level so a ray
846    /// through open air above the terrain skips `SUPER` cells per outer
847    /// step instead of `BRICK`. A super-brick is set iff any child brick
848    /// is set.
849    super_bits: Vec<u64>,
850}
851
852/// Super-brick edge in cells (`BRICK` bricks per axis).
853const SUPER: i32 = BRICK * BRICK;
854
855impl BrickMap {
856    /// Scan every mip-`mip` column of `grid`, building brick + super-
857    /// brick occupancy. `mip` must be `< grid.mip_count()`.
858    #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)]
859    fn build(grid: &GridView<'_>, mip: u32) -> Self {
860        let vsid_m = (grid.vsid >> mip).max(1) as i32;
861        let z_m = (crate::grid_view::CHUNK_SIZE_Z >> mip).max(1) as i32;
862        let nb = [
863            (vsid_m + BRICK - 1) / BRICK,
864            (vsid_m + BRICK - 1) / BRICK,
865            (z_m + BRICK - 1) / BRICK,
866        ];
867        let ns = [
868            (nb[0] + BRICK - 1) / BRICK,
869            (nb[1] + BRICK - 1) / BRICK,
870            (nb[2] + BRICK - 1) / BRICK,
871        ];
872        let count = (nb[0] * nb[1] * nb[2]) as usize;
873        let scount = (ns[0] * ns[1] * ns[2]) as usize;
874        let mut bits = vec![0u64; count.div_ceil(64)];
875        let mut super_bits = vec![0u64; scount.div_ceil(64)];
876        for y in 0..vsid_m {
877            for x in 0..vsid_m {
878                let (bx, by) = (x / BRICK, y / BRICK);
879                grid.for_each_run_mip(x as u32, y as u32, mip, |top, bot| {
880                    for bz in (top / BRICK)..=((bot - 1) / BRICK) {
881                        let idx = ((bz * nb[1] + by) * nb[0] + bx) as usize;
882                        bits[idx / 64] |= 1u64 << (idx % 64);
883                        let sidx =
884                            (((bz / BRICK) * ns[1] + by / BRICK) * ns[0] + bx / BRICK) as usize;
885                        super_bits[sidx / 64] |= 1u64 << (sidx % 64);
886                    }
887                });
888            }
889        }
890        Self {
891            nb,
892            bits,
893            ns,
894            super_bits,
895        }
896    }
897
898    /// Whether brick `b` is in range and holds any solid voxel.
899    #[inline]
900    #[allow(clippy::cast_sign_loss)]
901    fn occupied(&self, b: [i32; 3]) -> bool {
902        if b[0] < 0
903            || b[0] >= self.nb[0]
904            || b[1] < 0
905            || b[1] >= self.nb[1]
906            || b[2] < 0
907            || b[2] >= self.nb[2]
908        {
909            return false;
910        }
911        let idx = ((b[2] * self.nb[1] + b[1]) * self.nb[0] + b[0]) as usize;
912        (self.bits[idx / 64] >> (idx % 64)) & 1 != 0
913    }
914
915    /// Whether super-brick `s` is in range and holds any solid voxel.
916    #[inline]
917    #[allow(clippy::cast_sign_loss)]
918    fn occupied_super(&self, s: [i32; 3]) -> bool {
919        if s[0] < 0
920            || s[0] >= self.ns[0]
921            || s[1] < 0
922            || s[1] >= self.ns[1]
923            || s[2] < 0
924            || s[2] >= self.ns[2]
925        {
926            return false;
927        }
928        let idx = ((s[2] * self.ns[1] + s[1]) * self.ns[0] + s[0]) as usize;
929        (self.super_bits[idx / 64] >> (idx % 64)) & 1 != 0
930    }
931}
932
933/// Per-axis 3D-DDA stepping state for a cell size of `cell` voxels.
934/// `t_max[a]` is the ray parameter at which the next `a`-boundary is
935/// crossed; `t_delta[a]` is the parameter increment per cell. An
936/// axis-parallel component gets `t_max = t_delta = +inf` so it's never
937/// chosen as the stepping axis.
938pub(crate) fn dda_setup(
939    origin: [f32; 3],
940    dir: [f32; 3],
941    cell: [i32; 3],
942    cell_size: f32,
943) -> ([i32; 3], [f32; 3], [f32; 3]) {
944    let mut step = [0i32; 3];
945    let mut t_max = [f32::INFINITY; 3];
946    let mut t_delta = [f32::INFINITY; 3];
947    for a in 0..3 {
948        if dir[a] > 1e-9 {
949            step[a] = 1;
950            #[allow(clippy::cast_precision_loss)]
951            let boundary = (cell[a] + 1) as f32 * cell_size;
952            t_max[a] = (boundary - origin[a]) / dir[a];
953            t_delta[a] = cell_size / dir[a];
954        } else if dir[a] < -1e-9 {
955            step[a] = -1;
956            #[allow(clippy::cast_precision_loss)]
957            let boundary = cell[a] as f32 * cell_size;
958            t_max[a] = (boundary - origin[a]) / dir[a];
959            t_delta[a] = -cell_size / dir[a];
960        }
961    }
962    (step, t_max, t_delta)
963}
964
965/// Index of the axis with the smallest `t_max` (the next boundary the
966/// ray crosses).
967#[inline]
968pub(crate) fn min_axis(t_max: [f32; 3]) -> usize {
969    if t_max[0] <= t_max[1] && t_max[0] <= t_max[2] {
970        0
971    } else if t_max[1] <= t_max[2] {
972        1
973    } else {
974        2
975    }
976}
977
978/// Persistent, cross-frame brick occupancy cache (Substage DDA.7
979/// perf). Keyed by `(chunk x, y, z, mip)` with the chunk's edit
980/// `version`; an entry is reused until its chunk's version changes, so a
981/// static / streamed-once world pays **zero** brick-build cost after the
982/// first frame (the per-frame rebuild was the dominant DDA cost).
983///
984/// Owned by the caller across frames (the scene's `Grid`), populated
985/// single-threaded via [`Self::ensure`], then borrowed immutably by the
986/// parallel render bands.
987#[derive(Debug, Default)]
988pub struct BrickCache {
989    maps: HashMap<(i32, i32, i32, u32), (u64, BrickMap)>,
990}
991
992impl BrickCache {
993    /// An empty cache (same as [`Default`]). Entries appear via
994    /// [`ensure`](Self::ensure) as chunks are first rendered.
995    #[must_use]
996    pub fn new() -> Self {
997        Self::default()
998    }
999
1000    /// Ensure a current mip-`mip` brick map exists for `chunk` (built
1001    /// from `view`); rebuilds only when the cached `version` differs.
1002    pub fn ensure(&mut self, chunk: [i32; 3], mip: u32, version: u64, view: &GridView<'_>) {
1003        let key = (chunk[0], chunk[1], chunk[2], mip);
1004        let stale = self.maps.get(&key).is_none_or(|(v, _)| *v != version);
1005        if stale {
1006            self.maps.insert(key, (version, BrickMap::build(view, mip)));
1007        }
1008    }
1009
1010    #[inline]
1011    fn get(&self, chunk: [i32; 3], mip: u32) -> Option<&BrickMap> {
1012        self.maps
1013            .get(&(chunk[0], chunk[1], chunk[2], mip))
1014            .map(|(_, m)| m)
1015    }
1016
1017    /// Drop cached entries whose chunk fails `keep` — bounds memory as
1018    /// streaming evicts chunks. Called once per frame by the scene.
1019    pub fn retain_chunks(&mut self, keep: impl Fn([i32; 3]) -> bool) {
1020        self.maps.retain(|k, _| keep([k.0, k.1, k.2]));
1021    }
1022
1023    /// PF.9 — occupancy of the `BRICK`³ block containing chunk-local
1024    /// mip-`mip` cell `cell` of `chunk`. `None` when no map is cached for
1025    /// that (chunk, mip) — the caller must fall back to dense stepping.
1026    /// `Some(false)` guarantees the whole 8³ block holds no solid voxel,
1027    /// so an external shadow march may skip it wholesale.
1028    #[must_use]
1029    pub fn brick_occupied_at(&self, chunk: [i32; 3], mip: u32, cell: [i32; 3]) -> Option<bool> {
1030        self.get(chunk, mip)
1031            .map(|m| m.occupied([cell[0] >> 3, cell[1] >> 3, cell[2] >> 3]))
1032    }
1033
1034    /// PF.9 — like [`Self::brick_occupied_at`] for the `SUPER`³ (64³ at
1035    /// mip 0) super-brick level.
1036    #[must_use]
1037    pub fn super_occupied_at(&self, chunk: [i32; 3], mip: u32, cell: [i32; 3]) -> Option<bool> {
1038        self.get(chunk, mip)
1039            .map(|m| m.occupied_super([cell[0] >> 6, cell[1] >> 6, cell[2] >> 6]))
1040    }
1041}
1042
1043/// Build a throwaway [`BrickCache`] covering every populated chunk of
1044/// `grid` at the effective mip — for the sequential [`render_dda`] /
1045/// tests, where no persistent cache is threaded in. Returns
1046/// `(cache, effective_mip)`.
1047#[allow(clippy::cast_possible_wrap)]
1048fn local_cache(grid: &GridView<'_>, requested_mip: u32) -> (BrickCache, u32) {
1049    let mip = effective_mip(grid, requested_mip);
1050    let mut cache = BrickCache::new();
1051    if let Some(cg) = grid.chunk_grid {
1052        for dz in 0..cg.chunks_z as i32 {
1053            for dy in 0..cg.chunks_y as i32 {
1054                for dx in 0..cg.chunks_x as i32 {
1055                    let slot = ((dz * cg.chunks_y as i32 + dy) * cg.chunks_x as i32 + dx) as usize;
1056                    if let Some(Some(view)) = cg.chunks.get(slot) {
1057                        let ch = [
1058                            cg.origin_chunk_xy[0] + dx,
1059                            cg.origin_chunk_xy[1] + dy,
1060                            cg.origin_chunk_z + dz,
1061                        ];
1062                        cache.ensure(ch, mip, 0, view);
1063                    }
1064                }
1065            }
1066        }
1067    } else {
1068        cache.ensure([0, 0, 0], mip, 0, grid);
1069    }
1070    (cache, mip)
1071}
1072
1073/// Clamp a requested render mip to one every populated chunk actually
1074/// has built — so the uniform-mip traversal never under-samples a chunk
1075/// that lacks the requested level (which would punch holes). `0` short-
1076/// circuits (always available).
1077#[must_use]
1078pub fn effective_mip(grid: &GridView<'_>, requested: u32) -> u32 {
1079    if requested == 0 {
1080        return 0;
1081    }
1082    let mut m = requested;
1083    if let Some(cg) = grid.chunk_grid {
1084        for c in cg.chunks.iter().flatten() {
1085            m = m.min(c.mip_count().saturating_sub(1));
1086        }
1087    } else {
1088        m = m.min(grid.mip_count().saturating_sub(1));
1089    }
1090    m
1091}
1092
1093/// Cross-chunk voxel sampler (Substage DDA.4 / DDA.7).
1094///
1095/// Resolves a grid-local voxel coordinate to the chunk that owns it
1096/// (via [`GridView::chunk_at_xyz`]) and answers the DDA's per-voxel hit
1097/// query — brick-gated [`GridView::surface_color`]. It borrows the
1098/// shared immutable [`BrickMaps`] and caches the **current chunk**
1099/// (`cur_*`: view + brick-map reference): a ray usually stays in one
1100/// chunk for many voxels, so the per-voxel cost is a single index
1101/// compare + an O(1) brick bit test — no hashing, no mutation. Holding
1102/// only shared borrows, a `Sampler` is cheap to spin up per render band.
1103///
1104/// Single-chunk grids are the degenerate case: every voxel maps to
1105/// chunk `[0, 0, 0]` (= the view itself).
1106struct Sampler<'a> {
1107    grid: GridView<'a>,
1108    bricks: &'a BrickCache,
1109    /// Effective render mip (DDA.6). Traversal cells are mip-`mip`
1110    /// cells; sampling reads mip-`mip` data.
1111    mip: u32,
1112    /// Chunk size in mip-`mip` cells is a power of two; store it as
1113    /// `log2` (shift) + `size - 1` (mask) so [`Self::locate`] splits a
1114    /// cell into `(chunk, in-chunk)` with a shift + an `&` per axis
1115    /// instead of a signed `div_euclid` — the dominant per-cell cost.
1116    /// Arithmetic `>>` floors toward -∞ (= `div_euclid` for a positive
1117    /// power-of-two divisor) and `& mask` gives the non-negative
1118    /// remainder (= `rem_euclid`) even for negative cells (two's
1119    /// complement), so results are identical to the division form.
1120    xy_shift: u32,
1121    xy_mask: i32,
1122    z_shift: u32,
1123    z_mask: i32,
1124    cur_ch: [i32; 3],
1125    cur_view: Option<GridView<'a>>,
1126    cur_brick: Option<&'a BrickMap>,
1127    has_cur: bool,
1128}
1129
1130impl<'a> Sampler<'a> {
1131    fn new(grid: GridView<'a>, bricks: &'a BrickCache, mip: u32) -> Self {
1132        let cs_xy = (grid.chunk_size_xy >> mip).max(1);
1133        let cs_z = (crate::grid_view::CHUNK_SIZE_Z >> mip).max(1);
1134        debug_assert!(
1135            cs_xy.is_power_of_two() && cs_z.is_power_of_two(),
1136            "chunk dims must be powers of two for the shift/mask split"
1137        );
1138        #[allow(clippy::cast_possible_wrap)]
1139        Self {
1140            grid,
1141            bricks,
1142            mip,
1143            xy_shift: cs_xy.trailing_zeros(),
1144            xy_mask: cs_xy as i32 - 1,
1145            z_shift: cs_z.trailing_zeros(),
1146            z_mask: cs_z as i32 - 1,
1147            cur_ch: [0; 3],
1148            cur_view: None,
1149            cur_brick: None,
1150            has_cur: false,
1151        }
1152    }
1153
1154    /// Refresh the current-chunk cache (view + brick map) for `ch`.
1155    fn select_chunk(&mut self, ch: [i32; 3]) {
1156        if self.has_cur && self.cur_ch == ch {
1157            return;
1158        }
1159        self.cur_view = self.grid.chunk_at_xyz(ch);
1160        self.cur_brick = self.bricks.get(ch, self.mip);
1161        self.cur_ch = ch;
1162        self.has_cur = true;
1163    }
1164
1165    /// Split a grid-local **mip-`mip` cell** index into `(chunk index,
1166    /// in-chunk mip-cell)` via shift + mask (see field docs). Chunk
1167    /// indices are mip-independent; only the per-chunk resolution
1168    /// shrinks with mip.
1169    #[allow(clippy::cast_sign_loss)]
1170    fn locate(&self, c: [i32; 3]) -> ([i32; 3], [u32; 3]) {
1171        let ch = [
1172            c[0] >> self.xy_shift,
1173            c[1] >> self.xy_shift,
1174            c[2] >> self.z_shift,
1175        ];
1176        let loc = [
1177            (c[0] & self.xy_mask) as u32,
1178            (c[1] & self.xy_mask) as u32,
1179            (c[2] & self.z_mask) as u32,
1180        ];
1181        (ch, loc)
1182    }
1183
1184    /// Hit colour for grid-local mip-cell `c`, or `None` for air / empty
1185    /// chunk / uncoloured bedrock. Brick-gated so air inside a populated
1186    /// chunk costs only a bit test, not a slab walk.
1187    #[allow(clippy::cast_possible_wrap)]
1188    fn hit(&mut self, c: [i32; 3]) -> Option<u32> {
1189        #[cfg(test)]
1190        prof::SURF.with(|x| x.set(x.get() + 1));
1191        let (ch, loc) = self.locate(c);
1192        self.select_chunk(ch);
1193        let occupied = self.cur_brick.is_some_and(|bm| {
1194            bm.occupied([
1195                loc[0] as i32 / BRICK,
1196                loc[1] as i32 / BRICK,
1197                loc[2] as i32 / BRICK,
1198            ])
1199        });
1200        if !occupied {
1201            return None;
1202        }
1203        self.cur_view?
1204            .surface_color_mip(loc[0], loc[1], loc[2], self.mip)
1205            .map(|c| c.0)
1206    }
1207
1208    /// Chunk size in mip-cells along XY / Z (always a power of two).
1209    #[inline]
1210    fn cells_per_chunk_xy(&self) -> i32 {
1211        1 << self.xy_shift
1212    }
1213    #[inline]
1214    fn cells_per_chunk_z(&self) -> i32 {
1215        1 << self.z_shift
1216    }
1217
1218    /// Whether the brick at brick-index `brick` (in `BRICK`-mip-cell
1219    /// units) holds any solid voxel. Used by the outer brick-DDA to skip
1220    /// empty space `BRICK` cells at a time. Assumes bricks nest within
1221    /// chunks (caller gates on [`Self::cells_per_chunk_xy`]`>= BRICK`).
1222    #[allow(clippy::cast_sign_loss)]
1223    fn brick_occupied(&mut self, brick: [i32; 3]) -> bool {
1224        // First mip-cell of the brick (BRICK = 8 → `<< 3`).
1225        let c0 = [brick[0] << 3, brick[1] << 3, brick[2] << 3];
1226        let ch = [
1227            c0[0] >> self.xy_shift,
1228            c0[1] >> self.xy_shift,
1229            c0[2] >> self.z_shift,
1230        ];
1231        self.select_chunk(ch);
1232        self.cur_brick.is_some_and(|bm| {
1233            bm.occupied([
1234                (c0[0] & self.xy_mask) >> 3,
1235                (c0[1] & self.xy_mask) >> 3,
1236                (c0[2] & self.z_mask) >> 3,
1237            ])
1238        })
1239    }
1240
1241    /// Whether the super-brick at super-index `s` (in `SUPER`-mip-cell
1242    /// units) holds any solid voxel. Outer-most empty-space skip (steps
1243    /// `SUPER` cells). Assumes super-bricks nest in chunks (caller gates
1244    /// on `cells_per_chunk >= SUPER`).
1245    #[allow(clippy::cast_sign_loss)]
1246    fn super_occupied(&mut self, s: [i32; 3]) -> bool {
1247        // First mip-cell of the super-brick (SUPER = 64 → `<< 6`).
1248        let c0 = [s[0] << 6, s[1] << 6, s[2] << 6];
1249        let ch = [
1250            c0[0] >> self.xy_shift,
1251            c0[1] >> self.xy_shift,
1252            c0[2] >> self.z_shift,
1253        ];
1254        self.select_chunk(ch);
1255        self.cur_brick.is_some_and(|bm| {
1256            bm.occupied_super([
1257                (c0[0] & self.xy_mask) >> 6,
1258                (c0[1] & self.xy_mask) >> 6,
1259                (c0[2] & self.z_mask) >> 6,
1260            ])
1261        })
1262    }
1263}
1264
1265/// CPU.2 — safety cap on a shadow ray's voxel steps (the `shadow_max_dist`
1266/// / light-distance bound is the real limit; this only backstops a
1267/// degenerate ray). Mirrors the GPU `shadow_max_steps`.
1268const SHADOW_MAX_STEPS: u32 = 1024;
1269
1270/// CPU.2 — [`ShadowTester`] backed by the render [`Sampler`]: a hard-shadow
1271/// occlusion march over the grid's mip-`mip` voxels. The march reuses the
1272/// same `sampler.hit()` occupancy the primary ray uses (so a shadow ray is
1273/// blocked by the same surfaces the camera sees) and the same `[lo_c, hi_c)`
1274/// voxel-box bounds, stepping a standard 3D-DDA until it hits a solid cell
1275/// (occluded), leaves the box / exceeds `max_t` (lit), or hits the step cap.
1276struct SamplerShadow<'s, 'a> {
1277    sampler: &'s mut Sampler<'a>,
1278    cell_size: f32,
1279    lo_c: [i32; 3],
1280    hi_c: [i32; 3],
1281}
1282
1283impl ShadowTester for SamplerShadow<'_, '_> {
1284    #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
1285    fn occluded(&mut self, origin: [f32; 3], dir: [f32; 3], max_t: f32) -> bool {
1286        let cs = self.cell_size;
1287        // PF.9 (C3) — the shadow march gets the primary ray's empty-space
1288        // skip: fast-forward across empty super-bricks / bricks (skipping
1289        // an EMPTY box can never hide an occluder). The step budget is
1290        // consumed in Manhattan cell distance — exactly what the dense
1291        // walk would have spent crossing the same span — so the
1292        // `SHADOW_MAX_STEPS` truncation fires at the identical point and
1293        // hit/no-hit stays bit-compatible with the pre-skip march.
1294        let has_super =
1295            self.sampler.cells_per_chunk_xy() >= SUPER && self.sampler.cells_per_chunk_z() >= SUPER;
1296        let has_brick =
1297            self.sampler.cells_per_chunk_xy() >= BRICK && self.sampler.cells_per_chunk_z() >= BRICK;
1298        let mut cellc = [
1299            (origin[0] / cs).floor() as i32,
1300            (origin[1] / cs).floor() as i32,
1301            (origin[2] / cs).floor() as i32,
1302        ];
1303        let (step, mut t_max, t_delta) = dda_setup(origin, dir, cellc, cs);
1304        let inv = [
1305            if step[0] != 0 { 1.0 / dir[0] } else { 0.0 },
1306            if step[1] != 0 { 1.0 / dir[1] } else { 0.0 },
1307            if step[2] != 0 { 1.0 / dir[2] } else { 0.0 },
1308        ];
1309        let mut t_curr = 0.0f32;
1310        let mut used = 0u32;
1311        while used < SHADOW_MAX_STEPS {
1312            if cellc[0] < self.lo_c[0]
1313                || cellc[0] >= self.hi_c[0]
1314                || cellc[1] < self.lo_c[1]
1315                || cellc[1] >= self.hi_c[1]
1316                || cellc[2] < self.lo_c[2]
1317                || cellc[2] >= self.hi_c[2]
1318            {
1319                return false; // left the voxel box → no occluder ahead
1320            }
1321            if t_curr > max_t {
1322                return false; // past the cap / the light → unshadowed
1323            }
1324            // Empty-space skip (mirrors `cell_walk_skip`'s landing logic:
1325            // the exit axis is pinned to the integer boundary cell so the
1326            // next box's entry cell is always visited densely).
1327            let skip_shift = if has_super
1328                && !self
1329                    .sampler
1330                    .super_occupied([cellc[0] >> 6, cellc[1] >> 6, cellc[2] >> 6])
1331            {
1332                Some(6u32)
1333            } else if has_brick
1334                && !self
1335                    .sampler
1336                    .brick_occupied([cellc[0] >> 3, cellc[1] >> 3, cellc[2] >> 3])
1337            {
1338                Some(3u32)
1339            } else {
1340                None
1341            };
1342            if let Some(sh) = skip_shift {
1343                let mut best_t = f32::INFINITY;
1344                let mut best_axis = 3usize;
1345                let mut plane = [0i32; 3];
1346                for a in 0..3 {
1347                    if step[a] == 0 {
1348                        continue;
1349                    }
1350                    let idx = cellc[a] >> sh;
1351                    plane[a] = if step[a] > 0 {
1352                        (idx + 1) << sh
1353                    } else {
1354                        idx << sh
1355                    };
1356                    let tb = (plane[a] as f32 * cs - origin[a]) * inv[a];
1357                    if tb < best_t {
1358                        best_t = tb;
1359                        best_axis = a;
1360                    }
1361                }
1362                if best_axis == 3 {
1363                    return false;
1364                }
1365                let pb = [
1366                    origin[0] + dir[0] * (best_t + 1e-4),
1367                    origin[1] + dir[1] * (best_t + 1e-4),
1368                    origin[2] + dir[2] * (best_t + 1e-4),
1369                ];
1370                let mut nc = [
1371                    (pb[0] / cs).floor() as i32,
1372                    (pb[1] / cs).floor() as i32,
1373                    (pb[2] / cs).floor() as i32,
1374                ];
1375                nc[best_axis] = if step[best_axis] > 0 {
1376                    plane[best_axis]
1377                } else {
1378                    plane[best_axis] - 1
1379                };
1380                // Budget: the dense walk would have spent one step per
1381                // cell (Manhattan distance). If it runs out inside the
1382                // empty box the dense walk would have returned `false`
1383                // there — nothing solid to find inside it.
1384                let crossed =
1385                    cellc[0].abs_diff(nc[0]) + cellc[1].abs_diff(nc[1]) + cellc[2].abs_diff(nc[2]);
1386                if used.saturating_add(crossed) >= SHADOW_MAX_STEPS {
1387                    return false;
1388                }
1389                used += crossed;
1390                cellc = nc;
1391                for a in 0..3 {
1392                    if step[a] > 0 {
1393                        t_max[a] = ((cellc[a] + 1) as f32 * cs - origin[a]) * inv[a];
1394                    } else if step[a] < 0 {
1395                        t_max[a] = (cellc[a] as f32 * cs - origin[a]) * inv[a];
1396                    }
1397                }
1398                t_curr = best_t.max(t_curr);
1399                continue;
1400            }
1401            if self.sampler.hit(cellc).is_some() {
1402                return true; // a surface blocks the ray
1403            }
1404            let axis = min_axis(t_max);
1405            t_curr = t_max[axis];
1406            cellc[axis] += step[axis];
1407            t_max[axis] += t_delta[axis];
1408            used += 1;
1409        }
1410        false
1411    }
1412}
1413
1414/// Walk mip-cells along the ray within `[lo_c, hi_c)` and return the
1415/// first solid hit, with leak-free empty-space skipping (DDA.7 redux).
1416///
1417/// **Why one continuous DDA, not nested level-walks.** The previous
1418/// design ran an outer brick/super DDA that *jumped* whole bricks and
1419/// only descended into occupied ones. Stepping a coarse cell at a time
1420/// lets the ray slip diagonally **past an occupied coarse cell it only
1421/// touches at a shared edge/corner** — a leak that showed as bright
1422/// sky seams across thin diagonal walls (the cave-demo report). Here a
1423/// *single* cell-granularity DDA carries the exact `(cellc, t_max)`
1424/// state for the whole ray; it only ever **fast-forwards across an
1425/// empty super-brick / brick**, where skipping cannot miss anything.
1426/// The exit axis lands on the integer box-boundary cell (no float
1427/// re-floor on the critical axis), so the entry cell of the next —
1428/// possibly occupied — box is always visited densely. Result: hits are
1429/// bit-identical to the dense per-cell reference, with the empty-space
1430/// speed-up retained.
1431///
1432/// `cell_size` is the mip-cell edge in mip-0 voxels (`1 << mip`);
1433/// `fwd_dot = dir·forward` → perpendicular depth.
1434#[allow(
1435    clippy::too_many_arguments,
1436    clippy::cast_possible_truncation,
1437    clippy::cast_sign_loss,
1438    clippy::cast_precision_loss
1439)]
1440fn cell_walk_skip(
1441    origin: [f32; 3],
1442    dir: [f32; 3],
1443    fwd_dot: f32,
1444    sampler: &mut Sampler<'_>,
1445    lo_c: [i32; 3],
1446    hi_c: [i32; 3],
1447    cell_size: f32,
1448    t_enter: f32,
1449    t_exit: f32,
1450    max_dist: f32,
1451    env: &DdaEnv<'_>,
1452) -> Option<Hit> {
1453    let has_super = sampler.cells_per_chunk_xy() >= SUPER && sampler.cells_per_chunk_z() >= SUPER;
1454    let has_brick = sampler.cells_per_chunk_xy() >= BRICK && sampler.cells_per_chunk_z() >= BRICK;
1455
1456    let start = t_enter + 1e-4;
1457    let p = [
1458        origin[0] + dir[0] * start,
1459        origin[1] + dir[1] * start,
1460        origin[2] + dir[2] * start,
1461    ];
1462    let mut cellc = [
1463        ((p[0] / cell_size).floor() as i32).clamp(lo_c[0], hi_c[0] - 1),
1464        ((p[1] / cell_size).floor() as i32).clamp(lo_c[1], hi_c[1] - 1),
1465        ((p[2] / cell_size).floor() as i32).clamp(lo_c[2], hi_c[2] - 1),
1466    ];
1467    let (step, mut t_max, t_delta) = dda_setup(origin, dir, cellc, cell_size);
1468    // Reciprocal direction → the per-skip box-boundary t and the t_max
1469    // refresh use multiplies instead of divisions (the dominant skip
1470    // cost). `0.0` where `step == 0` (that axis' t_max stays +∞).
1471    let inv = [
1472        if step[0] != 0 { 1.0 / dir[0] } else { 0.0 },
1473        if step[1] != 0 { 1.0 / dir[1] } else { 0.0 },
1474        if step[2] != 0 { 1.0 / dir[2] } else { 0.0 },
1475    ];
1476    let mut t_curr = t_enter;
1477    let mut last_axis = 3usize;
1478    // World ray length per ray-parameter unit; divided by `cell_size` it turns
1479    // a cell's `t` span into its path length in voxel units (Volumetric weight).
1480    let dir_len = (dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]).sqrt();
1481    // PF.7 (C4) — hoisted out of the hit block: "does anything cast a
1482    // shadow?" is ray-invariant, and the O(lights) `any()` scan ran per
1483    // hit (per translucent layer on glass/water rays).
1484    let shadow_casts = env.lights.enabled
1485        && env.lights.shadow_strength > 0.0
1486        && (env.lights.sun_casts_shadow || env.lights.points.iter().any(|p| p.casts_shadow));
1487
1488    // TV: front-to-back translucent accumulation. While no translucent voxel
1489    // is hit (`touched` stays false) every return is unchanged — the opaque
1490    // world renders bit-identically. `prev_*` drive per-span compositing (one
1491    // alpha layer per contiguous solid run or material change).
1492    let mut accum = [0.0f32; 3];
1493    let mut trans = 1.0f32;
1494    let mut touched = false;
1495    let mut prev_solid = false;
1496    let mut prev_mat = 0u8;
1497
1498    // Each iteration either advances ≥1 cell (dense) or ≥1 box (skip),
1499    // so the total cell span bounds the loop.
1500    let span = (hi_c[0] - lo_c[0]) + (hi_c[1] - lo_c[1]) + (hi_c[2] - lo_c[2]);
1501    let max_steps = span.max(0) as usize + 16;
1502    for _ in 0..max_steps {
1503        if cellc[0] < lo_c[0]
1504            || cellc[0] >= hi_c[0]
1505            || cellc[1] < lo_c[1]
1506            || cellc[1] >= hi_c[1]
1507            || cellc[2] < lo_c[2]
1508            || cellc[2] >= hi_c[2]
1509        {
1510            return finalize_exit(touched, accum, trans, env, dir, max_dist);
1511        }
1512        let depth = t_curr * fwd_dot;
1513        if depth > max_dist || t_curr > t_exit {
1514            return finalize_exit(touched, accum, trans, env, dir, max_dist);
1515        }
1516        // Fog is fully opaque at `fog_max_dist`: nothing beyond is
1517        // visible, so stop the ray there and return the fog colour
1518        // rather than traversing (and skip/step-counting) to the far box
1519        // wall. Both correct and the dominant perf win for foggy worlds —
1520        // it caps every ray's length at the fog distance.
1521        if env.fog_max_dist > 0.0 && depth >= env.fog_max_dist {
1522            let fog = 0x8000_0000 | (env.fog_color & 0x00ff_ffff);
1523            let color = if touched {
1524                composite_over(accum, trans, fog)
1525            } else {
1526                fog
1527            };
1528            return Some(Hit {
1529                color,
1530                dist: env.fog_max_dist,
1531            });
1532        }
1533
1534        // Empty-space skip: a whole empty super-brick, else an empty
1535        // brick. Skipping only empty boxes can never miss a surface.
1536        let skip_shift = if has_super
1537            && !sampler.super_occupied([cellc[0] >> 6, cellc[1] >> 6, cellc[2] >> 6])
1538        {
1539            Some(6u32)
1540        } else if has_brick
1541            && !sampler.brick_occupied([cellc[0] >> 3, cellc[1] >> 3, cellc[2] >> 3])
1542        {
1543            Some(3u32)
1544        } else {
1545            None
1546        };
1547        if let Some(sh) = skip_shift {
1548            #[cfg(test)]
1549            prof::BRICKS.with(|x| x.set(x.get() + 1));
1550            // Nearest box boundary along the ray (in cell units).
1551            let mut best_t = f32::INFINITY;
1552            let mut best_axis = 3usize;
1553            let mut plane = [0i32; 3];
1554            for a in 0..3 {
1555                if step[a] == 0 {
1556                    continue;
1557                }
1558                let idx = cellc[a] >> sh;
1559                plane[a] = if step[a] > 0 {
1560                    (idx + 1) << sh
1561                } else {
1562                    idx << sh
1563                };
1564                let tb = (plane[a] as f32 * cell_size - origin[a]) * inv[a];
1565                if tb < best_t {
1566                    best_t = tb;
1567                    best_axis = a;
1568                }
1569            }
1570            if best_axis == 3 {
1571                return finalize_exit(touched, accum, trans, env, dir, max_dist);
1572            }
1573            // Land just across the boundary; pin the exit axis to the
1574            // integer boundary cell so float error can't skip the next
1575            // box's entry cell. Other axes haven't crossed their box
1576            // boundary (best_t is the min), so the point's floor is safe.
1577            let pb = [
1578                origin[0] + dir[0] * (best_t + 1e-4),
1579                origin[1] + dir[1] * (best_t + 1e-4),
1580                origin[2] + dir[2] * (best_t + 1e-4),
1581            ];
1582            let mut nc = [
1583                (pb[0] / cell_size).floor() as i32,
1584                (pb[1] / cell_size).floor() as i32,
1585                (pb[2] / cell_size).floor() as i32,
1586            ];
1587            nc[best_axis] = if step[best_axis] > 0 {
1588                plane[best_axis]
1589            } else {
1590                plane[best_axis] - 1
1591            };
1592            // The skip crossed a box boundary; if that takes the ray out
1593            // of the grid box it has exited (sky) — return rather than
1594            // clamping back in-bounds, which would spin at the edge.
1595            if nc[0] < lo_c[0]
1596                || nc[0] >= hi_c[0]
1597                || nc[1] < lo_c[1]
1598                || nc[1] >= hi_c[1]
1599                || nc[2] < lo_c[2]
1600                || nc[2] >= hi_c[2]
1601            {
1602                return finalize_exit(touched, accum, trans, env, dir, max_dist);
1603            }
1604            cellc = nc;
1605            // Refresh t_max for the new cell (dir unchanged → t_delta and
1606            // step constant; axes with step==0 keep their +∞).
1607            for a in 0..3 {
1608                if step[a] > 0 {
1609                    t_max[a] = ((cellc[a] + 1) as f32 * cell_size - origin[a]) * inv[a];
1610                } else if step[a] < 0 {
1611                    t_max[a] = (cellc[a] as f32 * cell_size - origin[a]) * inv[a];
1612                }
1613            }
1614            t_curr = best_t.max(t_curr);
1615            last_axis = best_axis;
1616            prev_solid = false; // skipped empty space → next hit starts a run
1617            continue;
1618        }
1619
1620        // Occupied brick: dense per-cell surface test.
1621        #[cfg(test)]
1622        prof::CELLS.with(|x| x.set(x.get() + 1));
1623        if let Some(color) = sampler.hit(cellc) {
1624            let bright_sub = side_shade_sub(env, last_axis, step);
1625            // PF.7 (C4) — one colour→material scan per hit: resolve the id
1626            // and the material together. EV.1 hoisted this above the shade
1627            // so the emissive branch can bypass lighting entirely; with no
1628            // terrain material map the result is `OPAQUE` (emissive 0) and
1629            // every path below is bit-identical to the pre-material code.
1630            let (m, mat_id) = match env.materials {
1631                Some(table) if !env.terrain_materials.is_empty() => {
1632                    let id = material_for_color(env.terrain_materials, color);
1633                    (table.get(id), id)
1634                }
1635                _ => (Material::OPAQUE, 0),
1636            };
1637            // CPU.1 — dynamic lighting (flat per voxel) when a rig is active;
1638            // else the baked-byte `shade` path (byte-identical). CPU.2 — a
1639            // sun/point shadow march reuses this same `sampler` (occupancy +
1640            // box bounds); only built when a caster is actually flagged so
1641            // the no-shadow rig stays march-free. EV.1 — an emissive
1642            // material outranks both: full-bright albedo, no face shade,
1643            // no rig, no shadow march.
1644            let shaded = if m.emissive > 0 {
1645                emissive_shade(color, m.emissive)
1646            } else if env.lights.enabled {
1647                let casts = shadow_casts;
1648                // Pick the shadow oracle: the scene-wide one (cross-grid +
1649                // sprites, XS.1) when present, else the single-grid Sampler;
1650                // `None` when no caster is flagged, so the rig stays
1651                // march-free. The two testers live in branch-local slots so
1652                // exactly one is borrowed for the `shade_lit_cpu` call.
1653                let mut world_sh;
1654                let mut sampler_sh;
1655                let tester: Option<&mut dyn ShadowTester> = if !casts {
1656                    None
1657                } else if let Some(ctx) = env.world_shadow {
1658                    world_sh = WorldShadow { ctx };
1659                    Some(&mut world_sh)
1660                } else {
1661                    sampler_sh = SamplerShadow {
1662                        sampler: &mut *sampler,
1663                        cell_size,
1664                        lo_c,
1665                        hi_c,
1666                    };
1667                    Some(&mut sampler_sh)
1668                };
1669                shade_lit_cpu(
1670                    color,
1671                    bright_sub,
1672                    last_axis,
1673                    step,
1674                    cellc,
1675                    cell_size,
1676                    &env.lights,
1677                    tester,
1678                )
1679            } else {
1680                shade(color, bright_sub)
1681            };
1682            let lit = apply_fog(shaded, depth.max(0.0), env);
1683            if m.is_opaque() {
1684                // Opaque surface: the background. Return the first hit verbatim
1685                // when nothing translucent preceded it (bit-identical), else
1686                // composite the accumulated layers over it.
1687                let color = if touched {
1688                    composite_over(accum, trans, lit)
1689                } else {
1690                    lit
1691                };
1692                return Some(Hit {
1693                    color,
1694                    dist: depth.max(0.0),
1695                });
1696            }
1697            let a = f32::from(m.alpha) / 255.0;
1698            if matches!(m.mode, roxlap_formats::material::BlendMode::Volumetric) {
1699                // Per-cell Beer–Lambert: opacity weighted by the ray's path
1700                // length through this voxel (so a filled volume thickens
1701                // smoothly with depth, a sliver contributes ≈0). Occludes.
1702                let t_exit = t_max[min_axis(t_max)];
1703                let seg_len = (t_exit - t_curr).max(0.0) * dir_len / cell_size;
1704                let eff_a = 1.0 - (1.0 - a).powf(seg_len);
1705                let c = rgb_to_f32(lit);
1706                accum[0] += trans * eff_a * c[0];
1707                accum[1] += trans * eff_a * c[1];
1708                accum[2] += trans * eff_a * c[2];
1709                trans *= 1.0 - eff_a;
1710                touched = true;
1711                prev_mat = mat_id;
1712                if trans < 1.0 / 256.0 {
1713                    return Some(Hit {
1714                        color: f32_to_rgb(accum),
1715                        dist: depth.max(0.0),
1716                    });
1717                }
1718            } else if !prev_solid || mat_id != prev_mat {
1719                // AlphaBlend / Additive: one alpha layer per solid-run entry or
1720                // material change (per-span — avoids the voxel-grid striping
1721                // through a thick glass/water slab; thickness-independent).
1722                let c = rgb_to_f32(lit);
1723                accum[0] += trans * a * c[0];
1724                accum[1] += trans * a * c[1];
1725                accum[2] += trans * a * c[2];
1726                if !matches!(m.mode, roxlap_formats::material::BlendMode::Additive) {
1727                    trans *= 1.0 - a; // AlphaBlend occludes; Additive does not.
1728                }
1729                touched = true;
1730                prev_mat = mat_id;
1731                if trans < 1.0 / 256.0 {
1732                    return Some(Hit {
1733                        color: f32_to_rgb(accum),
1734                        dist: depth.max(0.0),
1735                    });
1736                }
1737            }
1738            prev_solid = true;
1739        } else {
1740            prev_solid = false;
1741        }
1742        let axis = min_axis(t_max);
1743        last_axis = axis;
1744        t_curr = t_max[axis];
1745        cellc[axis] += step[axis];
1746        t_max[axis] += t_delta[axis];
1747    }
1748    None
1749}
1750
1751/// Per-face brightness reduction for the hit face. `axis` is the axis
1752/// the ray crossed to enter the hit voxel (`3` = entry voxel, no face);
1753/// `step[axis]` gives the crossing direction. Maps to the
1754/// `[x-, x+, y-, y+, z-, z+]` `side_shades` entry of the face the ray
1755/// looks at (a `+step` crossing enters through the low / `-` face).
1756#[inline]
1757fn side_shade_sub(env: &DdaEnv<'_>, axis: usize, step: [i32; 3]) -> u32 {
1758    if axis >= 3 {
1759        return 0;
1760    }
1761    let face = axis * 2 + usize::from(step[axis] < 0);
1762    env.side_shades[face].max(0) as u32
1763}
1764
1765/// Cast one ray into the grid and return the first solid hit.
1766///
1767/// **DDA.4:** cross-chunk per-pixel 3D-DDA over the grid's full voxel
1768/// box ([`GridView::voxel_bounds`], spanning every chunk in XY **and**
1769/// Z). The [`Sampler`] resolves each stepped voxel to its chunk and
1770/// brick-gates the slab walk. Cross-chunk look-down (the case the
1771/// voxlap renderer needed the whole virtual-column stack for) falls out
1772/// of the box simply spanning `chunks_z` along Z.
1773fn cast_ray(
1774    origin: [f32; 3],
1775    dir: [f32; 3],
1776    forward: [f32; 3],
1777    sampler: &mut Sampler<'_>,
1778    settings: &OpticastSettings,
1779    env: &DdaEnv<'_>,
1780) -> Option<Hit> {
1781    let (lo_i, hi_i) = sampler.grid.voxel_bounds();
1782    #[allow(clippy::cast_precision_loss)]
1783    let lo_f = [lo_i[0] as f32, lo_i[1] as f32, lo_i[2] as f32];
1784    #[allow(clippy::cast_precision_loss)]
1785    let hi_f = [hi_i[0] as f32, hi_i[1] as f32, hi_i[2] as f32];
1786    let (t_enter, t_exit) = intersect_aabb(origin, dir, lo_f, hi_f)?;
1787    let fwd_dot = dir[0] * forward[0] + dir[1] * forward[1] + dir[2] * forward[2];
1788    #[allow(clippy::cast_precision_loss)]
1789    let max_dist = settings.max_scan_dist.max(1) as f32;
1790    let cell = 1i32 << sampler.mip;
1791    let cell_size = cell as f32;
1792    let lo_c = [
1793        lo_i[0].div_euclid(cell),
1794        lo_i[1].div_euclid(cell),
1795        lo_i[2].div_euclid(cell),
1796    ];
1797    let hi_c = [
1798        hi_i[0].div_euclid(cell),
1799        hi_i[1].div_euclid(cell),
1800        hi_i[2].div_euclid(cell),
1801    ];
1802    cell_walk_skip(
1803        origin, dir, fwd_dot, sampler, lo_c, hi_c, cell_size, t_enter, t_exit, max_dist, env,
1804    )
1805}
1806
1807/// Render one grid into `sink` with per-pixel 3D-DDA.
1808///
1809/// `camera` is the grid-local pose, `settings`
1810/// ([`OpticastSettings`]) carries the projection + viewport (including
1811/// the `y_start..y_end` strip bound), and `grid` is the per-frame
1812/// [`GridView`] borrow. `pitch_pixels` is the framebuffer
1813/// row stride in pixels (matches `ScalarRasterizer::new`'s argument).
1814///
1815/// On a miss, a textured sky ([`DdaEnv::sky`]) is sampled per ray
1816/// direction and written at `+inf` depth; with no textured sky the miss
1817/// writes nothing, so the caller's solid sky pre-fill shows (the
1818/// `render_scene_composed` path pre-fills it).
1819pub fn render_dda(
1820    camera: &Camera,
1821    settings: &OpticastSettings,
1822    grid: GridView<'_>,
1823    pitch_pixels: usize,
1824    env: &DdaEnv<'_>,
1825    mip: u32,
1826    sink: &mut impl PixelSink,
1827) {
1828    let cs = camera_math::derive(
1829        camera,
1830        settings.xres,
1831        settings.yres,
1832        settings.hx,
1833        settings.hy,
1834        settings.hz,
1835    );
1836
1837    // Sequential path builds a throwaway per-call cache (tests / single
1838    // grid). The parallel path takes a persistent cross-frame cache.
1839    let (cache, mip) = local_cache(&grid, mip);
1840    let mut sampler = Sampler::new(grid, &cache, mip);
1841
1842    for py in settings.y_start..settings.y_end {
1843        let row = py as usize * pitch_pixels;
1844        for px in settings.x_start..settings.x_end {
1845            if let Some((color, dist)) = pixel_result(&cs, settings, &mut sampler, env, px, py) {
1846                sink.put(row + px as usize, color, dist);
1847            }
1848        }
1849    }
1850}
1851
1852/// Resolve one pixel: a shaded + fogged hit colour, a sampled textured
1853/// sky on a miss, or `None` (miss with no textured sky → caller's
1854/// pre-fill stands). Shared by the sequential ([`render_dda`]) and
1855/// parallel ([`render_dda_parallel`]) drivers.
1856#[inline]
1857fn pixel_result(
1858    cs: &CameraState,
1859    settings: &OpticastSettings,
1860    sampler: &mut Sampler<'_>,
1861    env: &DdaEnv<'_>,
1862    px: u32,
1863    py: u32,
1864) -> Option<(u32, f32)> {
1865    let (origin, dir) = pixel_ray(cs, settings, px, py);
1866    if let Some(hit) = cast_ray(origin, dir, cs.forward, sampler, settings, env) {
1867        Some((hit.color, hit.dist))
1868    } else {
1869        env.sky.map(|sky| (sample_sky(sky, dir), f32::INFINITY))
1870    }
1871}
1872
1873/// Tile-parallel [`render_dda`] writing straight into `(fb, zb)`.
1874///
1875/// DDA pixels are independent, so the framebuffer splits into disjoint
1876/// horizontal bands rendered concurrently (rayon) — **bit-identical**
1877/// to the sequential render regardless of thread count, unlike voxlap's
1878/// per-strip discretisation. Each band spins up its own lightweight
1879/// `Sampler` over the shared, immutable `cache`.
1880///
1881/// `cache` must already hold current brick maps for every chunk at
1882/// `mip` (populate via [`BrickCache::ensure`]); `mip` is the effective
1883/// render mip ([`effective_mip`]). `(fb, zb)` use the standard
1884/// conventions (`0x80RRGGBB`; z = perp distance, smaller = closer); a
1885/// miss writes nothing unless [`DdaEnv::sky`] is set. `pitch_pixels` is
1886/// the row stride.
1887#[allow(clippy::cast_possible_truncation, clippy::too_many_arguments)]
1888pub fn render_dda_parallel(
1889    camera: &Camera,
1890    settings: &OpticastSettings,
1891    grid: GridView<'_>,
1892    fb: &mut [u32],
1893    zb: &mut [f32],
1894    pitch_pixels: usize,
1895    env: &DdaEnv<'_>,
1896    cache: &BrickCache,
1897    mip: u32,
1898) {
1899    debug_assert_eq!(fb.len(), zb.len());
1900    let (y0, y1) = (settings.y_start, settings.y_end);
1901    if y1 <= y0 {
1902        return;
1903    }
1904    let cs = camera_math::derive(
1905        camera,
1906        settings.xres,
1907        settings.yres,
1908        settings.hx,
1909        settings.hy,
1910        settings.hz,
1911    );
1912    let target = RasterTarget::new(fb, zb);
1913
1914    // PF.7 (C5) — small fixed bands + rayon work-stealing instead of one
1915    // equal band per thread: sky-heavy rows finish instantly while
1916    // horizon/terrain rows dominate, so an equal split left threads idle
1917    // for the tail of every frame. 8 rows amortises the per-band
1918    // `Sampler` construction while staying fine-grained enough to
1919    // balance. Bit-identical (pixels are independent; rows disjoint).
1920    let band = 8u32;
1921    let bands: Vec<(u32, u32)> = (y0..y1)
1922        .step_by(band as usize)
1923        .map(|s| (s, (s + band).min(y1)))
1924        .collect();
1925
1926    bands.par_iter().for_each(|&(by0, by1)| {
1927        let mut sampler = Sampler::new(grid, cache, mip);
1928        for py in by0..by1 {
1929            let row = py as usize * pitch_pixels;
1930            for px in settings.x_start..settings.x_end {
1931                if let Some((color, dist)) = pixel_result(&cs, settings, &mut sampler, env, px, py)
1932                {
1933                    let idx = row + px as usize;
1934                    // SAFETY: bands cover disjoint row ranges, so writes
1935                    // never alias across threads; `idx` is in-bounds for
1936                    // a `pitch * height`-sized buffer.
1937                    unsafe {
1938                        target.write_color(idx, color);
1939                        target.write_depth(idx, dist);
1940                    }
1941                }
1942            }
1943        }
1944    });
1945}
1946
1947/// Dense per-voxel reference cast for a **single-chunk** grid: walks
1948/// every voxel of `[0, vsid)² × [0, CHUNK_SIZE_Z)` calling
1949/// [`GridView::surface_color`] directly — no brick gate, no chunk
1950/// resolution. The equivalence oracle the brickmap + sampler
1951/// [`cast_ray`] is checked against in tests.
1952#[cfg(test)]
1953#[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
1954fn cast_ray_reference(
1955    origin: [f32; 3],
1956    dir: [f32; 3],
1957    forward: [f32; 3],
1958    grid: &GridView<'_>,
1959    settings: &OpticastSettings,
1960) -> Option<Hit> {
1961    let nx = grid.vsid as f32;
1962    let nz = f32::from(u16::try_from(crate::grid_view::CHUNK_SIZE_Z).unwrap_or(256));
1963    #[allow(clippy::cast_possible_wrap)]
1964    let n_i = [
1965        grid.vsid as i32,
1966        grid.vsid as i32,
1967        crate::grid_view::CHUNK_SIZE_Z as i32,
1968    ];
1969    let (t_enter, t_exit) = intersect_aabb(origin, dir, [0.0; 3], [nx, nx, nz])?;
1970    let fwd_dot = dir[0] * forward[0] + dir[1] * forward[1] + dir[2] * forward[2];
1971    let max_dist = settings.max_scan_dist.max(1) as f32;
1972
1973    let start = t_enter + 1e-4;
1974    let p = [
1975        origin[0] + dir[0] * start,
1976        origin[1] + dir[1] * start,
1977        origin[2] + dir[2] * start,
1978    ];
1979    let mut voxel = [
1980        (p[0].floor() as i32).clamp(0, n_i[0] - 1),
1981        (p[1].floor() as i32).clamp(0, n_i[1] - 1),
1982        (p[2].floor() as i32).clamp(0, n_i[2] - 1),
1983    ];
1984    let (step, mut t_max, t_delta) = dda_setup(origin, dir, voxel, 1.0);
1985    let mut t_curr = t_enter;
1986    let max_steps = (n_i[0] + n_i[1] + n_i[2]) as usize + 8;
1987    for _ in 0..max_steps {
1988        if voxel[0] < 0
1989            || voxel[0] >= n_i[0]
1990            || voxel[1] < 0
1991            || voxel[1] >= n_i[1]
1992            || voxel[2] < 0
1993            || voxel[2] >= n_i[2]
1994        {
1995            return None;
1996        }
1997        let depth = t_curr * fwd_dot;
1998        if depth > max_dist || t_curr > t_exit {
1999            return None;
2000        }
2001        #[allow(clippy::cast_sign_loss)]
2002        if let Some(color) = grid.surface_color(voxel[0] as u32, voxel[1] as u32, voxel[2] as u32) {
2003            return Some(Hit {
2004                color: shade(color.0, 0),
2005                dist: depth.max(0.0),
2006            });
2007        }
2008        let axis = min_axis(t_max);
2009        t_curr = t_max[axis];
2010        voxel[axis] += step[axis];
2011        t_max[axis] += t_delta[axis];
2012    }
2013    None
2014}
2015
2016#[cfg(test)]
2017mod tests {
2018    use super::*;
2019    use roxlap_formats::VoxColor;
2020
2021    // CPU.1 — luminance of a packed colour's low-24-bit RGB.
2022    fn lum(p: u32) -> u32 {
2023        (p & 0xff) + ((p >> 8) & 0xff) + ((p >> 16) & 0xff)
2024    }
2025
2026    #[test]
2027    fn cel_band_quantizes_and_collapses() {
2028        // Two distinct factors round to the same band at bands=2.
2029        assert_eq!(cel_band(0.8, 2), cel_band(0.9, 2));
2030        assert!((cel_band(0.8, 2) - 1.0).abs() < 1e-6);
2031        // ...but a low factor lands on a different band.
2032        assert_ne!(cel_band(0.3, 2), cel_band(0.8, 2));
2033    }
2034
2035    #[test]
2036    fn shade_lit_cpu_sun_lights_by_facing() {
2037        // Grey voxel (brightness 0x80 = full ambient). Floor top face: hit via
2038        // a +z step (axis 2) ⇒ normal points up (-z).
2039        let color = 0x80_80_80_80;
2040        let step = [0, 0, 1];
2041        let base = CpuLights {
2042            enabled: true,
2043            sun: true,
2044            sun_color: [1.0; 3],
2045            sun_intensity: 1.0,
2046            ambient: [0.2; 3],
2047            ..CpuLights::default()
2048        };
2049        let facing = CpuLights {
2050            sun_dir: [0.0, 0.0, -1.0],
2051            ..base
2052        }; // toward sun = up
2053        let back = CpuLights {
2054            sun_dir: [0.0, 0.0, 1.0],
2055            ..base
2056        }; // sun below the face
2057        let lit = shade_lit_cpu(color, 0, 2, step, [0, 0, 0], 1.0, &facing, None);
2058        let dark = shade_lit_cpu(color, 0, 2, step, [0, 0, 0], 1.0, &back, None);
2059        assert!(
2060            lum(lit) > lum(dark),
2061            "sun facing the surface must brighten it: {lit:#08x} vs {dark:#08x}",
2062        );
2063    }
2064
2065    #[test]
2066    fn shade_dynamic_spot_cone_masks_off_axis() {
2067        // Surface at the origin, up-facing normal (-z, voxlap z-down); a light
2068        // 10 units "above" it (at -z). No ambient/AO ⇒ only the light shows.
2069        let albedo = [0.5, 0.5, 0.5];
2070        let n = [0.0, 0.0, -1.0];
2071        let sample = [0.0, 0.0, 0.0];
2072        let inner = 10.0f32.to_radians().cos();
2073        let outer = 15.0f32.to_radians().cos();
2074        let shade = |spot_dir: [f32; 3], cos_inner: f32, cos_outer: f32| {
2075            let pts = [CpuPointLight {
2076                pos: [0.0, 0.0, -10.0],
2077                color: [1.0; 3],
2078                intensity: 1.0,
2079                radius: 64.0,
2080                casts_shadow: false,
2081                spot_dir,
2082                cos_inner,
2083                cos_outer,
2084            }];
2085            let l = CpuLights {
2086                enabled: true,
2087                ambient: [0.0; 3],
2088                points: &pts,
2089                ..CpuLights::default()
2090            };
2091            shade_dynamic(albedo, 0.0, n, sample, &l, None)
2092        };
2093        // A pure point light (cos_outer = -1) ignores the axis entirely.
2094        let point = shade([0.0, 0.0, 1.0], -1.0, -1.0);
2095        // A spot whose axis shines straight down onto the surface (on-axis).
2096        let on_axis = shade([0.0, 0.0, 1.0], inner, outer);
2097        // Same spot aimed sideways ⇒ the surface is outside the cone.
2098        let off_axis = shade([1.0, 0.0, 0.0], inner, outer);
2099
2100        // On-axis (cd == 1) is fully inside the cone ⇒ identical to a point.
2101        assert_eq!(
2102            on_axis, point,
2103            "on-axis spot must equal the point light: {on_axis:#08x} vs {point:#08x}",
2104        );
2105        // Off-axis is masked to zero ⇒ only the (zero) ambient remains.
2106        assert!(
2107            lum(on_axis) > lum(off_axis),
2108            "off-axis spot must be darker: {on_axis:#08x} vs {off_axis:#08x}",
2109        );
2110        assert_eq!(lum(off_axis), 0, "off-cone spot contributes nothing");
2111    }
2112
2113    #[test]
2114    fn shade_lit_cpu_cel_terraces_sun() {
2115        // Two sun elevations with distinct N·L (0.8 / 0.9) collapse to one
2116        // band at bands=2 ⇒ identical stylized colour; smooth (bands=0) differs.
2117        let color = 0x80_80_80_80;
2118        let step = [0, 0, 1];
2119        let mk = |zc: f32, bands: u32| {
2120            let n = (1.0f32 - zc * zc).sqrt();
2121            CpuLights {
2122                enabled: true,
2123                sun: true,
2124                sun_dir: [n, 0.0, -zc], // ndl on the up face = zc
2125                sun_color: [1.0; 3],
2126                sun_intensity: 1.0,
2127                ambient: [0.1; 3],
2128                bands,
2129                ..CpuLights::default()
2130            }
2131        };
2132        let smooth_a = shade_lit_cpu(color, 0, 2, step, [0, 0, 0], 1.0, &mk(0.8, 0), None);
2133        let smooth_b = shade_lit_cpu(color, 0, 2, step, [0, 0, 0], 1.0, &mk(0.9, 0), None);
2134        assert_ne!(smooth_a, smooth_b, "smooth diffuse must vary with N·L");
2135        let cel_a = shade_lit_cpu(color, 0, 2, step, [0, 0, 0], 1.0, &mk(0.8, 2), None);
2136        let cel_b = shade_lit_cpu(color, 0, 2, step, [0, 0, 0], 1.0, &mk(0.9, 2), None);
2137        assert_eq!(
2138            cel_a, cel_b,
2139            "cel banding must terrace both N·L to one level"
2140        );
2141    }
2142
2143    /// CPU.2 — the shadow application math (independent of the march): an
2144    /// occluded sun-lit sample keeps only `1 - shadow_strength` of the sun
2145    /// key, and `shadow_strength == 0` makes shadows invisible.
2146    #[test]
2147    fn shade_dynamic_sun_shadow_darkens() {
2148        struct Mock(bool);
2149        impl ShadowTester for Mock {
2150            fn occluded(&mut self, _: [f32; 3], _: [f32; 3], _: f32) -> bool {
2151                self.0
2152            }
2153        }
2154        let l = CpuLights {
2155            enabled: true,
2156            sun: true,
2157            sun_dir: [0.0, 0.0, -1.0], // up = toward the sun
2158            sun_color: [1.0; 3],
2159            sun_intensity: 1.0,
2160            sun_casts_shadow: true,
2161            ambient: [0.2; 3],
2162            shadow_strength: 0.7,
2163            shadow_bias: 1.5,
2164            shadow_max_dist: 64.0,
2165            ..CpuLights::default()
2166        };
2167        let albedo = [0.8; 3];
2168        let n = [0.0, 0.0, -1.0]; // up face, faces the sun
2169        let s = [0.5, 0.5, 0.5];
2170        let lit = shade_dynamic(albedo, 1.0, n, s, &l, Some(&mut Mock(false)));
2171        let shadowed = shade_dynamic(albedo, 1.0, n, s, &l, Some(&mut Mock(true)));
2172        assert!(
2173            lum(shadowed) < lum(lit),
2174            "an occluded sun face must darken: shadowed={shadowed:#08x} lit={lit:#08x}",
2175        );
2176        // strength 0 ⇒ no visible shadow even when occluded.
2177        let l0 = CpuLights {
2178            shadow_strength: 0.0,
2179            ..l
2180        };
2181        assert_eq!(
2182            shade_dynamic(albedo, 1.0, n, s, &l0, Some(&mut Mock(true))),
2183            shade_dynamic(albedo, 1.0, n, s, &l0, Some(&mut Mock(false))),
2184            "shadow_strength 0 ⇒ shadows invisible",
2185        );
2186    }
2187
2188    /// CPU.2 — the actual [`SamplerShadow`] march casts a sun shadow through
2189    /// the grid: a wall on a floor, lit by a grazing sun, darkens the floor
2190    /// in the wall's shadow. Total scene luminance with shadows enabled is
2191    /// strictly less than with them off (shadows only ever subtract), and
2192    /// the gap is non-trivial (a real shadow, not FP noise).
2193    #[test]
2194    fn sampler_shadow_march_casts_sun_shadow() {
2195        // Floor at z>=60; a thin wall at x==32 rising from the floor (z 30..60).
2196        let vxl = roxlap_formats::vxl::Vxl::from_dense(64, |x, _y, z| {
2197            if z >= 60 {
2198                Some(VoxColor(0x80_80_80_80)) // floor
2199            } else if x == 32 && (30..60).contains(&z) {
2200                Some(VoxColor(0x80_70_70_70)) // wall (distinct so it's not a dead branch)
2201            } else {
2202                None
2203            }
2204        });
2205        let grid = GridView::from_single_vxl(&vxl);
2206        // Straight-down camera over the floor (voxlap z-down: forward = +z).
2207        let cam = Camera {
2208            pos: [32.0, 32.0, 6.0],
2209            right: [1.0, 0.0, 0.0],
2210            down: [0.0, 1.0, 0.0],
2211            forward: [0.0, 0.0, 1.0],
2212        };
2213        // Sun grazing from +x and above ⇒ the wall shadows the floor at x<32.
2214        let inv = 1.0f32 / 2.0f32.sqrt();
2215        let base = CpuLights {
2216            enabled: true,
2217            sun: true,
2218            sun_dir: [inv, 0.0, -inv],
2219            sun_color: [1.0; 3],
2220            sun_intensity: 1.0,
2221            ambient: [0.25; 3],
2222            shadow_strength: 0.8,
2223            shadow_bias: 1.5,
2224            shadow_max_dist: 128.0,
2225            ..CpuLights::default()
2226        };
2227        let (w, h) = (96u32, 96u32);
2228        let lit_env = DdaEnv {
2229            lights: CpuLights {
2230                sun_casts_shadow: false,
2231                ..base
2232            },
2233            ..DdaEnv::default()
2234        };
2235        let shadow_env = DdaEnv {
2236            lights: CpuLights {
2237                sun_casts_shadow: true,
2238                ..base
2239            },
2240            ..DdaEnv::default()
2241        };
2242        let (fb_lit, _) = render_brickmap_env(grid, &cam, w, h, &lit_env);
2243        let (fb_sh, _) = render_brickmap_env(grid, &cam, w, h, &shadow_env);
2244        let sum: fn(&[u32]) -> u64 = |fb| fb.iter().map(|&p| u64::from(lum(p))).sum();
2245        let lit_sum = sum(&fb_lit);
2246        let sh_sum = sum(&fb_sh);
2247        assert!(
2248            sh_sum < lit_sum,
2249            "the wall's shadow must darken the floor: shadow_sum={sh_sum} lit_sum={lit_sum}",
2250        );
2251        // Non-trivial: at least a few % of the lit total was removed.
2252        assert!(
2253            (lit_sum - sh_sum) * 50 > lit_sum,
2254            "shadow should remove >2% of total luminance: lit={lit_sum} shadow={sh_sum}",
2255        );
2256    }
2257
2258    /// Recording sink: collects `(idx, color, dist)` puts for tests.
2259    #[derive(Default)]
2260    struct Recorder {
2261        puts: Vec<(usize, u32, f32)>,
2262    }
2263    impl PixelSink for Recorder {
2264        fn put(&mut self, idx: usize, color: u32, dist: f32) {
2265            self.puts.push((idx, color, dist));
2266        }
2267    }
2268
2269    fn oracle_camera() -> Camera {
2270        // Identity-basis camera at origin: ray math is integer-exact.
2271        Camera {
2272            pos: [0.0, 0.0, 0.0],
2273            right: [1.0, 0.0, 0.0],
2274            down: [0.0, 0.0, 1.0],
2275            forward: [0.0, 1.0, 0.0],
2276        }
2277    }
2278
2279    /// Render `grid` from `camera` into a `w × h` framebuffer and
2280    /// return the per-pixel hit mask (`true` where a ray hit a voxel).
2281    fn render_mask(grid: GridView<'_>, camera: &Camera, w: u32, h: u32) -> Vec<bool> {
2282        let n = (w as usize) * (h as usize);
2283        let mut fb = vec![0u32; n]; // sky sentinel = 0
2284        let mut zb = vec![f32::INFINITY; n];
2285        let settings = OpticastSettings::for_oracle_framebuffer(w, h);
2286        {
2287            let mut sink = RasterSink::new(&mut fb, &mut zb);
2288            render_dda(
2289                camera,
2290                &settings,
2291                grid,
2292                w as usize,
2293                &DdaEnv::default(),
2294                0,
2295                &mut sink,
2296            );
2297        }
2298        fb.iter().map(|&c| c != 0).collect()
2299    }
2300
2301    /// A silhouette is "row-convex" if every framebuffer row's hit
2302    /// pixels form a single contiguous run (no interior gap). The
2303    /// voxlap silhouette notch is exactly such an interior gap, so this
2304    /// is the headline DDA.1 acceptance check.
2305    fn rows_have_no_holes(mask: &[bool], w: u32, h: u32) -> bool {
2306        let w = w as usize;
2307        for y in 0..h as usize {
2308            let row = &mask[y * w..(y + 1) * w];
2309            let first = row.iter().position(|&b| b);
2310            let last = row.iter().rposition(|&b| b);
2311            if let (Some(f), Some(l)) = (first, last) {
2312                if row[f..=l].iter().any(|&b| !b) {
2313                    return false;
2314                }
2315            }
2316        }
2317        true
2318    }
2319
2320    /// Same contiguity check down each column.
2321    fn cols_have_no_holes(mask: &[bool], w: u32, h: u32) -> bool {
2322        let w = w as usize;
2323        let h = h as usize;
2324        for x in 0..w {
2325            let col: Vec<bool> = (0..h).map(|y| mask[y * w + x]).collect();
2326            let first = col.iter().position(|&b| b);
2327            let last = col.iter().rposition(|&b| b);
2328            if let (Some(f), Some(l)) = (first, last) {
2329                if col[f..=l].iter().any(|&b| !b) {
2330                    return false;
2331                }
2332            }
2333        }
2334        true
2335    }
2336
2337    /// The principal-point pixel `(hx, hy)` looks straight down the
2338    /// forward axis, scaled by `hz`.
2339    #[test]
2340    fn center_pixel_ray_is_forward() {
2341        let settings = OpticastSettings::for_oracle_framebuffer(640, 480);
2342        let cs = camera_math::derive(&oracle_camera(), 640, 480, 320.0, 240.0, 320.0);
2343        // hx = hy = 320 / 240 → use the exact principal point.
2344        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
2345        let (origin, dir) = pixel_ray(&cs, &settings, settings.hx as u32, settings.hy as u32);
2346        assert_eq!(origin, [0.0, 0.0, 0.0]);
2347        // hz·forward = 320·[0,1,0].
2348        assert_eq!(
2349            dir.map(f32::to_bits),
2350            [0.0f32, 320.0, 0.0].map(f32::to_bits)
2351        );
2352    }
2353
2354    /// Pixel `(0, 0)`'s ray equals `camera_math`'s `corn[0]` — proving
2355    /// the DDA renderer samples the same rays the voxlap frustum is
2356    /// built from.
2357    #[test]
2358    fn corner_pixel_ray_matches_camera_corn0() {
2359        let settings = OpticastSettings::for_oracle_framebuffer(640, 480);
2360        let cs = camera_math::derive(&oracle_camera(), 640, 480, 320.0, 240.0, 320.0);
2361        let (_origin, dir) = pixel_ray(&cs, &settings, 0, 0);
2362        assert_eq!(dir.map(f32::to_bits), cs.corn[0].map(f32::to_bits));
2363    }
2364
2365    /// The renderer's independent slab decoder
2366    /// ([`GridView::voxel_color`]) must agree with the reference
2367    /// [`roxlap_formats::vxl::Vxl::voxel_color`] for every cell —
2368    /// including a column with an air gap, which exercises the
2369    /// ceiling-colour-list branch.
2370    #[test]
2371    fn gridview_voxel_color_matches_reference() {
2372        // Two solid runs per column separated by air → ceiling list.
2373        let vxl = roxlap_formats::vxl::Vxl::from_dense(8, |x, _, z| {
2374            let lo = (10..=12).contains(&z);
2375            let hi = (40..=42).contains(&z);
2376            (lo || hi).then_some(VoxColor(0x80_10_20_30 + x))
2377        });
2378        let grid = GridView::from_single_vxl(&vxl);
2379        for x in 0..8 {
2380            for y in 0..8 {
2381                for z in 0..64 {
2382                    assert_eq!(
2383                        grid.voxel_color(x, y, z),
2384                        vxl.voxel_color(x, y, z),
2385                        "mismatch at ({x},{y},{z})"
2386                    );
2387                }
2388            }
2389        }
2390    }
2391
2392    /// An all-air grid produces no hits (every ray misses).
2393    #[test]
2394    fn empty_grid_no_hits() {
2395        let vxl = roxlap_formats::vxl::Vxl::empty(64);
2396        let grid = GridView::from_single_vxl(&vxl);
2397        let settings = OpticastSettings::for_oracle_framebuffer(64, 48);
2398        let mut rec = Recorder::default();
2399        render_dda(
2400            &oracle_camera(),
2401            &settings,
2402            grid,
2403            64,
2404            &DdaEnv::default(),
2405            0,
2406            &mut rec,
2407        );
2408        assert!(rec.puts.is_empty(), "all-air grid must produce no hits");
2409    }
2410
2411    /// Camera above a solid floor, looking straight down: every ray
2412    /// hits, the recovered colour is the floor colour, and the centre
2413    /// pixel's depth ≈ the camera's height above the floor.
2414    #[test]
2415    fn floor_seen_from_above() {
2416        const FLOOR_Z: u32 = 40;
2417        const FLOOR_COL: VoxColor = VoxColor(0x80_30_60_90);
2418        let vxl =
2419            roxlap_formats::vxl::Vxl::from_dense(32, |_, _, z| (z >= FLOOR_Z).then_some(FLOOR_COL));
2420        let grid = GridView::from_single_vxl(&vxl);
2421
2422        // Eye above the floor (z is down), looking down (+z).
2423        let cam = Camera {
2424            pos: [16.0, 16.0, 10.0],
2425            right: [1.0, 0.0, 0.0],
2426            down: [0.0, 1.0, 0.0],
2427            forward: [0.0, 0.0, 1.0],
2428        };
2429        let settings = OpticastSettings::for_oracle_framebuffer(48, 48);
2430        let mut rec = Recorder::default();
2431        render_dda(&cam, &settings, grid, 48, &DdaEnv::default(), 0, &mut rec);
2432
2433        assert!(!rec.puts.is_empty(), "floor must be visible");
2434        // Centre pixel looks straight down → depth ≈ FLOOR_Z - eye_z.
2435        let centre = 24usize * 48 + 24;
2436        let hit = rec
2437            .puts
2438            .iter()
2439            .find(|(idx, _, _)| *idx == centre)
2440            .expect("centre ray must hit the floor");
2441        assert_eq!(hit.1 & 0x00ff_ffff, FLOOR_COL.0 & 0x00ff_ffff);
2442        let expected = (FLOOR_Z as f32) - 10.0;
2443        assert!(
2444            (hit.2 - expected).abs() < 1.5,
2445            "centre depth {} not ≈ {}",
2446            hit.2,
2447            expected
2448        );
2449    }
2450
2451    /// DDA.2: a camera looking at the horizon splits the frame into
2452    /// sky (upward rays miss → no write) and floor (downward rays hit).
2453    /// The top of the frame must be mostly sky, the bottom mostly
2454    /// floor.
2455    #[test]
2456    fn horizon_splits_sky_and_floor() {
2457        const FLOOR_Z: u32 = 40;
2458        let vxl = roxlap_formats::vxl::Vxl::from_dense(64, |_, _, z| {
2459            (z >= FLOOR_Z).then_some(VoxColor(0x80_44_66_88))
2460        });
2461        let grid = GridView::from_single_vxl(&vxl);
2462
2463        // At z=30 (above the z=40 floor), looking +y horizontally,
2464        // down = +z. Upward rays (low py) escape through the box top
2465        // (z=0) → sky; downward rays (high py) strike the floor.
2466        let cam = Camera {
2467            pos: [32.0, 4.0, 30.0],
2468            right: [-1.0, 0.0, 0.0],
2469            down: [0.0, 0.0, 1.0],
2470            forward: [0.0, 1.0, 0.0],
2471        };
2472        let (w, h) = (64u32, 64u32);
2473        let mask = render_mask(grid, &cam, w, h);
2474
2475        let count_band = |y0: usize, y1: usize| -> usize {
2476            (y0 * w as usize..y1 * w as usize)
2477                .filter(|&i| mask[i])
2478                .count()
2479        };
2480        let top = count_band(0, h as usize / 4);
2481        let bottom = count_band(3 * h as usize / 4, h as usize);
2482        assert!(mask.iter().any(|&b| b), "floor must be visible");
2483        assert!(mask.iter().any(|&b| !b), "sky must be visible");
2484        assert!(
2485            bottom > top,
2486            "bottom band ({bottom}) should hit more floor than top band ({top})"
2487        );
2488    }
2489
2490    /// Render `grid` from `camera` with the dense reference cast (no
2491    /// brickmap), returning `(colour, depth)` buffers.
2492    fn render_reference(
2493        grid: GridView<'_>,
2494        camera: &Camera,
2495        w: u32,
2496        h: u32,
2497    ) -> (Vec<u32>, Vec<f32>) {
2498        let n = (w as usize) * (h as usize);
2499        let mut fb = vec![0u32; n];
2500        let mut zb = vec![f32::INFINITY; n];
2501        let settings = OpticastSettings::for_oracle_framebuffer(w, h);
2502        let cs = camera_math::derive(camera, w, h, settings.hx, settings.hy, settings.hz);
2503        for py in 0..h {
2504            for px in 0..w {
2505                let (o, d) = pixel_ray(&cs, &settings, px, py);
2506                if let Some(hit) = cast_ray_reference(o, d, cs.forward, &grid, &settings) {
2507                    let i = (py * w + px) as usize;
2508                    fb[i] = hit.color;
2509                    zb[i] = hit.dist;
2510                }
2511            }
2512        }
2513        (fb, zb)
2514    }
2515
2516    /// Render `grid` from `camera` via the production brickmap path.
2517    fn render_brickmap(
2518        grid: GridView<'_>,
2519        camera: &Camera,
2520        w: u32,
2521        h: u32,
2522    ) -> (Vec<u32>, Vec<f32>) {
2523        render_brickmap_env(grid, camera, w, h, &DdaEnv::default())
2524    }
2525
2526    /// As [`render_brickmap`] but with an explicit [`DdaEnv`] (fog /
2527    /// textured sky / side shades).
2528    fn render_brickmap_env(
2529        grid: GridView<'_>,
2530        camera: &Camera,
2531        w: u32,
2532        h: u32,
2533        env: &DdaEnv<'_>,
2534    ) -> (Vec<u32>, Vec<f32>) {
2535        let n = (w as usize) * (h as usize);
2536        let mut fb = vec![0u32; n];
2537        let mut zb = vec![f32::INFINITY; n];
2538        let settings = OpticastSettings::for_oracle_framebuffer(w, h);
2539        {
2540            let mut sink = RasterSink::new(&mut fb, &mut zb);
2541            render_dda(camera, &settings, grid, w as usize, env, 0, &mut sink);
2542        }
2543        (fb, zb)
2544    }
2545
2546    /// Regression for the cave-demo "bright sky seams" report: the
2547    /// empty-space-skip walk must not leak past an occupied box the ray
2548    /// only grazes at a shared edge/corner. A 1-voxel-thick diagonal
2549    /// wall (`x+y==64`, voxels edge-connected) with air on both sides is
2550    /// the canonical case. The production skip walk must hit exactly the
2551    /// same pixels as the dense per-cell reference — zero divergence.
2552    #[test]
2553    fn no_sky_leak_through_diagonal_wall() {
2554        let vxl = roxlap_formats::vxl::Vxl::from_dense(64, |x, y, z| {
2555            ((x + y == 64) && (2..62).contains(&z)).then_some(VoxColor(0x80_40_80_60))
2556        });
2557        let grid = GridView::from_single_vxl(&vxl);
2558        let (w, h) = (160u32, 160u32);
2559        let c = [10.0, 10.0, 32.0];
2560        let poses = [
2561            Camera::from_yaw_pitch(c, 0.785, 0.0),
2562            Camera::from_yaw_pitch(c, 0.6, 0.1),
2563            Camera::from_yaw_pitch(c, 0.95, -0.1),
2564            Camera::from_yaw_pitch(c, 0.785, 0.3),
2565            Camera::from_yaw_pitch(c, 0.5, 0.0),
2566        ];
2567        for (i, cam) in poses.iter().enumerate() {
2568            let (fb_b, _) = render_brickmap(grid, cam, w, h);
2569            let (fb_r, _) = render_reference(grid, cam, w, h);
2570            let leak = (0..(w * h) as usize)
2571                .filter(|&k| (fb_b[k] != 0) != (fb_r[k] != 0))
2572                .count();
2573            assert_eq!(leak, 0, "pose {i}: {leak} px diverge from dense reference");
2574        }
2575    }
2576
2577    /// TV terrain transparency: a glass-coloured voxel slab in front of an
2578    /// opaque floor. With no terrain material map the glass is an opaque first
2579    /// hit; with the map it becomes translucent and the floor tints through.
2580    #[test]
2581    fn terrain_glass_tints_floor_behind() {
2582        let glass = VoxColor(0x80_40_C0_E0); // cyan
2583        let floor = VoxColor(0x80_C0_40_40); // red
2584        let vxl = roxlap_formats::vxl::Vxl::from_dense(16, |_, _, z| {
2585            if z == 4 {
2586                Some(glass)
2587            } else if z >= 10 {
2588                Some(floor)
2589            } else {
2590                None
2591            }
2592        });
2593        let grid = GridView::from_single_vxl(&vxl);
2594        // Camera above the grid looking straight down (+z), centred.
2595        let cam = Camera {
2596            pos: [8.0, 8.0, 0.0],
2597            right: [1.0, 0.0, 0.0],
2598            down: [0.0, 1.0, 0.0],
2599            forward: [0.0, 0.0, 1.0],
2600        };
2601        let (w, h) = (32u32, 32u32);
2602        let centre = (h / 2 * w + w / 2) as usize;
2603
2604        // Opaque: the glass voxel stops the ray (no terrain materials).
2605        let (fb_op, _) = render_brickmap(grid, &cam, w, h);
2606        assert_eq!(
2607            fb_op[centre] & 0x00ff_ffff,
2608            0x0040_C0E0,
2609            "opaque glass first-hit"
2610        );
2611
2612        // Translucent: glass colour → material 1 (alpha-blend).
2613        let mut table = MaterialTable::new();
2614        table.set(1, Material::alpha_blend(128));
2615        let env = DdaEnv {
2616            materials: Some(&table),
2617            terrain_materials: &[(glass.rgb_part(), 1)],
2618            lights: CpuLights::default(),
2619            ..DdaEnv::default()
2620        };
2621        let (fb_tr, _) = render_brickmap_env(grid, &cam, w, h, &env);
2622        assert_ne!(
2623            fb_tr[centre], fb_op[centre],
2624            "glass should composite over the floor, not stay opaque"
2625        );
2626        let r_op = (fb_op[centre] >> 16) & 0xff; // glass red ≈ 0x40
2627        let r_tr = (fb_tr[centre] >> 16) & 0xff; // + floor red bleeds in
2628        assert!(
2629            r_tr > r_op,
2630            "floor red tints through the glass (op={r_op:02x} tr={r_tr:02x})"
2631        );
2632    }
2633
2634    /// EV.1 — an emissive terrain voxel renders at over-bright albedo,
2635    /// ignoring the baked brightness byte, per-face side shades and the
2636    /// dynamic light rig.
2637    #[test]
2638    fn terrain_emissive_ignores_lighting() {
2639        let crystal = VoxColor(0x40_20_60_80); // deliberately DIM baked byte 0x40
2640        let vxl =
2641            roxlap_formats::vxl::Vxl::from_dense(
2642                16,
2643                |_, _, z| if z >= 4 { Some(crystal) } else { None },
2644            );
2645        let grid = GridView::from_single_vxl(&vxl);
2646        let cam = Camera {
2647            pos: [8.0, 8.0, 0.0],
2648            right: [1.0, 0.0, 0.0],
2649            down: [0.0, 1.0, 0.0],
2650            forward: [0.0, 0.0, 1.0],
2651        };
2652        let (w, h) = (32u32, 32u32);
2653        let centre = (h / 2 * w + w / 2) as usize;
2654
2655        // Control: the baked 0x40 byte halves the albedo.
2656        let (fb_dim, _) = render_brickmap(grid, &cam, w, h);
2657        assert_eq!(
2658            fb_dim[centre] & 0x00ff_ffff,
2659            0x0010_3040,
2660            "baked byte 0x40 = albedo/2"
2661        );
2662
2663        // Emissive: glow(255) ⇒ ×255/128 over-bright, per-channel clamp.
2664        let mut table = MaterialTable::new();
2665        table.set(1, Material::glow(255));
2666        let base = DdaEnv {
2667            materials: Some(&table),
2668            terrain_materials: &[(crystal.rgb_part(), 1)],
2669            ..DdaEnv::default()
2670        };
2671        let (fb_em, _) = render_brickmap_env(grid, &cam, w, h, &base);
2672        assert_eq!(
2673            fb_em[centre] & 0x00ff_ffff,
2674            0x003f_bfff,
2675            "glow(255) ≈ 2× albedo (0x20,0x60,0x80 → 0x3f,0xbf,0xff)"
2676        );
2677
2678        // Max side shades: a normal voxel darkens, an emissive one must not.
2679        let shaded_env = DdaEnv {
2680            side_shades: [64; 6],
2681            ..DdaEnv::default()
2682        };
2683        let (fb_ss_plain, _) = render_brickmap_env(grid, &cam, w, h, &shaded_env);
2684        assert_ne!(
2685            fb_ss_plain[centre], fb_dim[centre],
2686            "control: side shades darken a non-emissive voxel"
2687        );
2688        let em_ss = DdaEnv {
2689            side_shades: [64; 6],
2690            ..base
2691        };
2692        let (fb_em_ss, _) = render_brickmap_env(grid, &cam, w, h, &em_ss);
2693        assert_eq!(
2694            fb_em_ss[centre], fb_em[centre],
2695            "side shades must not touch an emissive voxel"
2696        );
2697
2698        // Dynamic rig active (no sun, zero ambient ⇒ a normal voxel goes
2699        // black): the emissive voxel is rig-independent.
2700        let em_rig = DdaEnv {
2701            lights: CpuLights {
2702                enabled: true,
2703                ..CpuLights::default()
2704            },
2705            ..base
2706        };
2707        let (fb_em_rig, _) = render_brickmap_env(grid, &cam, w, h, &em_rig);
2708        assert_eq!(
2709            fb_em_rig[centre], fb_em[centre],
2710            "the dynamic rig must not touch an emissive voxel"
2711        );
2712    }
2713
2714    /// TV terrain Volumetric: a **filled** grey smoke volume over a red floor.
2715    /// Beer–Lambert opacity grows with the ray's path length, so a deeper smoke
2716    /// column shows more of its own colour (green channel rises toward the
2717    /// smoke grey) — thickness-dependent, unlike per-span AlphaBlend.
2718    #[test]
2719    fn terrain_volumetric_thickness_deepens_opacity() {
2720        let smoke = VoxColor(0x80_90_90_90); // grey
2721        let floor = VoxColor(0x80_C0_20_20); // red (low green)
2722                                             // Centre green channel for a smoke column `depth` voxels deep (filled),
2723                                             // floor at z>=12, camera looking straight down.
2724        let green_at = |depth: u32| -> u32 {
2725            let vxl = roxlap_formats::vxl::Vxl::from_dense(16, |_, _, z| {
2726                if (4..4 + depth).contains(&z) {
2727                    Some(smoke)
2728                } else if z >= 12 {
2729                    Some(floor)
2730                } else {
2731                    None
2732                }
2733            });
2734            let grid = GridView::from_single_vxl(&vxl);
2735            let cam = Camera {
2736                pos: [8.0, 8.0, 0.0],
2737                right: [1.0, 0.0, 0.0],
2738                down: [0.0, 1.0, 0.0],
2739                forward: [0.0, 0.0, 1.0],
2740            };
2741            let (w, h) = (32u32, 32u32);
2742            let mut table = MaterialTable::new();
2743            table.set(1, Material::volumetric(80));
2744            let env = DdaEnv {
2745                materials: Some(&table),
2746                terrain_materials: &[(smoke.rgb_part(), 1)],
2747                lights: CpuLights::default(),
2748                ..DdaEnv::default()
2749            };
2750            let (fb, _) = render_brickmap_env(grid, &cam, w, h, &env);
2751            (fb[(h / 2 * w + w / 2) as usize] >> 8) & 0xff
2752        };
2753        let shallow = green_at(1);
2754        let deep = green_at(7);
2755        assert!(
2756            deep > shallow,
2757            "deeper Volumetric smoke shows more of its grey (deep g={deep:02x} > shallow g={shallow:02x})"
2758        );
2759    }
2760
2761    /// DDA.5: distance fog blends a hit toward the fog colour. A far
2762    /// floor pixel is closer to the fog colour than a near one.
2763    #[test]
2764    fn distance_fog_blends_toward_fog_color() {
2765        let vxl = roxlap_formats::vxl::Vxl::from_dense(64, |_, _, z| {
2766            (z >= 40).then_some(VoxColor(0x80_FF_FF_FF))
2767        });
2768        let grid = GridView::from_single_vxl(&vxl);
2769        let cam = Camera {
2770            pos: [32.0, 2.0, 38.0],
2771            right: [1.0, 0.0, 0.0],
2772            down: [0.0, 0.0, 1.0],
2773            forward: [0.0, 1.0, 0.0],
2774        };
2775        let env = DdaEnv {
2776            sky: None,
2777            fog_color: 0x00_00_00_00, // black fog → distance darkens
2778            fog_max_dist: 64.0,
2779            side_shades: [0; 6],
2780            materials: None,
2781            terrain_materials: &[],
2782            lights: CpuLights::default(),
2783            world_shadow: None,
2784        };
2785        let (w, h) = (64u32, 64u32);
2786        let (fog, _) = render_brickmap_env(grid, &cam, w, h, &env);
2787        let (nofog, zb) = render_brickmap(grid, &cam, w, h);
2788        let (idx, depth) = zb.iter().enumerate().filter(|(_, z)| z.is_finite()).fold(
2789            (0usize, 0.0f32),
2790            |acc, (i, &z)| {
2791                if z > acc.1 {
2792                    (i, z)
2793                } else {
2794                    acc
2795                }
2796            },
2797        );
2798        assert!(depth > 20.0, "need a deep pixel to test fog (got {depth})");
2799        let lum = |c: u32| (c & 0xff) + ((c >> 8) & 0xff) + ((c >> 16) & 0xff);
2800        assert!(
2801            lum(fog[idx]) < lum(nofog[idx]),
2802            "fogged pixel {:08x} not darker than {:08x}",
2803            fog[idx],
2804            nofog[idx]
2805        );
2806    }
2807
2808    /// DDA.5: with a textured sky, miss pixels are filled from the sky
2809    /// panorama (direction-dependent) instead of left at the pre-fill.
2810    #[test]
2811    fn textured_sky_fills_misses() {
2812        let sky = crate::sky::Sky::blue_gradient();
2813        let vxl = roxlap_formats::vxl::Vxl::empty(32); // all air → all miss
2814        let grid = GridView::from_single_vxl(&vxl);
2815        let env = DdaEnv {
2816            sky: Some(&sky),
2817            fog_color: 0,
2818            fog_max_dist: 0.0,
2819            side_shades: [0; 6],
2820            materials: None,
2821            terrain_materials: &[],
2822            lights: CpuLights::default(),
2823            world_shadow: None,
2824        };
2825        let cam = Camera::from_yaw_pitch([16.0, 16.0, 128.0], 0.3, -0.4);
2826        let (w, h) = (48u32, 48u32);
2827        let (fb, _) = render_brickmap_env(grid, &cam, w, h, &env);
2828        assert!(fb.iter().all(|&c| c >> 24 == 0x80), "all misses sky-filled");
2829        let top = fb[0];
2830        let bottom = fb[(h - 1) as usize * w as usize];
2831        assert_ne!(top, bottom, "sky gradient should vary with elevation");
2832    }
2833
2834    /// Sky elevation orientation matches the GPU `sky_color` (acos(-z)/π):
2835    /// looking **up** (−z) samples panorama column 0 (zenith), looking
2836    /// **down** (+z) samples the last column (nadir). Regression for the
2837    /// CPU up/down inversion.
2838    #[test]
2839    fn sky_elevation_zenith_at_column_zero() {
2840        let mut pixels = vec![0i32; 8];
2841        pixels[0] = 0x0011_1111; // zenith marker
2842        pixels[7] = 0x0099_9999; // nadir marker
2843        let sky = crate::sky::Sky::from_pixels(pixels, 8, 1);
2844        let up = sample_sky(&sky, [0.0, 0.0, -1.0]); // −z is up
2845        let down = sample_sky(&sky, [0.0, 0.0, 1.0]); // +z is down
2846        assert_eq!(
2847            up & 0x00ff_ffff,
2848            0x0011_1111,
2849            "looking up → column 0 (zenith)"
2850        );
2851        assert_eq!(
2852            down & 0x00ff_ffff,
2853            0x0099_9999,
2854            "looking down → last column (nadir)"
2855        );
2856    }
2857
2858    /// `render_sky_fill` paints the panorama for a **gridless** view — the
2859    /// same per-pixel sky sample the miss-ray path uses, with no grid present
2860    /// (the CPU empty-scene background, matching the GPU).
2861    #[test]
2862    fn sky_fill_paints_panorama_gridless() {
2863        let sky = crate::sky::Sky::blue_gradient();
2864        let cam = Camera::from_yaw_pitch([0.0, 0.0, 0.0], 0.3, -0.4);
2865        let (w, h) = (48u32, 48u32);
2866        let cs = crate::camera_math::derive(&cam, w, h, 24.0, 24.0, 24.0);
2867        let settings = crate::opticast::OpticastSettings::for_oracle_framebuffer(w, h);
2868        let mut fb = vec![0u32; (w * h) as usize];
2869        // All-background z-buffer (+∞) → every pixel gets the sky.
2870        let zb = vec![f32::INFINITY; (w * h) as usize];
2871        render_sky_fill(&mut fb, &zb, w as usize, w, h, &cs, &settings, &sky);
2872        assert!(
2873            fb.iter().all(|&c| c >> 24 == 0x80),
2874            "every pixel sky-filled with the brightness byte set"
2875        );
2876        let top = fb[0];
2877        let bottom = fb[(h - 1) as usize * w as usize];
2878        assert_ne!(top, bottom, "sky gradient should vary with elevation");
2879        // A finite-z (terrain) pixel is left untouched.
2880        let mut fb2 = vec![0x1234_5678u32; (w * h) as usize];
2881        let mut zb2 = vec![f32::INFINITY; (w * h) as usize];
2882        zb2[0] = 10.0; // pretend a terrain hit at pixel 0
2883        render_sky_fill(&mut fb2, &zb2, w as usize, w, h, &cs, &settings, &sky);
2884        assert_eq!(fb2[0], 0x1234_5678, "finite-z pixel is not overwritten");
2885    }
2886
2887    /// DDA.5: side shading darkens the hit face by its `side_shades`
2888    /// entry. A top-facing floor (ray crosses +z to enter) gets the
2889    /// `z-` face reduction (index 4).
2890    #[test]
2891    fn side_shades_darken_hit_face() {
2892        let vxl = roxlap_formats::vxl::Vxl::from_dense(16, |_, _, z| {
2893            (z >= 8).then_some(VoxColor(0x80_FF_FF_FF))
2894        });
2895        let grid = GridView::from_single_vxl(&vxl);
2896        let cam = Camera {
2897            pos: [8.0, 8.0, 2.0],
2898            right: [1.0, 0.0, 0.0],
2899            down: [0.0, 1.0, 0.0],
2900            forward: [0.0, 0.0, 1.0],
2901        };
2902        let centre = 16 * 32 + 16;
2903        let (plain, _) = render_brickmap(grid, &cam, 32, 32);
2904        let env = DdaEnv {
2905            sky: None,
2906            fog_color: 0,
2907            fog_max_dist: 0.0,
2908            side_shades: [0, 0, 0, 0, 0x40, 0],
2909            materials: None,
2910            terrain_materials: &[],
2911            lights: CpuLights::default(),
2912            world_shadow: None,
2913        };
2914        let (shaded, _) = render_brickmap_env(grid, &cam, 32, 32, &env);
2915        let lum = |c: u32| (c & 0xff) + ((c >> 8) & 0xff) + ((c >> 16) & 0xff);
2916        assert!(
2917            lum(shaded[centre]) < lum(plain[centre]),
2918            "side-shaded face {:08x} not darker than {:08x}",
2919            shaded[centre],
2920            plain[centre]
2921        );
2922    }
2923
2924    /// The two-level brick-skip cast closely approximates the dense
2925    /// per-voxel reference. The outer brick DDA re-seeds the inner cell
2926    /// walk at each occupied brick, so a few silhouette-boundary pixels
2927    /// jitter by one voxel (different hit cell → different colour/depth)
2928    /// — visually invisible, and the gain is ~`BRICK`× fewer air steps.
2929    /// Assert the divergence is tiny: coverage (hit/sky mask) is nearly
2930    /// identical and only a small fraction of pixels differ. (The
2931    /// thread-invariance guarantee is the separate, exact
2932    /// `parallel_matches_sequential`.)
2933    #[test]
2934    fn brickmap_approximates_dense_reference() {
2935        // Rolling heightmap + a floating block (air above and below).
2936        let vxl = roxlap_formats::vxl::Vxl::from_dense(64, |x, y, z| {
2937            let surf = 30 + ((x / 5 + y / 7) % 11);
2938            let ground = z >= surf;
2939            let block = (20..=24).contains(&z) && (10..20).contains(&x) && (40..50).contains(&y);
2940            (ground || block).then_some(VoxColor(0x80_30_50_70 + (x ^ y) % 0x40))
2941        });
2942        let grid = GridView::from_single_vxl(&vxl);
2943
2944        let (w, h) = (80u32, 80u32);
2945        let poses = [
2946            Camera::orbit(0.6, 0.5, 90.0, [32.0, 32.0, 40.0]),
2947            Camera::orbit(2.1, 0.2, 70.0, [32.0, 32.0, 35.0]),
2948            Camera::orbit(-1.0, 0.9, 120.0, [32.0, 32.0, 45.0]),
2949        ];
2950        let n = (w * h) as usize;
2951        for (i, cam) in poses.iter().enumerate() {
2952            let (fb_b, zb_b) = render_brickmap(grid, cam, w, h);
2953            let (fb_r, _zb_r) = render_reference(grid, cam, w, h);
2954            // Coverage (hit vs sky) must match almost exactly.
2955            let cov_b = fb_b.iter().filter(|&&c| c != 0).count();
2956            let cov_r = fb_r.iter().filter(|&&c| c != 0).count();
2957            assert!(cov_b > 200, "pose {i} rendered ~empty (cov {cov_b})");
2958            let cov_diff = cov_b.abs_diff(cov_r);
2959            assert!(
2960                cov_diff * 100 <= n, // < 1 % of pixels flip hit↔sky
2961                "pose {i} coverage diverged: brick {cov_b} vs dense {cov_r}"
2962            );
2963            // Colour diffs (boundary-voxel jitter) must be a small slice.
2964            let diffs = fb_b.iter().zip(&fb_r).filter(|(a, b)| a != b).count();
2965            assert!(
2966                diffs * 100 <= n * 3, // < 3 % of pixels differ
2967                "pose {i} too many pixel diffs vs dense: {diffs}/{n}"
2968            );
2969            // Depth must be sane (finite where hit), not wildly off.
2970            for k in 0..n {
2971                if fb_b[k] != 0 {
2972                    assert!(zb_b[k].is_finite(), "pose {i} px {k} non-finite depth");
2973                }
2974            }
2975        }
2976    }
2977
2978    /// DDA.5: a voxel's baked brightness byte darkens its colour. A
2979    /// half-bright voxel (`a = 0x40`) renders at roughly half RGB; a
2980    /// full-bright one (`a = 0x80`) is unchanged.
2981    #[test]
2982    fn baked_brightness_darkens_color() {
2983        // Half brightness: alpha 0x40 (64/128). White RGB → ~mid grey.
2984        let dim = roxlap_formats::vxl::Vxl::from_dense(16, |_, _, z| {
2985            (z >= 8).then_some(VoxColor(0x40_FF_FF_FF))
2986        });
2987        let grid = GridView::from_single_vxl(&dim);
2988        let cam = Camera {
2989            pos: [8.0, 8.0, 2.0],
2990            right: [1.0, 0.0, 0.0],
2991            down: [0.0, 1.0, 0.0],
2992            forward: [0.0, 0.0, 1.0],
2993        };
2994        let (fb, _) = render_brickmap(grid, &cam, 32, 32);
2995        let centre = 16 * 32 + 16;
2996        // 0xFF * 64 >> 7 = 127 per channel; alpha normalised to 0x80.
2997        assert_eq!(fb[centre], 0x80_7F_7F_7F, "got {:08x}", fb[centre]);
2998
2999        // Full brightness passes RGB through unchanged.
3000        let full = roxlap_formats::vxl::Vxl::from_dense(16, |_, _, z| {
3001            (z >= 8).then_some(VoxColor(0x80_FF_FF_FF))
3002        });
3003        let gridf = GridView::from_single_vxl(&full);
3004        let (fbf, _) = render_brickmap(gridf, &cam, 32, 32);
3005        assert_eq!(fbf[centre], 0x80_FF_FF_FF, "got {:08x}", fbf[centre]);
3006    }
3007
3008    /// DDA.4 headline gate: cross-chunk look-down. A camera in an
3009    /// all-air upper chunk (chz=0) looking straight down must see the
3010    /// floor in the *lower* stacked chunk (chz=1), through the chunk-Z
3011    /// boundary. This is exactly the case the voxlap renderer needed the
3012    /// whole virtual-column stack (S4B.6.j / VC) for; the DDA gets it
3013    /// for free from the outer box spanning `chunks_z`.
3014    #[test]
3015    fn cross_chunk_lookdown_sees_lower_stacked_floor() {
3016        const FLOOR_LOCAL_Z: u32 = 40;
3017        const FLOOR_COL: VoxColor = VoxColor(0x80_22_88_44);
3018        let upper = roxlap_formats::vxl::Vxl::empty(32); // all air + bedrock
3019        let lower = roxlap_formats::vxl::Vxl::from_dense(32, |_, _, z| {
3020            (z >= FLOOR_LOCAL_Z).then_some(FLOOR_COL)
3021        });
3022        let v_up = GridView::from_single_vxl(&upper);
3023        let v_lo = GridView::from_single_vxl(&lower);
3024        // Z-stack: index (dz*chunks_y+dy)*chunks_x+dx → [upper, lower].
3025        let chunks = [Some(v_up), Some(v_lo)];
3026        let cg = crate::ChunkGrid {
3027            chunks: &chunks,
3028            origin_chunk_xy: [0, 0],
3029            origin_chunk_z: 0,
3030            chunks_x: 1,
3031            chunks_y: 1,
3032            chunks_z: 2,
3033        };
3034        let grid = GridView::from_chunk_grid(&cg, 32);
3035
3036        // Camera in the upper chunk (world z=100), looking straight down.
3037        let cam = Camera {
3038            pos: [16.0, 16.0, 100.0],
3039            right: [1.0, 0.0, 0.0],
3040            down: [0.0, 1.0, 0.0],
3041            forward: [0.0, 0.0, 1.0],
3042        };
3043        let (w, h) = (48u32, 48u32);
3044        let (fb, zb) = render_brickmap(grid, &cam, w, h);
3045        let centre = 24 * 48 + 24;
3046        assert!(
3047            fb[centre] & 0x00ff_ffff == FLOOR_COL.0 & 0x00ff_ffff,
3048            "centre ray must reach the lower-chunk floor (got {:08x})",
3049            fb[centre]
3050        );
3051        // Floor world-z = 256 + 40 = 296; camera z = 100 → depth ≈ 196.
3052        let expected = 296.0 - 100.0;
3053        assert!(
3054            (zb[centre] - expected).abs() < 2.0,
3055            "look-down depth {} not ≈ {expected}",
3056            zb[centre]
3057        );
3058    }
3059
3060    /// DDA.4: a floor spanning two side-by-side chunks (chunks_x=2)
3061    /// renders continuously across the chunk-XY seam — hits on both
3062    /// sides, no gap column.
3063    #[test]
3064    fn cross_chunk_xy_floor_is_seamless() {
3065        let mk = || {
3066            roxlap_formats::vxl::Vxl::from_dense(32, |_, _, z| {
3067                (z >= 20).then_some(VoxColor(0x80_50_50_50))
3068            })
3069        };
3070        let (c0, c1) = (mk(), mk());
3071        let v0 = GridView::from_single_vxl(&c0);
3072        let v1 = GridView::from_single_vxl(&c1);
3073        let chunks = [Some(v0), Some(v1)];
3074        let cg = crate::ChunkGrid {
3075            chunks: &chunks,
3076            origin_chunk_xy: [0, 0],
3077            origin_chunk_z: 0,
3078            chunks_x: 2,
3079            chunks_y: 1,
3080            chunks_z: 1,
3081        };
3082        let grid = GridView::from_chunk_grid(&cg, 32);
3083
3084        // High above the seam (x=32), looking straight down.
3085        let cam = Camera {
3086            pos: [32.0, 16.0, 4.0],
3087            right: [1.0, 0.0, 0.0],
3088            down: [0.0, 1.0, 0.0],
3089            forward: [0.0, 0.0, 1.0],
3090        };
3091        let (w, h) = (64u32, 64u32);
3092        let mask = render_mask(grid, &cam, w, h);
3093        // Both the left chunk (screen left) and right chunk (screen
3094        // right) must show floor on the centre row.
3095        let row = (h / 2) as usize * w as usize;
3096        let left = (0..w as usize / 2).filter(|&x| mask[row + x]).count();
3097        let right = (w as usize / 2..w as usize)
3098            .filter(|&x| mask[row + x])
3099            .count();
3100        assert!(
3101            left > 5 && right > 5,
3102            "seam not continuous: left={left} right={right}"
3103        );
3104    }
3105
3106    /// Render `grid` from `camera` at render `mip` and return the hit
3107    /// mask.
3108    fn render_mask_mip(grid: GridView<'_>, camera: &Camera, w: u32, h: u32, mip: u32) -> Vec<bool> {
3109        let n = (w as usize) * (h as usize);
3110        let mut fb = vec![0u32; n];
3111        let mut zb = vec![f32::INFINITY; n];
3112        let settings = OpticastSettings::for_oracle_framebuffer(w, h);
3113        {
3114            let mut sink = RasterSink::new(&mut fb, &mut zb);
3115            render_dda(
3116                camera,
3117                &settings,
3118                grid,
3119                w as usize,
3120                &DdaEnv::default(),
3121                mip,
3122                &mut sink,
3123            );
3124        }
3125        fb.iter().map(|&c| c != 0).collect()
3126    }
3127
3128    /// DDA.6: rendering a mip-built grid at a coarse mip stays complete
3129    /// (hole-free silhouette) with roughly the same screen coverage as
3130    /// mip 0 — LOD coarsens detail, it doesn't punch holes or shrink the
3131    /// shape. (DDA has no axis-aligned mip beam — the artifact is
3132    /// structurally impossible with honest per-cell traversal.)
3133    #[test]
3134    fn mip_render_is_coarse_but_complete() {
3135        let mut vxl = roxlap_formats::vxl::Vxl::from_dense(64, |x, y, z| {
3136            let surf = 24 + ((x / 3 + y / 5) % 17);
3137            (z >= surf).then_some(VoxColor(0x80_50_70_90))
3138        });
3139        vxl.generate_mips(4);
3140        assert!(vxl.mip_count() >= 3, "need mips built for this test");
3141        let grid = GridView::from_single_vxl(&vxl);
3142        let (w, h) = (96u32, 96u32);
3143        let cam = Camera::orbit(0.7, 0.6, 110.0, [32.0, 32.0, 36.0]);
3144
3145        let m0 = render_mask_mip(grid, &cam, w, h, 0);
3146        let m2 = render_mask_mip(grid, &cam, w, h, 2);
3147
3148        let c0 = m0.iter().filter(|&&b| b).count();
3149        let c2 = m2.iter().filter(|&&b| b).count();
3150        assert!(c0 > 200 && c2 > 200, "both mips visible (c0={c0} c2={c2})");
3151        // Coverage within ~30 % — a coarse-mip silhouette closely tracks
3152        // the fine one (LOD coarsens detail, it doesn't lose the shape).
3153        // (Terrain silhouettes are non-convex — sky shows through
3154        // valleys — so a hole-free invariant doesn't apply here; that's
3155        // the convex single-voxel test's job.)
3156        let ratio = c2 as f32 / c0 as f32;
3157        assert!(
3158            (0.7..1.4).contains(&ratio),
3159            "mip-2 coverage {c2} vs mip-0 {c0} (ratio {ratio:.2}) diverged"
3160        );
3161    }
3162
3163    /// Headless perf bench (run: `cargo test -p roxlap-core --release
3164    /// dda::tests::bench_terrain -- --ignored --nocapture`). Single-
3165    /// thread `render_dda` over a hilly chunk at a horizon pose; prints
3166    /// ms/frame + per-frame traversal counters (cells / bricks /
3167    /// surface_color calls) to locate the bottleneck.
3168    #[test]
3169    #[ignore = "perf benchmark — run explicitly with --ignored"]
3170    fn bench_terrain() {
3171        use std::time::Instant;
3172        // Multi-chunk grid like the demo: NC×NC chunks of 128, hills.
3173        const NC: i32 = 6;
3174        let cs = crate::grid_view::CHUNK_SIZE_Z; // 256, but vsid is 128
3175        let _ = cs;
3176        let mut vxls: Vec<roxlap_formats::vxl::Vxl> = Vec::new();
3177        for cy in 0..NC {
3178            for cx in 0..NC {
3179                let (ox, oy) = (cx * 128, cy * 128);
3180                let mut v = roxlap_formats::vxl::Vxl::from_dense(128, |x, y, z| {
3181                    let (gx, gy) = (ox + x as i32, oy + y as i32);
3182                    let surf = 90 + ((gx / 7 + gy / 9).rem_euclid(40)) + ((gx / 23).rem_euclid(20));
3183                    (z as i32 >= surf).then_some(VoxColor(0x80_50_70_90 + (x ^ y) % 0x30))
3184                });
3185                v.generate_mips(4);
3186                vxls.push(v);
3187            }
3188        }
3189        let views: Vec<Option<GridView>> = vxls
3190            .iter()
3191            .map(|v| Some(GridView::from_single_vxl(v)))
3192            .collect();
3193        let cg = crate::ChunkGrid {
3194            chunks: &views,
3195            origin_chunk_xy: [0, 0],
3196            origin_chunk_z: 0,
3197            chunks_x: NC as u32,
3198            chunks_y: NC as u32,
3199            chunks_z: 1,
3200        };
3201        let grid = GridView::from_chunk_grid(&cg, 128);
3202
3203        let (w, h) = (960u32, 600u32);
3204        let mut settings = OpticastSettings::for_oracle_framebuffer(w, h);
3205        settings.max_scan_dist = 512;
3206        let n = (w * h) as usize;
3207        let mut fb = vec![0u32; n];
3208        let mut zb = vec![f32::INFINITY; n];
3209        let centre = [f64::from(NC * 128) / 2.0, f64::from(NC * 128) / 2.0, 60.0];
3210
3211        // Two poses: eye-level toward horizon (long rays) + looking down
3212        // at nearby terrain (short rays, demo-typical).
3213        let poses = [
3214            (
3215                "horizon",
3216                Camera::from_yaw_pitch([20.0, 20.0, 40.0], 0.6, 0.15),
3217            ),
3218            ("down", Camera::orbit(0.7, 1.0, 130.0, centre)),
3219        ];
3220        for (name, cam) in poses {
3221            {
3222                let mut sink = RasterSink::new(&mut fb, &mut zb);
3223                prof::reset();
3224                render_dda(
3225                    &cam,
3226                    &settings,
3227                    grid,
3228                    w as usize,
3229                    &DdaEnv::default(),
3230                    0,
3231                    &mut sink,
3232                );
3233            }
3234            let (cells, bricks, surf) = prof::read();
3235            let iters = 6;
3236            let t0 = Instant::now();
3237            for _ in 0..iters {
3238                let mut sink = RasterSink::new(&mut fb, &mut zb);
3239                render_dda(
3240                    &cam,
3241                    &settings,
3242                    grid,
3243                    w as usize,
3244                    &DdaEnv::default(),
3245                    0,
3246                    &mut sink,
3247                );
3248            }
3249            let ms = t0.elapsed().as_secs_f64() * 1000.0 / f64::from(iters);
3250            let hits = fb.iter().filter(|&&c| c != 0).count();
3251            eprintln!(
3252                "[{name}] {w}x{h} 1-thread: {ms:.1} ms | hits={hits}/{n} | per-px: cells={:.1} bricks={:.1} surf={:.1}",
3253                cells as f64 / n as f64,
3254                bricks as f64 / n as f64,
3255                surf as f64 / n as f64,
3256            );
3257        }
3258    }
3259
3260    /// DDA.7: the tile-parallel driver is bit-identical to the
3261    /// sequential one — DDA pixels are independent, so banding can't
3262    /// change a pixel.
3263    #[test]
3264    fn parallel_matches_sequential() {
3265        let vxl = roxlap_formats::vxl::Vxl::from_dense(64, |x, y, z| {
3266            let surf = 28 + ((x / 4 + y / 6) % 13);
3267            (z >= surf).then_some(VoxColor(0x80_40_60_80 + (x ^ y) % 0x30))
3268        });
3269        let grid = GridView::from_single_vxl(&vxl);
3270        let (w, h) = (96u32, 96u32);
3271        let cam = Camera::orbit(0.8, 0.55, 100.0, [32.0, 32.0, 40.0]);
3272        let env = DdaEnv {
3273            sky: None,
3274            fog_color: 0x00_20_30_40,
3275            fog_max_dist: 120.0,
3276            side_shades: [0, 0, 0, 0, 0x30, 0x10],
3277            materials: None,
3278            terrain_materials: &[],
3279            lights: CpuLights::default(),
3280            world_shadow: None,
3281        };
3282
3283        let (seq_fb, seq_zb) = render_brickmap_env(grid, &cam, w, h, &env);
3284
3285        let n = (w * h) as usize;
3286        let mut par_fb = vec![0u32; n];
3287        let mut par_zb = vec![f32::INFINITY; n];
3288        let settings = OpticastSettings::for_oracle_framebuffer(w, h);
3289        let (cache, mip) = local_cache(&grid, 0);
3290        render_dda_parallel(
3291            &cam,
3292            &settings,
3293            grid,
3294            &mut par_fb,
3295            &mut par_zb,
3296            w as usize,
3297            &env,
3298            &cache,
3299            mip,
3300        );
3301        assert!(par_fb == seq_fb, "parallel colour differs from sequential");
3302        assert!(
3303            par_zb
3304                .iter()
3305                .zip(&seq_zb)
3306                .all(|(a, b)| a.to_bits() == b.to_bits()),
3307            "parallel depth differs from sequential"
3308        );
3309    }
3310
3311    /// DDA.2 correctness: a heightmap column's interior is solid even
3312    /// though voxlap only stores a colour for its surface. `voxel_color`
3313    /// returns `None` for an interior voxel, but `surface_color` must
3314    /// return the run's surface colour — otherwise oblique rays striking
3315    /// a cliff *side* would pass straight through (see-through terrain).
3316    #[test]
3317    fn cliff_side_is_solid_not_see_through() {
3318        const TOP_Z: u32 = 50;
3319        const COL: VoxColor = VoxColor(0x80_77_88_99);
3320        let vxl = roxlap_formats::vxl::Vxl::from_dense(8, |_, _, z| (z >= TOP_Z).then_some(COL));
3321        let grid = GridView::from_single_vxl(&vxl);
3322
3323        // Surface voxel: coloured directly.
3324        assert_eq!(grid.voxel_color(4, 4, TOP_Z), Some(COL));
3325        // Interior voxel: voxlap stores no colour …
3326        assert_eq!(grid.voxel_color(4, 4, 150), None);
3327        // … but it is solid, and surface_color bleeds the run-top colour
3328        // down the cliff face → a real hit, not see-through.
3329        assert_eq!(grid.surface_color(4, 4, 150), Some(COL));
3330        // Bedrock-style air above the surface stays air.
3331        assert_eq!(grid.surface_color(4, 4, 10), None);
3332    }
3333
3334    /// DDA.2: a camera embedded in solid material hits its own voxel
3335    /// immediately — every ray reports a hit (no skip / no garbage).
3336    #[test]
3337    fn camera_inside_solid_hits_everywhere() {
3338        let vxl = roxlap_formats::vxl::Vxl::from_dense(16, |_, _, _| Some(VoxColor(0x80_55_55_55)));
3339        let grid = GridView::from_single_vxl(&vxl);
3340        let cam = Camera {
3341            pos: [8.0, 8.0, 128.0],
3342            right: [1.0, 0.0, 0.0],
3343            down: [0.0, 1.0, 0.0],
3344            forward: [0.0, 0.0, 1.0],
3345        };
3346        let (w, h) = (32u32, 32u32);
3347        let mask = render_mask(grid, &cam, w, h);
3348        assert!(
3349            mask.iter().all(|&b| b),
3350            "every ray must hit when the camera is inside solid"
3351        );
3352    }
3353
3354    /// Headline DDA.1 gate: a single solid voxel viewed obliquely
3355    /// projects to a convex silhouette with **no interior holes** —
3356    /// the artifact class (`tiny_grid_1x1x1` silhouette notch) the
3357    /// voxlap renderer cannot avoid. DDA casts independent per-pixel
3358    /// rays, so the silhouette is hole-free by construction.
3359    #[test]
3360    fn single_voxel_silhouette_has_no_notch() {
3361        const C: VoxColor = VoxColor(0x80_FF_80_40);
3362        let vxl = roxlap_formats::vxl::Vxl::from_dense(16, |x, y, z| {
3363            (x == 8 && y == 8 && z == 8).then_some(C)
3364        });
3365        let grid = GridView::from_single_vxl(&vxl);
3366
3367        // Orbit the voxel centre obliquely so all three faces show and
3368        // the silhouette is a sizeable hexagon (dist 4 → ~12 px wide).
3369        let cam = Camera::orbit(0.7, 0.6, 4.0, [8.5, 8.5, 8.5]);
3370        let (w, h) = (96u32, 96u32);
3371        let mask = render_mask(grid, &cam, w, h);
3372
3373        let hits = mask.iter().filter(|&&b| b).count();
3374        assert!(
3375            hits > 30,
3376            "silhouette too small to be meaningful: {hits} px"
3377        );
3378        assert!(
3379            rows_have_no_holes(&mask, w, h),
3380            "row-interior gap in single-voxel silhouette (notch)"
3381        );
3382        assert!(
3383            cols_have_no_holes(&mask, w, h),
3384            "column-interior gap in single-voxel silhouette (notch)"
3385        );
3386    }
3387}