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