Skip to main content

roxlap_render/
lib.rs

1//! roxlap-render — unified CPU/GPU renderer facade.
2//!
3//! One [`SceneRenderer`] hides the choice between the CPU opticast
4//! path (`roxlap-core` / `roxlap-scene`, presented via `softbuffer`)
5//! and the GPU compute-shader path (`roxlap-gpu`, presented via its
6//! own wgpu surface). Construction picks the GPU backend when asked
7//! and able, and **falls back to CPU automatically** when WGPU init
8//! fails — so a host never has to branch on GPU availability or carry
9//! the `Scene`→GPU upload/refresh/transform glue itself.
10//!
11//! Hosts stay thin: build a `Scene`, advance it from input, then call
12//! [`SceneRenderer::render`] each frame. The facade owns the window
13//! surface, the framebuffer/z-buffer (CPU) or the resident scene +
14//! dirty-chunk tracking (GPU), and presentation.
15//!
16//! The per-frame flow is `render` → *(optional overlays)* → finish.
17//! Between [`SceneRenderer::render`] and the finishing
18//! [`SceneRenderer::present`] / [`SceneRenderer::paint_egui`] call, a
19//! host may overlay depth-tested world-space lines with
20//! [`SceneRenderer::draw_lines`] (editor gizmos, debug geometry — see
21//! [`Line3`]); they land in the framebuffer, occluded by the rendered
22//! scene, with egui still painting panels on top.
23//!
24//! This is the RF.0 skeleton: backend selection + fallback + a
25//! clear-to-sky frame. RF.1/RF.2 fill in the real CPU/GPU scene
26//! render; RF.3 adds sprites; RF.4 adds framebuffer capture.
27
28#![forbid(unsafe_code)]
29
30mod cpu;
31/// WebGL2 framebuffer presenter for the CPU backend on wasm (the
32/// browser has no `softbuffer`).
33#[cfg(target_arch = "wasm32")]
34mod cpu_blit;
35#[cfg(feature = "hud")]
36mod cpu_egui;
37mod gpu;
38
39#[cfg(not(target_arch = "wasm32"))]
40use std::sync::Arc;
41
42use roxlap_core::kfa_draw::{compose_attachment, solve_kfa_limbs};
43use roxlap_core::opticast::OpticastSettings;
44use roxlap_core::sky::Sky;
45use roxlap_core::Camera;
46use roxlap_formats::voxel_clip::frame_at;
47use roxlap_scene::Scene;
48
49pub use roxlap_formats::character::{Attachment, Character, MeshRef};
50pub use roxlap_formats::kfa::KfaSprite;
51pub use roxlap_formats::kv6::Kv6;
52pub use roxlap_formats::material::{BlendMode, Material};
53pub use roxlap_formats::sprite::Sprite;
54pub use roxlap_formats::voxel_clip::{
55    DecodeError, DecodedClip, LoopMode, StreamingClip, VoxelClip, VoxelFrame,
56};
57pub use roxlap_gpu::{GpuInitError, GpuRendererSettings, PowerPreference};
58// Re-exported so hosts can name the [`SceneRenderer::new`] bounds
59// without adding a direct `raw-window-handle` dependency of their own.
60pub use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
61// Re-exported so hosts feed [`SceneRenderer::paint_egui`] from the exact
62// egui version the renderer was built against (`hud` feature).
63#[cfg(feature = "hud")]
64pub use egui;
65
66use crate::cpu::CpuBackend;
67use crate::gpu::GpuBackend;
68
69/// Type-erased display handle stored by the CPU backend's softbuffer
70/// surface. `raw-window-handle` implements `HasDisplayHandle` for
71/// `Arc<H>` (`H: ?Sized`), and the bare trait object implements its
72/// own object-safe trait — so `Arc<W>` coerces to `Arc<DynDisplay>`
73/// for any provider `W`.
74#[cfg(not(target_arch = "wasm32"))]
75pub(crate) type DynDisplay = dyn HasDisplayHandle + Send + Sync + 'static;
76/// Type-erased window handle counterpart to [`DynDisplay`].
77#[cfg(not(target_arch = "wasm32"))]
78pub(crate) type DynWindow = dyn HasWindowHandle + Send + Sync + 'static;
79
80/// One placed sprite instance: which [`SpriteSet::models`] entry and
81/// where in the world.
82pub struct SpriteInstanceDesc {
83    pub model: usize,
84    pub pos: [f32; 3],
85}
86
87/// Stable handle to a registered sprite model, returned (one per
88/// [`SpriteSet::models`] entry, in order) by
89/// [`SceneRenderer::set_sprites`]. Pass it to
90/// [`refresh_sprite_model`](SceneRenderer::refresh_sprite_model) to
91/// re-register that model's geometry after a content edit — so callers
92/// never track the positional `usize` index themselves. Opaque on
93/// purpose: there is no arithmetic to do on it.
94///
95/// Also returned by [`SceneRenderer::add_sprite_model`] for an
96/// incrementally registered model, and accepted by
97/// [`remove_sprite_model`](SceneRenderer::remove_sprite_model). A handle
98/// to a removed model is **stale**: it resolves to nothing, so passing
99/// it anywhere is a safe no-op. The `gen` (generation) field guards a
100/// future compacting registry; it stays `0` today because model slots
101/// are tombstoned in place and never reused (GPU chain ids are
102/// append-only).
103#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
104pub struct SpriteModelId {
105    pub(crate) slot: u32,
106    pub(crate) gen: u32,
107}
108
109/// Stable handle to a **dynamically added** sprite instance — the result
110/// of [`SceneRenderer::add_sprite_instance`], passed to
111/// [`remove_sprite_instance`](SceneRenderer::remove_sprite_instance).
112///
113/// Backends remove instances by swap (O(1)), which moves another instance
114/// into the freed slot; this handle survives that because the facade keeps
115/// the id↔slot mapping up to date. The generation guards against a stale
116/// handle aliasing a recycled slot.
117#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
118pub struct SpriteInstanceId {
119    slot: u32,
120    gen: u32,
121}
122
123/// Facade-side slotmap that turns the backends' swap-remove indexing into
124/// stable [`SpriteInstanceId`] handles. Both backends keep their dynamic
125/// instances as a tail sublist indexed `0..n`; `order[dyn_index]` is the
126/// owning slot, and a removal fixes up the one slot whose instance was
127/// swapped into the hole.
128#[derive(Default)]
129struct DynInstanceMap {
130    /// Per slot: `(generation, Some(dyn_index) while live)`.
131    slots: Vec<(u32, Option<u32>)>,
132    /// Per live `dyn_index`: the owning slot. Parallel to the backends'
133    /// dynamic sublist (so `order.len()` == the dynamic instance count).
134    order: Vec<u32>,
135    free: Vec<u32>,
136}
137
138impl DynInstanceMap {
139    /// Register a freshly appended instance (always at `dyn_index ==
140    /// order.len()`); returns its stable handle.
141    fn alloc(&mut self, dyn_index: u32) -> SpriteInstanceId {
142        debug_assert_eq!(self.order.len() as u32, dyn_index);
143        let slot = self.free.pop().unwrap_or_else(|| {
144            self.slots.push((0, None));
145            (self.slots.len() - 1) as u32
146        });
147        let gen = self.slots[slot as usize].0;
148        self.slots[slot as usize].1 = Some(dyn_index);
149        self.order.push(slot);
150        SpriteInstanceId { slot, gen }
151    }
152
153    /// Resolve a handle to its current backend `dyn_index`, or `None` if
154    /// it's stale / already removed.
155    fn dyn_index(&self, id: SpriteInstanceId) -> Option<u32> {
156        let (gen, idx) = *self.slots.get(id.slot as usize)?;
157        (gen == id.gen).then_some(idx).flatten()
158    }
159
160    /// Apply a removal: the backend swap-removed `removed` and reported
161    /// `moved` (the old-last `dyn_index` that slid into `removed`, or
162    /// `None` if `removed` was itself the last).
163    fn remove(&mut self, id: SpriteInstanceId, removed: u32, moved: Option<u32>) {
164        self.slots[id.slot as usize].1 = None;
165        self.slots[id.slot as usize].0 += 1; // bump generation
166        self.free.push(id.slot);
167        if let Some(last) = moved {
168            let moved_slot = self.order[last as usize];
169            self.slots[moved_slot as usize].1 = Some(removed);
170            self.order[removed as usize] = moved_slot;
171        }
172        self.order.pop();
173    }
174}
175
176/// Facade-side slotmap for registered sprite **models**, mirroring
177/// [`DynInstanceMap`] but **without** the swap-remove fixup: a model
178/// slot maps 1:1 to the backends' positional model index (the GPU LOD
179/// chain id), which is append-only and never reused. A removed model
180/// tombstones its slot *in place* (the backend frees the voxel data but
181/// keeps the id), so a stale [`SpriteModelId`] resolves to `None` → a
182/// safe no-op rather than aliasing another model.
183#[derive(Default)]
184struct DynModelMap {
185    /// Per slot (== backend model index): `(generation, live)`. Slots are
186    /// never reused, so `generation` stays `0`; `live` flips to `false`
187    /// on removal.
188    slots: Vec<(u32, bool)>,
189}
190
191impl DynModelMap {
192    /// Reset to `n` live models with ids `0..n` — used by
193    /// [`SceneRenderer::set_sprites`], which rebuilds the whole model set
194    /// positionally (model index = chain id on both backends).
195    fn reset(&mut self, n: usize) {
196        self.slots.clear();
197        self.slots.resize(n, (0, true));
198    }
199
200    /// Register a freshly appended model at positional index
201    /// `model_index` (always the new `slots.len()`); returns its handle.
202    fn alloc(&mut self, model_index: u32) -> SpriteModelId {
203        debug_assert_eq!(self.slots.len() as u32, model_index);
204        self.slots.push((0, true));
205        SpriteModelId {
206            slot: model_index,
207            gen: 0,
208        }
209    }
210
211    /// Resolve a handle to its backend model index, or `None` if it's
212    /// stale / already removed.
213    fn model_index(&self, id: SpriteModelId) -> Option<usize> {
214        let (gen, live) = *self.slots.get(id.slot as usize)?;
215        (gen == id.gen && live).then_some(id.slot as usize)
216    }
217
218    /// Tombstone a model slot in place. Returns `false` if the handle is
219    /// stale / already removed.
220    fn remove(&mut self, id: SpriteModelId) -> bool {
221        let Some(slot) = self.slots.get_mut(id.slot as usize) else {
222            return false;
223        };
224        if slot.0 != id.gen || !slot.1 {
225            return false;
226        }
227        slot.1 = false;
228        true
229    }
230}
231
232/// Stable handle to a registered animated voxel clip (VCL.4) — the
233/// result of [`SceneRenderer::add_voxel_clip`], passed to
234/// [`add_clip_instance_posed`](SceneRenderer::add_clip_instance_posed)
235/// and [`remove_voxel_clip`](SceneRenderer::remove_voxel_clip). Like
236/// [`SpriteModelId`], a removed clip's handle is stale → a safe no-op.
237/// Reset by [`set_sprites`](SceneRenderer::set_sprites) (which drops the
238/// dynamic + clip layers).
239#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
240pub struct VoxelClipId {
241    slot: u32,
242    gen: u32,
243}
244
245/// Facade-side slotmap for registered voxel clips — mirrors
246/// [`DynModelMap`]: a clip slot maps 1:1 to the backends' positional clip
247/// index (append-only, tombstoned in place on removal, never reused).
248///
249/// `reset` clears the slots **and bumps `epoch`**, which is baked into each
250/// minted id's `gen`. A handle from before a `set_sprites` therefore carries
251/// the old epoch and resolves to `None` rather than silently aliasing the
252/// new clip that re-took its slot.
253#[derive(Default)]
254struct DynClipMap {
255    /// Per slot: `(epoch_at_alloc, live)`.
256    slots: Vec<(u32, bool)>,
257    epoch: u32,
258}
259
260impl DynClipMap {
261    fn alloc(&mut self, clip_index: u32) -> VoxelClipId {
262        debug_assert_eq!(self.slots.len() as u32, clip_index);
263        self.slots.push((self.epoch, true));
264        VoxelClipId {
265            slot: clip_index,
266            gen: self.epoch,
267        }
268    }
269
270    fn clip_index(&self, id: VoxelClipId) -> Option<usize> {
271        let (gen, live) = *self.slots.get(id.slot as usize)?;
272        (gen == id.gen && live).then_some(id.slot as usize)
273    }
274
275    fn remove(&mut self, id: VoxelClipId) -> bool {
276        let Some(slot) = self.slots.get_mut(id.slot as usize) else {
277            return false;
278        };
279        if slot.0 != id.gen || !slot.1 {
280            return false;
281        }
282        slot.1 = false;
283        true
284    }
285
286    fn reset(&mut self) {
287        self.slots.clear();
288        self.epoch = self.epoch.wrapping_add(1);
289    }
290}
291
292/// Stable handle to a registered animated character (VCL.6) — the result
293/// of [`SceneRenderer::add_character`], advanced each frame with
294/// [`advance_character`](SceneRenderer::advance_character) and dropped with
295/// [`remove_character`](SceneRenderer::remove_character). Reset by
296/// [`set_sprites`](SceneRenderer::set_sprites).
297#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
298pub struct CharacterId {
299    slot: u32,
300    gen: u32,
301}
302
303/// Facade-side slotmap for registered characters (mirrors [`DynClipMap`],
304/// including the epoch bump on `reset` so a pre-`set_sprites` handle
305/// resolves to `None` instead of aliasing a new character).
306#[derive(Default)]
307struct CharMap {
308    /// Per slot: `(epoch_at_alloc, live)`.
309    slots: Vec<(u32, bool)>,
310    epoch: u32,
311}
312
313impl CharMap {
314    fn alloc(&mut self, index: u32) -> CharacterId {
315        debug_assert_eq!(self.slots.len() as u32, index);
316        self.slots.push((self.epoch, true));
317        CharacterId {
318            slot: index,
319            gen: self.epoch,
320        }
321    }
322    fn index(&self, id: CharacterId) -> Option<usize> {
323        let (gen, live) = *self.slots.get(id.slot as usize)?;
324        (gen == id.gen && live).then_some(id.slot as usize)
325    }
326    fn remove(&mut self, id: CharacterId) -> bool {
327        let Some(slot) = self.slots.get_mut(id.slot as usize) else {
328            return false;
329        };
330        if slot.0 != id.gen || !slot.1 {
331            return false;
332        }
333        slot.1 = false;
334        true
335    }
336    fn reset(&mut self) {
337        self.slots.clear();
338        self.epoch = self.epoch.wrapping_add(1);
339    }
340}
341
342/// Stable handle to a registered **streaming** voxel clip (follow-up #3) —
343/// the result of [`SceneRenderer::add_streaming_clip`], advanced with
344/// [`set_streaming_clip_frame`](SceneRenderer::set_streaming_clip_frame) and
345/// dropped with
346/// [`remove_streaming_clip`](SceneRenderer::remove_streaming_clip). Reset by
347/// [`set_sprites`](SceneRenderer::set_sprites).
348#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
349pub struct StreamingClipId {
350    slot: u32,
351    gen: u32,
352}
353
354/// Handle to an instance of a streaming clip
355/// ([`add_streaming_clip_instance`](SceneRenderer::add_streaming_clip_instance)).
356///
357/// Deliberately **distinct** from [`SpriteInstanceId`]: a streaming clip's
358/// frame is per-*clip* (all its instances share one re-uploaded model,
359/// advanced by
360/// [`set_streaming_clip_frame`](SceneRenderer::set_streaming_clip_frame)), so
361/// a streaming instance is *not* accepted by the per-instance
362/// [`set_clip_instance_frame`](SceneRenderer::set_clip_instance_frame) —
363/// trying to scrub two instances of one streaming clip independently is a
364/// compile error, not a silent coupling. (Use a flipbook clip for
365/// per-instance frames.) Move it with
366/// [`set_streaming_instance_transform`](SceneRenderer::set_streaming_instance_transform)
367/// and drop it with
368/// [`remove_streaming_instance`](SceneRenderer::remove_streaming_instance).
369#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
370pub struct StreamingInstanceId(SpriteInstanceId);
371
372/// Facade-side slotmap for streaming clips (mirrors [`CharMap`], epoch bump
373/// on `reset` included).
374#[derive(Default)]
375struct StreamingClipMap {
376    /// Per slot: `(epoch_at_alloc, live)`.
377    slots: Vec<(u32, bool)>,
378    epoch: u32,
379}
380
381impl StreamingClipMap {
382    fn alloc(&mut self, index: u32) -> StreamingClipId {
383        debug_assert_eq!(self.slots.len() as u32, index);
384        self.slots.push((self.epoch, true));
385        StreamingClipId {
386            slot: index,
387            gen: self.epoch,
388        }
389    }
390    fn index(&self, id: StreamingClipId) -> Option<usize> {
391        let (gen, live) = *self.slots.get(id.slot as usize)?;
392        (gen == id.gen && live).then_some(id.slot as usize)
393    }
394    fn remove(&mut self, id: StreamingClipId) -> bool {
395        let Some(slot) = self.slots.get_mut(id.slot as usize) else {
396            return false;
397        };
398        if slot.0 != id.gen || !slot.1 {
399            return false;
400        }
401        slot.1 = false;
402        true
403    }
404    fn reset(&mut self) {
405        self.slots.clear();
406        self.epoch = self.epoch.wrapping_add(1);
407    }
408}
409
410/// One registered streaming clip: the seekable cursor + the single sprite
411/// model it re-uploads each frame, plus the dims/pivot used to rebuild it.
412struct StreamingClipState {
413    cursor: StreamingClip,
414    model: SpriteModelId,
415    dims: [u32; 3],
416    pivot: [f32; 3],
417}
418
419/// Per-clip-attachment playback clock (VCL.6): the timing it needs to
420/// resolve a frame, plus its own accumulating clock.
421struct ClipClock {
422    durations: Vec<u32>,
423    loop_mode: LoopMode,
424    /// Playback rate, Q8 (256 = 1×).
425    speed_q8: i32,
426    /// Accumulated playback time (ms), seeded from the attachment's
427    /// `start_phase_ms`.
428    clock_ms: f64,
429}
430
431impl ClipClock {
432    /// Advance the clock by `dt` seconds at its Q8 `speed` and return the
433    /// frame to show. Shared by character attachments and standalone clip
434    /// players. A negative clock (rewind past 0) reads as frame 0 but is
435    /// kept signed so resuming forward is continuous.
436    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
437    fn tick(&mut self, dt: f64) -> u32 {
438        self.clock_ms += dt * 1000.0 * f64::from(self.speed_q8) / 256.0;
439        frame_at(
440            &self.durations,
441            self.loop_mode,
442            self.clock_ms.max(0.0) as u32,
443        ) as u32
444    }
445}
446
447/// Facade-side metadata captured for a registered flipbook clip, so editor
448/// queries + the auto-player don't shadow the `DecodedClip`.
449struct ClipMeta {
450    dims: [u32; 3],
451    pivot: [f32; 3],
452    voxel_world_size: f32,
453    durations: Vec<u32>,
454    loop_mode: LoopMode,
455}
456
457/// Public metadata for a registered clip — the inspector view returned by
458/// [`SceneRenderer::clip_metadata`].
459#[derive(Clone, Debug, PartialEq)]
460pub struct ClipMetadata {
461    /// Fixed bounding box (voxels).
462    pub dims: [u32; 3],
463    /// Model pivot (the kv6 pivot frames share).
464    pub pivot: [f32; 3],
465    /// Render scale (1 voxel = this many world units).
466    pub voxel_world_size: f32,
467    /// Playback wrap behaviour.
468    pub loop_mode: LoopMode,
469    /// Number of frames.
470    pub frame_count: usize,
471    /// Per-frame durations (ms), one per frame.
472    pub durations: Vec<u32>,
473    /// Total loop length (ms) — sum of `durations`.
474    pub total_ms: u32,
475}
476
477/// What an auto-advancing [`ClipPlayer`] (#6) drives each
478/// [`advance_voxel_clips`](SceneRenderer::advance_voxel_clips). A flipbook
479/// clip's frame is per-instance; a streaming clip's is per-clip (its
480/// instances share one model), so the targets differ.
481#[derive(Clone, Copy)]
482enum PlayerTarget {
483    Flipbook(SpriteInstanceId),
484    Streaming(StreamingClipId),
485}
486
487/// A standalone clip given its own playback clock (#6): the host calls
488/// `advance_voxel_clips(dt)` once instead of hand-driving `frame_at` +
489/// `set_clip_instance_frame`.
490struct ClipPlayer {
491    target: PlayerTarget,
492    clock: ClipClock,
493    /// When `true`, [`advance_voxel_clips`](SceneRenderer::advance_voxel_clips)
494    /// leaves the clock (and frame) untouched — the editor's play/pause.
495    paused: bool,
496}
497
498/// One live bone attachment: which bone drives it, its local offset, the
499/// renderer instance it owns, and (for a clip target) its playback clock.
500struct AttachInst {
501    bone: usize,
502    local_offset: roxlap_formats::xform::BoneXform,
503    inst: SpriteInstanceId,
504    clip: Option<ClipClock>,
505}
506
507/// A live animated character: the hinge skeleton (the bone-transform
508/// solver) + one [`AttachInst`] per bone attachment.
509struct CharInstance {
510    skeleton: KfaSprite,
511    attaches: Vec<AttachInst>,
512    /// Sprite models + voxel clips this character registered, so
513    /// [`remove_character`](SceneRenderer::remove_character) can free them
514    /// (otherwise they leak until the next `set_sprites`).
515    models: Vec<SpriteModelId>,
516    clips: Vec<VoxelClipId>,
517}
518
519/// Orientation + position for a dynamic sprite instance — the per-frame
520/// pose passed to [`SceneRenderer::add_sprite_instance_posed`] and
521/// [`set_sprite_instance_transform`](SceneRenderer::set_sprite_instance_transform).
522///
523/// `right`/`up`/`forward` are the instance's local axes expressed in
524/// world space (the columns of the model→world rotation), mapping
525/// directly onto the underlying [`Sprite`]'s `s`/`h`/`f` (kv6 local
526/// +x/+y/+z). They **must** be non-singular (`det ≠ 0`) but need not be
527/// orthonormal — a uniform/non-uniform scale or shear is fine. A
528/// near-singular basis falls through the renderer's degenerate-basis
529/// guards and the instance silently skips that frame rather than
530/// panicking. [`Default`] is the identity basis (axis-aligned).
531#[derive(Clone, Copy, Debug)]
532pub struct DynSpriteTransform {
533    /// Instance world position (the kv6 pivot maps here).
534    pub pos: [f32; 3],
535    /// Local +x in world space ↦ [`Sprite::s`].
536    pub right: [f32; 3],
537    /// Local +y in world space ↦ [`Sprite::h`].
538    pub up: [f32; 3],
539    /// Local +z in world space ↦ [`Sprite::f`].
540    pub forward: [f32; 3],
541}
542
543impl Default for DynSpriteTransform {
544    fn default() -> Self {
545        Self {
546            pos: [0.0, 0.0, 0.0],
547            right: [1.0, 0.0, 0.0],
548            up: [0.0, 1.0, 0.0],
549            forward: [0.0, 0.0, 1.0],
550        }
551    }
552}
553
554impl DynSpriteTransform {
555    /// Stamp this pose onto a [`Sprite`] in place: `pos → p`,
556    /// `right/up/forward → s/h/f` (a direct copy — the basis is the
557    /// model→world columns). Both backends keep the rest of the template
558    /// (`kv6`, `flags`) and only overwrite the pose.
559    pub(crate) fn apply_to(self, s: &mut Sprite) {
560        s.p = self.pos;
561        s.s = self.right;
562        s.h = self.up;
563        s.f = self.forward;
564    }
565}
566
567/// Backend-agnostic sprite description. The facade builds the CPU
568/// per-instance draw list and the GPU instanced registry from the
569/// same data, so both backends show identical sprites. The host owns
570/// content (which models, where, recolouring) — building a recoloured
571/// variant is just a second [`Sprite`] model with edited `kv6.voxels`.
572pub struct SpriteSet {
573    /// Distinct voxel models (KV6 + base orientation). Instances index
574    /// into this; their position overrides the model's.
575    pub models: Vec<Sprite>,
576    pub instances: Vec<SpriteInstanceDesc>,
577    /// Model the [`SceneRenderer::carve_active_sprite`] hotkey edits
578    /// (GPU only, mirroring the demo's `G`-carve). `None` disables it.
579    pub carve_model: Option<usize>,
580}
581
582/// Per-frame inputs both backends consume. The host builds the
583/// [`OpticastSettings`] (it owns scan distance etc.); the facade does
584/// everything else (pool config, sky fill, render, present).
585pub struct FrameParams<'a> {
586    /// CPU opticast settings (scan distance, mip ladder, framebuffer
587    /// geometry). Ignored by the GPU backend.
588    pub settings: &'a OpticastSettings,
589    /// Packed engine sky colour: the CPU sky-miss fill + skycast, and
590    /// the clear colour if no scene renders.
591    pub sky_color: u32,
592    /// Optional sky panorama for the CPU rasterizer's sky sampling.
593    pub sky: Option<&'a Sky>,
594    /// CPU fog: packed colour + max scan distance (voxels). `0` scan
595    /// distance disables CPU fog.
596    pub fog_color: u32,
597    pub fog_max_scan_dist: i32,
598    /// CPU: treat z=255 as air (avoids the S1.X bedrock path for
599    /// out-of-bounds cameras).
600    pub treat_z_max_as_air: bool,
601    /// GPU scene-grid LOD scan distance (world units); see GPU.11.1.
602    /// Ignored by the CPU backend.
603    pub gpu_mip_scan_dist: f32,
604    /// GPU outer-DDA step budget (chunks). Ignored by the CPU backend.
605    pub gpu_max_outer_steps: u32,
606    /// GPU vertical field of view (radians). Ignored by the CPU
607    /// backend (it derives projection from [`OpticastSettings`]).
608    pub gpu_fov_y_rad: f32,
609    /// Whether to draw the renderer's sprites this frame. Both backends
610    /// draw KV6 sprites flat-lit (the clean-room DDA sprite raycaster on
611    /// CPU; uploaded model colours on GPU), so no host-supplied lighting
612    /// is needed — this is just the on/off opt-in. `false` skips sprite
613    /// drawing.
614    pub draw_sprites: bool,
615    /// Per-face directional shading for the voxel grids — voxlap's
616    /// `setsideshades(top, bot, left, right, up, down)`, the grid-scan
617    /// analogue of [`draw_sprites`](Self::draw_sprites). Each
618    /// entry darkens the faces pointing that way; the host typically
619    /// passes its engine's `side_shades()`. The default `[0; 6]` keeps
620    /// `sideshademode` off (no per-side shading), so existing hosts and
621    /// the oracle goldens are unaffected. Applied each frame by **both**
622    /// backends: the CPU rasteriser via `gcsub`, and the GPU scene-DDA
623    /// pass by darkening a hit voxel's brightness by the hit face's
624    /// shade (the face taken from the DDA's last-stepped axis).
625    pub side_shades: [i8; 6],
626}
627
628/// Result of [`SceneRenderer::pick`] — a resolved screen→world voxel
629/// hit. `world` is the surface point (`cam.pos + t · normalize(ray)`);
630/// `grid` + `voxel` are the owning grid and its **grid-local** voxel
631/// (transform-correct for rotated / translated grids).
632#[derive(Clone, Copy, PartialEq, Debug)]
633pub struct PickHit {
634    pub world: [f32; 3],
635    pub grid: roxlap_scene::GridId,
636    pub voxel: glam::IVec3,
637}
638
639/// A world-space view ray: the canonical unproject output of
640/// [`SceneRenderer::view_ray`]. `dir` is unit-length. Feed it straight
641/// to [`roxlap_scene::Scene::raycast`] for depth-free, backend-agnostic
642/// voxel picking (`scene.raycast(ray.origin, ray.dir, max_dist)`), or
643/// intersect it with a plane for tile selection.
644#[derive(Clone, Copy, PartialEq, Debug)]
645pub struct Ray {
646    pub origin: glam::DVec3,
647    pub dir: glam::DVec3,
648}
649
650/// A world-space line segment to draw over a rendered frame via
651/// [`SceneRenderer::draw_lines`] — editor gizmos (bounding boxes, floor
652/// grids, axes, hover wireframes), debug paths, etc.
653#[derive(Clone, Copy, PartialEq, Debug)]
654pub struct Line3 {
655    /// World-space endpoints (voxel units), in the same frame the
656    /// rendered scene + `camera` use.
657    pub a: [f64; 3],
658    pub b: [f64; 3],
659    /// `0xAARRGGBB` — the high byte is an alpha blend factor (`0xFF`
660    /// opaque, `0x00` invisible), the low 24 bits the RGB colour.
661    pub color: u32,
662    /// Screen-space thickness in pixels (`<= 1.0` draws a 1px line).
663    pub width_px: f32,
664    /// `true`: the segment is occluded by nearer rendered geometry
665    /// (depth-tested against the frame's z-buffer). `false`: always on
666    /// top (e.g. a hover highlight that should show through the model).
667    pub depth_test: bool,
668}
669
670/// A handle to an uploaded image-sprite texture, returned by
671/// [`SceneRenderer::upload_image`]. Positional (like [`SpriteModelId`]):
672/// it indexes the backend's texture store. Pass it in an [`ImageSprite`]
673/// for [`SceneRenderer::draw_images`], or to
674/// [`drop_image`](SceneRenderer::drop_image) to release it. Opaque on
675/// purpose — there's no arithmetic to do on it.
676#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
677pub struct ImageId(pub(crate) usize);
678
679/// How an [`ImageSprite`]'s quad is oriented in the world.
680#[derive(Clone, Copy, PartialEq, Debug)]
681pub enum ImageFacing {
682    /// Fixed in world space: the quad lies in the plane spanned by `u`
683    /// (the image's +column / width direction) and `v` (its +row /
684    /// height direction). Both are world-space directions; their length
685    /// is ignored (the quad is sized by [`ImageSprite::size`]), so pass
686    /// the plane's axes directly. Row 0 of the image is the `origin`
687    /// edge and rows grow along `v`.
688    World { u: [f32; 3], v: [f32; 3] },
689    /// Always faces the camera (billboard); `up` is the world direction
690    /// the image's top edge points toward (e.g. world `-Z` for the
691    /// scene-demo's z-down world, or any "up" the host prefers).
692    Billboard { up: [f32; 3] },
693}
694
695/// One placed 2D image sprite for the current frame: a flat textured
696/// quad in world space, composited over the rendered scene with the
697/// frame's depth buffer (so the voxel model can occlude it). Built per
698/// frame and passed to [`SceneRenderer::draw_images`], mirroring
699/// [`Line3`] / [`SceneRenderer::draw_lines`]. The texture is uploaded
700/// once via [`SceneRenderer::upload_image`] and referenced by [`image`].
701///
702/// [`image`]: ImageSprite::image
703#[derive(Clone, Copy, PartialEq, Debug)]
704pub struct ImageSprite {
705    /// The uploaded texture to draw (from [`SceneRenderer::upload_image`]).
706    pub image: ImageId,
707    /// World position of the quad's **top-left** corner — the image's
708    /// `(column 0, row 0)` texel. The quad extends `size[0]` along the
709    /// facing's `u` and `size[1]` along its `v`.
710    pub origin: [f32; 3],
711    /// World orientation of the quad — fixed in world or camera-facing.
712    pub facing: ImageFacing,
713    /// World size of the quad along `u` and `v`. For pixel-art traced at
714    /// 1 texel = 1 voxel, pass `[width as f32, height as f32]`.
715    pub size: [f32; 2],
716    /// Multiplied into every sampled texel (tint + opacity), `0xAARRGGBB`.
717    /// `0xFFFFFFFF` draws the texture unchanged; the high byte scales
718    /// the texel alpha (e.g. `0x80FFFFFF` = 50 % opacity).
719    pub tint: u32,
720    /// Alpha cutoff in `0.0..=1.0`. Texels whose **own** alpha is below
721    /// this are discarded outright (not blended) — crisp pixel-art edges
722    /// instead of a semi-transparent haze, and the same threshold decides
723    /// what [`SceneRenderer::pick_image`] treats as solid. `0.0` keeps the
724    /// plain straight-alpha over-blend (every non-zero texel draws).
725    pub alpha_cutoff: f32,
726    /// `true`: occluded by nearer rendered geometry (depth-tested against
727    /// the frame's depth buffer, with a bias so a quad resting on a
728    /// coincident voxel face doesn't z-fight). `false`: always on top.
729    pub depth_test: bool,
730    /// `true`: draw regardless of which way the quad faces (no backface
731    /// cull) — what reference images usually want. `false`: cull when the
732    /// quad faces away from the camera. Ignored for
733    /// [`ImageFacing::Billboard`] (it always faces the camera).
734    pub double_sided: bool,
735}
736
737/// Backend-agnostic resolved quad: four world corners (`TL, TR, BL, BR`,
738/// with UVs `(0,0) (1,0) (0,1) (1,1)`) + the texture to map. The facade
739/// resolves [`ImageSprite::facing`] into corners and culls back-facing
740/// quads once, so both backends draw from the same geometry.
741#[derive(Clone, Copy, Debug)]
742pub(crate) struct QuadDraw {
743    pub corners: [[f32; 3]; 4],
744    pub image: ImageId,
745    pub tint: u32,
746    pub depth_test: bool,
747    pub alpha_cutoff: f32,
748}
749
750/// Result of [`SceneRenderer::pick_image`] — a resolved screen→sprite hit.
751/// `uv` is the normalised position within the quad (`(0,0)` = top-left
752/// corner); `texel` is the matching source-image pixel; `world` is the
753/// hit point; `t` is its euclidean distance from the camera.
754#[derive(Clone, Copy, PartialEq, Debug)]
755pub struct ImagePickHit {
756    pub image: ImageId,
757    pub uv: [f32; 2],
758    pub texel: (u32, u32),
759    pub world: [f32; 3],
760    pub t: f32,
761}
762
763/// Which renderer a [`SceneRenderer`] resolved to at construction.
764#[derive(Clone, Copy, PartialEq, Eq, Debug)]
765pub enum Backend {
766    /// `roxlap-core` opticast, presented via `softbuffer`.
767    Cpu,
768    /// `roxlap-gpu` compute marcher, presented via wgpu.
769    Gpu,
770}
771
772/// Construction-time options for [`SceneRenderer::new`].
773pub struct RenderOptions {
774    /// Try the GPU backend first. When `false`, or when GPU init
775    /// fails, the renderer uses the CPU backend.
776    pub want_gpu: bool,
777    /// Settings forwarded to [`roxlap_gpu::GpuRenderer`] when the GPU
778    /// backend is selected.
779    pub gpu: GpuRendererSettings,
780    /// Packed `0x00RRGGBB` (alpha ignored) the empty/clear frame fills
781    /// with until a scene render lands. Also the CPU sky-miss colour
782    /// default if a frame supplies none.
783    pub clear_sky: u32,
784    /// CPU [`ScratchPool`](roxlap_core::rasterizer::ScratchPool) `lastx`
785    /// sizing — the largest combined grid `vsid` the CPU rasterizer
786    /// will see. Pre-sizing keeps later frames allocation-free.
787    pub cpu_max_grid_vsid: u32,
788    /// CPU strip-parallel render thread count (capped to the rayon
789    /// pool). One [`ScratchPool`](roxlap_core::rasterizer::ScratchPool)
790    /// slot per thread.
791    pub cpu_render_threads: usize,
792}
793
794impl Default for RenderOptions {
795    fn default() -> Self {
796        Self {
797            want_gpu: false,
798            gpu: GpuRendererSettings::default(),
799            clear_sky: 0x0099_b3d9,
800            // 32 chunks × CHUNK_SIZE_XY — the scene-demo's widest
801            // combined ground grid.
802            cpu_max_grid_vsid: 32 * roxlap_scene::CHUNK_SIZE_XY,
803            cpu_render_threads: 4,
804        }
805    }
806}
807
808/// Depth-test slack (same spirit as the backends' `DEPTH_BIAS`) so a
809/// [`SceneRenderer::pick_image`] hit on a sprite resting on a coincident
810/// voxel face isn't rejected as "occluded".
811const PICK_DEPTH_BIAS: f32 = 0.5;
812
813// --- image-sprite geometry helpers (shared by both backends) ---
814
815fn v_sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
816    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
817}
818fn v_add(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
819    [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
820}
821fn v_scale(a: [f32; 3], s: f32) -> [f32; 3] {
822    [a[0] * s, a[1] * s, a[2] * s]
823}
824fn v_dot(a: [f32; 3], b: [f32; 3]) -> f32 {
825    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
826}
827fn v_cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
828    [
829        a[1] * b[2] - a[2] * b[1],
830        a[2] * b[0] - a[0] * b[2],
831        a[0] * b[1] - a[1] * b[0],
832    ]
833}
834fn v_norm(a: [f32; 3]) -> [f32; 3] {
835    let len = v_dot(a, a).sqrt();
836    if len < 1e-12 {
837        a
838    } else {
839        v_scale(a, 1.0 / len)
840    }
841}
842
843/// Intersect a ray (`origin` + `dir`, `dir` un-normalised) with a quad
844/// `[TL, TR, BL, BR]` and return `(uv, t)` for a front/back hit inside
845/// the quad — `uv` in `0..=1` (`(0,0)` = `TL`), `t` the ray parameter
846/// (`hit = origin + dir·t`). `None` for a parallel ray, a hit behind the
847/// origin, a degenerate quad, or a hit outside the `u`/`v` span. Solves
848/// affine coords exactly for a (possibly skew) parallelogram. Standalone
849/// so the geometry is unit-testable without a renderer.
850fn ray_quad_uv(
851    origin: [f32; 3],
852    dir: [f32; 3],
853    corners: &[[f32; 3]; 4],
854) -> Option<([f32; 2], f32)> {
855    let [tl, tr, bl, _br] = *corners;
856    let ue = v_sub(tr, tl); // +u edge (width)
857    let ve = v_sub(bl, tl); // +v edge (height)
858    let n = v_cross(ue, ve);
859    let denom = v_dot(dir, n);
860    if denom.abs() < 1e-12 {
861        return None; // ray parallel to the quad's plane
862    }
863    let t = v_dot(v_sub(tl, origin), n) / denom;
864    if t <= 1e-6 {
865        return None; // behind / at the origin
866    }
867    let p = v_add(origin, v_scale(dir, t));
868    let rel = v_sub(p, tl);
869    let guu = v_dot(ue, ue);
870    let guv = v_dot(ue, ve);
871    let gvv = v_dot(ve, ve);
872    let det = guu * gvv - guv * guv;
873    if det.abs() < 1e-12 {
874        return None; // degenerate quad
875    }
876    let wu = v_dot(rel, ue);
877    let wv = v_dot(rel, ve);
878    let a = (gvv * wu - guv * wv) / det;
879    let b = (guu * wv - guv * wu) / det;
880    if !(0.0..=1.0).contains(&a) || !(0.0..=1.0).contains(&b) {
881        return None; // outside the quad
882    }
883    Some(([a, b], t))
884}
885
886/// Resolve an [`ImageSprite`] into its four world corners (`TL, TR, BL,
887/// BR`), or `None` when a `double_sided == false` world quad faces away
888/// from the camera (back-face cull) or its plane is degenerate. The
889/// camera basis is used only for [`ImageFacing::Billboard`] and the cull
890/// test.
891fn resolve_quad(sprite: &ImageSprite, camera: &Camera) -> Option<QuadDraw> {
892    let cam_pos = [
893        camera.pos[0] as f32,
894        camera.pos[1] as f32,
895        camera.pos[2] as f32,
896    ];
897    let cam_fwd = v_norm([
898        camera.forward[0] as f32,
899        camera.forward[1] as f32,
900        camera.forward[2] as f32,
901    ]);
902
903    let (u_hat, v_hat) = match sprite.facing {
904        ImageFacing::World { u, v } => (v_norm(u), v_norm(v)),
905        ImageFacing::Billboard { up } => {
906            // Horizontal axis ⟂ both the view direction and `up`; fall
907            // back to the camera right when `up` is parallel to the view.
908            let mut u_hat = v_norm(v_cross(up, cam_fwd));
909            if v_dot(u_hat, u_hat) < 1e-12 {
910                u_hat = v_norm([
911                    camera.right[0] as f32,
912                    camera.right[1] as f32,
913                    camera.right[2] as f32,
914                ]);
915            }
916            // Vertical axis ⟂ both, pointing *down* (rows grow downward)
917            // so the top edge ends up toward `up`.
918            let mut v_hat = v_norm(v_cross(cam_fwd, u_hat));
919            if v_dot(v_hat, up) > 0.0 {
920                v_hat = v_scale(v_hat, -1.0);
921            }
922            (u_hat, v_hat)
923        }
924    };
925
926    let du = v_scale(u_hat, sprite.size[0]);
927    let dv = v_scale(v_hat, sprite.size[1]);
928    let tl = sprite.origin;
929    let tr = v_add(tl, du);
930    let bl = v_add(tl, dv);
931    let br = v_add(tr, dv);
932
933    // Back-face cull for fixed world quads (billboards always face us).
934    if !sprite.double_sided {
935        if let ImageFacing::World { .. } = sprite.facing {
936            let normal = v_cross(du, dv);
937            // Front-facing when the quad normal points toward the camera.
938            if v_dot(normal, v_sub(cam_pos, tl)) <= 0.0 {
939                return None;
940            }
941        }
942    }
943
944    Some(QuadDraw {
945        corners: [tl, tr, bl, br],
946        image: sprite.image,
947        tint: sprite.tint,
948        depth_test: sprite.depth_test,
949        alpha_cutoff: sprite.alpha_cutoff,
950    })
951}
952
953/// Renderer-internal backend; never exposes wgpu or softbuffer types.
954/// The GPU variant owns the whole wgpu device/queue/pipelines, so
955/// it's boxed to keep the enum small.
956enum BackendImpl {
957    // Both variants boxed so the enum stays small regardless of which
958    // backend's state is larger (clippy::large_enum_variant).
959    Cpu(Box<CpuBackend>),
960    Gpu(Box<GpuBackend>),
961}
962
963/// Unified renderer over the CPU and GPU paths. See the crate docs.
964pub struct SceneRenderer {
965    inner: BackendImpl,
966    /// Handles for dynamically added sprite instances (see
967    /// [`Self::add_sprite_instance`]). Reset by [`Self::set_sprites`].
968    dyn_map: DynInstanceMap,
969    /// Handles for registered sprite models (see [`Self::add_sprite_model`]
970    /// and the models returned by [`Self::set_sprites`]). Reset by
971    /// [`Self::set_sprites`].
972    model_map: DynModelMap,
973    /// Handles for registered animated voxel clips (see
974    /// [`Self::add_voxel_clip`]). Reset by [`Self::set_sprites`].
975    clip_map: DynClipMap,
976    /// Handles for registered animated characters (see
977    /// [`Self::add_character`]). Reset by [`Self::set_sprites`].
978    char_map: CharMap,
979    /// Live character runtimes, parallel to `char_map` slots (VCL.6).
980    char_instances: Vec<CharInstance>,
981    /// Handles for registered streaming clips (see
982    /// [`Self::add_streaming_clip`]). Reset by [`Self::set_sprites`].
983    streaming_map: StreamingClipMap,
984    /// Streaming-clip runtimes (cursor + one re-uploaded model), parallel
985    /// to `streaming_map` slots; `None` once removed (#3).
986    streaming_clips: Vec<Option<StreamingClipState>>,
987    /// Metadata per registered flipbook clip, indexed by the backend clip
988    /// index (parallel to `clip_map`). Captured at [`Self::add_voxel_clip`]
989    /// so the editor queries ([`Self::clip_metadata`]) + the auto-player
990    /// don't have to re-pass / shadow the `DecodedClip`. Reset by
991    /// [`Self::set_sprites`].
992    clip_meta: Vec<ClipMeta>,
993    /// Auto-advancing clip players (#6); ticked by
994    /// [`Self::advance_voxel_clips`]. Reset by [`Self::set_sprites`].
995    clip_players: Vec<ClipPlayer>,
996}
997
998impl SceneRenderer {
999    /// Build a renderer for `window` — any [`raw-window-handle`]
1000    /// provider (winit, SDL, GLFW, …) in an `Arc`. `size` is the
1001    /// window's initial physical framebuffer size in pixels; thereafter
1002    /// the host reports changes via [`Self::resize`]. Passing the size
1003    /// explicitly keeps the facade decoupled from any one windowing
1004    /// library's size API.
1005    ///
1006    /// Selects the GPU backend when `opts.want_gpu` and WGPU
1007    /// initialises; otherwise the CPU backend. **Never fails** — a
1008    /// missing/incompatible GPU silently yields the CPU path (the
1009    /// message is logged to stderr).
1010    ///
1011    /// [`raw-window-handle`]: raw_window_handle
1012    #[cfg(not(target_arch = "wasm32"))]
1013    #[must_use]
1014    pub fn new<W>(window: Arc<W>, size: (u32, u32), opts: &RenderOptions) -> Self
1015    where
1016        W: HasWindowHandle + HasDisplayHandle + Send + Sync + 'static,
1017    {
1018        if opts.want_gpu {
1019            match GpuBackend::new(window.clone(), size, opts) {
1020                Ok(g) => {
1021                    return Self {
1022                        inner: BackendImpl::Gpu(Box::new(g)),
1023                        dyn_map: DynInstanceMap::default(),
1024                        model_map: DynModelMap::default(),
1025                        clip_map: DynClipMap::default(),
1026                        char_map: CharMap::default(),
1027                        char_instances: Vec::new(),
1028                        streaming_map: StreamingClipMap::default(),
1029                        streaming_clips: Vec::new(),
1030                        clip_meta: Vec::new(),
1031                        clip_players: Vec::new(),
1032                    };
1033                }
1034                Err(e) => {
1035                    eprintln!(
1036                        "roxlap-render: GPU init failed ({e}); falling back to the CPU renderer",
1037                    );
1038                }
1039            }
1040        }
1041        Self {
1042            inner: BackendImpl::Cpu(Box::new(CpuBackend::new(window, size, opts))),
1043            dyn_map: DynInstanceMap::default(),
1044            model_map: DynModelMap::default(),
1045            clip_map: DynClipMap::default(),
1046            char_map: CharMap::default(),
1047            char_instances: Vec::new(),
1048            streaming_map: StreamingClipMap::default(),
1049            streaming_clips: Vec::new(),
1050            clip_meta: Vec::new(),
1051            clip_players: Vec::new(),
1052        }
1053    }
1054
1055    /// wasm/WebGPU build-time entry: build a renderer over an HTML
1056    /// `canvas`. `size` is the canvas's initial framebuffer size in
1057    /// pixels; the host reports later changes via [`Self::resize`].
1058    ///
1059    /// Async because the browser drives wgpu's adapter/device requests
1060    /// through its event loop — `await` it inside a
1061    /// `wasm_bindgen_futures::spawn_local` task. Selects the GPU
1062    /// (WebGPU) backend when `opts.want_gpu` and WebGPU is available;
1063    /// otherwise (no WebGPU, or init failed) it falls back to the CPU
1064    /// opticast path presented through a WebGL2 blit on the same canvas.
1065    /// **Never fails** — the message is logged to the browser console.
1066    #[cfg(target_arch = "wasm32")]
1067    pub async fn new_from_canvas_async(
1068        canvas: web_sys::HtmlCanvasElement,
1069        size: (u32, u32),
1070        opts: &RenderOptions,
1071    ) -> Self {
1072        if opts.want_gpu {
1073            // `SurfaceTarget::Canvas` moves the canvas into wgpu, so the
1074            // GPU attempt gets a clone — the CPU fallback keeps the
1075            // original if WebGPU init fails.
1076            match GpuBackend::new_async(canvas.clone(), size, opts).await {
1077                Ok(g) => {
1078                    return Self {
1079                        inner: BackendImpl::Gpu(Box::new(g)),
1080                        dyn_map: DynInstanceMap::default(),
1081                        model_map: DynModelMap::default(),
1082                        clip_map: DynClipMap::default(),
1083                        char_map: CharMap::default(),
1084                        char_instances: Vec::new(),
1085                        streaming_map: StreamingClipMap::default(),
1086                        streaming_clips: Vec::new(),
1087                        clip_meta: Vec::new(),
1088                        clip_players: Vec::new(),
1089                    };
1090                }
1091                Err(e) => {
1092                    web_sys::console::warn_1(
1093                        &format!("roxlap-render: WebGPU init failed ({e}); using the CPU renderer")
1094                            .into(),
1095                    );
1096                }
1097            }
1098        }
1099        Self {
1100            inner: BackendImpl::Cpu(Box::new(CpuBackend::new_from_canvas(canvas, size, opts))),
1101            dyn_map: DynInstanceMap::default(),
1102            model_map: DynModelMap::default(),
1103            clip_map: DynClipMap::default(),
1104            char_map: CharMap::default(),
1105            char_instances: Vec::new(),
1106            streaming_map: StreamingClipMap::default(),
1107            streaming_clips: Vec::new(),
1108            clip_meta: Vec::new(),
1109            clip_players: Vec::new(),
1110        }
1111    }
1112
1113    /// Which backend was selected.
1114    #[must_use]
1115    pub fn backend(&self) -> Backend {
1116        match self.inner {
1117            BackendImpl::Cpu(_) => Backend::Cpu,
1118            BackendImpl::Gpu(_) => Backend::Gpu,
1119        }
1120    }
1121
1122    /// The GPU adapter description when on the GPU backend, else
1123    /// `None`.
1124    #[must_use]
1125    pub fn adapter_info(&self) -> Option<&str> {
1126        match &self.inner {
1127            BackendImpl::Gpu(g) => Some(g.adapter_info()),
1128            BackendImpl::Cpu(_) => None,
1129        }
1130    }
1131
1132    /// Upload an equirectangular sky panorama (RGBA8, `w×h`) for the
1133    /// GPU marcher's sky sampling. No-op on the CPU backend, which
1134    /// samples the [`Sky`] passed in each [`FrameParams`] instead.
1135    pub fn set_sky_panorama(&mut self, rgba: &[u8], w: u32, h: u32) {
1136        if let BackendImpl::Gpu(g) = &mut self.inner {
1137            g.set_sky_panorama(rgba, w, h);
1138        }
1139    }
1140
1141    /// Follow a window resize. CPU resizes its framebuffer lazily, so
1142    /// this only matters to the GPU swapchain — but it's safe to call
1143    /// for both.
1144    pub fn resize(&mut self, width: u32, height: u32) {
1145        match &mut self.inner {
1146            BackendImpl::Cpu(c) => c.resize(width, height),
1147            BackendImpl::Gpu(g) => g.resize(width, height),
1148        }
1149    }
1150
1151    /// Composite `scene` from `camera` with `frame` params into the
1152    /// backend's frame buffer — **without presenting**. The CPU backend
1153    /// fills sky + runs the opticast compositor into an owned buffer;
1154    /// the GPU backend uploads/refreshes the scene, runs the compute
1155    /// marcher + sprite pass, and acquires (but does not present) the
1156    /// swapchain frame.
1157    ///
1158    /// Finish the frame with exactly one of [`present`](Self::present)
1159    /// (no overlay) or [`paint_egui`](Self::paint_egui) (UI overlay).
1160    /// Calling `render` again without finishing drops the pending frame.
1161    pub fn render(&mut self, scene: &mut Scene, camera: &Camera, frame: &FrameParams) {
1162        match &mut self.inner {
1163            BackendImpl::Cpu(c) => c.render(scene, camera, frame),
1164            BackendImpl::Gpu(g) => g.render(scene, camera, frame),
1165        }
1166    }
1167
1168    /// Draw world-space [`Line3`] segments over the frame
1169    /// [`render`](Self::render) composited, using that frame's camera +
1170    /// projection + depth buffer. Call **after** [`render`](Self::render)
1171    /// and **before** [`present`](Self::present) /
1172    /// [`paint_egui`](Self::paint_egui) — the lines land in the
1173    /// framebuffer, so a subsequent `paint_egui` still draws its panels
1174    /// on top.
1175    ///
1176    /// `camera` must be the one the last frame rendered with (the
1177    /// projection is taken from that frame). Depth-tested segments
1178    /// (`Line3::depth_test`) are occluded by nearer rendered geometry;
1179    /// always-on-top segments ignore depth. See [`Line3`] for colour /
1180    /// width / blend semantics.
1181    pub fn draw_lines(&mut self, camera: &Camera, lines: &[Line3]) {
1182        match &mut self.inner {
1183            BackendImpl::Cpu(c) => c.draw_lines(camera, lines),
1184            BackendImpl::Gpu(g) => g.draw_lines(camera, lines),
1185        }
1186    }
1187
1188    /// Upload (or replace) an RGBA8 image and return a stable [`ImageId`]
1189    /// to reference it in [`draw_images`](Self::draw_images). `rgba` is
1190    /// row-major, `width * height * 4` bytes, **straight** (un-premultiplied)
1191    /// alpha. The texture is retained until [`drop_image`](Self::drop_image),
1192    /// so the per-frame draw call stays cheap. Sampling is
1193    /// nearest-neighbour (pixel-art friendly — no blurring).
1194    ///
1195    /// Returns `None` for malformed input — a wrong byte count
1196    /// (`!= width·height·4`) or a zero dimension — so a bad upload can't be
1197    /// confused with the first valid id (`ImageId(0)`).
1198    pub fn upload_image(&mut self, rgba: &[u8], width: u32, height: u32) -> Option<ImageId> {
1199        if width == 0 || height == 0 || rgba.len() != (width as usize) * (height as usize) * 4 {
1200            return None;
1201        }
1202        Some(match &mut self.inner {
1203            BackendImpl::Cpu(c) => c.upload_image(rgba, width, height),
1204            BackendImpl::Gpu(g) => g.upload_image(rgba, width, height),
1205        })
1206    }
1207
1208    /// Release a texture uploaded with [`upload_image`](Self::upload_image).
1209    /// The id must not be reused afterwards (a later `upload_image` may
1210    /// hand the slot back out under a fresh id).
1211    pub fn drop_image(&mut self, id: ImageId) {
1212        match &mut self.inner {
1213            BackendImpl::Cpu(c) => c.drop_image(id),
1214            BackendImpl::Gpu(g) => g.drop_image(id),
1215        }
1216    }
1217
1218    /// Draw 2D [`ImageSprite`]s over the frame [`render`](Self::render)
1219    /// composited — flat textured quads placed in world space, using that
1220    /// frame's camera + projection + depth buffer. Same contract as
1221    /// [`draw_lines`](Self::draw_lines): call **after** [`render`](Self::render)
1222    /// and **before** [`present`](Self::present) / [`paint_egui`](Self::paint_egui).
1223    ///
1224    /// UVs are perspective-correct (no affine warp on an obliquely-viewed
1225    /// quad). Depth-tested sprites are occluded by nearer rendered
1226    /// geometry (with a bias to avoid z-fighting on a coincident face);
1227    /// the texture's straight alpha + the [`ImageSprite::tint`] composite
1228    /// over the scene. `camera` must be the one the last frame rendered.
1229    pub fn draw_images(&mut self, camera: &Camera, images: &[ImageSprite]) {
1230        if images.is_empty() {
1231            return;
1232        }
1233        let quads: Vec<QuadDraw> = images
1234            .iter()
1235            .filter_map(|s| resolve_quad(s, camera))
1236            .collect();
1237        if quads.is_empty() {
1238            return;
1239        }
1240        match &mut self.inner {
1241            BackendImpl::Cpu(c) => c.draw_images(camera, &quads),
1242            BackendImpl::Gpu(g) => g.draw_images(camera, &quads),
1243        }
1244    }
1245
1246    /// Project a world point to window pixel coordinates `(x, y)` under
1247    /// the projection the **last frame** rendered with — the backend-correct
1248    /// `world → screen` inverse of [`view_ray`](Self::view_ray). `None`
1249    /// before the first frame or for a point at/behind the camera near
1250    /// plane.
1251    ///
1252    /// Both backends honour their own projection (CPU `setcamera`
1253    /// `hx/hy/hz`, GPU vertical-FOV pinhole), so hosts never reconstruct
1254    /// it themselves. The returned `(x, y)` may fall outside `[0, w) ×
1255    /// [0, h)` for points off-screen but in front of the camera.
1256    #[must_use]
1257    pub fn project_point(&self, camera: &Camera, world: [f32; 3]) -> Option<(f32, f32)> {
1258        match &self.inner {
1259            BackendImpl::Cpu(c) => c.project_point(camera, world),
1260            BackendImpl::Gpu(g) => g.project_point(camera, world),
1261        }
1262    }
1263
1264    /// Screen→sprite pick: the nearest [`ImageSprite`] hit under window
1265    /// pixel `(x, y)`, resolving which texel was clicked. `sprites` is the
1266    /// same list passed to [`draw_images`](Self::draw_images) (image
1267    /// sprites are immediate-mode, so the caller owns the set). `None` for
1268    /// a miss.
1269    ///
1270    /// The ray is intersected with each quad's plane and mapped to its
1271    /// `uv` / source texel. A texel whose alpha is below the sprite's
1272    /// [`ImageSprite::alpha_cutoff`] (and any fully-transparent texel) is
1273    /// **see-through** — the pick passes through it to a sprite behind.
1274    /// For [`depth_test`](ImageSprite::depth_test) sprites the hit is
1275    /// rejected when nearer scene geometry occludes that pixel (shares the
1276    /// depth convention + bias of [`pick`](Self::pick); on the GPU backend
1277    /// the occlusion test costs a click-time depth readback).
1278    #[must_use]
1279    pub fn pick_image(
1280        &self,
1281        camera: &Camera,
1282        x: f64,
1283        y: f64,
1284        sprites: &[ImageSprite],
1285    ) -> Option<ImagePickHit> {
1286        if sprites.is_empty() {
1287            return None;
1288        }
1289        let dir = self.pixel_ray(camera, x, y)?;
1290        let dir = [dir[0] as f32, dir[1] as f32, dir[2] as f32];
1291        let dir_len = v_dot(dir, dir).sqrt();
1292        if dir_len < 1e-9 {
1293            return None;
1294        }
1295        let origin = [
1296            camera.pos[0] as f32,
1297            camera.pos[1] as f32,
1298            camera.pos[2] as f32,
1299        ];
1300        // Scene surface distance under this pixel (sky / no-hit → None);
1301        // used to occlude depth-tested sprites. Same metric as `pick`.
1302        let scene_t = self.pick_depth(x as u32, y as u32);
1303
1304        let mut best: Option<ImagePickHit> = None;
1305        for sprite in sprites {
1306            // Reuse the render-path resolve (back-face cull included), so
1307            // a single-sided quad that isn't drawn also can't be picked.
1308            let Some(q) = resolve_quad(sprite, camera) else {
1309                continue;
1310            };
1311            let Some(([a, b], t)) = ray_quad_uv(origin, dir, &q.corners) else {
1312                continue; // miss / parallel / behind
1313            };
1314            let d_eucl = t * dir_len;
1315            if best.is_some_and(|cur| d_eucl >= cur.t) {
1316                continue; // a nearer sprite already won
1317            }
1318            let p = v_add(origin, v_scale(dir, t));
1319
1320            let Some((iw, ih)) = self.image_dims(sprite.image) else {
1321                continue; // dropped / unknown image
1322            };
1323            let tx = ((a * iw as f32) as i32).clamp(0, iw as i32 - 1) as u32;
1324            let ty = ((b * ih as f32) as i32).clamp(0, ih as i32 - 1) as u32;
1325
1326            // See-through test: a texel is solid when its alpha clears the
1327            // cutoff (and a fully-transparent texel is never solid).
1328            let cutoff_u8 = (sprite.alpha_cutoff.clamp(0.0, 1.0) * 255.0) as u32;
1329            let solid_thresh = cutoff_u8.max(1);
1330            if u32::from(self.image_alpha_at(sprite.image, tx, ty)) < solid_thresh {
1331                continue;
1332            }
1333
1334            // Occlusion: a depth-tested sprite behind nearer geometry loses.
1335            if sprite.depth_test {
1336                if let Some(st) = scene_t {
1337                    if d_eucl > st + PICK_DEPTH_BIAS {
1338                        continue;
1339                    }
1340                }
1341            }
1342
1343            best = Some(ImagePickHit {
1344                image: sprite.image,
1345                uv: [a, b],
1346                texel: (tx, ty),
1347                world: p,
1348                t: d_eucl,
1349            });
1350        }
1351        best
1352    }
1353
1354    /// Source dimensions of an uploaded image, or `None` if the id was
1355    /// dropped / never uploaded. Internal helper for [`Self::pick_image`].
1356    fn image_dims(&self, id: ImageId) -> Option<(u32, u32)> {
1357        match &self.inner {
1358            BackendImpl::Cpu(c) => c.image_dims(id),
1359            BackendImpl::Gpu(g) => g.image_dims(id),
1360        }
1361    }
1362
1363    /// Alpha byte of texel `(tx, ty)` in an uploaded image (`0` for an
1364    /// unknown id / out-of-range texel). Internal helper for
1365    /// [`Self::pick_image`].
1366    fn image_alpha_at(&self, id: ImageId, tx: u32, ty: u32) -> u8 {
1367        match &self.inner {
1368            BackendImpl::Cpu(c) => c.image_alpha_at(id, tx, ty),
1369            BackendImpl::Gpu(g) => g.image_alpha_at(id, tx, ty),
1370        }
1371    }
1372
1373    /// Mirror the rendered 3D scene horizontally before display. The flip is
1374    /// applied *before* any egui overlay, so the UI stays upright while the
1375    /// viewport un-mirrors — a fix for the engine's left-handed render.
1376    /// Supported on both backends (CPU reverses the framebuffer rows; GPU
1377    /// mirrors the scene blit + line/image overlays). Picking/projection are
1378    /// unchanged, so a host that flips must mirror its cursor X (`width - x`)
1379    /// for ray casts.
1380    pub fn set_flip_x(&mut self, flip: bool) {
1381        match &mut self.inner {
1382            BackendImpl::Cpu(c) => c.set_flip_x(flip),
1383            BackendImpl::Gpu(g) => g.set_flip_x(flip),
1384        }
1385    }
1386
1387    /// Present the frame [`render`](Self::render) composited, with no UI
1388    /// overlay. Pairs with `render`; use [`paint_egui`](Self::paint_egui)
1389    /// instead to overlay an egui UI before presenting.
1390    pub fn present(&mut self) {
1391        match &mut self.inner {
1392            BackendImpl::Cpu(c) => c.present(),
1393            BackendImpl::Gpu(g) => g.present(),
1394        }
1395    }
1396
1397    /// Overlay an egui UI on the frame [`render`](Self::render)
1398    /// composited, then present it (`hud` feature). The host runs egui
1399    /// itself (e.g. `egui` + `egui-winit`) and passes the tessellated
1400    /// `jobs` ([`egui::Context::tessellate`]) and the per-frame
1401    /// `textures` delta from [`egui::FullOutput`]; `pixels_per_point` is
1402    /// the UI scale (`ctx.pixels_per_point()`).
1403    ///
1404    /// The GPU backend paints via `egui-wgpu`; the CPU backend
1405    /// software-rasterises the tessellation into its framebuffer. Use
1406    /// this **instead of** [`present`](Self::present) — both finish the
1407    /// frame.
1408    #[cfg(feature = "hud")]
1409    pub fn paint_egui(
1410        &mut self,
1411        jobs: &[egui::ClippedPrimitive],
1412        textures: &egui::TexturesDelta,
1413        pixels_per_point: f32,
1414    ) {
1415        match &mut self.inner {
1416            BackendImpl::Cpu(c) => c.paint_egui(jobs, textures, pixels_per_point),
1417            BackendImpl::Gpu(g) => g.paint_egui(jobs, textures, pixels_per_point),
1418        }
1419    }
1420
1421    /// Register sprite models + instances. The CPU backend builds a
1422    /// per-instance draw list; the GPU backend builds an instanced
1423    /// model registry. Call once at setup (or again to replace).
1424    pub fn set_sprites(&mut self, set: &SpriteSet) -> Vec<SpriteModelId> {
1425        match &mut self.inner {
1426            BackendImpl::Cpu(c) => c.set_sprites(set),
1427            BackendImpl::Gpu(g) => g.set_sprites(set),
1428        }
1429        // A fresh sprite set replaces the instance world, so any
1430        // previously added dynamic instances + models are gone — drop their
1431        // handles and re-seat the model slotmap with `set.models.len()`
1432        // live ids `0..n` (model index = chain id on both backends).
1433        self.dyn_map = DynInstanceMap::default();
1434        self.model_map.reset(set.models.len());
1435        // A full sprite rebuild drops the dynamic + clip layers on both
1436        // backends (the GPU registry is replaced), so reset the clip +
1437        // character maps too.
1438        self.clip_map.reset();
1439        self.char_map.reset();
1440        self.char_instances.clear();
1441        self.streaming_map.reset();
1442        self.streaming_clips.clear();
1443        self.clip_meta.clear();
1444        self.clip_players.clear();
1445        (0..set.models.len() as u32)
1446            .map(|slot| SpriteModelId { slot, gen: 0 })
1447            .collect()
1448    }
1449
1450    /// Re-register one sprite model's geometry after you've edited its
1451    /// content (a carve or recolour of its `kv6`). `model` is the
1452    /// [`SpriteModelId`] handed back by [`set_sprites`](Self::set_sprites);
1453    /// `kv6` is the model's **new** geometry — the caller owns the source
1454    /// of truth (e.g. a dense carve grid the surface-only `kv6` can't
1455    /// represent) and supplies the refreshed mesh here.
1456    ///
1457    /// This is a **backend-agnostic content refresh**, not a GPU upload:
1458    /// the renderer brings its stored model up to date however its active
1459    /// backend needs to. The instance set is left untouched (an edit never
1460    /// moves or adds an instance), so on the GPU backend only that one
1461    /// model's voxel data is re-uploaded — through a slack-backed
1462    /// suballocator, one model's bytes rather than the whole registry —
1463    /// while the CPU backend swaps the cached `kv6` into each instance of
1464    /// the model. Use [`set_sprites`](Self::set_sprites) to add/remove
1465    /// models or change the instance set.
1466    pub fn refresh_sprite_model(&mut self, model: SpriteModelId, kv6: &Kv6) {
1467        let Some(idx) = self.model_map.model_index(model) else {
1468            return; // stale / removed handle → no-op
1469        };
1470        match &mut self.inner {
1471            BackendImpl::Cpu(c) => c.update_sprite_model(idx, kv6),
1472            BackendImpl::Gpu(g) => g.update_sprite_model(idx, kv6),
1473        }
1474    }
1475
1476    /// Add one sprite instance of an already-registered `model` at world
1477    /// `pos`, **incrementally** — the cheap streaming-spawn path that both
1478    /// backends now share (GPU: append to the instance buffer, growing by
1479    /// powers of two; CPU: push one pre-posed [`Sprite`]). Returns a
1480    /// stable [`SpriteInstanceId`] for later removal.
1481    ///
1482    /// `model` must be a [`SpriteModelId`] from the current
1483    /// [`set_sprites`](Self::set_sprites) (a model registered there, even
1484    /// with zero initial instances). Dynamic instances live *after* the
1485    /// static set + any KFA limbs, so register those first.
1486    pub fn add_sprite_instance(&mut self, model: SpriteModelId, pos: [f32; 3]) -> SpriteInstanceId {
1487        self.add_sprite_instance_posed(
1488            model,
1489            DynSpriteTransform {
1490                pos,
1491                ..DynSpriteTransform::default()
1492            },
1493        )
1494    }
1495
1496    /// Add one sprite instance of an already-registered `model`,
1497    /// pre-posed with the orientation in `xf` — the streaming-spawn path
1498    /// for objects that appear mid-flight already rotated (so there's no
1499    /// one-frame axis-aligned flash before the first
1500    /// [`set_sprite_instance_transform`](Self::set_sprite_instance_transform)).
1501    /// Otherwise identical to
1502    /// [`add_sprite_instance`](Self::add_sprite_instance) (which is just
1503    /// this with the identity basis). Returns a stable
1504    /// [`SpriteInstanceId`].
1505    ///
1506    /// A stale/removed `model` handle spawns nothing and returns a handle
1507    /// that is itself already stale (it resolves to no instance). `xf`'s
1508    /// basis must be non-singular; a degenerate one makes the instance
1509    /// silently skip drawing (see [`DynSpriteTransform`]).
1510    pub fn add_sprite_instance_posed(
1511        &mut self,
1512        model: SpriteModelId,
1513        xf: DynSpriteTransform,
1514    ) -> SpriteInstanceId {
1515        let Some(idx) = self.model_map.model_index(model) else {
1516            // Stale model → spawn nothing; hand back a sentinel id that
1517            // resolves to no live instance (a safe no-op everywhere).
1518            return SpriteInstanceId {
1519                slot: u32::MAX,
1520                gen: u32::MAX,
1521            };
1522        };
1523        let dyn_index = match &mut self.inner {
1524            BackendImpl::Cpu(c) => c.add_dyn_instance_posed(idx, xf),
1525            BackendImpl::Gpu(g) => g.add_dyn_instance_posed(idx, xf),
1526        };
1527        self.dyn_map.alloc(dyn_index as u32)
1528    }
1529
1530    /// Remove a dynamic sprite instance added by
1531    /// [`add_sprite_instance`](Self::add_sprite_instance). O(1) on both
1532    /// backends (swap-remove); other dynamic handles stay valid. Returns
1533    /// `false` if the handle is stale / already removed.
1534    pub fn remove_sprite_instance(&mut self, id: SpriteInstanceId) -> bool {
1535        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
1536            return false;
1537        };
1538        let moved = match &mut self.inner {
1539            BackendImpl::Cpu(c) => c.remove_dyn_instance(dyn_index as usize),
1540            BackendImpl::Gpu(g) => g.remove_dyn_instance(dyn_index as usize),
1541        };
1542        self.dyn_map.remove(id, dyn_index, moved.map(|m| m as u32));
1543        true
1544    }
1545
1546    /// Number of live dynamic sprite instances (those added via
1547    /// [`add_sprite_instance`](Self::add_sprite_instance)).
1548    #[must_use]
1549    pub fn dynamic_sprite_count(&self) -> usize {
1550        self.dyn_map.order.len()
1551    }
1552
1553    /// Register one new sprite **model** incrementally from `kv6`,
1554    /// **without** rebuilding the existing model set — the streaming-in
1555    /// counterpart to [`add_sprite_instance`](Self::add_sprite_instance)
1556    /// for unique generated geometry (procedural asteroids, debris).
1557    /// Returns a stable [`SpriteModelId`] usable immediately with
1558    /// [`add_sprite_instance`](Self::add_sprite_instance) /
1559    /// [`add_sprite_instance_posed`](Self::add_sprite_instance_posed).
1560    ///
1561    /// Works before any [`set_sprites`](Self::set_sprites) (it establishes
1562    /// residency on the GPU backend's first model). The GPU backend
1563    /// appends one LOD chain to the resident registry (amortised O(model
1564    /// Define a global voxel **material** (TV stage): the opacity + blend
1565    /// mode that a per-voxel material id resolves to. The renderer owns one
1566    /// 256-entry palette shared by every model and grid.
1567    ///
1568    /// Id `0` is permanently [`Material::OPAQUE`] — the value every voxel
1569    /// without explicit material data resolves to — and **cannot** be
1570    /// redefined; passing `id == 0` is a no-op that returns `false`. Any
1571    /// other id returns `true`.
1572    ///
1573    /// While no translucent material is defined the renderer stays on the
1574    /// fully-opaque fast path, so this is inert until first called. See
1575    /// `PORTING-TRANSPARENCY.md`.
1576    pub fn define_material(&mut self, id: u8, mat: Material) -> bool {
1577        match &mut self.inner {
1578            BackendImpl::Cpu(c) => c.define_material(id, mat),
1579            BackendImpl::Gpu(g) => g.define_material(id, mat),
1580        }
1581    }
1582
1583    /// The [`Material`] currently at palette `id` ([`Material::OPAQUE`] for
1584    /// any id never passed to [`define_material`](Self::define_material)).
1585    #[must_use]
1586    pub fn material(&self, id: u8) -> Material {
1587        match &self.inner {
1588            BackendImpl::Cpu(c) => c.material(id),
1589            BackendImpl::Gpu(g) => g.material(id),
1590        }
1591    }
1592
1593    /// Set the **terrain** colour→material map (TV.4): pairs of `(rgb,
1594    /// material_id)` that make matching-colour world (grid) voxels translucent
1595    /// — glass walls, water pools. The materials themselves are defined via
1596    /// [`define_material`](Self::define_material). An empty map (the default)
1597    /// keeps all terrain opaque. The CPU backend composites these today; the
1598    /// GPU backend renders them once the TV.6 device path lands.
1599    pub fn set_terrain_materials(&mut self, map: &[(u32, u8)]) {
1600        match &mut self.inner {
1601            BackendImpl::Cpu(c) => c.set_terrain_materials(map),
1602            BackendImpl::Gpu(g) => g.set_terrain_materials(map),
1603        }
1604    }
1605
1606    /// voxels)); the CPU backend pushes an axis-aligned template.
1607    pub fn add_sprite_model(&mut self, kv6: &Kv6) -> SpriteModelId {
1608        let model_index = match &mut self.inner {
1609            BackendImpl::Cpu(c) => c.add_model(kv6),
1610            BackendImpl::Gpu(g) => g.add_model(kv6),
1611        };
1612        self.model_map.alloc(model_index as u32)
1613    }
1614
1615    /// Register a **mixed-material** sprite model (TV.3): `material_map` pairs
1616    /// a voxel RGB colour (`0xRRGGBB`) with a material id (defined via
1617    /// [`define_material`](Self::define_material)), so a single model can mix
1618    /// opaque and translucent voxels — an opaque window frame around glass, a
1619    /// bottle around a translucent potion. Voxels whose colour isn't in the
1620    /// map are opaque (material 0). Like [`add_sprite_model`](Self::add_sprite_model)
1621    /// otherwise.
1622    ///
1623    /// The CPU backend composites per-voxel materials today; the GPU backend
1624    /// carries the data and renders per-voxel materials once the TV.3b device
1625    /// path lands (until then it uses the instance's uniform material).
1626    pub fn add_sprite_model_with_materials(
1627        &mut self,
1628        kv6: &Kv6,
1629        material_map: &[(u32, u8)],
1630    ) -> SpriteModelId {
1631        let model_index = match &mut self.inner {
1632            BackendImpl::Cpu(c) => c.add_model_with_materials(kv6, material_map),
1633            BackendImpl::Gpu(g) => g.add_model_with_materials(kv6, material_map),
1634        };
1635        self.model_map.alloc(model_index as u32)
1636    }
1637
1638    /// Remove a registered sprite model, freeing its voxel data. Returns
1639    /// `false` if `id` is stale / already removed.
1640    ///
1641    /// The model's slot is tombstoned **in place**: its id is never
1642    /// reused, so every other [`SpriteModelId`] stays valid (no remap).
1643    /// Existing instances of the removed model are **not** dropped here —
1644    /// they linger but draw as nothing on the GPU backend (the CPU
1645    /// backend keeps each instance's own kv6 clone, so they keep drawing
1646    /// until removed via
1647    /// [`remove_sprite_instance`](Self::remove_sprite_instance)); remove
1648    /// them when convenient. Call
1649    /// [`compact_sprite_models`](Self::compact_sprite_models) afterwards
1650    /// to reclaim the GPU buffer holes.
1651    pub fn remove_sprite_model(&mut self, id: SpriteModelId) -> bool {
1652        let Some(idx) = self.model_map.model_index(id) else {
1653            return false;
1654        };
1655        match &mut self.inner {
1656            BackendImpl::Cpu(c) => c.remove_model(idx),
1657            BackendImpl::Gpu(g) => g.remove_model(idx),
1658        }
1659        self.model_map.remove(id)
1660    }
1661
1662    /// Reclaim the GPU buffer space left by
1663    /// [`remove_sprite_model`](Self::remove_sprite_model) by repacking the
1664    /// resident registry to its live models only. Model ids are preserved
1665    /// (no remap). O(live voxel volume) — call it when many models have
1666    /// been removed, not every frame. No-op on the CPU backend (which
1667    /// keeps cheap empty placeholders) and when nothing was removed.
1668    pub fn compact_sprite_models(&mut self) {
1669        match &mut self.inner {
1670            BackendImpl::Cpu(c) => c.compact_models(),
1671            BackendImpl::Gpu(g) => g.compact_models(),
1672        }
1673    }
1674
1675    /// Update one dynamic instance's full pose (position + orientation)
1676    /// for this frame. `id` is from
1677    /// [`add_sprite_instance`](Self::add_sprite_instance) /
1678    /// [`add_sprite_instance_posed`](Self::add_sprite_instance_posed). A
1679    /// stale / removed handle is a no-op.
1680    ///
1681    /// For many instances per frame prefer
1682    /// [`set_sprite_instance_transforms`](Self::set_sprite_instance_transforms):
1683    /// the GPU backend flushes all pending pose changes to the device
1684    /// once per [`render`](Self::render), so a per-instance call here is
1685    /// still O(1) device work, but the batch variant avoids re-walking
1686    /// the slotmap.
1687    pub fn set_sprite_instance_transform(&mut self, id: SpriteInstanceId, xf: DynSpriteTransform) {
1688        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
1689            return;
1690        };
1691        match &mut self.inner {
1692            BackendImpl::Cpu(c) => c.set_dyn_instance_transform(dyn_index as usize, xf),
1693            BackendImpl::Gpu(g) => g.set_dyn_instance_transform(dyn_index as usize, xf),
1694        }
1695    }
1696
1697    /// Batch form of
1698    /// [`set_sprite_instance_transform`](Self::set_sprite_instance_transform)
1699    /// — apply many `(instance, pose)` updates in one call. Stale handles
1700    /// in `updates` are skipped. On the GPU backend this marks the
1701    /// instance buffer dirty once and uploads the new poses a single time
1702    /// at the next [`render`](Self::render), so spinning a whole cluster
1703    /// of instances per frame is one device upload, not one per instance.
1704    pub fn set_sprite_instance_transforms(
1705        &mut self,
1706        updates: &[(SpriteInstanceId, DynSpriteTransform)],
1707    ) {
1708        for &(id, xf) in updates {
1709            let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
1710                continue;
1711            };
1712            match &mut self.inner {
1713                BackendImpl::Cpu(c) => c.set_dyn_instance_transform(dyn_index as usize, xf),
1714                BackendImpl::Gpu(g) => g.set_dyn_instance_transform(dyn_index as usize, xf),
1715            }
1716        }
1717    }
1718
1719    /// Set sprite instance `id`'s voxel-material id (TV stage) — indexes the
1720    /// global palette defined via [`define_material`](Self::define_material)
1721    /// for this whole instance's opacity + blend mode. `0` (the default) is
1722    /// opaque. Stale handles are ignored.
1723    ///
1724    /// Only the CPU backend composites translucent sprites today; the GPU
1725    /// backend retains the value for the forthcoming device-side path (see
1726    /// `PORTING-TRANSPARENCY.md`).
1727    pub fn set_sprite_instance_material(&mut self, id: SpriteInstanceId, material: u8) {
1728        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
1729            return;
1730        };
1731        match &mut self.inner {
1732            BackendImpl::Cpu(c) => c.set_dyn_instance_material(dyn_index as usize, material),
1733            BackendImpl::Gpu(g) => g.set_dyn_instance_material(dyn_index as usize, material),
1734        }
1735    }
1736
1737    /// Set sprite instance `id`'s per-instance alpha multiplier (TV stage),
1738    /// `0..=255` (`255` = unscaled). Scales the material's opacity so an
1739    /// effect can fade out by cheap per-frame updates without re-uploading
1740    /// its volume. Stale handles are ignored.
1741    pub fn set_sprite_instance_alpha(&mut self, id: SpriteInstanceId, alpha_mul: u8) {
1742        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
1743            return;
1744        };
1745        match &mut self.inner {
1746            BackendImpl::Cpu(c) => c.set_dyn_instance_alpha(dyn_index as usize, alpha_mul),
1747            BackendImpl::Gpu(g) => g.set_dyn_instance_alpha(dyn_index as usize, alpha_mul),
1748        }
1749    }
1750
1751    // ---- animated voxel clips (VCL.4) ------------------------------------
1752
1753    /// Register an animated voxel clip ("GIF/MP4 for voxels"): decode all
1754    /// its frames and upload the flipbook to the active backend (GPU: one
1755    /// LOD chain per frame; CPU: a cached dense grid per frame). Returns a
1756    /// [`VoxelClipId`] to spawn instances of it via
1757    /// [`add_clip_instance_posed`](Self::add_clip_instance_posed).
1758    ///
1759    /// Build the [`DecodedClip`] from a `.rvc` via
1760    /// [`VoxelClip::decode`](roxlap_formats::voxel_clip::VoxelClip::decode).
1761    /// Like [`add_sprite_model`](Self::add_sprite_model), this works before
1762    /// any [`set_sprites`](Self::set_sprites); a later `set_sprites`
1763    /// **drops** all registered clips (re-register afterwards).
1764    pub fn add_voxel_clip(&mut self, clip: &DecodedClip) -> VoxelClipId {
1765        let clip_index = match &mut self.inner {
1766            BackendImpl::Cpu(c) => c.add_voxel_clip(clip),
1767            BackendImpl::Gpu(g) => g.add_voxel_clip(clip),
1768        };
1769        // Capture metadata for editor queries + #6 auto-play; clip indices
1770        // are sequential and parallel to `clip_meta`.
1771        debug_assert_eq!(clip_index, self.clip_meta.len());
1772        self.clip_meta.push(ClipMeta {
1773            dims: clip.dims,
1774            pivot: clip.pivot,
1775            voxel_world_size: clip.voxel_world_size,
1776            durations: clip.durations.clone(),
1777            loop_mode: clip.loop_mode,
1778        });
1779        self.clip_map.alloc(clip_index as u32)
1780    }
1781
1782    /// Remove a registered clip, freeing its per-frame volumes. Instances
1783    /// of it linger but draw nothing until removed via
1784    /// [`remove_sprite_instance`](Self::remove_sprite_instance). Returns
1785    /// `false` if `id` is stale / already removed.
1786    pub fn remove_voxel_clip(&mut self, id: VoxelClipId) -> bool {
1787        let Some(clip_index) = self.clip_map.clip_index(id) else {
1788            return false;
1789        };
1790        match &mut self.inner {
1791            BackendImpl::Cpu(c) => c.remove_voxel_clip(clip_index),
1792            BackendImpl::Gpu(g) => g.remove_voxel_clip(clip_index),
1793        }
1794        self.clip_map.remove(id)
1795    }
1796
1797    /// Spawn an instance of clip `clip`, posed by `xf`, starting on frame
1798    /// 0. Returns a [`SpriteInstanceId`] — a clip instance is a dynamic
1799    /// sprite instance, so move it with
1800    /// [`set_sprite_instance_transform`](Self::set_sprite_instance_transform),
1801    /// advance its frame with
1802    /// [`set_clip_instance_frame`](Self::set_clip_instance_frame), and drop
1803    /// it with [`remove_sprite_instance`](Self::remove_sprite_instance).
1804    /// A stale `clip` handle yields an instance id that resolves to nothing
1805    /// (a safe no-op everywhere).
1806    ///
1807    /// This instance has **no playback clock**: drive its frame yourself via
1808    /// [`set_clip_instance_frame`](Self::set_clip_instance_frame) (frame-based
1809    /// scrubbing). For *clock*-based control — auto-advance, play/pause, or
1810    /// [`set_clip_instance_clock_ms`](Self::set_clip_instance_clock_ms)
1811    /// scrubbing — spawn with
1812    /// [`add_clip_instance_playing`](Self::add_clip_instance_playing) instead
1813    /// (the player-control methods no-op on an instance with no player).
1814    pub fn add_clip_instance_posed(
1815        &mut self,
1816        clip: VoxelClipId,
1817        xf: DynSpriteTransform,
1818    ) -> SpriteInstanceId {
1819        let Some(clip_index) = self.clip_map.clip_index(clip) else {
1820            return SpriteInstanceId {
1821                slot: u32::MAX,
1822                gen: u32::MAX,
1823            };
1824        };
1825        let dyn_index = match &mut self.inner {
1826            BackendImpl::Cpu(c) => c.add_clip_instance(clip_index, xf),
1827            BackendImpl::Gpu(g) => g.add_clip_instance(clip_index, xf),
1828        };
1829        self.dyn_map.alloc(dyn_index as u32)
1830    }
1831
1832    /// Select which frame a clip instance shows — the per-frame playback
1833    /// step. Cheap on both backends (GPU: swap the instance's model id;
1834    /// CPU: select the cached frame grid), with no volume re-upload. Drive
1835    /// it from a playback clock via
1836    /// [`DecodedClip::frame_at`](roxlap_formats::voxel_clip::DecodedClip::frame_at).
1837    /// No-op on a stale id or a non-clip instance.
1838    pub fn set_clip_instance_frame(&mut self, id: SpriteInstanceId, frame: u32) {
1839        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
1840            return;
1841        };
1842        match &mut self.inner {
1843            BackendImpl::Cpu(c) => c.set_clip_frame(dyn_index as usize, frame as usize),
1844            BackendImpl::Gpu(g) => g.set_clip_frame(dyn_index as usize, frame as usize),
1845        }
1846    }
1847
1848    // ---- clip queries (editor inspector) ---------------------------------
1849
1850    /// Frame count of a registered flipbook clip, or `None` if `id` is
1851    /// stale. (Same as `clip_metadata(id)?.frame_count`, without the clone.)
1852    #[must_use]
1853    pub fn clip_frame_count(&self, id: VoxelClipId) -> Option<usize> {
1854        let idx = self.clip_map.clip_index(id)?;
1855        Some(self.clip_meta[idx].durations.len())
1856    }
1857
1858    /// Inspector metadata (dims / pivot / scale / loop mode / per-frame
1859    /// durations) of a registered flipbook clip, or `None` if `id` is stale
1860    /// — so an editor needn't shadow the source [`DecodedClip`].
1861    #[must_use]
1862    pub fn clip_metadata(&self, id: VoxelClipId) -> Option<ClipMetadata> {
1863        let idx = self.clip_map.clip_index(id)?;
1864        let m = &self.clip_meta[idx];
1865        Some(ClipMetadata {
1866            dims: m.dims,
1867            pivot: m.pivot,
1868            voxel_world_size: m.voxel_world_size,
1869            loop_mode: m.loop_mode,
1870            frame_count: m.durations.len(),
1871            durations: m.durations.clone(),
1872            total_ms: m
1873                .durations
1874                .iter()
1875                .fold(0u32, |acc, &d| acc.saturating_add(d)),
1876        })
1877    }
1878
1879    /// Which frame a clip instance is currently showing (the timeline
1880    /// scrubber's read-back), or `None` if `id` isn't a live clip instance.
1881    #[must_use]
1882    pub fn get_clip_instance_frame(&self, id: SpriteInstanceId) -> Option<u32> {
1883        let dyn_index = self.dyn_map.dyn_index(id)? as usize;
1884        let frame = match &self.inner {
1885            BackendImpl::Cpu(c) => c.clip_instance_frame(dyn_index),
1886            BackendImpl::Gpu(g) => g.clip_instance_frame(dyn_index),
1887        }?;
1888        u32::try_from(frame).ok()
1889    }
1890
1891    /// Re-upload a **single** `frame` of registered clip `id` in place — the
1892    /// editor's one-voxel paint, O(1 frame) instead of `remove_voxel_clip` +
1893    /// `add_voxel_clip` (which rebuilds all N volumes). `vf` must fit the
1894    /// clip's fixed `dims`. Returns `false` on a stale `id`, an out-of-range
1895    /// `frame`, or a frame that fails the clip's layout (so it can't corrupt
1896    /// the flipbook).
1897    pub fn update_clip_frame(&mut self, id: VoxelClipId, frame: u32, vf: &VoxelFrame) -> bool {
1898        let Some(clip_index) = self.clip_map.clip_index(id) else {
1899            return false;
1900        };
1901        let m = &self.clip_meta[clip_index];
1902        let (dims, pivot, vws) = (m.dims, m.pivot, m.voxel_world_size);
1903        if vf.validate(dims).is_err() {
1904            return false;
1905        }
1906        let frame = frame as usize;
1907        match &mut self.inner {
1908            BackendImpl::Cpu(c) => c.update_clip_frame(clip_index, frame, vf, dims, pivot),
1909            BackendImpl::Gpu(g) => g.update_clip_frame(clip_index, frame, vf, dims, pivot, vws),
1910        }
1911    }
1912
1913    // ---- streaming voxel clips (#3) --------------------------------------
1914
1915    /// Register a **streaming** voxel clip — `O(1-frame)` memory (one sprite
1916    /// model + the compact encoded stream) rather than the N-volume flipbook
1917    /// [`add_voxel_clip`](Self::add_voxel_clip) builds, for huge clips where
1918    /// N frames are too costly to hold resident. Builds the model from frame
1919    /// 0; advance it with
1920    /// [`set_streaming_clip_frame`](Self::set_streaming_clip_frame). Spawn
1921    /// instances with
1922    /// [`add_streaming_clip_instance`](Self::add_streaming_clip_instance) —
1923    /// note that, unlike a flipbook, **all** instances of a streaming clip
1924    /// share its one model and so always show the same (current) frame.
1925    ///
1926    /// Takes the *encoded* [`VoxelClip`] (not a [`DecodedClip`]) — the whole
1927    /// point is to avoid materialising every frame.
1928    ///
1929    /// # Errors
1930    /// [`DecodeError`] if the clip's frame stream is empty or doesn't begin
1931    /// with a keyframe.
1932    pub fn add_streaming_clip(&mut self, clip: &VoxelClip) -> Result<StreamingClipId, DecodeError> {
1933        let cursor = StreamingClip::new(clip)?;
1934        let dims = cursor.dims();
1935        let pivot = cursor.pivot();
1936        let kv6 = cursor.current_frame().to_kv6(dims, pivot);
1937        let model = self.add_sprite_model(&kv6);
1938        let index = self.streaming_clips.len() as u32;
1939        self.streaming_clips.push(Some(StreamingClipState {
1940            cursor,
1941            model,
1942            dims,
1943            pivot,
1944        }));
1945        Ok(self.streaming_map.alloc(index))
1946    }
1947
1948    /// Spawn an instance of streaming clip `id`, posed by `xf`. Returns a
1949    /// [`SpriteInstanceId`] — move it with
1950    /// [`set_sprite_instance_transform`](Self::set_sprite_instance_transform)
1951    /// and drop it with
1952    /// [`remove_sprite_instance`](Self::remove_sprite_instance), like any
1953    /// dynamic instance. All instances of one streaming clip share its single
1954    /// model. A stale `id` yields a no-op instance handle.
1955    pub fn add_streaming_clip_instance(
1956        &mut self,
1957        id: StreamingClipId,
1958        xf: DynSpriteTransform,
1959    ) -> StreamingInstanceId {
1960        let model = self
1961            .streaming_map
1962            .index(id)
1963            .and_then(|idx| self.streaming_clips[idx].as_ref())
1964            .map(|s| s.model);
1965        let inst = match model {
1966            Some(model) => self.add_sprite_instance_posed(model, xf),
1967            None => SpriteInstanceId {
1968                slot: u32::MAX,
1969                gen: u32::MAX,
1970            },
1971        };
1972        StreamingInstanceId(inst)
1973    }
1974
1975    /// Re-pose a streaming-clip instance (world transform). No-op on a stale
1976    /// handle.
1977    pub fn set_streaming_instance_transform(
1978        &mut self,
1979        id: StreamingInstanceId,
1980        xf: DynSpriteTransform,
1981    ) {
1982        self.set_sprite_instance_transform(id.0, xf);
1983    }
1984
1985    /// Remove a streaming-clip instance. Returns `false` if `id` is stale.
1986    pub fn remove_streaming_instance(&mut self, id: StreamingInstanceId) -> bool {
1987        self.remove_sprite_instance(id.0)
1988    }
1989
1990    /// Advance a streaming clip to `frame`: seek the cursor and re-upload its
1991    /// single model — the per-frame streaming step (one volume re-upload,
1992    /// vs the flipbook's cheap model-select). Updates **every** instance of
1993    /// the clip at once. Drive it from a clock via
1994    /// [`frame_at`](roxlap_formats::voxel_clip::frame_at). No-op on a stale
1995    /// id; `frame` is clamped to the last.
1996    pub fn set_streaming_clip_frame(&mut self, id: StreamingClipId, frame: u32) {
1997        let Some(idx) = self.streaming_map.index(id) else {
1998            return;
1999        };
2000        let Some((model, kv6)) = self.streaming_clips[idx].as_mut().and_then(|s| {
2001            let vf = s.cursor.seek(frame as usize).ok()?;
2002            Some((s.model, vf.to_kv6(s.dims, s.pivot)))
2003        }) else {
2004            return;
2005        };
2006        self.refresh_sprite_model(model, &kv6);
2007    }
2008
2009    /// Remove a streaming clip: free its model and drop the cursor (the
2010    /// memory win for huge clips). Instances linger but draw nothing until
2011    /// removed. Returns `false` if `id` is stale / already removed.
2012    pub fn remove_streaming_clip(&mut self, id: StreamingClipId) -> bool {
2013        let Some(idx) = self.streaming_map.index(id) else {
2014            return false;
2015        };
2016        let model = self.streaming_clips[idx].as_ref().map(|s| s.model);
2017        self.streaming_clips[idx] = None;
2018        if let Some(model) = model {
2019            self.remove_sprite_model(model);
2020        }
2021        self.streaming_map.remove(id)
2022    }
2023
2024    // ---- auto-advancing clip players (#6) --------------------------------
2025
2026    /// Spawn a flipbook-clip instance that **plays itself**: like
2027    /// [`add_clip_instance_posed`](Self::add_clip_instance_posed), but the
2028    /// facade tracks a playback clock so a single
2029    /// [`advance_voxel_clips`](Self::advance_voxel_clips) call advances every
2030    /// such instance — no per-frame `frame_at` + `set_clip_instance_frame`
2031    /// bookkeeping in the host. `speed_q8` is the Q8 playback rate (`256` =
2032    /// 1×); `start_phase_ms` offsets the clock (stagger copies of one clip).
2033    /// A stale `clip` yields a no-op instance handle and no player.
2034    pub fn add_clip_instance_playing(
2035        &mut self,
2036        clip: VoxelClipId,
2037        xf: DynSpriteTransform,
2038        speed_q8: i32,
2039        start_phase_ms: u32,
2040    ) -> SpriteInstanceId {
2041        let Some(clip_index) = self.clip_map.clip_index(clip) else {
2042            return SpriteInstanceId {
2043                slot: u32::MAX,
2044                gen: u32::MAX,
2045            };
2046        };
2047        let meta = &self.clip_meta[clip_index];
2048        let clock = ClipClock {
2049            durations: meta.durations.clone(),
2050            loop_mode: meta.loop_mode,
2051            speed_q8,
2052            clock_ms: f64::from(start_phase_ms),
2053        };
2054        let inst = self.add_clip_instance_posed(clip, xf);
2055        self.clip_players.push(ClipPlayer {
2056            target: PlayerTarget::Flipbook(inst),
2057            clock,
2058            paused: false,
2059        });
2060        inst
2061    }
2062
2063    /// Give a streaming clip ([`add_streaming_clip`](Self::add_streaming_clip))
2064    /// its own playback clock, advanced by
2065    /// [`advance_voxel_clips`](Self::advance_voxel_clips). A streaming clip's
2066    /// frame is per-clip (all its instances share one model), so this is
2067    /// keyed on the clip, not an instance — register instances separately
2068    /// with
2069    /// [`add_streaming_clip_instance`](Self::add_streaming_clip_instance).
2070    /// No-op on a stale `clip`.
2071    ///
2072    /// Control the player (play/pause/scrub) via
2073    /// [`set_streaming_clip_paused`](Self::set_streaming_clip_paused) /
2074    /// [`set_streaming_clip_speed`](Self::set_streaming_clip_speed) /
2075    /// [`set_streaming_clip_clock_ms`](Self::set_streaming_clip_clock_ms), the
2076    /// per-clip analogues of the flipbook `set_clip_instance_*` methods.
2077    pub fn play_streaming_clip(
2078        &mut self,
2079        clip: StreamingClipId,
2080        speed_q8: i32,
2081        start_phase_ms: u32,
2082    ) {
2083        let Some(idx) = self.streaming_map.index(clip) else {
2084            return;
2085        };
2086        let Some(state) = self.streaming_clips[idx].as_ref() else {
2087            return;
2088        };
2089        let clock = ClipClock {
2090            durations: state.cursor.durations().to_vec(),
2091            loop_mode: state.cursor.loop_mode(),
2092            speed_q8,
2093            clock_ms: f64::from(start_phase_ms),
2094        };
2095        self.clip_players.push(ClipPlayer {
2096            target: PlayerTarget::Streaming(clip),
2097            clock,
2098            paused: false,
2099        });
2100    }
2101
2102    /// Advance every auto-playing clip ([`add_clip_instance_playing`] /
2103    /// [`play_streaming_clip`]) by `dt` seconds: tick each clock, resolve its
2104    /// frame via [`frame_at`](roxlap_formats::voxel_clip::frame_at), and
2105    /// apply it. Players whose instance / clip was removed are pruned. Call
2106    /// once per frame.
2107    ///
2108    /// [`add_clip_instance_playing`]: Self::add_clip_instance_playing
2109    /// [`play_streaming_clip`]: Self::play_streaming_clip
2110    pub fn advance_voxel_clips(&mut self, dt: f64) {
2111        // Phase 1: tick clocks → (target, frame), pruning dead players.
2112        // Borrow only the maps (disjoint from `clip_players`).
2113        let dyn_map = &self.dyn_map;
2114        let streaming_map = &self.streaming_map;
2115        let mut updates: Vec<(PlayerTarget, u32)> = Vec::new();
2116        self.clip_players.retain_mut(|p| {
2117            let alive = match p.target {
2118                PlayerTarget::Flipbook(inst) => dyn_map.dyn_index(inst).is_some(),
2119                PlayerTarget::Streaming(clip) => streaming_map.index(clip).is_some(),
2120            };
2121            if !alive {
2122                return false;
2123            }
2124            // A paused player keeps its clock + frame (the editor's pause).
2125            if !p.paused {
2126                updates.push((p.target, p.clock.tick(dt)));
2127            }
2128            true
2129        });
2130        // Phase 2: apply (borrows self mutably, disjoint from the above).
2131        for (target, frame) in updates {
2132            self.apply_player_frame(target, frame);
2133        }
2134    }
2135
2136    /// Apply a resolved frame to a player's target (flipbook instance vs.
2137    /// streaming clip).
2138    fn apply_player_frame(&mut self, target: PlayerTarget, frame: u32) {
2139        match target {
2140            PlayerTarget::Flipbook(inst) => self.set_clip_instance_frame(inst, frame),
2141            PlayerTarget::Streaming(clip) => self.set_streaming_clip_frame(clip, frame),
2142        }
2143    }
2144
2145    /// Find the auto-player driving flipbook instance `inst`, if any.
2146    fn flipbook_player_mut(&mut self, inst: SpriteInstanceId) -> Option<&mut ClipPlayer> {
2147        self.clip_players
2148            .iter_mut()
2149            .find(|p| matches!(p.target, PlayerTarget::Flipbook(i) if i == inst))
2150    }
2151
2152    /// Pause / resume the auto-player driving clip instance `id` (the
2153    /// editor's play/pause). No-op if `id` has no player.
2154    pub fn set_clip_instance_paused(&mut self, id: SpriteInstanceId, paused: bool) {
2155        if let Some(p) = self.flipbook_player_mut(id) {
2156            p.paused = paused;
2157        }
2158    }
2159
2160    /// Whether clip instance `id`'s auto-player is paused, or `None` if it
2161    /// has no player.
2162    #[must_use]
2163    pub fn is_clip_instance_paused(&self, id: SpriteInstanceId) -> Option<bool> {
2164        self.clip_players
2165            .iter()
2166            .find(|p| matches!(p.target, PlayerTarget::Flipbook(i) if i == id))
2167            .map(|p| p.paused)
2168    }
2169
2170    /// Set the playback speed (Q8: `256` = 1×, negative = reverse) of clip
2171    /// instance `id`'s auto-player. No-op if `id` has no player.
2172    pub fn set_clip_instance_speed(&mut self, id: SpriteInstanceId, speed_q8: i32) {
2173        if let Some(p) = self.flipbook_player_mut(id) {
2174            p.clock.speed_q8 = speed_q8;
2175        }
2176    }
2177
2178    /// **Scrub**: set clip instance `id`'s playback clock to `clock_ms` and
2179    /// immediately show the matching frame (works while paused). No-op if
2180    /// `id` has no player.
2181    pub fn set_clip_instance_clock_ms(&mut self, id: SpriteInstanceId, clock_ms: f64) {
2182        let Some((target, frame)) = self.flipbook_player_mut(id).map(|p| {
2183            p.clock.clock_ms = clock_ms;
2184            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
2185            let frame = frame_at(
2186                &p.clock.durations,
2187                p.clock.loop_mode,
2188                clock_ms.max(0.0) as u32,
2189            ) as u32;
2190            (p.target, frame)
2191        }) else {
2192            return;
2193        };
2194        self.apply_player_frame(target, frame);
2195    }
2196
2197    /// Clip instance `id`'s current playback-clock position (ms), or `None`
2198    /// if it has no player — the scrubber's read-back.
2199    #[must_use]
2200    pub fn clip_instance_clock_ms(&self, id: SpriteInstanceId) -> Option<f64> {
2201        self.clip_players
2202            .iter()
2203            .find(|p| matches!(p.target, PlayerTarget::Flipbook(i) if i == id))
2204            .map(|p| p.clock.clock_ms)
2205    }
2206
2207    /// Find the auto-player driving streaming clip `clip`, if any (a player
2208    /// registered via [`play_streaming_clip`](Self::play_streaming_clip)).
2209    fn streaming_player_mut(&mut self, clip: StreamingClipId) -> Option<&mut ClipPlayer> {
2210        self.clip_players
2211            .iter_mut()
2212            .find(|p| matches!(p.target, PlayerTarget::Streaming(c) if c == clip))
2213    }
2214
2215    /// Pause / resume a streaming clip's auto-player
2216    /// ([`play_streaming_clip`](Self::play_streaming_clip)). No-op if `clip`
2217    /// has no player.
2218    pub fn set_streaming_clip_paused(&mut self, clip: StreamingClipId, paused: bool) {
2219        if let Some(p) = self.streaming_player_mut(clip) {
2220            p.paused = paused;
2221        }
2222    }
2223
2224    /// Whether streaming clip `clip`'s auto-player is paused, or `None` if it
2225    /// has no player.
2226    #[must_use]
2227    pub fn is_streaming_clip_paused(&self, clip: StreamingClipId) -> Option<bool> {
2228        self.clip_players
2229            .iter()
2230            .find(|p| matches!(p.target, PlayerTarget::Streaming(c) if c == clip))
2231            .map(|p| p.paused)
2232    }
2233
2234    /// Set the playback speed (Q8: `256` = 1×, negative = reverse) of
2235    /// streaming clip `clip`'s auto-player. No-op if `clip` has no player.
2236    pub fn set_streaming_clip_speed(&mut self, clip: StreamingClipId, speed_q8: i32) {
2237        if let Some(p) = self.streaming_player_mut(clip) {
2238            p.clock.speed_q8 = speed_q8;
2239        }
2240    }
2241
2242    /// **Scrub** a streaming clip: set its auto-player's clock to `clock_ms`
2243    /// and immediately show the matching frame (works while paused). No-op if
2244    /// `clip` has no player.
2245    pub fn set_streaming_clip_clock_ms(&mut self, clip: StreamingClipId, clock_ms: f64) {
2246        let Some((target, frame)) = self.streaming_player_mut(clip).map(|p| {
2247            p.clock.clock_ms = clock_ms;
2248            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
2249            let frame = frame_at(
2250                &p.clock.durations,
2251                p.clock.loop_mode,
2252                clock_ms.max(0.0) as u32,
2253            ) as u32;
2254            (p.target, frame)
2255        }) else {
2256            return;
2257        };
2258        self.apply_player_frame(target, frame);
2259    }
2260
2261    /// Streaming clip `clip`'s current playback-clock position (ms), or
2262    /// `None` if it has no player — the scrubber's read-back.
2263    #[must_use]
2264    pub fn streaming_clip_clock_ms(&self, clip: StreamingClipId) -> Option<f64> {
2265        self.clip_players
2266            .iter()
2267            .find(|p| matches!(p.target, PlayerTarget::Streaming(c) if c == clip))
2268            .map(|p| p.clock.clock_ms)
2269    }
2270
2271    // ---- animated characters (VCL.6) -------------------------------------
2272
2273    /// Register an animated character (RKC v3): upload its meshes as sprite
2274    /// models + its embedded voxel clips as flipbooks, then spawn one
2275    /// renderer instance **per bone attachment** — a static mesh sits at
2276    /// its bone, a clip attachment plays back on its own clock. `clip`
2277    /// selects a skeletal animation clip to drive the bones (`None` =
2278    /// rest pose). Returns a [`CharacterId`]; advance it each frame with
2279    /// [`advance_character`](Self::advance_character).
2280    ///
2281    /// Like clips, this works before any [`set_sprites`](Self::set_sprites);
2282    /// a later `set_sprites` drops all registered characters.
2283    pub fn add_character(&mut self, ch: &Character, clip: Option<usize>) -> CharacterId {
2284        // 1. Meshes → sprite models.
2285        let model_ids: Vec<SpriteModelId> =
2286            ch.meshes.iter().map(|m| self.add_sprite_model(m)).collect();
2287        // 2. Voxel clips → flipbooks; keep each one's timing for the clocks.
2288        let clip_regs: Vec<Option<(VoxelClipId, Vec<u32>, LoopMode)>> = ch
2289            .voxel_clips
2290            .iter()
2291            .map(|vc| {
2292                vc.decode().ok().map(|d| {
2293                    let id = self.add_voxel_clip(&d);
2294                    (id, d.durations, d.loop_mode)
2295                })
2296            })
2297            .collect();
2298        // 3. Build + solve the skeleton (rest pose → bone transforms).
2299        let mut skeleton = ch.to_kfa_sprite(clip);
2300        solve_kfa_limbs(&mut skeleton);
2301        // 4. One instance per attachment, posed by bone × local_offset.
2302        let mut attaches = Vec::new();
2303        for (bi, bone) in ch.bones.iter().enumerate() {
2304            let limb = &skeleton.limbs[bi];
2305            for att in &bone.attachments {
2306                let (s, h, f, p) =
2307                    compose_attachment(limb.s, limb.h, limb.f, limb.p, &att.local_offset);
2308                let xf = DynSpriteTransform {
2309                    pos: p,
2310                    right: s,
2311                    up: h,
2312                    forward: f,
2313                };
2314                match att.target {
2315                    MeshRef::Static(mi) => {
2316                        if let Some(&mid) = model_ids.get(mi) {
2317                            let inst = self.add_sprite_instance_posed(mid, xf);
2318                            attaches.push(AttachInst {
2319                                bone: bi,
2320                                local_offset: att.local_offset,
2321                                inst,
2322                                clip: None,
2323                            });
2324                        }
2325                    }
2326                    MeshRef::Clip(ci) => {
2327                        if let Some(Some((cid, durations, loop_mode))) = clip_regs.get(ci) {
2328                            let inst = self.add_clip_instance_posed(*cid, xf);
2329                            attaches.push(AttachInst {
2330                                bone: bi,
2331                                local_offset: att.local_offset,
2332                                inst,
2333                                clip: Some(ClipClock {
2334                                    durations: durations.clone(),
2335                                    loop_mode: *loop_mode,
2336                                    speed_q8: att.playback.speed_q8,
2337                                    clock_ms: f64::from(att.playback.start_phase_ms),
2338                                }),
2339                            });
2340                        }
2341                    }
2342                }
2343            }
2344        }
2345        let clips: Vec<VoxelClipId> = clip_regs
2346            .iter()
2347            .filter_map(|r| r.as_ref().map(|(cid, _, _)| *cid))
2348            .collect();
2349        let idx = self.char_instances.len();
2350        self.char_instances.push(CharInstance {
2351            skeleton,
2352            attaches,
2353            models: model_ids,
2354            clips,
2355        });
2356        self.char_map.alloc(idx as u32)
2357    }
2358
2359    /// Advance a character by `dt` seconds: tick its skeletal animation +
2360    /// each clip attachment's clock, then re-pose every attachment
2361    /// (bone × local_offset) and select each clip's current frame. No-op on
2362    /// a stale id.
2363    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
2364    pub fn advance_character(&mut self, id: CharacterId, dt: f64) {
2365        let Some(idx) = self.char_map.index(id) else {
2366            return;
2367        };
2368        // Phase 1: solve the skeleton + compute each attachment's update,
2369        // borrowing only `char_instances[idx]`.
2370        let updates: Vec<(SpriteInstanceId, DynSpriteTransform, Option<u32>)> = {
2371            let CharInstance {
2372                skeleton, attaches, ..
2373            } = &mut self.char_instances[idx];
2374            skeleton.animsprite((dt * 1000.0) as i32);
2375            solve_kfa_limbs(skeleton);
2376            attaches
2377                .iter_mut()
2378                .map(|a| {
2379                    let limb = &skeleton.limbs[a.bone];
2380                    let (s, h, f, p) =
2381                        compose_attachment(limb.s, limb.h, limb.f, limb.p, &a.local_offset);
2382                    let xf = DynSpriteTransform {
2383                        pos: p,
2384                        right: s,
2385                        up: h,
2386                        forward: f,
2387                    };
2388                    let frame = a.clip.as_mut().map(|c| c.tick(dt));
2389                    (a.inst, xf, frame)
2390                })
2391                .collect()
2392        };
2393        // Phase 2: apply via the facade primitives (disjoint from
2394        // `char_instances`).
2395        for (inst, xf, frame) in updates {
2396            self.set_sprite_instance_transform(inst, xf);
2397            if let Some(f) = frame {
2398                self.set_clip_instance_frame(inst, f);
2399            }
2400        }
2401    }
2402
2403    /// Move/re-orient a character to a new world transform `xf` (the root
2404    /// limb's world pose) **without** ticking its animation or clip clocks —
2405    /// a teleport that holds the current animation frame (e.g. dragging a
2406    /// paused character in an editor). Re-solves the skeleton from the new
2407    /// root + re-poses every attachment; clip frames are left as-is. No-op on
2408    /// a stale id.
2409    pub fn set_character_world_transform(&mut self, id: CharacterId, xf: DynSpriteTransform) {
2410        let Some(idx) = self.char_map.index(id) else {
2411            return;
2412        };
2413        // Phase 1: set the root pose + re-solve (no animsprite), then compute
2414        // each attachment's new transform — borrowing only `char_instances`.
2415        let updates: Vec<(SpriteInstanceId, DynSpriteTransform)> = {
2416            let CharInstance {
2417                skeleton, attaches, ..
2418            } = &mut self.char_instances[idx];
2419            skeleton.p = xf.pos;
2420            skeleton.s = xf.right;
2421            skeleton.h = xf.up;
2422            skeleton.f = xf.forward;
2423            solve_kfa_limbs(skeleton);
2424            attaches
2425                .iter()
2426                .map(|a| {
2427                    let limb = &skeleton.limbs[a.bone];
2428                    let (s, h, f, p) =
2429                        compose_attachment(limb.s, limb.h, limb.f, limb.p, &a.local_offset);
2430                    (
2431                        a.inst,
2432                        DynSpriteTransform {
2433                            pos: p,
2434                            right: s,
2435                            up: h,
2436                            forward: f,
2437                        },
2438                    )
2439                })
2440                .collect()
2441        };
2442        // Phase 2: apply (clip frames untouched — clocks didn't tick).
2443        for (inst, t) in updates {
2444            self.set_sprite_instance_transform(inst, t);
2445        }
2446    }
2447
2448    /// Remove a character, dropping all its attachment instances **and**
2449    /// freeing the sprite models + voxel clips it registered. Returns
2450    /// `false` if `id` is stale.
2451    pub fn remove_character(&mut self, id: CharacterId) -> bool {
2452        let Some(idx) = self.char_map.index(id) else {
2453            return false;
2454        };
2455        let insts: Vec<SpriteInstanceId> = self.char_instances[idx]
2456            .attaches
2457            .iter()
2458            .map(|a| a.inst)
2459            .collect();
2460        for inst in insts {
2461            self.remove_sprite_instance(inst);
2462        }
2463        self.char_instances[idx].attaches.clear();
2464        // Free the models + clips this character registered (else they leak
2465        // until a `set_sprites` — costly for an editor hot-swapping all
2466        // session). `mem::take` so the per-id frees can borrow `self`.
2467        let models = std::mem::take(&mut self.char_instances[idx].models);
2468        let clips = std::mem::take(&mut self.char_instances[idx].clips);
2469        for model in models {
2470            self.remove_sprite_model(model);
2471        }
2472        for clip in clips {
2473            self.remove_voxel_clip(clip);
2474        }
2475        self.char_map.remove(id)
2476    }
2477
2478    /// Register animated KFA sprites (one or more bone hierarchies).
2479    /// The GPU backend uploads each limb's kv6 as an instanced model
2480    /// **once** (appended to the sprite registry) and seeds the limb
2481    /// instances at their current pose; the CPU backend caches the
2482    /// posed limbs for drawing. Call once at setup, after
2483    /// [`set_sprites`](Self::set_sprites), then drive motion per frame
2484    /// with [`update_kfa_poses`](Self::update_kfa_poses).
2485    ///
2486    /// Limbs are posed from the sprites' current
2487    /// [`kfaval`](roxlap_formats::kfa::KfaSprite::kfaval) (advance
2488    /// [`animsprite`](roxlap_formats::kfa::KfaSprite::animsprite) first
2489    /// if using a baked curve), so `kfas` is taken `&mut`.
2490    pub fn set_kfa_sprites(&mut self, kfas: &mut [KfaSprite]) {
2491        match &mut self.inner {
2492            BackendImpl::Cpu(c) => c.set_kfa_sprites(kfas),
2493            BackendImpl::Gpu(g) => g.set_kfa_sprites(kfas),
2494        }
2495    }
2496
2497    /// Re-pose the registered KFA sprites from their current
2498    /// `kfaval[]`. Call each frame after advancing the animation
2499    /// (`kfa.animsprite(dt_ms)` or poking `kfaval[]`). The GPU backend
2500    /// takes the cheap transform-only update (no model-volume
2501    /// re-upload); the CPU backend re-solves limb transforms for the
2502    /// next [`render`](Self::render). Must follow a
2503    /// [`set_kfa_sprites`](Self::set_kfa_sprites) with the same sprites.
2504    pub fn update_kfa_poses(&mut self, kfas: &mut [KfaSprite]) {
2505        match &mut self.inner {
2506            BackendImpl::Cpu(c) => c.update_kfa_poses(kfas),
2507            BackendImpl::Gpu(g) => g.update_kfa_poses(kfas),
2508        }
2509    }
2510
2511    /// Carve the next z-layer off the [`SpriteSet::carve_model`] and
2512    /// re-upload (the demo's `G` hotkey + GPU.12 copy-on-modify). GPU
2513    /// only; a no-op on the CPU backend. Returns the voxels removed.
2514    pub fn carve_active_sprite(&mut self) -> u32 {
2515        match &mut self.inner {
2516            BackendImpl::Cpu(_) => 0,
2517            BackendImpl::Gpu(g) => g.carve_active_sprite(),
2518        }
2519    }
2520
2521    /// Request that the next [`render`](Self::render) capture its
2522    /// framebuffer for [`take_capture`](Self::take_capture). CPU only
2523    /// (the GPU swapchain isn't read back) — a no-op on GPU.
2524    pub fn request_capture(&mut self) {
2525        if let BackendImpl::Cpu(c) = &mut self.inner {
2526            c.request_capture();
2527        }
2528    }
2529
2530    /// Take the most recently captured frame as packed `0x00RRGGBB`
2531    /// pixels + dimensions, or `None` if no capture is ready / GPU.
2532    pub fn take_capture(&mut self) -> Option<(Vec<u32>, u32, u32)> {
2533        match &mut self.inner {
2534            BackendImpl::Cpu(c) => c.take_capture(),
2535            BackendImpl::Gpu(_) => None,
2536        }
2537    }
2538
2539    /// Screen→world picking input: the world-space hit distance `t` at
2540    /// window pixel `(x, y)` from the **last rendered frame**, or `None`
2541    /// for out-of-bounds pixels and sky / no-hit. The host reconstructs
2542    /// the world hit point as `cam.pos + t * normalize(ray_dir)`, where
2543    /// `ray_dir` is the same per-pixel ray the frame was rendered with
2544    /// (see the backend's projection).
2545    ///
2546    /// `t` is the distance to the nearest **scene-grid** surface
2547    /// (terrain + grids); sprites do not occlude it (the sprite pass
2548    /// reads depth read-only), so a cursor sprite under the pointer is
2549    /// transparent to the pick.
2550    ///
2551    /// Cost: the CPU backend reads its in-memory z-buffer (free); the
2552    /// GPU backend stages the depth buffer and blocks on a device poll
2553    /// (cheap at click time — do not call every frame). The GPU path
2554    /// only has depth when the last frame drew sprites (`write_depth`).
2555    #[must_use]
2556    pub fn pick_depth(&self, x: u32, y: u32) -> Option<f32> {
2557        match &self.inner {
2558            BackendImpl::Cpu(c) => c.pick_depth(x, y),
2559            BackendImpl::Gpu(g) => g.pick_depth(x, y),
2560        }
2561    }
2562
2563    /// World-space view-ray direction (un-normalised) for window pixel
2564    /// `(x, y)`, under the projection the **last frame** rendered with.
2565    /// The backends differ (CPU `setcamera` vs GPU vertical-FOV
2566    /// pinhole), so this hides which one is active. `None` before the
2567    /// first frame. Intersect it with a plane for tile picking, or feed
2568    /// it to [`Self::pick`] for a voxel.
2569    #[must_use]
2570    pub fn pixel_ray(&self, camera: &Camera, x: f64, y: f64) -> Option<[f64; 3]> {
2571        match &self.inner {
2572            BackendImpl::Cpu(c) => c.pixel_ray(camera, x, y),
2573            BackendImpl::Gpu(g) => g.pixel_ray(camera, x, y),
2574        }
2575    }
2576
2577    /// Canonical screen→world unproject: the full view [`Ray`]
2578    /// (`camera.pos` origin + unit direction) for window pixel
2579    /// `(x, y)`, under whichever projection the last frame used. The
2580    /// one entry point both backends honour — hosts never reconstruct
2581    /// the projection. `None` before the first frame or for a
2582    /// degenerate ray.
2583    ///
2584    /// Compose with [`roxlap_scene::Scene::raycast`] for depth-free
2585    /// picking that's identical on CPU and GPU:
2586    /// `renderer.view_ray(cam, x, y).and_then(|r| scene.raycast(r.origin, r.dir, max))`.
2587    #[must_use]
2588    pub fn view_ray(&self, camera: &Camera, x: f64, y: f64) -> Option<Ray> {
2589        let d = self.pixel_ray(camera, x, y)?;
2590        let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
2591        if len < 1e-12 {
2592            return None;
2593        }
2594        Some(Ray {
2595            origin: glam::DVec3::from_array([camera.pos[0], camera.pos[1], camera.pos[2]]),
2596            dir: glam::DVec3::new(d[0] / len, d[1] / len, d[2] / len),
2597        })
2598    }
2599
2600    /// One-call screen→world voxel pick: unproject pixel `(x, y)` with
2601    /// the active backend's projection, read the last frame's depth
2602    /// there, reconstruct the world hit, and resolve it to the owning
2603    /// grid + grid-local voxel via [`Scene::resolve_voxel`]. `None` on
2604    /// sky / no-hit, or when no grid claims the surface.
2605    ///
2606    /// `scene` and `camera` must be the ones the last frame rendered;
2607    /// the projection (size + FOV / `hx,hy,hz`) is taken from that
2608    /// frame. Cheap on CPU (in-memory z-buffer); on GPU it stages the
2609    /// depth buffer (a click-time device poll — not per frame).
2610    #[must_use]
2611    pub fn pick(&self, scene: &Scene, camera: &Camera, x: u32, y: u32) -> Option<PickHit> {
2612        let dir = self.pixel_ray(camera, f64::from(x), f64::from(y))?;
2613        let t = f64::from(self.pick_depth(x, y)?);
2614        let len = (dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]).sqrt();
2615        if len < 1e-9 {
2616            return None;
2617        }
2618        let s = t / len; // world = cam.pos + t · (dir / |dir|)
2619        let world = glam::DVec3::new(
2620            camera.pos[0] + dir[0] * s,
2621            camera.pos[1] + dir[1] * s,
2622            camera.pos[2] + dir[2] * s,
2623        );
2624        let (grid, voxel) = scene.resolve_voxel(world, glam::DVec3::from_array(dir))?;
2625        #[allow(clippy::cast_possible_truncation)]
2626        let world_f32 = [world.x as f32, world.y as f32, world.z as f32];
2627        Some(PickHit {
2628            world: world_f32,
2629            grid,
2630            voxel,
2631        })
2632    }
2633}
2634
2635#[cfg(test)]
2636mod tests {
2637    use super::*;
2638
2639    /// The handle map must survive the backends' swap-remove indexing:
2640    /// drive a model `DynInstanceMap` against a `Vec` "backend" that
2641    /// swap-removes, and check every live handle keeps resolving to its
2642    /// own payload through a sequence of adds + removes.
2643    #[test]
2644    fn dyn_instance_map_survives_swap_removes() {
2645        let mut map = DynInstanceMap::default();
2646        // The "backend": payload per dynamic index; swap_remove mirrors
2647        // both backends' remove_dyn_instance.
2648        let mut backend: Vec<u32> = Vec::new();
2649        // Our bookkeeping: handle -> the payload we expect it to address.
2650        let mut expect: Vec<(SpriteInstanceId, u32)> = Vec::new();
2651
2652        let add = |map: &mut DynInstanceMap,
2653                   backend: &mut Vec<u32>,
2654                   expect: &mut Vec<(SpriteInstanceId, u32)>,
2655                   payload: u32| {
2656            let dyn_index = backend.len() as u32;
2657            backend.push(payload);
2658            let id = map.alloc(dyn_index);
2659            expect.push((id, payload));
2660        };
2661
2662        for p in 0..6 {
2663            add(&mut map, &mut backend, &mut expect, p);
2664        }
2665
2666        // Remove a middle handle (payload 2) and a later one (payload 4),
2667        // plus the current last — covering swap and no-swap paths.
2668        for victim_payload in [2u32, 4, 5] {
2669            let pos = expect
2670                .iter()
2671                .position(|&(_, p)| p == victim_payload)
2672                .unwrap();
2673            let (id, _) = expect.remove(pos);
2674            let dyn_index = map.dyn_index(id).expect("live handle resolves");
2675            // Backend swap-remove + report moved index (old last), exactly
2676            // like remove_dyn_instance on both backends.
2677            let last = backend.len() - 1;
2678            backend.swap_remove(dyn_index as usize);
2679            let moved = (dyn_index as usize != last).then_some(last as u32);
2680            map.remove(id, dyn_index, moved);
2681            // The removed handle is now stale.
2682            assert!(map.dyn_index(id).is_none(), "removed handle is stale");
2683        }
2684
2685        // Every surviving handle still resolves to its own payload.
2686        for &(id, payload) in &expect {
2687            let idx = map.dyn_index(id).expect("survivor resolves");
2688            assert_eq!(
2689                backend[idx as usize], payload,
2690                "handle addresses its payload"
2691            );
2692        }
2693        assert_eq!(map.order.len(), backend.len());
2694        assert_eq!(backend.len(), expect.len());
2695    }
2696
2697    /// The model slotmap mints stable ids, resolves only live handles,
2698    /// and never reuses a slot — so a removed model's id stays dead and
2699    /// every other id survives the remove.
2700    #[test]
2701    fn dyn_model_map_lifecycle() {
2702        let mut map = DynModelMap::default();
2703        // `set_sprites(3 models)` seeds ids 0..3, all live.
2704        map.reset(3);
2705        let ids: Vec<SpriteModelId> = (0..3).map(|s| SpriteModelId { slot: s, gen: 0 }).collect();
2706        for (i, &id) in ids.iter().enumerate() {
2707            assert_eq!(map.model_index(id), Some(i));
2708        }
2709
2710        // Incrementally add a fourth model.
2711        let extra = map.alloc(3);
2712        assert_eq!(extra, SpriteModelId { slot: 3, gen: 0 });
2713        assert_eq!(map.model_index(extra), Some(3));
2714
2715        // Remove model 1: its handle goes stale, the rest stay valid.
2716        assert!(map.remove(ids[1]));
2717        assert_eq!(map.model_index(ids[1]), None);
2718        assert_eq!(map.model_index(ids[0]), Some(0));
2719        assert_eq!(map.model_index(ids[2]), Some(2));
2720        assert_eq!(map.model_index(extra), Some(3));
2721
2722        // Double remove / stale removal is a no-op returning false.
2723        assert!(!map.remove(ids[1]));
2724
2725        // A bogus / out-of-range handle resolves to nothing, no panic.
2726        let bogus = SpriteModelId { slot: 999, gen: 0 };
2727        assert_eq!(map.model_index(bogus), None);
2728        assert!(!map.remove(bogus));
2729
2730        // A handle with a mismatched generation never resolves (guards a
2731        // future compacting registry).
2732        let wrong_gen = SpriteModelId { slot: 0, gen: 7 };
2733        assert_eq!(map.model_index(wrong_gen), None);
2734    }
2735
2736    /// The voxel-clip slotmap (VCL.4) mints stable ids, resolves only live
2737    /// handles, tombstones in place, and `reset` clears it — mirroring the
2738    /// model slotmap, since clips register append-only too.
2739    #[test]
2740    fn dyn_clip_map_lifecycle() {
2741        let mut map = DynClipMap::default();
2742        // Two clips registered incrementally (indices 0, 1).
2743        let c0 = map.alloc(0);
2744        let c1 = map.alloc(1);
2745        assert_eq!(c0, VoxelClipId { slot: 0, gen: 0 });
2746        assert_eq!(map.clip_index(c0), Some(0));
2747        assert_eq!(map.clip_index(c1), Some(1));
2748
2749        // Remove clip 0: stale handle, clip 1 stays valid; slot not reused.
2750        assert!(map.remove(c0));
2751        assert_eq!(map.clip_index(c0), None);
2752        assert_eq!(map.clip_index(c1), Some(1));
2753        // Double / stale / out-of-range removes are false, no panic.
2754        assert!(!map.remove(c0));
2755        assert!(!map.remove(VoxelClipId { slot: 99, gen: 0 }));
2756        // Mismatched generation never resolves.
2757        assert_eq!(map.clip_index(VoxelClipId { slot: 1, gen: 5 }), None);
2758
2759        // `set_sprites` resets the clip layer → ids restart at slot 0, but
2760        // the epoch bumps so old handles don't alias the new clips.
2761        map.reset();
2762        assert_eq!(map.clip_index(c1), None, "reset invalidates old handles");
2763        let again = map.alloc(0); // re-takes slot 0 under the new epoch
2764        assert_eq!(again, VoxelClipId { slot: 0, gen: 1 });
2765        assert_eq!(map.clip_index(again), Some(0));
2766        // The footgun fix: c0 (slot 0, old epoch) must NOT resolve to the new
2767        // clip now occupying slot 0.
2768        assert_eq!(
2769            map.clip_index(c0),
2770            None,
2771            "a pre-reset handle must not alias a new clip on the same slot"
2772        );
2773    }
2774
2775    /// The character slotmap (VCL.6) mints stable ids, resolves only live
2776    /// handles, tombstones in place, and `reset` clears it.
2777    #[test]
2778    fn char_map_lifecycle() {
2779        let mut map = CharMap::default();
2780        let a = map.alloc(0);
2781        let b = map.alloc(1);
2782        assert_eq!(a, CharacterId { slot: 0, gen: 0 });
2783        assert_eq!(map.index(a), Some(0));
2784        assert_eq!(map.index(b), Some(1));
2785
2786        assert!(map.remove(a));
2787        assert_eq!(map.index(a), None);
2788        assert_eq!(map.index(b), Some(1));
2789        assert!(!map.remove(a)); // double remove is a no-op
2790        assert!(!map.remove(CharacterId { slot: 9, gen: 0 }));
2791        assert_eq!(map.index(CharacterId { slot: 1, gen: 7 }), None);
2792
2793        map.reset();
2794        assert_eq!(map.index(b), None);
2795        assert_eq!(map.alloc(0), CharacterId { slot: 0, gen: 1 });
2796        assert_eq!(map.index(a), None, "pre-reset handle must not alias slot 0");
2797    }
2798
2799    /// The streaming-clip slotmap (#3) mints stable ids, resolves only live
2800    /// handles, tombstones in place, and `reset` clears it.
2801    #[test]
2802    fn streaming_clip_map_lifecycle() {
2803        let mut map = StreamingClipMap::default();
2804        let a = map.alloc(0);
2805        let b = map.alloc(1);
2806        assert_eq!(a, StreamingClipId { slot: 0, gen: 0 });
2807        assert_eq!(map.index(a), Some(0));
2808        assert_eq!(map.index(b), Some(1));
2809
2810        assert!(map.remove(a));
2811        assert_eq!(map.index(a), None);
2812        assert_eq!(map.index(b), Some(1));
2813        assert!(!map.remove(a)); // double remove is a no-op
2814        assert!(!map.remove(StreamingClipId { slot: 9, gen: 0 }));
2815        assert_eq!(map.index(StreamingClipId { slot: 1, gen: 7 }), None);
2816
2817        map.reset();
2818        assert_eq!(map.index(b), None);
2819        assert_eq!(map.alloc(0), StreamingClipId { slot: 0, gen: 1 });
2820        assert_eq!(map.index(a), None, "pre-reset handle must not alias slot 0");
2821    }
2822
2823    /// The shared clip-playback clock (#6 / VCL.6): `tick` accumulates time
2824    /// at its Q8 speed, resolves the frame, honours `start_phase`, and reads
2825    /// a rewound (negative) clock as frame 0.
2826    #[test]
2827    fn clip_clock_tick_advances_and_resolves_frames() {
2828        // 3 frames, 100 ms each → total 300 ms, looping.
2829        let mut c = ClipClock {
2830            durations: vec![100, 100, 100],
2831            loop_mode: LoopMode::Loop,
2832            speed_q8: 256, // 1×
2833            clock_ms: 0.0,
2834        };
2835        assert_eq!(c.tick(0.0), 0); // t=0 → frame 0
2836        assert_eq!(c.tick(0.10), 1); // t=100 → frame 1 (100 is not < 100)
2837        assert_eq!(c.clock_ms as u32, 100);
2838        assert_eq!(c.tick(0.15), 2); // t=250 → frame 2
2839        assert_eq!(c.tick(0.10), 0); // t=350 → 350%300=50 → frame 0
2840                                     // 0.5× speed advances half as fast.
2841        let mut slow = ClipClock {
2842            durations: vec![100, 100],
2843            loop_mode: LoopMode::Once,
2844            speed_q8: 128, // 0.5×
2845            clock_ms: 0.0,
2846        };
2847        assert_eq!(slow.tick(0.20), 1); // 200ms wall → 100ms clock → frame 1
2848        assert!((slow.clock_ms - 100.0).abs() < 1e-6);
2849        // start_phase seeds the clock; negative clock reads as frame 0.
2850        let mut phased = ClipClock {
2851            durations: vec![50, 50, 50],
2852            loop_mode: LoopMode::Loop,
2853            speed_q8: -256, // rewind
2854            clock_ms: 50.0, // start mid frame 1
2855        };
2856        assert_eq!(phased.tick(0.10), 0); // 50 - 100 = -50 → max(0)=0 → frame 0
2857        assert!(phased.clock_ms < 0.0); // kept signed
2858    }
2859
2860    #[test]
2861    fn dyn_sprite_transform_default_is_identity_and_applies() {
2862        let xf = DynSpriteTransform::default();
2863        assert_eq!(xf.pos, [0.0, 0.0, 0.0]);
2864        assert_eq!(xf.right, [1.0, 0.0, 0.0]);
2865        assert_eq!(xf.up, [0.0, 1.0, 0.0]);
2866        assert_eq!(xf.forward, [0.0, 0.0, 1.0]);
2867
2868        let mut s = Sprite::axis_aligned(
2869            roxlap_formats::kv6::Kv6::solid_cube(2, 0x80_FF_FF_FF),
2870            [9.0, 9.0, 9.0],
2871        );
2872        let posed = DynSpriteTransform {
2873            pos: [1.0, 2.0, 3.0],
2874            right: [0.0, 0.0, 1.0],
2875            up: [0.0, 1.0, 0.0],
2876            forward: [1.0, 0.0, 0.0],
2877        };
2878        posed.apply_to(&mut s);
2879        assert_eq!(s.p, [1.0, 2.0, 3.0]);
2880        assert_eq!(s.s, [0.0, 0.0, 1.0]);
2881        assert_eq!(s.h, [0.0, 1.0, 0.0]);
2882        assert_eq!(s.f, [1.0, 0.0, 0.0]);
2883    }
2884
2885    #[test]
2886    fn options_default_is_cpu_intent() {
2887        let o = RenderOptions::default();
2888        assert!(!o.want_gpu);
2889        assert_eq!(o.clear_sky & 0xFF00_0000, 0, "clear_sky is 0x00RRGGBB");
2890    }
2891
2892    /// A camera at the origin looking down +Y (voxlap z-down world): right
2893    /// = +X, down = +Z, forward = +Y. Handedness `right × down == forward`.
2894    fn cam_looking_y() -> Camera {
2895        Camera {
2896            pos: [0.0, 0.0, 0.0],
2897            right: [1.0, 0.0, 0.0],
2898            down: [0.0, 0.0, 1.0],
2899            forward: [0.0, 1.0, 0.0],
2900        }
2901    }
2902
2903    #[test]
2904    fn world_quad_corner_layout() {
2905        // Top-left at (-5, 10, -5); u = +X (width), v = +Z (down). A
2906        // 10×10 quad facing the camera (its +Y normal points back at us).
2907        let sprite = ImageSprite {
2908            image: ImageId(0),
2909            origin: [-5.0, 10.0, -5.0],
2910            facing: ImageFacing::World {
2911                u: [1.0, 0.0, 0.0],
2912                v: [0.0, 0.0, 1.0],
2913            },
2914            size: [10.0, 10.0],
2915            tint: 0xFFFF_FFFF,
2916            alpha_cutoff: 0.0,
2917            depth_test: true,
2918            double_sided: true,
2919        };
2920        let q = resolve_quad(&sprite, &cam_looking_y()).expect("front-facing");
2921        assert_eq!(q.corners[0], [-5.0, 10.0, -5.0], "TL = origin");
2922        assert_eq!(q.corners[1], [5.0, 10.0, -5.0], "TR = origin + u·size");
2923        assert_eq!(q.corners[2], [-5.0, 10.0, 5.0], "BL = origin + v·size");
2924        assert_eq!(q.corners[3], [5.0, 10.0, 5.0], "BR = origin + u + v");
2925    }
2926
2927    #[test]
2928    fn world_quad_backface_culls_when_single_sided() {
2929        // Same plane but spanned so its normal (u × v) points *away* from
2930        // the camera: swap u/v so the winding flips.
2931        let sprite = ImageSprite {
2932            image: ImageId(0),
2933            origin: [-5.0, 10.0, -5.0],
2934            facing: ImageFacing::World {
2935                u: [0.0, 0.0, 1.0], // v-ish
2936                v: [1.0, 0.0, 0.0], // u-ish → normal flips to -Y... toward camera?
2937            },
2938            size: [10.0, 10.0],
2939            tint: 0xFFFF_FFFF,
2940            alpha_cutoff: 0.0,
2941            depth_test: true,
2942            double_sided: false,
2943        };
2944        // With double_sided=false one of the two windings must cull; the
2945        // opposite winding must draw. Exactly one of the two resolves.
2946        let a = resolve_quad(&sprite, &cam_looking_y()).is_some();
2947        let mut flipped = sprite;
2948        flipped.facing = ImageFacing::World {
2949            u: [1.0, 0.0, 0.0],
2950            v: [0.0, 0.0, 1.0],
2951        };
2952        let b = resolve_quad(&flipped, &cam_looking_y()).is_some();
2953        assert!(a ^ b, "exactly one winding is front-facing");
2954    }
2955
2956    #[test]
2957    fn double_sided_never_culls() {
2958        let mut sprite = ImageSprite {
2959            image: ImageId(0),
2960            origin: [-5.0, 10.0, -5.0],
2961            facing: ImageFacing::World {
2962                u: [0.0, 0.0, 1.0],
2963                v: [1.0, 0.0, 0.0],
2964            },
2965            size: [10.0, 10.0],
2966            tint: 0xFFFF_FFFF,
2967            alpha_cutoff: 0.0,
2968            depth_test: true,
2969            double_sided: true,
2970        };
2971        assert!(resolve_quad(&sprite, &cam_looking_y()).is_some());
2972        sprite.facing = ImageFacing::World {
2973            u: [1.0, 0.0, 0.0],
2974            v: [0.0, 0.0, 1.0],
2975        };
2976        assert!(resolve_quad(&sprite, &cam_looking_y()).is_some());
2977    }
2978
2979    #[test]
2980    fn ray_quad_uv_center_and_corners() {
2981        // 10×10 quad on the y=10 plane: TL(-5,10,-5) u=+X v=+Z. Camera at
2982        // origin looking +Y. A ray straight at the quad centre → uv (.5,.5).
2983        let corners = [
2984            [-5.0, 10.0, -5.0], // TL
2985            [5.0, 10.0, -5.0],  // TR
2986            [-5.0, 10.0, 5.0],  // BL
2987            [5.0, 10.0, 5.0],   // BR
2988        ];
2989        let (uv, t) = ray_quad_uv([0.0, 0.0, 0.0], [0.0, 1.0, 0.0], &corners).expect("center hit");
2990        assert!(
2991            (uv[0] - 0.5).abs() < 1e-5 && (uv[1] - 0.5).abs() < 1e-5,
2992            "centre → (.5,.5)"
2993        );
2994        assert!((t - 10.0).abs() < 1e-4, "t = plane distance");
2995        // Ray toward the TL corner texel region (−x, +y, −z) → uv near (0,0).
2996        let (uv_tl, _) = ray_quad_uv([0.0, 0.0, 0.0], [-4.0, 10.0, -4.0], &corners).unwrap();
2997        assert!(uv_tl[0] < 0.2 && uv_tl[1] < 0.2, "toward TL → small uv");
2998    }
2999
3000    #[test]
3001    fn ray_quad_uv_misses_outside_and_behind() {
3002        let corners = [
3003            [-5.0, 10.0, -5.0],
3004            [5.0, 10.0, -5.0],
3005            [-5.0, 10.0, 5.0],
3006            [5.0, 10.0, 5.0],
3007        ];
3008        // Ray pointing away (−Y) never reaches the +Y plane in front.
3009        assert!(ray_quad_uv([0.0, 0.0, 0.0], [0.0, -1.0, 0.0], &corners).is_none());
3010        // Ray parallel to the quad plane (in +X) → no intersection.
3011        assert!(ray_quad_uv([0.0, 0.0, 0.0], [1.0, 0.0, 0.0], &corners).is_none());
3012        // Ray hitting the plane far outside the quad → outside uv.
3013        assert!(ray_quad_uv([100.0, 0.0, 0.0], [0.0, 1.0, 0.0], &corners).is_none());
3014    }
3015
3016    #[test]
3017    fn billboard_axes_orthogonal_and_top_toward_up() {
3018        // World up = -Z (z-down world). The billboard's v (top→bottom)
3019        // must point away from `up`, and u/v must be ⟂ the view direction.
3020        let up = [0.0, 0.0, -1.0];
3021        let sprite = ImageSprite {
3022            image: ImageId(0),
3023            origin: [0.0, 50.0, 0.0],
3024            facing: ImageFacing::Billboard { up },
3025            size: [4.0, 4.0],
3026            tint: 0xFFFF_FFFF,
3027            alpha_cutoff: 0.0,
3028            depth_test: false,
3029            double_sided: false, // billboards must NEVER cull
3030        };
3031        let q = resolve_quad(&sprite, &cam_looking_y()).expect("billboard always faces camera");
3032        let u = v_sub(q.corners[1], q.corners[0]); // TR - TL = u·size
3033        let v = v_sub(q.corners[2], q.corners[0]); // BL - TL = v·size
3034        let fwd = [0.0, 1.0, 0.0];
3035        assert!(v_dot(u, fwd).abs() < 1e-5, "u ⟂ view");
3036        assert!(v_dot(v, fwd).abs() < 1e-5, "v ⟂ view");
3037        assert!(v_dot(u, v).abs() < 1e-5, "u ⟂ v");
3038        assert!(
3039            v_dot(v, up) < 0.0,
3040            "rows grow away from `up` (top edge toward up)"
3041        );
3042    }
3043}