Skip to main content

ssruntime/eval/
framedata.rs

1use crate::eval::interpolation::*;
2use crate::eval::keyframes::{KeyColumns, KeyRun};
3use crate::eval::{SsCoordinateSystem, SsOrigin, SsUnit};
4use crate::runtime;
5use alloc::vec::Vec;
6
7pub const NUM_PART_ATTRIBUTES: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::all().bits().count_ones() as usize;
8
9pub const IDX_ATTRIBUTECELL: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeCell.bits().trailing_zeros() as usize;
10const IDX_ATTRIBUTEPOSX: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributePosX.bits().trailing_zeros() as usize;
11const IDX_ATTRIBUTEPOSY: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributePosY.bits().trailing_zeros() as usize;
12const IDX_ATTRIBUTEPOSZ: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributePosZ.bits().trailing_zeros() as usize;
13const IDX_ATTRIBUTEROTX: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeRotX.bits().trailing_zeros() as usize;
14const IDX_ATTRIBUTEROTY: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeRotY.bits().trailing_zeros() as usize;
15const IDX_ATTRIBUTEROTZ: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeRotZ.bits().trailing_zeros() as usize;
16const IDX_ATTRIBUTESCLX: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeSclX.bits().trailing_zeros() as usize;
17const IDX_ATTRIBUTESCLY: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeSclY.bits().trailing_zeros() as usize;
18const IDX_ATTRIBUTELOSCLX: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeLosclX.bits().trailing_zeros() as usize;
19const IDX_ATTRIBUTELOSCLY: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeLosclY.bits().trailing_zeros() as usize;
20const IDX_ATTRIBUTEALPHA: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeAlpha.bits().trailing_zeros() as usize;
21const IDX_ATTRIBUTELOALPHA: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeLoAlpha.bits().trailing_zeros() as usize;
22pub(crate) const IDX_ATTRIBUTEPRIO: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributePrio.bits().trailing_zeros() as usize;
23const IDX_ATTRIBUTEFLIPH: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeFlipH.bits().trailing_zeros() as usize;
24const IDX_ATTRIBUTEFLIPV: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeFlipV.bits().trailing_zeros() as usize;
25const IDX_ATTRIBUTEHIDE: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeHide.bits().trailing_zeros() as usize;
26pub(crate) const IDX_ATTRIBUTEPARTCOLOR: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributePartColor.bits().trailing_zeros() as usize;
27pub(crate) const IDX_ATTRIBUTESHADER: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeShader.bits().trailing_zeros() as usize;
28const IDX_ATTRIBUTEVERTEX: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeVertex.bits().trailing_zeros() as usize;
29const IDX_ATTRIBUTEPIVOTX: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributePivotX.bits().trailing_zeros() as usize;
30const IDX_ATTRIBUTEPIVOTY: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributePivotY.bits().trailing_zeros() as usize;
31const IDX_ATTRIBUTEANCHORX: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeAnchorX.bits().trailing_zeros() as usize;
32const IDX_ATTRIBUTEANCHORY: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeAnchorY.bits().trailing_zeros() as usize;
33const IDX_ATTRIBUTESIZEX: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeSizeX.bits().trailing_zeros() as usize;
34const IDX_ATTRIBUTESIZEY: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeSizeY.bits().trailing_zeros() as usize;
35const IDX_ATTRIBUTEIMGFLIPH: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeImgFlipH.bits().trailing_zeros() as usize;
36const IDX_ATTRIBUTEIMGFLIPV: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeImgFlipV.bits().trailing_zeros() as usize;
37const IDX_ATTRIBUTEUVTX: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeUvtX.bits().trailing_zeros() as usize;
38const IDX_ATTRIBUTEUVTY: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeUvtY.bits().trailing_zeros() as usize;
39const IDX_ATTRIBUTEUVRZ: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeUvrZ.bits().trailing_zeros() as usize;
40const IDX_ATTRIBUTEUVSX: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeUvsX.bits().trailing_zeros() as usize;
41const IDX_ATTRIBUTEUVSY: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeUvsY.bits().trailing_zeros() as usize;
42const IDX_ATTRIBUTEBOUNDR: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeBoundr.bits().trailing_zeros() as usize;
43const IDX_ATTRIBUTEMASK: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeMask.bits().trailing_zeros() as usize;
44const IDX_ATTRIBUTESKEW: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeSkew.bits().trailing_zeros() as usize;
45pub const IDX_ATTRIBUTEDEFORM: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeDeform.bits().trailing_zeros() as usize;
46pub const IDX_ATTRIBUTETEXTURE: usize = crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeTexture.bits().trailing_zeros() as usize;
47
48/// Stride (number of `f32`s) per part in the `shape_vertices` and
49/// `shape_vertex_box_coords` buffers (`ss_runtime_get_shape_vertices` and
50/// `ss_runtime_get_shape_vertex_box_coords` in the C-API): 12 vertices of two
51/// floats each, the most a shape part has (a star).
52pub const SHAPE_VERTICES_STRIDE: usize = 24;
53
54/// Stride (number of `f32`s) per part in the `local_vertices` SoA buffer.
55/// Layout: `[lt.x, lt.y, rt.x, rt.y, lb.x, lb.y, rb.x, rb.y, center.x, center.y]`
56/// in part-local space, with `coordinate_system` (Y-Up/Y-Down) flip already applied.
57pub const LOCAL_VERTICES_STRIDE: usize = 10;
58
59#[derive(Clone, Copy, Default)]
60pub struct ResolvedCellMeta {
61    pub pivot_x: f32,
62    pub pivot_y: f32,
63    pub size_w: f32,
64    pub size_h: f32,
65
66    pub rect_left: f32,
67    pub rect_top: f32,
68    pub tex_w: f32,
69    pub tex_h: f32,
70    pub rotated: bool,
71
72    pub texture_hash: u32,
73}
74
75/// Resolve one `(cellmap_name_hash, cell_name_hash)` against the SSAB cellmaps
76/// to a [`ResolvedCellMeta`], or `None` when either lookup fails. Both
77/// cellmaps and cells are stored in `name_hash`-sorted order (FlatBuffers
78/// `key`), so each lookup is a binary search. Resolves every cell the pack's
79/// keys show, once, at load ([`KeyColumns::new`]), and the Override Layer's
80/// cell at set time, so the two cannot disagree.
81pub(crate) fn resolve_cell(cellmaps: &flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<ssab::ssab::ss::format::CellMap<'_>>>, cellmap_name_hash: u32, cell_name_hash: u32) -> Option<ResolvedCellMeta> {
82    let cellmap = crate::eval::ssab_lookup::find_cellmap(cellmaps, cellmap_name_hash)?;
83    let cells = cellmap.cells()?;
84    let cell = crate::eval::ssab_lookup::find_cell(&cells, cell_name_hash)?;
85
86    let p = cell.pivot();
87    let (pivot_x, pivot_y) = (p.v1(), p.v2());
88    let r = cell.region();
89    let (rect_left, rect_top, size_w, size_h) = (r.x(), r.y(), r.w(), r.h());
90    // A zero `size_original` takes the cell rect's size as the texture size.
91    let v = cellmap.size_original();
92    let (w, h) = (v.v1(), v.v2());
93    let (tex_w, tex_h) = if w > 0.0 && h > 0.0 { (w, h) } else { (size_w, size_h) };
94    Some(ResolvedCellMeta { pivot_x, pivot_y, size_w, size_h, rect_left, rect_top, tex_w, tex_h, rotated: cell.rotated(), texture_hash: cellmap.name_hash() })
95}
96
97/// Pre-decoded skinned mesh bind-pose data for a single part.
98///
99/// Built once per part at SSAB load time from `PartData.mesh_binding()` (AoS
100/// in the FlatBuffer), and shared by that part's `CachedPartData` in every
101/// animation: the binding belongs to the part, not to an animation. CSR layout for influence
102/// offsets + SoA for weights / bind coords so the per-frame skinning pass
103/// (`compute_skinned_mesh_vertices`) can stream the data SIMD-friendly.
104///
105/// Bone indices are part-resolved: ssconverter has already mapped each
106/// `TableIDPartsBone` slot to its owning part index, so the runtime can
107/// directly index `bone_world_matrices[bone_indices[i]]`.
108#[derive(Clone, Default)]
109pub struct MeshBindingCache {
110    pub influence_offsets: alloc::vec::Vec<u32>,
111    pub bone_indices: alloc::vec::Vec<u16>,
112    pub weights: alloc::vec::Vec<f32>,
113    pub coords_x: alloc::vec::Vec<f32>,
114    pub coords_y: alloc::vec::Vec<f32>,
115}
116
117impl MeshBindingCache {
118    #[inline]
119    pub fn num_vertices(&self) -> usize {
120        self.influence_offsets.len().saturating_sub(1)
121    }
122}
123
124/// Builds a [`MeshBindingCache`] from the SSAB-side `PartMeshBinding` table.
125/// Returns `None` when the part has no mesh binding or the offset vector is
126/// empty.
127pub fn build_mesh_binding_cache(mesh_binding: Option<ssab::ssab::ss::format::PartMeshBinding<'_>>) -> Option<MeshBindingCache> {
128    let binding = mesh_binding?;
129    let offsets = binding.vertex_influence_offset()?;
130    if offsets.len() < 2 {
131        return None;
132    }
133    let bones = binding.influence_bone()?;
134    let weights = binding.influence_weight()?;
135    let coords_x = binding.influence_coord_x()?;
136    let coords_y = binding.influence_coord_y()?;
137
138    Some(MeshBindingCache { influence_offsets: offsets.iter().collect(), bone_indices: bones.iter().collect(), weights: weights.iter().collect(), coords_x: coords_x.iter().collect(), coords_y: coords_y.iter().collect() })
139}
140
141/// Per-part static mesh geometry resolved from the part's Cell.
142///
143/// Mesh parts may not change their cell after frame 0 (SS spec), so this is
144/// resolved once per cell at SSAB load time and shared by every part and
145/// animation that draws that cell. `uvs` are interleaved `[u, v, ...]` in
146/// cellmap texture-pixel space (the cell rectangle origin is already added —
147/// divide by the texture size to normalize). `rest_x` / `rest_y` are SoA
148/// rest-pose positions (cell coordinate minus the cell pivot's pixel
149/// position, so the mesh is centred; Y-down native — same texture-pixel
150/// space as `uvs`), consumed by the non-skeletal (Deform-only) mesh path.
151/// SoA so the per-frame `W · rest` transform vectorizes with contiguous
152/// loads. `indices` are triangle indices widened from the SSAB-side `u16`
153/// `table_index_vertex`.
154#[derive(Clone, Default)]
155pub struct MeshCellData {
156    pub uvs: alloc::vec::Vec<f32>,
157    pub rest_x: alloc::vec::Vec<f32>,
158    pub rest_y: alloc::vec::Vec<f32>,
159    pub indices: alloc::vec::Vec<i32>,
160}
161
162impl MeshCellData {
163    #[inline]
164    pub fn num_vertices(&self) -> usize {
165        self.uvs.len() / 2
166    }
167}
168
169/// Per-frame mesh deform for one part, retained from Phase 1's `evaluate_deform`
170/// so the Phase 2 mesh-vertex pass can consume it. `indices` selects which mesh
171/// vertices are deformed; `dx`/`dy` are the matching SoA deltas in part-local
172/// space (Y-down flip already applied). All three empty when the part has no
173/// deform this frame.
174#[derive(Clone, Default)]
175pub struct PartDeformFrame {
176    pub indices: alloc::vec::Vec<i16>,
177    pub dx: alloc::vec::Vec<f32>,
178    pub dy: alloc::vec::Vec<f32>,
179}
180
181impl PartDeformFrame {
182    #[inline]
183    pub fn clear(&mut self) {
184        self.indices.clear();
185        self.dx.clear();
186        self.dy.clear();
187    }
188}
189
190#[derive(Default, Copy, Clone)]
191pub struct RawVertexDeform {
192    pub present: bool,
193    pub dx: [f32; 4],
194    pub dy: [f32; 4],
195}
196
197/// One part's entry in a per-part deform work area (`RawVertexDeform`,
198/// `PartDeformFrame`): nothing until the part first carries a deform, then a
199/// box that stays allocated and is cleared every frame. Most parts never
200/// deform, so they cost a pointer rather than the whole entry.
201pub type DeformSlot<T> = Option<alloc::boxed::Box<T>>;
202
203/// Part `i`'s vertex deform this frame, if it has one.
204#[inline]
205pub fn vertex_deform_at(raw_vertex_deform: &[DeformSlot<RawVertexDeform>], i: usize) -> Option<&RawVertexDeform> {
206    raw_vertex_deform.get(i).and_then(|d| d.as_deref()).filter(|d| d.present)
207}
208
209/// A mesh part's Cell, as an index for [`KeyColumns::cell`] — fixed at frame 0
210/// per the SS mesh spec, so the first cell keyframe is authoritative. `None`
211/// when the part has no cell keys.
212pub fn mesh_part_cell(keys: &KeyColumns<'_>, cell_keys: Option<KeyRun>) -> Option<u32> {
213    let cell_keys = cell_keys?;
214    if cell_keys.count() == 0 {
215        return None;
216    }
217    Some(keys.key(cell_keys.first() as usize).cell())
218}
219
220/// Extracts a mesh cell's triangulated geometry. Returns `None` when the cell
221/// cannot be resolved or carries no mesh tables (i.e. it is not a mesh cell).
222pub fn build_mesh_cell_data(ssab: &ssab::ssab::ss::format::SsAnimeBinary<'_>, value: &runtime::framedata::ss::runtime::PartAttributeCell) -> Option<MeshCellData> {
223    let cellmaps = ssab.cellmaps()?;
224    let cellmap = crate::eval::ssab_lookup::find_cellmap(&cellmaps, value.cellmap_name_hash())?;
225    let cells = cellmap.cells()?;
226    let cell = crate::eval::ssab_lookup::find_cell(&cells, value.name_hash())?;
227
228    let coord_x = cell.table_coord_x()?;
229    let coord_y = cell.table_coord_y()?;
230    let tri = cell.table_index_vertex()?;
231    if coord_x.is_empty() || coord_y.is_empty() || tri.is_empty() {
232        return None;
233    }
234    let n = coord_x.len().min(coord_y.len());
235
236    // Cell-local mesh coordinates are pixel offsets within the cell. For UVs
237    // add the cell rectangle origin (→ cellmap texture-pixel space); for rest
238    // positions subtract the cell pivot so the mesh sits centred on the part
239    // origin. `table_coord_x` / `table_coord_y` are the `.ssce` meshPointList
240    // verbatim, i.e. texture-pixel space (Y-down native); the Deform-only mesh
241    // path flips it only for a Y-up target. `cell.pivot()` is normalized
242    // (offset from the cell centre, 0 = centre) and Y-up; convert to a Y-down
243    // texture-pixel position via `(pivot.x + 0.5) * size_w` and
244    // `(-pivot.y + 0.5) * size_h` — the Y pivot is negated to mirror
245    // compute_local_vertices (`cpy`) so it matches the Y-down coordinates.
246    let r = cell.region();
247    let (rect_left, rect_top, size_w, size_h) = (r.x(), r.y(), r.w(), r.h());
248    let p = cell.pivot();
249    let (pivot_norm_x, pivot_norm_y) = (p.v1(), p.v2());
250    let pivot_px_x = (pivot_norm_x + 0.5) * size_w;
251    let pivot_px_y = (-pivot_norm_y + 0.5) * size_h;
252    let mut uvs = alloc::vec::Vec::with_capacity(n * 2);
253    let mut rest_x = alloc::vec::Vec::with_capacity(n);
254    let mut rest_y = alloc::vec::Vec::with_capacity(n);
255    for i in 0..n {
256        let x = coord_x.get(i);
257        let y = coord_y.get(i);
258        uvs.push(x + rect_left);
259        uvs.push(y + rect_top);
260        rest_x.push(x - pivot_px_x);
261        rest_y.push(y - pivot_px_y);
262    }
263    let indices: alloc::vec::Vec<i32> = tri.iter().map(|i| i as i32).collect();
264
265    Some(MeshCellData { uvs, indices, rest_x, rest_y })
266}
267
268/// Per-part static Nine-Slice authoring, read once from `PartTypeNines`.
269/// Margins are `(left, top, right, bottom)` in source-cell pixels.
270#[derive(Clone, Copy)]
271pub struct NinesPartData {
272    pub margins: (f32, f32, f32, f32),
273    pub fill_mode: crate::eval::geometry::NinesFillMode,
274}
275
276/// Builds a [`NinesPartData`] from the SSAB-side `PartTypeNines` table.
277/// Returns `None` for every other part type.
278pub fn build_nines_part_data(part_meta: &ssab::ssab::ss::format::PartData<'_>) -> Option<NinesPartData> {
279    let n = part_meta.part_type_as_part_type_nines()?;
280    Some(NinesPartData { margins: (n.nines_margin_l() as f32, n.nines_margin_t() as f32, n.nines_margin_r() as f32, n.nines_margin_b() as f32), fill_mode: crate::eval::geometry::NinesFillMode::from_i32(n.nines_fill_mode()) })
281}
282
283/// Per-part Nine-Slice geometry for the current frame, concatenated across
284/// parts in CSR layout. Non-nines parts occupy an empty range.
285///
286/// `vertices` / `box_coords` / `uvs` are interleaved pairs sliced by
287/// `vertex_offsets`; `indices` is sliced by `index_offsets` and its values are
288/// local to each part's vertex range.
289#[derive(Default)]
290pub struct NinesBuffers {
291    pub vertices: alloc::vec::Vec<f32>,
292    pub uvs: alloc::vec::Vec<f32>,
293    pub box_coords: alloc::vec::Vec<f32>,
294    pub indices: alloc::vec::Vec<i32>,
295    pub vertex_offsets: alloc::vec::Vec<u32>,
296    pub index_offsets: alloc::vec::Vec<u32>,
297}
298
299impl NinesBuffers {
300    fn begin(&mut self, num_parts: usize) {
301        self.vertices.clear();
302        self.uvs.clear();
303        self.box_coords.clear();
304        self.indices.clear();
305        self.vertex_offsets.clear();
306        self.vertex_offsets.reserve(num_parts + 1);
307        self.index_offsets.clear();
308        self.index_offsets.reserve(num_parts + 1);
309    }
310
311    /// Vertex / index count of part `i`, `(0, 0)` for parts without geometry.
312    #[inline]
313    pub fn counts(&self, i: usize) -> (u32, u32) {
314        let span = |o: &[u32]| match (o.get(i), o.get(i + 1)) {
315            (Some(start), Some(end)) => end.saturating_sub(*start),
316            _ => 0,
317        };
318        (span(&self.vertex_offsets), span(&self.index_offsets))
319    }
320}
321
322#[derive(Clone)]
323pub struct CachedPartData {
324    pub part_index: i16,
325    pub parent_index: i16,
326    /// Which continuous attributes (`MIXED_ATTRIBUTES`) this animation actually
327    /// keys on this part. Decided **per animation** (the run exists at all),
328    /// never per frame — a per-frame signal would flip at the first key and
329    /// make the part pop in and out of the mix mid-playback.
330    ///
331    /// The mix consults this to keep a source that does not animate an
332    /// attribute from voting `evaluate_part`'s hardcoded default into the
333    /// weighted sum. Note the converter seeds every animation with the setup
334    /// pose, so "has a run" means "authored by the animator **or** by the
335    /// setup pose" — both are real poses, and only the genuinely absent case
336    /// is excluded.
337    pub coverage: crate::runtime::framedata::ss::runtime::UpdateAttributeFlags,
338    /// `fnv1a_hash_str(PartData.name)`, cached for the Override Layer's
339    /// `name -> part_index` resolver. Stable within an SSAB (part identity is
340    /// AnimationPack-scoped and 1:1 with `parts_animation_data`).
341    pub name_hash: u32,
342    /// One bit per attribute this part has keys for, at the attribute's
343    /// `IDX_ATTRIBUTE*` position. An instance keeps a key cursor for each of
344    /// these attributes only, in bit order (see [`cursor_slot`]).
345    pub key_mask: u64,
346    /// Where this part's key cursors start in an instance's cursor buffer:
347    /// the number of cursors every earlier part of the animation keeps.
348    pub cursor_base: u32,
349    /// The keyed attributes that read the same on every frame of the
350    /// animation — a run of one key, which the animation reaches at its start
351    /// — as [`key_mask`](Self::key_mask) bits. They are evaluated once, into
352    /// the animation's part bases, rather than on every frame.
353    pub constant_mask: u64,
354    pub shape_kind: Option<crate::eval::geometry::ShapeType>,
355    pub nines: Option<NinesPartData>,
356    pub mesh_binding: Option<alloc::sync::Arc<MeshBindingCache>>,
357    pub mesh_cell: Option<alloc::sync::Arc<MeshCellData>>,
358
359    // Batch-key metadata: read once from the SSAB `PartData` at setup, used by the
360    // per-frame `DrawBatch` pass.
361    pub blend_type: ssab::ssab::ss::format::BlendType,
362    pub part_type_disc: ssab::ssab::ss::format::PartType,
363    pub mask_influence: bool,
364    pub is_mask_contributor: bool,
365    /// The key runs of the attributes in [`key_mask`](Self::key_mask), in bit
366    /// order: attribute `idx` is `runs[cursor_slot(key_mask, idx)]`, the same
367    /// packing as an instance's cursors. A part keys a handful of its
368    /// attributes, so this holds a few runs. Read one with [`run`](Self::run).
369    pub runs: alloc::boxed::Box<[KeyRun]>,
370}
371
372/// The weighted (continuous) attributes, the ones the mix blends: discrete ones
373/// come from the primary and never take part in a weighted sum. A part's
374/// [`coverage`](CachedPartData::coverage) is the ones of these it keys.
375///
376/// `skew_x` / `skew_y` share one key run and therefore one flag, matching how
377/// `evaluate_part` sets `AttributeSkew`.
378pub(crate) const MIXED_ATTRIBUTES: crate::runtime::framedata::ss::runtime::UpdateAttributeFlags = {
379    use crate::runtime::framedata::ss::runtime::UpdateAttributeFlags as F;
380    F::AttributePosX
381        .union(F::AttributePosY)
382        .union(F::AttributePosZ)
383        .union(F::AttributeRotX)
384        .union(F::AttributeRotY)
385        .union(F::AttributeRotZ)
386        .union(F::AttributeSclX)
387        .union(F::AttributeSclY)
388        .union(F::AttributeLosclX)
389        .union(F::AttributeLosclY)
390        .union(F::AttributeAlpha)
391        .union(F::AttributeLoAlpha)
392        .union(F::AttributePivotX)
393        .union(F::AttributePivotY)
394        .union(F::AttributeAnchorX)
395        .union(F::AttributeAnchorY)
396        .union(F::AttributeSizeX)
397        .union(F::AttributeSizeY)
398        .union(F::AttributeUvtX)
399        .union(F::AttributeUvtY)
400        .union(F::AttributeUvrZ)
401        .union(F::AttributeUvsX)
402        .union(F::AttributeUvsY)
403        .union(F::AttributeBoundr)
404        .union(F::AttributeMask)
405        .union(F::AttributeSkew)
406};
407
408impl CachedPartData {
409    #[allow(clippy::too_many_arguments)]
410    pub fn new(
411        part: ssab::ssab::ss::format::PartAnimationData<'_>,
412        keys: &KeyColumns,
413        part_index: i16,
414        parent_index: i16,
415        name_hash: u32,
416        shape_kind: Option<crate::eval::geometry::ShapeType>,
417        nines: Option<NinesPartData>,
418        mesh_binding: Option<alloc::sync::Arc<MeshBindingCache>>,
419        mesh_cell: Option<alloc::sync::Arc<MeshCellData>>,
420        blend_type: ssab::ssab::ss::format::BlendType,
421        part_type_disc: ssab::ssab::ss::format::PartType,
422        mask_influence: bool,
423        is_mask_contributor: bool,
424        start_frame: i32,
425    ) -> Self {
426        let all: [(Option<KeyRun>, usize); NUM_PART_ATTRIBUTES] = [
427            (keys.run(part.cell_keys()), IDX_ATTRIBUTECELL),
428            (keys.run(part.position_x_keys()), IDX_ATTRIBUTEPOSX),
429            (keys.run(part.position_y_keys()), IDX_ATTRIBUTEPOSY),
430            (keys.run(part.position_z_keys()), IDX_ATTRIBUTEPOSZ),
431            (keys.run(part.rotation_x_keys()), IDX_ATTRIBUTEROTX),
432            (keys.run(part.rotation_y_keys()), IDX_ATTRIBUTEROTY),
433            (keys.run(part.rotation_z_keys()), IDX_ATTRIBUTEROTZ),
434            (keys.run(part.scale_x_keys()), IDX_ATTRIBUTESCLX),
435            (keys.run(part.scale_y_keys()), IDX_ATTRIBUTESCLY),
436            (keys.run(part.local_scale_x_keys()), IDX_ATTRIBUTELOSCLX),
437            (keys.run(part.local_scale_y_keys()), IDX_ATTRIBUTELOSCLY),
438            (keys.run(part.alpha_keys()), IDX_ATTRIBUTEALPHA),
439            (keys.run(part.local_alpha_keys()), IDX_ATTRIBUTELOALPHA),
440            (keys.run(part.priority_keys()), IDX_ATTRIBUTEPRIO),
441            (keys.run(part.flip_h_keys()), IDX_ATTRIBUTEFLIPH),
442            (keys.run(part.flip_v_keys()), IDX_ATTRIBUTEFLIPV),
443            (keys.run(part.hide_keys()), IDX_ATTRIBUTEHIDE),
444            (keys.run(part.part_color_keys()), IDX_ATTRIBUTEPARTCOLOR),
445            (keys.run(part.shader_keys()), IDX_ATTRIBUTESHADER),
446            (keys.run(part.vertex_keys()), IDX_ATTRIBUTEVERTEX),
447            (keys.run(part.pivot_x_keys()), IDX_ATTRIBUTEPIVOTX),
448            (keys.run(part.pivot_y_keys()), IDX_ATTRIBUTEPIVOTY),
449            (keys.run(part.anchor_x_keys()), IDX_ATTRIBUTEANCHORX),
450            (keys.run(part.anchor_y_keys()), IDX_ATTRIBUTEANCHORY),
451            (keys.run(part.size_x_keys()), IDX_ATTRIBUTESIZEX),
452            (keys.run(part.size_y_keys()), IDX_ATTRIBUTESIZEY),
453            (keys.run(part.img_flip_h_keys()), IDX_ATTRIBUTEIMGFLIPH),
454            (keys.run(part.img_flip_v_keys()), IDX_ATTRIBUTEIMGFLIPV),
455            (keys.run(part.uv_translation_x_keys()), IDX_ATTRIBUTEUVTX),
456            (keys.run(part.uv_translation_y_keys()), IDX_ATTRIBUTEUVTY),
457            (keys.run(part.uv_rotation_z_keys()), IDX_ATTRIBUTEUVRZ),
458            (keys.run(part.uv_scale_x_keys()), IDX_ATTRIBUTEUVSX),
459            (keys.run(part.uv_scale_y_keys()), IDX_ATTRIBUTEUVSY),
460            (keys.run(part.bounding_radius_keys()), IDX_ATTRIBUTEBOUNDR),
461            (keys.run(part.mask_keys()), IDX_ATTRIBUTEMASK),
462            (keys.run(part.skew_keys()), IDX_ATTRIBUTESKEW),
463            (keys.run(part.deform_keys()), IDX_ATTRIBUTEDEFORM),
464            (keys.run(part.texture_keys()), IDX_ATTRIBUTETEXTURE),
465        ];
466        // `all` lists the attributes in bit order, so the keyed runs gather
467        // straight into `key_mask` order, in one allocation of their exact
468        // size. This runs for every part of every animation set up.
469        debug_assert!(all.iter().enumerate().all(|(bit, (_, idx))| bit == *idx));
470        let key_mask = all.iter().filter(|(run, _)| run.is_some()).fold(0u64, |mask, (_, idx)| mask | 1 << idx);
471        let mut runs = alloc::vec::Vec::with_capacity(key_mask.count_ones() as usize);
472        runs.extend(all.iter().filter_map(|(run, _)| *run));
473        let mut cached = Self {
474            part_index,
475            parent_index,
476            name_hash,
477            key_mask,
478            runs: runs.into_boxed_slice(),
479            cursor_base: 0,
480            constant_mask: 0,
481            coverage: crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::from_bits_retain(key_mask) & MIXED_ATTRIBUTES,
482            shape_kind,
483            nines,
484            mesh_binding,
485            mesh_cell,
486            blend_type,
487            part_type_disc,
488            mask_influence,
489            is_mask_contributor,
490        };
491        cached.constant_mask = cached.constant_attributes(keys, start_frame);
492        cached
493    }
494
495    /// The attributes whose value is the same on every frame of an animation
496    /// starting at `start_frame`, as [`constant_mask`](Self::constant_mask) bits:
497    /// a run of one key. A float-like run reads its key on every frame. A
498    /// bool, cell or texture run reads nothing before its key, so it counts
499    /// only when the key sits at or before the start. Deform is left out: its
500    /// result lives in per-frame workspaces, not in the part state.
501    fn constant_attributes(&self, keys: &KeyColumns, start_frame: i32) -> u64 {
502        const READS_NOTHING_BEFORE_ITS_KEY: [usize; 7] = [IDX_ATTRIBUTECELL, IDX_ATTRIBUTEFLIPH, IDX_ATTRIBUTEFLIPV, IDX_ATTRIBUTEHIDE, IDX_ATTRIBUTEIMGFLIPH, IDX_ATTRIBUTEIMGFLIPV, IDX_ATTRIBUTETEXTURE];
503        let mut mask = 0;
504        for (idx, run) in self.keyed_runs() {
505            if run.count() != 1 || idx == IDX_ATTRIBUTEDEFORM {
506                continue;
507            }
508            if READS_NOTHING_BEFORE_ITS_KEY.contains(&idx) && keys.key(run.first() as usize).index() as i32 > start_frame {
509                continue;
510            }
511            mask |= 1 << idx;
512        }
513        mask
514    }
515
516    /// The keyed attributes' `IDX_ATTRIBUTE*` positions with their runs, in bit order.
517    fn keyed_runs(&self) -> impl Iterator<Item = (usize, KeyRun)> + '_ {
518        let mut bits = self.key_mask;
519        self.runs.iter().map(move |run| {
520            let idx = bits.trailing_zeros() as usize;
521            bits &= bits - 1;
522            (idx, *run)
523        })
524    }
525
526    /// This part's key run for attribute `idx` (an `IDX_ATTRIBUTE*`), or `None`
527    /// when the part has no keys for it.
528    #[inline]
529    pub fn run(&self, idx: usize) -> Option<KeyRun> {
530        (self.key_mask >> idx & 1 == 1).then(|| self.runs[cursor_slot(self.key_mask, idx)])
531    }
532
533    /// This part's key cursors within an instance's cursor buffer.
534    #[inline]
535    pub fn cursors<'c>(&self, all: &'c mut [u32]) -> &'c mut [u32] {
536        let base = self.cursor_base as usize;
537        &mut all[base..base + self.key_mask.count_ones() as usize]
538    }
539}
540
541/// Where attribute `idx`'s cursor sits among a part's cursors: the part keeps
542/// one for each attribute in its `key_mask`, in bit order.
543#[inline]
544pub fn cursor_slot(key_mask: u64, idx: usize) -> usize {
545    (key_mask & ((1u64 << idx) - 1)).count_ones() as usize
546}
547
548/// How many key cursors an instance needs to play an animation with
549/// `cached_parts`, whose `cursor_base`s run up to it.
550pub fn cursor_count(cached_parts: &[CachedPartData]) -> usize {
551    cached_parts.last().map_or(0, |p| p.cursor_base as usize + p.key_mask.count_ones() as usize)
552}
553
554/// Test-only stub of a [`CachedPartData`] with no keyframe tracks, for unit
555/// tests that exercise per-part logic (e.g. the Override Layer) without loading
556/// a real SSAB. Only the fields those tests read are parameterized.
557#[cfg(test)]
558pub(crate) fn cached_part_stub(part_index: i16, parent_index: i16, part_type_disc: ssab::ssab::ss::format::PartType, is_mask_contributor: bool) -> CachedPartData {
559    CachedPartData {
560        part_index,
561        parent_index,
562        name_hash: 0,
563        key_mask: 0,
564        cursor_base: 0,
565        constant_mask: 0,
566        // The stub has no keyframe tracks at all, but callers use it to exercise
567        // per-part logic rather than the mix; claiming full coverage keeps it from
568        // silently disabling attributes if one of them ever runs a blend.
569        coverage: crate::runtime::framedata::ss::runtime::UpdateAttributeFlags::all(),
570        shape_kind: None,
571        nines: None,
572        mesh_binding: None,
573        mesh_cell: None,
574        blend_type: ssab::ssab::ss::format::BlendType::Mix,
575        part_type_disc,
576        mask_influence: false,
577        is_mask_contributor,
578        runs: alloc::boxed::Box::new([]),
579    }
580}
581
582pub struct PartEvaluationResult {
583    pub state: runtime::framedata::ss::runtime::PartState,
584    /// The cell the part shows, as an index for [`KeyColumns::cell`].
585    pub cell: Option<u32>,
586    pub part_color: Option<crate::runtime::framedata::ss::runtime::PartAttributePartColor>,
587    pub shader: Option<crate::runtime::framedata::ss::runtime::PartAttributeShader>,
588    pub vertex: Option<crate::runtime::framedata::ss::runtime::PartAttributeVertex>,
589    /// Set when `evaluate_deform` produced a key. Coordinates / indices
590    /// live in the caller-owned workspaces — they are valid until the
591    /// next `evaluate_part` overwrites them, so the caller must consume
592    /// them within the same loop iteration.
593    pub deform_present: bool,
594}
595
596/// A float attribute other than position X / Y, which also take the root
597/// part's origin offset and unit normalization ([`place`]). `evaluate_part`
598/// writes a key's value with `set`, and `setup_pose_part` writes the setup value
599/// it reads with `setup` the same way: one table, so the setup pose lands in the
600/// space the keyed pose does.
601struct FloatAttribute {
602    idx: usize,
603    set: fn(&mut runtime::framedata::ss::runtime::PartState, f32),
604    setup: fn(&ssab::ssab::ss::format::InitialPartAttributes<'_>) -> f32,
605    /// Negated for a Y-down target.
606    flips: bool,
607}
608
609const FLOAT_ATTRIBUTES: [FloatAttribute; 23] = {
610    use runtime::framedata::ss::runtime::PartState as S;
611    [
612        FloatAttribute { idx: IDX_ATTRIBUTEPOSZ, set: S::set_position_z, setup: |a| a.position_z(), flips: false },
613        FloatAttribute { idx: IDX_ATTRIBUTEROTX, set: S::set_rotation_x, setup: |a| a.rotation_x(), flips: true },
614        FloatAttribute { idx: IDX_ATTRIBUTEROTY, set: S::set_rotation_y, setup: |a| a.rotation_y(), flips: false },
615        FloatAttribute { idx: IDX_ATTRIBUTEROTZ, set: S::set_rotation_z, setup: |a| a.rotation_z(), flips: true },
616        FloatAttribute { idx: IDX_ATTRIBUTESCLX, set: S::set_scale_x, setup: |a| a.scale_x(), flips: false },
617        FloatAttribute { idx: IDX_ATTRIBUTESCLY, set: S::set_scale_y, setup: |a| a.scale_y(), flips: false },
618        FloatAttribute { idx: IDX_ATTRIBUTELOSCLX, set: S::set_local_scale_x, setup: |a| a.local_scale_x(), flips: false },
619        FloatAttribute { idx: IDX_ATTRIBUTELOSCLY, set: S::set_local_scale_y, setup: |a| a.local_scale_y(), flips: false },
620        FloatAttribute { idx: IDX_ATTRIBUTEALPHA, set: S::set_alpha, setup: |a| a.alpha(), flips: false },
621        FloatAttribute { idx: IDX_ATTRIBUTELOALPHA, set: S::set_local_alpha, setup: |a| a.local_alpha(), flips: false },
622        FloatAttribute { idx: IDX_ATTRIBUTEPIVOTX, set: S::set_pivot_x, setup: |a| a.pivot_x(), flips: false },
623        FloatAttribute { idx: IDX_ATTRIBUTEPIVOTY, set: S::set_pivot_y, setup: |a| a.pivot_y(), flips: true },
624        FloatAttribute { idx: IDX_ATTRIBUTEANCHORX, set: S::set_anchor_x, setup: |a| a.anchor_x(), flips: false },
625        FloatAttribute { idx: IDX_ATTRIBUTEANCHORY, set: S::set_anchor_y, setup: |a| a.anchor_y(), flips: true },
626        FloatAttribute { idx: IDX_ATTRIBUTESIZEX, set: S::set_size_x, setup: |a| a.size_x(), flips: false },
627        FloatAttribute { idx: IDX_ATTRIBUTESIZEY, set: S::set_size_y, setup: |a| a.size_y(), flips: false },
628        FloatAttribute { idx: IDX_ATTRIBUTEUVTX, set: S::set_uv_translation_x, setup: |a| a.uv_translation_x(), flips: false },
629        FloatAttribute { idx: IDX_ATTRIBUTEUVTY, set: S::set_uv_translation_y, setup: |a| a.uv_translation_y(), flips: false },
630        FloatAttribute { idx: IDX_ATTRIBUTEUVRZ, set: S::set_uv_rotation_z, setup: |a| a.uv_rotation_z(), flips: false },
631        FloatAttribute { idx: IDX_ATTRIBUTEUVSX, set: S::set_uv_scale_x, setup: |a| a.uv_scale_x(), flips: false },
632        FloatAttribute { idx: IDX_ATTRIBUTEUVSY, set: S::set_uv_scale_y, setup: |a| a.uv_scale_y(), flips: false },
633        FloatAttribute { idx: IDX_ATTRIBUTEBOUNDR, set: S::set_bounding_radius, setup: |a| a.bounding_radius(), flips: false },
634        FloatAttribute { idx: IDX_ATTRIBUTEMASK, set: S::set_mask, setup: |a| a.mask(), flips: false },
635    ]
636};
637
638/// A bool attribute, and how `evaluate_part` writes its key.
639struct BoolAttribute {
640    idx: usize,
641    set: fn(&mut runtime::framedata::ss::runtime::PartState, bool),
642}
643
644const BOOL_ATTRIBUTES: [BoolAttribute; 5] = {
645    use runtime::framedata::ss::runtime::PartState as S;
646    [
647        BoolAttribute { idx: IDX_ATTRIBUTEFLIPH, set: S::set_flip_h },
648        BoolAttribute { idx: IDX_ATTRIBUTEFLIPV, set: S::set_flip_v },
649        BoolAttribute { idx: IDX_ATTRIBUTEHIDE, set: S::set_hide },
650        BoolAttribute { idx: IDX_ATTRIBUTEIMGFLIPH, set: S::set_img_flip_h },
651        BoolAttribute { idx: IDX_ATTRIBUTEIMGFLIPV, set: S::set_img_flip_v },
652    ]
653};
654
655/// A part's position in the target's space: a root part moved by the origin
656/// offset, then both axes normalized when the unit asks for it. `y` comes in
657/// already negated for a Y-down target.
658#[allow(clippy::too_many_arguments)]
659fn place(mut x: f32, mut y: f32, parent_index: i16, coordinate_system: SsCoordinateSystem, origin: SsOrigin, unit: SsUnit, canvas_width: f32, canvas_height: f32) -> (f32, f32) {
660    if origin == SsOrigin::TopLeft && parent_index == -1 {
661        x += canvas_width / 2.0;
662        if coordinate_system == SsCoordinateSystem::YDown {
663            y += canvas_height / 2.0;
664        } else {
665            y -= canvas_height / 2.0;
666        }
667    }
668    if unit == SsUnit::Normalized && canvas_width != 0.0 && canvas_height != 0.0 {
669        x /= canvas_width;
670        y /= canvas_height;
671    }
672    (x, y)
673}
674
675/// The setup pose of one part, in the same space `evaluate_part` produces, or
676/// the stack's floor lands in a different space than the poses folded onto it
677/// (a track at `alpha < 1` would then drift toward a mis-transformed rest
678/// pose). Both go through [`place`] and [`FLOAT_ATTRIBUTES`]; skew, the one
679/// other attribute the mix blends, is written raw by both.
680#[allow(clippy::too_many_arguments)]
681pub(crate) fn setup_pose_part(
682    a: &ssab::ssab::ss::format::InitialPartAttributes<'_>,
683    parent_index: i16,
684    coordinate_system: SsCoordinateSystem,
685    origin: SsOrigin,
686    unit: SsUnit,
687    canvas_width: f32,
688    canvas_height: f32,
689) -> runtime::framedata::ss::runtime::PartState {
690    let mut s = runtime::framedata::ss::runtime::PartState::default();
691    let y_down = coordinate_system == SsCoordinateSystem::YDown;
692
693    let (pos_x, pos_y) = place(a.position_x(), if y_down { -a.position_y() } else { a.position_y() }, parent_index, coordinate_system, origin, unit, canvas_width, canvas_height);
694    s.set_position_x(pos_x);
695    s.set_position_y(pos_y);
696    for f in &FLOAT_ATTRIBUTES {
697        let value = (f.setup)(a);
698        (f.set)(&mut s, if f.flips && y_down { -value } else { value });
699    }
700    s.set_skew_x(a.skew_x());
701    s.set_skew_y(a.skew_y());
702    s
703}
704
705/// A part's state before any key is applied: the defaults `evaluate_part`
706/// starts from when it builds a part base.
707fn default_part_evaluation(cached_part: &CachedPartData) -> (runtime::framedata::ss::runtime::PartState, PartEvaluationResult) {
708    let mut part_state = runtime::framedata::ss::runtime::PartState::default();
709
710    part_state.set_alpha(1.0);
711    part_state.set_local_alpha(1.0);
712    part_state.set_scale_x(1.0);
713    part_state.set_scale_y(1.0);
714    part_state.set_local_scale_x(1.0);
715    part_state.set_local_scale_y(1.0);
716    part_state.set_size_x(1.0);
717    part_state.set_size_y(1.0);
718    part_state.set_uv_scale_x(1.0);
719    part_state.set_uv_scale_y(1.0);
720    part_state.set_cell(-1);
721    part_state.set_part_color(-1);
722    part_state.set_shader(-1);
723    part_state.set_vertex(-1);
724    part_state.set_deform(-1);
725    // A part with no Hide keys at all is rendered as hidden by default; a Hide
726    // run overrides it in `evaluate_part`. This is the standard SS authoring
727    // model: a part has to opt in to being shown with a Hide=false key.
728    part_state.set_hide(true);
729
730    let result = PartEvaluationResult { state: runtime::framedata::ss::runtime::PartState::default(), cell: None, part_color: None, shader: None, vertex: None, deform_present: false };
731
732    part_state.set_part_index(cached_part.part_index);
733    (part_state, result)
734}
735
736#[allow(clippy::too_many_arguments)]
737pub(crate) fn evaluate_part(
738    cached_part: &CachedPartData,
739    keys: &KeyColumns,
740    frame_no: f32,
741    part_cursors: &mut [u32],
742    base: Option<PartBaseRef>,
743    evaluate: u64,
744    coordinate_system: SsCoordinateSystem,
745    origin: SsOrigin,
746    unit: SsUnit,
747    canvas_width: f32,
748    canvas_height: f32,
749    start_workspace: &mut Vec<f32>,
750    end_workspace: &mut Vec<f32>,
751    out_workspace: &mut Vec<f32>,
752    deform_coord_workspace: &mut Vec<runtime::framedata::ss::runtime::Vec2>,
753    deform_index_workspace: &mut Vec<i16>,
754) -> PartEvaluationResult {
755    use runtime::framedata::ss::runtime::UpdateAttributeFlags as F;
756    // `evaluate` picks the attributes to evaluate here: every keyed one when
757    // building a part base, the ones that change during the animation when
758    // starting from one.
759    let on = |idx: usize| evaluate & (1u64 << idx) != 0;
760    let from_base = base.is_some();
761    let (mut part_state, mut update_flag, mut result) = match base {
762        Some(base) => {
763            let result = base.result();
764            // Most parts change nothing during an animation: the base is the answer.
765            if evaluate == 0 {
766                return result;
767            }
768            (result.state, result.state.update_flag(), result)
769        }
770        None => {
771            let (state, result) = default_part_evaluation(cached_part);
772            (state, F::empty(), result)
773        }
774    };
775    let y_down = coordinate_system == SsCoordinateSystem::YDown;
776
777    if let Some(cell) = evaluated(cached_part, evaluate, part_cursors, IDX_ATTRIBUTECELL).and_then(|(run, cursor)| evaluate_cell(keys, &run, frame_no, cursor)) {
778        result.cell = Some(cell);
779        update_flag |= F::AttributeCell;
780    }
781
782    let mut pos_x = 0.0;
783    if let Some(value) = evaluated(cached_part, evaluate, part_cursors, IDX_ATTRIBUTEPOSX).and_then(|(run, cursor)| evaluate_float(keys, &run, frame_no, cursor)) {
784        pos_x = value;
785        update_flag |= F::AttributePosX;
786    }
787    let mut pos_y = 0.0;
788    if let Some(value) = evaluated(cached_part, evaluate, part_cursors, IDX_ATTRIBUTEPOSY).and_then(|(run, cursor)| evaluate_float(keys, &run, frame_no, cursor)) {
789        pos_y = if y_down { -value } else { value };
790        update_flag |= F::AttributePosY;
791    }
792    let (pos_x, pos_y) = place(pos_x, pos_y, cached_part.parent_index, coordinate_system, origin, unit, canvas_width, canvas_height);
793    // From a part base, an axis that does not change keeps the base's value.
794    if !from_base || on(IDX_ATTRIBUTEPOSX) {
795        part_state.set_position_x(pos_x);
796    }
797    if !from_base || on(IDX_ATTRIBUTEPOSY) {
798        part_state.set_position_y(pos_y);
799    }
800
801    for f in &FLOAT_ATTRIBUTES {
802        if let Some(value) = evaluated(cached_part, evaluate, part_cursors, f.idx).and_then(|(run, cursor)| evaluate_float(keys, &run, frame_no, cursor)) {
803            (f.set)(&mut part_state, if f.flips && y_down { -value } else { value });
804            update_flag |= F::from_bits_retain(1 << f.idx);
805        }
806    }
807    if let Some(value) = evaluated(cached_part, evaluate, part_cursors, IDX_ATTRIBUTEPRIO).and_then(|(run, cursor)| evaluate_int(keys, &run, frame_no, cursor)) {
808        part_state.set_priority(value);
809        update_flag |= F::AttributePrio;
810    }
811    for b in &BOOL_ATTRIBUTES {
812        if let Some(value) = evaluated(cached_part, evaluate, part_cursors, b.idx).and_then(|(run, cursor)| evaluate_bool(keys, &run, frame_no, cursor)) {
813            (b.set)(&mut part_state, value);
814            update_flag |= F::from_bits_retain(1 << b.idx);
815        }
816    }
817
818    if let Some(value) = evaluated(cached_part, evaluate, part_cursors, IDX_ATTRIBUTEPARTCOLOR).and_then(|(run, cursor)| evaluate_partcolor(keys, &run, frame_no, cursor)) {
819        result.part_color = Some(value);
820        update_flag |= F::AttributePartColor;
821    }
822    if let Some(value) = evaluated(cached_part, evaluate, part_cursors, IDX_ATTRIBUTESHADER).and_then(|(run, cursor)| evaluate_shader(keys, &run, frame_no, cursor)) {
823        result.shader = Some(value);
824        update_flag |= F::AttributeShader;
825    }
826    if let Some(value) = evaluated(cached_part, evaluate, part_cursors, IDX_ATTRIBUTEVERTEX).and_then(|(run, cursor)| evaluate_vertex(keys, &run, frame_no, cursor)) {
827        // Raw deform Y is kept in the source (Y-Up) orientation here; the always-on
828        // local-vertex calc consumes it as deform offsets and the result is flipped
829        // to YDown only at the very end. The intermediate raw deform value is never
830        // exposed publicly, so flipping/unflipping it would be wasted work.
831        result.vertex = Some(value);
832        update_flag |= F::AttributeVertex;
833    }
834    if let Some((skew_x, skew_y)) = evaluated(cached_part, evaluate, part_cursors, IDX_ATTRIBUTESKEW).and_then(|(run, cursor)| evaluate_skew(keys, &run, frame_no, cursor)) {
835        // Skew is stored raw here (no coordinate-system flip). It is a
836        // Vertex-deform-mode attribute, so the Y-down conversion happens where
837        // the shear is applied to local vertices — the same authored-Y-up path
838        // the 4-corner Vertex deform takes.
839        part_state.set_skew_x(skew_x);
840        part_state.set_skew_y(skew_y);
841        update_flag |= F::AttributeSkew;
842    }
843    if let Some((run, cursor)) = evaluated(cached_part, evaluate, part_cursors, IDX_ATTRIBUTEDEFORM)
844        && evaluate_deform(keys, &run, frame_no, cursor, start_workspace, end_workspace, out_workspace, deform_coord_workspace, deform_index_workspace)
845    {
846        // Deform offsets are an ssae animation attribute — Y-up native like
847        // position / pivot / anchor — so they flip for a Y-down target, the
848        // SAME condition as those attributes. The mesh rest, by contrast,
849        // comes from the .ssce cell (`table_coord_x` / `table_coord_y`) and is
850        // Y-down native, so it flips on the opposite (YUp) condition in
851        // compute_mesh_vertices. rest and deform are deliberately mirror-imaged.
852        if y_down {
853            for v in deform_coord_workspace.iter_mut() {
854                v.set_y(-v.y());
855            }
856        }
857        result.deform_present = true;
858        update_flag |= F::AttributeDeform;
859    }
860    if let Some(value) = evaluated(cached_part, evaluate, part_cursors, IDX_ATTRIBUTETEXTURE).and_then(|(run, cursor)| evaluate_texture(keys, &run, frame_no, cursor)) {
861        part_state.set_texture(value);
862        update_flag |= F::AttributeTexture;
863    }
864
865    part_state.set_update_flag(update_flag);
866    result.state = part_state;
867    result
868}
869
870/// Attribute `idx`'s key run and cursor, when the part keys it and `evaluate`
871/// asks for it.
872#[inline]
873fn evaluated<'c>(cached_part: &CachedPartData, evaluate: u64, part_cursors: &'c mut [u32], idx: usize) -> Option<(KeyRun, &'c mut u32)> {
874    if evaluate & cached_part.key_mask & 1 << idx == 0 {
875        return None;
876    }
877    let slot = cursor_slot(cached_part.key_mask, idx);
878    Some((cached_part.runs[slot], &mut part_cursors[slot]))
879}
880
881/// Pre-multiply one PartColor corner's alpha by the part's hierarchical alpha
882/// (RGB and per-corner `rate` are preserved). Shared by keyframe decode
883/// ([`extract_pose`]) and the Override Layer so both honor one alpha contract.
884pub(crate) fn premultiply_part_color_corner(c: &crate::runtime::framedata::ss::runtime::SsAttributePartColorKeyValueColor, alpha: f32) -> crate::runtime::framedata::ss::runtime::SsAttributePartColorKeyValueColor {
885    let rgba = c.rgba();
886    let new_a = ((rgba.a() as f32 / 255.0) * alpha * 255.0).clamp(0.0, 255.0) as u8;
887    crate::runtime::framedata::ss::runtime::SsAttributePartColorKeyValueColor::new(&crate::runtime::framedata::ss::runtime::U8Color::new(new_a, rgba.r(), rgba.g(), rgba.b()), c.rate())
888}
889
890/// Every part's base for an animation under one coordinate setup: its state
891/// with the attributes that never change during the animation
892/// ([`CachedPartData::constant_mask`]) already applied. `extract_pose` starts
893/// each part from its base and evaluates only the rest.
894pub struct PartBases {
895    parts: Vec<PartBase>,
896    /// The constant part color, shader and vertex deform of the few parts that
897    /// have one, kept apart so the common part does not carry their room.
898    extras: Vec<PartBaseExtras>,
899}
900
901#[derive(Clone, Copy)]
902struct PartBase {
903    state: runtime::framedata::ss::runtime::PartState,
904    cell: Option<u32>,
905    /// Index into `PartBases::extras`, or `u32::MAX`.
906    extras: u32,
907}
908
909#[derive(Clone, Copy)]
910struct PartBaseExtras {
911    part_color: Option<runtime::framedata::ss::runtime::PartAttributePartColor>,
912    shader: Option<runtime::framedata::ss::runtime::PartAttributeShader>,
913    vertex: Option<runtime::framedata::ss::runtime::PartAttributeVertex>,
914}
915
916impl PartBases {
917    #[allow(clippy::too_many_arguments)]
918    pub fn build(cached_parts: &[CachedPartData], keys: &KeyColumns, start_frame: f32, coordinate_system: SsCoordinateSystem, origin: SsOrigin, unit: SsUnit, canvas_width: f32, canvas_height: f32) -> Self {
919        // Constant attributes never search, and deform is never constant, so these stay as they are.
920        let (mut cursors, mut start, mut end, mut out, mut coords, mut indices) = (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());
921        let mut bases = PartBases { parts: Vec::with_capacity(cached_parts.len()), extras: Vec::new() };
922        for part in cached_parts {
923            cursors.clear();
924            cursors.resize(part.key_mask.count_ones() as usize, 0);
925            let r = evaluate_part(part, keys, start_frame, &mut cursors, None, part.constant_mask, coordinate_system, origin, unit, canvas_width, canvas_height, &mut start, &mut end, &mut out, &mut coords, &mut indices);
926            let extras = if r.part_color.is_some() || r.shader.is_some() || r.vertex.is_some() {
927                bases.extras.push(PartBaseExtras { part_color: r.part_color, shader: r.shader, vertex: r.vertex });
928                bases.extras.len() as u32 - 1
929            } else {
930                u32::MAX
931            };
932            bases.parts.push(PartBase { state: r.state, cell: r.cell, extras });
933        }
934        bases
935    }
936
937    /// Part `i`'s base, for `evaluate_part` to start from.
938    pub fn get(&self, i: usize) -> Option<PartBaseRef<'_>> {
939        let base = self.parts.get(i)?;
940        Some(PartBaseRef { base, extras: self.extras.get(base.extras as usize) })
941    }
942}
943
944/// One part's base, as [`PartBases::get`] hands it to `evaluate_part`.
945#[derive(Clone, Copy)]
946pub struct PartBaseRef<'b> {
947    base: &'b PartBase,
948    extras: Option<&'b PartBaseExtras>,
949}
950
951impl PartBaseRef<'_> {
952    /// The part as its base leaves it: what `evaluate_part` returns for a part
953    /// with nothing to evaluate.
954    fn result(self) -> PartEvaluationResult {
955        let extras = self.extras;
956        PartEvaluationResult { state: self.base.state, cell: self.base.cell, part_color: extras.and_then(|e| e.part_color), shader: extras.and_then(|e| e.shader), vertex: extras.and_then(|e| e.vertex), deform_present: false }
957    }
958}
959
960#[allow(clippy::too_many_arguments)]
961pub fn extract_pose<'a>(
962    fb: &mut flatbuffers::FlatBufferBuilder<'a>,
963    cached_parts: &[CachedPartData],
964    keys: &KeyColumns<'a>,
965    frame_no: f32,
966    parts_vec: &mut Vec<runtime::framedata::ss::runtime::PartState>,
967    cell_vec: &mut Vec<crate::runtime::framedata::ss::runtime::PartAttributeCell>,
968    parts_color_vec: &mut Vec<crate::runtime::framedata::ss::runtime::PartAttributePartColor>,
969    shader_vec: &mut Vec<crate::runtime::framedata::ss::runtime::PartAttributeShader>,
970    deform_vec: &mut Vec<flatbuffers::WIPOffset<runtime::framedata::ss::runtime::PartAttributeDeform<'a>>>,
971    raw_vertex_deform: &mut [DeformSlot<RawVertexDeform>],
972    cursors: &mut Vec<u32>,
973    bases: Option<&PartBases>,
974    cell_meta_per_part: &mut [f32],
975    cell_texture_hashes: &mut [u32],
976    cell_ids: &mut Vec<Option<u32>>,
977    mesh_deform: &mut Vec<DeformSlot<PartDeformFrame>>,
978    coordinate_system: SsCoordinateSystem,
979    origin: SsOrigin,
980    unit: SsUnit,
981    canvas_width: f32,
982    canvas_height: f32,
983    start_workspace: &mut Vec<f32>,
984    end_workspace: &mut Vec<f32>,
985    out_workspace: &mut Vec<f32>,
986    deform_coord_workspace: &mut Vec<runtime::framedata::ss::runtime::Vec2>,
987    deform_index_workspace: &mut Vec<i16>,
988    inheritance_alphas_workspace: &mut Vec<f32>,
989) {
990    if mesh_deform.len() != cached_parts.len() {
991        mesh_deform.resize_with(cached_parts.len(), || None);
992    }
993    for d in mesh_deform.iter_mut().flatten() {
994        d.clear();
995    }
996    parts_vec.clear();
997    cell_vec.clear();
998    cell_ids.clear();
999    parts_color_vec.clear();
1000    shader_vec.clear();
1001    deform_vec.clear();
1002    for slot in cell_meta_per_part.iter_mut() {
1003        *slot = 0.0;
1004    }
1005    for slot in cell_texture_hashes.iter_mut() {
1006        *slot = 0;
1007    }
1008    for slot in raw_vertex_deform.iter_mut().flatten() {
1009        slot.present = false;
1010    }
1011
1012    inheritance_alphas_workspace.clear();
1013    inheritance_alphas_workspace.reserve(cached_parts.len());
1014    // Sized by `setup_animation`; a layer that last played another animation
1015    // gets a buffer of this one's size. The values are search hints, valid in
1016    // any state, so a resized buffer only costs the first frame a longer search.
1017    let cursor_len = cursor_count(cached_parts);
1018    if cursors.len() != cursor_len {
1019        cursors.clear();
1020        cursors.resize(cursor_len, 0);
1021    }
1022
1023    for (i, part) in cached_parts.iter().enumerate() {
1024        let part_cursors = part.cursors(cursors);
1025        // Start from the part's base and evaluate only what changes during the
1026        // animation; without a base, evaluate every keyed attribute. Most parts
1027        // change nothing, and for them the base is the answer without the call.
1028        let base = bases.and_then(|b| b.get(i));
1029        let evaluate = if base.is_some() { part.key_mask & !part.constant_mask } else { part.key_mask };
1030        let mut result = match base {
1031            Some(base) if evaluate == 0 => base.result(),
1032            _ => evaluate_part(part, keys, frame_no, part_cursors, base, evaluate, coordinate_system, origin, unit, canvas_width, canvas_height, start_workspace, end_workspace, out_workspace, deform_coord_workspace, deform_index_workspace),
1033        };
1034
1035        let cell = result.cell.map(|c| keys.cell(c));
1036        let cell_meta = cell.map(|c| c.meta).unwrap_or_default();
1037        let (cell_size_w, cell_size_h) = (cell_meta.size_w, cell_meta.size_h);
1038
1039        let off = i * 6;
1040        if off + 6 <= cell_meta_per_part.len() {
1041            cell_meta_per_part[off] = cell_meta.pivot_x;
1042            cell_meta_per_part[off + 1] = cell_meta.pivot_y;
1043            cell_meta_per_part[off + 2] = cell_size_w;
1044            cell_meta_per_part[off + 3] = cell_size_h;
1045            cell_meta_per_part[off + 4] = cell_meta.rect_left;
1046            cell_meta_per_part[off + 5] = cell_meta.rect_top;
1047        }
1048        if i < cell_texture_hashes.len() {
1049            cell_texture_hashes[i] = cell_meta.texture_hash;
1050        }
1051
1052        let flag = result.state.update_flag();
1053        if !flag.contains(runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeSizeX) {
1054            result.state.set_size_x(cell_size_w);
1055        }
1056        if !flag.contains(runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeSizeY) {
1057            result.state.set_size_y(cell_size_h);
1058        }
1059
1060        let parent_idx = part.parent_index;
1061        let valid_parent_idx = (parent_idx >= 0 && (parent_idx as usize) < i).then_some(parent_idx as usize);
1062
1063        let parent_inh_alpha = valid_parent_idx.and_then(|p_idx| inheritance_alphas_workspace.get(p_idx).copied()).unwrap_or(1.0);
1064
1065        let inh_alpha = result.state.alpha() * parent_inh_alpha;
1066        inheritance_alphas_workspace.push(inh_alpha);
1067
1068        let has_local_alpha = result.state.update_flag().contains(runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeLoAlpha);
1069        let effective_alpha = if has_local_alpha { result.state.local_alpha() } else { inh_alpha };
1070        result.state.set_alpha(effective_alpha);
1071
1072        // Hide is per-part at runtime: the converter bakes each part's HIDE
1073        // inheritance (`ineheritRates/HIDE`) into its own keys. The hierarchy is a
1074        // transform hierarchy, and hidden parts are routinely used as pure
1075        // transform anchors with visible children (e.g. a hidden hand part
1076        // anchoring a visible weapon). Only alpha inherits down the tree; `hide`
1077        // must not be propagated.
1078
1079        // Pre-multiply per-vertex parts color alpha with the hierarchical alpha.
1080        if let Some(pc) = result.part_color {
1081            let alpha = result.state.alpha();
1082            let blend_type = pc.blend_type();
1083            let lt = premultiply_part_color_corner(pc.lt(), alpha);
1084            let rt = premultiply_part_color_corner(pc.rt(), alpha);
1085            let lb = premultiply_part_color_corner(pc.lb(), alpha);
1086            let rb = premultiply_part_color_corner(pc.rb(), alpha);
1087
1088            result.part_color = Some(crate::runtime::framedata::ss::runtime::PartAttributePartColor::new(blend_type, &lt, &rt, &lb, &rb));
1089        }
1090
1091        if let Some(v) = result.vertex.as_ref()
1092            && i < raw_vertex_deform.len()
1093        {
1094            let lt = v.lt();
1095            let rt = v.rt();
1096            let lb = v.lb();
1097            let rb = v.rb();
1098            **raw_vertex_deform[i].get_or_insert_with(Default::default) = RawVertexDeform { present: true, dx: [lt.x(), rt.x(), lb.x(), rb.x()], dy: [lt.y(), rt.y(), lb.y(), rb.y()] };
1099        }
1100
1101        if let Some(cell) = cell {
1102            cell_vec.push(cell.cell);
1103            result.state.set_cell((cell_vec.len() - 1) as i16);
1104        }
1105        cell_ids.push(result.cell);
1106        if let Some(part_color) = result.part_color {
1107            parts_color_vec.push(part_color);
1108            result.state.set_part_color((parts_color_vec.len() - 1) as i16);
1109        }
1110        if let Some(shader) = result.shader {
1111            shader_vec.push(shader);
1112            result.state.set_shader((shader_vec.len() - 1) as i16);
1113        }
1114        if result.deform_present {
1115            let mut args = runtime::framedata::ss::runtime::PartAttributeDeformArgs::default();
1116            if !deform_coord_workspace.is_empty() {
1117                args.coordinate = Some(fb.create_vector(deform_coord_workspace));
1118            }
1119            if !deform_index_workspace.is_empty() {
1120                args.index = Some(fb.create_vector(deform_index_workspace));
1121            }
1122            let deform_off = runtime::framedata::ss::runtime::PartAttributeDeform::create(fb, &args);
1123            deform_vec.push(deform_off);
1124            result.state.set_deform((deform_vec.len() - 1) as i16);
1125            // Retain per-part deform so the Phase 2 mesh-vertex pass can apply it.
1126            let retained = mesh_deform[i].get_or_insert_with(Default::default);
1127            retained.indices.extend_from_slice(deform_index_workspace.as_slice());
1128            for c in deform_coord_workspace.iter() {
1129                retained.dx.push(c.x());
1130                retained.dy.push(c.y());
1131            }
1132        }
1133        parts_vec.push(result.state);
1134    }
1135}
1136
1137/// Builds this frame's Nine-Slice geometry for every nines part — the runtime
1138/// side of `SsNines`, driven by the part's authored margins / fill mode and the
1139/// pose's size and Cell.
1140///
1141/// Positions land in the same local-space box the quad path produces (pivot,
1142/// image flip and Y-Up/Y-Down already applied), so a Player only multiplies
1143/// them by the world matrix. UVs are cellmap texture-pixel coordinates, and
1144/// `box_coords` carry each vertex's fraction inside the part box so per-corner
1145/// PartColor interpolates the same way `shape_vertex_box_coords` drives it.
1146///
1147/// A part flip mirrors the box coordinates rather than the UVs: a nine-slice
1148/// has asymmetric margins, so mirroring the sampling alone would squeeze the
1149/// far margin into the near slice instead of mirroring the drawn box.
1150pub fn compute_nines_geometry_for_parts(
1151    parts_vec: &[runtime::framedata::ss::runtime::PartState],
1152    cached_parts: &[CachedPartData],
1153    cell_meta_per_part: &[f32],
1154    raw_vertex_deform: &[DeformSlot<RawVertexDeform>],
1155    coordinate_system: SsCoordinateSystem,
1156    out: &mut NinesBuffers,
1157) {
1158    out.begin(parts_vec.len());
1159
1160    for (i, state) in parts_vec.iter().enumerate() {
1161        out.vertex_offsets.push((out.box_coords.len() / 2) as u32);
1162        out.index_offsets.push(out.indices.len() as u32);
1163
1164        let Some(nines) = cached_parts.get(i).and_then(|c| c.nines) else {
1165            continue;
1166        };
1167        let (w, h) = (state.size_x(), state.size_y());
1168        if state.cell() < 0 || w <= 0.0 || h <= 0.0 {
1169            continue;
1170        }
1171
1172        let off = i * 6;
1173        let meta = |k: usize| cell_meta_per_part.get(off + k).copied().unwrap_or(0.0);
1174        let (cell_w, cell_h) = (meta(2), meta(3));
1175        let (rect_left, rect_top) = (meta(4), meta(5));
1176        if cell_w <= 0.0 || cell_h <= 0.0 {
1177            continue;
1178        }
1179
1180        let start = out.box_coords.len() / 2;
1181        let index_start = out.indices.len();
1182        let (vertex_count, _) = crate::eval::geometry::emit_nines_geometry((w, h), (rect_left, rect_top, rect_left + cell_w, rect_top + cell_h), nines.margins, nines.fill_mode, &mut out.box_coords, &mut out.uvs, &mut out.indices);
1183
1184        let mut pivot_y = state.pivot_y();
1185        if coordinate_system == SsCoordinateSystem::YDown {
1186            pivot_y = -pivot_y;
1187        }
1188        let (bx, by) = crate::eval::geometry::compute_local_vertices((w, h), (meta(0), meta(1)), (state.pivot_x(), pivot_y), (state.img_flip_h(), state.img_flip_v()), None);
1189        let (left, top, right, bottom) = (bx[0], by[0], bx[3], by[3]);
1190
1191        let mirror_u = state.flip_h() != state.img_flip_h();
1192        let mirror_v = state.flip_v() != state.img_flip_v();
1193        let deform = vertex_deform_at(raw_vertex_deform, i);
1194        // Skew shares the Vertex-deform slot; applied as a shear about the pivot
1195        // origin in Y-up, before the Y-down flip, like the 4-corner deform.
1196        let skew = crate::eval::geometry::skew_local_tans(state.skew_x(), state.skew_y());
1197
1198        for v in start..start + vertex_count as usize {
1199            let (mut fx, mut fy) = (out.box_coords[v * 2], out.box_coords[v * 2 + 1]);
1200            if mirror_u {
1201                fx = 1.0 - fx;
1202            }
1203            if mirror_v {
1204                fy = 1.0 - fy;
1205            }
1206            out.box_coords[v * 2] = fx;
1207            out.box_coords[v * 2 + 1] = fy;
1208
1209            let mut x = left + fx * (right - left);
1210            let mut y = top + fy * (bottom - top);
1211            if let Some(d) = deform {
1212                let (dx, dy) = crate::eval::geometry::bilinear_box_deform(&d.dx, &d.dy, fx, fy);
1213                x += dx;
1214                y += dy;
1215            }
1216            if let Some((tan_x, tan_y)) = skew {
1217                let (nx, ny) = crate::eval::geometry::skew_point_yup(x, y, tan_x, tan_y);
1218                x = nx;
1219                y = ny;
1220            }
1221            if coordinate_system == SsCoordinateSystem::YDown {
1222                y = -y;
1223            }
1224            out.vertices.push(x);
1225            out.vertices.push(y);
1226        }
1227
1228        // Mirroring one axis reverses each triangle's orientation; restore it
1229        // so Players that cull back faces still see the grid.
1230        if mirror_u != mirror_v {
1231            for tri in out.indices[index_start..].as_chunks_mut::<3>().0 {
1232                tri.swap(1, 2);
1233            }
1234        }
1235    }
1236
1237    out.vertex_offsets.push((out.box_coords.len() / 2) as u32);
1238    out.index_offsets.push(out.indices.len() as u32);
1239}
1240
1241pub fn compute_local_vertices_for_parts(
1242    parts_vec: &mut [runtime::framedata::ss::runtime::PartState],
1243    cell_meta_per_part: &[f32],
1244    raw_vertex_deform: &[DeformSlot<RawVertexDeform>],
1245    vertex_vec: &mut Vec<crate::runtime::framedata::ss::runtime::PartAttributeVertex>,
1246    local_vertices: &mut [f32],
1247    coordinate_system: SsCoordinateSystem,
1248) {
1249    vertex_vec.clear();
1250    for slot in local_vertices.iter_mut() {
1251        *slot = 0.0;
1252    }
1253
1254    for (i, state) in parts_vec.iter_mut().enumerate() {
1255        if state.cell() < 0 {
1256            continue;
1257        }
1258
1259        let cell_pivot_x = cell_meta_per_part.get(i * 6).copied().unwrap_or(0.0);
1260        let cell_pivot_y = cell_meta_per_part.get(i * 6 + 1).copied().unwrap_or(0.0);
1261        let pivot = (cell_pivot_x, cell_pivot_y);
1262
1263        let deform = vertex_deform_at(raw_vertex_deform, i).map(|d| (d.dx, d.dy));
1264
1265        let mut pivot_y = state.pivot_y();
1266        if coordinate_system == SsCoordinateSystem::YDown {
1267            pivot_y = -pivot_y;
1268        }
1269
1270        let (mut vx, mut vy) = crate::eval::geometry::compute_local_vertices((state.size_x(), state.size_y()), pivot, (state.pivot_x(), pivot_y), (state.img_flip_h(), state.img_flip_v()), deform.as_ref().map(|(x, y)| (x, y)));
1271
1272        // Skew: a Vertex-deform-mode shear about the pivot origin, applied in
1273        // the authored Y-up space before the Y-down flip below (mutually
1274        // exclusive with the 4-corner deform, so `vx`/`vy` are the plain box).
1275        if let Some((tan_x, tan_y)) = crate::eval::geometry::skew_local_tans(state.skew_x(), state.skew_y()) {
1276            for k in 0..vx.len() {
1277                let (nx, ny) = crate::eval::geometry::skew_point_yup(vx[k], vy[k], tan_x, tan_y);
1278                vx[k] = nx;
1279                vy[k] = ny;
1280            }
1281        }
1282
1283        if coordinate_system == SsCoordinateSystem::YDown {
1284            for y in vy.iter_mut() {
1285                *y = -*y;
1286            }
1287        }
1288
1289        let lt = crate::runtime::framedata::ss::runtime::Vec2::new(vx[0], vy[0]);
1290        let rt = crate::runtime::framedata::ss::runtime::Vec2::new(vx[1], vy[1]);
1291        let lb = crate::runtime::framedata::ss::runtime::Vec2::new(vx[2], vy[2]);
1292        let rb = crate::runtime::framedata::ss::runtime::Vec2::new(vx[3], vy[3]);
1293        let needs_center = state.update_flag().contains(runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributeVertex) || state.update_flag().contains(runtime::framedata::ss::runtime::UpdateAttributeFlags::AttributePartColor);
1294        let center = if needs_center { crate::runtime::framedata::ss::runtime::Vec2::new(vx[4], vy[4]) } else { crate::runtime::framedata::ss::runtime::Vec2::default() };
1295        vertex_vec.push(crate::runtime::framedata::ss::runtime::PartAttributeVertex::new(&lt, &rt, &lb, &rb, &center));
1296        state.set_vertex((vertex_vec.len() - 1) as i16);
1297
1298        let off = i * LOCAL_VERTICES_STRIDE;
1299        if off + LOCAL_VERTICES_STRIDE <= local_vertices.len() {
1300            local_vertices[off] = vx[0];
1301            local_vertices[off + 1] = vy[0];
1302            local_vertices[off + 2] = vx[1];
1303            local_vertices[off + 3] = vy[1];
1304            local_vertices[off + 4] = vx[2];
1305            local_vertices[off + 5] = vy[2];
1306            local_vertices[off + 6] = vx[3];
1307            local_vertices[off + 7] = vy[3];
1308            local_vertices[off + 8] = vx[4];
1309            local_vertices[off + 9] = vy[4];
1310        }
1311    }
1312}
1313
1314type PoseFbOffsets<'a> = (
1315    Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, runtime::framedata::ss::runtime::PartAttributeCell>>>,
1316    Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, runtime::framedata::ss::runtime::PartAttributePartColor>>>,
1317    Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, runtime::framedata::ss::runtime::PartAttributeShader>>>,
1318    Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, runtime::framedata::ss::runtime::PartAttributeVertex>>>,
1319    Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<runtime::framedata::ss::runtime::PartAttributeDeform<'a>>>>>,
1320);
1321
1322fn serialize_pose_to_fb<'a>(
1323    fb: &mut flatbuffers::FlatBufferBuilder<'a>,
1324    cell_vec: &[runtime::framedata::ss::runtime::PartAttributeCell],
1325    parts_color_vec: &[runtime::framedata::ss::runtime::PartAttributePartColor],
1326    shader_vec: &[runtime::framedata::ss::runtime::PartAttributeShader],
1327    vertex_vec: &[runtime::framedata::ss::runtime::PartAttributeVertex],
1328    deform_vec: &[flatbuffers::WIPOffset<runtime::framedata::ss::runtime::PartAttributeDeform<'a>>],
1329) -> PoseFbOffsets<'a> {
1330    let cells_off = (!cell_vec.is_empty()).then(|| fb.create_vector(cell_vec));
1331    let parts_color_off = (!parts_color_vec.is_empty()).then(|| fb.create_vector(parts_color_vec));
1332    let shaders_off = (!shader_vec.is_empty()).then(|| fb.create_vector(shader_vec));
1333    let vertices_off = (!vertex_vec.is_empty()).then(|| fb.create_vector(vertex_vec));
1334    let deforms_off = (!deform_vec.is_empty()).then(|| fb.create_vector(deform_vec));
1335    (cells_off, parts_color_off, shaders_off, vertices_off, deforms_off)
1336}
1337
1338#[allow(clippy::too_many_arguments)]
1339fn classify_for_draw_batch(disc: ssab::ssab::ss::format::PartType) -> Option<(runtime::framedata::ss::runtime::DrawBatchKind, bool)> {
1340    use runtime::framedata::ss::runtime::DrawBatchKind as K;
1341    use ssab::ssab::ss::format::PartType as P;
1342    if disc == P::PartTypeNormal {
1343        return Some((K::Normal, true));
1344    }
1345    if disc == P::PartTypeShape {
1346        return Some((K::Shape, true));
1347    }
1348    if disc == P::PartTypeMesh {
1349        // Modern renderers support dynamic index buffer concatenation for arbitrary meshes
1350        // within a single DrawBatch, so they are fully batchable.
1351        return Some((K::Mesh, true));
1352    }
1353    if disc == P::PartTypeNines {
1354        // Same story as Mesh: the per-part grids are concatenated in the Nines
1355        // SoA buffers, so consecutive nines parts merge into one batch.
1356        return Some((K::Nines, true));
1357    }
1358    if disc == P::PartTypeText {
1359        // Glyph layout and rasterisation belong to the Player, so the batch
1360        // carries neither geometry nor a texture — it exists to give the part
1361        // its slot in the draw order. Not batchable: the runtime cannot key the
1362        // font a part draws with, so merging two text parts would hide a font
1363        // change inside one batch.
1364        return Some((K::Text, false));
1365    }
1366    if disc == P::PartTypeInstance {
1367        return Some((K::Instance, false));
1368    }
1369    if disc == P::PartTypeEffect {
1370        return Some((K::Effect, false));
1371    }
1372    if disc == P::PartTypeMask {
1373        return Some((K::Mask, false));
1374    }
1375    None
1376}
1377
1378const FLAG_MASK_INFLUENCE: u8 = 0x01;
1379
1380#[inline]
1381fn ssab_blend_to_runtime(b: ssab::ssab::ss::format::BlendType) -> runtime::framedata::ss::runtime::BlendType {
1382    runtime::framedata::ss::runtime::BlendType(b.0)
1383}
1384
1385#[derive(Clone, Copy, PartialEq, Eq)]
1386struct BatchKey {
1387    kind: runtime::framedata::ss::runtime::DrawBatchKind,
1388    texture_hash: u32,
1389    blend_type: runtime::framedata::ss::runtime::BlendType,
1390    flags: u8,
1391}
1392
1393struct InProgressBatch {
1394    start_rank: u16,
1395    count: u16,
1396    vertex_count: u32,
1397    index_count: u32,
1398    key: BatchKey,
1399}
1400
1401fn finalize_batch(ip: InProgressBatch, out: &mut Vec<runtime::framedata::ss::runtime::DrawBatch>) {
1402    out.push(runtime::framedata::ss::runtime::DrawBatch::new(ip.start_rank, ip.count, ip.key.texture_hash, ip.vertex_count.min(u16::MAX as u32) as u16, ip.index_count.min(u16::MAX as u32) as u16, ip.key.blend_type, ip.key.kind, ip.key.flags));
1403}
1404
1405type DrawOrderAndBatchesOffsets<'a> = (flatbuffers::WIPOffset<flatbuffers::Vector<'a, u16>>, flatbuffers::WIPOffset<flatbuffers::Vector<'a, runtime::framedata::ss::runtime::DrawBatch>>, flatbuffers::WIPOffset<flatbuffers::Vector<'a, u16>>);
1406
1407fn build_draw_order_and_batches<'a>(
1408    fb: &mut flatbuffers::FlatBufferBuilder<'a>,
1409    z_indices: &[usize],
1410    cached_parts: &[CachedPartData],
1411    parts_vec: &[runtime::framedata::ss::runtime::PartState],
1412    cell_texture_hashes: &[u32],
1413    nines: &NinesBuffers,
1414    draw_order_workspace: &mut Vec<u16>,
1415    batches_workspace: &mut Vec<runtime::framedata::ss::runtime::DrawBatch>,
1416    mask_indices_workspace: &mut Vec<u16>,
1417) -> DrawOrderAndBatchesOffsets<'a> {
1418    use runtime::framedata::ss::runtime::{DrawBatchKind, UpdateAttributeFlags};
1419
1420    draw_order_workspace.clear();
1421    draw_order_workspace.reserve(z_indices.len());
1422    batches_workspace.clear();
1423    mask_indices_workspace.clear();
1424
1425    let mut in_progress: Option<InProgressBatch> = None;
1426
1427    for &part_idx in z_indices.iter() {
1428        if part_idx >= cached_parts.len() || part_idx >= parts_vec.len() {
1429            continue;
1430        }
1431        let cached = &cached_parts[part_idx];
1432        let part_state = &parts_vec[part_idx];
1433
1434        let Some((kind, batchable)) = classify_for_draw_batch(cached.part_type_disc) else {
1435            continue;
1436        };
1437
1438        // A text part authored as a pure mask is dropped outright. The runtime
1439        // produces no glyphs, so it can neither write coverage nor be honoured
1440        // as a mask — and surfacing it as an ordinary batch would draw text the
1441        // author meant to be invisible.
1442        if kind == DrawBatchKind::Text && cached.is_mask_contributor {
1443            continue;
1444        }
1445
1446        if cached.is_mask_contributor {
1447            mask_indices_workspace.push(part_idx as u16);
1448        }
1449
1450        let blend_type = ssab_blend_to_runtime(cached.blend_type);
1451        let mut flags: u8 = 0;
1452        if cached.mask_influence {
1453            flags |= FLAG_MASK_INFLUENCE;
1454        }
1455
1456        let is_pure_mask = kind == DrawBatchKind::Mask;
1457        let needs_mask_twin = cached.is_mask_contributor && !is_pure_mask;
1458        let cell_texture_hash = cell_texture_hashes.get(part_idx).copied().unwrap_or(0);
1459        // Both kinds draw the part's Cell, so without one there is nothing to
1460        // batch — a nines part also has an empty geometry range in that case.
1461        // Culled on the *cell* hash: a TCHG override names a texture but never gives a
1462        // cell-less part geometry to draw, so it must not resurrect one here.
1463        let cell_backed_no_cell = matches!(kind, DrawBatchKind::Normal | DrawBatchKind::Nines) && cell_texture_hash == 0;
1464        // An authored TextureChange (TCHG) rebinds this part's texture, so it has to take part
1465        // in the batch key — otherwise parts sharing a cellmap merge into one batch and the
1466        // override cannot be bound. `texture` is 0 both by schema default and for the authored
1467        // "no override" (empty TextureName), which falls back to the cell's own texture. Only a
1468        // part that resolved a cell honours the override: a textureless kind (`Shape`, `Text`)
1469        // keeps `texture_hash` at 0, and a cell-less part is culled below anyway.
1470        let texture_override = part_state.texture();
1471        let texture_hash = if cell_texture_hash != 0 && part_state.update_flag().contains(UpdateAttributeFlags::AttributeTexture) && texture_override != 0 { texture_override } else { cell_texture_hash };
1472        // Masks honour Hide too: a hidden mask must NOT contribute coverage
1473        // (SS mask opt-out is mask-value==0 OR Hide==true) — otherwise a hidden
1474        // mask would wrongly clip its targets once the player rasterises mask
1475        // coverage.
1476        let drawn_as_self = !part_state.hide() && !cell_backed_no_cell;
1477
1478        if !needs_mask_twin && !drawn_as_self {
1479            continue;
1480        }
1481
1482        let rank = draw_order_workspace.len() as u16;
1483        draw_order_workspace.push(part_idx as u16);
1484
1485        if needs_mask_twin {
1486            if let Some(ip) = in_progress.take() {
1487                finalize_batch(ip, batches_workspace);
1488            }
1489            batches_workspace.push(runtime::framedata::ss::runtime::DrawBatch::new(rank, 1, 0, 0, 0, blend_type, DrawBatchKind::Mask, flags));
1490        }
1491
1492        if !drawn_as_self {
1493            continue;
1494        }
1495
1496        let (vc, ic): (u32, u32) = if kind == DrawBatchKind::Normal {
1497            let f = part_state.update_flag();
1498            let needs_center = f.contains(UpdateAttributeFlags::AttributeVertex) || f.contains(UpdateAttributeFlags::AttributePartColor);
1499            if needs_center { (5, 12) } else { (4, 6) }
1500        } else if kind == DrawBatchKind::Nines {
1501            // Known exactly: the grid was built before the draw plan.
1502            nines.counts(part_idx)
1503        } else {
1504            (0, 0)
1505        };
1506
1507        let key = BatchKey { kind, texture_hash, blend_type, flags };
1508
1509        if let Some(ip) = in_progress.as_mut() {
1510            if batchable && ip.key == key {
1511                ip.count = ip.count.saturating_add(1);
1512                ip.vertex_count = ip.vertex_count.saturating_add(vc);
1513                ip.index_count = ip.index_count.saturating_add(ic);
1514                continue;
1515            }
1516            finalize_batch(in_progress.take().unwrap(), batches_workspace);
1517        }
1518
1519        in_progress = Some(InProgressBatch { start_rank: rank, count: 1, vertex_count: vc, index_count: ic, key });
1520    }
1521
1522    if let Some(ip) = in_progress {
1523        finalize_batch(ip, batches_workspace);
1524    }
1525
1526    let draw_order_off = fb.create_vector(draw_order_workspace);
1527    let batches_off = fb.create_vector(batches_workspace);
1528    let mask_indices_off = fb.create_vector(mask_indices_workspace);
1529    (draw_order_off, batches_off, mask_indices_off)
1530}
1531
1532#[allow(clippy::too_many_arguments)]
1533pub fn compose_frame_data<'a>(
1534    fb: &mut flatbuffers::FlatBufferBuilder<'a>,
1535    cached_parts: &[CachedPartData],
1536    z_order: &mut crate::eval::z_order::ZOrderTable,
1537    parts_vec: &mut [runtime::framedata::ss::runtime::PartState],
1538    cell_vec: &[crate::runtime::framedata::ss::runtime::PartAttributeCell],
1539    parts_color_vec: &[crate::runtime::framedata::ss::runtime::PartAttributePartColor],
1540    shader_vec: &[crate::runtime::framedata::ss::runtime::PartAttributeShader],
1541    vertex_vec: &mut Vec<crate::runtime::framedata::ss::runtime::PartAttributeVertex>,
1542    deform_vec: &[flatbuffers::WIPOffset<runtime::framedata::ss::runtime::PartAttributeDeform<'a>>],
1543    raw_vertex_deform: &[DeformSlot<RawVertexDeform>],
1544    cell_meta_per_part: &[f32],
1545    cell_texture_hashes: &[u32],
1546    local_vertices: &mut [f32],
1547    nines: &mut NinesBuffers,
1548    coordinate_system: SsCoordinateSystem,
1549    render_mode: crate::eval::RenderMode,
1550    draw_order_workspace: &mut Vec<u16>,
1551    batches_workspace: &mut Vec<runtime::framedata::ss::runtime::DrawBatch>,
1552    mask_indices_workspace: &mut Vec<u16>,
1553) -> flatbuffers::WIPOffset<runtime::framedata::ss::runtime::FrameData<'a>> {
1554    compute_local_vertices_for_parts(parts_vec, cell_meta_per_part, raw_vertex_deform, vertex_vec, local_vertices, coordinate_system);
1555    // Before the draw plan: its Nines batches carry the exact vertex / index counts.
1556    compute_nines_geometry_for_parts(parts_vec, cached_parts, cell_meta_per_part, raw_vertex_deform, coordinate_system, nines);
1557
1558    let (cells_off, parts_color_off, shaders_off, vertices_off, deforms_off) = if render_mode == crate::eval::RenderMode::Direct {
1559        let pc = (!parts_color_vec.is_empty()).then(|| fb.create_vector(parts_color_vec));
1560        let s = (!shader_vec.is_empty()).then(|| fb.create_vector(shader_vec));
1561        (None, pc, s, None, None)
1562    } else {
1563        serialize_pose_to_fb(fb, cell_vec, parts_color_vec, shader_vec, vertex_vec, deform_vec)
1564    };
1565
1566    let mut args = runtime::framedata::ss::runtime::FrameDataArgs { cells: cells_off, parts_color: parts_color_off, shaders: shaders_off, vertices: vertices_off, deforms: deforms_off, ..Default::default() };
1567    args.parts = Some(fb.create_vector(parts_vec));
1568
1569    // The draw order, batches and mask indices need the finished `parts_vec` and
1570    // `cell_texture_hashes`, and must be in `args` before `FrameData::create`.
1571    z_order.update(parts_vec);
1572    let (draw_order_off, draw_batches_off, mask_indices_off) = build_draw_order_and_batches(fb, z_order.indices(), cached_parts, parts_vec, cell_texture_hashes, nines, draw_order_workspace, batches_workspace, mask_indices_workspace);
1573    args.draw_order = Some(draw_order_off);
1574    args.draw_batches = Some(draw_batches_off);
1575    args.mask_indices = Some(mask_indices_off);
1576
1577    runtime::framedata::ss::runtime::FrameData::create(fb, &args)
1578}
1579
1580#[cfg(test)]
1581mod tests {
1582    use super::*;
1583    use crate::runtime::framedata::ss::runtime::UpdateAttributeFlags;
1584
1585    #[test]
1586    fn test_attribute_indices_consistency() {
1587        // Verify that each IDX_ATTRIBUTE constant matches the trailing zeros of its flag.
1588        // This ensures that our indexing into the cursors array is correctly aligned with bit positions.
1589        assert_eq!(IDX_ATTRIBUTECELL, UpdateAttributeFlags::AttributeCell.bits().trailing_zeros() as usize);
1590        assert_eq!(IDX_ATTRIBUTEPOSX, UpdateAttributeFlags::AttributePosX.bits().trailing_zeros() as usize);
1591        assert_eq!(IDX_ATTRIBUTEPOSY, UpdateAttributeFlags::AttributePosY.bits().trailing_zeros() as usize);
1592        assert_eq!(IDX_ATTRIBUTEPOSZ, UpdateAttributeFlags::AttributePosZ.bits().trailing_zeros() as usize);
1593        assert_eq!(IDX_ATTRIBUTEROTX, UpdateAttributeFlags::AttributeRotX.bits().trailing_zeros() as usize);
1594        assert_eq!(IDX_ATTRIBUTEROTY, UpdateAttributeFlags::AttributeRotY.bits().trailing_zeros() as usize);
1595        assert_eq!(IDX_ATTRIBUTEROTZ, UpdateAttributeFlags::AttributeRotZ.bits().trailing_zeros() as usize);
1596        assert_eq!(IDX_ATTRIBUTESCLX, UpdateAttributeFlags::AttributeSclX.bits().trailing_zeros() as usize);
1597        assert_eq!(IDX_ATTRIBUTESCLY, UpdateAttributeFlags::AttributeSclY.bits().trailing_zeros() as usize);
1598        assert_eq!(IDX_ATTRIBUTELOSCLX, UpdateAttributeFlags::AttributeLosclX.bits().trailing_zeros() as usize);
1599        assert_eq!(IDX_ATTRIBUTELOSCLY, UpdateAttributeFlags::AttributeLosclY.bits().trailing_zeros() as usize);
1600        assert_eq!(IDX_ATTRIBUTEALPHA, UpdateAttributeFlags::AttributeAlpha.bits().trailing_zeros() as usize);
1601        assert_eq!(IDX_ATTRIBUTELOALPHA, UpdateAttributeFlags::AttributeLoAlpha.bits().trailing_zeros() as usize);
1602        assert_eq!(IDX_ATTRIBUTEPRIO, UpdateAttributeFlags::AttributePrio.bits().trailing_zeros() as usize);
1603        assert_eq!(IDX_ATTRIBUTEFLIPH, UpdateAttributeFlags::AttributeFlipH.bits().trailing_zeros() as usize);
1604        assert_eq!(IDX_ATTRIBUTEFLIPV, UpdateAttributeFlags::AttributeFlipV.bits().trailing_zeros() as usize);
1605        assert_eq!(IDX_ATTRIBUTEHIDE, UpdateAttributeFlags::AttributeHide.bits().trailing_zeros() as usize);
1606        assert_eq!(IDX_ATTRIBUTEPARTCOLOR, UpdateAttributeFlags::AttributePartColor.bits().trailing_zeros() as usize);
1607        assert_eq!(IDX_ATTRIBUTESHADER, UpdateAttributeFlags::AttributeShader.bits().trailing_zeros() as usize);
1608        assert_eq!(IDX_ATTRIBUTEVERTEX, UpdateAttributeFlags::AttributeVertex.bits().trailing_zeros() as usize);
1609        assert_eq!(IDX_ATTRIBUTEPIVOTX, UpdateAttributeFlags::AttributePivotX.bits().trailing_zeros() as usize);
1610        assert_eq!(IDX_ATTRIBUTEPIVOTY, UpdateAttributeFlags::AttributePivotY.bits().trailing_zeros() as usize);
1611        assert_eq!(IDX_ATTRIBUTEANCHORX, UpdateAttributeFlags::AttributeAnchorX.bits().trailing_zeros() as usize);
1612        assert_eq!(IDX_ATTRIBUTEANCHORY, UpdateAttributeFlags::AttributeAnchorY.bits().trailing_zeros() as usize);
1613        assert_eq!(IDX_ATTRIBUTESIZEX, UpdateAttributeFlags::AttributeSizeX.bits().trailing_zeros() as usize);
1614        assert_eq!(IDX_ATTRIBUTESIZEY, UpdateAttributeFlags::AttributeSizeY.bits().trailing_zeros() as usize);
1615        assert_eq!(IDX_ATTRIBUTEIMGFLIPH, UpdateAttributeFlags::AttributeImgFlipH.bits().trailing_zeros() as usize);
1616        assert_eq!(IDX_ATTRIBUTEIMGFLIPV, UpdateAttributeFlags::AttributeImgFlipV.bits().trailing_zeros() as usize);
1617        assert_eq!(IDX_ATTRIBUTEUVTX, UpdateAttributeFlags::AttributeUvtX.bits().trailing_zeros() as usize);
1618        assert_eq!(IDX_ATTRIBUTEUVTY, UpdateAttributeFlags::AttributeUvtY.bits().trailing_zeros() as usize);
1619        assert_eq!(IDX_ATTRIBUTEUVRZ, UpdateAttributeFlags::AttributeUvrZ.bits().trailing_zeros() as usize);
1620        assert_eq!(IDX_ATTRIBUTEUVSX, UpdateAttributeFlags::AttributeUvsX.bits().trailing_zeros() as usize);
1621        assert_eq!(IDX_ATTRIBUTEUVSY, UpdateAttributeFlags::AttributeUvsY.bits().trailing_zeros() as usize);
1622        assert_eq!(IDX_ATTRIBUTEBOUNDR, UpdateAttributeFlags::AttributeBoundr.bits().trailing_zeros() as usize);
1623        assert_eq!(IDX_ATTRIBUTEMASK, UpdateAttributeFlags::AttributeMask.bits().trailing_zeros() as usize);
1624        assert_eq!(IDX_ATTRIBUTESKEW, UpdateAttributeFlags::AttributeSkew.bits().trailing_zeros() as usize);
1625        assert_eq!(IDX_ATTRIBUTEDEFORM, UpdateAttributeFlags::AttributeDeform.bits().trailing_zeros() as usize);
1626        assert_eq!(IDX_ATTRIBUTETEXTURE, UpdateAttributeFlags::AttributeTexture.bits().trailing_zeros() as usize);
1627    }
1628
1629    #[test]
1630    fn test_num_part_attributes_count() {
1631        assert_eq!(NUM_PART_ATTRIBUTES, UpdateAttributeFlags::all().bits().count_ones() as usize);
1632    }
1633
1634    #[test]
1635    fn test_attribute_flags_no_gaps() {
1636        let all_bits = UpdateAttributeFlags::all().bits();
1637        let num_bits = all_bits.count_ones();
1638        // Check for gaps: If there are no gaps, the value of all_bits should be (1 << num_bits) - 1.
1639        // The bit positions are the `IDX_ATTRIBUTE*` constants, which place each
1640        // attribute's bit in a part's `key_mask` and so its key cursor.
1641        let expected_mask = (1u64 << num_bits) - 1;
1642        assert_eq!(all_bits, expected_mask, "UpdateAttributeFlags must not have gaps in bit values to avoid array out-of-bounds when using bit positions as indices.");
1643    }
1644
1645    /// The setup pose is the floor the mix folds tracks onto, so it has to land
1646    /// in the space `evaluate_part` produces: a part keyed, once, with its setup
1647    /// values evaluates to its setup pose, under every coordinate setup.
1648    #[test]
1649    fn setup_pose_matches_a_pose_keyed_with_the_setup_values() {
1650        use crate::eval::{SsCoordinateSystem, SsOrigin, SsUnit};
1651        use flatbuffers::{FlatBufferBuilder, WIPOffset};
1652        use ssab::ssab::ss::format::{
1653            InitialPartAttributes, InitialPartAttributesArgs, InterpolationType, KeyCurve, Keyframes, KeyframesArgs, PartAnimationData, PartAnimationDataArgs, PartAttributeCell, PartAttributeDeform, PartAttributePartColor, PartAttributeShader,
1654            PartAttributeVertex, Vec2, Vec2Args,
1655        };
1656
1657        // Every attribute the mix blends, a distinct value each.
1658        let setup = InitialPartAttributesArgs {
1659            position_x: 3.0,
1660            position_y: 5.0,
1661            position_z: 7.0,
1662            rotation_x: 11.0,
1663            rotation_y: 13.0,
1664            rotation_z: 17.0,
1665            scale_x: 1.5,
1666            scale_y: 2.5,
1667            local_scale_x: 0.5,
1668            local_scale_y: 0.75,
1669            alpha: 0.25,
1670            local_alpha: 0.125,
1671            pivot_x: 0.1,
1672            pivot_y: 0.2,
1673            anchor_x: 0.3,
1674            anchor_y: 0.4,
1675            size_x: 19.0,
1676            size_y: 23.0,
1677            uv_translation_x: 0.01,
1678            uv_translation_y: 0.02,
1679            uv_rotation_z: 29.0,
1680            uv_scale_x: 1.25,
1681            uv_scale_y: 1.75,
1682            bounding_radius: 31.0,
1683            mask: 37.0,
1684            skew_x: 41.0,
1685            skew_y: -43.0,
1686            ..Default::default()
1687        };
1688
1689        // The same values as one key each, at frame 0.
1690        let mut values = Vec::new();
1691        let mut part = PartAnimationDataArgs::default();
1692        let mut key = |run: &mut u32, value: f32| {
1693            *run = values.len() as u32;
1694            values.push(value.to_bits());
1695        };
1696        key(&mut part.position_x_keys, setup.position_x);
1697        key(&mut part.position_y_keys, setup.position_y);
1698        key(&mut part.position_z_keys, setup.position_z);
1699        key(&mut part.rotation_x_keys, setup.rotation_x);
1700        key(&mut part.rotation_y_keys, setup.rotation_y);
1701        key(&mut part.rotation_z_keys, setup.rotation_z);
1702        key(&mut part.scale_x_keys, setup.scale_x);
1703        key(&mut part.scale_y_keys, setup.scale_y);
1704        key(&mut part.local_scale_x_keys, setup.local_scale_x);
1705        key(&mut part.local_scale_y_keys, setup.local_scale_y);
1706        key(&mut part.alpha_keys, setup.alpha);
1707        key(&mut part.local_alpha_keys, setup.local_alpha);
1708        key(&mut part.pivot_x_keys, setup.pivot_x);
1709        key(&mut part.pivot_y_keys, setup.pivot_y);
1710        key(&mut part.anchor_x_keys, setup.anchor_x);
1711        key(&mut part.anchor_y_keys, setup.anchor_y);
1712        key(&mut part.size_x_keys, setup.size_x);
1713        key(&mut part.size_y_keys, setup.size_y);
1714        key(&mut part.uv_translation_x_keys, setup.uv_translation_x);
1715        key(&mut part.uv_translation_y_keys, setup.uv_translation_y);
1716        key(&mut part.uv_rotation_z_keys, setup.uv_rotation_z);
1717        key(&mut part.uv_scale_x_keys, setup.uv_scale_x);
1718        key(&mut part.uv_scale_y_keys, setup.uv_scale_y);
1719        key(&mut part.bounding_radius_keys, setup.bounding_radius);
1720        key(&mut part.mask_keys, setup.mask);
1721        // Skew's key is an index into `skews`, which holds the one pair.
1722        part.skew_keys = values.len() as u32;
1723        values.push(0);
1724
1725        let mut fb = FlatBufferBuilder::new();
1726        let skew = Vec2::create(&mut fb, &Vec2Args { v1: setup.skew_x, v2: setup.skew_y });
1727        let n = values.len();
1728        let args = KeyframesArgs {
1729            runs: Some(fb.create_vector(&(0..=n as u32).collect::<Vec<_>>())),
1730            frame: Some(fb.create_vector(&alloc::vec![0u16; n])),
1731            interpolation: Some(fb.create_vector(&alloc::vec![InterpolationType::None; n])),
1732            curve: Some(fb.create_vector(&alloc::vec![ssab::NO_CURVE; n])),
1733            value: Some(fb.create_vector(&values)),
1734            curves: Some(fb.create_vector::<KeyCurve>(&[])),
1735            easing_rates: Some(fb.create_vector::<f32>(&[])),
1736            cells: Some(fb.create_vector::<WIPOffset<PartAttributeCell>>(&[])),
1737            part_colors: Some(fb.create_vector::<WIPOffset<PartAttributePartColor>>(&[])),
1738            shaders: Some(fb.create_vector::<WIPOffset<PartAttributeShader>>(&[])),
1739            vertices: Some(fb.create_vector::<WIPOffset<PartAttributeVertex>>(&[])),
1740            skews: Some(fb.create_vector(&[skew])),
1741            deforms: Some(fb.create_vector::<WIPOffset<PartAttributeDeform>>(&[])),
1742        };
1743        let root = Keyframes::create(&mut fb, &args);
1744        fb.finish(root, None);
1745        let keys = KeyColumns::new(flatbuffers::root::<Keyframes>(fb.finished_data()).unwrap(), None);
1746
1747        let mut part_fb = FlatBufferBuilder::new();
1748        let root = PartAnimationData::create(&mut part_fb, &part);
1749        part_fb.finish(root, None);
1750        let part = flatbuffers::root::<PartAnimationData>(part_fb.finished_data()).unwrap();
1751        let cached = CachedPartData::new(part, &keys, 0, -1, 0, None, None, None, None, ssab::ssab::ss::format::BlendType::Mix, ssab::ssab::ss::format::PartType::PartTypeNormal, false, false, 0);
1752
1753        let mut setup_fb = FlatBufferBuilder::new();
1754        let root = InitialPartAttributes::create(&mut setup_fb, &setup);
1755        setup_fb.finish(root, None);
1756        let setup = flatbuffers::root::<InitialPartAttributes>(setup_fb.finished_data()).unwrap();
1757
1758        type Read = fn(&runtime::framedata::ss::runtime::PartState) -> f32;
1759        let mixed: [(&str, Read); 27] = [
1760            ("position_x", |s| s.position_x()),
1761            ("position_y", |s| s.position_y()),
1762            ("position_z", |s| s.position_z()),
1763            ("rotation_x", |s| s.rotation_x()),
1764            ("rotation_y", |s| s.rotation_y()),
1765            ("rotation_z", |s| s.rotation_z()),
1766            ("scale_x", |s| s.scale_x()),
1767            ("scale_y", |s| s.scale_y()),
1768            ("local_scale_x", |s| s.local_scale_x()),
1769            ("local_scale_y", |s| s.local_scale_y()),
1770            ("alpha", |s| s.alpha()),
1771            ("local_alpha", |s| s.local_alpha()),
1772            ("pivot_x", |s| s.pivot_x()),
1773            ("pivot_y", |s| s.pivot_y()),
1774            ("anchor_x", |s| s.anchor_x()),
1775            ("anchor_y", |s| s.anchor_y()),
1776            ("size_x", |s| s.size_x()),
1777            ("size_y", |s| s.size_y()),
1778            ("uv_translation_x", |s| s.uv_translation_x()),
1779            ("uv_translation_y", |s| s.uv_translation_y()),
1780            ("uv_rotation_z", |s| s.uv_rotation_z()),
1781            ("uv_scale_x", |s| s.uv_scale_x()),
1782            ("uv_scale_y", |s| s.uv_scale_y()),
1783            ("bounding_radius", |s| s.bounding_radius()),
1784            ("mask", |s| s.mask()),
1785            ("skew_x", |s| s.skew_x()),
1786            ("skew_y", |s| s.skew_y()),
1787        ];
1788        let (canvas_width, canvas_height) = (200.0, 100.0);
1789        for coordinate_system in [SsCoordinateSystem::YUp, SsCoordinateSystem::YDown] {
1790            for origin in [SsOrigin::Center, SsOrigin::TopLeft] {
1791                for unit in [SsUnit::Pixel, SsUnit::Normalized] {
1792                    let floor = setup_pose_part(&setup, -1, coordinate_system, origin, unit, canvas_width, canvas_height);
1793                    let mut cursors = alloc::vec![0; cached.key_mask.count_ones() as usize];
1794                    let (mut a, mut b, mut c, mut d, mut e) = (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());
1795                    let keyed = evaluate_part(&cached, &keys, 0.0, &mut cursors, None, cached.key_mask, coordinate_system, origin, unit, canvas_width, canvas_height, &mut a, &mut b, &mut c, &mut d, &mut e).state;
1796                    for (name, read) in mixed {
1797                        assert_eq!(read(&floor), read(&keyed), "{name} under {coordinate_system:?} / {origin:?} / {unit:?}");
1798                    }
1799                }
1800            }
1801        }
1802    }
1803
1804    #[test]
1805    fn test_part_evaluation_result_init() {
1806        let mut part_state = runtime::framedata::ss::runtime::PartState::default();
1807        part_state.set_part_index(5);
1808
1809        let result = PartEvaluationResult { state: part_state, cell: None, part_color: None, shader: None, vertex: None, deform_present: false };
1810
1811        assert_eq!(result.state.part_index(), 5);
1812        assert!(result.cell.is_none());
1813        assert!(result.part_color.is_none());
1814    }
1815
1816    fn make_stage_b_state(cell_index: i16, size: (f32, f32), pivot: (f32, f32), flag: UpdateAttributeFlags) -> runtime::framedata::ss::runtime::PartState {
1817        let mut s = runtime::framedata::ss::runtime::PartState::default();
1818        s.set_cell(cell_index);
1819        s.set_vertex(-1);
1820        s.set_size_x(size.0);
1821        s.set_size_y(size.1);
1822        s.set_pivot_x(pivot.0);
1823        s.set_pivot_y(pivot.1);
1824        s.set_update_flag(flag);
1825        s
1826    }
1827
1828    #[test]
1829    fn stage_b_skips_cellless_parts() {
1830        let mut parts_vec = vec![make_stage_b_state(-1, (10.0, 20.0), (0.0, 0.0), UpdateAttributeFlags::empty())];
1831        let cell_meta_per_part = vec![0.0_f32; 6];
1832        let raw_vertex_deform: alloc::vec::Vec<DeformSlot<RawVertexDeform>> = vec![None];
1833        let mut vertex_vec: Vec<runtime::framedata::ss::runtime::PartAttributeVertex> = Vec::new();
1834        let mut local_vertices = vec![0.0_f32; LOCAL_VERTICES_STRIDE];
1835
1836        compute_local_vertices_for_parts(&mut parts_vec, &cell_meta_per_part, &raw_vertex_deform, &mut vertex_vec, &mut local_vertices, crate::eval::SsCoordinateSystem::YUp);
1837
1838        assert!(vertex_vec.is_empty(), "vertex_vec should not gain entries for cell-less parts");
1839        assert_eq!(parts_vec[0].vertex(), -1, "vertex index should remain -1");
1840        assert!(local_vertices.iter().all(|&v| v == 0.0), "local_vertices for cell-less parts should stay zero");
1841    }
1842
1843    #[test]
1844    fn stage_b_resolves_no_deform_box() {
1845        // size (10, 20), cell pivot (0, 0), state pivot (0, 0), Y-Up:
1846        // 5-corner box centered at origin: LT(-5,10), RT(5,10), LB(-5,-10), RB(5,-10), center(0,0).
1847        let mut parts_vec = vec![make_stage_b_state(0, (10.0, 20.0), (0.0, 0.0), UpdateAttributeFlags::AttributeCell)];
1848        let cell_meta_per_part = vec![0.0_f32; 6];
1849        let raw_vertex_deform: alloc::vec::Vec<DeformSlot<RawVertexDeform>> = vec![None];
1850        let mut vertex_vec: Vec<runtime::framedata::ss::runtime::PartAttributeVertex> = Vec::new();
1851        let mut local_vertices = vec![0.0_f32; LOCAL_VERTICES_STRIDE];
1852
1853        compute_local_vertices_for_parts(&mut parts_vec, &cell_meta_per_part, &raw_vertex_deform, &mut vertex_vec, &mut local_vertices, crate::eval::SsCoordinateSystem::YUp);
1854
1855        assert_eq!(vertex_vec.len(), 1);
1856        assert_eq!(parts_vec[0].vertex(), 0);
1857        let v = &vertex_vec[0];
1858        assert_eq!((v.lt().x(), v.lt().y()), (-5.0, 10.0));
1859        assert_eq!((v.rt().x(), v.rt().y()), (5.0, 10.0));
1860        assert_eq!((v.lb().x(), v.lb().y()), (-5.0, -10.0));
1861        assert_eq!((v.rb().x(), v.rb().y()), (5.0, -10.0));
1862        assert_eq!(&local_vertices[..], &[-5.0, 10.0, 5.0, 10.0, -5.0, -10.0, 5.0, -10.0, 0.0, 0.0]);
1863    }
1864
1865    #[test]
1866    fn stage_b_applies_deform_offsets() {
1867        // Same box as above + deform offsets per corner. AttributeVertex flag is set so
1868        // the packed `PartAttributeVertex.center` carries the Varignon-mean center.
1869        let mut parts_vec = vec![make_stage_b_state(0, (10.0, 20.0), (0.0, 0.0), UpdateAttributeFlags::AttributeCell | UpdateAttributeFlags::AttributeVertex)];
1870        let cell_meta_per_part = vec![0.0_f32; 6];
1871        let raw_vertex_deform = vec![Some(alloc::boxed::Box::new(RawVertexDeform { present: true, dx: [1.0, 2.0, 3.0, 4.0], dy: [10.0, 20.0, 30.0, 40.0] }))];
1872        let mut vertex_vec: Vec<runtime::framedata::ss::runtime::PartAttributeVertex> = Vec::new();
1873        let mut local_vertices = vec![0.0_f32; LOCAL_VERTICES_STRIDE];
1874
1875        compute_local_vertices_for_parts(&mut parts_vec, &cell_meta_per_part, &raw_vertex_deform, &mut vertex_vec, &mut local_vertices, crate::eval::SsCoordinateSystem::YUp);
1876
1877        let v = &vertex_vec[0];
1878        assert_eq!((v.lt().x(), v.lt().y()), (-4.0, 20.0)); // base (-5,10) + (1,10)
1879        assert_eq!((v.rt().x(), v.rt().y()), (7.0, 30.0)); //      (5,10) + (2,20)
1880        assert_eq!((v.lb().x(), v.lb().y()), (-2.0, 20.0)); // (-5,-10) + (3,30)
1881        assert_eq!((v.rb().x(), v.rb().y()), (9.0, 30.0)); //  (5,-10) + (4,40)
1882        // Varignon center: ((-4+7-2+9)/4, (20+30+20+30)/4) = (2.5, 25)
1883        assert_eq!((v.center().x(), v.center().y()), (2.5, 25.0));
1884    }
1885
1886    #[test]
1887    fn stage_b_y_down_flips_vertical() {
1888        // Same setup as stage_b_resolves_no_deform_box, but Y-Down flips all vy.
1889        let mut parts_vec = vec![make_stage_b_state(0, (10.0, 20.0), (0.0, 0.0), UpdateAttributeFlags::AttributeCell | UpdateAttributeFlags::AttributeVertex)];
1890        let cell_meta_per_part = vec![0.0_f32; 6];
1891        let raw_vertex_deform: alloc::vec::Vec<DeformSlot<RawVertexDeform>> = vec![None];
1892        let mut vertex_vec: Vec<runtime::framedata::ss::runtime::PartAttributeVertex> = Vec::new();
1893        let mut local_vertices = vec![0.0_f32; LOCAL_VERTICES_STRIDE];
1894
1895        compute_local_vertices_for_parts(&mut parts_vec, &cell_meta_per_part, &raw_vertex_deform, &mut vertex_vec, &mut local_vertices, crate::eval::SsCoordinateSystem::YDown);
1896
1897        let v = &vertex_vec[0];
1898        // vx unchanged, vy negated.
1899        assert_eq!((v.lt().x(), v.lt().y()), (-5.0, -10.0));
1900        assert_eq!((v.rt().x(), v.rt().y()), (5.0, -10.0));
1901        assert_eq!((v.lb().x(), v.lb().y()), (-5.0, 10.0));
1902        assert_eq!((v.rb().x(), v.rb().y()), (5.0, 10.0));
1903        assert_eq!((v.center().x(), v.center().y()), (0.0, 0.0));
1904    }
1905
1906    #[test]
1907    fn stage_c_empty_vecs_yield_none() {
1908        let mut fb = flatbuffers::FlatBufferBuilder::new();
1909        let cell_vec: Vec<runtime::framedata::ss::runtime::PartAttributeCell> = Vec::new();
1910        let parts_color_vec: Vec<runtime::framedata::ss::runtime::PartAttributePartColor> = Vec::new();
1911        let shader_vec: Vec<runtime::framedata::ss::runtime::PartAttributeShader> = Vec::new();
1912        let vertex_vec: Vec<runtime::framedata::ss::runtime::PartAttributeVertex> = Vec::new();
1913        let deform_vec: Vec<flatbuffers::WIPOffset<runtime::framedata::ss::runtime::PartAttributeDeform>> = Vec::new();
1914
1915        let (c, pc, s, v, d) = serialize_pose_to_fb(&mut fb, &cell_vec, &parts_color_vec, &shader_vec, &vertex_vec, &deform_vec);
1916
1917        assert!(c.is_none());
1918        assert!(pc.is_none());
1919        assert!(s.is_none());
1920        assert!(v.is_none());
1921        assert!(d.is_none());
1922    }
1923
1924    #[test]
1925    fn stage_c_populated_vecs_yield_some() {
1926        let mut fb = flatbuffers::FlatBufferBuilder::new();
1927        let deform_off = runtime::framedata::ss::runtime::PartAttributeDeform::create(&mut fb, &runtime::framedata::ss::runtime::PartAttributeDeformArgs::default());
1928
1929        let cell_vec = vec![runtime::framedata::ss::runtime::PartAttributeCell::default()];
1930        let parts_color_vec = vec![runtime::framedata::ss::runtime::PartAttributePartColor::default()];
1931        let shader_vec = vec![runtime::framedata::ss::runtime::PartAttributeShader::default()];
1932        let vertex_vec = vec![runtime::framedata::ss::runtime::PartAttributeVertex::default()];
1933        let deform_vec = vec![deform_off];
1934
1935        let (c, pc, s, v, d) = serialize_pose_to_fb(&mut fb, &cell_vec, &parts_color_vec, &shader_vec, &vertex_vec, &deform_vec);
1936
1937        assert!(c.is_some());
1938        assert!(pc.is_some());
1939        assert!(s.is_some());
1940        assert!(v.is_some());
1941        assert!(d.is_some());
1942    }
1943
1944    #[test]
1945    fn stage_c_emits_only_populated_attributes() {
1946        // Only deform_vec is populated; the remaining four attributes are empty
1947        // and must yield None — never an empty vector offset.
1948        let mut fb = flatbuffers::FlatBufferBuilder::new();
1949        let deform_off = runtime::framedata::ss::runtime::PartAttributeDeform::create(&mut fb, &runtime::framedata::ss::runtime::PartAttributeDeformArgs::default());
1950
1951        let cell_vec: Vec<runtime::framedata::ss::runtime::PartAttributeCell> = Vec::new();
1952        let parts_color_vec: Vec<runtime::framedata::ss::runtime::PartAttributePartColor> = Vec::new();
1953        let shader_vec: Vec<runtime::framedata::ss::runtime::PartAttributeShader> = Vec::new();
1954        let vertex_vec: Vec<runtime::framedata::ss::runtime::PartAttributeVertex> = Vec::new();
1955        let deform_vec = vec![deform_off];
1956
1957        let (c, pc, s, v, d) = serialize_pose_to_fb(&mut fb, &cell_vec, &parts_color_vec, &shader_vec, &vertex_vec, &deform_vec);
1958
1959        assert!(c.is_none());
1960        assert!(pc.is_none());
1961        assert!(s.is_none());
1962        assert!(v.is_none());
1963        assert!(d.is_some());
1964    }
1965
1966    #[test]
1967    fn raw_vertex_deform_default_is_inert() {
1968        // Stage B applies a slot's offsets only when `present` is set, so a slot
1969        // made with `Default` must read as no deform.
1970        let d = RawVertexDeform::default();
1971        assert!(!d.present);
1972        assert_eq!(d.dx, [0.0; 4]);
1973        assert_eq!(d.dy, [0.0; 4]);
1974    }
1975
1976    #[test]
1977    fn stage_b_center_is_gated_by_update_flag() {
1978        // Cell pivot (0.1, 0.2) produces a non-symmetric box whose Varignon center is (-1, -4).
1979        let cell_meta_per_part = vec![0.1_f32, 0.2, 10.0, 20.0, 0.0, 0.0];
1980        let raw_vertex_deform: alloc::vec::Vec<DeformSlot<RawVertexDeform>> = vec![None];
1981
1982        // Case A: only AttributeCell — center field in vertex_vec stays at default (0, 0),
1983        // but local_vertices always carries the computed center.
1984        {
1985            let mut parts_vec = vec![make_stage_b_state(0, (10.0, 20.0), (0.0, 0.0), UpdateAttributeFlags::AttributeCell)];
1986            let mut vertex_vec: Vec<runtime::framedata::ss::runtime::PartAttributeVertex> = Vec::new();
1987            let mut local_vertices = vec![0.0_f32; LOCAL_VERTICES_STRIDE];
1988            compute_local_vertices_for_parts(&mut parts_vec, &cell_meta_per_part, &raw_vertex_deform, &mut vertex_vec, &mut local_vertices, crate::eval::SsCoordinateSystem::YUp);
1989            assert_eq!((vertex_vec[0].center().x(), vertex_vec[0].center().y()), (0.0, 0.0));
1990            assert_eq!((local_vertices[8], local_vertices[9]), (-1.0, -4.0));
1991        }
1992
1993        // Case B: AttributeVertex also set — center is populated with the computed value.
1994        {
1995            let mut parts_vec = vec![make_stage_b_state(0, (10.0, 20.0), (0.0, 0.0), UpdateAttributeFlags::AttributeCell | UpdateAttributeFlags::AttributeVertex)];
1996            let mut vertex_vec: Vec<runtime::framedata::ss::runtime::PartAttributeVertex> = Vec::new();
1997            let mut local_vertices = vec![0.0_f32; LOCAL_VERTICES_STRIDE];
1998            compute_local_vertices_for_parts(&mut parts_vec, &cell_meta_per_part, &raw_vertex_deform, &mut vertex_vec, &mut local_vertices, crate::eval::SsCoordinateSystem::YUp);
1999            assert_eq!((vertex_vec[0].center().x(), vertex_vec[0].center().y()), (-1.0, -4.0));
2000        }
2001    }
2002
2003    /// One nines part with 10 px margins over a 64 px cell.
2004    fn make_nines_part(fill_mode: crate::eval::geometry::NinesFillMode) -> Vec<CachedPartData> {
2005        let mut part = cached_part_stub(0, -1, ssab::ssab::ss::format::PartType::PartTypeNines, false);
2006        part.nines = Some(NinesPartData { margins: (10.0, 10.0, 10.0, 10.0), fill_mode });
2007        vec![part]
2008    }
2009
2010    /// `[pivot_x, pivot_y, size_w, size_h, rect_left, rect_top]` for a 64x64
2011    /// cell at the texture's origin.
2012    fn nines_cell_meta() -> Vec<f32> {
2013        vec![0.0, 0.0, 64.0, 64.0, 0.0, 0.0]
2014    }
2015
2016    fn run_nines(parts_vec: &[runtime::framedata::ss::runtime::PartState], cached: &[CachedPartData], deform: &[RawVertexDeform], coordinate_system: crate::eval::SsCoordinateSystem) -> NinesBuffers {
2017        let mut out = NinesBuffers::default();
2018        let deform: Vec<DeformSlot<RawVertexDeform>> = deform.iter().map(|d| Some(alloc::boxed::Box::new(*d))).collect();
2019        compute_nines_geometry_for_parts(parts_vec, cached, &nines_cell_meta(), &deform, coordinate_system, &mut out);
2020        out
2021    }
2022
2023    #[test]
2024    fn nines_stretch_fills_the_part_box() {
2025        let parts_vec = vec![make_stage_b_state(0, (100.0, 100.0), (0.0, 0.0), UpdateAttributeFlags::AttributeCell)];
2026        let out = run_nines(&parts_vec, &make_nines_part(crate::eval::geometry::NinesFillMode::Stretch), &[RawVertexDeform::default()], crate::eval::SsCoordinateSystem::YUp);
2027
2028        assert_eq!(out.vertex_offsets, vec![0, 16]);
2029        assert_eq!(out.index_offsets, vec![0, 54]);
2030        assert_eq!(out.counts(0), (16, 54));
2031
2032        // The grid's corners are the part's box corners, Y-Up and pivot-centred.
2033        assert_eq!((out.vertices[0], out.vertices[1]), (-50.0, 50.0));
2034        assert_eq!((out.vertices[30], out.vertices[31]), (50.0, -50.0));
2035        // Box coordinates run 0 -> 1 across it, UVs stay in cell pixels.
2036        assert_eq!((out.box_coords[0], out.box_coords[1]), (0.0, 0.0));
2037        assert_eq!((out.box_coords[30], out.box_coords[31]), (1.0, 1.0));
2038        assert_eq!((out.uvs[0], out.uvs[1]), (0.0, 0.0));
2039        assert_eq!((out.uvs[30], out.uvs[31]), (64.0, 64.0));
2040        // The slice line sits one margin in, in both spaces.
2041        assert_eq!((out.vertices[10], out.vertices[11]), (-40.0, 40.0));
2042        assert_eq!((out.uvs[10], out.uvs[11]), (10.0, 10.0));
2043    }
2044
2045    #[test]
2046    fn nines_tile_repeats_the_middle_slice() {
2047        // A 44 px middle slice covers the part's 80 px middle in 2 repeats.
2048        let parts_vec = vec![make_stage_b_state(0, (100.0, 100.0), (0.0, 0.0), UpdateAttributeFlags::AttributeCell)];
2049        let out = run_nines(&parts_vec, &make_nines_part(crate::eval::geometry::NinesFillMode::Tile), &[RawVertexDeform::default()], crate::eval::SsCoordinateSystem::YUp);
2050
2051        let quads = 4 + 2 * 2 + 2 * 2 + 2 * 2;
2052        assert_eq!(out.counts(0), (quads * 4, quads * 6));
2053        // Independent quads, so the vertex and index buffers stay in lockstep.
2054        assert_eq!(out.vertices.len(), out.box_coords.len());
2055        assert_eq!(out.uvs.len(), out.box_coords.len());
2056    }
2057
2058    #[test]
2059    fn nines_flip_mirrors_the_box_and_keeps_winding() {
2060        let mut state = make_stage_b_state(0, (100.0, 100.0), (0.0, 0.0), UpdateAttributeFlags::AttributeCell);
2061        state.set_flip_h(true);
2062        let out = run_nines(&[state], &make_nines_part(crate::eval::geometry::NinesFillMode::Stretch), &[RawVertexDeform::default()], crate::eval::SsCoordinateSystem::YUp);
2063
2064        // The first grid vertex still samples the cell's top-left, but it is now
2065        // drawn at the box's right edge — mirroring the box, not the sampling,
2066        // is what keeps asymmetric margins mirrored instead of squeezed.
2067        assert_eq!((out.uvs[0], out.uvs[1]), (0.0, 0.0));
2068        assert_eq!((out.box_coords[0], out.box_coords[1]), (1.0, 0.0));
2069        assert_eq!((out.vertices[0], out.vertices[1]), (50.0, 50.0));
2070
2071        // Mirroring a single axis would reverse each triangle, so
2072        // `compute_nines_geometry_for_parts` swaps the last two indices back.
2073        assert_eq!(&out.indices[0..6], &[0, 4, 1, 4, 5, 1]);
2074
2075        // Mirroring both axes cancels out and leaves the original winding.
2076        let mut state = make_stage_b_state(0, (100.0, 100.0), (0.0, 0.0), UpdateAttributeFlags::AttributeCell);
2077        state.set_flip_h(true);
2078        state.set_flip_v(true);
2079        let out = run_nines(&[state], &make_nines_part(crate::eval::geometry::NinesFillMode::Stretch), &[RawVertexDeform::default()], crate::eval::SsCoordinateSystem::YUp);
2080        assert_eq!((out.box_coords[0], out.box_coords[1]), (1.0, 1.0));
2081        assert_eq!(&out.indices[0..6], &[0, 1, 4, 4, 1, 5]);
2082    }
2083
2084    #[test]
2085    fn nines_spreads_vertex_deform_across_the_grid() {
2086        let parts_vec = vec![make_stage_b_state(0, (100.0, 100.0), (0.0, 0.0), UpdateAttributeFlags::AttributeCell | UpdateAttributeFlags::AttributeVertex)];
2087        // Move the LT corner 10 px right; the offset fades out across the grid.
2088        let deform = vec![RawVertexDeform { present: true, dx: [10.0, 0.0, 0.0, 0.0], dy: [0.0; 4] }];
2089        let out = run_nines(&parts_vec, &make_nines_part(crate::eval::geometry::NinesFillMode::Stretch), &deform, crate::eval::SsCoordinateSystem::YUp);
2090
2091        assert_eq!(out.vertices[0], -40.0); // LT takes the whole offset
2092        assert_eq!(out.vertices[30], 50.0); // RB takes none of it
2093        // Interior vertex (0.1, 0.1): 10 * 0.9 * 0.9.
2094        assert!((out.vertices[10] - (-40.0 + 8.1)).abs() < 1e-4, "got {}", out.vertices[10]);
2095    }
2096
2097    #[test]
2098    fn nines_honours_y_down() {
2099        let parts_vec = vec![make_stage_b_state(0, (100.0, 100.0), (0.0, 0.0), UpdateAttributeFlags::AttributeCell)];
2100        let out = run_nines(&parts_vec, &make_nines_part(crate::eval::geometry::NinesFillMode::Stretch), &[RawVertexDeform::default()], crate::eval::SsCoordinateSystem::YDown);
2101
2102        // Same box coordinate, mirrored Y — the grid's first vertex is the box's
2103        // top-left in both systems.
2104        assert_eq!((out.box_coords[0], out.box_coords[1]), (0.0, 0.0));
2105        assert_eq!((out.vertices[0], out.vertices[1]), (-50.0, -50.0));
2106        assert_eq!((out.vertices[30], out.vertices[31]), (50.0, 50.0));
2107    }
2108
2109    #[test]
2110    fn nines_geometry_is_empty_without_drawable_input() {
2111        let stretch = crate::eval::geometry::NinesFillMode::Stretch;
2112        let deform = [RawVertexDeform::default()];
2113
2114        // Not a nines part.
2115        let normal = vec![cached_part_stub(0, -1, ssab::ssab::ss::format::PartType::PartTypeNormal, false)];
2116        let parts_vec = vec![make_stage_b_state(0, (100.0, 100.0), (0.0, 0.0), UpdateAttributeFlags::AttributeCell)];
2117        let out = run_nines(&parts_vec, &normal, &deform, crate::eval::SsCoordinateSystem::YUp);
2118        assert_eq!(out.counts(0), (0, 0));
2119        assert_eq!(out.vertex_offsets, vec![0, 0]);
2120
2121        // Nines part with no Cell resolved this frame.
2122        let parts_vec = vec![make_stage_b_state(-1, (100.0, 100.0), (0.0, 0.0), UpdateAttributeFlags::empty())];
2123        let out = run_nines(&parts_vec, &make_nines_part(stretch), &deform, crate::eval::SsCoordinateSystem::YUp);
2124        assert_eq!(out.counts(0), (0, 0));
2125
2126        // Nines part collapsed to zero size.
2127        let parts_vec = vec![make_stage_b_state(0, (0.0, 100.0), (0.0, 0.0), UpdateAttributeFlags::AttributeCell)];
2128        let out = run_nines(&parts_vec, &make_nines_part(stretch), &deform, crate::eval::SsCoordinateSystem::YUp);
2129        assert_eq!(out.counts(0), (0, 0));
2130        assert!(out.vertices.is_empty() && out.indices.is_empty());
2131    }
2132
2133    #[test]
2134    fn text_parts_take_a_draw_slot_but_never_a_mask_slot() {
2135        // Three text parts; the middle one is authored as a pure mask.
2136        let cached =
2137            vec![cached_part_stub(0, -1, ssab::ssab::ss::format::PartType::PartTypeText, false), cached_part_stub(1, -1, ssab::ssab::ss::format::PartType::PartTypeText, true), cached_part_stub(2, -1, ssab::ssab::ss::format::PartType::PartTypeText, false)];
2138        let parts_vec: Vec<_> = (0..3).map(|_| make_stage_b_state(-1, (10.0, 10.0), (0.0, 0.0), UpdateAttributeFlags::empty())).collect();
2139
2140        let mut fb = flatbuffers::FlatBufferBuilder::new();
2141        let (mut draw_order, mut batches, mut mask_indices) = (Vec::new(), Vec::new(), Vec::new());
2142        build_draw_order_and_batches(&mut fb, &[0, 1, 2], &cached, &parts_vec, &[0, 0, 0], &NinesBuffers::default(), &mut draw_order, &mut batches, &mut mask_indices);
2143
2144        // Text takes part in the draw order, but a text mask is left out
2145        // entirely, since the runtime has no glyphs to write coverage with.
2146        assert_eq!(draw_order, vec![0, 2]);
2147        assert!(mask_indices.is_empty(), "a text mask must not claim coverage it cannot write");
2148
2149        // One batch per text part: the runtime cannot key the font, so merging
2150        // would hide a font change inside a single batch.
2151        assert_eq!(batches.len(), 2);
2152        for (batch, rank) in batches.iter().zip([0, 1]) {
2153            assert_eq!(batch.kind(), runtime::framedata::ss::runtime::DrawBatchKind::Text);
2154            assert_eq!(batch.start_rank(), rank);
2155            assert_eq!(batch.count(), 1);
2156            // The Player owns the glyphs, so the batch carries no geometry and
2157            // no texture — the font comes from the ssab.
2158            assert_eq!((batch.vertex_count(), batch.index_count()), (0, 0));
2159            assert_eq!(batch.texture_hash(), 0);
2160        }
2161    }
2162
2163    #[test]
2164    fn hidden_text_parts_stay_out_of_the_draw_plan() {
2165        let cached = vec![cached_part_stub(0, -1, ssab::ssab::ss::format::PartType::PartTypeText, false)];
2166        let mut state = make_stage_b_state(-1, (10.0, 10.0), (0.0, 0.0), UpdateAttributeFlags::empty());
2167        state.set_hide(true);
2168        let mut fb = flatbuffers::FlatBufferBuilder::new();
2169        let (mut draw_order, mut batches, mut mask_indices) = (Vec::new(), Vec::new(), Vec::new());
2170        build_draw_order_and_batches(&mut fb, &[0], &cached, &[state], &[0], &NinesBuffers::default(), &mut draw_order, &mut batches, &mut mask_indices);
2171
2172        assert!(draw_order.is_empty() && batches.is_empty() && mask_indices.is_empty());
2173    }
2174}