Skip to main content

ssruntime/eval/
override_layer.rs

1//! Per-part runtime **Override Layer**
2//!
3//! Applies per-part runtime overrides (Visibility, Color, Cell) on the
4//! *resolved* pose at a single seam in `Context::get_frame_data` — after the
5//! source mix, before `compose_frame_data`. Overriding here (rather than during
6//! per-source `extract_pose`) is what lets an override win over both keyframe
7//! values and blend results.
8//!
9//! The override table is a dense `Vec<Option<PartOverride>>` on `InstanceState`,
10//! indexed by `part_index` (O(1), zero per-frame alloc, `no_std` — no `HashMap`).
11
12use alloc::vec::Vec;
13
14use crate::eval::framedata::{CachedPartData, ResolvedCellMeta, premultiply_part_color_corner};
15use crate::eval::keyframes::KeyColumns;
16use crate::runtime::framedata::ss::runtime::{BlendType, PartAttributeCell, PartAttributePartColor, PartState, SsAttributePartColorKeyValueColor, U8Color, UpdateAttributeFlags};
17
18/// Keyframe-vs-override precedence for the attributes that conflict with the
19/// animation (Color and Cell). Visibility has no priority mode.
20#[derive(Clone, Copy, PartialEq, Eq, Debug)]
21pub enum PriorityMode {
22    /// A temporal one-shot handover. The override wins from the moment it
23    /// is set until playback *decodes a surviving keyframe* of that attribute —
24    /// detected by watching the controller's actually-traversed frames
25    /// (`get_passed_frames`) for a key frame. This is section / loop / reverse /
26    /// ping-pong correct for free: only frames the playhead really visits count,
27    /// and the loop wraps to the section start, so keys outside the play range
28    /// never trigger it. The override's own set-frame keyframe is ignored through
29    /// the update of its first evaluation, so setting on a keyframe wins that
30    /// keyframe's segment, however many times that update's frame is evaluated.
31    ///
32    /// At handover the slot is dropped, so it does not reappear (only a re-set
33    /// reactivates it). If the play range decodes no key of that
34    /// attribute, the override persists like `Permanent`. The "surviving key"
35    /// wording matters: the converter prunes flat-hold duplicates, so handover
36    /// lands on a key that actually shapes the curve. Cleared on a new animation.
37    OverwriteOnNextKeyframe,
38    /// Wins for the current animation; cleared on a new one.
39    HoldUntilNextAnimation,
40    /// Wins and persists across animation changes (re-validated by
41    /// index range within the same SSAB).
42    Permanent,
43}
44
45impl PriorityMode {
46    /// Map the FFI `priority_mode` byte (`0/1/2`) to a mode.
47    pub fn from_u8(v: u8) -> Option<Self> {
48        match v {
49            0 => Some(Self::OverwriteOnNextKeyframe),
50            1 => Some(Self::HoldUntilNextAnimation),
51            2 => Some(Self::Permanent),
52            _ => None,
53        }
54    }
55}
56
57/// Per-part color override (mirrors SS6 `PartsColorChange`). Applied to Normal
58/// parts only. Corners are stored raw (r, g, b, a) in ssruntime order
59/// `lt, rt, lb, rb`; alpha is pre-multiplied at the seam against the part's
60/// composited alpha, matching keyframed PartColor.
61#[derive(Clone, Copy)]
62pub struct ColorOverride {
63    /// `0=Mix 1=Mul 2=Add 3=Sub`.
64    pub blend_op: u8,
65    /// Four corners `lt, rt, lb, rb`, each `[r, g, b, a]`.
66    pub corners_rgba: [[u8; 4]; 4],
67    /// Per-corner blend rate (single value applied to all corners; `1.0` = full).
68    pub rate: f32,
69    pub priority: PriorityMode,
70    /// `OverwriteOnNextKeyframe` only: the integer frame the override was set on
71    /// (floor of the playhead). Handover fires once playback *decodes* a
72    /// surviving PartColor keyframe after this — but the override's own
73    /// `set_frame` keyframe is ignored through the update of its first
74    /// evaluation, so setting on a keyframe wins that keyframe's segment. Unused
75    /// for other modes.
76    pub set_frame: i32,
77    /// `OverwriteOnNextKeyframe` only: the update the override was first
78    /// evaluated in (the context's `Context::update` count), or `None` before
79    /// that. Every evaluation in that update skips `set_frame`, so a frame
80    /// evaluated again gives the same answer. See
81    /// [`PriorityMode::OverwriteOnNextKeyframe`] / [`passed_reaches_key`].
82    pub first_eval_update: Option<u64>,
83}
84
85/// Per-part cell override (mirrors SS6 `CellChangeParts`). Applied to Normal and
86/// Mask parts only. The cell is identified by `(cellmap_name_hash,
87/// cell_name_hash)` and resolved to a [`ResolvedCellMeta`] **once at set time**
88/// (cached here); the seam then only writes the resolved geometry / texture / UV
89/// meta and repoints the identity index — no per-frame hash lookup.
90#[derive(Clone, Copy)]
91pub struct CellOverride {
92    pub cellmap_name_hash: u32,
93    pub cell_name_hash: u32,
94    pub resolved: ResolvedCellMeta,
95    pub priority: PriorityMode,
96    /// `OverwriteOnNextKeyframe` only: the integer frame the override was set on.
97    /// See [`ColorOverride::set_frame`].
98    pub set_frame: i32,
99    /// `OverwriteOnNextKeyframe` only: the update of the first evaluation. See
100    /// [`ColorOverride::first_eval_update`].
101    pub first_eval_update: Option<u64>,
102}
103
104/// Force-hide a part, optionally cascading to its descendants (a faithful port
105/// of SS6 `HideSet`'s `flagInvolveChildren`). Force-*visible* (overriding a
106/// keyframed hide) is intentionally reserved but not implemented; the FFI
107/// reserves `force == 2` for it.
108#[derive(Clone, Copy, Default)]
109pub struct VisibilityOverride {
110    /// When set, the force-hide propagates to all descendants in the part tree.
111    pub cascade: bool,
112}
113
114/// A per-part override entry. Absent attributes are `None`. An all-`None` entry
115/// is equivalent to no override (see [`PartOverride::is_empty`]).
116#[derive(Clone, Default)]
117pub struct PartOverride {
118    pub visibility: Option<VisibilityOverride>,
119    pub color: Option<ColorOverride>,
120    pub cell: Option<CellOverride>,
121}
122
123impl PartOverride {
124    /// True when the entry carries no active override (all attributes `None`).
125    pub fn is_empty(&self) -> bool {
126        self.visibility.is_none() && self.color.is_none() && self.cell.is_none()
127    }
128}
129
130/// Decide whether an `OverwriteOnNextKeyframe` override should hand over this
131/// update, from the frames the controller actually traversed (`passed_frames`).
132///
133/// Handover fires when any passed frame is a surviving keyframe of the
134/// attribute, except that through the update of the first evaluation
135/// (`skip_set_frame`) the override's own `set_frame` is skipped — setting on (or
136/// the first update sitting on) a keyframe wins that keyframe's segment rather
137/// than reclaiming immediately. Using the traversed frames makes this section /
138/// loop / reverse / ping-pong correct without any direction or wrap-point
139/// bookkeeping.
140pub fn passed_reaches_key(passed_frames: &[i32], set_frame: i32, skip_set_frame: bool, is_key: impl Fn(i32) -> bool) -> bool {
141    passed_frames.iter().any(|&f| !(skip_set_frame && f == set_frame) && is_key(f))
142}
143
144/// Whether an OverwriteOnNextKeyframe override evaluated in `update` skips its own `set_frame`: on its
145/// first evaluation, and on any other in the same update. The traversed frames
146/// change only with the next update, so every evaluation of one update sees
147/// what the first saw and must decide as it did.
148fn skips_set_frame(first_eval_update: Option<u64>, update: u64) -> bool {
149    first_eval_update.is_none_or(|u| u == update)
150}
151
152/// True when `run` (surviving keyframes, sorted ascending by frame) has a
153/// keyframe exactly at frame `f`: the last key at or before `f` sits on it.
154fn run_has_key_at(keys: &KeyColumns, run: Option<crate::eval::keyframes::KeyRun>, f: i32) -> bool {
155    let Some(run) = run else { return false };
156    keys.frames(&run).locate(f as f32, &mut 0).is_some_and(|i| keys.key(run.first() as usize + i).index() as i32 == f)
157}
158
159/// Apply the override table on the resolved pose at the seam.
160///
161/// `override_hide_workspace` is a caller-owned scratch buffer (reused frame to
162/// frame to avoid hot-path allocation); its contents on entry are irrelevant.
163/// `parts_color_vec` is the resolved layer's per-part color side vector; a color
164/// override appends a resolved entry and repoints `PartState.part_color` (the
165/// side vecs are rebuilt from the primary every frame, so appends never
166/// accumulate across frames). A cell override likewise appends to `cell_vec`,
167/// overwrites the parallel `cell_meta_per_part` (6 floats/part) + the
168/// `cell_texture_hashes` slot, and repoints `PartState.cell`. `update` is the
169/// context's `Context::update` count, which an OverwriteOnNextKeyframe override's first evaluation
170/// records.
171#[allow(clippy::too_many_arguments)]
172pub fn apply_part_overrides(
173    part_overrides: &mut [Option<PartOverride>],
174    cached_parts: &[CachedPartData],
175    keys: &KeyColumns,
176    parts_vec: &mut [PartState],
177    parts_color_vec: &mut Vec<PartAttributePartColor>,
178    cell_vec: &mut Vec<PartAttributeCell>,
179    cell_meta_per_part: &mut [f32],
180    cell_texture_hashes: &mut [u32],
181    override_cell_uv_meta: &mut [Option<ResolvedCellMeta>],
182    override_hide_workspace: &mut Vec<bool>,
183    passed_frames: &[i32],
184    update: u64,
185) {
186    let n = parts_vec.len();
187
188    // --- Visibility (force-hide + optional cascade) ---
189    //
190    // Parts are stored parent-before-child, so a single forward pass that
191    // propagates an "ancestor force-hidden (cascading)" flag through
192    // `parent_index` handles the cascade without building child lists. Note
193    // this cascade is *override-only* behavior: keyframed `hide` is per-part in
194    // SpriteStudio and never cascades (see `eval/framedata.rs`), so we must not key the
195    // cascade off `parts_vec[parent].hide()` — only off overrides.
196    override_hide_workspace.clear();
197    override_hide_workspace.resize(n, false);
198
199    for i in 0..n {
200        if i >= cached_parts.len() {
201            break;
202        }
203        let vis = part_overrides.get(i).and_then(|o| o.as_ref()).and_then(|o| o.visibility);
204        let self_hide = vis.is_some();
205        let cascade = vis.map(|v| v.cascade).unwrap_or(false);
206
207        let parent_idx = cached_parts[i].parent_index;
208        let ancestor_cascading = if parent_idx >= 0 && (parent_idx as usize) < i { override_hide_workspace[parent_idx as usize] } else { false };
209
210        let force_hidden = self_hide || ancestor_cascading;
211        // The workspace flag = "force-hide cascades from here to descendants":
212        // an inherited cascade continues, and an own override cascades only when
213        // its `cascade` bit is set.
214        override_hide_workspace[i] = ancestor_cascading || (self_hide && cascade);
215
216        if force_hidden {
217            parts_vec[i].set_hide(true);
218        }
219    }
220
221    // --- Color (Normal parts only) ---
222    for i in 0..n {
223        if i >= cached_parts.len() {
224            break;
225        }
226        // Copy the entry out (Copy) so the borrow is released before a possible
227        // one-shot drop below.
228        let Some(color) = part_overrides.get(i).and_then(|o| o.as_ref()).and_then(|o| o.color) else {
229            continue;
230        };
231        // SS6 restricts PartsColorChange to NORMAL parts.
232        if cached_parts[i].part_type_disc != ssab::ssab::ss::format::PartType::PartTypeNormal {
233            continue;
234        }
235
236        // OverwriteOnNextKeyframe: one-shot temporal handover. The override
237        // wins until playback decodes a surviving PartColor key of this part —
238        // i.e. a traversed frame lands on a key (its own set-frame key skipped
239        // through the update of its first evaluation). Dropping the slot makes
240        // it permanent: it survives loops and only a re-set brings it back.
241        if color.priority == PriorityMode::OverwriteOnNextKeyframe {
242            let skip = skips_set_frame(color.first_eval_update, update);
243            let handed_over = passed_reaches_key(passed_frames, color.set_frame, skip, |f| run_has_key_at(keys, cached_parts[i].run(crate::eval::framedata::IDX_ATTRIBUTEPARTCOLOR), f));
244            if let Some(o) = part_overrides.get_mut(i).and_then(|o| o.as_mut()) {
245                if handed_over {
246                    o.color = None;
247                } else if let Some(c) = o.color.as_mut() {
248                    c.first_eval_update.get_or_insert(update);
249                }
250            }
251            if handed_over {
252                continue;
253            }
254        }
255
256        let flag = parts_vec[i].update_flag();
257
258        // Build the override color and pre-multiply alpha by the part's already
259        // composited alpha, exactly as keyframed PartColor does.
260        let alpha = parts_vec[i].alpha();
261        let corner = |k: usize| -> SsAttributePartColorKeyValueColor {
262            let [r, g, b, a] = color.corners_rgba[k];
263            let raw = SsAttributePartColorKeyValueColor::new(&U8Color::new(a, r, g, b), color.rate);
264            premultiply_part_color_corner(&raw, alpha)
265        };
266        let (lt, rt, lb, rb) = (corner(0), corner(1), corner(2), corner(3));
267        let pc = PartAttributePartColor::new(BlendType(color.blend_op), &lt, &rt, &lb, &rb);
268
269        parts_color_vec.push(pc);
270        parts_vec[i].set_part_color((parts_color_vec.len() - 1) as i16);
271        // Mark the attribute present so compose emits the 5-vertex/center-color
272        // form for parts that had no keyframed color.
273        parts_vec[i].set_update_flag(flag | UpdateAttributeFlags::AttributePartColor);
274    }
275
276    // --- Cell (Normal + Mask parts only) ---
277    for i in 0..n {
278        if i >= cached_parts.len() {
279            break;
280        }
281        let Some(cell) = part_overrides.get(i).and_then(|o| o.as_ref()).and_then(|o| o.cell) else {
282            continue;
283        };
284        let cp = &cached_parts[i];
285        // SS6 restricts CellChangeParts to NORMAL; masks also sample a cell.
286        if cp.part_type_disc != ssab::ssab::ss::format::PartType::PartTypeNormal && !cp.is_mask_contributor {
287            continue;
288        }
289
290        // OverwriteOnNextKeyframe one-shot handover (see the color pass for the rationale).
291        if cell.priority == PriorityMode::OverwriteOnNextKeyframe {
292            let skip = skips_set_frame(cell.first_eval_update, update);
293            let handed_over = passed_reaches_key(passed_frames, cell.set_frame, skip, |f| run_has_key_at(keys, cp.run(crate::eval::framedata::IDX_ATTRIBUTECELL), f));
294            if let Some(o) = part_overrides.get_mut(i).and_then(|o| o.as_mut()) {
295                if handed_over {
296                    o.cell = None;
297                } else if let Some(c) = o.cell.as_mut() {
298                    c.first_eval_update.get_or_insert(update);
299                }
300            }
301            if handed_over {
302                continue;
303            }
304        }
305
306        let flag = parts_vec[i].update_flag();
307
308        let m = &cell.resolved;
309        // (1) geometry channel — consumed by compute_local_vertices_for_parts.
310        let off = i * 6;
311        if off + 6 <= cell_meta_per_part.len() {
312            cell_meta_per_part[off] = m.pivot_x;
313            cell_meta_per_part[off + 1] = m.pivot_y;
314            cell_meta_per_part[off + 2] = m.size_w;
315            cell_meta_per_part[off + 3] = m.size_h;
316            cell_meta_per_part[off + 4] = m.rect_left;
317            cell_meta_per_part[off + 5] = m.rect_top;
318        }
319        // (2) texture channel — drives the DrawBatch texture_hash.
320        if i < cell_texture_hashes.len() {
321            cell_texture_hashes[i] = m.texture_hash;
322        }
323        // (3) UV channel — compute_local_uvs samples the keyframe cell
324        // (the layer's cell_ids) which the seam cannot touch; record the
325        // resolved meta so the overridden cell's UV rect / rotation / tex size
326        // is what actually gets sampled.
327        if i < override_cell_uv_meta.len() {
328            override_cell_uv_meta[i] = Some(*m);
329        }
330        // (4) identity — the emitted FrameData's cell reference.
331        cell_vec.push(PartAttributeCell::new(cell.cellmap_name_hash, cell.cell_name_hash));
332        parts_vec[i].set_cell((cell_vec.len() - 1) as i16);
333        parts_vec[i].set_update_flag(flag | UpdateAttributeFlags::AttributeCell);
334
335        // A changed cell re-derives the default size for parts without a SizeX/Y
336        // key (mirrors extract_pose's cell-size fallback).
337        if !flag.contains(UpdateAttributeFlags::AttributeSizeX) {
338            parts_vec[i].set_size_x(m.size_w);
339        }
340        if !flag.contains(UpdateAttributeFlags::AttributeSizeY) {
341            parts_vec[i].set_size_y(m.size_h);
342        }
343    }
344}
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349    use crate::eval::framedata::cached_part_stub;
350    use ssab::ssab::ss::format::PartType;
351
352    /// A blank part state with a given composited alpha and dirty-flag mask.
353    fn state(alpha: f32, flag: UpdateAttributeFlags) -> PartState {
354        let mut s = PartState::default();
355        s.set_alpha(alpha);
356        s.set_cell(-1);
357        s.set_part_color(-1);
358        s.set_update_flag(flag);
359        s
360    }
361
362    /// Run `apply_part_overrides` with no traversed frames (the common case for
363    /// tests of the other modes, and for this one where nothing has been decoded yet).
364    #[allow(clippy::type_complexity)]
365    fn run(ovr: &mut [Option<PartOverride>], cached: &[CachedPartData], parts: &mut [PartState]) -> (Vec<PartAttributePartColor>, Vec<PartAttributeCell>, Vec<f32>, Vec<u32>, Vec<Option<ResolvedCellMeta>>) {
366        run_passed(ovr, cached, parts, &[])
367    }
368
369    /// Run `apply_part_overrides` with freshly-sized side buffers and an explicit
370    /// traversed-frame list; returns `(parts_color_vec, cell_vec,
371    /// cell_meta_per_part, cell_texture_hashes, override_cell_uv_meta)`.
372    #[allow(clippy::type_complexity)]
373    fn run_passed(ovr: &mut [Option<PartOverride>], cached: &[CachedPartData], parts: &mut [PartState], passed_frames: &[i32]) -> (Vec<PartAttributePartColor>, Vec<PartAttributeCell>, Vec<f32>, Vec<u32>, Vec<Option<ResolvedCellMeta>>) {
374        let n = parts.len();
375        let mut color_vec = Vec::new();
376        let mut cell_vec = Vec::new();
377        let mut cell_meta = vec![0.0f32; n * 6];
378        let mut tex_hashes = vec![0u32; n];
379        let mut uv_meta = vec![None; n];
380        let mut ws = Vec::new();
381        let keyframes = crate::eval::keyframes::empty_keyframes();
382        let keys = KeyColumns::new(flatbuffers::root::<ssab::ssab::ss::format::Keyframes>(&keyframes).unwrap(), None);
383        // Update 1: the helpers' OverwriteOnNextKeyframe overrides were first evaluated in update 0.
384        apply_part_overrides(ovr, cached, &keys, parts, &mut color_vec, &mut cell_vec, &mut cell_meta, &mut tex_hashes, &mut uv_meta, &mut ws, passed_frames, 1);
385        (color_vec, cell_vec, cell_meta, tex_hashes, uv_meta)
386    }
387
388    fn vis(cascade: bool) -> PartOverride {
389        PartOverride { visibility: Some(VisibilityOverride { cascade }), ..Default::default() }
390    }
391
392    fn color(blend_op: u8, rgba: [u8; 4], priority: PriorityMode) -> PartOverride {
393        PartOverride { color: Some(ColorOverride { blend_op, corners_rgba: [rgba; 4], rate: 1.0, priority, set_frame: 0, first_eval_update: Some(0) }), ..Default::default() }
394    }
395
396    fn cell(cellmap_name_hash: u32, cell_name_hash: u32, size: (f32, f32), texture_hash: u32, priority: PriorityMode) -> PartOverride {
397        let resolved = ResolvedCellMeta { size_w: size.0, size_h: size.1, texture_hash, ..Default::default() };
398        PartOverride { cell: Some(CellOverride { cellmap_name_hash, cell_name_hash, resolved, priority, set_frame: 0, first_eval_update: Some(0) }), ..Default::default() }
399    }
400
401    #[test]
402    fn priority_mode_from_u8() {
403        assert_eq!(PriorityMode::from_u8(0), Some(PriorityMode::OverwriteOnNextKeyframe));
404        assert_eq!(PriorityMode::from_u8(1), Some(PriorityMode::HoldUntilNextAnimation));
405        assert_eq!(PriorityMode::from_u8(2), Some(PriorityMode::Permanent));
406        assert_eq!(PriorityMode::from_u8(3), None);
407    }
408
409    // --- Visibility ---
410
411    #[test]
412    fn visibility_force_hide_single() {
413        let cached = [cached_part_stub(0, -1, PartType::PartTypeNull, false), cached_part_stub(1, 0, PartType::PartTypeNormal, false)];
414        let mut parts = [state(1.0, UpdateAttributeFlags::empty()), state(1.0, UpdateAttributeFlags::empty())];
415        let mut ovr = [None, Some(vis(false))];
416        run(&mut ovr, &cached, &mut parts);
417        assert!(!parts[0].hide());
418        assert!(parts[1].hide());
419    }
420
421    #[test]
422    fn visibility_cascade_hides_whole_subtree() {
423        // 0 = root, 1 child of 0, 2 child of 1 (parent-before-child order).
424        let cached = [cached_part_stub(0, -1, PartType::PartTypeNull, false), cached_part_stub(1, 0, PartType::PartTypeNormal, false), cached_part_stub(2, 1, PartType::PartTypeNormal, false)];
425        let mut parts = [state(1.0, UpdateAttributeFlags::empty()), state(1.0, UpdateAttributeFlags::empty()), state(1.0, UpdateAttributeFlags::empty())];
426        let mut ovr = [Some(vis(true)), None, None];
427        run(&mut ovr, &cached, &mut parts);
428        assert!(parts[0].hide() && parts[1].hide() && parts[2].hide());
429    }
430
431    #[test]
432    fn visibility_non_cascade_leaves_descendants() {
433        let cached = [cached_part_stub(0, -1, PartType::PartTypeNull, false), cached_part_stub(1, 0, PartType::PartTypeNormal, false), cached_part_stub(2, 1, PartType::PartTypeNormal, false)];
434        let mut parts = [state(1.0, UpdateAttributeFlags::empty()), state(1.0, UpdateAttributeFlags::empty()), state(1.0, UpdateAttributeFlags::empty())];
435        let mut ovr = [Some(vis(false)), None, None];
436        run(&mut ovr, &cached, &mut parts);
437        assert!(parts[0].hide());
438        assert!(!parts[1].hide() && !parts[2].hide());
439    }
440
441    #[test]
442    fn keyframe_hide_does_not_cascade() {
443        // A parent hidden by a *keyframe* (not an override) must not hide its
444        // child — the override cascade keys off overrides only.
445        let cached = [cached_part_stub(0, -1, PartType::PartTypeNormal, false), cached_part_stub(1, 0, PartType::PartTypeNormal, false)];
446        let mut parts = [state(1.0, UpdateAttributeFlags::empty()), state(1.0, UpdateAttributeFlags::empty())];
447        parts[0].set_hide(true); // simulate a keyframed hide on the parent
448        let mut ovr = [None, None];
449        run(&mut ovr, &cached, &mut parts);
450        assert!(!parts[1].hide());
451    }
452
453    // --- Color ---
454
455    #[test]
456    fn color_normal_only_and_premultiply() {
457        let cached = [cached_part_stub(0, -1, PartType::PartTypeNull, false), cached_part_stub(1, -1, PartType::PartTypeNormal, false)];
458        let mut parts = [state(1.0, UpdateAttributeFlags::empty()), state(0.5, UpdateAttributeFlags::empty())];
459        // Add color (Add op) with opaque input to both; only the Normal part takes it.
460        let mut ovr = [Some(color(2, [0x80, 0x40, 0x20, 0xFF], PriorityMode::HoldUntilNextAnimation)), Some(color(2, [0x80, 0x40, 0x20, 0xFF], PriorityMode::HoldUntilNextAnimation))];
461        let (cv, ..) = run(&mut ovr, &cached, &mut parts);
462
463        assert_eq!(parts[0].part_color(), -1, "non-Normal part must be skipped");
464        let idx = parts[1].part_color();
465        assert!(idx >= 0);
466        assert_eq!(cv.len(), 1);
467        assert!(parts[1].update_flag().contains(UpdateAttributeFlags::AttributePartColor), "center-vertex flag must be set");
468        let lt = cv[idx as usize].lt().rgba();
469        assert_eq!((lt.r(), lt.g(), lt.b()), (0x80, 0x40, 0x20));
470        assert_eq!(lt.a(), 127, "alpha 0xFF pre-multiplied by part alpha 0.5");
471        assert_eq!(cv[idx as usize].blend_type().0, 2, "blend op preserved (Add)");
472    }
473
474    // --- Color OverwriteOnNextKeyframe ---
475    //
476    // The seam decides handover from `passed_frames` against the part's key
477    // run. The pure predicate is unit-tested in `passed_reaches_key_*` below;
478    // the end-to-end behaviour with real keyframes / looping lives in the
479    // `override_*_non_*` tests in `src/tests/override_layer.rs`. Here we assert only the plumbing
480    // for a part that has no color keys: it can never decode one, so an OverwriteOnNextKeyframe
481    // override applies indefinitely (like Permanent).
482
483    #[test]
484    fn color_non_without_keys_is_permanent() {
485        let cached = [cached_part_stub(0, -1, PartType::PartTypeNormal, false)];
486        let mut parts = [state(1.0, UpdateAttributeFlags::empty())];
487        let mut ovr = [Some(color(0, [1, 2, 3, 255], PriorityMode::OverwriteOnNextKeyframe))];
488        // Even with frames "passed", a keyless part never hands over.
489        let (cv, ..) = run_passed(&mut ovr, &cached, &mut parts, &[0, 5, 10]);
490        assert_eq!(cv.len(), 1, "no color keys → OverwriteOnNextKeyframe override never hands over");
491        assert!(parts[0].part_color() >= 0);
492        assert!(ovr[0].as_ref().unwrap().color.is_some());
493    }
494
495    #[test]
496    fn color_priority_now_overrides_keyframe() {
497        let cached = [cached_part_stub(0, -1, PartType::PartTypeNormal, false)];
498        let mut parts = [state(1.0, UpdateAttributeFlags::AttributePartColor)];
499        let mut ovr = [Some(color(0, [1, 2, 3, 255], PriorityMode::HoldUntilNextAnimation))];
500        let (cv, ..) = run(&mut ovr, &cached, &mut parts);
501        assert_eq!(cv.len(), 1);
502        assert!(parts[0].part_color() >= 0);
503    }
504
505    // --- Cell ---
506
507    #[test]
508    fn cell_applies_all_channels_and_size() {
509        let cached = [cached_part_stub(0, -1, PartType::PartTypeNormal, false)];
510        let mut parts = [state(1.0, UpdateAttributeFlags::empty())];
511        let mut ovr = [Some(cell(0x1111, 0x2222, (30.0, 40.0), 0xABCD, PriorityMode::HoldUntilNextAnimation))];
512        let (_, cv, cmp, cth, uv) = run(&mut ovr, &cached, &mut parts);
513
514        let idx = parts[0].cell();
515        assert!(idx >= 0);
516        assert_eq!((cv[idx as usize].cellmap_name_hash(), cv[idx as usize].name_hash()), (0x1111, 0x2222));
517        assert_eq!(cth[0], 0xABCD, "texture channel");
518        assert_eq!(cmp[2], 30.0, "geometry size_w at +2");
519        assert_eq!(cmp[3], 40.0, "geometry size_h at +3");
520        // UV channel: the resolved meta is recorded so compute_local_uvs samples
521        // the overridden cell (not just the geometry/texture channels).
522        let uv_meta = uv[0].expect("UV meta recorded for the overridden cell");
523        assert_eq!((uv_meta.size_w, uv_meta.size_h, uv_meta.texture_hash), (30.0, 40.0, 0xABCD));
524        assert!(parts[0].update_flag().contains(UpdateAttributeFlags::AttributeCell));
525        assert_eq!(parts[0].size_x(), 30.0, "size re-derived when unkeyed");
526        assert_eq!(parts[0].size_y(), 40.0);
527    }
528
529    #[test]
530    fn cell_normal_and_mask_only() {
531        let cached = [cached_part_stub(0, -1, PartType::PartTypeNull, false), cached_part_stub(1, -1, PartType::PartTypeMask, true)];
532        let mut parts = [state(1.0, UpdateAttributeFlags::empty()), state(1.0, UpdateAttributeFlags::empty())];
533        let ov = cell(1, 2, (8.0, 8.0), 9, PriorityMode::HoldUntilNextAnimation);
534        let mut ovr = [Some(ov.clone()), Some(ov)];
535        let (_, cv, ..) = run(&mut ovr, &cached, &mut parts);
536        assert_eq!(parts[0].cell(), -1, "Null part skipped");
537        assert!(parts[1].cell() >= 0, "Mask part applied");
538        assert_eq!(cv.len(), 1);
539    }
540
541    // --- passed_reaches_key (the OverwriteOnNextKeyframe handover predicate) ---
542
543    #[test]
544    fn passed_reaches_key_fires_on_a_key_frame() {
545        let is_key = |f: i32| [0, 20, 40].contains(&f);
546        // Crossed 6..8, none is a key → no handover.
547        assert!(!passed_reaches_key(&[6, 7, 8], 5, false, is_key));
548        // Crossed onto key 20 → handover.
549        assert!(passed_reaches_key(&[18, 19, 20], 5, false, is_key));
550    }
551
552    #[test]
553    fn passed_reaches_key_skips_the_set_frame_on_first_eval() {
554        let is_key = |f: i32| [0, 20, 40].contains(&f);
555        // First eval: the set frame's own key (0) is where the override took
556        // over — sitting on it must not hand over.
557        assert!(!passed_reaches_key(&[0], 0, true, is_key));
558        // A *different* key traversed on the same first eval still hands over.
559        assert!(passed_reaches_key(&[0, 20], 0, true, is_key));
560        // Past the first eval, the set frame reached again (e.g. a loop) counts.
561        assert!(passed_reaches_key(&[0], 0, false, is_key));
562    }
563
564    #[test]
565    fn passed_reaches_key_empty_never_fires() {
566        assert!(!passed_reaches_key(&[], 5, true, |_| true));
567        assert!(!passed_reaches_key(&[], 5, false, |_| true));
568    }
569}