Skip to main content

roxlap_render/
lib.rs

1//! roxlap-render — unified CPU/GPU renderer facade.
2//!
3//! New to roxlap? **[The roxlap book](https://ncrashed.github.io/roxlap/)**
4//! is the guide (quickstart, concepts, rendering, lighting, sprites);
5//! this page is the API reference.
6//!
7//! One [`SceneRenderer`] hides the choice between the CPU opticast
8//! path (`roxlap-core` / `roxlap-scene`, presented via `softbuffer`)
9//! and the GPU compute-shader path (`roxlap-gpu`, presented via its
10//! own wgpu surface). Construction picks the GPU backend when asked
11//! and able, and **falls back to CPU automatically** when WGPU init
12//! fails — so a host never has to branch on GPU availability or carry
13//! the `Scene`→GPU upload/refresh/transform glue itself.
14//!
15//! Hosts stay thin: build a `Scene`, advance it from input, then call
16//! [`SceneRenderer::render`] each frame. The facade owns the window
17//! surface, the framebuffer/z-buffer (CPU) or the resident scene +
18//! dirty-chunk tracking (GPU), and presentation.
19//!
20//! The per-frame flow is `render` → *(optional overlays)* → finish.
21//! Between [`SceneRenderer::render`] and the finishing
22//! [`SceneRenderer::present`] / [`SceneRenderer::paint_egui`] call, a
23//! host may overlay depth-tested world-space lines with
24//! [`SceneRenderer::draw_lines`] (editor gizmos, debug geometry — see
25//! [`Line3`]); they land in the framebuffer, occluded by the rendered
26//! scene, with egui still painting panels on top.
27//!
28//! Beyond the scene render itself, the facade owns sprites (static +
29//! per-instance dynamic), animated voxel clips, billboard sprites +
30//! actors, characters (`.rkc`), materials + transparency, dynamic
31//! lighting ([`FrameParams::lights`]), screen→world picking, overlay
32//! lines / images / egui, and the fixed-resolution post pipeline
33//! ([`SceneRenderer::set_render_resolution`] / `set_ssaa` /
34//! `set_posterize`).
35
36#![forbid(unsafe_code)]
37// Compile the workspace README's Rust snippets as doctests so the
38// "Use it in your game" example can never rot the way the pre-QE.0
39// Multicore snippet did (it kept calling API deleted releases earlier).
40// `cfg(doctest)` keeps the README out of the rendered crate docs.
41#[cfg(doctest)]
42#[doc = include_str!("../../../README.md")]
43struct ReadmeDoctests;
44
45mod cpu;
46/// WebGL2 framebuffer presenter for the CPU backend on wasm (the
47/// browser has no `softbuffer`).
48#[cfg(target_arch = "wasm32")]
49mod cpu_blit;
50#[cfg(feature = "hud")]
51mod cpu_egui;
52/// QE-C6 — the one place `ROXLAP_*` env overrides are read (once, at
53/// construction). The user-facing variable table is on
54/// [`RenderOptions`].
55/// Falling voxel islands over dynamic sprite instances (stage DT) —
56/// see `docs/porting/PORTING-DESTRUCTION.md`.
57mod debris;
58mod env_config;
59mod gpu;
60/// Dynamic lighting types (stages DL + SL) — runtime sun, point and
61/// spot lights, on both backends.
62mod light;
63/// Particle system over dynamic sprite instances (stage PS) — see
64/// `docs/porting/PORTING-PARTICLES.md`.
65mod particles;
66
67#[cfg(not(target_arch = "wasm32"))]
68use std::sync::Arc;
69
70use roxlap_core::kfa_draw::{compose_attachment, solve_kfa_limbs};
71use roxlap_core::opticast::OpticastSettings;
72use roxlap_core::sky::Sky;
73use roxlap_core::Camera;
74use roxlap_formats::material::MaterialTable;
75use roxlap_formats::voxel_clip::{duration_prefix_sums, frame_at_prefix};
76use roxlap_scene::Scene;
77
78pub use debris::{DebrisImpact, DebrisSystem};
79pub use light::{DirectionalLight, LightRig, PointLight, SpotLight};
80pub use particles::{
81    CollisionMode, ConeDef, EmitterId, EmitterShape, Particle, ParticleEmitterDef, ParticleSystem,
82    SpawnMode, VelocityDef, CARVE_DEBRIS_CAP, DEFAULT_MAX_PARTICLES,
83};
84pub use roxlap_formats::character::{Attachment, Character, MeshRef};
85pub use roxlap_formats::color::{OverlayColor, Rgb, VoxColor};
86/// Animated-GIF → [`VoxelClip`] importer for Doom-style billboard sprites
87/// (stage BB). Behind the `gif` feature; see `PORTING-BILLBOARD.md`.
88#[cfg(feature = "gif")]
89pub use roxlap_formats::gif_import;
90pub use roxlap_formats::kfa::KfaSprite;
91pub use roxlap_formats::kv6::Kv6;
92pub use roxlap_formats::material::{BlendMode, Material};
93/// PNG-sequence / APNG → [`VoxelClip`] importer (stage BB). Behind the `png`
94/// feature; see `PORTING-BILLBOARD.md`.
95#[cfg(feature = "png")]
96pub use roxlap_formats::png_import;
97pub use roxlap_formats::sprite::Sprite;
98pub use roxlap_formats::voxel_clip::{
99    DecodeError, DecodedClip, LoopMode, StreamingClip, VoxelClip, VoxelFrame,
100};
101pub use roxlap_gpu::{GpuInitError, GpuRendererSettings, PowerPreference};
102// Re-exported so hosts can name the [`SceneRenderer::new`] bounds
103// without adding a direct `raw-window-handle` dependency of their own.
104pub use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
105// Re-exported so hosts feed [`SceneRenderer::paint_egui`] from the exact
106// egui version the renderer was built against (`hud` feature).
107#[cfg(feature = "hud")]
108pub use egui;
109
110use crate::cpu::CpuBackend;
111use crate::gpu::GpuBackend;
112
113/// Type-erased display handle stored by the CPU backend's softbuffer
114/// surface. `raw-window-handle` implements `HasDisplayHandle` for
115/// `Arc<H>` (`H: ?Sized`), and the bare trait object implements its
116/// own object-safe trait — so `Arc<W>` coerces to `Arc<DynDisplay>`
117/// for any provider `W`.
118#[cfg(not(target_arch = "wasm32"))]
119pub(crate) type DynDisplay = dyn HasDisplayHandle + Send + Sync + 'static;
120/// Type-erased window handle counterpart to [`DynDisplay`].
121#[cfg(not(target_arch = "wasm32"))]
122pub(crate) type DynWindow = dyn HasWindowHandle + Send + Sync + 'static;
123
124/// One placed sprite instance: which [`SpriteSet::models`] entry and
125/// where in the world.
126pub struct SpriteInstanceDesc {
127    /// Positional index into [`SpriteSet::models`].
128    pub model: usize,
129    /// World position of the model's anchor (voxel units).
130    pub pos: [f32; 3],
131}
132
133/// Stable handle to a registered sprite model, returned (one per
134/// [`SpriteSet::models`] entry, in order) by
135/// [`SceneRenderer::set_sprites`]. Pass it to
136/// [`refresh_sprite_model`](SceneRenderer::refresh_sprite_model) to
137/// re-register that model's geometry after a content edit — so callers
138/// never track the positional `usize` index themselves. Opaque on
139/// purpose: there is no arithmetic to do on it.
140///
141/// Also returned by [`SceneRenderer::add_sprite_model`] for an
142/// incrementally registered model, and accepted by
143/// [`remove_sprite_model`](SceneRenderer::remove_sprite_model). A handle
144/// to a removed model is **stale**: it resolves to nothing, so passing
145/// it anywhere is a safe no-op. The `gen` (generation) field guards a
146/// future compacting registry; it stays `0` today because model slots
147/// are tombstoned in place and never reused (GPU chain ids are
148/// append-only).
149#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
150pub struct SpriteModelId {
151    pub(crate) slot: u32,
152    pub(crate) gen: u32,
153}
154
155/// Stable handle to a **dynamically added** sprite instance — the result
156/// of [`SceneRenderer::add_sprite_instance`], passed to
157/// [`remove_sprite_instance`](SceneRenderer::remove_sprite_instance).
158///
159/// Backends remove instances by swap (O(1)), which moves another instance
160/// into the freed slot; this handle survives that because the facade keeps
161/// the id↔slot mapping up to date. The generation guards against a stale
162/// handle aliasing a recycled slot.
163#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
164pub struct SpriteInstanceId {
165    slot: u32,
166    gen: u32,
167}
168
169/// Facade-side slotmap that turns the backends' swap-remove indexing into
170/// stable [`SpriteInstanceId`] handles. Both backends keep their dynamic
171/// instances as a tail sublist indexed `0..n`; `order[dyn_index]` is the
172/// owning slot, and a removal fixes up the one slot whose instance was
173/// swapped into the hole.
174#[derive(Default)]
175struct DynInstanceMap {
176    /// Per slot: `(generation, Some(dyn_index) while live)`.
177    slots: Vec<(u32, Option<u32>)>,
178    /// Per live `dyn_index`: the owning slot. Parallel to the backends'
179    /// dynamic sublist (so `order.len()` == the dynamic instance count).
180    order: Vec<u32>,
181    free: Vec<u32>,
182}
183
184impl DynInstanceMap {
185    /// Register a freshly appended instance (always at `dyn_index ==
186    /// order.len()`); returns its stable handle.
187    fn alloc(&mut self, dyn_index: u32) -> SpriteInstanceId {
188        debug_assert_eq!(self.order.len() as u32, dyn_index);
189        let slot = self.free.pop().unwrap_or_else(|| {
190            self.slots.push((0, None));
191            (self.slots.len() - 1) as u32
192        });
193        let gen = self.slots[slot as usize].0;
194        self.slots[slot as usize].1 = Some(dyn_index);
195        self.order.push(slot);
196        SpriteInstanceId { slot, gen }
197    }
198
199    /// Resolve a handle to its current backend `dyn_index`, or `None` if
200    /// it's stale / already removed.
201    fn dyn_index(&self, id: SpriteInstanceId) -> Option<u32> {
202        let (gen, idx) = *self.slots.get(id.slot as usize)?;
203        (gen == id.gen).then_some(idx).flatten()
204    }
205
206    /// Apply a removal: the backend swap-removed `removed` and reported
207    /// `moved` (the old-last `dyn_index` that slid into `removed`, or
208    /// `None` if `removed` was itself the last).
209    fn remove(&mut self, id: SpriteInstanceId, removed: u32, moved: Option<u32>) {
210        self.slots[id.slot as usize].1 = None;
211        self.slots[id.slot as usize].0 += 1; // bump generation
212        self.free.push(id.slot);
213        if let Some(last) = moved {
214            let moved_slot = self.order[last as usize];
215            self.slots[moved_slot as usize].1 = Some(removed);
216            self.order[removed as usize] = moved_slot;
217        }
218        self.order.pop();
219    }
220}
221
222/// Crate-internal contract of every epoch-slotmap handle type
223/// ([`SpriteModelId`], [`VoxelClipId`], [`CharacterId`],
224/// [`StreamingClipId`], [`BillboardActorId`]): mint from / split into
225/// the `(slot, generation)` pair. Lets one generic [`EpochSlotMap`]
226/// serve all five families while each keeps its own distinct handle
227/// type (so a `CharacterId` can never be passed where a `VoxelClipId`
228/// is expected).
229trait SlotHandle: Copy {
230    fn mint(slot: u32, gen: u32) -> Self;
231    fn parts(self) -> (u32, u32);
232}
233
234macro_rules! impl_slot_handle {
235    ($($t:ty),+ $(,)?) => {$(
236        impl SlotHandle for $t {
237            fn mint(slot: u32, gen: u32) -> Self {
238                Self { slot, gen }
239            }
240            fn parts(self) -> (u32, u32) {
241                (self.slot, self.gen)
242            }
243        }
244    )+};
245}
246
247impl_slot_handle!(
248    SpriteModelId,
249    VoxelClipId,
250    CharacterId,
251    StreamingClipId,
252    BillboardActorId,
253);
254
255/// Facade-side epoch slotmap (QE.1a — one generic replacing five
256/// hand-rolled copies). Unlike [`DynInstanceMap`] there is **no**
257/// swap-remove fixup: a slot maps 1:1 to the backends' positional
258/// index, which is append-only and never reused. A removed entry
259/// tombstones its slot *in place* (the backend frees the data but
260/// keeps the index), so a stale handle resolves to `None` → a safe
261/// no-op rather than aliasing another entry.
262///
263/// [`reset`](Self::reset) clears the slots **and bumps `epoch`**,
264/// which is baked into each minted id's generation. A handle from
265/// before a [`SceneRenderer::set_sprites`] therefore carries the old
266/// epoch and resolves to `None` rather than silently aliasing the
267/// entry that re-took its slot. ([`reset_live`](Self::reset_live) is
268/// the model map's deliberate exception.)
269struct EpochSlotMap<I> {
270    /// Per slot (== backend positional index): `(epoch_at_alloc, live)`.
271    slots: Vec<(u32, bool)>,
272    epoch: u32,
273    _handle: std::marker::PhantomData<I>,
274}
275
276impl<I> Default for EpochSlotMap<I> {
277    fn default() -> Self {
278        Self {
279            slots: Vec::new(),
280            epoch: 0,
281            _handle: std::marker::PhantomData,
282        }
283    }
284}
285
286impl<I: SlotHandle> EpochSlotMap<I> {
287    /// Register a freshly appended entry at positional `index` (always
288    /// the current `slots.len()`); returns its stable handle.
289    fn alloc(&mut self, index: u32) -> I {
290        debug_assert_eq!(self.slots.len() as u32, index);
291        self.slots.push((self.epoch, true));
292        I::mint(index, self.epoch)
293    }
294
295    /// The handle a live slot at `index` resolves from — used by
296    /// [`SceneRenderer::set_sprites`] to hand back ids for the `0..n`
297    /// entries seeded by [`reset_live`](Self::reset_live).
298    fn minted(&self, index: u32) -> I {
299        I::mint(index, self.epoch)
300    }
301
302    /// Resolve a handle to its backend positional index, or `None` if
303    /// it's stale / already removed.
304    fn index(&self, id: I) -> Option<usize> {
305        let (slot, gen) = id.parts();
306        let (epoch, live) = *self.slots.get(slot as usize)?;
307        (epoch == gen && live).then_some(slot as usize)
308    }
309
310    /// Tombstone a slot in place. Returns `false` if the handle is
311    /// stale / already removed.
312    fn remove(&mut self, id: I) -> bool {
313        let (slot, gen) = id.parts();
314        let Some(entry) = self.slots.get_mut(slot as usize) else {
315            return false;
316        };
317        if entry.0 != gen || !entry.1 {
318            return false;
319        }
320        entry.1 = false;
321        true
322    }
323
324    /// Drop every entry and invalidate every outstanding handle (the
325    /// epoch bump).
326    fn reset(&mut self) {
327        self.slots.clear();
328        self.epoch = self.epoch.wrapping_add(1);
329    }
330
331    /// Positional indices of every live entry, ascending — the
332    /// iteration [`SceneRenderer::tick`] drives collection updates
333    /// from.
334    fn live_indices(&self) -> impl Iterator<Item = usize> + '_ {
335        self.slots
336            .iter()
337            .enumerate()
338            .filter_map(|(i, &(_, live))| live.then_some(i))
339    }
340
341    /// Re-seat `n` live entries with positional ids `0..n` **without**
342    /// bumping the epoch — [`SceneRenderer::set_sprites`]' model-map
343    /// semantics, where model index = chain id on both backends and a
344    /// pre-rebuild positional id deliberately keeps meaning "model
345    /// `i` of the current set".
346    fn reset_live(&mut self, n: usize) {
347        self.slots.clear();
348        self.slots.resize(n, (self.epoch, true));
349    }
350}
351
352/// Stable handle to a registered animated voxel clip (VCL.4) — the
353/// result of [`SceneRenderer::add_voxel_clip`], passed to
354/// [`add_clip_instance_posed`](SceneRenderer::add_clip_instance_posed)
355/// and [`remove_voxel_clip`](SceneRenderer::remove_voxel_clip). Like
356/// [`SpriteModelId`], a removed clip's handle is stale → a safe no-op.
357/// Reset by [`set_sprites`](SceneRenderer::set_sprites) (which drops the
358/// dynamic + clip layers).
359#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
360pub struct VoxelClipId {
361    slot: u32,
362    gen: u32,
363}
364
365/// Stable handle to a registered animated character (VCL.6) — the result
366/// of [`SceneRenderer::add_character`], advanced each frame with
367/// [`advance_character`](SceneRenderer::advance_character) and dropped with
368/// [`remove_character`](SceneRenderer::remove_character). Reset by
369/// [`set_sprites`](SceneRenderer::set_sprites).
370#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
371pub struct CharacterId {
372    slot: u32,
373    gen: u32,
374}
375
376/// Stable handle to a registered **streaming** voxel clip (follow-up #3) —
377/// the result of [`SceneRenderer::add_streaming_clip`], advanced with
378/// [`set_streaming_clip_frame`](SceneRenderer::set_streaming_clip_frame) and
379/// dropped with
380/// [`remove_streaming_clip`](SceneRenderer::remove_streaming_clip). Reset by
381/// [`set_sprites`](SceneRenderer::set_sprites).
382#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
383pub struct StreamingClipId {
384    slot: u32,
385    gen: u32,
386}
387
388/// Handle to an instance of a streaming clip
389/// ([`add_streaming_clip_instance`](SceneRenderer::add_streaming_clip_instance)).
390///
391/// Deliberately **distinct** from [`SpriteInstanceId`]: a streaming clip's
392/// frame is per-*clip* (all its instances share one re-uploaded model,
393/// advanced by
394/// [`set_streaming_clip_frame`](SceneRenderer::set_streaming_clip_frame)), so
395/// a streaming instance is *not* accepted by the per-instance
396/// [`set_clip_instance_frame`](SceneRenderer::set_clip_instance_frame) —
397/// trying to scrub two instances of one streaming clip independently is a
398/// compile error, not a silent coupling. (Use a flipbook clip for
399/// per-instance frames.) Move it with
400/// [`set_streaming_instance_transform`](SceneRenderer::set_streaming_instance_transform)
401/// and drop it with
402/// [`remove_streaming_instance`](SceneRenderer::remove_streaming_instance).
403#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
404pub struct StreamingInstanceId(SpriteInstanceId);
405
406/// One registered streaming clip: the seekable cursor + the single sprite
407/// model it re-uploads each frame, plus the dims/pivot used to rebuild it.
408struct StreamingClipState {
409    cursor: StreamingClip,
410    model: SpriteModelId,
411    dims: [u32; 3],
412    pivot: [f32; 3],
413    /// Colour→material map (TV.3), empty for an all-opaque streaming clip.
414    /// Re-applied on every per-frame re-upload so the streamed model keeps
415    /// its per-voxel materials as it advances.
416    material_map: Vec<(Rgb, u8)>,
417    /// PF.5 — the clip frame currently resident on `model`. A player driven
418    /// at render rate re-applies the same clip frame most ticks (10 fps clip
419    /// on a 144 fps render = 14×); when it matches, the dense `to_kv6`
420    /// rebuild + LOD chain + GPU re-upload are skipped entirely.
421    last_applied: Option<usize>,
422}
423
424/// Per-clip-attachment playback clock (VCL.6): the timing it needs to
425/// resolve a frame, plus its own accumulating clock.
426struct ClipClock {
427    /// PF.13 (S4) — inclusive duration prefix sums (ms), built once per
428    /// timeline via [`duration_prefix_sums`] so every tick resolves its
429    /// frame by binary search instead of re-summing the duration list.
430    prefix: Vec<u64>,
431    loop_mode: LoopMode,
432    /// Playback rate, Q8 (256 = 1×).
433    speed_q8: i32,
434    /// Accumulated playback time (ms), seeded from the attachment's
435    /// `start_phase_ms`.
436    clock_ms: f64,
437}
438
439impl ClipClock {
440    /// Build a clock over `durations` starting at `clock_ms`.
441    fn new(durations: &[u32], loop_mode: LoopMode, speed_q8: i32, clock_ms: f64) -> Self {
442        Self {
443            prefix: duration_prefix_sums(durations),
444            loop_mode,
445            speed_q8,
446            clock_ms,
447        }
448    }
449
450    /// Frame shown at `elapsed_ms` on this clock's timeline —
451    /// [`frame_at`](roxlap_formats::voxel_clip::frame_at) over the
452    /// cached prefix sums.
453    fn frame_for(&self, elapsed_ms: u32) -> u32 {
454        frame_at_prefix(&self.prefix, self.loop_mode, elapsed_ms) as u32
455    }
456
457    /// Advance the clock by `dt` seconds at its Q8 `speed` and return the
458    /// frame to show. Shared by character attachments and standalone clip
459    /// players. A negative clock (rewind past 0) reads as frame 0 but is
460    /// kept signed so resuming forward is continuous.
461    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
462    fn tick(&mut self, dt: f64) -> u32 {
463        self.clock_ms += dt * 1000.0 * f64::from(self.speed_q8) / 256.0;
464        self.frame_for(self.clock_ms.max(0.0) as u32)
465    }
466
467    /// Retarget this clock to a different clip's timeline (BB.1): swap the
468    /// per-frame `durations` + `loop_mode` and restart at `0`, **preserving
469    /// the playback rate** (`speed_q8`). Used by
470    /// [`SceneRenderer::set_clip_instance_clip`] so swapping a billboard's
471    /// animation keeps its speed / pause policy.
472    fn retarget(&mut self, durations: &[u32], loop_mode: LoopMode) {
473        self.prefix = duration_prefix_sums(durations);
474        self.loop_mode = loop_mode;
475        self.clock_ms = 0.0;
476    }
477}
478
479/// Facade-side metadata captured for a registered flipbook clip, so editor
480/// queries + the auto-player don't shadow the `DecodedClip`.
481struct ClipMeta {
482    dims: [u32; 3],
483    pivot: [f32; 3],
484    voxel_world_size: f32,
485    durations: Vec<u32>,
486    loop_mode: LoopMode,
487    /// Colour→material map the clip was registered with (TV.3), empty for an
488    /// all-opaque clip. Retained so an in-place
489    /// [`update_clip_frame`](SceneRenderer::update_clip_frame) re-classifies
490    /// the edited frame's voxels instead of dropping its per-voxel materials.
491    material_map: Vec<(Rgb, u8)>,
492}
493
494/// Public metadata for a registered clip — the inspector view returned by
495/// [`SceneRenderer::clip_metadata`].
496#[derive(Clone, Debug, PartialEq)]
497pub struct ClipMetadata {
498    /// Fixed bounding box (voxels).
499    pub dims: [u32; 3],
500    /// Model pivot (the kv6 pivot frames share).
501    pub pivot: [f32; 3],
502    /// Render scale (1 voxel = this many world units).
503    pub voxel_world_size: f32,
504    /// Playback wrap behaviour.
505    pub loop_mode: LoopMode,
506    /// Number of frames.
507    pub frame_count: usize,
508    /// Per-frame durations (ms), one per frame.
509    pub durations: Vec<u32>,
510    /// Total loop length (ms) — sum of `durations`.
511    pub total_ms: u32,
512}
513
514/// What an auto-advancing [`ClipPlayer`] (#6) drives each
515/// [`advance_voxel_clips`](SceneRenderer::advance_voxel_clips). A flipbook
516/// clip's frame is per-instance; a streaming clip's is per-clip (its
517/// instances share one model), so the targets differ.
518#[derive(Clone, Copy)]
519enum PlayerTarget {
520    Flipbook(SpriteInstanceId),
521    Streaming(StreamingClipId),
522}
523
524/// A standalone clip given its own playback clock (#6): the host calls
525/// `advance_voxel_clips(dt)` once instead of hand-driving `frame_at` +
526/// `set_clip_instance_frame`.
527struct ClipPlayer {
528    target: PlayerTarget,
529    clock: ClipClock,
530    /// When `true`, [`advance_voxel_clips`](SceneRenderer::advance_voxel_clips)
531    /// leaves the clock (and frame) untouched — the editor's play/pause.
532    paused: bool,
533}
534
535/// One live bone attachment: which bone drives it, its local offset, the
536/// renderer instance it owns, and (for a clip target) its playback clock.
537struct AttachInst {
538    bone: usize,
539    local_offset: roxlap_formats::xform::BoneXform,
540    inst: SpriteInstanceId,
541    clip: Option<ClipClock>,
542}
543
544/// A live animated character: the hinge skeleton (the bone-transform
545/// solver) + one [`AttachInst`] per bone attachment.
546struct CharInstance {
547    skeleton: KfaSprite,
548    attaches: Vec<AttachInst>,
549    /// Sprite models + voxel clips this character registered, so
550    /// [`remove_character`](SceneRenderer::remove_character) can free them
551    /// (otherwise they leak until the next `set_sprites`).
552    models: Vec<SpriteModelId>,
553    clips: Vec<VoxelClipId>,
554}
555
556/// Orientation + position for a dynamic sprite instance — the per-frame
557/// pose passed to [`SceneRenderer::add_sprite_instance_posed`] and
558/// [`set_sprite_instance_transform`](SceneRenderer::set_sprite_instance_transform).
559///
560/// `right`/`up`/`forward` are the instance's local axes expressed in
561/// world space (the columns of the model→world rotation), mapping
562/// directly onto the underlying [`Sprite`]'s `s`/`h`/`f` (kv6 local
563/// +x/+y/+z). They **must** be non-singular (`det ≠ 0`) but need not be
564/// orthonormal — a uniform/non-uniform scale or shear is fine. A
565/// near-singular basis falls through the renderer's degenerate-basis
566/// guards and the instance silently skips that frame rather than
567/// panicking. [`Default`] is the identity basis (axis-aligned).
568#[derive(Clone, Copy, Debug)]
569pub struct DynSpriteTransform {
570    /// Instance world position (the kv6 pivot maps here).
571    pub pos: [f32; 3],
572    /// Local +x in world space ↦ [`Sprite::s`].
573    pub right: [f32; 3],
574    /// Local +y in world space ↦ [`Sprite::h`].
575    pub up: [f32; 3],
576    /// Local +z in world space ↦ [`Sprite::f`].
577    pub forward: [f32; 3],
578}
579
580impl Default for DynSpriteTransform {
581    fn default() -> Self {
582        Self {
583            pos: [0.0, 0.0, 0.0],
584            right: [1.0, 0.0, 0.0],
585            up: [0.0, 1.0, 0.0],
586            forward: [0.0, 0.0, 1.0],
587        }
588    }
589}
590
591impl DynSpriteTransform {
592    /// Stamp this pose onto a [`Sprite`] in place: `pos → p`,
593    /// `right/up/forward → s/h/f` (a direct copy — the basis is the
594    /// model→world columns). Both backends keep the rest of the template
595    /// (`kv6`, `flags`) and only overwrite the pose.
596    pub(crate) fn apply_to(self, s: &mut Sprite) {
597        s.p = self.pos;
598        s.s = self.right;
599        s.h = self.up;
600        s.f = self.forward;
601    }
602}
603
604/// How a billboard instance turns to face the camera (BB.2). Set per
605/// instance via [`SceneRenderer::add_billboard_instance`] /
606/// [`set_billboard_mode`](SceneRenderer::set_billboard_mode); applied each
607/// [`face_billboards_to`](SceneRenderer::face_billboards_to).
608#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
609pub enum BillboardMode {
610    /// Not auto-oriented — the host drives its transform directly. Default
611    /// (so a billboard record with no mode is inert).
612    #[default]
613    None,
614    /// Yaw-only: the slab stays vertical (image up = world up) and rotates
615    /// about the vertical axis to face the camera. The Doom/Build default —
616    /// its cast shadow stays sane (a vertical card) as the camera orbits.
617    Cylindrical,
618    /// Full face: the slab is always perpendicular to the camera direction
619    /// (pitches with the view). Ideal head-on, but its cast shadow rotates
620    /// as you orbit.
621    Spherical,
622}
623
624/// How a sprite/billboard instance derives its **shading normal** (BB.2b) —
625/// a per-instance choice that rides the sprite `flags`. A camera-facing
626/// billboard's DDA face normal tracks the camera, so its `N·L` would shift as
627/// you orbit; `WorldUp` / `AmbientOnly` tame that. Only affects the dynamic
628/// lighting path (a disabled rig is unaffected). Set via
629/// [`set_sprite_instance_lighting`](SceneRenderer::set_sprite_instance_lighting)
630/// or [`BillboardActorDef::lighting`].
631#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
632pub enum BillboardLighting {
633    /// The DDA hit-face normal — today's DL.7 look (default).
634    #[default]
635    FaceNormal,
636    /// A fixed world-up normal: stable directional shading regardless of the
637    /// camera angle.
638    WorldUp,
639    /// Ambient only — no sun / point-light direct term, the flattest,
640    /// most Doom-faithful cutout look (still scaled by the scene's ambient
641    /// level, so it dims in a dim scene).
642    AmbientOnly,
643    /// Full-bright / **emissive** — the voxel colour at full intensity,
644    /// ignoring all lighting. The right look for glows (fire, spell auras,
645    /// muzzle flashes) and markers that shouldn't darken in shadow.
646    FullBright,
647}
648
649/// One camera-facing billboard instance (BB.2): the clip/sprite instance it
650/// drives, its world position, and how it orients.
651struct BillboardRec {
652    id: SpriteInstanceId,
653    pos: [f32; 3],
654    mode: BillboardMode,
655}
656
657/// roxlap world up — voxlap is z-down, so up is `-z` (matches the
658/// scene-demo camera builder + the lighting bake's z convention). Billboard
659/// orientation assumes this; an app with a different up convention would
660/// need this generalised (not exposed yet — YAGNI).
661const BILLBOARD_UP: [f32; 3] = [0.0, 0.0, -1.0];
662
663fn bb_norm(v: [f32; 3]) -> Option<[f32; 3]> {
664    let m = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
665    (m > 1e-6).then(|| [v[0] / m, v[1] / m, v[2] / m])
666}
667
668fn bb_cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
669    [
670        a[1] * b[2] - a[2] * b[1],
671        a[2] * b[0] - a[0] * b[2],
672        a[0] * b[1] - a[1] * b[0],
673    ]
674}
675
676/// The camera-facing basis for a billboard at `pos` (the slab's local axes:
677/// `+x` = image horizontal, `+y` = normal toward the camera, `+z` = image
678/// vertical). Returns `None` for [`BillboardMode::None`] or a degenerate
679/// pose (camera on the sprite's vertical axis for cylindrical; looking
680/// straight along world-up for spherical) — the caller then skips it.
681fn billboard_transform(
682    pos: [f32; 3],
683    cam: [f64; 3],
684    mode: BillboardMode,
685) -> Option<DynSpriteTransform> {
686    #[allow(clippy::cast_possible_truncation)]
687    let to_cam = [
688        cam[0] as f32 - pos[0],
689        cam[1] as f32 - pos[1],
690        cam[2] as f32 - pos[2],
691    ];
692    // `+y` = slab normal toward the camera (horizontal-only for
693    // cylindrical). Degenerate view axes (camera exactly overhead /
694    // exactly at the pos — e.g. a third-person camera the instant
695    // before its boom applies) fall back to a fixed facing instead
696    // of returning None: the card is edge-on/invisible right then
697    // anyway, but the POSITION update must never be dropped, or the
698    // actor freezes at its last pose (the CC.4 third-person bug).
699    const FALLBACK: [f32; 3] = [0.0, 1.0, 0.0];
700    let ny = match mode {
701        BillboardMode::Cylindrical => bb_norm([to_cam[0], to_cam[1], 0.0]).unwrap_or(FALLBACK),
702        BillboardMode::Spherical => bb_norm(to_cam).unwrap_or(FALLBACK),
703        BillboardMode::None => return None,
704    };
705    // `+x` = image horizontal = screen-right (non-mirrored): up × normal.
706    let nx = bb_norm(bb_cross(BILLBOARD_UP, ny)).unwrap_or([1.0, 0.0, 0.0]);
707    // `+z` = image vertical (≈ world up; exactly world up for cylindrical).
708    let nz = bb_cross(ny, nx);
709    Some(DynSpriteTransform {
710        pos,
711        right: nx,
712        up: ny,
713        forward: nz,
714    })
715}
716
717/// Apply shadow cast/receive booleans to a sprite `flags` word in place
718/// (XS.4 bits 4/5), preserving the other bits. Shared by both backends'
719/// per-instance shadow-flag setters (BB.3).
720pub(crate) fn apply_shadow_flags(flags: &mut u32, casts: bool, receives: bool) {
721    use roxlap_formats::sprite::{SPRITE_FLAG_NO_SHADOW_CAST, SPRITE_FLAG_NO_SHADOW_RECEIVE};
722    if casts {
723        *flags &= !SPRITE_FLAG_NO_SHADOW_CAST;
724    } else {
725        *flags |= SPRITE_FLAG_NO_SHADOW_CAST;
726    }
727    if receives {
728        *flags &= !SPRITE_FLAG_NO_SHADOW_RECEIVE;
729    } else {
730        *flags |= SPRITE_FLAG_NO_SHADOW_RECEIVE;
731    }
732}
733
734/// Apply a [`BillboardLighting`] mode to a sprite `flags` word in place
735/// (BB.2b bits 6/7), preserving the other bits. Shared by both backends'
736/// per-instance lighting setters.
737pub(crate) fn apply_lighting_flags(flags: &mut u32, mode: BillboardLighting) {
738    use roxlap_formats::sprite::{SPRITE_FLAG_LIGHT_AMBIENT_ONLY, SPRITE_FLAG_LIGHT_WORLD_UP};
739    *flags &= !(SPRITE_FLAG_LIGHT_WORLD_UP | SPRITE_FLAG_LIGHT_AMBIENT_ONLY);
740    match mode {
741        BillboardLighting::FaceNormal => {}
742        BillboardLighting::WorldUp => *flags |= SPRITE_FLAG_LIGHT_WORLD_UP,
743        BillboardLighting::AmbientOnly => *flags |= SPRITE_FLAG_LIGHT_AMBIENT_ONLY,
744        // Full-bright is encoded as both bits set (the decoders check it first).
745        BillboardLighting::FullBright => {
746            *flags |= SPRITE_FLAG_LIGHT_WORLD_UP | SPRITE_FLAG_LIGHT_AMBIENT_ONLY;
747        }
748    }
749}
750
751// ---- billboard actors (BB.4) --------------------------------------------
752
753/// Stable handle to a [`BillboardActor`](SceneRenderer::add_billboard_actor)
754/// — a high-level directional billboard managed by the renderer (it owns one
755/// clip instance, picks the directional clip by view angle, and plays a
756/// named-state animation). Reset by [`set_sprites`](SceneRenderer::set_sprites);
757/// a removed actor's handle is stale → a safe no-op.
758#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
759pub struct BillboardActorId {
760    slot: u32,
761    gen: u32,
762}
763
764/// One animation state of a [`BillboardActorDef`]: its name plus the clips
765/// for each viewing direction. `dirs.len()` may be `1` (non-directional),
766/// `8` (classic Doom rotations), or any `N` (uniform angular bins). Index 0
767/// is the view-from-front (camera in the actor's facing direction),
768/// increasing counter-clockwise.
769pub struct ActorState {
770    /// State name [`SceneRenderer::set_actor_state`] selects by
771    /// (e.g. `"walk"`, `"attack"`). Owned since QE.7b, so actor
772    /// definitions can come from data files (monster definitions
773    /// loaded at runtime) without `Box::leak`.
774    pub name: String,
775    /// One clip per view direction, counter-clockwise from "facing the
776    /// viewer" — 1 (billboard), 4, or 8 entries.
777    pub dirs: Vec<VoxelClipId>,
778}
779
780/// How a sprite instance participates in dynamic-light shadows
781/// (QE.7b — replaces the unreadable
782/// `set_sprite_instance_shadow_flags(id, true, false)` bool pair).
783#[derive(Clone, Copy, PartialEq, Eq, Debug)]
784pub struct ShadowFlags {
785    /// The instance's voxels block dynamic-light shadow rays.
786    pub casts: bool,
787    /// Terrain / other-caster shadows darken the instance's voxels.
788    pub receives: bool,
789}
790
791impl Default for ShadowFlags {
792    /// Both on — the participating default every spawn starts with.
793    fn default() -> Self {
794        Self {
795            casts: true,
796            receives: true,
797        }
798    }
799}
800
801/// Recipe for [`add_billboard_actor`](SceneRenderer::add_billboard_actor).
802pub struct BillboardActorDef {
803    /// Animation states (≥1, each with ≥1 directional clip). The first is
804    /// the initial state.
805    pub states: Vec<ActorState>,
806    /// How the slab turns to face the camera (default [`BillboardMode::Cylindrical`]).
807    pub mode: BillboardMode,
808    /// Shading-normal mode (BB.2b; default [`BillboardLighting::FaceNormal`]).
809    pub lighting: BillboardLighting,
810    /// Playback rate of the state animation (`1.0` = authored speed,
811    /// negative = reverse). QE.7b — was Q8 fixed point (`speed_q8:
812    /// 256`); migrate with `speed = speed_q8 as f32 / 256.0`.
813    pub speed: f32,
814    /// World units per slab voxel (`1.0` = classic 1:1). Applied to
815    /// the instance basis every tick. Composes multiplicatively with
816    /// the clip's own `voxel_world_size` (both backends honour both).
817    pub scale: f32,
818    /// Shadow participation for the actor's voxels.
819    pub shadows: ShadowFlags,
820}
821
822impl Default for BillboardActorDef {
823    fn default() -> Self {
824        Self {
825            states: Vec::new(),
826            mode: BillboardMode::Cylindrical,
827            lighting: BillboardLighting::FaceNormal,
828            speed: 1.0,
829            scale: 1.0,
830            shadows: ShadowFlags::default(),
831        }
832    }
833}
834
835/// QE.7b — the public API speaks `f32` speed (`1.0` = authored rate);
836/// the clip clocks keep their Q8 fixed-point internals.
837#[allow(clippy::cast_possible_truncation)]
838fn speed_to_q8(speed: f32) -> i32 {
839    (speed * 256.0).round() as i32
840}
841
842/// A live directional billboard: one clip instance whose directional clip is
843/// reselected by view angle and whose animation plays a named state.
844struct BillboardActor {
845    /// World units per slab voxel (from the def).
846    scale: f32,
847    inst: SpriteInstanceId,
848    states: Vec<ActorState>,
849    cur_state: usize,
850    pos: [f32; 3],
851    /// World yaw the actor "faces" (radians); the dir picker compares the
852    /// camera's bearing against it.
853    facing_yaw: f64,
854    mode: BillboardMode,
855    clock: ClipClock,
856    /// The directional clip currently shown, to avoid redundant clip swaps.
857    showing: Option<VoxelClipId>,
858    /// The def's playback rate, kept for state-switch clock rebuilds.
859    speed: f32,
860}
861
862impl BillboardActor {
863    /// Pick the directional clip index for a camera at `cam` (world). See
864    /// [`dir_index`].
865    fn pick_dir(&self, cam: [f64; 3]) -> usize {
866        dir_index(
867            self.pos,
868            self.facing_yaw,
869            cam,
870            self.states[self.cur_state].dirs.len(),
871        )
872    }
873}
874
875/// Bin a camera's bearing (relative to an actor at `pos` facing `facing_yaw`)
876/// into one of `n` viewing-direction sectors. Index 0 = viewed-from-front
877/// (camera in the actor's facing direction), increasing counter-clockwise.
878/// `n <= 1` or a camera directly above/below ⇒ 0.
879fn dir_index(pos: [f32; 3], facing_yaw: f64, cam: [f64; 3], n: usize) -> usize {
880    if n <= 1 {
881        return 0;
882    }
883    let dx = cam[0] - f64::from(pos[0]);
884    let dy = cam[1] - f64::from(pos[1]);
885    if dx * dx + dy * dy < 1e-12 {
886        return 0; // camera directly above/below → no horizontal bearing
887    }
888    let rel = (dy.atan2(dx) - facing_yaw).rem_euclid(std::f64::consts::TAU);
889    let sector = std::f64::consts::TAU / n as f64;
890    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
891    let idx = (rel / sector).round() as usize % n;
892    idx
893}
894
895/// Backend-agnostic sprite description. The facade builds the CPU
896/// per-instance draw list and the GPU instanced registry from the
897/// same data, so both backends show identical sprites. The host owns
898/// content (which models, where, recolouring) — building a recoloured
899/// variant is just a second [`Sprite`] model with edited `kv6.voxels`.
900pub struct SpriteSet {
901    /// Distinct voxel models (KV6 + base orientation). Instances index
902    /// into this; their position overrides the model's.
903    pub models: Vec<Sprite>,
904    /// Initial placements — one drawn sprite per entry, each binding a
905    /// [`models`](Self::models) index to a world position.
906    pub instances: Vec<SpriteInstanceDesc>,
907    /// Model the [`SceneRenderer::carve_active_sprite`] hotkey edits
908    /// (GPU only, mirroring the demo's `G`-carve). `None` disables it.
909    pub carve_model: Option<usize>,
910}
911
912/// Per-frame inputs both backends consume. The host builds the
913/// [`OpticastSettings`] (it owns scan distance, projection etc.); the
914/// facade does everything else (pool config, sky fill, render,
915/// present).
916///
917/// **Both backends derive their projection from
918/// [`settings`](Self::settings)** (QE.2a): the vertical field of view
919/// is `2·atan(yres/2 / hz)` and the GPU outer-DDA step budget follows
920/// [`OpticastSettings::max_scan_dist`], so the two backends can no
921/// longer disagree about what they show. Pick an explicit FOV with
922/// [`OpticastSettings::with_fov_y`].
923///
924/// `#[non_exhaustive]`: construct with [`FrameParams::new`] and
925/// override fields — a future field addition is then not a breaking
926/// change (pre-QE.2, every added field broke every host's struct
927/// literal).
928#[non_exhaustive]
929pub struct FrameParams<'a> {
930    /// Render settings both backends share: framebuffer geometry +
931    /// projection (`hx`/`hy`/`hz`), scan distances, and the mip
932    /// ladder. (Named for the CPU renderer it configured first; the
933    /// GPU backend derives its FOV + step budget from it too.)
934    pub settings: &'a OpticastSettings,
935    /// Packed engine sky colour: the CPU sky-miss fill + skycast, and
936    /// the clear colour if no scene renders.
937    pub sky_color: Rgb,
938    /// Optional sky panorama for the CPU rasterizer's sky sampling.
939    pub sky: Option<&'a Sky>,
940    /// CPU fog: the packed colour distant voxels fade toward.
941    pub fog_color: Rgb,
942    /// CPU fog: full-fog distance (voxels). `0` disables CPU fog.
943    pub fog_max_scan_dist: i32,
944    /// CPU: treat z=255 as air (avoids the S1.X bedrock path for
945    /// out-of-bounds cameras).
946    pub treat_z_max_as_air: bool,
947    /// Whether to draw the renderer's sprites this frame. Both backends
948    /// draw KV6 sprites flat-lit (the clean-room DDA sprite raycaster on
949    /// CPU; uploaded model colours on GPU), so no host-supplied lighting
950    /// is needed — this is just the on/off opt-in. `false` skips sprite
951    /// drawing.
952    pub draw_sprites: bool,
953    /// Per-face directional shading for the voxel grids — voxlap's
954    /// `setsideshades(top, bot, left, right, up, down)`, the grid-scan
955    /// analogue of [`draw_sprites`](Self::draw_sprites). Each
956    /// entry darkens the faces pointing that way; the host typically
957    /// passes its engine's `side_shades()`. The default `[0; 6]` keeps
958    /// `sideshademode` off (no per-side shading), so existing hosts and
959    /// the oracle goldens are unaffected. Applied each frame by **both**
960    /// backends: the CPU rasteriser via `gcsub`, and the GPU scene-DDA
961    /// pass by darkening a hit voxel's brightness by the hit face's
962    /// shade (the face taken from the DDA's last-stepped axis).
963    pub side_shades: [i8; 6],
964    /// Dynamic lighting (stages DL + SL) — runtime sun + point + spot
965    /// lights + stylized shadows, applied by **both** backends (GPU
966    /// shaders since DL; the CPU renderer since CPU.1/CPU.2). `None`
967    /// (the default for hosts that don't set it) ⇒ exactly the pre-DL
968    /// render, both backends. The baked brightness byte is
969    /// reinterpreted as the ambient/AO channel; direct light composites
970    /// on top (`albedo*ambient + Σ direct`).
971    pub lights: Option<LightRig<'a>>,
972}
973
974impl<'a> FrameParams<'a> {
975    /// Frame params with sensible defaults for everything except
976    /// [`settings`](Self::settings) (which the host owns): the default
977    /// sky colour ([`RenderOptions::clear_sky`]'s default), no
978    /// panorama, CPU fog off, sprites on, no per-side shading, no
979    /// dynamic lights. Both backends' projection comes from
980    /// `settings` (see the struct docs).
981    ///
982    /// `treat_z_max_as_air` defaults to `true` (what every demo passes;
983    /// out-of-bounds cameras skip the bedrock path). Hosts that want
984    /// the pre-QE literal-struct behaviour set it back to `false`.
985    ///
986    /// Every field stays public — construct with `new` and override
987    /// what differs:
988    ///
989    /// ```ignore
990    /// let mut fp = FrameParams::new(&settings);
991    /// fp.sky = Some(&sky);
992    /// fp.lights = Some(rig);
993    /// ```
994    #[must_use]
995    pub fn new(settings: &'a OpticastSettings) -> Self {
996        let default_sky = RenderOptions::default().clear_sky;
997        Self {
998            settings,
999            sky_color: default_sky,
1000            sky: None,
1001            fog_color: default_sky,
1002            fog_max_scan_dist: 0,
1003            treat_z_max_as_air: true,
1004            draw_sprites: true,
1005            side_shades: [0; 6],
1006            lights: None,
1007        }
1008    }
1009
1010    /// The vertical field of view both backends render `settings`
1011    /// with: `2·atan(yres/2 / hz)` — resolution-independent, so it
1012    /// holds at any window / logical size.
1013    // Screen dims cast to f32 are bounded by realistic resolutions.
1014    #[allow(clippy::cast_precision_loss)]
1015    #[must_use]
1016    pub fn fov_y_rad(&self) -> f32 {
1017        2.0 * ((self.settings.yres as f32) * 0.5 / self.settings.hz).atan()
1018    }
1019
1020    /// The GPU outer-DDA step budget (chunks) derived from
1021    /// [`OpticastSettings::max_scan_dist`]: enough chunk steps to cover
1022    /// the scan distance, plus slack for the entry/exit chunks.
1023    #[allow(clippy::cast_sign_loss)]
1024    #[must_use]
1025    pub fn gpu_outer_steps(&self) -> u32 {
1026        (self.settings.max_scan_dist.max(1) as u32) / roxlap_scene::CHUNK_SIZE_XY + 4
1027    }
1028}
1029
1030/// Backend-agnostic scene bookkeeping the facade owns **once** (QE.3a
1031/// — previously each backend kept a duplicate copy, and every new
1032/// feature needed three coordinated edits: facade arm + cpu + gpu,
1033/// with parity drift as the failure mode: the GPU copy had grown
1034/// change-detection the CPU copy lacked).
1035///
1036/// Backends receive `&SceneState` where they need it (the render
1037/// passes); the truly divergent reactions (CPU flipbook draw, GPU
1038/// instance-buffer/model-id writes, device palette mirror) stay in the
1039/// backends behind small `apply_*` hooks.
1040pub(crate) struct SceneState {
1041    /// Global voxel-material palette (TV stage): per-voxel material
1042    /// ids resolve to opacity + blend mode here. The CPU compositor
1043    /// reads it live each frame; the GPU mirrors it to device
1044    /// palettes when [`materials_dirty`](Self::materials_dirty).
1045    pub(crate) materials: MaterialTable,
1046    /// Terrain colour→material map (TV.4) — matching-colour world
1047    /// voxels render with that material (glass walls, water).
1048    pub(crate) terrain_materials: Vec<(Rgb, u8)>,
1049    /// PF.5 — set when `materials` / `terrain_materials` change;
1050    /// cleared after each `render` (the GPU mirrors device palettes
1051    /// only then). Starts `true` so the first GPU frame seeds them.
1052    pub(crate) materials_dirty: bool,
1053    /// Per **dynamic** instance (parallel to the backends' dynamic
1054    /// sublist): `Some((clip_index, current_frame))` for a clip
1055    /// instance, `None` for a plain model instance. The CPU render
1056    /// picks each instance's flipbook frame from this; the GPU keeps
1057    /// its instance buffer in sync via the `apply_clip_*` hooks.
1058    pub(crate) dyn_clip: Vec<Option<(usize, usize)>>,
1059}
1060
1061impl Default for SceneState {
1062    fn default() -> Self {
1063        Self {
1064            materials: MaterialTable::new(),
1065            terrain_materials: Vec::new(),
1066            materials_dirty: true,
1067            dyn_clip: Vec::new(),
1068        }
1069    }
1070}
1071
1072/// Result of [`SceneRenderer::pick`] — a resolved screen→world voxel
1073/// hit. `world` is the surface point (`cam.pos + t · normalize(ray)`);
1074/// `grid` + `voxel` are the owning grid and its **grid-local** voxel
1075/// (transform-correct for rotated / translated grids).
1076#[derive(Clone, Copy, PartialEq, Debug)]
1077pub struct PickHit {
1078    /// World-space surface point of the hit.
1079    pub world: [f32; 3],
1080    /// The grid owning the hit voxel.
1081    pub grid: roxlap_scene::GridId,
1082    /// The hit voxel, in `grid`-local coordinates.
1083    pub voxel: glam::IVec3,
1084}
1085
1086/// A world-space view ray: the canonical unproject output of
1087/// [`SceneRenderer::view_ray`]. `dir` is unit-length. Feed it straight
1088/// to [`roxlap_scene::Scene::raycast`] for depth-free, backend-agnostic
1089/// voxel picking (`scene.raycast(ray.origin, ray.dir, max_dist)`), or
1090/// intersect it with a plane for tile selection.
1091#[derive(Clone, Copy, PartialEq, Debug)]
1092pub struct Ray {
1093    /// World-space ray origin (the camera position for view rays).
1094    pub origin: glam::DVec3,
1095    /// Unit-length world-space ray direction.
1096    pub dir: glam::DVec3,
1097}
1098
1099/// A world-space line segment to draw over a rendered frame via
1100/// [`SceneRenderer::draw_lines`] — editor gizmos (bounding boxes, floor
1101/// grids, axes, hover wireframes), debug paths, etc.
1102#[derive(Clone, Copy, PartialEq, Debug)]
1103pub struct Line3 {
1104    /// World-space endpoints (voxel units), in the same frame the
1105    /// rendered scene + `camera` use.
1106    pub a: [f64; 3],
1107    /// The segment's other endpoint, same space as `a`.
1108    pub b: [f64; 3],
1109    /// `0xAARRGGBB` — the high byte is an alpha blend factor (`0xFF`
1110    /// opaque, `0x00` invisible), the low 24 bits the RGB colour.
1111    pub color: OverlayColor,
1112    /// Screen-space thickness in pixels (`<= 1.0` draws a 1px line).
1113    pub width_px: f32,
1114    /// `true`: the segment is occluded by nearer rendered geometry
1115    /// (depth-tested against the frame's z-buffer). `false`: always on
1116    /// top (e.g. a hover highlight that should show through the model).
1117    pub depth_test: bool,
1118}
1119
1120/// A handle to an uploaded image-sprite texture, returned by
1121/// [`SceneRenderer::upload_image`]. **Generational** (QE-B6): image
1122/// slots are reused after [`drop_image`](SceneRenderer::drop_image),
1123/// so each handle carries the slot's generation — a stale handle
1124/// (kept across a drop) resolves to a safe no-op instead of aliasing
1125/// whatever texture re-took the slot. Pass it in an [`ImageSprite`]
1126/// for [`SceneRenderer::draw_images`]. Opaque on purpose — there's no
1127/// arithmetic to do on it.
1128#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1129pub struct ImageId {
1130    slot: u32,
1131    gen: u32,
1132}
1133
1134/// QE-B6 — generational guard for image slots. Unlike
1135/// [`EpochSlotMap`] (whose backend indices are append-only), image
1136/// slots ARE reused: `drop_image` frees the texture slot and the next
1137/// upload may take it. Each slot therefore carries its own
1138/// generation; a stale [`ImageId`] resolves to `None`.
1139#[derive(Default)]
1140struct ImageSlotMap {
1141    /// Per backend slot: (current generation, live).
1142    slots: Vec<(u32, bool)>,
1143}
1144
1145impl ImageSlotMap {
1146    /// Register the slot the backend just filled (append or reuse).
1147    fn alloc(&mut self, slot: usize) -> ImageId {
1148        if slot >= self.slots.len() {
1149            self.slots.resize(slot + 1, (0, false));
1150            self.slots[slot] = (0, true);
1151        } else {
1152            let e = &mut self.slots[slot];
1153            e.0 = e.0.wrapping_add(1);
1154            e.1 = true;
1155        }
1156        ImageId {
1157            slot: u32::try_from(slot).expect("image slots fit u32"),
1158            gen: self.slots[slot].0,
1159        }
1160    }
1161
1162    /// Resolve to the backend slot, or `None` when stale / removed.
1163    fn index(&self, id: ImageId) -> Option<usize> {
1164        let e = *self.slots.get(id.slot as usize)?;
1165        (e.0 == id.gen && e.1).then_some(id.slot as usize)
1166    }
1167
1168    /// Tombstone; `false` when the handle was already stale.
1169    fn remove(&mut self, id: ImageId) -> bool {
1170        let Some(e) = self.slots.get_mut(id.slot as usize) else {
1171            return false;
1172        };
1173        if e.0 != id.gen || !e.1 {
1174            return false;
1175        }
1176        e.1 = false;
1177        true
1178    }
1179}
1180
1181/// How an [`ImageSprite`]'s quad is oriented in the world.
1182#[derive(Clone, Copy, PartialEq, Debug)]
1183pub enum ImageFacing {
1184    /// Fixed in world space: the quad lies in the plane spanned by `u`
1185    /// (the image's +column / width direction) and `v` (its +row /
1186    /// height direction). Both are world-space directions; their length
1187    /// is ignored (the quad is sized by [`ImageSprite::size`]), so pass
1188    /// the plane's axes directly. Row 0 of the image is the `origin`
1189    /// edge and rows grow along `v`.
1190    World {
1191        /// World direction of the image's +column (width) axis.
1192        u: [f32; 3],
1193        /// World direction of the image's +row (height) axis.
1194        v: [f32; 3],
1195    },
1196    /// Always faces the camera (billboard); `up` is the world direction
1197    /// the image's top edge points toward (e.g. world `-Z` for the
1198    /// scene-demo's z-down world, or any "up" the host prefers).
1199    Billboard {
1200        /// World direction the image's top edge points toward.
1201        up: [f32; 3],
1202    },
1203}
1204
1205/// One placed 2D image sprite for the current frame: a flat textured
1206/// quad in world space, composited over the rendered scene with the
1207/// frame's depth buffer (so the voxel model can occlude it). Built per
1208/// frame and passed to [`SceneRenderer::draw_images`], mirroring
1209/// [`Line3`] / [`SceneRenderer::draw_lines`]. The texture is uploaded
1210/// once via [`SceneRenderer::upload_image`] and referenced by [`image`].
1211///
1212/// [`image`]: ImageSprite::image
1213#[derive(Clone, Copy, PartialEq, Debug)]
1214pub struct ImageSprite {
1215    /// The uploaded texture to draw (from [`SceneRenderer::upload_image`]).
1216    pub image: ImageId,
1217    /// World position of the quad's **top-left** corner — the image's
1218    /// `(column 0, row 0)` texel. The quad extends `size[0]` along the
1219    /// facing's `u` and `size[1]` along its `v`.
1220    pub origin: [f32; 3],
1221    /// World orientation of the quad — fixed in world or camera-facing.
1222    pub facing: ImageFacing,
1223    /// World size of the quad along `u` and `v`. For pixel-art traced at
1224    /// 1 texel = 1 voxel, pass `[width as f32, height as f32]`.
1225    pub size: [f32; 2],
1226    /// Multiplied into every sampled texel (tint + opacity) — real
1227    /// alpha, so [`OverlayColor`]. `OverlayColor(0xFFFF_FFFF)` draws the
1228    /// texture unchanged; the high byte scales the texel alpha
1229    /// (`OverlayColor(0x80FF_FFFF)` = 50 % opacity).
1230    pub tint: OverlayColor,
1231    /// Alpha cutoff in `0.0..=1.0`. Texels whose **own** alpha is below
1232    /// this are discarded outright (not blended) — crisp pixel-art edges
1233    /// instead of a semi-transparent haze, and the same threshold decides
1234    /// what [`SceneRenderer::pick_image`] treats as solid. `0.0` keeps the
1235    /// plain straight-alpha over-blend (every non-zero texel draws).
1236    pub alpha_cutoff: f32,
1237    /// `true`: occluded by nearer rendered geometry (depth-tested against
1238    /// the frame's depth buffer, with a bias so a quad resting on a
1239    /// coincident voxel face doesn't z-fight). `false`: always on top.
1240    pub depth_test: bool,
1241    /// `true`: draw regardless of which way the quad faces (no backface
1242    /// cull) — what reference images usually want. `false`: cull when the
1243    /// quad faces away from the camera. Ignored for
1244    /// [`ImageFacing::Billboard`] (it always faces the camera).
1245    pub double_sided: bool,
1246}
1247
1248/// Backend-agnostic resolved quad: four world corners (`TL, TR, BL, BR`,
1249/// with UVs `(0,0) (1,0) (0,1) (1,1)`) + the texture to map. The facade
1250/// resolves [`ImageSprite::facing`] into corners and culls back-facing
1251/// quads once, so both backends draw from the same geometry.
1252#[derive(Clone, Copy, Debug)]
1253pub(crate) struct QuadDraw {
1254    pub corners: [[f32; 3]; 4],
1255    /// Backend texture SLOT (facade-resolved; see `draw_images`).
1256    pub image: usize,
1257    pub tint: OverlayColor,
1258    pub depth_test: bool,
1259    pub alpha_cutoff: f32,
1260}
1261
1262/// Result of [`SceneRenderer::pick_image`] — a resolved screen→sprite hit.
1263/// `uv` is the normalised position within the quad (`(0,0)` = top-left
1264/// corner); `texel` is the matching source-image pixel; `world` is the
1265/// hit point; `t` is its euclidean distance from the camera.
1266#[derive(Clone, Copy, PartialEq, Debug)]
1267pub struct ImagePickHit {
1268    /// The hit sprite's texture handle.
1269    pub image: ImageId,
1270    /// Normalised position within the quad (`(0,0)` = top-left).
1271    pub uv: [f32; 2],
1272    /// The matching source-image pixel (column, row).
1273    pub texel: (u32, u32),
1274    /// World-space hit point on the quad.
1275    pub world: [f32; 3],
1276    /// Euclidean distance from the camera to `world`.
1277    pub t: f32,
1278}
1279
1280/// Which renderer a [`SceneRenderer`] resolved to at construction.
1281#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1282pub enum Backend {
1283    /// `roxlap-core` opticast, presented via `softbuffer`.
1284    Cpu,
1285    /// `roxlap-gpu` compute marcher, presented via wgpu.
1286    Gpu,
1287}
1288
1289/// A backend-dependent capability, probed via
1290/// [`SceneRenderer::supports`] (QE.7a). Every method below the parity
1291/// line degrades to a silent no-op on the unsupporting backend; this
1292/// enum turns the tribal knowledge into a queryable answer.
1293///
1294/// | Feature | CPU | GPU |
1295/// |---|---|---|
1296/// | [`Capture`](Self::Capture) | ✅ | ✅ native (❌ wasm — WebGPU can't block) |
1297/// | [`SkyPanorama`](Self::SkyPanorama) | ❌ (use [`FrameParams::sky`]) | ✅ |
1298/// | [`CarveActiveSprite`](Self::CarveActiveSprite) | ❌ | ✅ |
1299/// | [`TranslucentSpriteMaterials`](Self::TranslucentSpriteMaterials) | ✅ | ✅ (TV.3) |
1300/// | [`TranslucentTerrain`](Self::TranslucentTerrain) | ✅ | ✅ (TV.6) |
1301/// | [`FreePickDepth`](Self::FreePickDepth) | ✅ | ❌ (blocking readback) |
1302#[non_exhaustive]
1303#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1304pub enum Feature {
1305    /// [`SceneRenderer::request_capture`] / `take_capture` produce
1306    /// frames.
1307    Capture,
1308    /// [`SceneRenderer::set_sky_panorama`] uploads a sampled sky (the
1309    /// CPU backend samples [`FrameParams::sky`] instead).
1310    SkyPanorama,
1311    /// [`SceneRenderer::carve_active_sprite`] carves.
1312    CarveActiveSprite,
1313    /// Per-voxel / per-instance **sprite** materials composite
1314    /// translucently (an unsupporting backend renders them opaque).
1315    TranslucentSpriteMaterials,
1316    /// [`SceneRenderer::set_terrain_materials`] terrain translucency
1317    /// composites (an unsupporting backend renders terrain opaque).
1318    TranslucentTerrain,
1319    /// [`SceneRenderer::pick_depth`] is cheap enough for per-frame use
1320    /// (an in-memory read). Unsupporting = it works but **blocks** on
1321    /// a device readback — hotkey-grade, not reticle-grade.
1322    FreePickDepth,
1323}
1324
1325/// Which backend [`SceneRenderer::try_new`] should build (QE.7b —
1326/// replaces `RenderOptions.want_gpu: bool`, which couldn't express
1327/// "GPU or fail": headless CI rigs and benchmarks silently fell back
1328/// to a software render and measured the wrong thing).
1329#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
1330pub enum BackendPreference {
1331    /// The CPU renderer, unconditionally (the pre-QE.7 `want_gpu:
1332    /// false`). The default.
1333    #[default]
1334    Cpu,
1335    /// Try the GPU; fall back to CPU with a logged `warn` when WGPU
1336    /// init fails (the pre-QE.7 `want_gpu: true`).
1337    PreferGpu,
1338    /// GPU or [`RenderError::GpuInit`] — no silent software fallback.
1339    /// (The wasm constructor has no `Result` channel and treats this
1340    /// as [`PreferGpu`](Self::PreferGpu).)
1341    RequireGpu,
1342}
1343
1344/// Construction failure from [`SceneRenderer::try_new`] (QE.2b).
1345///
1346/// Under [`BackendPreference::PreferGpu`] a GPU failure is not an
1347/// error (it logs a `warn` and falls back to CPU); `try_new` fails
1348/// when the last-resort CPU surface can't be created, or when
1349/// [`BackendPreference::RequireGpu`] couldn't get its GPU.
1350#[derive(Debug)]
1351pub enum RenderError {
1352    /// The CPU backend couldn't bind its software present surface
1353    /// (softbuffer context/surface creation failed — e.g. a broken or
1354    /// unsupported display connection).
1355    CpuSurface(String),
1356    /// [`BackendPreference::RequireGpu`] and WGPU init failed (QE.7b).
1357    GpuInit(GpuInitError),
1358}
1359
1360impl std::fmt::Display for RenderError {
1361    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1362        match self {
1363            Self::CpuSurface(msg) => write!(f, "CPU present surface init failed: {msg}"),
1364            Self::GpuInit(e) => write!(f, "GPU init failed (RequireGpu, no fallback): {e}"),
1365        }
1366    }
1367}
1368
1369impl std::error::Error for RenderError {
1370    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1371        match self {
1372            Self::GpuInit(e) => Some(e),
1373            Self::CpuSurface(_) => None,
1374        }
1375    }
1376}
1377
1378/// Construction-time options for [`SceneRenderer::new`].
1379///
1380/// # Environment overrides (QE-C6)
1381///
1382/// Each GPU tuning knob below has a `ROXLAP_*` escape hatch, so a
1383/// shipped binary can be re-tuned from the shell. All of them are
1384/// read **once**, at `SceneRenderer` construction (never per frame),
1385/// the env value wins over the programmatic one, and unparseable
1386/// values are dropped with a `log::warn!`. On wasm there is no
1387/// process environment and the field values apply as-is.
1388///
1389/// | variable | overrides | values |
1390/// |---|---|---|
1391/// | `ROXLAP_GPU_POWER` | [`gpu`](Self::gpu)`.power_preference` | `low` / `high` |
1392/// | `ROXLAP_GPU_SPRITE_LOD_PX` | [`gpu_sprite_lod_px`](Self::gpu_sprite_lod_px) | `f32`, screen px |
1393/// | `ROXLAP_GPU_MIP_SCAN_DIST` | [`gpu_mip_scan_dist`](Self::gpu_mip_scan_dist) | `f32`, world units |
1394/// | `ROXLAP_GPU_CHUNK_BUDGET` | [`gpu_chunk_upload_budget`](Self::gpu_chunk_upload_budget) | `u32`, `0` = unbounded |
1395/// | `ROXLAP_GPU_CLIP_BUDGET` | [`gpu_clip_upload_budget`](Self::gpu_clip_upload_budget) | `u32`, `0` = unbounded |
1396///
1397/// Other `ROXLAP_*` variables you may have seen (`ROXLAP_GPU`,
1398/// `ROXLAP_SCENE`, `ROXLAP_CAPTURE`, …) belong to the demo hosts, not
1399/// the library — backend selection is [`backend`](Self::backend),
1400/// decided by *your* code.
1401#[derive(Clone)]
1402pub struct RenderOptions {
1403    /// Which backend to build (QE.7b — replaces `want_gpu: bool`;
1404    /// migrate `want_gpu: true` → [`BackendPreference::PreferGpu`],
1405    /// `false` → [`BackendPreference::Cpu`]).
1406    pub backend: BackendPreference,
1407    /// Settings forwarded to [`roxlap_gpu::GpuRenderer`] when the GPU
1408    /// backend is selected.
1409    pub gpu: GpuRendererSettings,
1410    /// Packed `0x00RRGGBB` (alpha ignored) the empty/clear frame fills
1411    /// with until a scene render lands. Also the CPU sky-miss colour
1412    /// default if a frame supplies none.
1413    pub clear_sky: Rgb,
1414    /// GPU scene-grid LOD scan distance in world units (GPU.11.1):
1415    /// rays farther than this from the camera sample coarser chunk
1416    /// mips. QE.2a — construction-time here (was a per-frame
1417    /// `FrameParams` field); the `ROXLAP_GPU_MIP_SCAN_DIST` env var
1418    /// still overrides it as a user-side escape hatch. Ignored by the
1419    /// CPU backend (its mip ladder comes from
1420    /// [`OpticastSettings::mip_scan_dist`]).
1421    pub gpu_mip_scan_dist: f32,
1422    /// GPU per-frame dirty-chunk install budget (QE.2c — was env-only
1423    /// `ROXLAP_GPU_CHUNK_BUDGET`, which still overrides). Each chunk
1424    /// install issues several `queue.write_buffer` calls; a big batch
1425    /// can exhaust the device staging pool (seen as egui-wgpu panics on
1426    /// Mesa/NVK while flying fast). Small budget = bounded per-frame
1427    /// writes, more terrain pop-in when moving quickly. `0` =
1428    /// unbounded.
1429    pub gpu_chunk_upload_budget: u32,
1430    /// GPU frames-per-staging-flush while registering a flipbook clip
1431    /// (QE.2c — was env-only `ROXLAP_GPU_CLIP_BUDGET`, which still
1432    /// overrides). `0` = unbounded.
1433    pub gpu_clip_upload_budget: u32,
1434    /// GPU sprite mip-LOD threshold (QE.8; `ROXLAP_GPU_SPRITE_LOD_PX`
1435    /// overrides): the pass steps to a coarser sprite mip once a
1436    /// mip-0 voxel would project smaller than this many screen pixels.
1437    /// `1.0` (the default) is the "don't go sub-pixel" threshold and
1438    /// keeps GPU sprites visually identical to the CPU backend (which
1439    /// has no sprite LOD); raise it to trade sprite fidelity for
1440    /// distant-sprite speed (the pre-QE.8 behaviour was `4.0`, which
1441    /// visibly densified thin/hollow translucent models at range).
1442    pub gpu_sprite_lod_px: f32,
1443    /// Unused. Sized the strip-parallel opticast's per-frame scratch
1444    /// pool; the per-pixel DDA renderer that replaced it needs no
1445    /// pre-sizing, so the value is ignored.
1446    #[deprecated(
1447        since = "0.22.0",
1448        note = "ignored — the DDA renderer replaced the strip-parallel \
1449                opticast and needs no scratch-pool pre-sizing"
1450    )]
1451    pub cpu_max_grid_vsid: u32,
1452    /// Unused. Set the strip-parallel opticast's thread count; the DDA
1453    /// renderer parallelises internally over the rayon pool (bound it
1454    /// with `RAYON_NUM_THREADS` if needed), so the value is ignored.
1455    #[deprecated(
1456        since = "0.22.0",
1457        note = "ignored — the DDA renderer parallelises over the rayon \
1458                pool; bound it with RAYON_NUM_THREADS"
1459    )]
1460    pub cpu_render_threads: usize,
1461}
1462
1463// The deprecated fields still have to be constructed until they are
1464// removed for real (QE has a breaking window; see docs/porting/
1465// PORTING-QUALITY.md).
1466#[allow(deprecated)]
1467impl Default for RenderOptions {
1468    fn default() -> Self {
1469        Self {
1470            backend: BackendPreference::Cpu,
1471            gpu: GpuRendererSettings::default(),
1472            clear_sky: Rgb(0x0099_b3d9),
1473            gpu_mip_scan_dist: 64.0,
1474            gpu_chunk_upload_budget: 2,
1475            gpu_clip_upload_budget: 8,
1476            gpu_sprite_lod_px: 1.0,
1477            cpu_max_grid_vsid: 32 * roxlap_scene::CHUNK_SIZE_XY,
1478            cpu_render_threads: 4,
1479        }
1480    }
1481}
1482
1483/// Depth-test slack (same spirit as the backends' `DEPTH_BIAS`) so a
1484/// [`SceneRenderer::pick_image`] hit on a sprite resting on a coincident
1485/// voxel face isn't rejected as "occluded".
1486const PICK_DEPTH_BIAS: f32 = 0.5;
1487
1488// --- image-sprite geometry helpers (shared by both backends) ---
1489
1490fn v_sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
1491    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
1492}
1493fn v_add(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
1494    [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
1495}
1496fn v_scale(a: [f32; 3], s: f32) -> [f32; 3] {
1497    [a[0] * s, a[1] * s, a[2] * s]
1498}
1499fn v_dot(a: [f32; 3], b: [f32; 3]) -> f32 {
1500    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
1501}
1502fn v_cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
1503    [
1504        a[1] * b[2] - a[2] * b[1],
1505        a[2] * b[0] - a[0] * b[2],
1506        a[0] * b[1] - a[1] * b[0],
1507    ]
1508}
1509fn v_norm(a: [f32; 3]) -> [f32; 3] {
1510    let len = v_dot(a, a).sqrt();
1511    if len < 1e-12 {
1512        a
1513    } else {
1514        v_scale(a, 1.0 / len)
1515    }
1516}
1517
1518/// Intersect a ray (`origin` + `dir`, `dir` un-normalised) with a quad
1519/// `[TL, TR, BL, BR]` and return `(uv, t)` for a front/back hit inside
1520/// the quad — `uv` in `0..=1` (`(0,0)` = `TL`), `t` the ray parameter
1521/// (`hit = origin + dir·t`). `None` for a parallel ray, a hit behind the
1522/// origin, a degenerate quad, or a hit outside the `u`/`v` span. Solves
1523/// affine coords exactly for a (possibly skew) parallelogram. Standalone
1524/// so the geometry is unit-testable without a renderer.
1525fn ray_quad_uv(
1526    origin: [f32; 3],
1527    dir: [f32; 3],
1528    corners: &[[f32; 3]; 4],
1529) -> Option<([f32; 2], f32)> {
1530    let [tl, tr, bl, _br] = *corners;
1531    let ue = v_sub(tr, tl); // +u edge (width)
1532    let ve = v_sub(bl, tl); // +v edge (height)
1533    let n = v_cross(ue, ve);
1534    let denom = v_dot(dir, n);
1535    if denom.abs() < 1e-12 {
1536        return None; // ray parallel to the quad's plane
1537    }
1538    let t = v_dot(v_sub(tl, origin), n) / denom;
1539    if t <= 1e-6 {
1540        return None; // behind / at the origin
1541    }
1542    let p = v_add(origin, v_scale(dir, t));
1543    let rel = v_sub(p, tl);
1544    let guu = v_dot(ue, ue);
1545    let guv = v_dot(ue, ve);
1546    let gvv = v_dot(ve, ve);
1547    let det = guu * gvv - guv * guv;
1548    if det.abs() < 1e-12 {
1549        return None; // degenerate quad
1550    }
1551    let wu = v_dot(rel, ue);
1552    let wv = v_dot(rel, ve);
1553    let a = (gvv * wu - guv * wv) / det;
1554    let b = (guu * wv - guv * wu) / det;
1555    if !(0.0..=1.0).contains(&a) || !(0.0..=1.0).contains(&b) {
1556        return None; // outside the quad
1557    }
1558    Some(([a, b], t))
1559}
1560
1561/// Resolve an [`ImageSprite`] into its four world corners (`TL, TR, BL,
1562/// BR`), or `None` when a `double_sided == false` world quad faces away
1563/// from the camera (back-face cull) or its plane is degenerate. The
1564/// camera basis is used only for [`ImageFacing::Billboard`] and the cull
1565/// test.
1566fn resolve_quad(sprite: &ImageSprite, camera: &Camera) -> Option<QuadDraw> {
1567    let cam_pos = [
1568        camera.pos[0] as f32,
1569        camera.pos[1] as f32,
1570        camera.pos[2] as f32,
1571    ];
1572    let cam_fwd = v_norm([
1573        camera.forward[0] as f32,
1574        camera.forward[1] as f32,
1575        camera.forward[2] as f32,
1576    ]);
1577
1578    let (u_hat, v_hat) = match sprite.facing {
1579        ImageFacing::World { u, v } => (v_norm(u), v_norm(v)),
1580        ImageFacing::Billboard { up } => {
1581            // Horizontal axis ⟂ both the view direction and `up`; fall
1582            // back to the camera right when `up` is parallel to the view.
1583            let mut u_hat = v_norm(v_cross(up, cam_fwd));
1584            if v_dot(u_hat, u_hat) < 1e-12 {
1585                u_hat = v_norm([
1586                    camera.right[0] as f32,
1587                    camera.right[1] as f32,
1588                    camera.right[2] as f32,
1589                ]);
1590            }
1591            // Vertical axis ⟂ both, pointing *down* (rows grow downward)
1592            // so the top edge ends up toward `up`.
1593            let mut v_hat = v_norm(v_cross(cam_fwd, u_hat));
1594            if v_dot(v_hat, up) > 0.0 {
1595                v_hat = v_scale(v_hat, -1.0);
1596            }
1597            (u_hat, v_hat)
1598        }
1599    };
1600
1601    let du = v_scale(u_hat, sprite.size[0]);
1602    let dv = v_scale(v_hat, sprite.size[1]);
1603    let tl = sprite.origin;
1604    let tr = v_add(tl, du);
1605    let bl = v_add(tl, dv);
1606    let br = v_add(tr, dv);
1607
1608    // Back-face cull for fixed world quads (billboards always face us).
1609    if !sprite.double_sided {
1610        if let ImageFacing::World { .. } = sprite.facing {
1611            let normal = v_cross(du, dv);
1612            // Front-facing when the quad normal points toward the camera.
1613            if v_dot(normal, v_sub(cam_pos, tl)) <= 0.0 {
1614                return None;
1615            }
1616        }
1617    }
1618
1619    Some(QuadDraw {
1620        corners: [tl, tr, bl, br],
1621        image: 0, // placeholder — draw_images resolves the real slot
1622        tint: sprite.tint,
1623        depth_test: sprite.depth_test,
1624        alpha_cutoff: sprite.alpha_cutoff,
1625    })
1626}
1627
1628/// Where the per-pixel raycaster actually runs, decoupled from the window
1629/// size (RP.0). Both backends are per-pixel marchers, so frame cost scales
1630/// with the pixel count — rendering into a fixed **logical** target and
1631/// nearest-upscaling it to the window makes FPS independent of window size
1632/// and creates the seam for the later posterize / SSAA post (RP.1/RP.2).
1633///
1634/// The default ([`Native`](RenderResolution::Native)) keeps `logical == window`
1635/// and is **byte-identical** to the pre-RP straight blit.
1636#[derive(Clone, Copy, Debug, PartialEq, Default)]
1637pub enum RenderResolution {
1638    /// Logical resolution == window. Default. Identical to pre-RP behaviour.
1639    #[default]
1640    Native,
1641    /// Fixed logical grid, independent of the window (the retro pixel grid).
1642    /// Upscaled to the window with nearest sampling (hard pixels). A logical
1643    /// aspect ratio different from the window's stretches non-uniformly — a
1644    /// deliberate, classic fixed-res look (no letterbox in RP.0).
1645    Fixed {
1646        /// Logical framebuffer width, pixels.
1647        w: u32,
1648        /// Logical framebuffer height, pixels.
1649        h: u32,
1650    },
1651    /// Logical = `round(window * factor)`. `0.5` ⇒ a quarter of the pixels,
1652    /// aspect preserved. Clamped to `>= 1px` per axis.
1653    Scale(f32),
1654}
1655
1656impl RenderResolution {
1657    /// Resolve to a concrete logical pixel size given the current window
1658    /// (native) size. Always `>= 1` per axis.
1659    #[must_use]
1660    pub(crate) fn logical_for(self, native: (u32, u32)) -> (u32, u32) {
1661        let (nw, nh) = (native.0.max(1), native.1.max(1));
1662        match self {
1663            Self::Native => (nw, nh),
1664            Self::Fixed { w, h } => (w.max(1), h.max(1)),
1665            Self::Scale(f) => {
1666                let s = f.max(1e-3);
1667                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1668                let lw = ((nw as f32) * s).round() as u32;
1669                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1670                let lh = ((nh as f32) * s).round() as u32;
1671                (lw.max(1), lh.max(1))
1672            }
1673        }
1674    }
1675}
1676
1677/// Dither applied before the posterize quantization (RP.2), to break up
1678/// banding and turn it into a stable retro pattern instead of crawling edges.
1679/// Indexed by the *logical* pixel, so each hard pixel still resolves to one
1680/// colour.
1681#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1682pub enum DitherMode {
1683    /// No dither — plain round-to-nearest quantization (hard banding).
1684    #[default]
1685    None,
1686    /// Classic `4×4` ordered (Bayer) dither — the cross-hatch console look.
1687    Bayer4x4,
1688    /// Interleaved-gradient noise — a cheap, texture-free blue-noise-ish
1689    /// stochastic dither (finer than Bayer, no repeating grid).
1690    BlueNoise,
1691}
1692
1693/// Reduced-palette post (RP.2), applied at the logical resolution in the
1694/// resolve step (after the SSAA box-downfilter, before the nearest upscale).
1695/// Each channel is quantized to its own number of levels; `levels <= 1` leaves
1696/// that channel untouched. `None` posterize ⇒ the RP.0/RP.1 paths verbatim.
1697#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1698pub struct PosterizeConfig {
1699    /// Quantisation levels for the red channel (≥ 2).
1700    pub levels_r: u8,
1701    /// Quantisation levels for the green channel (≥ 2).
1702    pub levels_g: u8,
1703    /// Quantisation levels for the blue channel (≥ 2).
1704    pub levels_b: u8,
1705    /// Dither pattern applied before quantisation.
1706    pub dither: DitherMode,
1707}
1708
1709impl PosterizeConfig {
1710    /// Uniform per-channel level count with the given dither.
1711    #[must_use]
1712    pub fn uniform(levels: u8, dither: DitherMode) -> Self {
1713        Self {
1714            levels_r: levels,
1715            levels_g: levels,
1716            levels_b: levels,
1717            dither,
1718        }
1719    }
1720}
1721
1722/// Renderer-internal backend; never exposes wgpu or softbuffer types.
1723/// The GPU variant owns the whole wgpu device/queue/pipelines, so
1724/// it's boxed to keep the enum small.
1725enum BackendImpl {
1726    // Both variants boxed so the enum stays small regardless of which
1727    // backend's state is larger (clippy::large_enum_variant).
1728    Cpu(Box<CpuBackend>),
1729    Gpu(Box<GpuBackend>),
1730}
1731
1732/// Unified renderer over the CPU and GPU paths. See the crate docs.
1733pub struct SceneRenderer {
1734    inner: BackendImpl,
1735    /// Handles for dynamically added sprite instances (see
1736    /// [`Self::add_sprite_instance`]). Reset by [`Self::set_sprites`].
1737    dyn_map: DynInstanceMap,
1738    /// Handles for registered sprite models (see [`Self::add_sprite_model`]
1739    /// and the models returned by [`Self::set_sprites`]). Reset by
1740    /// [`Self::set_sprites`].
1741    model_map: EpochSlotMap<SpriteModelId>,
1742    /// Handles for registered animated voxel clips (see
1743    /// [`Self::add_voxel_clip`]). Reset by [`Self::set_sprites`].
1744    clip_map: EpochSlotMap<VoxelClipId>,
1745    /// Handles for registered animated characters (see
1746    /// [`Self::add_character`]). Reset by [`Self::set_sprites`].
1747    char_map: EpochSlotMap<CharacterId>,
1748    /// Live character runtimes, parallel to `char_map` slots (VCL.6).
1749    char_instances: Vec<CharInstance>,
1750    /// Handles for registered streaming clips (see
1751    /// [`Self::add_streaming_clip`]). Reset by [`Self::set_sprites`].
1752    streaming_map: EpochSlotMap<StreamingClipId>,
1753    /// Streaming-clip runtimes (cursor + one re-uploaded model), parallel
1754    /// to `streaming_map` slots; `None` once removed (#3).
1755    streaming_clips: Vec<Option<StreamingClipState>>,
1756    /// Metadata per registered flipbook clip, indexed by the backend clip
1757    /// index (parallel to `clip_map`). Captured at [`Self::add_voxel_clip`]
1758    /// so the editor queries ([`Self::clip_metadata`]) + the auto-player
1759    /// don't have to re-pass / shadow the `DecodedClip`. Reset by
1760    /// [`Self::set_sprites`].
1761    clip_meta: Vec<ClipMeta>,
1762    /// Auto-advancing clip players (#6); ticked by
1763    /// [`Self::advance_voxel_clips`]. Reset by [`Self::set_sprites`].
1764    clip_players: Vec<ClipPlayer>,
1765    /// Camera-facing billboard instances (BB.2): each carries its world
1766    /// position + mode, re-oriented every [`Self::face_billboards_to`].
1767    /// Reset by [`Self::set_sprites`].
1768    billboards: Vec<BillboardRec>,
1769    /// Handles for high-level directional billboard actors (BB.4). Reset by
1770    /// [`Self::set_sprites`].
1771    actor_map: EpochSlotMap<BillboardActorId>,
1772    /// Live billboard-actor runtimes, parallel to `actor_map` slots; `None`
1773    /// once removed. Driven by [`Self::update_billboard_actors`].
1774    billboard_actors: Vec<Option<BillboardActor>>,
1775    /// QE.3a - the once-per-facade scene bookkeeping both backends
1776    /// read (materials, terrain map, clip-instance frames).
1777    state: SceneState,
1778    /// QE-B6 — generational image-slot guard (see [`ImageSlotMap`]).
1779    image_map: ImageSlotMap,
1780}
1781
1782impl SceneRenderer {
1783    /// Wrap a constructed backend with the facade's (empty) handle
1784    /// registries — the shared tail of every constructor.
1785    fn from_backend(inner: BackendImpl) -> Self {
1786        Self {
1787            inner,
1788            image_map: ImageSlotMap::default(),
1789            dyn_map: DynInstanceMap::default(),
1790            model_map: EpochSlotMap::default(),
1791            clip_map: EpochSlotMap::default(),
1792            char_map: EpochSlotMap::default(),
1793            char_instances: Vec::new(),
1794            streaming_map: EpochSlotMap::default(),
1795            streaming_clips: Vec::new(),
1796            clip_meta: Vec::new(),
1797            clip_players: Vec::new(),
1798            billboards: Vec::new(),
1799            actor_map: EpochSlotMap::default(),
1800            billboard_actors: Vec::new(),
1801            state: SceneState::default(),
1802        }
1803    }
1804
1805    /// Build a renderer for `window` — any [`raw-window-handle`]
1806    /// provider (winit, SDL, GLFW, …) in an `Arc`. `size` is the
1807    /// window's initial physical framebuffer size in pixels; thereafter
1808    /// the host reports changes via [`Self::resize`]. Passing the size
1809    /// explicitly keeps the facade decoupled from any one windowing
1810    /// library's size API.
1811    ///
1812    /// Builds the backend [`opts.backend`](RenderOptions::backend)
1813    /// asks for. Under [`BackendPreference::PreferGpu`] a WGPU-init
1814    /// failure falls back to the CPU backend with a `warn` through
1815    /// the [`log`] facade (install a logger like `env_logger` to see
1816    /// why a machine is software-rendering);
1817    /// [`BackendPreference::RequireGpu`] turns that failure into an
1818    /// error instead (QE.7b — headless CI / benchmark rigs must not
1819    /// silently measure a software render).
1820    ///
1821    /// # Errors
1822    /// [`RenderError::CpuSurface`] — the last-resort softbuffer
1823    /// context/surface couldn't bind to `window`;
1824    /// [`RenderError::GpuInit`] — `RequireGpu` and WGPU init failed.
1825    ///
1826    /// [`raw-window-handle`]: raw_window_handle
1827    #[cfg(not(target_arch = "wasm32"))]
1828    pub fn try_new<W>(
1829        window: Arc<W>,
1830        size: (u32, u32),
1831        opts: &RenderOptions,
1832    ) -> Result<Self, RenderError>
1833    where
1834        W: HasWindowHandle + HasDisplayHandle + Send + Sync + 'static,
1835    {
1836        // QE-C6 — resolve `ROXLAP_*` env overrides once, here, and
1837        // thread plain options into the backends (no env reads below).
1838        let opts = &env_config::EnvOverrides::from_env().applied(opts);
1839        if opts.backend != BackendPreference::Cpu {
1840            match GpuBackend::new(window.clone(), size, opts) {
1841                Ok(g) => return Ok(Self::from_backend(BackendImpl::Gpu(Box::new(g)))),
1842                Err(e) if opts.backend == BackendPreference::RequireGpu => {
1843                    return Err(RenderError::GpuInit(e));
1844                }
1845                Err(e) => {
1846                    log::warn!("GPU init failed ({e}); falling back to the CPU renderer");
1847                }
1848            }
1849        }
1850        let cpu = CpuBackend::try_new(window, size, opts)?;
1851        Ok(Self::from_backend(BackendImpl::Cpu(Box::new(cpu))))
1852    }
1853
1854    /// Infallible [`Self::try_new`]: **panics** if even the CPU
1855    /// software surface can't be created — the convenient default for
1856    /// demos and tools, where "no window surface at all" has no
1857    /// meaningful recovery. Games that want to show their own error UI
1858    /// call [`try_new`](Self::try_new).
1859    ///
1860    /// # Panics
1861    /// When [`Self::try_new`] returns [`RenderError::CpuSurface`].
1862    #[cfg(not(target_arch = "wasm32"))]
1863    #[must_use]
1864    pub fn new<W>(window: Arc<W>, size: (u32, u32), opts: &RenderOptions) -> Self
1865    where
1866        W: HasWindowHandle + HasDisplayHandle + Send + Sync + 'static,
1867    {
1868        match Self::try_new(window, size, opts) {
1869            Ok(r) => r,
1870            Err(e) => panic!("SceneRenderer::new: {e} (use try_new to handle this)"),
1871        }
1872    }
1873
1874    /// wasm/WebGPU build-time entry: build a renderer over an HTML
1875    /// `canvas`. `size` is the canvas's initial framebuffer size in
1876    /// pixels; the host reports later changes via [`Self::resize`].
1877    ///
1878    /// Async because the browser drives wgpu's adapter/device requests
1879    /// through its event loop — `await` it inside a
1880    /// `wasm_bindgen_futures::spawn_local` task. Selects the GPU
1881    /// (WebGPU) backend when `opts.backend` asks for GPU and WebGPU is
1882    /// available (`RequireGpu` degrades to `PreferGpu` here — no
1883    /// `Result` channel in the async wasm constructor);
1884    /// otherwise (no WebGPU, or init failed) it falls back to the CPU
1885    /// opticast path presented through a WebGL2 blit on the same canvas.
1886    /// **Never fails** — the message is logged to the browser console.
1887    #[cfg(target_arch = "wasm32")]
1888    pub async fn new_from_canvas_async(
1889        canvas: web_sys::HtmlCanvasElement,
1890        size: (u32, u32),
1891        opts: &RenderOptions,
1892    ) -> Self {
1893        // QE-C6 mirror of the native path; on wasm every override is
1894        // `None` (no process environment), so this is a plain copy.
1895        let opts = &env_config::EnvOverrides::from_env().applied(opts);
1896        if opts.backend != BackendPreference::Cpu {
1897            // `SurfaceTarget::Canvas` moves the canvas into wgpu, so the
1898            // GPU attempt gets a clone — the CPU fallback keeps the
1899            // original if WebGPU init fails.
1900            match GpuBackend::new_async(canvas.clone(), size, opts).await {
1901                Ok(g) => return Self::from_backend(BackendImpl::Gpu(Box::new(g))),
1902                Err(e) => {
1903                    web_sys::console::warn_1(
1904                        &format!("roxlap-render: WebGPU init failed ({e}); using the CPU renderer")
1905                            .into(),
1906                    );
1907                }
1908            }
1909        }
1910        Self::from_backend(BackendImpl::Cpu(Box::new(CpuBackend::new_from_canvas(
1911            canvas, size, opts,
1912        ))))
1913    }
1914
1915    /// Which backend was selected.
1916    #[must_use]
1917    pub fn backend(&self) -> Backend {
1918        match self.inner {
1919            BackendImpl::Cpu(_) => Backend::Cpu,
1920            BackendImpl::Gpu(_) => Backend::Gpu,
1921        }
1922    }
1923
1924    /// Whether the active backend supports `feature` (QE.7a) — the
1925    /// queryable form of the parity table on [`Feature`]. Methods on
1926    /// the "❌" side stay callable and degrade to documented no-ops;
1927    /// use this to pick a strategy up front (e.g. photo mode: capture
1928    /// vs "not available on this platform").
1929    #[must_use]
1930    pub fn supports(&self, feature: Feature) -> bool {
1931        let gpu = matches!(self.inner, BackendImpl::Gpu(_));
1932        match feature {
1933            Feature::Capture => {
1934                // GPU capture is a blocking readback — native only.
1935                !gpu || cfg!(not(target_arch = "wasm32"))
1936            }
1937            Feature::SkyPanorama | Feature::CarveActiveSprite => gpu,
1938            // Translucency landed on BOTH backends in the TV stage
1939            // (TV.3 sprites / TV.6 terrain, GPU visually verified);
1940            // QE.7a shipped this table stale — saying `!gpu` — and the
1941            // author re-confirmed the GPU paths before this fix.
1942            Feature::TranslucentSpriteMaterials | Feature::TranslucentTerrain => true,
1943            Feature::FreePickDepth => !gpu,
1944        }
1945    }
1946
1947    /// The GPU adapter description when on the GPU backend, else
1948    /// `None`.
1949    #[must_use]
1950    pub fn adapter_info(&self) -> Option<&str> {
1951        match &self.inner {
1952            BackendImpl::Gpu(g) => Some(g.adapter_info()),
1953            BackendImpl::Cpu(_) => None,
1954        }
1955    }
1956
1957    /// `true` when this renderer runs on modest hardware: the CPU
1958    /// backend, or a GPU adapter that is not a discrete card
1959    /// (integrated / software / virtual). A hint for hosts to pick a
1960    /// lighter default render resolution — never consulted internally.
1961    #[must_use]
1962    pub fn is_low_power(&self) -> bool {
1963        match &self.inner {
1964            BackendImpl::Cpu(_) => true,
1965            BackendImpl::Gpu(g) => g.low_power(),
1966        }
1967    }
1968
1969    /// Upload an equirectangular sky panorama (RGBA8, `w×h`) for the
1970    /// GPU marcher's sky sampling. No-op on the CPU backend, which
1971    /// samples the [`Sky`] passed in each [`FrameParams`] instead.
1972    pub fn set_sky_panorama(&mut self, rgba: &[u8], w: u32, h: u32) {
1973        if let BackendImpl::Gpu(g) = &mut self.inner {
1974            g.set_sky_panorama(rgba, w, h);
1975        }
1976    }
1977
1978    /// Follow a window resize. CPU resizes its framebuffer lazily, so
1979    /// this only matters to the GPU swapchain — but it's safe to call
1980    /// for both.
1981    pub fn resize(&mut self, width: u32, height: u32) {
1982        match &mut self.inner {
1983            BackendImpl::Cpu(c) => c.resize(width, height),
1984            BackendImpl::Gpu(g) => g.resize(width, height),
1985        }
1986    }
1987
1988    /// Set the logical (fixed) render resolution (RP.0). The scene marches at
1989    /// the resolved logical size and is nearest-upscaled to the window, so the
1990    /// raycaster's cost — and thus FPS — stops depending on the window size.
1991    /// [`RenderResolution::Native`] (the default) keeps `logical == window`
1992    /// and is byte-identical to pre-RP rendering. Takes effect from the next
1993    /// [`render`](Self::render).
1994    pub fn set_render_resolution(&mut self, res: RenderResolution) {
1995        match &mut self.inner {
1996            BackendImpl::Cpu(c) => c.set_render_resolution(res),
1997            BackendImpl::Gpu(g) => g.set_render_resolution(res),
1998        }
1999    }
2000
2001    /// Set the supersampling factor (RP.1). `1` = off; `2` marches `2×2`
2002    /// samples per logical pixel and box-downfilters back before the upscale,
2003    /// anti-aliasing the retro grid. Clamped to `1..=4`. The marcher then runs
2004    /// at `logical_dims × factor` — predictable cost, independent of the window
2005    /// size. Takes effect from the next [`render`](Self::render).
2006    pub fn set_ssaa(&mut self, factor: u8) {
2007        match &mut self.inner {
2008            BackendImpl::Cpu(c) => c.set_ssaa(factor),
2009            BackendImpl::Gpu(g) => g.set_ssaa(factor),
2010        }
2011    }
2012
2013    /// The resolution the raycaster actually runs at this frame —
2014    /// `logical_dims × ssaa` (RP.1). Reflects the most recent window size,
2015    /// [`RenderResolution`], and SSAA factor.
2016    #[must_use]
2017    pub fn render_dims(&self) -> (u32, u32) {
2018        match &self.inner {
2019            BackendImpl::Cpu(c) => c.render_dims(),
2020            BackendImpl::Gpu(g) => g.render_dims(),
2021        }
2022    }
2023
2024    /// Set the reduced-palette posterize post (RP.2), or `None` to disable it
2025    /// (the default — RP.0/RP.1 paths verbatim). Quantization runs at the
2026    /// logical resolution in the resolve step, after the SSAA downfilter and
2027    /// before the nearest upscale, with the configured dither. Takes effect
2028    /// from the next [`render`](Self::render).
2029    pub fn set_posterize(&mut self, cfg: Option<PosterizeConfig>) {
2030        match &mut self.inner {
2031            BackendImpl::Cpu(c) => c.set_posterize(cfg),
2032            BackendImpl::Gpu(g) => g.set_posterize(cfg),
2033        }
2034    }
2035
2036    /// The logical (fixed) render-target size resolved against the current
2037    /// window size, per the active [`RenderResolution`].
2038    #[must_use]
2039    pub fn logical_dims(&self) -> (u32, u32) {
2040        match &self.inner {
2041            BackendImpl::Cpu(c) => c.logical_dims(),
2042            BackendImpl::Gpu(g) => g.logical_dims(),
2043        }
2044    }
2045
2046    /// One-call per-frame animation tick (QE.1b): drives **every**
2047    /// facade-owned animated collection, replacing the multi-call
2048    /// protocol hosts previously had to know (and could silently get
2049    /// wrong — a missed call meant frozen clips or unfaced
2050    /// billboards). Call once per frame before [`render`](Self::render):
2051    ///
2052    /// 1. [`advance_voxel_clips`](Self::advance_voxel_clips) —
2053    ///    auto-playing flipbook + streaming clip players;
2054    /// 2. every live character — skeleton + clip attachments (the
2055    ///    all-characters sweep of
2056    ///    [`advance_character`](Self::advance_character));
2057    /// 3. [`update_billboard_actors`](Self::update_billboard_actors) —
2058    ///    actor direction/state clips + camera facing;
2059    /// 4. [`face_billboards_to`](Self::face_billboards_to) — plain
2060    ///    billboard instances.
2061    ///
2062    /// The fine-grained methods stay public for hosts that need a
2063    /// custom per-entity `dt` (slow-motion on one character) or their
2064    /// own ordering — `tick` is the "do the right thing" default and
2065    /// is exactly equivalent to calling them in the order above.
2066    /// KFA sprites driven via
2067    /// [`update_kfa_poses`](Self::update_kfa_poses) remain a separate
2068    /// call (they mutate host-owned skeletons).
2069    pub fn tick(&mut self, camera: &Camera, dt: f64) {
2070        self.advance_voxel_clips(dt);
2071        let live: Vec<usize> = self.char_map.live_indices().collect();
2072        for idx in live {
2073            self.advance_character_at(idx, dt);
2074        }
2075        self.update_billboard_actors(camera, dt);
2076        self.face_billboards_to(camera);
2077    }
2078
2079    /// Composite `scene` from `camera` with `frame` params into the
2080    /// backend's frame buffer — **without presenting**. The CPU backend
2081    /// fills sky + runs the opticast compositor into an owned buffer;
2082    /// the GPU backend uploads/refreshes the scene, runs the compute
2083    /// marcher + sprite pass, and acquires (but does not present) the
2084    /// swapchain frame.
2085    ///
2086    /// Finish the frame with exactly one of [`present`](Self::present)
2087    /// (no overlay) or [`paint_egui`](Self::paint_egui) (UI overlay).
2088    /// Calling `render` again without finishing drops the pending frame.
2089    pub fn render(&mut self, scene: &mut Scene, camera: &Camera, frame: &FrameParams) {
2090        match &mut self.inner {
2091            BackendImpl::Cpu(c) => c.render(scene, camera, frame, &self.state),
2092            BackendImpl::Gpu(g) => g.render(scene, camera, frame, &self.state),
2093        }
2094        // The GPU mirrored its device palettes this frame if it needed
2095        // to; the CPU reads the table live. Either way the change flag
2096        // is consumed.
2097        self.state.materials_dirty = false;
2098    }
2099
2100    /// Draw world-space [`Line3`] segments over the frame
2101    /// [`render`](Self::render) composited, using that frame's camera +
2102    /// projection + depth buffer. Call **after** [`render`](Self::render)
2103    /// and **before** [`present`](Self::present) /
2104    /// [`paint_egui`](Self::paint_egui) — the lines land in the
2105    /// framebuffer, so a subsequent `paint_egui` still draws its panels
2106    /// on top.
2107    ///
2108    /// `camera` must be the one the last frame rendered with (the
2109    /// projection is taken from that frame). Depth-tested segments
2110    /// (`Line3::depth_test`) are occluded by nearer rendered geometry;
2111    /// always-on-top segments ignore depth. See [`Line3`] for colour /
2112    /// width / blend semantics.
2113    pub fn draw_lines(&mut self, camera: &Camera, lines: &[Line3]) {
2114        match &mut self.inner {
2115            BackendImpl::Cpu(c) => c.draw_lines(camera, lines),
2116            BackendImpl::Gpu(g) => g.draw_lines(camera, lines),
2117        }
2118    }
2119
2120    /// Upload (or replace) an RGBA8 image and return a stable [`ImageId`]
2121    /// to reference it in [`draw_images`](Self::draw_images). `rgba` is
2122    /// row-major, `width * height * 4` bytes, **straight** (un-premultiplied)
2123    /// alpha. The texture is retained until [`drop_image`](Self::drop_image),
2124    /// so the per-frame draw call stays cheap. Sampling is
2125    /// nearest-neighbour (pixel-art friendly — no blurring).
2126    ///
2127    /// Returns `None` for malformed input — a wrong byte count
2128    /// (`!= width·height·4`) or a zero dimension — so a bad upload can't be
2129    /// confused with the first valid id (`ImageId(0)`).
2130    pub fn upload_image(&mut self, rgba: &[u8], width: u32, height: u32) -> Option<ImageId> {
2131        if width == 0 || height == 0 || rgba.len() != (width as usize) * (height as usize) * 4 {
2132            return None;
2133        }
2134        let slot = match &mut self.inner {
2135            BackendImpl::Cpu(c) => c.upload_image(rgba, width, height),
2136            BackendImpl::Gpu(g) => g.upload_image(rgba, width, height),
2137        };
2138        Some(self.image_map.alloc(slot))
2139    }
2140
2141    /// Release a texture uploaded with [`upload_image`](Self::upload_image).
2142    /// Stale handles (already dropped, or aliasing a reused slot) are a
2143    /// safe no-op — ids are generational since QE-B6.
2144    pub fn drop_image(&mut self, id: ImageId) {
2145        let Some(slot) = self.image_map.index(id) else {
2146            return;
2147        };
2148        self.image_map.remove(id);
2149        match &mut self.inner {
2150            BackendImpl::Cpu(c) => c.drop_image(slot),
2151            BackendImpl::Gpu(g) => g.drop_image(slot),
2152        }
2153    }
2154
2155    /// Draw 2D [`ImageSprite`]s over the frame [`render`](Self::render)
2156    /// composited — flat textured quads placed in world space, using that
2157    /// frame's camera + projection + depth buffer. Same contract as
2158    /// [`draw_lines`](Self::draw_lines): call **after** [`render`](Self::render)
2159    /// and **before** [`present`](Self::present) / [`paint_egui`](Self::paint_egui).
2160    ///
2161    /// UVs are perspective-correct (no affine warp on an obliquely-viewed
2162    /// quad). Depth-tested sprites are occluded by nearer rendered
2163    /// geometry (with a bias to avoid z-fighting on a coincident face);
2164    /// the texture's straight alpha + the [`ImageSprite::tint`] composite
2165    /// over the scene. `camera` must be the one the last frame rendered.
2166    pub fn draw_images(&mut self, camera: &Camera, images: &[ImageSprite]) {
2167        if images.is_empty() {
2168            return;
2169        }
2170        let quads: Vec<QuadDraw> = images
2171            .iter()
2172            .filter_map(|s| {
2173                // QE-B6 — stale image handles draw nothing (vs aliasing
2174                // whatever texture reused the slot).
2175                let slot = self.image_map.index(s.image)?;
2176                let mut q = resolve_quad(s, camera)?;
2177                q.image = slot;
2178                Some(q)
2179            })
2180            .collect();
2181        if quads.is_empty() {
2182            return;
2183        }
2184        match &mut self.inner {
2185            BackendImpl::Cpu(c) => c.draw_images(camera, &quads),
2186            BackendImpl::Gpu(g) => g.draw_images(camera, &quads),
2187        }
2188    }
2189
2190    /// Project a world point to window pixel coordinates `(x, y)` under
2191    /// the projection the **last frame** rendered with — the backend-correct
2192    /// `world → screen` inverse of [`view_ray`](Self::view_ray). `None`
2193    /// before the first frame or for a point at/behind the camera near
2194    /// plane.
2195    ///
2196    /// Both backends honour their own projection (CPU `setcamera`
2197    /// `hx/hy/hz`, GPU vertical-FOV pinhole), so hosts never reconstruct
2198    /// it themselves. The returned `(x, y)` may fall outside `[0, w) ×
2199    /// [0, h)` for points off-screen but in front of the camera.
2200    #[must_use]
2201    pub fn project_point(&self, camera: &Camera, world: [f32; 3]) -> Option<(f32, f32)> {
2202        match &self.inner {
2203            BackendImpl::Cpu(c) => c.project_point(camera, world),
2204            BackendImpl::Gpu(g) => g.project_point(camera, world),
2205        }
2206    }
2207
2208    /// Screen→sprite pick: the nearest [`ImageSprite`] hit under window
2209    /// pixel `(x, y)`, resolving which texel was clicked. `sprites` is the
2210    /// same list passed to [`draw_images`](Self::draw_images) (image
2211    /// sprites are immediate-mode, so the caller owns the set). `None` for
2212    /// a miss.
2213    ///
2214    /// The ray is intersected with each quad's plane and mapped to its
2215    /// `uv` / source texel. A texel whose alpha is below the sprite's
2216    /// [`ImageSprite::alpha_cutoff`] (and any fully-transparent texel) is
2217    /// **see-through** — the pick passes through it to a sprite behind.
2218    /// For [`depth_test`](ImageSprite::depth_test) sprites the hit is
2219    /// rejected when nearer scene geometry occludes that pixel (shares the
2220    /// depth convention + bias of [`pick`](Self::pick); on the GPU backend
2221    /// the occlusion test costs a click-time depth readback).
2222    #[must_use]
2223    pub fn pick_image(
2224        &self,
2225        camera: &Camera,
2226        x: f64,
2227        y: f64,
2228        sprites: &[ImageSprite],
2229    ) -> Option<ImagePickHit> {
2230        if sprites.is_empty() {
2231            return None;
2232        }
2233        let dir = self.pixel_ray(camera, x, y)?;
2234        let dir = [dir[0] as f32, dir[1] as f32, dir[2] as f32];
2235        let dir_len = v_dot(dir, dir).sqrt();
2236        if dir_len < 1e-9 {
2237            return None;
2238        }
2239        let origin = [
2240            camera.pos[0] as f32,
2241            camera.pos[1] as f32,
2242            camera.pos[2] as f32,
2243        ];
2244        // Scene surface distance under this pixel (sky / no-hit → None);
2245        // used to occlude depth-tested sprites. Same metric as `pick`.
2246        let scene_t = self.pick_depth(x as u32, y as u32);
2247
2248        let mut best: Option<ImagePickHit> = None;
2249        for sprite in sprites {
2250            // Reuse the render-path resolve (back-face cull included), so
2251            // a single-sided quad that isn't drawn also can't be picked.
2252            let Some(q) = resolve_quad(sprite, camera) else {
2253                continue;
2254            };
2255            let Some(([a, b], t)) = ray_quad_uv(origin, dir, &q.corners) else {
2256                continue; // miss / parallel / behind
2257            };
2258            let d_eucl = t * dir_len;
2259            if best.is_some_and(|cur| d_eucl >= cur.t) {
2260                continue; // a nearer sprite already won
2261            }
2262            let p = v_add(origin, v_scale(dir, t));
2263
2264            let Some((iw, ih)) = self.image_dims(sprite.image) else {
2265                continue; // dropped / unknown image
2266            };
2267            let tx = ((a * iw as f32) as i32).clamp(0, iw as i32 - 1) as u32;
2268            let ty = ((b * ih as f32) as i32).clamp(0, ih as i32 - 1) as u32;
2269
2270            // See-through test: a texel is solid when its alpha clears the
2271            // cutoff (and a fully-transparent texel is never solid).
2272            let cutoff_u8 = (sprite.alpha_cutoff.clamp(0.0, 1.0) * 255.0) as u32;
2273            let solid_thresh = cutoff_u8.max(1);
2274            if u32::from(self.image_alpha_at(sprite.image, tx, ty)) < solid_thresh {
2275                continue;
2276            }
2277
2278            // Occlusion: a depth-tested sprite behind nearer geometry loses.
2279            if sprite.depth_test {
2280                if let Some(st) = scene_t {
2281                    if d_eucl > st + PICK_DEPTH_BIAS {
2282                        continue;
2283                    }
2284                }
2285            }
2286
2287            best = Some(ImagePickHit {
2288                image: sprite.image,
2289                uv: [a, b],
2290                texel: (tx, ty),
2291                world: p,
2292                t: d_eucl,
2293            });
2294        }
2295        best
2296    }
2297
2298    /// Source dimensions of an uploaded image, or `None` if the id was
2299    /// dropped / never uploaded. Internal helper for [`Self::pick_image`].
2300    fn image_dims(&self, id: ImageId) -> Option<(u32, u32)> {
2301        let slot = self.image_map.index(id)?;
2302        match &self.inner {
2303            BackendImpl::Cpu(c) => c.image_dims(slot),
2304            BackendImpl::Gpu(g) => g.image_dims(slot),
2305        }
2306    }
2307
2308    /// Alpha byte of texel `(tx, ty)` in an uploaded image (`0` for an
2309    /// unknown id / out-of-range texel). Internal helper for
2310    /// [`Self::pick_image`].
2311    fn image_alpha_at(&self, id: ImageId, tx: u32, ty: u32) -> u8 {
2312        let Some(slot) = self.image_map.index(id) else {
2313            return 0;
2314        };
2315        match &self.inner {
2316            BackendImpl::Cpu(c) => c.image_alpha_at(slot, tx, ty),
2317            BackendImpl::Gpu(g) => g.image_alpha_at(slot, tx, ty),
2318        }
2319    }
2320
2321    /// Mirror the rendered 3D scene horizontally before display. The flip is
2322    /// applied *before* any egui overlay, so the UI stays upright while the
2323    /// viewport un-mirrors — a fix for the engine's left-handed render.
2324    /// Supported on both backends (CPU reverses the framebuffer rows; GPU
2325    /// mirrors the scene blit + line/image overlays). Picking/projection are
2326    /// unchanged, so a host that flips must mirror its cursor X (`width - x`)
2327    /// for ray casts.
2328    pub fn set_flip_x(&mut self, flip: bool) {
2329        match &mut self.inner {
2330            BackendImpl::Cpu(c) => c.set_flip_x(flip),
2331            BackendImpl::Gpu(g) => g.set_flip_x(flip),
2332        }
2333    }
2334
2335    /// Present the frame [`render`](Self::render) composited, with no UI
2336    /// overlay. Pairs with `render`; use [`paint_egui`](Self::paint_egui)
2337    /// instead to overlay an egui UI before presenting.
2338    pub fn present(&mut self) {
2339        match &mut self.inner {
2340            BackendImpl::Cpu(c) => c.present(),
2341            BackendImpl::Gpu(g) => g.present(),
2342        }
2343    }
2344
2345    /// Block until the active backend has finished all in-flight work, ready
2346    /// for a clean teardown. On the GPU backend this drains the device queue
2347    /// and releases any acquired-but-unpresented swapchain frame; on the CPU
2348    /// backend it is a no-op (nothing is in flight).
2349    ///
2350    /// Call this at shutdown **before dropping the renderer and its window**,
2351    /// so the GPU device/surface tear down with no commands queued and no
2352    /// half-presented frame. Skipping it (or dropping the window first) can
2353    /// leave the driver/compositor showing stale buffers after an exit — the
2354    /// "leftover triangles / flicker" symptom of an unclean shutdown.
2355    pub fn wait_idle(&mut self) {
2356        match &mut self.inner {
2357            BackendImpl::Cpu(c) => c.wait_idle(),
2358            BackendImpl::Gpu(g) => g.wait_idle(),
2359        }
2360    }
2361
2362    /// Composite `scene` and return a [`Frame`] guard — the type-state
2363    /// form of the `render → overlays → present`/`paint_egui` protocol
2364    /// (QE-B6), which the split calls enforce by documentation only.
2365    /// With the guard, misuse is unrepresentable: overlays can only be
2366    /// drawn on a live frame (with the camera it was rendered with —
2367    /// the guard holds it), presenting consumes the guard so a double
2368    /// present can't compile, and *dropping* an unfinished frame
2369    /// presents it — a bare `renderer.frame(..);` shows the frame.
2370    ///
2371    /// ```ignore
2372    /// renderer
2373    ///     .frame(&mut scene, &camera, &params)
2374    ///     .draw_lines(&gizmo)
2375    ///     .present(); // or .paint_egui(..); or just drop it
2376    /// ```
2377    ///
2378    /// The split [`render`](Self::render) / [`present`](Self::present)
2379    /// calls remain available for hosts that need custom control flow
2380    /// between the stages.
2381    pub fn frame(&mut self, scene: &mut Scene, camera: &Camera, params: &FrameParams) -> Frame<'_> {
2382        self.render(scene, camera, params);
2383        Frame {
2384            renderer: self,
2385            camera: *camera,
2386            finished: false,
2387        }
2388    }
2389
2390    /// Overlay an egui UI on the frame [`render`](Self::render)
2391    /// composited, then present it (`hud` feature). The host runs egui
2392    /// itself (e.g. `egui` + `egui-winit`) and passes the tessellated
2393    /// `jobs` ([`egui::Context::tessellate`]) and the per-frame
2394    /// `textures` delta from [`egui::FullOutput`]; `pixels_per_point` is
2395    /// the UI scale (`ctx.pixels_per_point()`).
2396    ///
2397    /// The GPU backend paints via `egui-wgpu`; the CPU backend
2398    /// software-rasterises the tessellation into its framebuffer. Use
2399    /// this **instead of** [`present`](Self::present) — both finish the
2400    /// frame.
2401    #[cfg(feature = "hud")]
2402    pub fn paint_egui(
2403        &mut self,
2404        jobs: &[egui::ClippedPrimitive],
2405        textures: &egui::TexturesDelta,
2406        pixels_per_point: f32,
2407    ) {
2408        match &mut self.inner {
2409            BackendImpl::Cpu(c) => c.paint_egui(jobs, textures, pixels_per_point),
2410            BackendImpl::Gpu(g) => g.paint_egui(jobs, textures, pixels_per_point),
2411        }
2412    }
2413
2414    /// Reset the whole sprite world: every model, dynamic instance,
2415    /// voxel clip, streaming clip, character, billboard and actor is
2416    /// dropped, and **every outstanding handle from any of those
2417    /// families goes stale** (resolving to safe no-ops — the maps are
2418    /// generational). The explicit scene-switch verb (QE-B6): what the
2419    /// demo host does between scenes, without the "register an empty
2420    /// set" idiom spelling it.
2421    pub fn clear_sprites(&mut self) {
2422        self.set_sprites(&SpriteSet {
2423            models: Vec::new(),
2424            instances: Vec::new(),
2425            carve_model: None,
2426        });
2427    }
2428
2429    /// Register sprite models + instances — **replacing the whole
2430    /// sprite world**. This is a bulk *set*, not an append: every
2431    /// handle family (models, dynamic instances, clips, streaming
2432    /// clips, characters, billboards, actors) is reset and previously
2433    /// issued handles go stale (safe no-ops). Call once at setup, or
2434    /// again to replace everything; to build up incrementally instead,
2435    /// use [`add_sprite_model`](Self::add_sprite_model) /
2436    /// [`add_sprite_instance`](Self::add_sprite_instance) &c., and to
2437    /// drop everything use [`clear_sprites`](Self::clear_sprites).
2438    pub fn set_sprites(&mut self, set: &SpriteSet) -> Vec<SpriteModelId> {
2439        match &mut self.inner {
2440            BackendImpl::Cpu(c) => c.set_sprites(set),
2441            BackendImpl::Gpu(g) => g.set_sprites(set),
2442        }
2443        // A fresh sprite set replaces the instance world, so any
2444        // previously added dynamic instances + models are gone — drop their
2445        // handles and re-seat the model slotmap with `set.models.len()`
2446        // live ids `0..n` (model index = chain id on both backends).
2447        self.dyn_map = DynInstanceMap::default();
2448        self.model_map.reset_live(set.models.len());
2449        // A full sprite rebuild drops the dynamic + clip layers on both
2450        // backends (the GPU registry is replaced), so reset the clip +
2451        // character maps too.
2452        self.clip_map.reset();
2453        self.char_map.reset();
2454        self.char_instances.clear();
2455        self.streaming_map.reset();
2456        self.streaming_clips.clear();
2457        self.clip_meta.clear();
2458        self.clip_players.clear();
2459        self.billboards.clear();
2460        self.actor_map.reset();
2461        self.billboard_actors.clear();
2462        self.state.dyn_clip.clear();
2463        (0..set.models.len() as u32)
2464            .map(|slot| self.model_map.minted(slot))
2465            .collect()
2466    }
2467
2468    /// Re-register one sprite model's geometry after you've edited its
2469    /// content (a carve or recolour of its `kv6`). `model` is the
2470    /// [`SpriteModelId`] handed back by [`set_sprites`](Self::set_sprites);
2471    /// `kv6` is the model's **new** geometry — the caller owns the source
2472    /// of truth (e.g. a dense carve grid the surface-only `kv6` can't
2473    /// represent) and supplies the refreshed mesh here.
2474    ///
2475    /// This is a **backend-agnostic content refresh**, not a GPU upload:
2476    /// the renderer brings its stored model up to date however its active
2477    /// backend needs to. The instance set is left untouched (an edit never
2478    /// moves or adds an instance), so on the GPU backend only that one
2479    /// model's voxel data is re-uploaded — through a slack-backed
2480    /// suballocator, one model's bytes rather than the whole registry —
2481    /// while the CPU backend swaps the cached `kv6` into each instance of
2482    /// the model. Use [`set_sprites`](Self::set_sprites) to add/remove
2483    /// models or change the instance set.
2484    pub fn refresh_sprite_model(&mut self, model: SpriteModelId, kv6: &Kv6) {
2485        let Some(idx) = self.model_map.index(model) else {
2486            return; // stale / removed handle → no-op
2487        };
2488        match &mut self.inner {
2489            BackendImpl::Cpu(c) => c.update_sprite_model(idx, kv6),
2490            BackendImpl::Gpu(g) => g.update_sprite_model(idx, kv6),
2491        }
2492    }
2493
2494    /// Like [`refresh_sprite_model`](Self::refresh_sprite_model) but also
2495    /// re-classifies the refreshed voxels into per-voxel material ids by
2496    /// colour (TV.3) via `material_map` — used by the material-aware streaming
2497    /// clip path so a re-uploaded frame keeps its per-voxel materials. An
2498    /// empty map matches `refresh_sprite_model`.
2499    pub fn refresh_sprite_model_with_materials(
2500        &mut self,
2501        model: SpriteModelId,
2502        kv6: &Kv6,
2503        material_map: &[(Rgb, u8)],
2504    ) {
2505        let Some(idx) = self.model_map.index(model) else {
2506            return; // stale / removed handle → no-op
2507        };
2508        match &mut self.inner {
2509            BackendImpl::Cpu(c) => {
2510                c.update_sprite_model_with_materials(idx, kv6, Some(material_map));
2511            }
2512            BackendImpl::Gpu(g) => g.update_sprite_model_with_materials(idx, kv6, material_map),
2513        }
2514    }
2515
2516    /// Add one sprite instance of an already-registered `model` at world
2517    /// `pos`, **incrementally** — the cheap streaming-spawn path that both
2518    /// backends now share (GPU: append to the instance buffer, growing by
2519    /// powers of two; CPU: push one pre-posed [`Sprite`]). Returns a
2520    /// stable [`SpriteInstanceId`] for later removal.
2521    ///
2522    /// `model` must be a [`SpriteModelId`] from the current
2523    /// [`set_sprites`](Self::set_sprites) (a model registered there, even
2524    /// with zero initial instances). Dynamic instances live *after* the
2525    /// static set + any KFA limbs, so register those first.
2526    ///
2527    /// Returns `None` — spawning nothing — on a stale/removed `model`
2528    /// handle (QE.1c; previously a silent sentinel id).
2529    pub fn add_sprite_instance(
2530        &mut self,
2531        model: SpriteModelId,
2532        pos: [f32; 3],
2533    ) -> Option<SpriteInstanceId> {
2534        self.add_sprite_instance_posed(
2535            model,
2536            DynSpriteTransform {
2537                pos,
2538                ..DynSpriteTransform::default()
2539            },
2540        )
2541    }
2542
2543    /// Add one sprite instance of an already-registered `model`,
2544    /// pre-posed with the orientation in `xf` — the streaming-spawn path
2545    /// for objects that appear mid-flight already rotated (so there's no
2546    /// one-frame axis-aligned flash before the first
2547    /// [`set_sprite_instance_transform`](Self::set_sprite_instance_transform)).
2548    /// Otherwise identical to
2549    /// [`add_sprite_instance`](Self::add_sprite_instance) (which is just
2550    /// this with the identity basis). Returns a stable
2551    /// [`SpriteInstanceId`].
2552    ///
2553    /// Returns `None` — spawning nothing — on a stale/removed `model`
2554    /// handle (QE.1c; previously a silent sentinel id). `xf`'s basis
2555    /// must be non-singular; a degenerate one makes the instance
2556    /// silently skip drawing (see [`DynSpriteTransform`]).
2557    pub fn add_sprite_instance_posed(
2558        &mut self,
2559        model: SpriteModelId,
2560        xf: DynSpriteTransform,
2561    ) -> Option<SpriteInstanceId> {
2562        let idx = self.model_map.index(model)?;
2563        let dyn_index = match &mut self.inner {
2564            BackendImpl::Cpu(c) => c.add_dyn_instance_posed(idx, xf),
2565            BackendImpl::Gpu(g) => g.add_dyn_instance_posed(idx, xf),
2566        }?;
2567        self.state.dyn_clip.push(None); // a plain model instance
2568        Some(self.dyn_map.alloc(dyn_index as u32))
2569    }
2570
2571    /// Remove a dynamic sprite instance added by
2572    /// [`add_sprite_instance`](Self::add_sprite_instance). O(1) on both
2573    /// backends (swap-remove); other dynamic handles stay valid. Returns
2574    /// `false` if the handle is stale / already removed.
2575    pub fn remove_sprite_instance(&mut self, id: SpriteInstanceId) -> bool {
2576        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
2577            return false;
2578        };
2579        let moved = match &mut self.inner {
2580            BackendImpl::Cpu(c) => c.remove_dyn_instance(dyn_index as usize),
2581            BackendImpl::Gpu(g) => g.remove_dyn_instance(dyn_index as usize),
2582        };
2583        // Mirror the backend's swap-remove on the facade's parallel
2584        // clip bookkeeping (QE.3a).
2585        self.state.dyn_clip.swap_remove(dyn_index as usize);
2586        self.dyn_map.remove(id, dyn_index, moved.map(|m| m as u32));
2587        true
2588    }
2589
2590    /// Number of live dynamic sprite instances (those added via
2591    /// [`add_sprite_instance`](Self::add_sprite_instance)).
2592    #[must_use]
2593    pub fn dynamic_sprite_count(&self) -> usize {
2594        self.dyn_map.order.len()
2595    }
2596
2597    /// Define a global voxel **material** (TV stage): the opacity + blend
2598    /// mode that a per-voxel material id resolves to. The renderer owns one
2599    /// 256-entry palette shared by every model and grid.
2600    ///
2601    /// Id `0` is permanently [`Material::OPAQUE`] — the value every voxel
2602    /// without explicit material data resolves to — and **cannot** be
2603    /// redefined; passing `id == 0` is a no-op that returns `false`. Any
2604    /// other id returns `true`.
2605    ///
2606    /// While no translucent material is defined the renderer stays on the
2607    /// fully-opaque fast path, so this is inert until first called. See
2608    /// `PORTING-TRANSPARENCY.md`.
2609    pub fn define_material(&mut self, id: u8, mat: Material) -> bool {
2610        let changed = self.state.materials.set(id, mat);
2611        if changed {
2612            self.state.materials_dirty = true;
2613        }
2614        changed
2615    }
2616
2617    /// The [`Material`] currently at palette `id` ([`Material::OPAQUE`] for
2618    /// any id never passed to [`define_material`](Self::define_material)).
2619    #[must_use]
2620    pub fn material(&self, id: u8) -> Material {
2621        self.state.materials.get(id)
2622    }
2623
2624    /// Set the **terrain** colour→material map (TV.4): pairs of `(rgb,
2625    /// material_id)` that make matching-colour world (grid) voxels translucent
2626    /// — glass walls, water pools. The materials themselves are defined via
2627    /// [`define_material`](Self::define_material). An empty map (the default)
2628    /// keeps all terrain opaque. The CPU backend composites these today; the
2629    /// GPU backend renders them once the TV.6 device path lands.
2630    pub fn set_terrain_materials(&mut self, map: &[(Rgb, u8)]) {
2631        if self.state.terrain_materials != map {
2632            self.state.terrain_materials = map.to_vec();
2633            self.state.materials_dirty = true;
2634        }
2635    }
2636
2637    /// Register one new sprite **model** incrementally from `kv6`,
2638    /// **without** rebuilding the existing model set — the streaming-in
2639    /// counterpart to [`add_sprite_instance`](Self::add_sprite_instance)
2640    /// for unique generated geometry (procedural asteroids, debris).
2641    /// Returns a stable [`SpriteModelId`] usable immediately with
2642    /// [`add_sprite_instance`](Self::add_sprite_instance) /
2643    /// [`add_sprite_instance_posed`](Self::add_sprite_instance_posed).
2644    ///
2645    /// Works before any [`set_sprites`](Self::set_sprites) (it establishes
2646    /// residency on the GPU backend's first model). The GPU backend
2647    /// appends one LOD chain to the resident registry (amortised O(model
2648    /// voxels)); the CPU backend pushes an axis-aligned template.
2649    pub fn add_sprite_model(&mut self, kv6: &Kv6) -> SpriteModelId {
2650        let model_index = match &mut self.inner {
2651            BackendImpl::Cpu(c) => c.add_model(kv6),
2652            BackendImpl::Gpu(g) => g.add_model(kv6),
2653        };
2654        self.model_map.alloc(model_index as u32)
2655    }
2656
2657    /// Register a **mixed-material** sprite model (TV.3): `material_map` pairs
2658    /// a voxel RGB colour (`0xRRGGBB`) with a material id (defined via
2659    /// [`define_material`](Self::define_material)), so a single model can mix
2660    /// opaque and translucent voxels — an opaque window frame around glass, a
2661    /// bottle around a translucent potion. Voxels whose colour isn't in the
2662    /// map are opaque (material 0). Like [`add_sprite_model`](Self::add_sprite_model)
2663    /// otherwise.
2664    ///
2665    /// The CPU backend composites per-voxel materials today; the GPU backend
2666    /// carries the data and renders per-voxel materials once the TV.3b device
2667    /// path lands (until then it uses the instance's uniform material).
2668    pub fn add_sprite_model_with_materials(
2669        &mut self,
2670        kv6: &Kv6,
2671        material_map: &[(Rgb, u8)],
2672    ) -> SpriteModelId {
2673        let model_index = match &mut self.inner {
2674            BackendImpl::Cpu(c) => c.add_model_with_materials(kv6, material_map),
2675            BackendImpl::Gpu(g) => g.add_model_with_materials(kv6, material_map),
2676        };
2677        self.model_map.alloc(model_index as u32)
2678    }
2679
2680    /// Remove a registered sprite model, freeing its voxel data. Returns
2681    /// `false` if `id` is stale / already removed.
2682    ///
2683    /// The model's slot is tombstoned **in place**: its id is never
2684    /// reused, so every other [`SpriteModelId`] stays valid (no remap).
2685    /// Existing instances of the removed model are **not** dropped here —
2686    /// they linger but draw as nothing on the GPU backend (the CPU
2687    /// backend keeps each instance's own kv6 clone, so they keep drawing
2688    /// until removed via
2689    /// [`remove_sprite_instance`](Self::remove_sprite_instance)); remove
2690    /// them when convenient. Call
2691    /// [`compact_sprite_models`](Self::compact_sprite_models) afterwards
2692    /// to reclaim the GPU buffer holes.
2693    pub fn remove_sprite_model(&mut self, id: SpriteModelId) -> bool {
2694        let Some(idx) = self.model_map.index(id) else {
2695            return false;
2696        };
2697        match &mut self.inner {
2698            BackendImpl::Cpu(c) => c.remove_model(idx),
2699            BackendImpl::Gpu(g) => g.remove_model(idx),
2700        }
2701        self.model_map.remove(id)
2702    }
2703
2704    /// Reclaim the GPU buffer space left by
2705    /// [`remove_sprite_model`](Self::remove_sprite_model) by repacking the
2706    /// resident registry to its live models only. Model ids are preserved
2707    /// (no remap). O(live voxel volume) — call it when many models have
2708    /// been removed, not every frame. No-op on the CPU backend (which
2709    /// keeps cheap empty placeholders) and when nothing was removed.
2710    pub fn compact_sprite_models(&mut self) {
2711        match &mut self.inner {
2712            BackendImpl::Cpu(c) => c.compact_models(),
2713            BackendImpl::Gpu(g) => g.compact_models(),
2714        }
2715    }
2716
2717    /// Update one dynamic instance's full pose (position + orientation)
2718    /// for this frame. `id` is from
2719    /// [`add_sprite_instance`](Self::add_sprite_instance) /
2720    /// [`add_sprite_instance_posed`](Self::add_sprite_instance_posed). A
2721    /// stale / removed handle is a no-op.
2722    ///
2723    /// For many instances per frame prefer
2724    /// [`set_sprite_instance_transforms`](Self::set_sprite_instance_transforms):
2725    /// the GPU backend flushes all pending pose changes to the device
2726    /// once per [`render`](Self::render), so a per-instance call here is
2727    /// still O(1) device work, but the batch variant avoids re-walking
2728    /// the slotmap.
2729    pub fn set_sprite_instance_transform(&mut self, id: SpriteInstanceId, xf: DynSpriteTransform) {
2730        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
2731            return;
2732        };
2733        match &mut self.inner {
2734            BackendImpl::Cpu(c) => c.set_dyn_instance_transform(dyn_index as usize, xf),
2735            BackendImpl::Gpu(g) => g.set_dyn_instance_transform(dyn_index as usize, xf),
2736        }
2737    }
2738
2739    /// Batch form of
2740    /// [`set_sprite_instance_transform`](Self::set_sprite_instance_transform)
2741    /// — apply many `(instance, pose)` updates in one call. Stale handles
2742    /// in `updates` are skipped. On the GPU backend this marks the
2743    /// instance buffer dirty once and uploads the new poses a single time
2744    /// at the next [`render`](Self::render), so spinning a whole cluster
2745    /// of instances per frame is one device upload, not one per instance.
2746    pub fn set_sprite_instance_transforms(
2747        &mut self,
2748        updates: &[(SpriteInstanceId, DynSpriteTransform)],
2749    ) {
2750        for &(id, xf) in updates {
2751            let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
2752                continue;
2753            };
2754            match &mut self.inner {
2755                BackendImpl::Cpu(c) => c.set_dyn_instance_transform(dyn_index as usize, xf),
2756                BackendImpl::Gpu(g) => g.set_dyn_instance_transform(dyn_index as usize, xf),
2757            }
2758        }
2759    }
2760
2761    /// Set sprite instance `id`'s voxel-material id (TV stage) — indexes the
2762    /// global palette defined via [`define_material`](Self::define_material)
2763    /// for this whole instance's opacity + blend mode. `0` (the default) is
2764    /// opaque. Stale handles are ignored.
2765    ///
2766    /// Only the CPU backend composites translucent sprites today; the GPU
2767    /// backend retains the value for the forthcoming device-side path (see
2768    /// `PORTING-TRANSPARENCY.md`).
2769    pub fn set_sprite_instance_material(&mut self, id: SpriteInstanceId, material: u8) {
2770        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
2771            return;
2772        };
2773        match &mut self.inner {
2774            BackendImpl::Cpu(c) => c.set_dyn_instance_material(dyn_index as usize, material),
2775            BackendImpl::Gpu(g) => g.set_dyn_instance_material(dyn_index as usize, material),
2776        }
2777    }
2778
2779    /// Set sprite instance `id`'s per-instance alpha multiplier (TV stage),
2780    /// `0..=255` (`255` = unscaled). Scales the material's opacity so an
2781    /// effect can fade out by cheap per-frame updates without re-uploading
2782    /// its volume. Stale handles are ignored.
2783    pub fn set_sprite_instance_alpha(&mut self, id: SpriteInstanceId, alpha_mul: u8) {
2784        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
2785            return;
2786        };
2787        match &mut self.inner {
2788            BackendImpl::Cpu(c) => c.set_dyn_instance_alpha(dyn_index as usize, alpha_mul),
2789            BackendImpl::Gpu(g) => g.set_dyn_instance_alpha(dyn_index as usize, alpha_mul),
2790        }
2791    }
2792
2793    /// Set sprite instance `id`'s per-instance **RGB tint**, packed
2794    /// `0x00RRGGBB`: every rendered voxel's colour is multiplied by it (per
2795    /// channel), so instances of one model can be recoloured cheaply per frame.
2796    /// `0x00FF_FFFF` (white, the default) is a no-op. Works on both backends;
2797    /// stale handles are ignored. Tint is colour only — for transparency, use a
2798    /// translucent material with
2799    /// [`set_sprite_instance_alpha`](Self::set_sprite_instance_alpha).
2800    pub fn set_sprite_instance_tint(&mut self, id: SpriteInstanceId, tint: Rgb) {
2801        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
2802            return;
2803        };
2804        match &mut self.inner {
2805            BackendImpl::Cpu(c) => c.set_dyn_instance_tint(dyn_index as usize, tint.0),
2806            BackendImpl::Gpu(g) => g.set_dyn_instance_tint(dyn_index as usize, tint.0),
2807        }
2808    }
2809
2810    /// Toggle a sprite/clip instance's shadow participation **live**
2811    /// (XS.4 flags, BB.3). [`ShadowFlags::default`] (both on) is what
2812    /// every spawn starts with. The per-instance counterpart to the
2813    /// template-level `Sprite::with_casts_shadow` /
2814    /// `with_receives_shadow` — e.g. a flat additive glow billboard
2815    /// that should not cast, or a UI marker that ignores shadows.
2816    /// Other flag bits are preserved. No-op on a stale id.
2817    ///
2818    /// QE.7b — takes [`ShadowFlags`] instead of the old unreadable
2819    /// `(id, true, false)` bool pair; migrate with
2820    /// `ShadowFlags { casts, receives }`.
2821    pub fn set_sprite_instance_shadow_flags(&mut self, id: SpriteInstanceId, shadows: ShadowFlags) {
2822        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
2823            return;
2824        };
2825        match &mut self.inner {
2826            BackendImpl::Cpu(c) => {
2827                c.set_dyn_instance_shadow_flags(
2828                    dyn_index as usize,
2829                    shadows.casts,
2830                    shadows.receives,
2831                );
2832            }
2833            BackendImpl::Gpu(g) => {
2834                g.set_dyn_instance_shadow_flags(
2835                    dyn_index as usize,
2836                    shadows.casts,
2837                    shadows.receives,
2838                );
2839            }
2840        }
2841    }
2842
2843    /// Set a sprite/clip instance's **lighting mode** live (BB.2b): how its
2844    /// shading normal is derived ([`BillboardLighting`]). Useful for
2845    /// camera-facing billboards whose face normal would otherwise track the
2846    /// camera. Other flag bits are preserved; only affects the dynamic
2847    /// lighting path. No-op on a stale id.
2848    pub fn set_sprite_instance_lighting(&mut self, id: SpriteInstanceId, mode: BillboardLighting) {
2849        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
2850            return;
2851        };
2852        match &mut self.inner {
2853            BackendImpl::Cpu(c) => c.set_dyn_instance_lighting(dyn_index as usize, mode),
2854            BackendImpl::Gpu(g) => g.set_dyn_instance_lighting(dyn_index as usize, mode),
2855        }
2856    }
2857
2858    // ---- animated voxel clips (VCL.4) ------------------------------------
2859
2860    /// Register an animated voxel clip ("GIF/MP4 for voxels"): decode all
2861    /// its frames and upload the flipbook to the active backend (GPU: one
2862    /// LOD chain per frame; CPU: a cached dense grid per frame). Returns a
2863    /// [`VoxelClipId`] to spawn instances of it via
2864    /// [`add_clip_instance_posed`](Self::add_clip_instance_posed).
2865    ///
2866    /// Build the [`DecodedClip`] from a `.rvc` via
2867    /// [`VoxelClip::decode`](roxlap_formats::voxel_clip::VoxelClip::decode).
2868    /// Like [`add_sprite_model`](Self::add_sprite_model), this works before
2869    /// any [`set_sprites`](Self::set_sprites); a later `set_sprites`
2870    /// **drops** all registered clips (re-register afterwards).
2871    pub fn add_voxel_clip(&mut self, clip: &DecodedClip) -> VoxelClipId {
2872        self.add_voxel_clip_with_materials(clip, &[])
2873    }
2874
2875    /// Register a **mixed-material** animated voxel clip (TV.3): the clip
2876    /// analogue of
2877    /// [`add_sprite_model_with_materials`](Self::add_sprite_model_with_materials).
2878    /// `material_map` pairs a voxel RGB colour (`0xRRGGBB`) with a material id
2879    /// (defined via [`define_material`](Self::define_material)), classifying
2880    /// every frame's voxels so an animated clip can mix opaque and translucent
2881    /// voxels — an opaque torch handle around an additive flame, a spinning
2882    /// glass orb. Voxels whose colour isn't in the map stay opaque
2883    /// (material 0). Like [`add_voxel_clip`](Self::add_voxel_clip) otherwise.
2884    pub fn add_voxel_clip_with_materials(
2885        &mut self,
2886        clip: &DecodedClip,
2887        material_map: &[(Rgb, u8)],
2888    ) -> VoxelClipId {
2889        let clip_index = match &mut self.inner {
2890            BackendImpl::Cpu(c) => c.add_voxel_clip_with_materials(clip, material_map),
2891            BackendImpl::Gpu(g) => g.add_voxel_clip_with_materials(clip, material_map),
2892        };
2893        // Capture metadata for editor queries + #6 auto-play; clip indices
2894        // are sequential and parallel to `clip_meta`.
2895        debug_assert_eq!(clip_index, self.clip_meta.len());
2896        self.clip_meta.push(ClipMeta {
2897            dims: clip.dims,
2898            pivot: clip.pivot,
2899            voxel_world_size: clip.voxel_world_size,
2900            durations: clip.durations.clone(),
2901            loop_mode: clip.loop_mode,
2902            material_map: material_map.to_vec(),
2903        });
2904        self.clip_map.alloc(clip_index as u32)
2905    }
2906
2907    /// Remove a registered clip, freeing its per-frame volumes. Instances
2908    /// of it linger but draw nothing until removed via
2909    /// [`remove_sprite_instance`](Self::remove_sprite_instance). Returns
2910    /// `false` if `id` is stale / already removed.
2911    pub fn remove_voxel_clip(&mut self, id: VoxelClipId) -> bool {
2912        let Some(clip_index) = self.clip_map.index(id) else {
2913            return false;
2914        };
2915        match &mut self.inner {
2916            BackendImpl::Cpu(c) => c.remove_voxel_clip(clip_index),
2917            BackendImpl::Gpu(g) => g.remove_voxel_clip(clip_index),
2918        }
2919        // Detach instances that were playing this clip so they stop
2920        // being treated as clip instances (QE.3a — facade bookkeeping;
2921        // was duplicated in both backends).
2922        for slot in &mut self.state.dyn_clip {
2923            if matches!(slot, Some((c, _)) if *c == clip_index) {
2924                *slot = None;
2925            }
2926        }
2927        self.clip_map.remove(id)
2928    }
2929
2930    /// Spawn an instance of clip `clip`, posed by `xf`, starting on frame
2931    /// 0. Returns a [`SpriteInstanceId`] — a clip instance is a dynamic
2932    /// sprite instance, so move it with
2933    /// [`set_sprite_instance_transform`](Self::set_sprite_instance_transform),
2934    /// advance its frame with
2935    /// [`set_clip_instance_frame`](Self::set_clip_instance_frame), and drop
2936    /// it with [`remove_sprite_instance`](Self::remove_sprite_instance).
2937    /// Returns `None` — spawning nothing — on a stale/removed `clip`
2938    /// handle (QE.1c; previously a silent sentinel id).
2939    ///
2940    /// This instance has **no playback clock**: drive its frame yourself via
2941    /// [`set_clip_instance_frame`](Self::set_clip_instance_frame) (frame-based
2942    /// scrubbing). For *clock*-based control — auto-advance, play/pause, or
2943    /// [`set_clip_instance_clock_ms`](Self::set_clip_instance_clock_ms)
2944    /// scrubbing — spawn with
2945    /// [`add_clip_instance_playing`](Self::add_clip_instance_playing) instead
2946    /// (the player-control methods no-op on an instance with no player).
2947    pub fn add_clip_instance_posed(
2948        &mut self,
2949        clip: VoxelClipId,
2950        xf: DynSpriteTransform,
2951    ) -> Option<SpriteInstanceId> {
2952        let clip_index = self.clip_map.index(clip)?;
2953        let dyn_index = match &mut self.inner {
2954            BackendImpl::Cpu(c) => c.add_clip_instance(clip_index, xf),
2955            BackendImpl::Gpu(g) => g.add_clip_instance(clip_index, xf),
2956        }?;
2957        self.state.dyn_clip.push(Some((clip_index, 0)));
2958        Some(self.dyn_map.alloc(dyn_index as u32))
2959    }
2960
2961    /// Select which frame a clip instance shows — the per-frame playback
2962    /// step. Cheap on both backends (GPU: swap the instance's model id;
2963    /// CPU: select the cached frame grid), with no volume re-upload. Drive
2964    /// it from a playback clock via
2965    /// [`DecodedClip::frame_at`](roxlap_formats::voxel_clip::DecodedClip::frame_at).
2966    /// No-op on a stale id or a non-clip instance.
2967    pub fn set_clip_instance_frame(&mut self, id: SpriteInstanceId, frame: u32) {
2968        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
2969            return;
2970        };
2971        let frame = frame as usize;
2972        let Some(Some((clip_index, cur_frame))) = self.state.dyn_clip.get_mut(dyn_index as usize)
2973        else {
2974            return; // not a clip instance
2975        };
2976        // PF.5 — same-frame guard: a player ticking at render rate
2977        // re-applies the same frame most ticks; skip the bookkeeping +
2978        // GPU writes (QE.3a: the guard now covers both backends).
2979        if *cur_frame == frame {
2980            return;
2981        }
2982        let clip_index = *clip_index;
2983        *cur_frame = frame;
2984        // The CPU render reads the frame from `state.dyn_clip`; only
2985        // the GPU keeps device-side state (the instance's model id).
2986        if let BackendImpl::Gpu(g) = &mut self.inner {
2987            g.apply_clip_frame(dyn_index as usize, clip_index, frame);
2988        }
2989    }
2990
2991    /// Retarget a live clip instance onto a **different** registered clip,
2992    /// restarting it at frame 0 while keeping its world transform and any
2993    /// auto-playback clock *policy* (speed / paused). The per-frame primitive
2994    /// for directional ("8-way") billboards and animation-state changes
2995    /// (idle → walk → attack): far cheaper than `remove_sprite_instance` +
2996    /// `add_clip_instance_*`, reusing the instance's existing GPU residency
2997    /// (just a model-id swap, no volume re-upload).
2998    ///
2999    /// If the instance has a playback clock
3000    /// ([`add_clip_instance_playing`](Self::add_clip_instance_playing)), its
3001    /// timeline is retargeted to the new clip (durations + loop mode) and the
3002    /// clock restarts at 0; the speed and paused state carry over.
3003    ///
3004    /// Returns `false` (a safe no-op) on a stale instance id, a stale `clip`,
3005    /// or a non-clip instance.
3006    pub fn set_clip_instance_clip(&mut self, id: SpriteInstanceId, clip: VoxelClipId) -> bool {
3007        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
3008            return false;
3009        };
3010        let Some(clip_index) = self.clip_map.index(clip) else {
3011            return false;
3012        };
3013        if !matches!(self.state.dyn_clip.get(dyn_index as usize), Some(Some(_))) {
3014            return false; // not a clip instance
3015        }
3016        // Only the GPU has device-side state to retarget (the model
3017        // id); it reports whether the new clip actually has frames.
3018        let ok = match &mut self.inner {
3019            BackendImpl::Cpu(_) => true,
3020            BackendImpl::Gpu(g) => g.apply_clip_retarget(dyn_index as usize, clip_index),
3021        };
3022        if ok {
3023            self.state.dyn_clip[dyn_index as usize] = Some((clip_index, 0));
3024            // Retarget the auto-player's timeline to the new clip (different
3025            // frame count / durations / loop), restart its clock, keep the
3026            // playback policy (speed + paused). Clone metadata first so the
3027            // immutable borrow ends before the mutable player borrow.
3028            let durations = self.clip_meta[clip_index].durations.clone();
3029            let loop_mode = self.clip_meta[clip_index].loop_mode;
3030            if let Some(player) = self.flipbook_player_mut(id) {
3031                player.clock.retarget(&durations, loop_mode);
3032            }
3033        }
3034        ok
3035    }
3036
3037    // ---- billboards (BB.2) -----------------------------------------------
3038
3039    /// Spawn a clip instance that auto-orients toward the camera every
3040    /// [`face_billboards_to`](Self::face_billboards_to) — a Doom/Build-style
3041    /// billboard. `pos` is its world position (the clip pivot maps here);
3042    /// `mode` chooses cylindrical (the Doom default) or spherical facing.
3043    /// Drive its animation through the clip player
3044    /// ([`advance_voxel_clips`](Self::advance_voxel_clips)) and swap
3045    /// animations with [`set_clip_instance_clip`](Self::set_clip_instance_clip).
3046    ///
3047    /// The instance starts axis-aligned until the first `face_billboards_to`,
3048    /// so call that (with the frame's camera) before `render` — like
3049    /// `advance_voxel_clips(dt)`. Returns a stale id on a stale `clip` (no
3050    /// billboard recorded).
3051    pub fn add_billboard_instance(
3052        &mut self,
3053        clip: VoxelClipId,
3054        pos: [f32; 3],
3055        mode: BillboardMode,
3056    ) -> Option<SpriteInstanceId> {
3057        let xf = DynSpriteTransform {
3058            pos,
3059            ..Default::default()
3060        };
3061        let id = self.add_clip_instance_posed(clip, xf)?;
3062        self.billboards.push(BillboardRec { id, pos, mode });
3063        Some(id)
3064    }
3065
3066    /// Change a billboard instance's facing mode. No-op on a non-billboard id.
3067    pub fn set_billboard_mode(&mut self, id: SpriteInstanceId, mode: BillboardMode) {
3068        if let Some(b) = self.billboards.iter_mut().find(|b| b.id == id) {
3069            b.mode = mode;
3070        }
3071    }
3072
3073    /// Move a billboard instance. Its auto-orientation is preserved; the new
3074    /// position takes effect on the next
3075    /// [`face_billboards_to`](Self::face_billboards_to). No-op on a
3076    /// non-billboard id.
3077    pub fn set_billboard_position(&mut self, id: SpriteInstanceId, pos: [f32; 3]) {
3078        if let Some(b) = self.billboards.iter_mut().find(|b| b.id == id) {
3079            b.pos = pos;
3080        }
3081    }
3082
3083    /// Re-orient every billboard instance to face `camera` — one batched
3084    /// transform flush (BB.2). Call once per frame before `render`, after
3085    /// moving billboards / the camera (the billboard analogue of
3086    /// [`advance_voxel_clips`](Self::advance_voxel_clips)). Billboards whose
3087    /// instance was removed are pruned; a degenerate pose (camera on the
3088    /// sprite's vertical axis) is skipped for that frame.
3089    pub fn face_billboards_to(&mut self, camera: &Camera) {
3090        let cam = camera.pos;
3091        let dyn_map = &self.dyn_map;
3092        let mut updates: Vec<(SpriteInstanceId, DynSpriteTransform)> = Vec::new();
3093        self.billboards.retain(|b| {
3094            if dyn_map.dyn_index(b.id).is_none() {
3095                return false; // the instance was removed → drop the record
3096            }
3097            if let Some(xf) = billboard_transform(b.pos, cam, b.mode) {
3098                updates.push((b.id, xf));
3099            }
3100            true
3101        });
3102        self.set_sprite_instance_transforms(&updates);
3103    }
3104
3105    // ---- billboard actors (BB.4) -----------------------------------------
3106
3107    /// Build a [`ClipClock`] seeded from `clip`'s timeline (durations + loop
3108    /// mode), or an empty/looping clock if `clip` is `None`/stale.
3109    fn clock_for_clip(&self, clip: Option<VoxelClipId>, speed: f32) -> ClipClock {
3110        let (durations, loop_mode) = clip.and_then(|c| self.clip_map.index(c)).map_or_else(
3111            || (Vec::new(), LoopMode::Loop),
3112            |ci| {
3113                (
3114                    self.clip_meta[ci].durations.clone(),
3115                    self.clip_meta[ci].loop_mode,
3116                )
3117            },
3118        );
3119        ClipClock::new(&durations, loop_mode, speed_to_q8(speed), 0.0)
3120    }
3121
3122    /// Register a high-level **directional billboard actor** (BB.4): the
3123    /// renderer owns one clip instance and, every
3124    /// [`update_billboard_actors`](Self::update_billboard_actors), picks the
3125    /// directional clip from the view angle, faces it to the camera, and
3126    /// advances its state animation. The convenience layer over
3127    /// [`add_billboard_instance`](Self::add_billboard_instance) +
3128    /// [`set_clip_instance_clip`](Self::set_clip_instance_clip) + the clip
3129    /// clock for Doom-style monsters.
3130    ///
3131    /// `pos` is the actor's world position; `facing_yaw` is the world yaw it
3132    /// faces (radians; the dir picker compares the camera's bearing to it).
3133    /// Returns `None` — spawning nothing — if `def` has no states / a
3134    /// state with no dirs, or the initial clip is stale (QE.1c;
3135    /// previously a silent sentinel id).
3136    pub fn add_billboard_actor(
3137        &mut self,
3138        def: BillboardActorDef,
3139        pos: [f32; 3],
3140        facing_yaw: f64,
3141    ) -> Option<BillboardActorId> {
3142        if def.states.is_empty() || def.states.iter().any(|s| s.dirs.is_empty()) {
3143            return None;
3144        }
3145        let init_clip = def.states[0].dirs[0];
3146        let xf = DynSpriteTransform {
3147            pos,
3148            ..Default::default()
3149        };
3150        let inst = self.add_clip_instance_posed(init_clip, xf)?;
3151        self.set_sprite_instance_shadow_flags(inst, def.shadows);
3152        self.set_sprite_instance_lighting(inst, def.lighting);
3153        let clock = self.clock_for_clip(Some(init_clip), def.speed);
3154        let actor = BillboardActor {
3155            scale: def.scale,
3156            inst,
3157            states: def.states,
3158            cur_state: 0,
3159            pos,
3160            facing_yaw,
3161            mode: def.mode,
3162            clock,
3163            showing: None,
3164            speed: def.speed,
3165        };
3166        let index = self.billboard_actors.len() as u32;
3167        self.billboard_actors.push(Some(actor));
3168        Some(self.actor_map.alloc(index))
3169    }
3170
3171    /// Switch an actor to a named animation state, restarting its clock (the
3172    /// directional clip is reselected on the next
3173    /// [`update_billboard_actors`](Self::update_billboard_actors)). No-op on a
3174    /// stale id or an unknown state name.
3175    pub fn set_actor_state(&mut self, id: BillboardActorId, state: &str) -> bool {
3176        let Some(idx) = self.actor_map.index(id) else {
3177            return false;
3178        };
3179        let Some(a) = self.billboard_actors[idx].as_ref() else {
3180            return false;
3181        };
3182        let Some(state_idx) = a.states.iter().position(|s| s.name == state) else {
3183            return false;
3184        };
3185        let rep = a.states[state_idx].dirs.first().copied();
3186        let speed = a.speed;
3187        let clock = self.clock_for_clip(rep, speed);
3188        let a = self.billboard_actors[idx].as_mut().unwrap();
3189        a.cur_state = state_idx;
3190        a.clock = clock;
3191        a.showing = None; // force a clip reselect next update
3192        true
3193    }
3194
3195    /// Move/turn an actor. Its orientation + directional clip update on the
3196    /// next [`update_billboard_actors`](Self::update_billboard_actors). No-op
3197    /// on a stale id.
3198    pub fn set_actor_transform(&mut self, id: BillboardActorId, pos: [f32; 3], facing_yaw: f64) {
3199        let Some(idx) = self.actor_map.index(id) else {
3200            return;
3201        };
3202        if let Some(a) = self.billboard_actors[idx].as_mut() {
3203            a.pos = pos;
3204            a.facing_yaw = facing_yaw;
3205        }
3206    }
3207
3208    /// Change an actor's lighting mode at runtime (BB.2b) — the per-actor
3209    /// counterpart to [`BillboardActorDef::lighting`], routed to its clip
3210    /// instance via [`set_sprite_instance_lighting`](Self::set_sprite_instance_lighting).
3211    /// Returns `false` on a stale id.
3212    pub fn set_actor_lighting(&mut self, id: BillboardActorId, mode: BillboardLighting) -> bool {
3213        let Some(idx) = self.actor_map.index(id) else {
3214            return false;
3215        };
3216        let Some(inst) = self.billboard_actors[idx].as_ref().map(|a| a.inst) else {
3217            return false;
3218        };
3219        self.set_sprite_instance_lighting(inst, mode);
3220        true
3221    }
3222
3223    /// Tint an actor at runtime — the per-actor counterpart to
3224    /// [`set_sprite_instance_tint`](Self::set_sprite_instance_tint), routed to
3225    /// its clip instance. `tint` is an `0x00RR_GGBB` colour multiply
3226    /// (`0x00FF_FFFF` = white = no-op). Returns `false` on a stale id.
3227    pub fn set_actor_tint(&mut self, id: BillboardActorId, tint: Rgb) -> bool {
3228        let Some(idx) = self.actor_map.index(id) else {
3229            return false;
3230        };
3231        let Some(inst) = self.billboard_actors[idx].as_ref().map(|a| a.inst) else {
3232            return false;
3233        };
3234        self.set_sprite_instance_tint(inst, tint);
3235        true
3236    }
3237
3238    /// Remove an actor and its clip instance. Returns `false` on a stale id.
3239    pub fn remove_billboard_actor(&mut self, id: BillboardActorId) -> bool {
3240        let Some(idx) = self.actor_map.index(id) else {
3241            return false;
3242        };
3243        if let Some(a) = self.billboard_actors[idx].take() {
3244            self.remove_sprite_instance(a.inst);
3245        }
3246        self.actor_map.remove(id)
3247    }
3248
3249    /// Drive every billboard actor by `dt` seconds (BB.4): for each, pick the
3250    /// directional clip from the camera bearing (swapping clips only on
3251    /// change), advance its state-animation clock, and face it to the camera.
3252    /// Call once per frame before `render` (the actor analogue of
3253    /// [`advance_voxel_clips`](Self::advance_voxel_clips) +
3254    /// [`face_billboards_to`](Self::face_billboards_to)). Actors whose
3255    /// instance was removed are pruned.
3256    pub fn update_billboard_actors(&mut self, camera: &Camera, dt: f64) {
3257        struct Action {
3258            inst: SpriteInstanceId,
3259            set_clip: Option<VoxelClipId>,
3260            frame: u32,
3261            xf: Option<DynSpriteTransform>,
3262        }
3263        let cam = camera.pos;
3264        let dyn_map = &self.dyn_map;
3265        let mut actions: Vec<Action> = Vec::new();
3266        for slot in &mut self.billboard_actors {
3267            let Some(a) = slot.as_mut() else {
3268                continue;
3269            };
3270            if dyn_map.dyn_index(a.inst).is_none() {
3271                *slot = None; // instance gone → drop the actor
3272                continue;
3273            }
3274            let dir = a.pick_dir(cam);
3275            let desired = a.states[a.cur_state].dirs[dir];
3276            let set_clip = (a.showing != Some(desired)).then(|| {
3277                a.showing = Some(desired);
3278                desired
3279            });
3280            let frame = a.clock.tick(dt);
3281            let xf = billboard_transform(a.pos, cam, a.mode).map(|mut xf| {
3282                for axis in [&mut xf.right, &mut xf.up, &mut xf.forward] {
3283                    for c in axis.iter_mut() {
3284                        *c *= a.scale;
3285                    }
3286                }
3287                xf
3288            });
3289            actions.push(Action {
3290                inst: a.inst,
3291                set_clip,
3292                frame,
3293                xf,
3294            });
3295        }
3296        // Apply (each call borrows self mutably; disjoint from the loop above).
3297        let mut xforms: Vec<(SpriteInstanceId, DynSpriteTransform)> = Vec::new();
3298        for act in actions {
3299            if let Some(clip) = act.set_clip {
3300                self.set_clip_instance_clip(act.inst, clip);
3301            }
3302            // After a clip swap the backend reset the frame to 0; set the
3303            // clock's frame so the walk cycle stays continuous across turns.
3304            self.set_clip_instance_frame(act.inst, act.frame);
3305            if let Some(xf) = act.xf {
3306                xforms.push((act.inst, xf));
3307            }
3308        }
3309        self.set_sprite_instance_transforms(&xforms);
3310    }
3311
3312    // ---- clip queries (editor inspector) ---------------------------------
3313
3314    /// Frame count of a registered flipbook clip, or `None` if `id` is
3315    /// stale. (Same as `clip_metadata(id)?.frame_count`, without the clone.)
3316    #[must_use]
3317    pub fn clip_frame_count(&self, id: VoxelClipId) -> Option<usize> {
3318        let idx = self.clip_map.index(id)?;
3319        Some(self.clip_meta[idx].durations.len())
3320    }
3321
3322    /// Inspector metadata (dims / pivot / scale / loop mode / per-frame
3323    /// durations) of a registered flipbook clip, or `None` if `id` is stale
3324    /// — so an editor needn't shadow the source [`DecodedClip`].
3325    #[must_use]
3326    pub fn clip_metadata(&self, id: VoxelClipId) -> Option<ClipMetadata> {
3327        let idx = self.clip_map.index(id)?;
3328        let m = &self.clip_meta[idx];
3329        Some(ClipMetadata {
3330            dims: m.dims,
3331            pivot: m.pivot,
3332            voxel_world_size: m.voxel_world_size,
3333            loop_mode: m.loop_mode,
3334            frame_count: m.durations.len(),
3335            durations: m.durations.clone(),
3336            total_ms: m
3337                .durations
3338                .iter()
3339                .fold(0u32, |acc, &d| acc.saturating_add(d)),
3340        })
3341    }
3342
3343    /// Which frame a clip instance is currently showing (the timeline
3344    /// scrubber's read-back), or `None` if `id` isn't a live clip instance.
3345    #[must_use]
3346    pub fn clip_instance_frame(&self, id: SpriteInstanceId) -> Option<u32> {
3347        let dyn_index = self.dyn_map.dyn_index(id)? as usize;
3348        let (_, frame) = (*self.state.dyn_clip.get(dyn_index)?)?;
3349        u32::try_from(frame).ok()
3350    }
3351
3352    /// QE.7b — renamed: this was the only `get_`-prefixed method in
3353    /// the crate. Forwarding shim for one minor release.
3354    #[deprecated(since = "0.22.0", note = "renamed to `clip_instance_frame`")]
3355    #[must_use]
3356    pub fn get_clip_instance_frame(&self, id: SpriteInstanceId) -> Option<u32> {
3357        self.clip_instance_frame(id)
3358    }
3359
3360    /// Re-upload a **single** `frame` of registered clip `id` in place — the
3361    /// editor's one-voxel paint, O(1 frame) instead of `remove_voxel_clip` +
3362    /// `add_voxel_clip` (which rebuilds all N volumes). `vf` must fit the
3363    /// clip's fixed `dims`. Returns `false` on a stale `id`, an out-of-range
3364    /// `frame`, or a frame that fails the clip's layout (so it can't corrupt
3365    /// the flipbook).
3366    pub fn update_clip_frame(&mut self, id: VoxelClipId, frame: u32, vf: &VoxelFrame) -> bool {
3367        let Some(clip_index) = self.clip_map.index(id) else {
3368            return false;
3369        };
3370        let m = &self.clip_meta[clip_index];
3371        let (dims, pivot, vws) = (m.dims, m.pivot, m.voxel_world_size);
3372        if vf.validate(dims).is_err() {
3373            return false;
3374        }
3375        // Re-classify with the clip's registered colour→material map (TV.3) so
3376        // an in-place frame edit keeps the clip's per-voxel materials.
3377        let material_map = m.material_map.clone();
3378        let frame = frame as usize;
3379        match &mut self.inner {
3380            BackendImpl::Cpu(c) => {
3381                c.update_clip_frame(clip_index, frame, vf, dims, pivot, vws, &material_map)
3382            }
3383            BackendImpl::Gpu(g) => {
3384                g.update_clip_frame(clip_index, frame, vf, dims, pivot, vws, &material_map)
3385            }
3386        }
3387    }
3388
3389    // ---- streaming voxel clips (#3) --------------------------------------
3390
3391    /// Register a **streaming** voxel clip — `O(1-frame)` memory (one sprite
3392    /// model + the compact encoded stream) rather than the N-volume flipbook
3393    /// [`add_voxel_clip`](Self::add_voxel_clip) builds, for huge clips where
3394    /// N frames are too costly to hold resident. Builds the model from frame
3395    /// 0; advance it with
3396    /// [`set_streaming_clip_frame`](Self::set_streaming_clip_frame). Spawn
3397    /// instances with
3398    /// [`add_streaming_clip_instance`](Self::add_streaming_clip_instance) —
3399    /// note that, unlike a flipbook, **all** instances of a streaming clip
3400    /// share its one model and so always show the same (current) frame.
3401    ///
3402    /// Takes the *encoded* [`VoxelClip`] (not a [`DecodedClip`]) — the whole
3403    /// point is to avoid materialising every frame.
3404    ///
3405    /// # Errors
3406    /// [`DecodeError`] if the clip's frame stream is empty or doesn't begin
3407    /// with a keyframe.
3408    pub fn add_streaming_clip(&mut self, clip: &VoxelClip) -> Result<StreamingClipId, DecodeError> {
3409        self.add_streaming_clip_with_materials(clip, &[])
3410    }
3411
3412    /// Register a **mixed-material** streaming voxel clip (TV.3): the streaming
3413    /// analogue of
3414    /// [`add_voxel_clip_with_materials`](Self::add_voxel_clip_with_materials).
3415    /// `material_map` pairs a voxel RGB colour with a material id (defined via
3416    /// [`define_material`](Self::define_material)); it is re-applied on every
3417    /// per-frame re-upload, so the single streamed model keeps its per-voxel
3418    /// materials as the clip advances. An empty map is identical to
3419    /// [`add_streaming_clip`](Self::add_streaming_clip).
3420    ///
3421    /// # Errors
3422    /// As [`add_streaming_clip`](Self::add_streaming_clip).
3423    pub fn add_streaming_clip_with_materials(
3424        &mut self,
3425        clip: &VoxelClip,
3426        material_map: &[(Rgb, u8)],
3427    ) -> Result<StreamingClipId, DecodeError> {
3428        let cursor = StreamingClip::new(clip)?;
3429        let dims = cursor.dims();
3430        let pivot = cursor.pivot();
3431        let kv6 = cursor.current_frame().to_kv6(dims, pivot);
3432        let resident_frame = cursor.current_index();
3433        let model = self.add_sprite_model_with_materials(&kv6, material_map);
3434        let index = self.streaming_clips.len() as u32;
3435        self.streaming_clips.push(Some(StreamingClipState {
3436            cursor,
3437            model,
3438            dims,
3439            pivot,
3440            material_map: material_map.to_vec(),
3441            // The model was just built from the cursor's current frame.
3442            last_applied: Some(resident_frame),
3443        }));
3444        Ok(self.streaming_map.alloc(index))
3445    }
3446
3447    /// Spawn an instance of streaming clip `id`, posed by `xf`. Returns a
3448    /// [`SpriteInstanceId`] — move it with
3449    /// [`set_sprite_instance_transform`](Self::set_sprite_instance_transform)
3450    /// and drop it with
3451    /// [`remove_sprite_instance`](Self::remove_sprite_instance), like any
3452    /// dynamic instance. All instances of one streaming clip share its single
3453    /// model. Returns `None` — spawning nothing — on a stale/removed
3454    /// `id` (QE.1c; previously a silent sentinel handle).
3455    pub fn add_streaming_clip_instance(
3456        &mut self,
3457        id: StreamingClipId,
3458        xf: DynSpriteTransform,
3459    ) -> Option<StreamingInstanceId> {
3460        let model = self
3461            .streaming_map
3462            .index(id)
3463            .and_then(|idx| self.streaming_clips[idx].as_ref())
3464            .map(|s| s.model)?;
3465        let inst = self.add_sprite_instance_posed(model, xf)?;
3466        Some(StreamingInstanceId(inst))
3467    }
3468
3469    /// Re-pose a streaming-clip instance (world transform). No-op on a stale
3470    /// handle.
3471    pub fn set_streaming_instance_transform(
3472        &mut self,
3473        id: StreamingInstanceId,
3474        xf: DynSpriteTransform,
3475    ) {
3476        self.set_sprite_instance_transform(id.0, xf);
3477    }
3478
3479    /// Remove a streaming-clip instance. Returns `false` if `id` is stale.
3480    pub fn remove_streaming_instance(&mut self, id: StreamingInstanceId) -> bool {
3481        self.remove_sprite_instance(id.0)
3482    }
3483
3484    /// Advance a streaming clip to `frame`: seek the cursor and re-upload its
3485    /// single model — the per-frame streaming step (one volume re-upload,
3486    /// vs the flipbook's cheap model-select). Updates **every** instance of
3487    /// the clip at once. Drive it from a clock via
3488    /// [`frame_at`](roxlap_formats::voxel_clip::frame_at). No-op on a stale
3489    /// id; `frame` is clamped to the last.
3490    pub fn set_streaming_clip_frame(&mut self, id: StreamingClipId, frame: u32) {
3491        let Some(idx) = self.streaming_map.index(id) else {
3492            return;
3493        };
3494        let Some((model, kv6, material_map)) = self.streaming_clips[idx].as_mut().and_then(|s| {
3495            s.cursor.seek(frame as usize).ok()?;
3496            // PF.5 — same-frame guard on the RESOLVED (clamped) index: skip
3497            // the dense rebuild + re-upload when this frame is already
3498            // resident on the model.
3499            let resolved = s.cursor.current_index();
3500            if s.last_applied == Some(resolved) {
3501                return None;
3502            }
3503            s.last_applied = Some(resolved);
3504            let vf = s.cursor.current_frame();
3505            Some((s.model, vf.to_kv6(s.dims, s.pivot), s.material_map.clone()))
3506        }) else {
3507            return;
3508        };
3509        self.refresh_sprite_model_with_materials(model, &kv6, &material_map);
3510    }
3511
3512    /// Remove a streaming clip: free its model and drop the cursor (the
3513    /// memory win for huge clips). Instances linger but draw nothing until
3514    /// removed. Returns `false` if `id` is stale / already removed.
3515    pub fn remove_streaming_clip(&mut self, id: StreamingClipId) -> bool {
3516        let Some(idx) = self.streaming_map.index(id) else {
3517            return false;
3518        };
3519        let model = self.streaming_clips[idx].as_ref().map(|s| s.model);
3520        self.streaming_clips[idx] = None;
3521        if let Some(model) = model {
3522            self.remove_sprite_model(model);
3523        }
3524        self.streaming_map.remove(id)
3525    }
3526
3527    // ---- auto-advancing clip players (#6) --------------------------------
3528
3529    /// Spawn a flipbook-clip instance that **plays itself**: like
3530    /// [`add_clip_instance_posed`](Self::add_clip_instance_posed), but the
3531    /// facade tracks a playback clock so a single
3532    /// [`advance_voxel_clips`](Self::advance_voxel_clips) call advances every
3533    /// such instance — no per-frame `frame_at` + `set_clip_instance_frame`
3534    /// bookkeeping in the host. `speed` is the playback rate (`1.0` =
3535    /// authored speed, negative = reverse; QE.7b - was Q8, migrate with
3536    /// `speed_q8 as f32 / 256.0`); `start_phase_ms` offsets the clock
3537    /// (stagger copies of one clip). Returns `None` — spawning nothing,
3538    /// registering no player — on a stale/removed `clip` (QE.1c;
3539    /// previously a silent sentinel id).
3540    pub fn add_clip_instance_playing(
3541        &mut self,
3542        clip: VoxelClipId,
3543        xf: DynSpriteTransform,
3544        speed: f32,
3545        start_phase_ms: u32,
3546    ) -> Option<SpriteInstanceId> {
3547        let clip_index = self.clip_map.index(clip)?;
3548        let meta = &self.clip_meta[clip_index];
3549        let clock = ClipClock::new(
3550            &meta.durations,
3551            meta.loop_mode,
3552            speed_to_q8(speed),
3553            f64::from(start_phase_ms),
3554        );
3555        let inst = self.add_clip_instance_posed(clip, xf)?;
3556        self.clip_players.push(ClipPlayer {
3557            target: PlayerTarget::Flipbook(inst),
3558            clock,
3559            paused: false,
3560        });
3561        Some(inst)
3562    }
3563
3564    /// Give a streaming clip ([`add_streaming_clip`](Self::add_streaming_clip))
3565    /// its own playback clock, advanced by
3566    /// [`advance_voxel_clips`](Self::advance_voxel_clips). A streaming clip's
3567    /// frame is per-clip (all its instances share one model), so this is
3568    /// keyed on the clip, not an instance — register instances separately
3569    /// with
3570    /// [`add_streaming_clip_instance`](Self::add_streaming_clip_instance).
3571    /// No-op on a stale `clip`.
3572    ///
3573    /// Control the player (play/pause/scrub) via
3574    /// [`set_streaming_clip_paused`](Self::set_streaming_clip_paused) /
3575    /// [`set_streaming_clip_speed`](Self::set_streaming_clip_speed) /
3576    /// [`set_streaming_clip_clock_ms`](Self::set_streaming_clip_clock_ms), the
3577    /// per-clip analogues of the flipbook `set_clip_instance_*` methods.
3578    /// `speed` is the playback rate (`1.0` = authored; QE.7b - was Q8).
3579    pub fn play_streaming_clip(&mut self, clip: StreamingClipId, speed: f32, start_phase_ms: u32) {
3580        let Some(idx) = self.streaming_map.index(clip) else {
3581            return;
3582        };
3583        let Some(state) = self.streaming_clips[idx].as_ref() else {
3584            return;
3585        };
3586        let clock = ClipClock::new(
3587            state.cursor.durations(),
3588            state.cursor.loop_mode(),
3589            speed_to_q8(speed),
3590            f64::from(start_phase_ms),
3591        );
3592        self.clip_players.push(ClipPlayer {
3593            target: PlayerTarget::Streaming(clip),
3594            clock,
3595            paused: false,
3596        });
3597    }
3598
3599    /// Advance every auto-playing clip ([`add_clip_instance_playing`] /
3600    /// [`play_streaming_clip`]) by `dt` seconds: tick each clock, resolve its
3601    /// frame via [`frame_at`](roxlap_formats::voxel_clip::frame_at), and
3602    /// apply it. Players whose instance / clip was removed are pruned. Call
3603    /// once per frame.
3604    ///
3605    /// [`add_clip_instance_playing`]: Self::add_clip_instance_playing
3606    /// [`play_streaming_clip`]: Self::play_streaming_clip
3607    pub fn advance_voxel_clips(&mut self, dt: f64) {
3608        // Phase 1: tick clocks → (target, frame), pruning dead players.
3609        // Borrow only the maps (disjoint from `clip_players`).
3610        let dyn_map = &self.dyn_map;
3611        let streaming_map = &self.streaming_map;
3612        let mut updates: Vec<(PlayerTarget, u32)> = Vec::new();
3613        self.clip_players.retain_mut(|p| {
3614            let alive = match p.target {
3615                PlayerTarget::Flipbook(inst) => dyn_map.dyn_index(inst).is_some(),
3616                PlayerTarget::Streaming(clip) => streaming_map.index(clip).is_some(),
3617            };
3618            if !alive {
3619                return false;
3620            }
3621            // A paused player keeps its clock + frame (the editor's pause).
3622            if !p.paused {
3623                updates.push((p.target, p.clock.tick(dt)));
3624            }
3625            true
3626        });
3627        // Phase 2: apply (borrows self mutably, disjoint from the above).
3628        for (target, frame) in updates {
3629            self.apply_player_frame(target, frame);
3630        }
3631    }
3632
3633    /// Apply a resolved frame to a player's target (flipbook instance vs.
3634    /// streaming clip).
3635    fn apply_player_frame(&mut self, target: PlayerTarget, frame: u32) {
3636        match target {
3637            PlayerTarget::Flipbook(inst) => self.set_clip_instance_frame(inst, frame),
3638            PlayerTarget::Streaming(clip) => self.set_streaming_clip_frame(clip, frame),
3639        }
3640    }
3641
3642    /// Find the auto-player driving flipbook instance `inst`, if any.
3643    fn flipbook_player_mut(&mut self, inst: SpriteInstanceId) -> Option<&mut ClipPlayer> {
3644        self.clip_players
3645            .iter_mut()
3646            .find(|p| matches!(p.target, PlayerTarget::Flipbook(i) if i == inst))
3647    }
3648
3649    /// Pause / resume the auto-player driving clip instance `id` (the
3650    /// editor's play/pause). No-op if `id` has no player.
3651    pub fn set_clip_instance_paused(&mut self, id: SpriteInstanceId, paused: bool) {
3652        if let Some(p) = self.flipbook_player_mut(id) {
3653            p.paused = paused;
3654        }
3655    }
3656
3657    /// Whether clip instance `id`'s auto-player is paused, or `None` if it
3658    /// has no player.
3659    #[must_use]
3660    pub fn is_clip_instance_paused(&self, id: SpriteInstanceId) -> Option<bool> {
3661        self.clip_players
3662            .iter()
3663            .find(|p| matches!(p.target, PlayerTarget::Flipbook(i) if i == id))
3664            .map(|p| p.paused)
3665    }
3666
3667    /// Set the playback speed (`1.0` = authored rate, negative =
3668    /// reverse; QE.7b — was Q8) of clip instance `id`'s auto-player.
3669    /// No-op if `id` has no player.
3670    pub fn set_clip_instance_speed(&mut self, id: SpriteInstanceId, speed: f32) {
3671        if let Some(p) = self.flipbook_player_mut(id) {
3672            p.clock.speed_q8 = speed_to_q8(speed);
3673        }
3674    }
3675
3676    /// **Scrub**: set clip instance `id`'s playback clock to `clock_ms` and
3677    /// immediately show the matching frame (works while paused). No-op if
3678    /// `id` has no player.
3679    pub fn set_clip_instance_clock_ms(&mut self, id: SpriteInstanceId, clock_ms: f64) {
3680        let Some((target, frame)) = self.flipbook_player_mut(id).map(|p| {
3681            p.clock.clock_ms = clock_ms;
3682            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
3683            let frame = p.clock.frame_for(clock_ms.max(0.0) as u32);
3684            (p.target, frame)
3685        }) else {
3686            return;
3687        };
3688        self.apply_player_frame(target, frame);
3689    }
3690
3691    /// Clip instance `id`'s current playback-clock position (ms), or `None`
3692    /// if it has no player — the scrubber's read-back.
3693    #[must_use]
3694    pub fn clip_instance_clock_ms(&self, id: SpriteInstanceId) -> Option<f64> {
3695        self.clip_players
3696            .iter()
3697            .find(|p| matches!(p.target, PlayerTarget::Flipbook(i) if i == id))
3698            .map(|p| p.clock.clock_ms)
3699    }
3700
3701    /// Find the auto-player driving streaming clip `clip`, if any (a player
3702    /// registered via [`play_streaming_clip`](Self::play_streaming_clip)).
3703    fn streaming_player_mut(&mut self, clip: StreamingClipId) -> Option<&mut ClipPlayer> {
3704        self.clip_players
3705            .iter_mut()
3706            .find(|p| matches!(p.target, PlayerTarget::Streaming(c) if c == clip))
3707    }
3708
3709    /// Pause / resume a streaming clip's auto-player
3710    /// ([`play_streaming_clip`](Self::play_streaming_clip)). No-op if `clip`
3711    /// has no player.
3712    pub fn set_streaming_clip_paused(&mut self, clip: StreamingClipId, paused: bool) {
3713        if let Some(p) = self.streaming_player_mut(clip) {
3714            p.paused = paused;
3715        }
3716    }
3717
3718    /// Whether streaming clip `clip`'s auto-player is paused, or `None` if it
3719    /// has no player.
3720    #[must_use]
3721    pub fn is_streaming_clip_paused(&self, clip: StreamingClipId) -> Option<bool> {
3722        self.clip_players
3723            .iter()
3724            .find(|p| matches!(p.target, PlayerTarget::Streaming(c) if c == clip))
3725            .map(|p| p.paused)
3726    }
3727
3728    /// Set the playback speed (`1.0` = authored rate, negative =
3729    /// reverse; QE.7b — was Q8) of streaming clip `clip`'s
3730    /// auto-player. No-op if `clip` has no player.
3731    pub fn set_streaming_clip_speed(&mut self, clip: StreamingClipId, speed: f32) {
3732        if let Some(p) = self.streaming_player_mut(clip) {
3733            p.clock.speed_q8 = speed_to_q8(speed);
3734        }
3735    }
3736
3737    /// **Scrub** a streaming clip: set its auto-player's clock to `clock_ms`
3738    /// and immediately show the matching frame (works while paused). No-op if
3739    /// `clip` has no player.
3740    pub fn set_streaming_clip_clock_ms(&mut self, clip: StreamingClipId, clock_ms: f64) {
3741        let Some((target, frame)) = self.streaming_player_mut(clip).map(|p| {
3742            p.clock.clock_ms = clock_ms;
3743            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
3744            let frame = p.clock.frame_for(clock_ms.max(0.0) as u32);
3745            (p.target, frame)
3746        }) else {
3747            return;
3748        };
3749        self.apply_player_frame(target, frame);
3750    }
3751
3752    /// Streaming clip `clip`'s current playback-clock position (ms), or
3753    /// `None` if it has no player — the scrubber's read-back.
3754    #[must_use]
3755    pub fn streaming_clip_clock_ms(&self, clip: StreamingClipId) -> Option<f64> {
3756        self.clip_players
3757            .iter()
3758            .find(|p| matches!(p.target, PlayerTarget::Streaming(c) if c == clip))
3759            .map(|p| p.clock.clock_ms)
3760    }
3761
3762    // ---- animated characters (VCL.6) -------------------------------------
3763
3764    /// Register an animated character (RKC v3): upload its meshes as sprite
3765    /// models + its embedded voxel clips as flipbooks, then spawn one
3766    /// renderer instance **per bone attachment** — a static mesh sits at
3767    /// its bone, a clip attachment plays back on its own clock. `clip`
3768    /// selects a skeletal animation clip to drive the bones (`None` =
3769    /// rest pose). Returns a [`CharacterId`]; advance it each frame with
3770    /// [`advance_character`](Self::advance_character).
3771    ///
3772    /// Like clips, this works before any [`set_sprites`](Self::set_sprites);
3773    /// a later `set_sprites` drops all registered characters.
3774    pub fn add_character(&mut self, ch: &Character, clip: Option<usize>) -> CharacterId {
3775        // 1. Meshes → sprite models.
3776        let model_ids: Vec<SpriteModelId> =
3777            ch.meshes.iter().map(|m| self.add_sprite_model(m)).collect();
3778        // 2. Voxel clips → flipbooks; keep each one's timing for the clocks.
3779        let clip_regs: Vec<Option<(VoxelClipId, Vec<u32>, LoopMode)>> = ch
3780            .voxel_clips
3781            .iter()
3782            .map(|vc| {
3783                vc.decode().ok().map(|d| {
3784                    let id = self.add_voxel_clip(&d);
3785                    (id, d.durations, d.loop_mode)
3786                })
3787            })
3788            .collect();
3789        // 3. Build + solve the skeleton (rest pose → bone transforms).
3790        let mut skeleton = ch.to_kfa_sprite(clip);
3791        solve_kfa_limbs(&mut skeleton);
3792        // 4. One instance per attachment, posed by bone × local_offset.
3793        let mut attaches = Vec::new();
3794        for (bi, bone) in ch.bones.iter().enumerate() {
3795            let limb = &skeleton.limbs[bi];
3796            for att in &bone.attachments {
3797                let (s, h, f, p) =
3798                    compose_attachment(limb.s, limb.h, limb.f, limb.p, &att.local_offset);
3799                let xf = DynSpriteTransform {
3800                    pos: p,
3801                    right: s,
3802                    up: h,
3803                    forward: f,
3804                };
3805                match att.target {
3806                    MeshRef::Static(mi) => {
3807                        // The model was registered a few lines up, so the
3808                        // spawn can only fail on an out-of-range mesh index.
3809                        if let Some(inst) = model_ids
3810                            .get(mi)
3811                            .and_then(|&mid| self.add_sprite_instance_posed(mid, xf))
3812                        {
3813                            attaches.push(AttachInst {
3814                                bone: bi,
3815                                local_offset: att.local_offset,
3816                                inst,
3817                                clip: None,
3818                            });
3819                        }
3820                    }
3821                    MeshRef::Clip(ci) => {
3822                        if let Some(Some((cid, durations, loop_mode))) = clip_regs.get(ci) {
3823                            let Some(inst) = self.add_clip_instance_posed(*cid, xf) else {
3824                                continue;
3825                            };
3826                            attaches.push(AttachInst {
3827                                bone: bi,
3828                                local_offset: att.local_offset,
3829                                inst,
3830                                clip: Some(ClipClock::new(
3831                                    durations,
3832                                    *loop_mode,
3833                                    att.playback.speed_q8,
3834                                    f64::from(att.playback.start_phase_ms),
3835                                )),
3836                            });
3837                        }
3838                    }
3839                }
3840            }
3841        }
3842        let clips: Vec<VoxelClipId> = clip_regs
3843            .iter()
3844            .filter_map(|r| r.as_ref().map(|(cid, _, _)| *cid))
3845            .collect();
3846        let idx = self.char_instances.len();
3847        self.char_instances.push(CharInstance {
3848            skeleton,
3849            attaches,
3850            models: model_ids,
3851            clips,
3852        });
3853        self.char_map.alloc(idx as u32)
3854    }
3855
3856    /// Advance a character by `dt` seconds: tick its skeletal animation +
3857    /// each clip attachment's clock, then re-pose every attachment
3858    /// (bone × local_offset) and select each clip's current frame. No-op on
3859    /// a stale id.
3860    pub fn advance_character(&mut self, id: CharacterId, dt: f64) {
3861        let Some(idx) = self.char_map.index(id) else {
3862            return;
3863        };
3864        self.advance_character_at(idx, dt);
3865    }
3866
3867    /// [`advance_character`](Self::advance_character)'s resolved-index
3868    /// core, shared with [`tick`](Self::tick)'s all-characters sweep.
3869    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
3870    fn advance_character_at(&mut self, idx: usize, dt: f64) {
3871        // Phase 1: solve the skeleton + compute each attachment's update,
3872        // borrowing only `char_instances[idx]`.
3873        let updates: Vec<(SpriteInstanceId, DynSpriteTransform, Option<u32>)> = {
3874            let CharInstance {
3875                skeleton, attaches, ..
3876            } = &mut self.char_instances[idx];
3877            skeleton.animsprite((dt * 1000.0) as i32);
3878            solve_kfa_limbs(skeleton);
3879            attaches
3880                .iter_mut()
3881                .map(|a| {
3882                    let limb = &skeleton.limbs[a.bone];
3883                    let (s, h, f, p) =
3884                        compose_attachment(limb.s, limb.h, limb.f, limb.p, &a.local_offset);
3885                    let xf = DynSpriteTransform {
3886                        pos: p,
3887                        right: s,
3888                        up: h,
3889                        forward: f,
3890                    };
3891                    let frame = a.clip.as_mut().map(|c| c.tick(dt));
3892                    (a.inst, xf, frame)
3893                })
3894                .collect()
3895        };
3896        // Phase 2: apply via the facade primitives (disjoint from
3897        // `char_instances`).
3898        for (inst, xf, frame) in updates {
3899            self.set_sprite_instance_transform(inst, xf);
3900            if let Some(f) = frame {
3901                self.set_clip_instance_frame(inst, f);
3902            }
3903        }
3904    }
3905
3906    /// Move/re-orient a character to a new world transform `xf` (the root
3907    /// limb's world pose) **without** ticking its animation or clip clocks —
3908    /// a teleport that holds the current animation frame (e.g. dragging a
3909    /// paused character in an editor). Re-solves the skeleton from the new
3910    /// root + re-poses every attachment; clip frames are left as-is. No-op on
3911    /// a stale id.
3912    pub fn set_character_world_transform(&mut self, id: CharacterId, xf: DynSpriteTransform) {
3913        let Some(idx) = self.char_map.index(id) else {
3914            return;
3915        };
3916        // Phase 1: set the root pose + re-solve (no animsprite), then compute
3917        // each attachment's new transform — borrowing only `char_instances`.
3918        let updates: Vec<(SpriteInstanceId, DynSpriteTransform)> = {
3919            let CharInstance {
3920                skeleton, attaches, ..
3921            } = &mut self.char_instances[idx];
3922            skeleton.p = xf.pos;
3923            skeleton.s = xf.right;
3924            skeleton.h = xf.up;
3925            skeleton.f = xf.forward;
3926            solve_kfa_limbs(skeleton);
3927            attaches
3928                .iter()
3929                .map(|a| {
3930                    let limb = &skeleton.limbs[a.bone];
3931                    let (s, h, f, p) =
3932                        compose_attachment(limb.s, limb.h, limb.f, limb.p, &a.local_offset);
3933                    (
3934                        a.inst,
3935                        DynSpriteTransform {
3936                            pos: p,
3937                            right: s,
3938                            up: h,
3939                            forward: f,
3940                        },
3941                    )
3942                })
3943                .collect()
3944        };
3945        // Phase 2: apply (clip frames untouched — clocks didn't tick).
3946        for (inst, t) in updates {
3947            self.set_sprite_instance_transform(inst, t);
3948        }
3949    }
3950
3951    /// Remove a character, dropping all its attachment instances **and**
3952    /// freeing the sprite models + voxel clips it registered. Returns
3953    /// `false` if `id` is stale.
3954    pub fn remove_character(&mut self, id: CharacterId) -> bool {
3955        let Some(idx) = self.char_map.index(id) else {
3956            return false;
3957        };
3958        let insts: Vec<SpriteInstanceId> = self.char_instances[idx]
3959            .attaches
3960            .iter()
3961            .map(|a| a.inst)
3962            .collect();
3963        for inst in insts {
3964            self.remove_sprite_instance(inst);
3965        }
3966        self.char_instances[idx].attaches.clear();
3967        // Free the models + clips this character registered (else they leak
3968        // until a `set_sprites` — costly for an editor hot-swapping all
3969        // session). `mem::take` so the per-id frees can borrow `self`.
3970        let models = std::mem::take(&mut self.char_instances[idx].models);
3971        let clips = std::mem::take(&mut self.char_instances[idx].clips);
3972        for model in models {
3973            self.remove_sprite_model(model);
3974        }
3975        for clip in clips {
3976            self.remove_voxel_clip(clip);
3977        }
3978        self.char_map.remove(id)
3979    }
3980
3981    /// Register animated KFA sprites (one or more bone hierarchies).
3982    /// The GPU backend uploads each limb's kv6 as an instanced model
3983    /// **once** (appended to the sprite registry) and seeds the limb
3984    /// instances at their current pose; the CPU backend caches the
3985    /// posed limbs for drawing. Call once at setup, after
3986    /// [`set_sprites`](Self::set_sprites), then drive motion per frame
3987    /// with [`update_kfa_poses`](Self::update_kfa_poses).
3988    ///
3989    /// Limbs are posed from the sprites' current
3990    /// [`kfaval`](roxlap_formats::kfa::KfaSprite::kfaval) (advance
3991    /// [`animsprite`](roxlap_formats::kfa::KfaSprite::animsprite) first
3992    /// if using a baked curve), so `kfas` is taken `&mut`.
3993    pub fn set_kfa_sprites(&mut self, kfas: &mut [KfaSprite]) {
3994        match &mut self.inner {
3995            BackendImpl::Cpu(c) => c.set_kfa_sprites(kfas),
3996            BackendImpl::Gpu(g) => g.set_kfa_sprites(kfas),
3997        }
3998    }
3999
4000    /// Re-pose the registered KFA sprites from their current
4001    /// `kfaval[]`. Call each frame after advancing the animation
4002    /// (`kfa.animsprite(dt_ms)` or poking `kfaval[]`). The GPU backend
4003    /// takes the cheap transform-only update (no model-volume
4004    /// re-upload); the CPU backend re-solves limb transforms for the
4005    /// next [`render`](Self::render). Must follow a
4006    /// [`set_kfa_sprites`](Self::set_kfa_sprites) with the same sprites.
4007    pub fn update_kfa_poses(&mut self, kfas: &mut [KfaSprite]) {
4008        match &mut self.inner {
4009            BackendImpl::Cpu(c) => c.update_kfa_poses(kfas),
4010            BackendImpl::Gpu(g) => g.update_kfa_poses(kfas),
4011        }
4012    }
4013
4014    /// Carve the next z-layer off the [`SpriteSet::carve_model`] and
4015    /// re-upload (the demo's `G` hotkey + GPU.12 copy-on-modify). GPU
4016    /// only; a no-op on the CPU backend. Returns the voxels removed.
4017    pub fn carve_active_sprite(&mut self) -> u32 {
4018        match &mut self.inner {
4019            BackendImpl::Cpu(_) => 0,
4020            BackendImpl::Gpu(g) => g.carve_active_sprite(),
4021        }
4022    }
4023
4024    /// Request that a frame be captured for
4025    /// [`take_capture`](Self::take_capture) — screenshots, photo
4026    /// modes, golden tests. Works on **both** backends since QE.7a
4027    /// (previously a GPU no-op — screenshots were impossible on the
4028    /// backend most games run). CPU: the next
4029    /// [`render`](Self::render) copies its composited framebuffer.
4030    /// GPU: arms [`take_capture`](Self::take_capture) to read back the
4031    /// most recent frame.
4032    pub fn request_capture(&mut self) {
4033        match &mut self.inner {
4034            BackendImpl::Cpu(c) => c.request_capture(),
4035            BackendImpl::Gpu(g) => g.request_capture(),
4036        }
4037    }
4038
4039    /// Take the captured frame as packed `0x00RRGGBB` pixels +
4040    /// dimensions (the **logical** resolution on GPU —
4041    /// post-SSAA/posterize, pre-upscale), or `None` if no capture was
4042    /// requested / nothing rendered yet. The GPU readback blocks like
4043    /// [`pick_depth`](Self::pick_depth) — a hotkey path, not
4044    /// per-frame — and returns `None` on wasm (WebGPU can't block).
4045    pub fn take_capture(&mut self) -> Option<(Vec<u32>, u32, u32)> {
4046        match &mut self.inner {
4047            BackendImpl::Cpu(c) => c.take_capture(),
4048            BackendImpl::Gpu(g) => g.take_capture(),
4049        }
4050    }
4051
4052    /// Screen→world picking input: the world-space hit distance `t` at
4053    /// window pixel `(x, y)` from the **last rendered frame**, or `None`
4054    /// for out-of-bounds pixels and sky / no-hit. The host reconstructs
4055    /// the world hit point as `cam.pos + t * normalize(ray_dir)`, where
4056    /// `ray_dir` is the same per-pixel ray the frame was rendered with
4057    /// (see the backend's projection).
4058    ///
4059    /// `t` is the distance to the nearest **scene-grid** surface
4060    /// (terrain + grids); sprites do not occlude it (the sprite pass
4061    /// reads depth read-only), so a cursor sprite under the pointer is
4062    /// transparent to the pick.
4063    ///
4064    /// Cost: the CPU backend reads its in-memory z-buffer (free); the
4065    /// GPU backend stages the depth buffer and blocks on a device poll
4066    /// (cheap at click time — do not call every frame). The GPU path
4067    /// only has depth when the last frame drew sprites (`write_depth`).
4068    #[must_use]
4069    pub fn pick_depth(&self, x: u32, y: u32) -> Option<f32> {
4070        match &self.inner {
4071            BackendImpl::Cpu(c) => c.pick_depth(x, y),
4072            BackendImpl::Gpu(g) => g.pick_depth(x, y),
4073        }
4074    }
4075
4076    /// World-space view-ray direction (un-normalised) for window pixel
4077    /// `(x, y)`, under the projection the **last frame** rendered with.
4078    /// The backends differ (CPU `setcamera` vs GPU vertical-FOV
4079    /// pinhole), so this hides which one is active. `None` before the
4080    /// first frame. Intersect it with a plane for tile picking, or feed
4081    /// it to [`Self::pick`] for a voxel.
4082    #[must_use]
4083    pub fn pixel_ray(&self, camera: &Camera, x: f64, y: f64) -> Option<[f64; 3]> {
4084        match &self.inner {
4085            BackendImpl::Cpu(c) => c.pixel_ray(camera, x, y),
4086            BackendImpl::Gpu(g) => g.pixel_ray(camera, x, y),
4087        }
4088    }
4089
4090    /// Canonical screen→world unproject: the full view [`Ray`]
4091    /// (`camera.pos` origin + unit direction) for window pixel
4092    /// `(x, y)`, under whichever projection the last frame used. The
4093    /// one entry point both backends honour — hosts never reconstruct
4094    /// the projection. `None` before the first frame or for a
4095    /// degenerate ray.
4096    ///
4097    /// Compose with [`roxlap_scene::Scene::raycast`] for depth-free
4098    /// picking that's identical on CPU and GPU:
4099    /// `renderer.view_ray(cam, x, y).and_then(|r| scene.raycast(r.origin, r.dir, max))`.
4100    #[must_use]
4101    pub fn view_ray(&self, camera: &Camera, x: f64, y: f64) -> Option<Ray> {
4102        let d = self.pixel_ray(camera, x, y)?;
4103        let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
4104        if len < 1e-12 {
4105            return None;
4106        }
4107        Some(Ray {
4108            origin: glam::DVec3::from_array([camera.pos[0], camera.pos[1], camera.pos[2]]),
4109            dir: glam::DVec3::new(d[0] / len, d[1] / len, d[2] / len),
4110        })
4111    }
4112
4113    /// One-call screen→world voxel pick: unproject pixel `(x, y)` with
4114    /// the active backend's projection, read the last frame's depth
4115    /// there, reconstruct the world hit, and resolve it to the owning
4116    /// grid + grid-local voxel via [`Scene::resolve_voxel`]. `None` on
4117    /// sky / no-hit, or when no grid claims the surface.
4118    ///
4119    /// `scene` and `camera` must be the ones the last frame rendered;
4120    /// the projection (size + FOV / `hx,hy,hz`) is taken from that
4121    /// frame. Cheap on CPU (in-memory z-buffer); on GPU it stages the
4122    /// depth buffer (a click-time device poll — not per frame).
4123    #[must_use]
4124    pub fn pick(&self, scene: &Scene, camera: &Camera, x: u32, y: u32) -> Option<PickHit> {
4125        let dir = self.pixel_ray(camera, f64::from(x), f64::from(y))?;
4126        let t = f64::from(self.pick_depth(x, y)?);
4127        let len = (dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]).sqrt();
4128        if len < 1e-9 {
4129            return None;
4130        }
4131        let s = t / len; // world = cam.pos + t · (dir / |dir|)
4132        let world = glam::DVec3::new(
4133            camera.pos[0] + dir[0] * s,
4134            camera.pos[1] + dir[1] * s,
4135            camera.pos[2] + dir[2] * s,
4136        );
4137        let (grid, voxel) = scene.resolve_voxel(world, glam::DVec3::from_array(dir))?;
4138        #[allow(clippy::cast_possible_truncation)]
4139        let world_f32 = [world.x as f32, world.y as f32, world.z as f32];
4140        Some(PickHit {
4141            world: world_f32,
4142            grid,
4143            voxel,
4144        })
4145    }
4146}
4147
4148/// A frame in flight (QE-B6) — returned by [`SceneRenderer::frame`].
4149/// Overlays draw into the composited frame with the camera it was
4150/// rendered with; exactly one present happens, by [`Self::present`] /
4151/// [`Self::paint_egui`] or on drop.
4152pub struct Frame<'r> {
4153    renderer: &'r mut SceneRenderer,
4154    /// The camera the frame composited with — overlays must use it.
4155    camera: Camera,
4156    finished: bool,
4157}
4158
4159impl Frame<'_> {
4160    /// Draw world-space overlay lines (see
4161    /// [`SceneRenderer::draw_lines`]); chainable.
4162    #[must_use = "the frame must still be presented (or dropped)"]
4163    pub fn draw_lines(self, lines: &[Line3]) -> Self {
4164        let cam = self.camera;
4165        self.renderer.draw_lines(&cam, lines);
4166        self
4167    }
4168
4169    /// Draw 2D image-sprite quads (see
4170    /// [`SceneRenderer::draw_images`]); chainable.
4171    #[must_use = "the frame must still be presented (or dropped)"]
4172    pub fn draw_images(self, images: &[ImageSprite]) -> Self {
4173        let cam = self.camera;
4174        self.renderer.draw_images(&cam, images);
4175        self
4176    }
4177
4178    /// Present with no UI overlay. Consuming — a second present
4179    /// cannot compile.
4180    pub fn present(mut self) {
4181        self.finish();
4182    }
4183
4184    /// Overlay a tessellated egui UI, then present (`hud` feature) —
4185    /// see [`SceneRenderer::paint_egui`] for the arguments. Consuming.
4186    #[cfg(feature = "hud")]
4187    pub fn paint_egui(
4188        mut self,
4189        jobs: &[egui::ClippedPrimitive],
4190        textures: &egui::TexturesDelta,
4191        pixels_per_point: f32,
4192    ) {
4193        self.finished = true;
4194        self.renderer.paint_egui(jobs, textures, pixels_per_point);
4195    }
4196
4197    fn finish(&mut self) {
4198        if !self.finished {
4199            self.finished = true;
4200            self.renderer.present();
4201        }
4202    }
4203}
4204
4205impl Drop for Frame<'_> {
4206    /// An unfinished frame presents itself — forgetting to present is
4207    /// not representable.
4208    fn drop(&mut self) {
4209        self.finish();
4210    }
4211}
4212
4213#[cfg(test)]
4214mod tests {
4215    use super::*;
4216
4217    /// RP.0 — `Native` resolves to the window size verbatim (the byte-identical
4218    /// gate), `Fixed` ignores the window, `Scale` scales + clamps, and every
4219    /// result is `>= 1` per axis.
4220    #[test]
4221    fn render_resolution_logical_for() {
4222        let win = (1920, 1080);
4223        assert_eq!(RenderResolution::Native.logical_for(win), win);
4224        assert_eq!(
4225            RenderResolution::Fixed { w: 860, h: 520 }.logical_for(win),
4226            (860, 520)
4227        );
4228        // Fixed is independent of the window.
4229        assert_eq!(
4230            RenderResolution::Fixed { w: 860, h: 520 }.logical_for((640, 480)),
4231            (860, 520)
4232        );
4233        assert_eq!(RenderResolution::Scale(0.5).logical_for(win), (960, 540));
4234        // Scale rounds, not truncates: 801 * 0.5 = 400.5 → 401.
4235        assert_eq!(
4236            RenderResolution::Scale(0.5).logical_for((801, 601)),
4237            (401, 301)
4238        );
4239        // Degenerate inputs never produce a zero axis.
4240        assert_eq!(RenderResolution::Scale(0.001).logical_for((1, 1)), (1, 1));
4241        assert_eq!(
4242            RenderResolution::Fixed { w: 0, h: 0 }.logical_for(win),
4243            (1, 1)
4244        );
4245        assert_eq!(RenderResolution::Native.logical_for((0, 0)), (1, 1));
4246    }
4247
4248    /// The handle map must survive the backends' swap-remove indexing:
4249    /// drive a model `DynInstanceMap` against a `Vec` "backend" that
4250    /// swap-removes, and check every live handle keeps resolving to its
4251    /// own payload through a sequence of adds + removes.
4252    #[test]
4253    fn dyn_instance_map_survives_swap_removes() {
4254        let mut map = DynInstanceMap::default();
4255        // The "backend": payload per dynamic index; swap_remove mirrors
4256        // both backends' remove_dyn_instance.
4257        let mut backend: Vec<u32> = Vec::new();
4258        // Our bookkeeping: handle -> the payload we expect it to address.
4259        let mut expect: Vec<(SpriteInstanceId, u32)> = Vec::new();
4260
4261        let add = |map: &mut DynInstanceMap,
4262                   backend: &mut Vec<u32>,
4263                   expect: &mut Vec<(SpriteInstanceId, u32)>,
4264                   payload: u32| {
4265            let dyn_index = backend.len() as u32;
4266            backend.push(payload);
4267            let id = map.alloc(dyn_index);
4268            expect.push((id, payload));
4269        };
4270
4271        for p in 0..6 {
4272            add(&mut map, &mut backend, &mut expect, p);
4273        }
4274
4275        // Remove a middle handle (payload 2) and a later one (payload 4),
4276        // plus the current last — covering swap and no-swap paths.
4277        for victim_payload in [2u32, 4, 5] {
4278            let pos = expect
4279                .iter()
4280                .position(|&(_, p)| p == victim_payload)
4281                .unwrap();
4282            let (id, _) = expect.remove(pos);
4283            let dyn_index = map.dyn_index(id).expect("live handle resolves");
4284            // Backend swap-remove + report moved index (old last), exactly
4285            // like remove_dyn_instance on both backends.
4286            let last = backend.len() - 1;
4287            backend.swap_remove(dyn_index as usize);
4288            let moved = (dyn_index as usize != last).then_some(last as u32);
4289            map.remove(id, dyn_index, moved);
4290            // The removed handle is now stale.
4291            assert!(map.dyn_index(id).is_none(), "removed handle is stale");
4292        }
4293
4294        // Every surviving handle still resolves to its own payload.
4295        for &(id, payload) in &expect {
4296            let idx = map.dyn_index(id).expect("survivor resolves");
4297            assert_eq!(
4298                backend[idx as usize], payload,
4299                "handle addresses its payload"
4300            );
4301        }
4302        assert_eq!(map.order.len(), backend.len());
4303        assert_eq!(backend.len(), expect.len());
4304    }
4305
4306    /// The model slotmap mints stable ids, resolves only live handles,
4307    /// and never reuses a slot — so a removed model's id stays dead and
4308    /// every other id survives the remove.
4309    #[test]
4310    fn dyn_model_map_lifecycle() {
4311        let mut map = EpochSlotMap::default();
4312        // `set_sprites(3 models)` seeds ids 0..3, all live.
4313        map.reset_live(3);
4314        let ids: Vec<SpriteModelId> = (0..3).map(|s| SpriteModelId { slot: s, gen: 0 }).collect();
4315        for (i, &id) in ids.iter().enumerate() {
4316            assert_eq!(map.index(id), Some(i));
4317        }
4318
4319        // Incrementally add a fourth model.
4320        let extra = map.alloc(3);
4321        assert_eq!(extra, SpriteModelId { slot: 3, gen: 0 });
4322        assert_eq!(map.index(extra), Some(3));
4323
4324        // Remove model 1: its handle goes stale, the rest stay valid.
4325        assert!(map.remove(ids[1]));
4326        assert_eq!(map.index(ids[1]), None);
4327        assert_eq!(map.index(ids[0]), Some(0));
4328        assert_eq!(map.index(ids[2]), Some(2));
4329        assert_eq!(map.index(extra), Some(3));
4330
4331        // Double remove / stale removal is a no-op returning false.
4332        assert!(!map.remove(ids[1]));
4333
4334        // A bogus / out-of-range handle resolves to nothing, no panic.
4335        let bogus = SpriteModelId { slot: 999, gen: 0 };
4336        assert_eq!(map.index(bogus), None);
4337        assert!(!map.remove(bogus));
4338
4339        // A handle with a mismatched generation never resolves (guards a
4340        // future compacting registry).
4341        let wrong_gen = SpriteModelId { slot: 0, gen: 7 };
4342        assert_eq!(map.index(wrong_gen), None);
4343    }
4344
4345    /// The voxel-clip slotmap (VCL.4) mints stable ids, resolves only live
4346    /// handles, tombstones in place, and `reset` clears it — mirroring the
4347    /// model slotmap, since clips register append-only too.
4348    #[test]
4349    fn dyn_clip_map_lifecycle() {
4350        let mut map = EpochSlotMap::default();
4351        // Two clips registered incrementally (indices 0, 1).
4352        let c0 = map.alloc(0);
4353        let c1 = map.alloc(1);
4354        assert_eq!(c0, VoxelClipId { slot: 0, gen: 0 });
4355        assert_eq!(map.index(c0), Some(0));
4356        assert_eq!(map.index(c1), Some(1));
4357
4358        // Remove clip 0: stale handle, clip 1 stays valid; slot not reused.
4359        assert!(map.remove(c0));
4360        assert_eq!(map.index(c0), None);
4361        assert_eq!(map.index(c1), Some(1));
4362        // Double / stale / out-of-range removes are false, no panic.
4363        assert!(!map.remove(c0));
4364        assert!(!map.remove(VoxelClipId { slot: 99, gen: 0 }));
4365        // Mismatched generation never resolves.
4366        assert_eq!(map.index(VoxelClipId { slot: 1, gen: 5 }), None);
4367
4368        // `set_sprites` resets the clip layer → ids restart at slot 0, but
4369        // the epoch bumps so old handles don't alias the new clips.
4370        map.reset();
4371        assert_eq!(map.index(c1), None, "reset invalidates old handles");
4372        let again = map.alloc(0); // re-takes slot 0 under the new epoch
4373        assert_eq!(again, VoxelClipId { slot: 0, gen: 1 });
4374        assert_eq!(map.index(again), Some(0));
4375        // The footgun fix: c0 (slot 0, old epoch) must NOT resolve to the new
4376        // clip now occupying slot 0.
4377        assert_eq!(
4378            map.index(c0),
4379            None,
4380            "a pre-reset handle must not alias a new clip on the same slot"
4381        );
4382    }
4383
4384    /// The character slotmap (VCL.6) mints stable ids, resolves only live
4385    /// handles, tombstones in place, and `reset` clears it.
4386    #[test]
4387    fn char_map_lifecycle() {
4388        let mut map = EpochSlotMap::default();
4389        let a = map.alloc(0);
4390        let b = map.alloc(1);
4391        assert_eq!(a, CharacterId { slot: 0, gen: 0 });
4392        assert_eq!(map.index(a), Some(0));
4393        assert_eq!(map.index(b), Some(1));
4394
4395        assert!(map.remove(a));
4396        assert_eq!(map.index(a), None);
4397        assert_eq!(map.index(b), Some(1));
4398        assert!(!map.remove(a)); // double remove is a no-op
4399        assert!(!map.remove(CharacterId { slot: 9, gen: 0 }));
4400        assert_eq!(map.index(CharacterId { slot: 1, gen: 7 }), None);
4401
4402        map.reset();
4403        assert_eq!(map.index(b), None);
4404        assert_eq!(map.alloc(0), CharacterId { slot: 0, gen: 1 });
4405        assert_eq!(map.index(a), None, "pre-reset handle must not alias slot 0");
4406    }
4407
4408    /// The streaming-clip slotmap (#3) mints stable ids, resolves only live
4409    /// handles, tombstones in place, and `reset` clears it.
4410    #[test]
4411    fn streaming_clip_map_lifecycle() {
4412        let mut map = EpochSlotMap::default();
4413        let a = map.alloc(0);
4414        let b = map.alloc(1);
4415        assert_eq!(a, StreamingClipId { slot: 0, gen: 0 });
4416        assert_eq!(map.index(a), Some(0));
4417        assert_eq!(map.index(b), Some(1));
4418
4419        assert!(map.remove(a));
4420        assert_eq!(map.index(a), None);
4421        assert_eq!(map.index(b), Some(1));
4422        assert!(!map.remove(a)); // double remove is a no-op
4423        assert!(!map.remove(StreamingClipId { slot: 9, gen: 0 }));
4424        assert_eq!(map.index(StreamingClipId { slot: 1, gen: 7 }), None);
4425
4426        map.reset();
4427        assert_eq!(map.index(b), None);
4428        assert_eq!(map.alloc(0), StreamingClipId { slot: 0, gen: 1 });
4429        assert_eq!(map.index(a), None, "pre-reset handle must not alias slot 0");
4430    }
4431
4432    /// The shared clip-playback clock (#6 / VCL.6): `tick` accumulates time
4433    /// at its Q8 speed, resolves the frame, honours `start_phase`, and reads
4434    /// a rewound (negative) clock as frame 0.
4435    #[test]
4436    fn clip_clock_tick_advances_and_resolves_frames() {
4437        // 3 frames, 100 ms each → total 300 ms, looping.
4438        let mut c = ClipClock::new(&[100, 100, 100], LoopMode::Loop, 256, 0.0); // 1×
4439        assert_eq!(c.tick(0.0), 0); // t=0 → frame 0
4440        assert_eq!(c.tick(0.10), 1); // t=100 → frame 1 (100 is not < 100)
4441        assert_eq!(c.clock_ms as u32, 100);
4442        assert_eq!(c.tick(0.15), 2); // t=250 → frame 2
4443        assert_eq!(c.tick(0.10), 0); // t=350 → 350%300=50 → frame 0
4444                                     // 0.5× speed advances half as fast.
4445        let mut slow = ClipClock::new(&[100, 100], LoopMode::Once, 128, 0.0); // 0.5×
4446        assert_eq!(slow.tick(0.20), 1); // 200ms wall → 100ms clock → frame 1
4447        assert!((slow.clock_ms - 100.0).abs() < 1e-6);
4448        // start_phase seeds the clock; negative clock reads as frame 0.
4449        // rewind at -1×, clock seeded mid frame 1
4450        let mut phased = ClipClock::new(&[50, 50, 50], LoopMode::Loop, -256, 50.0);
4451        assert_eq!(phased.tick(0.10), 0); // 50 - 100 = -50 → max(0)=0 → frame 0
4452        assert!(phased.clock_ms < 0.0); // kept signed
4453    }
4454
4455    #[test]
4456    fn clip_clock_retarget_swaps_timeline_restarts_keeps_speed() {
4457        // BB.1: swapping a billboard's animation retargets the player's
4458        // timeline (durations + loop) and restarts the clock, but keeps the
4459        // playback rate (the clock policy).
4460        let mut c = ClipClock::new(&[100, 100, 100], LoopMode::Loop, 512, 250.0); // 2×
4461        c.retarget(&[50, 50], LoopMode::Once);
4462        assert_eq!(c.prefix, vec![50, 100]); // new clip's timeline (prefix sums)
4463        assert_eq!(c.loop_mode, LoopMode::Once); // new clip's loop mode
4464        assert!((c.clock_ms - 0.0).abs() < 1e-9); // restarted at frame 0
4465        assert_eq!(c.speed_q8, 512); // playback rate preserved
4466                                     // After retarget, ticking advances on the *new* timeline.
4467        assert_eq!(c.tick(0.0), 0);
4468        assert_eq!(c.tick(0.025), 1); // 25ms wall × 2× = 50ms → frame 1
4469    }
4470
4471    fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
4472        a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
4473    }
4474    fn unit(v: [f32; 3]) -> bool {
4475        (dot(v, v) - 1.0).abs() < 1e-5
4476    }
4477
4478    #[test]
4479    fn billboard_cylindrical_faces_camera_upright_and_ignores_height() {
4480        // Camera due +x of the sprite. Cylindrical normal (local +y) points
4481        // at the camera horizontally; image vertical (local +z) is world up.
4482        let xf = billboard_transform(
4483            [0.0, 0.0, 0.0],
4484            [10.0, 0.0, 0.0],
4485            BillboardMode::Cylindrical,
4486        )
4487        .expect("non-degenerate");
4488        assert_eq!(xf.up, [1.0, 0.0, 0.0]); // normal → toward camera
4489        assert_eq!(xf.forward, BILLBOARD_UP); // image vertical → world up (-z)
4490        assert_eq!(xf.right, [0.0, -1.0, 0.0]); // image horizontal = screen-right
4491                                                // Cylindrical ignores camera height: a camera at a different z gives
4492                                                // the same (vertical) basis.
4493        let high = billboard_transform(
4494            [0.0, 0.0, 0.0],
4495            [10.0, 0.0, -50.0],
4496            BillboardMode::Cylindrical,
4497        )
4498        .unwrap();
4499        assert_eq!(high.up, xf.up);
4500        assert_eq!(high.forward, xf.forward);
4501        // Orthonormal basis.
4502        for v in [xf.right, xf.up, xf.forward] {
4503            assert!(unit(v));
4504        }
4505        assert!(dot(xf.right, xf.up).abs() < 1e-5);
4506        assert!(dot(xf.up, xf.forward).abs() < 1e-5);
4507        assert!(dot(xf.right, xf.forward).abs() < 1e-5);
4508    }
4509
4510    #[test]
4511    fn billboard_spherical_tilts_with_view_and_normal_points_at_camera() {
4512        // Camera above (-z) and in front (+x): the normal tilts up; the
4513        // image vertical gains an up-tilt too (unlike cylindrical).
4514        let cam = [10.0, 0.0, -10.0];
4515        let xf = billboard_transform([0.0, 0.0, 0.0], cam, BillboardMode::Spherical).unwrap();
4516        // Normal (local +y) = normalized direction to the camera.
4517        let n = bb_norm([cam[0] as f32, cam[1] as f32, cam[2] as f32]).unwrap();
4518        for (u, ni) in xf.up.iter().zip(n.iter()) {
4519            assert!((u - ni).abs() < 1e-5);
4520        }
4521        // Not vertical-locked: image vertical tilts off world up.
4522        assert!(xf.forward != BILLBOARD_UP);
4523        for v in [xf.right, xf.up, xf.forward] {
4524            assert!(unit(v));
4525        }
4526        assert!(dot(xf.right, xf.up).abs() < 1e-5);
4527        assert!(dot(xf.up, xf.forward).abs() < 1e-5);
4528        assert!(dot(xf.right, xf.forward).abs() < 1e-5);
4529    }
4530
4531    #[test]
4532    fn dir_index_bins_view_angle_front_ccw() {
4533        let o = [0.0, 0.0, 0.0];
4534        // N == 1 (non-directional) is always 0, regardless of camera.
4535        assert_eq!(dir_index(o, 0.0, [5.0, 3.0, 0.0], 1), 0);
4536        // 8-way, actor facing +x (yaw 0). Camera in front (+x) = front = 0.
4537        assert_eq!(dir_index(o, 0.0, [10.0, 0.0, 0.0], 8), 0);
4538        // Camera at +y (90° CCW from facing) → sector 2 (90° / 45°).
4539        assert_eq!(dir_index(o, 0.0, [0.0, 10.0, 0.0], 8), 2);
4540        // Camera behind (−x, 180°) → sector 4.
4541        assert_eq!(dir_index(o, 0.0, [-10.0, 0.0, 0.0], 8), 4);
4542        // Camera at −y (270°) → sector 6.
4543        assert_eq!(dir_index(o, 0.0, [0.0, -10.0, 0.0], 8), 6);
4544        // Rotating the actor's facing rotates the picked sector: facing +y
4545        // (yaw 90°), camera at +y is now "front" → 0.
4546        let fy = std::f64::consts::FRAC_PI_2;
4547        assert_eq!(dir_index(o, fy, [0.0, 10.0, 0.0], 8), 0);
4548        // Camera straight overhead (no horizontal bearing) → 0.
4549        assert_eq!(dir_index(o, 0.0, [0.0, 0.0, -10.0], 8), 0);
4550        // 4-way still bins front/left/back/right.
4551        assert_eq!(dir_index(o, 0.0, [10.0, 0.0, 0.0], 4), 0);
4552        assert_eq!(dir_index(o, 0.0, [0.0, 10.0, 0.0], 4), 1);
4553    }
4554
4555    #[test]
4556    fn apply_shadow_flags_toggles_bits_and_preserves_others() {
4557        use roxlap_formats::sprite::{SPRITE_FLAG_NO_SHADOW_CAST, SPRITE_FLAG_NO_SHADOW_RECEIVE};
4558        let other = 1u32 << 2; // an unrelated flag bit must survive every call
4559        let mut f = other;
4560        apply_shadow_flags(&mut f, true, true); // both on ⇒ no NO_* bits
4561        assert_eq!(f & SPRITE_FLAG_NO_SHADOW_CAST, 0);
4562        assert_eq!(f & SPRITE_FLAG_NO_SHADOW_RECEIVE, 0);
4563        apply_shadow_flags(&mut f, false, true); // no cast
4564        assert_ne!(f & SPRITE_FLAG_NO_SHADOW_CAST, 0);
4565        assert_eq!(f & SPRITE_FLAG_NO_SHADOW_RECEIVE, 0);
4566        apply_shadow_flags(&mut f, true, false); // no receive
4567        assert_eq!(f & SPRITE_FLAG_NO_SHADOW_CAST, 0);
4568        assert_ne!(f & SPRITE_FLAG_NO_SHADOW_RECEIVE, 0);
4569        apply_shadow_flags(&mut f, false, false); // neither
4570        assert_ne!(f & SPRITE_FLAG_NO_SHADOW_CAST, 0);
4571        assert_ne!(f & SPRITE_FLAG_NO_SHADOW_RECEIVE, 0);
4572        assert_eq!(f & other, other, "unrelated bit preserved throughout");
4573    }
4574
4575    #[test]
4576    fn apply_lighting_flags_sets_exclusive_mode_and_preserves_others() {
4577        use roxlap_formats::sprite::{
4578            SPRITE_FLAG_LIGHT_AMBIENT_ONLY, SPRITE_FLAG_LIGHT_WORLD_UP, SPRITE_FLAG_NO_SHADOW_CAST,
4579        };
4580        let other = SPRITE_FLAG_NO_SHADOW_CAST; // a shadow bit must survive
4581        let mut f = other;
4582        apply_lighting_flags(&mut f, BillboardLighting::WorldUp);
4583        assert_ne!(f & SPRITE_FLAG_LIGHT_WORLD_UP, 0);
4584        assert_eq!(f & SPRITE_FLAG_LIGHT_AMBIENT_ONLY, 0);
4585        apply_lighting_flags(&mut f, BillboardLighting::AmbientOnly);
4586        assert_eq!(f & SPRITE_FLAG_LIGHT_WORLD_UP, 0, "modes are exclusive");
4587        assert_ne!(f & SPRITE_FLAG_LIGHT_AMBIENT_ONLY, 0);
4588        apply_lighting_flags(&mut f, BillboardLighting::FullBright);
4589        assert_ne!(
4590            f & SPRITE_FLAG_LIGHT_WORLD_UP,
4591            0,
4592            "full-bright sets both bits"
4593        );
4594        assert_ne!(f & SPRITE_FLAG_LIGHT_AMBIENT_ONLY, 0);
4595        apply_lighting_flags(&mut f, BillboardLighting::FaceNormal);
4596        assert_eq!(
4597            f & (SPRITE_FLAG_LIGHT_WORLD_UP | SPRITE_FLAG_LIGHT_AMBIENT_ONLY),
4598            0
4599        );
4600        assert_eq!(f & other, other, "unrelated bit preserved throughout");
4601    }
4602
4603    #[test]
4604    fn billboard_degenerate_keeps_position_none_stays_none() {
4605        // Degenerate view axes (camera straight overhead) must still
4606        // yield a transform — a fixed fallback facing — because
4607        // dropping it also drops the POSITION update and the actor
4608        // freezes at its last pose (the CC.4 third-person bug: a
4609        // camera at the actor's own xy column degenerated every
4610        // frame). The card is edge-on right then, so the facing
4611        // itself is cosmetically irrelevant.
4612        let xf = billboard_transform(
4613            [1.0, 2.0, 0.0],
4614            [1.0, 2.0, -10.0],
4615            BillboardMode::Cylindrical,
4616        )
4617        .expect("degenerate cylindrical falls back, not drops");
4618        assert_eq!(xf.pos, [1.0, 2.0, 0.0], "position always lands");
4619        let xf = billboard_transform([1.0, 2.0, 0.0], [1.0, 2.0, -10.0], BillboardMode::Spherical)
4620            .expect("degenerate spherical falls back, not drops");
4621        assert_eq!(xf.pos, [1.0, 2.0, 0.0]);
4622        // None mode is never auto-oriented.
4623        assert!(
4624            billboard_transform([0.0, 0.0, 0.0], [10.0, 0.0, 0.0], BillboardMode::None).is_none()
4625        );
4626    }
4627
4628    #[test]
4629    fn dyn_sprite_transform_default_is_identity_and_applies() {
4630        let xf = DynSpriteTransform::default();
4631        assert_eq!(xf.pos, [0.0, 0.0, 0.0]);
4632        assert_eq!(xf.right, [1.0, 0.0, 0.0]);
4633        assert_eq!(xf.up, [0.0, 1.0, 0.0]);
4634        assert_eq!(xf.forward, [0.0, 0.0, 1.0]);
4635
4636        let mut s = Sprite::axis_aligned(
4637            roxlap_formats::kv6::Kv6::solid_cube(2, roxlap_formats::VoxColor(0x80_FF_FF_FF)),
4638            [9.0, 9.0, 9.0],
4639        );
4640        let posed = DynSpriteTransform {
4641            pos: [1.0, 2.0, 3.0],
4642            right: [0.0, 0.0, 1.0],
4643            up: [0.0, 1.0, 0.0],
4644            forward: [1.0, 0.0, 0.0],
4645        };
4646        posed.apply_to(&mut s);
4647        assert_eq!(s.p, [1.0, 2.0, 3.0]);
4648        assert_eq!(s.s, [0.0, 0.0, 1.0]);
4649        assert_eq!(s.h, [0.0, 1.0, 0.0]);
4650        assert_eq!(s.f, [1.0, 0.0, 0.0]);
4651    }
4652
4653    #[test]
4654    fn options_default_is_cpu_intent() {
4655        let o = RenderOptions::default();
4656        assert_eq!(o.backend, BackendPreference::Cpu);
4657        assert_eq!(o.clear_sky.0 & 0xFF00_0000, 0, "clear_sky is 0x00RRGGBB");
4658    }
4659
4660    /// A camera at the origin looking down +Y (voxlap z-down world): right
4661    /// = +X, down = +Z, forward = +Y. Handedness `right × down == forward`.
4662    fn cam_looking_y() -> Camera {
4663        Camera {
4664            pos: [0.0, 0.0, 0.0],
4665            right: [1.0, 0.0, 0.0],
4666            down: [0.0, 0.0, 1.0],
4667            forward: [0.0, 1.0, 0.0],
4668        }
4669    }
4670
4671    #[test]
4672    fn world_quad_corner_layout() {
4673        // Top-left at (-5, 10, -5); u = +X (width), v = +Z (down). A
4674        // 10×10 quad facing the camera (its +Y normal points back at us).
4675        let sprite = ImageSprite {
4676            image: ImageId { slot: 0, gen: 0 },
4677            origin: [-5.0, 10.0, -5.0],
4678            facing: ImageFacing::World {
4679                u: [1.0, 0.0, 0.0],
4680                v: [0.0, 0.0, 1.0],
4681            },
4682            size: [10.0, 10.0],
4683            tint: OverlayColor(0xFFFF_FFFF),
4684            alpha_cutoff: 0.0,
4685            depth_test: true,
4686            double_sided: true,
4687        };
4688        let q = resolve_quad(&sprite, &cam_looking_y()).expect("front-facing");
4689        assert_eq!(q.corners[0], [-5.0, 10.0, -5.0], "TL = origin");
4690        assert_eq!(q.corners[1], [5.0, 10.0, -5.0], "TR = origin + u·size");
4691        assert_eq!(q.corners[2], [-5.0, 10.0, 5.0], "BL = origin + v·size");
4692        assert_eq!(q.corners[3], [5.0, 10.0, 5.0], "BR = origin + u + v");
4693    }
4694
4695    #[test]
4696    fn world_quad_backface_culls_when_single_sided() {
4697        // Same plane but spanned so its normal (u × v) points *away* from
4698        // the camera: swap u/v so the winding flips.
4699        let sprite = ImageSprite {
4700            image: ImageId { slot: 0, gen: 0 },
4701            origin: [-5.0, 10.0, -5.0],
4702            facing: ImageFacing::World {
4703                u: [0.0, 0.0, 1.0], // v-ish
4704                v: [1.0, 0.0, 0.0], // u-ish → normal flips to -Y... toward camera?
4705            },
4706            size: [10.0, 10.0],
4707            tint: OverlayColor(0xFFFF_FFFF),
4708            alpha_cutoff: 0.0,
4709            depth_test: true,
4710            double_sided: false,
4711        };
4712        // With double_sided=false one of the two windings must cull; the
4713        // opposite winding must draw. Exactly one of the two resolves.
4714        let a = resolve_quad(&sprite, &cam_looking_y()).is_some();
4715        let mut flipped = sprite;
4716        flipped.facing = ImageFacing::World {
4717            u: [1.0, 0.0, 0.0],
4718            v: [0.0, 0.0, 1.0],
4719        };
4720        let b = resolve_quad(&flipped, &cam_looking_y()).is_some();
4721        assert!(a ^ b, "exactly one winding is front-facing");
4722    }
4723
4724    #[test]
4725    fn double_sided_never_culls() {
4726        let mut sprite = ImageSprite {
4727            image: ImageId { slot: 0, gen: 0 },
4728            origin: [-5.0, 10.0, -5.0],
4729            facing: ImageFacing::World {
4730                u: [0.0, 0.0, 1.0],
4731                v: [1.0, 0.0, 0.0],
4732            },
4733            size: [10.0, 10.0],
4734            tint: OverlayColor(0xFFFF_FFFF),
4735            alpha_cutoff: 0.0,
4736            depth_test: true,
4737            double_sided: true,
4738        };
4739        assert!(resolve_quad(&sprite, &cam_looking_y()).is_some());
4740        sprite.facing = ImageFacing::World {
4741            u: [1.0, 0.0, 0.0],
4742            v: [0.0, 0.0, 1.0],
4743        };
4744        assert!(resolve_quad(&sprite, &cam_looking_y()).is_some());
4745    }
4746
4747    #[test]
4748    fn ray_quad_uv_center_and_corners() {
4749        // 10×10 quad on the y=10 plane: TL(-5,10,-5) u=+X v=+Z. Camera at
4750        // origin looking +Y. A ray straight at the quad centre → uv (.5,.5).
4751        let corners = [
4752            [-5.0, 10.0, -5.0], // TL
4753            [5.0, 10.0, -5.0],  // TR
4754            [-5.0, 10.0, 5.0],  // BL
4755            [5.0, 10.0, 5.0],   // BR
4756        ];
4757        let (uv, t) = ray_quad_uv([0.0, 0.0, 0.0], [0.0, 1.0, 0.0], &corners).expect("center hit");
4758        assert!(
4759            (uv[0] - 0.5).abs() < 1e-5 && (uv[1] - 0.5).abs() < 1e-5,
4760            "centre → (.5,.5)"
4761        );
4762        assert!((t - 10.0).abs() < 1e-4, "t = plane distance");
4763        // Ray toward the TL corner texel region (−x, +y, −z) → uv near (0,0).
4764        let (uv_tl, _) = ray_quad_uv([0.0, 0.0, 0.0], [-4.0, 10.0, -4.0], &corners).unwrap();
4765        assert!(uv_tl[0] < 0.2 && uv_tl[1] < 0.2, "toward TL → small uv");
4766    }
4767
4768    #[test]
4769    fn ray_quad_uv_misses_outside_and_behind() {
4770        let corners = [
4771            [-5.0, 10.0, -5.0],
4772            [5.0, 10.0, -5.0],
4773            [-5.0, 10.0, 5.0],
4774            [5.0, 10.0, 5.0],
4775        ];
4776        // Ray pointing away (−Y) never reaches the +Y plane in front.
4777        assert!(ray_quad_uv([0.0, 0.0, 0.0], [0.0, -1.0, 0.0], &corners).is_none());
4778        // Ray parallel to the quad plane (in +X) → no intersection.
4779        assert!(ray_quad_uv([0.0, 0.0, 0.0], [1.0, 0.0, 0.0], &corners).is_none());
4780        // Ray hitting the plane far outside the quad → outside uv.
4781        assert!(ray_quad_uv([100.0, 0.0, 0.0], [0.0, 1.0, 0.0], &corners).is_none());
4782    }
4783
4784    #[test]
4785    fn billboard_axes_orthogonal_and_top_toward_up() {
4786        // World up = -Z (z-down world). The billboard's v (top→bottom)
4787        // must point away from `up`, and u/v must be ⟂ the view direction.
4788        let up = [0.0, 0.0, -1.0];
4789        let sprite = ImageSprite {
4790            image: ImageId { slot: 0, gen: 0 },
4791            origin: [0.0, 50.0, 0.0],
4792            facing: ImageFacing::Billboard { up },
4793            size: [4.0, 4.0],
4794            tint: OverlayColor(0xFFFF_FFFF),
4795            alpha_cutoff: 0.0,
4796            depth_test: false,
4797            double_sided: false, // billboards must NEVER cull
4798        };
4799        let q = resolve_quad(&sprite, &cam_looking_y()).expect("billboard always faces camera");
4800        let u = v_sub(q.corners[1], q.corners[0]); // TR - TL = u·size
4801        let v = v_sub(q.corners[2], q.corners[0]); // BL - TL = v·size
4802        let fwd = [0.0, 1.0, 0.0];
4803        assert!(v_dot(u, fwd).abs() < 1e-5, "u ⟂ view");
4804        assert!(v_dot(v, fwd).abs() < 1e-5, "v ⟂ view");
4805        assert!(v_dot(u, v).abs() < 1e-5, "u ⟂ v");
4806        assert!(
4807            v_dot(v, up) < 0.0,
4808            "rows grow away from `up` (top edge toward up)"
4809        );
4810    }
4811}
4812
4813#[cfg(test)]
4814mod image_map_tests {
4815    use super::{ImageId, ImageSlotMap};
4816
4817    /// QE-B6 regression — image slots are reused by the backends, so
4818    /// a stale handle must resolve to nothing rather than alias the
4819    /// texture that re-took its slot (the pre-B6 behaviour).
4820    #[test]
4821    fn image_ids_are_generational() {
4822        let mut m = ImageSlotMap::default();
4823        let a = m.alloc(0);
4824        assert_eq!(m.index(a), Some(0));
4825        assert!(m.remove(a));
4826        assert_eq!(m.index(a), None);
4827
4828        // The backend hands slot 0 out again: a fresh generation.
4829        let b = m.alloc(0);
4830        assert_ne!(a, b, "reused slot must mint a distinct handle");
4831        assert_eq!(m.index(b), Some(0));
4832        assert_eq!(m.index(a), None, "stale handle stays stale");
4833        assert!(!m.remove(a), "stale drop is refused…");
4834        assert_eq!(m.index(b), Some(0), "…and cannot hurt the newcomer");
4835
4836        // Appending past the end still works.
4837        let c = m.alloc(1);
4838        assert_eq!(m.index(c), Some(1));
4839        let _ = ImageId { slot: 9, gen: 9 };
4840        assert_eq!(m.index(ImageId { slot: 9, gen: 9 }), None);
4841    }
4842}