Skip to main content

ssruntime/eval/
geometry.rs

1use crate::eval::SsMatrix4x4;
2use wide::f32x4;
3
4/// Computes the local vertices for a part, including pivot calculation and deformations.
5/// Utilizes SIMD via the `wide` crate for maximum performance.
6/// Returns a tuple containing the x and y coordinates of the 5 vertices.
7pub fn compute_local_vertices(size: (f32, f32), pivot: (f32, f32), pivot_offset: (f32, f32), flip: (bool, bool), deform: Option<(&[f32; 4], &[f32; 4])>) -> ([f32; 5], [f32; 5]) {
8    // 1. Pivot Calculation
9    let cpx = if flip.0 { 1.0 - (pivot.0 + 0.5) } else { pivot.0 + 0.5 };
10    let p_x = (cpx + pivot_offset.0) * size.0;
11
12    let cpy = if flip.1 { 1.0 - (-pivot.1 + 0.5) } else { -pivot.1 + 0.5 };
13    let p_y = (cpy - pivot_offset.1) * size.1;
14
15    let sx = -p_x;
16    let ex = sx + size.0;
17    let sy = p_y;
18    let ey = sy - size.1;
19
20    // 2. Base 4 coordinates (Z order: LU, RU, LD, RD)
21    let mut vx = f32x4::from([sx, ex, sx, ex]);
22    let mut vy = f32x4::from([sy, sy, ey, ey]);
23
24    // 3. Add Deform offsets, then 4. the 5th center vertex — the mean of the
25    //    four corners (Varignon's theorem). Undeformed, the quad is still the
26    //    axis-aligned box, so its centre is analytic and the two horizontal
27    //    reductions are skipped entirely on the common (no-deform) path.
28    let (cx, cy) = if let Some((dx_arr, dy_arr)) = deform {
29        vx += f32x4::from(*dx_arr);
30        vy += f32x4::from(*dy_arr);
31        (vx.reduce_add() * 0.25, vy.reduce_add() * 0.25)
32    } else {
33        ((sx + ex) * 0.5, (sy + ey) * 0.5)
34    };
35
36    let vx_arr: [f32; 4] = vx.to_array();
37    let vy_arr: [f32; 4] = vy.to_array();
38
39    ([vx_arr[0], vx_arr[1], vx_arr[2], vx_arr[3], cx], [vy_arr[0], vy_arr[1], vy_arr[2], vy_arr[3], cy])
40}
41
42/// `Some((tan(skew_x), tan(skew_y)))` when a part's Skew must be applied as a
43/// local-vertex shear, or `None` when there is no skew or when Skew runs in
44/// propagate mode (folded into the world matrix instead). See
45/// [`crate::eval::SKEW_PROPAGATES`]. Angles are in degrees.
46#[inline]
47#[must_use]
48pub fn skew_local_tans(skew_x_deg: f32, skew_y_deg: f32) -> Option<(f32, f32)> {
49    if crate::eval::SKEW_PROPAGATES || (skew_x_deg == 0.0 && skew_y_deg == 0.0) {
50        return None;
51    }
52    let r = core::f32::consts::PI / 180.0;
53    Some((crate::eval::math::tanf(skew_x_deg * r), crate::eval::math::tanf(skew_y_deg * r)))
54}
55
56/// Shears one local-space vertex about the pivot origin, in the part's Y-up
57/// authored space — callers apply the Y-down flip afterwards, exactly as they
58/// do for the 4-corner Vertex deform, so the sign matches that path. `tan_x` /
59/// `tan_y` come from [`skew_local_tans`]. This is the same shear the world
60/// matrix applies in propagate mode: `(x, y) -> (x + tan_x·y, y + tan_y·x)`.
61#[inline]
62#[must_use]
63pub fn skew_point_yup(x: f32, y: f32, tan_x: f32, tan_y: f32) -> (f32, f32) {
64    (x + tan_x * y, y + tan_y * x)
65}
66
67/// Computes the local UV coordinates for a part, including UV animation (translate, rotate, scale) and flipping.
68/// Returns a tuple containing the u and v coordinates for the 5 vertices.
69pub fn compute_local_uvs(
70    uv_rect: (f32, f32, f32, f32),      // (left, top, right, bottom)
71    uv_anim: (f32, f32, f32, f32, f32), // (trans_u, trans_v, rot_deg, scale_u, scale_v)
72    part_flip: (bool, bool),            // (h_flip, v_flip)
73    image_flip: (bool, bool),           // (img_flip_h, img_flip_v)
74    rotated: bool,                      // is the cell rotated?
75) -> ([f32; 5], [f32; 5]) {
76    let (left, top, right, bottom) = uv_rect;
77    let (tu, tv, rot_deg, su, sv) = uv_anim;
78
79    let hw = (right - left) * 0.5;
80    let hh = (bottom - top) * 0.5;
81
82    let center_u = left + hw;
83    let center_v = top + hh;
84
85    let su_scaled = su * if image_flip.0 { -1.0 } else { 1.0 } * hw;
86    let sv_scaled = sv * if image_flip.1 { -1.0 } else { 1.0 } * hh;
87
88    let fx = if part_flip.0 { -1.0 } else { 1.0 };
89    let fy = if part_flip.1 { -1.0 } else { 1.0 };
90
91    let rot_rad = rot_deg * core::f32::consts::PI / 180.0;
92    // Most parts never rotate their UVs, and sin and cos of ±0 are ±0 and 1.
93    let (sin_r, cos_r) = if rot_rad == 0.0 { (rot_rad, 1.0) } else { crate::eval::math::sincosf(rot_rad) };
94
95    let ou = center_u + tu;
96    let ov = center_v + tv;
97
98    // 2D affine entries laid out as
99    //   [ m00  m01 ] [ x ]   [ u - ou ]
100    //   [ m10  m11 ] [ y ] = [ v - ov ]
101    let (m00, m10, m01, m11) = if !rotated { (cos_r * su_scaled * fx, sin_r * su_scaled * fx, -sin_r * sv_scaled * fy, cos_r * sv_scaled * fy) } else { (sin_r * sv_scaled * fx, -cos_r * sv_scaled * fx, cos_r * su_scaled * fy, sin_r * su_scaled * fy) };
102
103    let x = f32x4::from([-1.0, 1.0, -1.0, 1.0]);
104    let y = f32x4::from([-1.0, -1.0, 1.0, 1.0]);
105
106    let u_simd = f32x4::splat(m00).mul_add(x, f32x4::splat(m01).mul_add(y, f32x4::splat(ou)));
107    let v_simd = f32x4::splat(m10).mul_add(x, f32x4::splat(m11).mul_add(y, f32x4::splat(ov)));
108
109    let u_arr: [f32; 4] = u_simd.to_array();
110    let v_arr: [f32; 4] = v_simd.to_array();
111
112    ([u_arr[0], u_arr[1], u_arr[2], u_arr[3], ou], [v_arr[0], v_arr[1], v_arr[2], v_arr[3], ov])
113}
114
115/// Performs a hit test for a point against a rectangle in local space.
116/// The point is expected to be already transformed into local space (using inverse matrix).
117pub fn is_point_in_rect(local_p: (f32, f32), size: (f32, f32)) -> bool {
118    let hw = size.0 * 0.5;
119    let hh = size.1 * 0.5;
120    local_p.0 >= -hw && local_p.0 <= hw && local_p.1 >= -hh && local_p.1 <= hh
121}
122
123/// Performs a hit test for a point against a 4-point quadrilateral in world space.
124/// Uses the even-odd rule (ray casting) algorithm and SIMD via the `wide` crate to support both convex and concave quadrilaterals efficiently.
125///
126/// A point exactly on an edge is inside when the quad lies on the edge's +x
127/// side, or on its +y side for an edge parallel to the x axis: on an
128/// axis-aligned quad, the left edge and the edge at the smaller y (the top one
129/// in Y-down coordinates) are inside, and the right edge and the edge at the
130/// larger y are outside. [`is_point_in_rect`] counts all four edges as inside.
131/// On a slanted edge the crossing is computed with rounding, so a point on it
132/// can fall either way.
133pub fn is_point_in_quad(target_p: (f32, f32), v_x: &[f32; 4], v_y: &[f32; 4]) -> bool {
134    let tp_x = f32x4::splat(target_p.0);
135    let tp_y = f32x4::splat(target_p.1);
136
137    // Indices for LU(0) -> RU(1) -> RD(3) -> LD(2) loop
138    let x0 = f32x4::from([v_x[0], v_x[1], v_x[3], v_x[2]]);
139    let y0 = f32x4::from([v_y[0], v_y[1], v_y[3], v_y[2]]);
140    let x1 = f32x4::from([v_x[1], v_x[3], v_x[2], v_x[0]]);
141    let y1 = f32x4::from([v_y[1], v_y[3], v_y[2], v_y[0]]);
142
143    // Ray casting to the right (+x direction)
144    // Condition 1: (y0 > target_p.1) != (y1 > target_p.1)
145    let y0_gt = y0.simd_gt(tp_y);
146    let y1_gt = y1.simd_gt(tp_y);
147    let y_cond = y0_gt ^ y1_gt;
148
149    // Condition 2: target_p.0 < intersect_x
150    // intersect_x = x0 + (target_p.1 - y0) * (x1 - x0) / (y1 - y0)
151    let dx = x1 - x0;
152    let dy = y1 - y0;
153    let intersect_x = x0 + (tp_y - y0) * dx / dy;
154    let x_cond = tp_x.simd_lt(intersect_x);
155
156    let inside_mask = y_cond & x_cond;
157
158    // Using wide's to_bitmask, we get a 4-bit integer where each bit represents a lane.
159    let intersections = inside_mask.to_bitmask().count_ones();
160
161    (intersections & 1) != 0
162}
163
164/// Fill mode of a Nine-Slice part (`PartTypeNines.nines_fill_mode`), mirroring
165/// `SsNines::m_eFillMode` in the SpriteStudio SDK.
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
167pub enum NinesFillMode {
168    /// `0` — the four edges and the centre are stretched to fill the part.
169    #[default]
170    Stretch,
171    /// `1` — the four edges and the centre repeat the source slice at its
172    /// native pixel size; the repeat that overflows the region is clipped.
173    Tile,
174}
175
176impl NinesFillMode {
177    pub fn from_i32(value: i32) -> Self {
178        match value {
179            1 => Self::Tile,
180            _ => Self::Stretch,
181        }
182    }
183}
184
185/// Runaway guard for [`emit_nines_geometry`]: repeats per axis are clamped to
186/// this, and a centre whose repeat count exceeds [`NINES_MAX_TILE_QUADS`] falls
187/// back to a single stretched quad. Authored content never reaches either — a
188/// 4096 px part filled by a 16 px source slice needs 256 repeats — they only
189/// stop degenerate data (a near-zero source slice) from exhausting memory.
190pub const NINES_MAX_TILE_DIV: i32 = 4096;
191/// Companion to [`NINES_MAX_TILE_DIV`] for the two-axis centre region.
192pub const NINES_MAX_TILE_QUADS: i64 = 1 << 16;
193
194/// Shrinks two opposing margins that together exceed the source extent so the
195/// middle slice never inverts — `SsNines::updateSafeMargin`. The overlap is
196/// split in half with the odd pixel charged to the far side, matching the SDK's
197/// integer division.
198#[inline]
199fn shrink_opposing_margins(near: f32, far: f32, extent: f32) -> (f32, f32) {
200    let diff = near + far - extent;
201    if diff <= 0.0 {
202        return (near, far);
203    }
204    let half = crate::eval::math::floorf(diff * 0.5);
205    (near - half, far - (diff - half))
206}
207
208/// Clamps a part's authored margins against the source cell so opposing
209/// margins never overlap. Margins are `(left, top, right, bottom)`.
210pub fn nines_safe_margins(margins: (f32, f32, f32, f32), source_size: (f32, f32)) -> (f32, f32, f32, f32) {
211    let (ml, mt, mr, mb) = margins;
212    let (sw, sh) = source_size;
213    let (sml, smr) = shrink_opposing_margins(ml, mr, sw);
214    let (smt, smb) = shrink_opposing_margins(mt, mb, sh);
215    (sml, smt, smr, smb)
216}
217
218/// The four slice lines of a Nine-Slice part — `SsNines::updatePoints`.
219///
220/// `x` / `y` are box fractions (`0` = left / top edge, `1` = right / bottom
221/// edge) so the caller can place them inside whatever local-space box the
222/// pivot produced; `u` / `v` are cellmap texture-pixel coordinates.
223#[derive(Debug, Clone, Copy, PartialEq)]
224pub struct NineSliceLines {
225    pub x: [f32; 4],
226    pub y: [f32; 4],
227    pub u: [f32; 4],
228    pub v: [f32; 4],
229}
230
231/// Computes the slice lines for a Nine-Slice part.
232/// `size`: (width, height) of the part — must be non-zero.
233/// `cell_rect`: (left, top, right, bottom) of the source cell, in texture pixels.
234/// `margins`: (left, top, right, bottom) authored margins, in source pixels.
235pub fn compute_nineslice_lines(size: (f32, f32), cell_rect: (f32, f32, f32, f32), margins: (f32, f32, f32, f32)) -> NineSliceLines {
236    let (w, h) = size;
237    let (rl, rt, rr, rb) = cell_rect;
238    let (sml, smt, smr, smb) = nines_safe_margins(margins, (rr - rl, rb - rt));
239
240    NineSliceLines { x: [0.0, sml / w, 1.0 - smr / w, 1.0], y: [0.0, smt / h, 1.0 - smb / h, 1.0], u: [rl, rl + sml, rr - smr, rr], v: [rt, rt + smt, rb - smb, rb] }
241}
242
243/// Appends one quad. `vertex_base` is the part's first vertex in `out_box`, so
244/// the emitted indices stay local to the part's range.
245#[inline]
246fn push_nines_quad(vertex_base: usize, out_box: &mut alloc::vec::Vec<f32>, out_uv: &mut alloc::vec::Vec<f32>, out_idx: &mut alloc::vec::Vec<i32>, x: (f32, f32), y: (f32, f32), u: (f32, f32), v: (f32, f32)) {
247    let base = (out_box.len() / 2 - vertex_base) as i32;
248    // LT, RT, LB, RB — the corner order `compute_local_vertices` uses.
249    out_box.extend_from_slice(&[x.0, y.0, x.1, y.0, x.0, y.1, x.1, y.1]);
250    out_uv.extend_from_slice(&[u.0, v.0, u.1, v.0, u.0, v.1, u.1, v.1]);
251    out_idx.extend_from_slice(&[base, base + 1, base + 2, base + 2, base + 1, base + 3]);
252}
253
254/// Number of whole-or-partial repeats covering `dst` with a `src`-sized slice,
255/// clamped by [`NINES_MAX_TILE_DIV`]. `0` when the region has no extent.
256#[inline]
257fn nines_tile_div(dst: f32, src: f32) -> i32 {
258    if dst <= 0.0 || src <= 0.0 {
259        return 0;
260    }
261    let div = crate::eval::math::ceilf(dst / src);
262    if div >= NINES_MAX_TILE_DIV as f32 { NINES_MAX_TILE_DIV } else { div as i32 }
263}
264
265/// Appends one Nine-Slice part's geometry to the output buffers, ported from
266/// `SsNines::createStretchPolygon` / `createTilePolygon`.
267///
268/// `out_box` receives interleaved box coordinates `(fx, fy)` — `0` at the left
269/// / top edge, `1` at the right / bottom — which the caller maps into the
270/// part's local-space box (and reuses to interpolate the four PartColor
271/// corners). `out_uv` receives interleaved texture-pixel UVs, `out_idx`
272/// triangle indices local to this part's vertex range. Returns
273/// `(vertex_count, index_count)`.
274///
275/// Tiling anchors the repeats the way the SDK does: horizontally from the left
276/// edge of each region and vertically from its bottom edge, so the clipped
277/// partial repeat lands on the right and at the top.
278pub fn emit_nines_geometry(
279    size: (f32, f32),
280    cell_rect: (f32, f32, f32, f32),
281    margins: (f32, f32, f32, f32),
282    fill_mode: NinesFillMode,
283    out_box: &mut alloc::vec::Vec<f32>,
284    out_uv: &mut alloc::vec::Vec<f32>,
285    out_idx: &mut alloc::vec::Vec<i32>,
286) -> (u32, u32) {
287    let lines = compute_nineslice_lines(size, cell_rect, margins);
288    let vertex_base = out_box.len() / 2;
289    let index_base = out_idx.len();
290
291    match fill_mode {
292        NinesFillMode::Stretch => {
293            for row in 0..4 {
294                for col in 0..4 {
295                    out_box.extend_from_slice(&[lines.x[col], lines.y[row]]);
296                    out_uv.extend_from_slice(&[lines.u[col], lines.v[row]]);
297                }
298            }
299            for row in 0..3i32 {
300                for col in 0..3i32 {
301                    let lt = row * 4 + col;
302                    let (rt, lb, rb) = (lt + 1, lt + 4, lt + 5);
303                    out_idx.extend_from_slice(&[lt, rt, lb, lb, rt, rb]);
304                }
305            }
306        }
307        NinesFillMode::Tile => emit_nines_tiles(vertex_base, size, &lines, out_box, out_uv, out_idx),
308    }
309
310    (((out_box.len() / 2) - vertex_base) as u32, (out_idx.len() - index_base) as u32)
311}
312
313fn emit_nines_tiles(vertex_base: usize, size: (f32, f32), lines: &NineSliceLines, out_box: &mut alloc::vec::Vec<f32>, out_uv: &mut alloc::vec::Vec<f32>, out_idx: &mut alloc::vec::Vec<i32>) {
314    let (w, h) = size;
315    // Region extents in part-local units: one source pixel tiles as one unit.
316    let (dst_w, dst_h) = ((lines.x[2] - lines.x[1]) * w, (lines.y[2] - lines.y[1]) * h);
317    let (src_w, src_h) = (lines.u[2] - lines.u[1], lines.v[2] - lines.v[1]);
318
319    let div_w = nines_tile_div(dst_w, src_w);
320    let div_h = nines_tile_div(dst_h, src_h);
321
322    // Columns of the horizontal repeat: box fractions plus the clipped `u`.
323    let column = |i: i32| -> (f32, f32, f32) {
324        let x0 = lines.x[1] + (src_w / w) * i as f32;
325        let x1 = x0 + src_w / w;
326        if x1 > lines.x[2] { (x0, lines.x[2], lines.u[2] - (x1 - lines.x[2]) * w) } else { (x0, x1, lines.u[2]) }
327    };
328    // Rows repeat from the bottom edge upwards, so the partial one is on top.
329    let row = |i: i32| -> (f32, f32, f32) {
330        let y1 = lines.y[2] - (src_h / h) * i as f32;
331        let y0 = y1 - src_h / h;
332        if y0 < lines.y[1] { (lines.y[1], y1, lines.v[2] - (y1 - lines.y[1]) * h) } else { (y0, y1, lines.v[1]) }
333    };
334
335    // Centre.
336    if div_w > 0 && div_h > 0 {
337        if div_w as i64 * div_h as i64 > NINES_MAX_TILE_QUADS {
338            push_nines_quad(vertex_base, out_box, out_uv, out_idx, (lines.x[1], lines.x[2]), (lines.y[1], lines.y[2]), (lines.u[1], lines.u[2]), (lines.v[1], lines.v[2]));
339        } else {
340            for iy in 0..div_h {
341                let (y0, y1, v0) = row(iy);
342                for ix in 0..div_w {
343                    let (x0, x1, u1) = column(ix);
344                    push_nines_quad(vertex_base, out_box, out_uv, out_idx, (x0, x1), (y0, y1), (lines.u[1], u1), (v0, lines.v[2]));
345                }
346            }
347        }
348    }
349
350    // Top / bottom edges tile horizontally, left / right edges vertically.
351    for ix in 0..div_w {
352        let (x0, x1, u1) = column(ix);
353        push_nines_quad(vertex_base, out_box, out_uv, out_idx, (x0, x1), (lines.y[0], lines.y[1]), (lines.u[1], u1), (lines.v[0], lines.v[1]));
354        push_nines_quad(vertex_base, out_box, out_uv, out_idx, (x0, x1), (lines.y[2], lines.y[3]), (lines.u[1], u1), (lines.v[2], lines.v[3]));
355    }
356    for iy in 0..div_h {
357        let (y0, y1, v0) = row(iy);
358        push_nines_quad(vertex_base, out_box, out_uv, out_idx, (lines.x[0], lines.x[1]), (y0, y1), (lines.u[0], lines.u[1]), (v0, lines.v[2]));
359        push_nines_quad(vertex_base, out_box, out_uv, out_idx, (lines.x[2], lines.x[3]), (y0, y1), (lines.u[2], lines.u[3]), (v0, lines.v[2]));
360    }
361
362    // Corners never repeat.
363    for c in [0usize, 2] {
364        for r in [0usize, 2] {
365            push_nines_quad(vertex_base, out_box, out_uv, out_idx, (lines.x[c], lines.x[c + 1]), (lines.y[r], lines.y[r + 1]), (lines.u[c], lines.u[c + 1]), (lines.v[r], lines.v[r + 1]));
366        }
367    }
368}
369
370/// Primitive shape types supported by Shape Parts.
371#[derive(Debug, Clone, Copy, PartialEq, Eq)]
372#[repr(i32)]
373pub enum ShapeType {
374    Rectangle = 0,
375    Triangle = 1,
376    Star = 2,
377    Arrow = 3,
378}
379
380/// Spreads the four box-corner vertex-deform offsets across an arbitrary
381/// point inside the part's bounding box by bilinear interpolation.
382///
383/// `dx`/`dy` are the per-corner offsets in `[LT, RT, LB, RB]` order (the same
384/// layout produced by `compute_local_vertices`'s 4-corner deform). `(fx, fy)`
385/// are the point's box coordinates with `fx = 0` at the left edge / `fy = 0`
386/// at the top edge, matching `shape_vertex_box_coords` and the renderer's
387/// per-corner PartColor weighting. Returns the interpolated `(dx, dy)` offset.
388#[inline]
389pub fn bilinear_box_deform(dx: &[f32; 4], dy: &[f32; 4], fx: f32, fy: f32) -> (f32, f32) {
390    let w_lt = (1.0 - fx) * (1.0 - fy);
391    let w_rt = fx * (1.0 - fy);
392    let w_lb = (1.0 - fx) * fy;
393    let w_rb = fx * fy;
394    (dx[0] * w_lt + dx[1] * w_rt + dx[2] * w_lb + dx[3] * w_rb, dy[0] * w_lt + dy[1] * w_rt + dy[2] * w_lb + dy[3] * w_rb)
395}
396
397/// Computes local vertices for a primitive shape.
398/// Returns the number of vertices and the coordinates.
399pub fn compute_shape_vertices(shape_type: ShapeType, size: (f32, f32)) -> (usize, [f32; 16], [f32; 16]) {
400    let (w, h) = size;
401    let hw = w * 0.5;
402    let hh = h * 0.5;
403
404    let mut out_x = [0.0; 16];
405    let mut out_y = [0.0; 16];
406
407    let count = match shape_type {
408        ShapeType::Rectangle => {
409            // Center + 4 corners (perimeter winding) + closing vertex — a
410            // TRIANGLE_FAN layout matching Triangle and Star. A deformed or
411            // per-corner-coloured rectangle then interpolates from its center
412            // (4 triangles) instead of across a single diagonal seam
413            // (2 triangles), which is what SpriteStudio does.
414            out_x[0] = 0.0;
415            out_y[0] = 0.0;
416            out_x[1..6].copy_from_slice(&[-hw, hw, hw, -hw, -hw]);
417            out_y[1..6].copy_from_slice(&[hh, hh, -hh, -hh, hh]);
418            6
419        }
420        ShapeType::Triangle => {
421            // Center + 3 points
422            out_x[0] = 0.0;
423            out_y[0] = 0.0;
424
425            // Angles: 0, 120, 240 degrees in radians
426            const DEG120_RAD: f32 = 120.0 * core::f32::consts::PI / 180.0;
427            let rads = f32x4::from([0.0, DEG120_RAD, DEG120_RAD * 2.0, 0.0]);
428            let (s, c) = rads.sin_cos();
429
430            let vx = s * hw;
431            let vy = c * hh;
432
433            out_x[1..5].copy_from_slice(&vx.to_array());
434            out_y[1..5].copy_from_slice(&vy.to_array());
435
436            out_x[4] = out_x[1]; // Close the fan
437            out_y[4] = out_y[1];
438            5
439        }
440        ShapeType::Star => {
441            // Center + 10 perimeter points (5 tips, 5 inner corners) + closing vertex
442            // (so a TRIANGLE_FAN consumer gets all 10 wedges).
443            out_x[0] = 0.0;
444            out_y[0] = 0.0;
445
446            let hw_simd = f32x4::splat(hw);
447            let hh_simd = f32x4::splat(hh);
448            let r_scale = f32x4::from([1.0, 0.382, 1.0, 0.382]);
449
450            for i in (0..10).step_by(4) {
451                let idx = f32x4::from([i as f32, (i + 1) as f32, (i + 2) as f32, (i + 3) as f32]);
452                let rad = idx * (36.0 * core::f32::consts::PI / 180.0);
453                let (s, c) = rad.sin_cos();
454
455                let vx = s * hw_simd * r_scale;
456                let vy = c * hh_simd * r_scale;
457
458                let end = (i + 1 + 4).min(11);
459                let len = end - (i + 1);
460                let vx_arr = vx.to_array();
461                let vy_arr = vy.to_array();
462                out_x[i + 1..end].copy_from_slice(&vx_arr[..len]);
463                out_y[i + 1..end].copy_from_slice(&vy_arr[..len]);
464            }
465            out_x[11] = out_x[1];
466            out_y[11] = out_y[1];
467            12
468        }
469        ShapeType::Arrow => {
470            let sx = hw * 0.5;
471            let sy = 0.0;
472            // 7 points
473            out_x[0..7].copy_from_slice(&[-sx / 2.0, sx / 2.0, sx / 2.0, hw, 0.0, -hw, -sx / 2.0]);
474            out_y[0..7].copy_from_slice(&[-hh, -hh, sy, sy, hh, sy, sy]);
475            7
476        }
477    };
478
479    (count, out_x, out_y)
480}
481
482/// Optional per-frame deform delta passed to [`compute_skinned_mesh_vertices`].
483///
484/// Tuple layout: `(changed_vertex_indices, delta_x, delta_y, part_world_matrix)`.
485/// `changed_vertex_indices[k]` selects which output vertex receives `(delta_x[k], delta_y[k])`.
486pub type SkinnedMeshDeform<'a> = (&'a [i16], &'a [f32], &'a [f32], &'a SsMatrix4x4);
487
488/// Computes skinned (bone-weighted) mesh vertex positions in world space.
489///
490/// For each vertex `v`:
491/// 1. **Skeletal** — accumulate `Σ bone_world_matrices[bone_indices[i]] · (coords_x[i], coords_y[i]) · weights[i]`
492///    over the CSR influence slice `influence_offsets[v]..influence_offsets[v + 1]`.
493///    Translation IS applied (MultiplyPoint3x4 — the `m[12]`, `m[13]` terms).
494/// 2. **Deform delta** (optional) — for each entry in `deform.0`, add
495///    `part_world_mat · (delta_x, delta_y)` (rotation/scale only — MultiplyVector).
496///
497/// Bone indices are expected to be pre-resolved to **part indices** by ssconverter;
498/// no further `TableIDPartsBone` lookup is performed at runtime.
499///
500/// Layout: CSR for `influence_offsets`, SoA for `weights`/`coords_x`/`coords_y`.
501/// Vectorized **across vertices**, four at a time, mirroring
502/// [`compute_rigid_mesh_vertices`]: each `f32x4` lane owns one vertex and the
503/// influence slots are walked lane-wise, so the accumulators never leave the
504/// lanes and no horizontal reduction is performed. Lanes whose vertex has run
505/// out of influences contribute weight `0.0`, which makes ragged influence
506/// counts fall out of the same loop — there is no separate >4-influence path.
507/// Vectorizing the influence axis instead would cost two `reduce_add`s per
508/// vertex, which dominates for the 1–2 influence counts SS data actually
509/// contains.
510///
511/// `flip_y` negates the bind `coords_y`. SSAB-side bind coordinates are authored
512/// Y-up; set `flip_y` when the bone world matrices are Y-down so the bind-pose
513/// invariant (each influence resolves to the same rest position) holds.
514///
515/// Skins exactly `out_x.len()` vertices from the front of the binding. The SpriteStudio
516/// meshList appends 4 unbound placeholder vertices (the cell-quad corners) after
517/// the rendered mesh, so `influence_offsets` may be longer than `out_x.len() + 1`;
518/// the trailing entries are simply never read.
519pub fn compute_skinned_mesh_vertices(
520    influence_offsets: &[u32],
521    bone_indices: &[u16],
522    weights: &[f32],
523    coords_x: &[f32],
524    coords_y: &[f32],
525    bone_world_matrices: &[SsMatrix4x4],
526    deform: Option<SkinnedMeshDeform<'_>>,
527    flip_y: bool,
528    out_x: &mut [f32],
529    out_y: &mut [f32],
530) {
531    let num_vertices = out_x.len();
532    debug_assert_eq!(out_y.len(), num_vertices);
533    debug_assert!(influence_offsets.len() > num_vertices);
534
535    // Bind coords are authored Y-up; negate for a Y-down target. Resolved once
536    // and applied as a sign multiply (SIMD in the fast path) — no per-influence
537    // branch.
538    let y_sign = if flip_y { -1.0f32 } else { 1.0f32 };
539    let y_sign_v = f32x4::from([y_sign; 4]);
540
541    // 1. Skeletal: per-vertex weighted bone transform sum (MultiplyPoint3x4 — translation included).
542    //
543    // SIMD body: 4 vertices per iteration, one per lane. `max_slots` is the
544    // widest influence count in the group; lanes that run out early gather
545    // weight 0.0 and so contribute nothing. Real SS meshes are near-uniform
546    // (almost always all-1 or all-2), so the group rarely does excess work.
547    let chunks = num_vertices / 4;
548    for c in 0..chunks {
549        let b = c * 4;
550        // `influence_offsets` is CSR, so vertex b+3's end is index b+4 — in
551        // range because the caller guarantees len > num_vertices.
552        let starts = [influence_offsets[b] as usize, influence_offsets[b + 1] as usize, influence_offsets[b + 2] as usize, influence_offsets[b + 3] as usize];
553        let slots = [influence_offsets[b + 1] as usize - starts[0], influence_offsets[b + 2] as usize - starts[1], influence_offsets[b + 3] as usize - starts[2], influence_offsets[b + 4] as usize - starts[3]];
554        let max_slots = slots[0].max(slots[1]).max(slots[2]).max(slots[3]);
555
556        let mut acc_x = f32x4::splat(0.0);
557        let mut acc_y = f32x4::splat(0.0);
558
559        for k in 0..max_slots {
560            let mut w_lanes = [0.0f32; 4];
561            let mut cx_lanes = [0.0f32; 4];
562            let mut cy_lanes = [0.0f32; 4];
563            let mut m0_lanes = [0.0f32; 4];
564            let mut m4_lanes = [0.0f32; 4];
565            let mut m12_lanes = [0.0f32; 4];
566            let mut m1_lanes = [0.0f32; 4];
567            let mut m5_lanes = [0.0f32; 4];
568            let mut m13_lanes = [0.0f32; 4];
569
570            for lane in 0..4 {
571                if k < slots[lane] {
572                    let i = starts[lane] + k;
573                    w_lanes[lane] = weights[i];
574                    cx_lanes[lane] = coords_x[i];
575                    cy_lanes[lane] = coords_y[i];
576                    let mat = &bone_world_matrices[bone_indices[i] as usize];
577                    m0_lanes[lane] = mat.m[0];
578                    m4_lanes[lane] = mat.m[4];
579                    m12_lanes[lane] = mat.m[12];
580                    m1_lanes[lane] = mat.m[1];
581                    m5_lanes[lane] = mat.m[5];
582                    m13_lanes[lane] = mat.m[13];
583                }
584            }
585
586            let w = f32x4::from(w_lanes);
587            let cx = f32x4::from(cx_lanes);
588            let cy = f32x4::from(cy_lanes) * y_sign_v;
589
590            let px = f32x4::from(m0_lanes) * cx + f32x4::from(m4_lanes) * cy + f32x4::from(m12_lanes);
591            let py = f32x4::from(m1_lanes) * cx + f32x4::from(m5_lanes) * cy + f32x4::from(m13_lanes);
592
593            acc_x = px.mul_add(w, acc_x);
594            acc_y = py.mul_add(w, acc_y);
595        }
596
597        out_x[b..b + 4].copy_from_slice(&acc_x.to_array());
598        out_y[b..b + 4].copy_from_slice(&acc_y.to_array());
599    }
600
601    // Scalar tail: the final < 4 vertices.
602    for v in (chunks * 4)..num_vertices {
603        let start = influence_offsets[v] as usize;
604        let end = influence_offsets[v + 1] as usize;
605        let mut acc_x = 0.0f32;
606        let mut acc_y = 0.0f32;
607        for i in start..end {
608            let w = weights[i];
609            let cx = coords_x[i];
610            let cy = coords_y[i] * y_sign;
611            let mat = &bone_world_matrices[bone_indices[i] as usize];
612            acc_x += (mat.m[0] * cx + mat.m[4] * cy + mat.m[12]) * w;
613            acc_y += (mat.m[1] * cx + mat.m[5] * cy + mat.m[13]) * w;
614        }
615        out_x[v] = acc_x;
616        out_y[v] = acc_y;
617    }
618
619    // 2. Deform delta: MultiplyVector — rotation/scale only, NO translation.
620    //    Kept scalar: writes are randomly-indexed (scatter), so SIMD wouldn't help.
621    if let Some((indices, dx, dy, part_mat)) = deform {
622        debug_assert_eq!(dx.len(), indices.len());
623        debug_assert_eq!(dy.len(), indices.len());
624
625        for k in 0..indices.len() {
626            let v = indices[k] as usize;
627            let tx = part_mat.m[0] * dx[k] + part_mat.m[4] * dy[k];
628            let ty = part_mat.m[1] * dx[k] + part_mat.m[5] * dy[k];
629            out_x[v] += tx;
630            out_y[v] += ty;
631        }
632    }
633}
634
635/// Rigidly transforms a Deform-only mesh's rest vertices by the part's world
636/// matrix — `out = W · rest` for every vertex. SoA layout in and out,
637/// computed four vertices at a time with `f32x4`; the contiguous SoA loads
638/// keep the input gather vectorizable. The per-frame deform delta is a sparse
639/// scatter and is applied separately (scalar) by the caller.
640///
641/// `flip_rest_y` negates the rest Y. The rest comes from the cell's
642/// `table_coord_x` / `table_coord_y` (Y-down native), so it flips for a Y-up
643/// target — the opposite of the Y-up-native skinned bind coordinates.
644pub fn compute_rigid_mesh_vertices(rest_x: &[f32], rest_y: &[f32], world: &SsMatrix4x4, flip_rest_y: bool, out_x: &mut [f32], out_y: &mut [f32]) {
645    let count = out_x.len();
646    debug_assert_eq!(out_y.len(), count);
647    debug_assert_eq!(rest_x.len(), count);
648    debug_assert_eq!(rest_y.len(), count);
649
650    let m = &world.m;
651    let m0 = f32x4::from([m[0]; 4]);
652    let m1 = f32x4::from([m[1]; 4]);
653    let m4 = f32x4::from([m[4]; 4]);
654    let m5 = f32x4::from([m[5]; 4]);
655    let m12 = f32x4::from([m[12]; 4]);
656    let m13 = f32x4::from([m[13]; 4]);
657    // Resolved once; applied as a sign multiply (f32x4 in the SIMD body, scalar in the tail).
658    let y_sign = if flip_rest_y { -1.0f32 } else { 1.0f32 };
659    let y_sign_v = f32x4::from([y_sign; 4]);
660
661    // SIMD body: 4 vertices per iteration. `rest_*` are contiguous SoA, so
662    // each lane load is a plain 128-bit read; the output buffers are SoA too.
663    let chunks = count / 4;
664    for c in 0..chunks {
665        let b = c * 4;
666        let rx = f32x4::from([rest_x[b], rest_x[b + 1], rest_x[b + 2], rest_x[b + 3]]);
667        let ry = f32x4::from([rest_y[b], rest_y[b + 1], rest_y[b + 2], rest_y[b + 3]]) * y_sign_v;
668        let ox = m0 * rx + m4 * ry + m12;
669        let oy = m1 * rx + m5 * ry + m13;
670        out_x[b..b + 4].copy_from_slice(&ox.to_array());
671        out_y[b..b + 4].copy_from_slice(&oy.to_array());
672    }
673
674    // Scalar tail: the final < 4 vertices.
675    for v in (chunks * 4)..count {
676        let rx = rest_x[v];
677        let ry = rest_y[v] * y_sign;
678        out_x[v] = m[0] * rx + m[4] * ry + m[12];
679        out_y[v] = m[1] * rx + m[5] * ry + m[13];
680    }
681}
682
683#[cfg(test)]
684mod tests {
685
686    #[test]
687    fn test_is_point_in_rect() {
688        assert!(is_point_in_rect((0.0, 0.0), (100.0, 100.0)));
689        assert!(is_point_in_rect((49.0, -49.0), (100.0, 100.0)));
690        assert!(!is_point_in_rect((51.0, 0.0), (100.0, 100.0)));
691    }
692
693    #[test]
694    fn test_is_point_in_quad() {
695        // Simple 100x100 square vertices in Z-order: LU, RU, LD, RD
696        let vx = [-50.0, 50.0, -50.0, 50.0];
697        let vy = [50.0, 50.0, -50.0, -50.0];
698
699        assert!(is_point_in_quad((0.0, 0.0), &vx, &vy));
700        assert!(is_point_in_quad((45.0, 45.0), &vx, &vy));
701        assert!(!is_point_in_quad((55.0, 0.0), &vx, &vy));
702
703        // Deformed trapezoid
704        let vx2 = [-20.0, 20.0, -50.0, 50.0];
705        let vy2 = [50.0, 50.0, -50.0, -50.0];
706        assert!(is_point_in_quad((0.0, 0.0), &vx2, &vy2));
707        assert!(is_point_in_quad((15.0, 45.0), &vx2, &vy2));
708        assert!(!is_point_in_quad((25.0, 45.0), &vx2, &vy2));
709    }
710
711    #[test]
712    fn test_compute_local_uvs_basic() {
713        let rect = (0.0, 0.0, 1.0, 1.0);
714        let anim = (0.0, 0.0, 0.0, 1.0, 1.0);
715        let (u, v) = compute_local_uvs(rect, anim, (false, false), (false, false), false);
716        assert_arr_approx_eq(&u, &[0.0, 1.0, 0.0, 1.0], 4);
717        assert_arr_approx_eq(&v, &[0.0, 0.0, 1.0, 1.0], 4);
718    }
719
720    #[test]
721    fn test_compute_local_uvs_part_flip() {
722        let rect = (0.0, 0.0, 1.0, 1.0);
723        let anim = (0.0, 0.0, 0.0, 1.0, 1.0);
724        let (u, v) = compute_local_uvs(rect, anim, (true, false), (false, false), false);
725        assert_arr_approx_eq(&u, &[1.0, 0.0, 1.0, 0.0], 4);
726        assert_arr_approx_eq(&v, &[0.0, 0.0, 1.0, 1.0], 4);
727    }
728
729    use super::*;
730
731    fn assert_approx_eq(a: f32, b: f32) {
732        assert!((a - b).abs() < 1e-4, "{} != {}", a, b);
733    }
734
735    fn assert_arr_approx_eq(a: &[f32], b: &[f32], count: usize) {
736        for i in 0..count {
737            assert_approx_eq(a[i], b[i]);
738        }
739    }
740
741    #[test]
742    fn test_basic_4_vertices() {
743        // Simple 100x100 square, center pivot
744        let size = (100.0, 100.0);
745        let pivot = (0.0, 0.0);
746        let pivot_offset = (0.0, 0.0);
747        let flip = (false, false);
748        let deform = None;
749
750        let (x, y) = compute_local_vertices(size, pivot, pivot_offset, flip, deform);
751        // Expecting LU: (-50, 50), RU: (50, 50), LD: (-50, -50), RD: (50, -50)
752        assert_arr_approx_eq(&x, &[-50.0, 50.0, -50.0, 50.0], 4);
753        assert_arr_approx_eq(&y, &[50.0, 50.0, -50.0, -50.0], 4);
754    }
755
756    #[test]
757    fn test_pivot_offset() {
758        // 100x100 square, center pivot, offset by 0.5 (moves pivot to right/bottom)
759        let size = (100.0, 100.0);
760        let pivot = (0.0, 0.0);
761        let pivot_offset = (0.5, -0.5); // Move pivot right by 50, down by 50
762        let flip = (false, false);
763
764        let (x, y) = compute_local_vertices(size, pivot, pivot_offset, flip, None);
765        // Expecting LU: (-100, 100), RU: (0, 100), LD: (-100, 0), RD: (0, 0)
766        assert_arr_approx_eq(&x, &[-100.0, 0.0, -100.0, 0.0], 4);
767        assert_arr_approx_eq(&y, &[100.0, 100.0, 0.0, 0.0], 4);
768    }
769
770    #[test]
771    fn test_flip_h_v() {
772        // 100x100 square, pivot at top-left (-0.5, 0.5)
773        let size = (100.0, 100.0);
774        let pivot = (-0.5, 0.5);
775        let pivot_offset = (0.0, 0.0);
776
777        // No flip: LU should be (0, 0), RU: (100, 0), LD: (0, -100), RD: (100, -100)
778        let (x1, y1) = compute_local_vertices(size, pivot, pivot_offset, (false, false), None);
779        assert_arr_approx_eq(&x1, &[0.0, 100.0, 0.0, 100.0], 4);
780        assert_arr_approx_eq(&y1, &[0.0, 0.0, -100.0, -100.0], 4);
781
782        // Flip H: pivot effectively moves to top-right
783        let (x2, y2) = compute_local_vertices(size, pivot, pivot_offset, (true, false), None);
784        assert_arr_approx_eq(&x2, &[-100.0, 0.0, -100.0, 0.0], 4);
785        assert_arr_approx_eq(&y2, &[0.0, 0.0, -100.0, -100.0], 4);
786
787        // Flip V: pivot effectively moves to bottom-left
788        let (x3, y3) = compute_local_vertices(size, pivot, pivot_offset, (false, true), None);
789        assert_arr_approx_eq(&x3, &[0.0, 100.0, 0.0, 100.0], 4);
790        assert_arr_approx_eq(&y3, &[100.0, 100.0, 0.0, 0.0], 4);
791    }
792
793    #[test]
794    fn test_deform_addition() {
795        let size = (100.0, 100.0);
796        let pivot = (0.0, 0.0);
797        let deform_x = [10.0, 20.0, 30.0, 40.0];
798        let deform_y = [1.0, 2.0, 3.0, 4.0];
799
800        let (x, y) = compute_local_vertices(size, pivot, (0.0, 0.0), (false, false), Some((&deform_x, &deform_y)));
801        // Original X: [-50, 50, -50, 50] -> [+10, +20, +30, +40]
802        assert_arr_approx_eq(&x, &[-40.0, 70.0, -20.0, 90.0], 4);
803        // Original Y: [50, 50, -50, -50] -> [+1, +2, +3, +4]
804        assert_arr_approx_eq(&y, &[51.0, 52.0, -47.0, -46.0], 4);
805    }
806
807    #[test]
808    fn test_5_vertices_center_calculation() {
809        let size = (100.0, 100.0);
810        let pivot = (0.0, 0.0);
811
812        // A complex deform that makes it an irregular quadrilateral
813        let deform_x = [10.0, -10.0, 20.0, -20.0];
814        let deform_y = [5.0, 15.0, -5.0, -15.0];
815
816        let (x, y) = compute_local_vertices(size, pivot, (0.0, 0.0), (false, false), Some((&deform_x, &deform_y)));
817
818        // Sum of X: (-50+10) + (50-10) + (-50+20) + (50-20) = -40 + 40 - 30 + 30 = 0
819        // Average X = 0
820        assert_approx_eq(x[4], 0.0);
821
822        // Sum of Y: (50+5) + (50+15) + (-50-5) + (-50-15) = 55 + 65 - 55 - 65 = 0
823        // Average Y = 0
824        assert_approx_eq(y[4], 0.0);
825
826        // Let's try an asymmetrical deform
827        let deform_x2 = [100.0, 0.0, 0.0, 0.0];
828        let deform_y2 = [0.0, 100.0, 0.0, 0.0];
829
830        let (x2, y2) = compute_local_vertices(size, pivot, (0.0, 0.0), (false, false), Some((&deform_x2, &deform_y2)));
831
832        // Sum of X: (-50+100) + 50 - 50 + 50 = 50 + 50 - 50 + 50 = 100. Average = 25.0
833        assert_approx_eq(x2[4], 25.0);
834        // Sum of Y: 50 + (50+100) - 50 - 50 = 50 + 150 - 50 - 50 = 100. Average = 25.0
835        assert_approx_eq(y2[4], 25.0);
836    }
837
838    #[test]
839    fn test_vertices_complex_flip_offset() {
840        // 100x100 square, pivot at bottom-right (0.5, -0.5), offset by (0.5, 0.5).
841        let size = (100.0, 100.0);
842        let pivot = (0.5, -0.5);
843        let pivot_offset = (0.5, 0.5);
844        let flip = (true, true); // Double flip
845
846        let (x, y) = compute_local_vertices(size, pivot, pivot_offset, flip, None);
847
848        // With H-Flip: pivot_x becomes 1.0 - (0.5 + 0.5) = 0.0
849        // With V-Flip: pivot_y becomes 1.0 - (0.5 + 0.5) = 0.0
850        // Resulting p_x = (0.0 + 0.5) * 100 = 50
851        // Resulting p_y = (0.0 - 0.5) * 100 = -50
852        // sx = -50, ex = 50, sy = -50, ey = -150
853        assert_approx_eq(x[0], -50.0); // LU
854        assert_approx_eq(y[0], -50.0);
855    }
856
857    #[test]
858    fn test_uvs_full_transform() {
859        let rect = (0.0, 0.0, 1.0, 1.0);
860        // Translate 0.1, Rotate 90deg, Scale 2.0
861        let anim = (0.1, 0.1, 90.0, 2.0, 2.0);
862        let (u, v) = compute_local_uvs(rect, anim, (false, false), (false, false), false);
863
864        // Center is (0.5, 0.5)
865        // LU (0, 0) relative to center is (-0.5, -0.5)
866        // Scale 2.0 -> (-1.0, -1.0)
867        // Rotate 90deg -> (1.0, -1.0)  [x' = -y, y' = x]
868        // Back to origin (0.5, 0.5) -> (1.5, -0.5)
869        // Translate 0.1 -> (1.6, -0.4)
870        assert_approx_eq(u[0], 1.6);
871        assert_approx_eq(v[0], -0.4);
872    }
873
874    #[test]
875    fn test_uvs_zero_rotation_is_what_sincosf_gives() {
876        // compute_local_uvs skips sincosf for a zero rotation.
877        for zero in [0.0f32, -0.0] {
878            let (sin, cos) = crate::eval::math::sincosf(zero);
879            assert_eq!((sin.to_bits(), cos.to_bits()), (zero.to_bits(), 1.0f32.to_bits()));
880        }
881    }
882
883    #[test]
884    fn test_uvs_rotated_cell() {
885        let rect = (0.1, 0.1, 0.5, 0.4); // 0.4x0.3 rect
886        let anim = (0.0, 0.0, 0.0, 1.0, 1.0);
887        let (u, v) = compute_local_uvs(rect, anim, (false, false), (false, false), true);
888
889        // In rotated mode, LU corresponds to (left, bottom) of the rect
890        assert_approx_eq(u[0], 0.1);
891        assert_approx_eq(v[0], 0.4);
892        // RU corresponds to (left, top)
893        assert_approx_eq(u[1], 0.1);
894        assert_approx_eq(v[1], 0.1);
895    }
896
897    #[test]
898    fn test_hit_test_edge_cases() {
899        let vx = [0.0, 10.0, 0.0, 10.0];
900        let vy = [10.0, 10.0, 0.0, 0.0];
901
902        // Inside
903        assert!(is_point_in_quad((5.0, 5.0), &vx, &vy));
904        // Outside
905        assert!(!is_point_in_quad((11.0, 5.0), &vx, &vy));
906        // Exactly on the left edge: the crossing test keeps left / bottom edges, drops right / top
907        assert!(is_point_in_quad((0.0, 5.0), &vx, &vy));
908        // Exactly on vertex
909        assert!(is_point_in_quad((0.0, 0.0), &vx, &vy));
910    }
911
912    #[test]
913    fn test_hit_test_concave_quad() {
914        // Vertices forming a true concave shape (boomerang style)
915        // LU: (0, 10), RU: (2, 2), LD: (0, 0), RD: (10, 0)
916        // This makes RU folded inwards.
917        let vx = [0.0, 2.0, 0.0, 10.0];
918        let vy = [10.0, 2.0, 0.0, 0.0];
919
920        // Inside the top arm
921        assert!(is_point_in_quad((1.0, 5.0), &vx, &vy));
922        // Inside the bottom arm
923        assert!(is_point_in_quad((5.0, 1.0), &vx, &vy));
924
925        // Outside, in the concave notch (right side of the fold)
926        assert!(!is_point_in_quad((5.0, 5.0), &vx, &vy));
927        // Outside, entirely to the right
928        assert!(!is_point_in_quad((11.0, 5.0), &vx, &vy));
929    }
930
931    #[test]
932    fn test_compute_nineslice_lines() {
933        let lines = compute_nineslice_lines((100.0, 100.0), (0.0, 0.0, 100.0, 100.0), (10.0, 10.0, 10.0, 10.0));
934
935        // Box fractions: the margins occupy a tenth of the part on each side.
936        assert_approx_eq(lines.x[0], 0.0);
937        assert_approx_eq(lines.x[1], 0.1);
938        assert_approx_eq(lines.x[2], 0.9);
939        assert_approx_eq(lines.x[3], 1.0);
940        assert_eq!(lines.x, lines.y);
941
942        // UVs stay in texture-pixel space.
943        assert_approx_eq(lines.u[0], 0.0);
944        assert_approx_eq(lines.u[1], 10.0);
945        assert_approx_eq(lines.u[2], 90.0);
946        assert_approx_eq(lines.u[3], 100.0);
947        assert_eq!(lines.u, lines.v);
948    }
949
950    #[test]
951    fn test_nines_safe_margins_shrink_overlapping() {
952        // Fits: margins are returned untouched.
953        assert_eq!(nines_safe_margins((10.0, 10.0, 10.0, 10.0), (64.0, 64.0)), (10.0, 10.0, 10.0, 10.0));
954
955        // 40 + 30 over a 60 px source overlaps by 10, split evenly.
956        let (l, _, r, _) = nines_safe_margins((40.0, 0.0, 30.0, 0.0), (60.0, 100.0));
957        assert_approx_eq(l, 35.0);
958        assert_approx_eq(r, 25.0);
959
960        // An odd overlap charges the extra pixel to the far side, matching the
961        // SDK's integer division.
962        let (l, _, r, _) = nines_safe_margins((40.0, 0.0, 25.0, 0.0), (60.0, 100.0));
963        assert_approx_eq(l, 38.0);
964        assert_approx_eq(r, 22.0);
965    }
966
967    #[test]
968    fn test_emit_nines_stretch() {
969        let (mut b, mut uv, mut idx) = (alloc::vec::Vec::new(), alloc::vec::Vec::new(), alloc::vec::Vec::new());
970        let (vc, ic) = emit_nines_geometry((100.0, 100.0), (0.0, 0.0, 100.0, 100.0), (10.0, 10.0, 10.0, 10.0), NinesFillMode::Stretch, &mut b, &mut uv, &mut idx);
971
972        // A shared 4x4 grid: 16 vertices, 9 quads.
973        assert_eq!((vc, ic), (16, 54));
974        assert_eq!(b.len(), 32);
975        assert_eq!(idx.len(), 54);
976
977        // Row-major from the top-left corner.
978        assert_approx_eq(b[0], 0.0);
979        assert_approx_eq(b[1], 0.0);
980        assert_approx_eq(uv[0], 0.0);
981        assert_approx_eq(uv[1], 0.0);
982        // Vertex (1, 1) — the inner corner of the top-left slice.
983        assert_approx_eq(b[10], 0.1);
984        assert_approx_eq(b[11], 0.1);
985        assert_approx_eq(uv[10], 10.0);
986        assert_approx_eq(uv[11], 10.0);
987        // First quad, wound LT, RT, LB / LB, RT, RB.
988        assert_eq!(&idx[0..6], &[0, 1, 4, 4, 1, 5]);
989    }
990
991    #[test]
992    fn test_emit_nines_tile_repeats_and_clips() {
993        let (mut b, mut uv, mut idx) = (alloc::vec::Vec::new(), alloc::vec::Vec::new(), alloc::vec::Vec::new());
994        // A 64 px cell with 16 px margins leaves a 32 px middle slice, which
995        // covers the part's 68 px middle in ceil(68 / 32) = 3 repeats per axis.
996        let (vc, ic) = emit_nines_geometry((100.0, 100.0), (0.0, 0.0, 64.0, 64.0), (16.0, 16.0, 16.0, 16.0), NinesFillMode::Tile, &mut b, &mut uv, &mut idx);
997
998        // 4 corners + 2 * 3 horizontal edges + 2 * 3 vertical + 3 * 3 centre.
999        let quads = 4 + 2 * 3 + 2 * 3 + 3 * 3;
1000        assert_eq!((vc, ic), (quads * 4, quads * 6));
1001
1002        // Centre repeat (0, 0): full slice, anchored at the region's bottom.
1003        assert_approx_eq(b[0], 0.16);
1004        assert_approx_eq(b[1], 0.52);
1005        assert_approx_eq(uv[0], 16.0);
1006        assert_approx_eq(uv[1], 16.0);
1007        assert_approx_eq(b[7], 0.84); // RB.y — the bottom edge of the middle
1008        assert_approx_eq(uv[7], 48.0);
1009
1010        // Centre repeat (2, 0): overflows to the right, so it is clipped to the
1011        // region edge and its UV is cut to the 4 px that remain.
1012        let (bq, uq) = (&b[2 * 8..3 * 8], &uv[2 * 8..3 * 8]);
1013        assert_approx_eq(bq[0], 0.80);
1014        assert_approx_eq(bq[2], 0.84);
1015        assert_approx_eq(uq[0], 16.0);
1016        assert_approx_eq(uq[2], 20.0);
1017
1018        // The vertical partial repeat lands at the top of the region.
1019        let (bq, uq) = (&b[6 * 8..7 * 8], &uv[6 * 8..7 * 8]);
1020        assert_approx_eq(bq[1], 0.16);
1021        assert_approx_eq(bq[5], 0.20);
1022        assert_approx_eq(uq[1], 44.0);
1023        assert_approx_eq(uq[5], 48.0);
1024    }
1025
1026    #[test]
1027    fn test_emit_nines_tile_clamps_degenerate_repeats() {
1028        let (mut b, mut uv, mut idx) = (alloc::vec::Vec::new(), alloc::vec::Vec::new(), alloc::vec::Vec::new());
1029        // Margins that leave a 0.2 px middle slice would need half a million
1030        // repeats to fill a 100000 px part: the per-axis clamp caps the edges
1031        // and the centre falls back to a single stretched quad.
1032        let (vc, ic) = emit_nines_geometry((100_000.0, 100_000.0), (0.0, 0.0, 64.0, 64.0), (31.9, 31.9, 31.9, 31.9), NinesFillMode::Tile, &mut b, &mut uv, &mut idx);
1033
1034        let quads = 4 + 4 * NINES_MAX_TILE_DIV as u32 + 1;
1035        assert_eq!((vc, ic), (quads * 4, quads * 6));
1036        assert!(b.iter().all(|c| c.is_finite()));
1037    }
1038
1039    #[test]
1040    fn test_compute_shape_vertices_rectangle() {
1041        let (count, x, y) = compute_shape_vertices(ShapeType::Rectangle, (100.0, 200.0));
1042        // Center-first TRIANGLE_FAN: [center, LT, RT, RB, LB, LT(closing)].
1043        assert_eq!(count, 6);
1044        assert_approx_eq(x[0], 0.0); // center
1045        assert_approx_eq(y[0], 0.0);
1046        assert_approx_eq(x[1], -50.0); // LT
1047        assert_approx_eq(y[1], 100.0);
1048        assert_approx_eq(x[5], x[1]); // closing vertex repeats LT
1049        assert_approx_eq(y[5], y[1]);
1050    }
1051
1052    #[test]
1053    fn test_bilinear_box_deform_corners() {
1054        // At each box corner the matching deform offset is returned exactly.
1055        let dx = [10.0, 20.0, 30.0, 40.0]; // LT, RT, LB, RB
1056        let dy = [-1.0, -2.0, -3.0, -4.0];
1057        assert_eq!(bilinear_box_deform(&dx, &dy, 0.0, 0.0), (10.0, -1.0)); // LT
1058        assert_eq!(bilinear_box_deform(&dx, &dy, 1.0, 0.0), (20.0, -2.0)); // RT
1059        assert_eq!(bilinear_box_deform(&dx, &dy, 0.0, 1.0), (30.0, -3.0)); // LB
1060        assert_eq!(bilinear_box_deform(&dx, &dy, 1.0, 1.0), (40.0, -4.0)); // RB
1061    }
1062
1063    #[test]
1064    fn test_bilinear_box_deform_center_and_edges() {
1065        let dx = [10.0, 20.0, 30.0, 40.0];
1066        let dy = [0.0, 0.0, 0.0, 0.0];
1067        // Center = mean of the four corners.
1068        let (cx, _) = bilinear_box_deform(&dx, &dy, 0.5, 0.5);
1069        assert_approx_eq(cx, 25.0);
1070        // Top edge midpoint blends LT/RT only.
1071        let (tx, _) = bilinear_box_deform(&dx, &dy, 0.5, 0.0);
1072        assert_approx_eq(tx, 15.0);
1073        // Left edge midpoint blends LT/LB only.
1074        let (lx, _) = bilinear_box_deform(&dx, &dy, 0.0, 0.5);
1075        assert_approx_eq(lx, 20.0);
1076    }
1077
1078    #[test]
1079    fn test_compute_shape_vertices_star_closes_fan() {
1080        let (count, x, y) = compute_shape_vertices(ShapeType::Star, (100.0, 200.0));
1081        assert_eq!(count, 12);
1082        assert_approx_eq(x[0], 0.0);
1083        assert_approx_eq(y[0], 0.0);
1084        assert_approx_eq(x[11], x[1]);
1085        assert_approx_eq(y[11], y[1]);
1086    }
1087
1088    #[test]
1089    fn test_skinned_mesh_identity_single_influence() {
1090        // Two vertices, each with one influence to bone 0 (identity), weight 1.0 →
1091        // output should equal the bind-pose coordinates.
1092        let offsets = [0u32, 1, 2];
1093        let bone_indices = [0u16, 0];
1094        let weights = [1.0f32, 1.0];
1095        let coords_x = [3.0f32, -4.0];
1096        let coords_y = [5.0f32, 7.0];
1097        let bones = [SsMatrix4x4::IDENTITY];
1098
1099        let mut out_x = [0.0f32; 2];
1100        let mut out_y = [0.0f32; 2];
1101
1102        compute_skinned_mesh_vertices(&offsets, &bone_indices, &weights, &coords_x, &coords_y, &bones, None, false, &mut out_x, &mut out_y);
1103
1104        assert_arr_approx_eq(&out_x, &[3.0, -4.0], 2);
1105        assert_arr_approx_eq(&out_y, &[5.0, 7.0], 2);
1106    }
1107
1108    #[test]
1109    fn test_skinned_mesh_translation_applied() {
1110        // MultiplyPoint3x4 must include translation: bone translates (10, 20),
1111        // bind coord (3, 5) → output (13, 25).
1112        let offsets = [0u32, 1];
1113        let bone_indices = [0u16];
1114        let weights = [1.0f32];
1115        let coords_x = [3.0f32];
1116        let coords_y = [5.0f32];
1117        let bones = [SsMatrix4x4::create_translation(10.0, 20.0, 0.0)];
1118
1119        let mut out_x = [0.0f32];
1120        let mut out_y = [0.0f32];
1121
1122        compute_skinned_mesh_vertices(&offsets, &bone_indices, &weights, &coords_x, &coords_y, &bones, None, false, &mut out_x, &mut out_y);
1123
1124        assert_arr_approx_eq(&out_x, &[13.0], 1);
1125        assert_arr_approx_eq(&out_y, &[25.0], 1);
1126    }
1127
1128    #[test]
1129    fn test_skinned_mesh_two_bone_blend() {
1130        // One vertex weighted 50/50 between identity-bone and translated-bone,
1131        // both viewing bind coord (0, 0) → output (50, 0).
1132        let offsets = [0u32, 2];
1133        let bone_indices = [0u16, 1];
1134        let weights = [0.5f32, 0.5];
1135        let coords_x = [0.0f32, 0.0];
1136        let coords_y = [0.0f32, 0.0];
1137        let bones = [SsMatrix4x4::IDENTITY, SsMatrix4x4::create_translation(100.0, 0.0, 0.0)];
1138
1139        let mut out_x = [0.0f32];
1140        let mut out_y = [0.0f32];
1141
1142        compute_skinned_mesh_vertices(&offsets, &bone_indices, &weights, &coords_x, &coords_y, &bones, None, false, &mut out_x, &mut out_y);
1143
1144        assert_arr_approx_eq(&out_x, &[50.0], 1);
1145        assert_arr_approx_eq(&out_y, &[0.0], 1);
1146    }
1147
1148    #[test]
1149    fn test_skinned_mesh_rotation() {
1150        // 90deg Z rotation applied to bone, bind coord (1, 0) → output (0, 1).
1151        let offsets = [0u32, 1];
1152        let bone_indices = [0u16];
1153        let weights = [1.0f32];
1154        let coords_x = [1.0f32];
1155        let coords_y = [0.0f32];
1156        let bones = [SsMatrix4x4::create_rotation_z(core::f32::consts::FRAC_PI_2)];
1157
1158        let mut out_x = [0.0f32];
1159        let mut out_y = [0.0f32];
1160
1161        compute_skinned_mesh_vertices(&offsets, &bone_indices, &weights, &coords_x, &coords_y, &bones, None, false, &mut out_x, &mut out_y);
1162
1163        assert_arr_approx_eq(&out_x, &[0.0], 1);
1164        assert_arr_approx_eq(&out_y, &[1.0], 1);
1165    }
1166
1167    #[test]
1168    fn test_skinned_mesh_deform_delta_ignores_translation() {
1169        // Verifies deform uses MultiplyVector (no translation).
1170        // part_mat = T(1000,1000) * R(90°), delta = (1, 0) →
1171        // skeletal yields (0, 0) (identity bone, zero bind), deform adds R·(1,0) = (0, 1).
1172        let offsets = [0u32, 1];
1173        let bone_indices = [0u16];
1174        let weights = [1.0f32];
1175        let coords_x = [0.0f32];
1176        let coords_y = [0.0f32];
1177        let bones = [SsMatrix4x4::IDENTITY];
1178
1179        let rot = SsMatrix4x4::create_rotation_z(core::f32::consts::FRAC_PI_2);
1180        let trans = SsMatrix4x4::create_translation(1000.0, 1000.0, 0.0);
1181        let part_mat = trans * rot;
1182
1183        let indices = [0i16];
1184        let dx = [1.0f32];
1185        let dy = [0.0f32];
1186
1187        let mut out_x = [0.0f32];
1188        let mut out_y = [0.0f32];
1189
1190        compute_skinned_mesh_vertices(&offsets, &bone_indices, &weights, &coords_x, &coords_y, &bones, Some((&indices, &dx, &dy, &part_mat)), false, &mut out_x, &mut out_y);
1191
1192        assert_arr_approx_eq(&out_x, &[0.0], 1);
1193        assert_arr_approx_eq(&out_y, &[1.0], 1);
1194    }
1195
1196    #[test]
1197    fn test_skinned_mesh_partial_deform() {
1198        // Three vertices, only vertex 1 receives a deform delta;
1199        // vertices 0 and 2 must remain at their skeletal-only positions.
1200        let offsets = [0u32, 1, 2, 3];
1201        let bone_indices = [0u16; 3];
1202        let weights = [1.0f32; 3];
1203        let coords_x = [1.0f32, 2.0, 3.0];
1204        let coords_y = [10.0f32, 20.0, 30.0];
1205        let bones = [SsMatrix4x4::IDENTITY];
1206
1207        let indices = [1i16];
1208        let dx = [100.0f32];
1209        let dy = [200.0f32];
1210        let part_mat = SsMatrix4x4::IDENTITY;
1211
1212        let mut out_x = [0.0f32; 3];
1213        let mut out_y = [0.0f32; 3];
1214
1215        compute_skinned_mesh_vertices(&offsets, &bone_indices, &weights, &coords_x, &coords_y, &bones, Some((&indices, &dx, &dy, &part_mat)), false, &mut out_x, &mut out_y);
1216
1217        assert_arr_approx_eq(&out_x, &[1.0, 102.0, 3.0], 3);
1218        assert_arr_approx_eq(&out_y, &[10.0, 220.0, 30.0], 3);
1219    }
1220
1221    #[test]
1222    fn test_rigid_mesh_vertices_simd_chunk_and_tail() {
1223        // 6 vertices = one 4-wide SIMD chunk + a 2-vertex scalar tail.
1224        let rest_x = [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0];
1225        let rest_y = [10.0f32, 20.0, 30.0, 40.0, 50.0, 60.0];
1226        // 90° rotation: W · (x, y) = (-y, x).
1227        let world = SsMatrix4x4::create_rotation_z(core::f32::consts::FRAC_PI_2);
1228        let mut out_x = [0.0f32; 6];
1229        let mut out_y = [0.0f32; 6];
1230
1231        compute_rigid_mesh_vertices(&rest_x, &rest_y, &world, false, &mut out_x, &mut out_y);
1232        assert_arr_approx_eq(&out_x, &[-10.0, -20.0, -30.0, -40.0, -50.0, -60.0], 6);
1233        assert_arr_approx_eq(&out_y, &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], 6);
1234
1235        // flip_rest_y negates rest Y before the transform: out_x = -(-y) = y.
1236        compute_rigid_mesh_vertices(&rest_x, &rest_y, &world, true, &mut out_x, &mut out_y);
1237        assert_arr_approx_eq(&out_x, &[10.0, 20.0, 30.0, 40.0, 50.0, 60.0], 6);
1238        assert_arr_approx_eq(&out_y, &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], 6);
1239    }
1240
1241    #[test]
1242    fn test_skinned_mesh_five_influences_scalar_tail() {
1243        // A lone vertex never fills a 4-wide group, so this exercises the scalar
1244        // tail with more than 4 influences. Five identity bones, equal weights,
1245        // bind coord (10, 20) seen by every influence → output equals (10, 20).
1246        let offsets = [0u32, 5];
1247        let bone_indices = [0u16; 5];
1248        let weights = [0.2f32; 5];
1249        let coords_x = [10.0f32; 5];
1250        let coords_y = [20.0f32; 5];
1251        let bones = [SsMatrix4x4::IDENTITY];
1252
1253        let mut out_x = [0.0f32];
1254        let mut out_y = [0.0f32];
1255
1256        compute_skinned_mesh_vertices(&offsets, &bone_indices, &weights, &coords_x, &coords_y, &bones, None, false, &mut out_x, &mut out_y);
1257
1258        assert_arr_approx_eq(&out_x, &[10.0], 1);
1259        assert_arr_approx_eq(&out_y, &[20.0], 1);
1260    }
1261
1262    #[test]
1263    fn test_skinned_mesh_ragged_influence_counts_in_simd_group() {
1264        // 4 vertices = exactly one SIMD group, with influence counts 1/2/5/3.
1265        // `max_slots` is 5, so every lane but the third zero-pads for at least
1266        // two slots — the group must still produce each vertex's own weighted sum.
1267        //
1268        // Bone 0 is identity; bone 1 translates by (+100, +200). Every vertex
1269        // binds at (10, 20) and its weights sum to 1, so a vertex is at (10, 20)
1270        // when all its influences are bone 0, and shifted by the bone-1 weight
1271        // fraction otherwise.
1272        let offsets = [0u32, 1, 3, 8, 11];
1273        let bone_indices = [
1274            0u16, // v0: 1 influence, bone 0
1275            0, 0, // v1: 2 influences, both bone 0
1276            0, 0, 0, 0, 1, // v2: 5 influences, last one bone 1 (weight 0.2)
1277            0, 0, 0, // v3: 3 influences, all bone 0
1278        ];
1279        let weights = [1.0f32, 0.5, 0.5, 0.2, 0.2, 0.2, 0.2, 0.2, 1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0];
1280        let coords_x = [10.0f32; 11];
1281        let coords_y = [20.0f32; 11];
1282
1283        let mut bone1 = SsMatrix4x4::IDENTITY;
1284        bone1.m[12] = 100.0;
1285        bone1.m[13] = 200.0;
1286        let bones = [SsMatrix4x4::IDENTITY, bone1];
1287
1288        let mut out_x = [0.0f32; 4];
1289        let mut out_y = [0.0f32; 4];
1290
1291        compute_skinned_mesh_vertices(&offsets, &bone_indices, &weights, &coords_x, &coords_y, &bones, None, false, &mut out_x, &mut out_y);
1292
1293        // v2 = 0.8·(10, 20) + 0.2·(110, 220) = (30, 60).
1294        assert_arr_approx_eq(&out_x, &[10.0, 10.0, 30.0, 10.0], 4);
1295        assert_arr_approx_eq(&out_y, &[20.0, 20.0, 60.0, 20.0], 4);
1296    }
1297
1298    #[test]
1299    fn test_skinned_mesh_simd_chunk_and_tail() {
1300        // 6 vertices = one 4-wide group + a 2-vertex scalar tail. Both halves
1301        // must agree; a chunk/tail boundary bug shows up as the last two
1302        // vertices keeping their zero-initialized values.
1303        let offsets = [0u32, 1, 2, 3, 4, 5, 6];
1304        let bone_indices = [0u16; 6];
1305        let weights = [1.0f32; 6];
1306        let coords_x = [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0];
1307        let coords_y = [10.0f32, 20.0, 30.0, 40.0, 50.0, 60.0];
1308        // 90° rotation: W · (x, y) = (-y, x).
1309        let bones = [SsMatrix4x4::create_rotation_z(core::f32::consts::FRAC_PI_2)];
1310
1311        let mut out_x = [0.0f32; 6];
1312        let mut out_y = [0.0f32; 6];
1313
1314        compute_skinned_mesh_vertices(&offsets, &bone_indices, &weights, &coords_x, &coords_y, &bones, None, false, &mut out_x, &mut out_y);
1315        assert_arr_approx_eq(&out_x, &[-10.0, -20.0, -30.0, -40.0, -50.0, -60.0], 6);
1316        assert_arr_approx_eq(&out_y, &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], 6);
1317
1318        // flip_y negates the bind Y before the transform: out_x = -(-y) = y.
1319        compute_skinned_mesh_vertices(&offsets, &bone_indices, &weights, &coords_x, &coords_y, &bones, None, true, &mut out_x, &mut out_y);
1320        assert_arr_approx_eq(&out_x, &[10.0, 20.0, 30.0, 40.0, 50.0, 60.0], 6);
1321        assert_arr_approx_eq(&out_y, &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], 6);
1322    }
1323
1324    #[test]
1325    fn test_skew_local_tans_gate() {
1326        // No skew -> nothing to apply.
1327        assert!(skew_local_tans(0.0, 0.0).is_none());
1328        // With skew (and propagate off, the default) -> the tan pair.
1329        if crate::eval::SKEW_PROPAGATES {
1330            assert!(skew_local_tans(30.0, 0.0).is_none());
1331        } else {
1332            let (tx, ty) = skew_local_tans(30.0, 45.0).expect("skew present");
1333            assert!((tx - crate::eval::math::tanf(30.0 * core::f32::consts::PI / 180.0)).abs() < 1e-6);
1334            assert!((ty - crate::eval::math::tanf(45.0 * core::f32::consts::PI / 180.0)).abs() < 1e-6);
1335        }
1336    }
1337
1338    #[test]
1339    fn test_skew_point_yup() {
1340        // A horizontal shear (skew_x only) slides x by tan·y and leaves y.
1341        let t = crate::eval::math::tanf(30.0 * core::f32::consts::PI / 180.0);
1342        // Top vertex (y > 0) moves +x; bottom (y < 0) moves -x: a lean.
1343        let (tx, ty) = skew_point_yup(0.0, 10.0, t, 0.0);
1344        assert!((tx - t * 10.0).abs() < 1e-6);
1345        assert!((ty - 10.0).abs() < 1e-6);
1346        let (bx, by) = skew_point_yup(0.0, -10.0, t, 0.0);
1347        assert!((bx + t * 10.0).abs() < 1e-6);
1348        assert!((by + 10.0).abs() < 1e-6);
1349        // The pivot origin is the shear's fixed point.
1350        let (ox, oy) = skew_point_yup(0.0, 0.0, t, t);
1351        assert!(ox.abs() < 1e-6 && oy.abs() < 1e-6);
1352    }
1353}