Skip to main content

roxlap_scene/
billboard.rs

1//! Billboard impostor cache — S6.2 of `PORTING-SCENE.md` § S6.
2//!
3//! At `Lod::Far` distance the per-grid rasterizer is too expensive
4//! and produces sub-pixel detail no one will ever see. The
5//! billboard cache replaces it with N pre-rendered orthographic-ish
6//! snapshots from canonical viewpoints arranged on a sphere; the
7//! S6.3 blit path picks the snapshot whose direction most closely
8//! matches the current camera and stamps it into the framebuffer
9//! as a screen-aligned quad with per-pixel depth.
10//!
11//! S6.2 lands the cache infrastructure ONLY — types + viewpoint
12//! generation + lazy population API + edit-time invalidation. The
13//! blit path (consuming the snapshots) is S6.3.
14//!
15//! ## Viewpoint set
16//!
17//! [`canonical_viewpoints`] returns 26 unit vectors covering the
18//! sphere octants:
19//!
20//! - **6 face viewpoints**: `±x`, `±y`, `±z` — axis-aligned.
21//! - **12 edge viewpoints**: e.g. `(1, 1, 0) / √2` — between two
22//!   adjacent faces.
23//! - **8 corner viewpoints**: `(1, 1, 1) / √3` — diagonal.
24//!
25//! The set is hand-tuned to PORTING-SCENE.md § S6's "26 is a
26//! reasonable starting point" recommendation; can grow to a
27//! denser Fibonacci sphere later if angular gaps prove visible.
28//!
29//! ## Snapshot camera
30//!
31//! For each unit viewpoint `v`, the snapshot camera lives in
32//! **grid-local space** at:
33//! ```text
34//! pos     = grid_center_local + v * D
35//! forward = -v
36//! ```
37//! where `D = 8 * bounding_radius` (well past the Far threshold).
38//! The basis right / down is constructed via Gram-Schmidt from an
39//! arbitrary "up reference" — `(0, 0, 1)` unless the viewpoint is
40//! near-parallel, in which case `(1, 0, 0)`. Final basis satisfies
41//! voxlap's right-handed convention `right × down == forward`.
42//!
43//! The projection is perspective with a large focal length so it
44//! approximates orthographic: `hz = N * D / (2 * R)`. At `D = 8R`
45//! this is `hz = 4N` — a very narrow FOV, rays diverge by at most
46//! `atan(1/8) ≈ 7°` across the framebuffer, which is "ortho
47//! enough" for impostor purposes.
48//!
49//! S6.2's `mip_levels = 1` keeps the snapshot rendering simple.
50//! Multi-mip and bigger resolutions are a S6.4 polish concern.
51
52use glam::{DVec3, IVec3};
53use roxlap_core::dda::{render_dda, DdaEnv, RasterSink};
54use roxlap_core::opticast::OpticastSettings;
55use roxlap_core::Camera;
56
57use crate::{Grid, CHUNK_SIZE_XY, CHUNK_SIZE_Z};
58
59/// Per-grid bounding metadata in grid-local space — computed once
60/// per render dispatch by `grid_local_centre_and_radius`.
61/// Exposed so S6.3's `render_scene_composed` Far arm can share the
62/// centre/radius pair across the cache lookup AND the blit
63/// projection without recomputing.
64#[derive(Debug, Clone, Copy)]
65pub struct GridLocalBounds {
66    /// Grid-local centre of the populated-chunk bounding box.
67    pub centre: DVec3,
68    /// Bounding-sphere radius around `centre` (grid-local units).
69    pub radius: f64,
70}
71
72/// See `super::grid_local_centre_and_radius` for the internal
73/// version. The pub re-export keeps render.rs out of the
74/// internal-helper namespace.
75#[must_use]
76pub fn grid_bounds(grid: &Grid) -> GridLocalBounds {
77    let (centre, radius) = grid_local_centre_and_radius(grid);
78    GridLocalBounds { centre, radius }
79}
80
81/// Distance multiple of `bounding_radius` at which the snapshot
82/// camera is placed. 8× is "narrow enough FOV to look orthographic
83/// without busting numerical precision". Documented above; not a
84/// runtime knob in S6.2 (S6.4 polish can expose it).
85const CAMERA_DISTANCE_FACTOR: f64 = 8.0;
86
87/// Default per-snapshot framebuffer resolution. 128 × 128 keeps
88/// memory budget per grid at `26 × 128² × (4 colour + 4 depth) =
89/// ~3.4 MB` — acceptable for a handful of ships in a scene.
90/// Configurable via `BillboardCache::with_resolution`.
91pub const DEFAULT_RESOLUTION: u32 = 128;
92
93/// Sentinel colour stamped into a snapshot's framebuffer wherever
94/// opticast would have drawn sky. The S6.3 blit detects sentinel
95/// pixels and skips them so the snapshot's sky shows through to
96/// whatever else is in the shared `(fb, zb)` (sky panorama, ground
97/// from another grid, etc.).
98///
99/// Picked as `0x00_00_00_00` because:
100/// - Alpha byte `0x00` is unused by voxlap's lit-voxel path
101///   (`set_side_shades` produces values in `[0x40, 0x80]`), so a
102///   real hit never accidentally collides with the sentinel.
103/// - All-zero is trivially fast to check and to bulk-fill.
104pub const SKY_SENTINEL: u32 = 0x00_00_00_00;
105
106/// One pre-rendered orthographic-ish view of a grid from a fixed
107/// direction. The depth buffer carries grid-local Euclidean
108/// distance (voxlap's z-buffer convention: smaller = closer); S6.3
109/// uses it to z-compose the billboard with other grids' rendered
110/// pixels.
111#[derive(Debug, Clone)]
112pub struct BillboardSnapshot {
113    /// Unit vector from the grid centre TO the viewpoint, in
114    /// grid-local space. The snapshot camera was at
115    /// `centre + view_dir * D` looking back.
116    pub view_dir: DVec3,
117    /// Snapshot framebuffer width and height in pixels (square in
118    /// S6.2 but the struct supports rectangular for future work).
119    pub width: u32,
120    /// See [`Self::width`].
121    pub height: u32,
122    /// RGBA framebuffer. Sky pixels carry the build's `sky_color`.
123    pub color: Vec<u32>,
124    /// Per-pixel grid-local distance (voxlap's z-buffer convention:
125    /// smaller = closer). Sky pixels carry [`f32::INFINITY`].
126    pub depth: Vec<f32>,
127}
128
129/// Per-grid lazy cache of 26 [`BillboardSnapshot`]s indexed by the
130/// 26 [`canonical_viewpoints`] directions.
131///
132/// Construction modes:
133/// - [`Self::new_empty`]: allocate an empty cache, populate later
134///   via [`Self::build`].
135/// - [`Self::build`]: render all 26 snapshots in one call. Use this
136///   from the render-time lazy path: when a grid first lands on
137///   `Lod::Far`, the S6.3 dispatch checks
138///   [`Grid::billboards`]; if `None`, calls `build` and stores.
139#[derive(Debug, Clone)]
140pub struct BillboardCache {
141    /// Snapshot resolution in pixels (square). Pinned at build
142    /// time; rebuilds construct a fresh `BillboardCache` rather
143    /// than resizing in place.
144    pub resolution: u32,
145    /// 26 snapshots, indexed in the same order as
146    /// [`canonical_viewpoints`]. Empty (`Vec::new`) iff this cache
147    /// is uninitialised.
148    pub snapshots: Vec<BillboardSnapshot>,
149}
150
151impl BillboardCache {
152    /// Allocate an empty cache. `snapshots` is empty; future
153    /// [`Self::build`] populates it. Cheap — no allocations beyond
154    /// the empty `Vec` header.
155    #[must_use]
156    pub fn new_empty(resolution: u32) -> Self {
157        Self {
158            resolution,
159            snapshots: Vec::new(),
160        }
161    }
162
163    /// Number of snapshots populated. `0` for an empty cache,
164    /// `26` after [`Self::build`].
165    #[must_use]
166    pub fn len(&self) -> usize {
167        self.snapshots.len()
168    }
169
170    /// `true` iff this cache has not yet been populated (no
171    /// snapshots stored).
172    #[must_use]
173    pub fn is_empty(&self) -> bool {
174        self.snapshots.is_empty()
175    }
176
177    /// Render all 26 viewpoint snapshots of `grid` into a fresh
178    /// cache.
179    ///
180    /// Cost: `O(26 × resolution² × grid_render_cost)`. For
181    /// `resolution = 128` and a small ship grid this is roughly
182    /// equivalent to a single full-frame render. Intended to be
183    /// called once per grid-edit cycle (caches are invalidated on
184    /// edits via [`Grid::set_voxel`] et al.).
185    ///
186    /// An empty grid (no populated chunks) yields 26 all-sky
187    /// snapshots. The cache is still populated so the S6.3 blit
188    /// path doesn't keep retrying — a Far-tier empty grid's blit
189    /// is then a no-op (every pixel skipped via [`SKY_SENTINEL`]).
190    ///
191    /// **Sky-pixel detection**: the pool's skycast colour is set
192    /// to [`SKY_SENTINEL`] before each snapshot render so opticast
193    /// writes the sentinel (not a real sky colour) into pixels
194    /// rays missed. Post-render, every sentinel pixel's depth is
195    /// reset to [`f32::INFINITY`] (opticast writes a finite "sky
196    /// distance" for these pixels, which would otherwise leak
197    /// through the blit's depth check).
198    #[must_use]
199    pub fn build(grid: &Grid, resolution: u32) -> Self {
200        let viewpoints = canonical_viewpoints();
201        let mut snapshots = Vec::with_capacity(viewpoints.len());
202
203        // Grid centre + bounding radius in grid-local space.
204        let (centre, radius) = grid_local_centre_and_radius(grid);
205        // Camera distance + ray budget. `R_floor` prevents
206        // degenerate budgets for empty grids.
207        let r = radius.max(1.0);
208        let d = CAMERA_DISTANCE_FACTOR * r;
209        // Scan budget covers camera-to-far-side + a little slack
210        // for foreshortened rays past the centre.
211        let max_scan_dist = ((d + r) * 1.25).ceil().max(64.0) as i32;
212
213        for view_dir in viewpoints {
214            let camera = snapshot_camera(view_dir, centre, d);
215            let mut color = vec![SKY_SENTINEL; (resolution as usize) * (resolution as usize)];
216            let mut depth = vec![f32::INFINITY; color.len()];
217
218            // Empty grid → render all-sky and move on (no chunks
219            // means `chunk_xyz_backing` returns None).
220            if let Some(backing) = grid.chunk_xyz_backing() {
221                let cg = roxlap_core::ChunkGrid {
222                    chunks: &backing.chunks,
223                    origin_chunk_xy: backing.origin_chunk_xy,
224                    origin_chunk_z: backing.origin_chunk_z,
225                    chunks_x: backing.chunks_x,
226                    chunks_y: backing.chunks_y,
227                    chunks_z: backing.chunks_z,
228                };
229                let grid_view = roxlap_core::GridView::from_chunk_grid(&cg, CHUNK_SIZE_XY);
230                let settings = snapshot_settings(resolution, d, r, max_scan_dist);
231                // DDA render: no textured sky (`DdaEnv::default`), so a
232                // miss leaves the `SKY_SENTINEL` prefill untouched — the
233                // blit detects impostor sky by that sentinel. Impostors
234                // are unfogged. `render_dda` builds its own per-call brick
235                // cache covering all populated chunks.
236                let mut sink = RasterSink::new(&mut color, &mut depth);
237                render_dda(
238                    &camera,
239                    &settings,
240                    grid_view,
241                    resolution as usize,
242                    &DdaEnv::default(),
243                    0,
244                    &mut sink,
245                );
246            }
247
248            // Sentinel post-process: the prefill already left sky pixels
249            // at `SKY_SENTINEL` / `INFINITY`; DDA misses don't touch them,
250            // so depths are already `INFINITY`. This keeps the blit's
251            // `is_infinite()` belt-and-braces check consistent if a future
252            // change ever writes a finite sky depth.
253            for (px, z) in color.iter().zip(depth.iter_mut()) {
254                if *px == SKY_SENTINEL {
255                    *z = f32::INFINITY;
256                }
257            }
258
259            snapshots.push(BillboardSnapshot {
260                view_dir,
261                width: resolution,
262                height: resolution,
263                color,
264                depth,
265            });
266        }
267
268        Self {
269            resolution,
270            snapshots,
271        }
272    }
273
274    /// Pick the snapshot whose `view_dir` is closest to `query`
275    /// (largest dot product). Returns `None` iff the cache is
276    /// empty.
277    ///
278    /// `query` is the unit vector from the grid centre to the
279    /// current camera position in grid-local space — the same
280    /// frame the snapshot `view_dir`s live in. Caller is
281    /// responsible for normalisation.
282    ///
283    /// Tie-breaking is "first in viewpoint order"; with the 26
284    /// canonical viewpoints, ties only happen for query directions
285    /// exactly equidistant between two viewpoints, which is a
286    /// measure-zero set under f64.
287    #[must_use]
288    pub fn pick_nearest(&self, query: DVec3) -> Option<&BillboardSnapshot> {
289        if self.snapshots.is_empty() {
290            return None;
291        }
292        let mut best_idx = 0usize;
293        let mut best_dot = self.snapshots[0].view_dir.dot(query);
294        for (i, snap) in self.snapshots.iter().enumerate().skip(1) {
295            let d = snap.view_dir.dot(query);
296            if d > best_dot {
297                best_dot = d;
298                best_idx = i;
299            }
300        }
301        Some(&self.snapshots[best_idx])
302    }
303}
304
305/// 26 unit vectors covering the cube's face / edge / corner
306/// directions on the unit sphere.
307///
308/// Order is stable: 6 face → 12 edge → 8 corner. Indices are
309/// implementation details — call [`BillboardCache::pick_nearest`]
310/// for the query-driven lookup rather than indexing directly.
311///
312/// All vectors are unit length to within f64 precision (face
313/// vectors are exact; edge / corner vectors come from
314/// `normalize()` so they carry the platform's sqrt rounding —
315/// typically 1 ULP).
316#[must_use]
317pub fn canonical_viewpoints() -> Vec<DVec3> {
318    let mut out = Vec::with_capacity(26);
319
320    // 6 face directions — axis-aligned, exact unit length.
321    for &axis in &[
322        DVec3::X,
323        DVec3::NEG_X,
324        DVec3::Y,
325        DVec3::NEG_Y,
326        DVec3::Z,
327        DVec3::NEG_Z,
328    ] {
329        out.push(axis);
330    }
331
332    // 12 edge directions — (±1, ±1, 0), (±1, 0, ±1), (0, ±1, ±1)
333    // normalised to unit length (1/√2 in each non-zero component).
334    let signs = [-1.0_f64, 1.0_f64];
335    for &sa in &signs {
336        for &sb in &signs {
337            out.push(DVec3::new(sa, sb, 0.0).normalize());
338            out.push(DVec3::new(sa, 0.0, sb).normalize());
339            out.push(DVec3::new(0.0, sa, sb).normalize());
340        }
341    }
342
343    // 8 corner directions — (±1, ±1, ±1) normalised (1/√3 each).
344    for &sx in &signs {
345        for &sy in &signs {
346            for &sz in &signs {
347                out.push(DVec3::new(sx, sy, sz).normalize());
348            }
349        }
350    }
351
352    debug_assert_eq!(out.len(), 26);
353    out
354}
355
356/// Grid centre + bounding-sphere radius, in grid-local voxel
357/// coordinates. The centre is the AABB midpoint of the populated
358/// chunks (NOT the bounding-sphere centre, which would require a
359/// Welzl pass and isn't worth it for 26 fixed viewpoints).
360///
361/// Empty grid → centre is `(0, 0, 0)` and radius `0.0`. The
362/// snapshot camera still renders to all-sky in this case (no
363/// chunks → opticast skips the dispatch).
364fn grid_local_centre_and_radius(grid: &Grid) -> (DVec3, f64) {
365    if grid.chunks.is_empty() {
366        return (DVec3::ZERO, 0.0);
367    }
368    let mut lo = IVec3::splat(i32::MAX);
369    let mut hi = IVec3::splat(i32::MIN);
370    for &idx in grid.chunks.keys() {
371        lo = lo.min(idx);
372        hi = hi.max(idx);
373    }
374    let sx = f64::from(CHUNK_SIZE_XY);
375    let sz = f64::from(CHUNK_SIZE_Z);
376    let lo_v = DVec3::new(
377        f64::from(lo.x) * sx,
378        f64::from(lo.y) * sx,
379        f64::from(lo.z) * sz,
380    );
381    let hi_v = DVec3::new(
382        f64::from(hi.x + 1) * sx,
383        f64::from(hi.y + 1) * sx,
384        f64::from(hi.z + 1) * sz,
385    );
386    let centre = (lo_v + hi_v) * 0.5;
387    let half_extent = (hi_v - lo_v) * 0.5;
388    let radius = half_extent.length();
389    (centre, radius)
390}
391
392/// Build the snapshot camera for one viewpoint.
393///
394/// Positions the camera at `centre + view_dir * d` in grid-local
395/// space, looking back at the grid centre with a right-handed
396/// basis (`right × down == forward` per voxlap convention).
397fn snapshot_camera(view_dir: DVec3, centre: DVec3, d: f64) -> Camera {
398    let pos = centre + view_dir * d;
399    let forward = -view_dir;
400    // Pick an "up reference" not parallel to forward.
401    //
402    // Voxlap is z-down (positive Z = downward in world space), so
403    // the world's "up" direction is **negative** Z. Using
404    // `DVec3::NEG_Z` here gives `down = forward × right` that
405    // points toward voxlap's +Z (= screen down) — i.e. the
406    // snapshot is rendered right-side-up.
407    //
408    // Pre-2026-05-28 bug: this was `DVec3::Z`, producing
409    // `down = (0,0,-1)` for face viewpoints. The rasterizer
410    // rendered each snapshot upside-down; the blit then stamped
411    // the inverted image at the projected grid centre, making
412    // pillars appear at the wrong vertical position (visually:
413    // "billboards are taller than the voxel model").
414    //
415    // Falls back to +X when the viewpoint is near-±Z (forward
416    // nearly parallel to the up reference).
417    let up_ref = if forward.z.abs() < 0.99 {
418        DVec3::NEG_Z
419    } else {
420        DVec3::X
421    };
422    let right = forward.cross(up_ref).normalize();
423    // down = forward × right gives right × down == forward (voxlap
424    // RH convention). Verified by cross-product handedness.
425    let down = forward.cross(right);
426    Camera {
427        pos: pos.to_array(),
428        right: right.to_array(),
429        down: down.to_array(),
430        forward: forward.to_array(),
431    }
432}
433
434/// Build the [`OpticastSettings`] for one snapshot render.
435///
436/// `mip_levels = 1` keeps mip-0 only — the snapshot resolution is
437/// already coarse, deep mips would over-blur. `mip_scan_dist` is
438/// the floor (4). `max_scan_dist` is sized to cover camera-to-
439/// far-side of the grid plus a 25 % slack for foreshortened rays
440/// past the centre.
441///
442/// Projection: orthographic-ish perspective with `hz = N * D /
443/// (2 * R)`. The image scale at the grid centre lands the
444/// bounding sphere exactly at the framebuffer edges; rays
445/// diverge by `atan(R/D)` across the framebuffer (~7° at the
446/// default `D = 8R`).
447fn snapshot_settings(resolution: u32, d: f64, r: f64, max_scan_dist: i32) -> OpticastSettings {
448    let n = f64::from(resolution);
449    let half_n = (n * 0.5) as f32;
450    // hz = (N * D) / (2 * R). For D = 8R this is 4N — narrow FOV,
451    // near-orthographic. f64 → f32 cast: f32 mantissa handles
452    // values up to ~16M, comfortably above realistic 4N for the
453    // 128×128 default.
454    #[allow(clippy::cast_possible_truncation)]
455    let hz = ((n * d) / (2.0 * r)) as f32;
456    OpticastSettings {
457        xres: resolution,
458        yres: resolution,
459        y_start: 0,
460        y_end: resolution,
461        x_start: 0,
462        x_end: resolution,
463        hx: half_n,
464        hy: half_n,
465        hz,
466        anginc: 1.0,
467        mip_levels: 1,
468        mip_scan_dist: 4,
469        max_scan_dist,
470    }
471}
472
473/// Blit one [`BillboardSnapshot`] into a `(fb, zb)` pair as a
474/// camera-aligned 2D quad — the S6.3 Far-tier render path.
475///
476/// Projection:
477/// - The grid's world centre projects to a screen pixel via the
478///   runtime camera's basis + `settings.{hx, hy, hz}`. If the
479///   centre is at or behind the camera (`depth <= 0`), this is a
480///   no-op.
481/// - The grid's bounding sphere (`radius` in grid-local voxel
482///   units, identical to world units because rotations preserve
483///   distance) projects to a screen-pixel half-extent
484///   `pixel_radius = radius * hz / depth`. The blit covers the
485///   square `[cx - pixel_radius, cx + pixel_radius]² ×
486///   [cy - pixel_radius, cy + pixel_radius]` around the projected
487///   centre.
488/// - Source-to-destination sampling is nearest-neighbour. The
489///   snapshot's resolution is fixed at build time; under-sampling
490///   when far away (snapshot_pixels >> screen_pixels) is fine for
491///   impostors. Over-sampling when close (screen_pixels >>
492///   snapshot_pixels) causes blocky scaling but Far tier is by
493///   definition past the radius-based threshold so screen_pixels
494///   should stay modest.
495///
496/// Depth: every non-sky destination pixel gets the same `z` value
497/// — the camera-to-grid-centre distance. This treats the impostor
498/// as a flat disk at the grid centre. Adequate for S6.3 minimum-
499/// viable; S6.4 polish can use per-pixel depth from
500/// `snapshot.depth` to recover internal shape.
501///
502/// Sky pixels: detected via `snapshot.depth[..].is_infinite()`.
503/// Skipped entirely (the destination pixel + zbuffer are
504/// untouched), so the underlying sky / other grids show through.
505///
506/// Compose: min-z merge against the existing `zb`. Closer-than-
507/// existing wins. Sky pixels in the snapshot don't even attempt
508/// the merge, so distant grids never wipe out a near grid's
509/// rendered pixel.
510#[allow(clippy::too_many_arguments)]
511pub fn billboard_blit_into(
512    fb: &mut [u32],
513    zb: &mut [f32],
514    pitch_pixels: usize,
515    width: u32,
516    height: u32,
517    snapshot: &BillboardSnapshot,
518    grid_world_centre: DVec3,
519    grid_world_radius: f64,
520    camera: &Camera,
521    settings: &OpticastSettings,
522) {
523    // Camera basis in world space.
524    let cam_pos = DVec3::from_array(camera.pos);
525    let forward = DVec3::from_array(camera.forward);
526    let right = DVec3::from_array(camera.right);
527    let down = DVec3::from_array(camera.down);
528    // Vector from camera to grid centre.
529    let to_centre = grid_world_centre - cam_pos;
530    // Depth along the camera forward axis. Negative = behind
531    // camera; skip (the perspective project would invert sign).
532    let depth = to_centre.dot(forward);
533    if depth <= 0.0 || !depth.is_finite() {
534        return;
535    }
536    // Off-axis offsets along right / down.
537    let x_off = to_centre.dot(right);
538    let y_off = to_centre.dot(down);
539    // Perspective scale factor at the grid centre's depth.
540    let scale = f64::from(settings.hz) / depth;
541    let cx = f64::from(settings.hx) + x_off * scale;
542    let cy = f64::from(settings.hy) + y_off * scale;
543    // Half-extent of the impostor quad in destination pixels.
544    let pixel_radius_f = grid_world_radius * scale;
545    if !pixel_radius_f.is_finite() || pixel_radius_f < 1.0 {
546        // Sub-pixel impostor — invisible at this resolution.
547        return;
548    }
549    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
550    let pixel_radius = pixel_radius_f.ceil() as i32;
551    let dst_size = pixel_radius * 2;
552    if dst_size <= 0 {
553        return;
554    }
555    // Source dims.
556    let src_w = snapshot.width as i32;
557    let src_h = snapshot.height as i32;
558    if src_w <= 0 || src_h <= 0 {
559        return;
560    }
561    // Quad's top-left destination corner. Clamped to screen at
562    // sampling time so partially-off-screen quads still render
563    // their visible portion.
564    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
565    let dst_left = (cx - pixel_radius_f) as i32;
566    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
567    let dst_top = (cy - pixel_radius_f) as i32;
568    // Z value used for every non-sky billboard pixel.
569    #[allow(clippy::cast_possible_truncation)]
570    let z = depth as f32;
571
572    let w_i = width as i32;
573    let h_i = height as i32;
574    for dy in 0..dst_size {
575        let screen_y = dst_top + dy;
576        if screen_y < 0 || screen_y >= h_i {
577            continue;
578        }
579        // Nearest-neighbour source y.
580        let sy = (dy * src_h) / dst_size;
581        let row_src_base = (sy as usize) * (src_w as usize);
582        let row_dst_base = (screen_y as usize) * pitch_pixels;
583        for dx in 0..dst_size {
584            let screen_x = dst_left + dx;
585            if screen_x < 0 || screen_x >= w_i {
586                continue;
587            }
588            let sx = (dx * src_w) / dst_size;
589            let src_idx = row_src_base + sx as usize;
590            // Sky pixels: skip. Two redundant signals — colour
591            // matches [`SKY_SENTINEL`] (opticast's skycast write)
592            // OR depth is infinite (post-build patch + empty-grid
593            // init). Either alone is sufficient; both are checked
594            // so a future refactor of build's init can drop one
595            // without breaking the blit.
596            if snapshot.color[src_idx] == SKY_SENTINEL || snapshot.depth[src_idx].is_infinite() {
597                continue;
598            }
599            let dst_idx = row_dst_base + screen_x as usize;
600            if z < zb[dst_idx] {
601                fb[dst_idx] = snapshot.color[src_idx];
602                zb[dst_idx] = z;
603            }
604        }
605    }
606}
607
608#[cfg(test)]
609mod tests {
610    use super::*;
611    use crate::GridTransform;
612    use roxlap_formats::color::VoxColor;
613
614    // Sky pixels in built snapshots are tagged with SKY_SENTINEL
615    // (not a caller-supplied colour). The test asserts use this
616    // directly rather than re-exposing a separate constant.
617
618    #[test]
619    fn canonical_viewpoints_has_26() {
620        let v = canonical_viewpoints();
621        assert_eq!(v.len(), 26);
622    }
623
624    #[test]
625    fn canonical_viewpoints_all_unit_length() {
626        for (i, d) in canonical_viewpoints().iter().enumerate() {
627            let len = d.length();
628            assert!(
629                (len - 1.0).abs() < 1e-12,
630                "viewpoint {i}: {d:?} length={len}",
631            );
632        }
633    }
634
635    #[test]
636    fn canonical_viewpoints_all_distinct() {
637        let v = canonical_viewpoints();
638        for i in 0..v.len() {
639            for j in (i + 1)..v.len() {
640                let same = (v[i] - v[j]).length() < 1e-9;
641                assert!(!same, "viewpoint {i} and {j} are equal: {:?}", v[i]);
642            }
643        }
644    }
645
646    #[test]
647    fn canonical_viewpoints_cover_all_octants() {
648        // Among the 8 corner viewpoints, all eight (±1, ±1, ±1) sign
649        // combos should appear. Octant signature = (sign_x, sign_y, sign_z).
650        let mut octants_seen = std::collections::HashSet::new();
651        for v in canonical_viewpoints() {
652            let sig = (
653                v.x.partial_cmp(&0.0).unwrap(),
654                v.y.partial_cmp(&0.0).unwrap(),
655                v.z.partial_cmp(&0.0).unwrap(),
656            );
657            // Only collect strictly-positive-or-strictly-negative axes
658            // (no zeros) — those identify the 8 corner octants.
659            use std::cmp::Ordering::*;
660            if !matches!(sig.0, Equal) && !matches!(sig.1, Equal) && !matches!(sig.2, Equal) {
661                octants_seen.insert(sig);
662            }
663        }
664        assert_eq!(octants_seen.len(), 8);
665    }
666
667    fn build_small_grid() -> Grid {
668        // Single-chunk grid with a recognisable shape — 16-voxel
669        // box at chunk-local (50, 50, 50)..(65, 65, 65). Enough
670        // content that every viewpoint sees non-sky pixels.
671        let mut g = Grid::new(GridTransform::identity());
672        g.set_rect(
673            IVec3::new(40, 40, 40),
674            IVec3::new(80, 80, 80),
675            Some(VoxColor(0x80_22_aa_22)),
676        );
677        g
678    }
679
680    #[test]
681    fn build_populates_26_snapshots() {
682        let grid = build_small_grid();
683        let cache = BillboardCache::build(&grid, 32);
684        assert_eq!(cache.resolution, 32);
685        assert_eq!(cache.len(), 26);
686        for (i, snap) in cache.snapshots.iter().enumerate() {
687            assert_eq!(snap.width, 32);
688            assert_eq!(snap.height, 32);
689            assert_eq!(snap.color.len(), 32 * 32);
690            assert_eq!(snap.depth.len(), 32 * 32);
691            // Each snapshot's view_dir must match the canonical
692            // viewpoint at the same index.
693            let expected = canonical_viewpoints()[i];
694            assert!(
695                (snap.view_dir - expected).length() < 1e-12,
696                "snapshot {i} view_dir mismatch",
697            );
698        }
699    }
700
701    #[test]
702    fn build_renders_some_non_sky_pixels_per_viewpoint() {
703        // Every viewpoint should hit the box. We don't pin pixel
704        // counts (mip-0 + 32×32 res + 8R distance produces 5-50
705        // hit pixels depending on viewpoint), just that every
706        // viewpoint produces at least ONE non-sky pixel — i.e.
707        // the snapshot camera correctly framed the grid.
708        let grid = build_small_grid();
709        let cache = BillboardCache::build(&grid, 32);
710        for (i, snap) in cache.snapshots.iter().enumerate() {
711            let non_sky = snap.color.iter().filter(|&&p| p != SKY_SENTINEL).count();
712            assert!(
713                non_sky > 0,
714                "snapshot {i} (view_dir={:?}) rendered all-sky",
715                snap.view_dir,
716            );
717        }
718    }
719
720    #[test]
721    fn build_empty_grid_yields_26_all_sky_snapshots() {
722        let grid = Grid::new(GridTransform::identity());
723        let cache = BillboardCache::build(&grid, 16);
724        assert_eq!(cache.len(), 26);
725        for (i, snap) in cache.snapshots.iter().enumerate() {
726            for &px in &snap.color {
727                assert_eq!(
728                    px, SKY_SENTINEL,
729                    "empty grid snapshot {i} produced non-sky pixel {px:#010x}",
730                );
731            }
732            for &z in &snap.depth {
733                assert!(z.is_infinite(), "empty grid snapshot {i} depth not INF");
734            }
735        }
736    }
737
738    #[test]
739    fn pick_nearest_returns_face_viewpoint_for_axis_query() {
740        let grid = build_small_grid();
741        let cache = BillboardCache::build(&grid, 16);
742        // Query along +x: nearest viewpoint should be +x.
743        let snap = cache.pick_nearest(DVec3::X).expect("non-empty cache");
744        assert!(
745            (snap.view_dir - DVec3::X).length() < 1e-12,
746            "+x query picked {:?}",
747            snap.view_dir,
748        );
749        // Query along -z: nearest viewpoint should be -z.
750        let snap = cache.pick_nearest(DVec3::NEG_Z).expect("non-empty cache");
751        assert!(
752            (snap.view_dir - DVec3::NEG_Z).length() < 1e-12,
753            "-z query picked {:?}",
754            snap.view_dir,
755        );
756    }
757
758    #[test]
759    fn pick_nearest_routes_oblique_to_a_corner_viewpoint() {
760        // Query along (1, 1, 1) / √3 lands exactly on the (+, +, +)
761        // corner viewpoint; pick_nearest must return that.
762        let grid = build_small_grid();
763        let cache = BillboardCache::build(&grid, 16);
764        let query = DVec3::new(1.0, 1.0, 1.0).normalize();
765        let snap = cache.pick_nearest(query).expect("non-empty cache");
766        assert!(
767            (snap.view_dir - query).length() < 1e-9,
768            "diagonal query picked {:?}",
769            snap.view_dir,
770        );
771    }
772
773    #[test]
774    fn pick_nearest_returns_none_for_empty_cache() {
775        let cache = BillboardCache::new_empty(32);
776        assert!(cache.is_empty());
777        assert!(cache.pick_nearest(DVec3::X).is_none());
778    }
779
780    #[test]
781    fn new_empty_allocates_no_snapshots() {
782        let cache = BillboardCache::new_empty(64);
783        assert_eq!(cache.resolution, 64);
784        assert_eq!(cache.len(), 0);
785        assert!(cache.is_empty());
786    }
787}