Skip to main content

repose_core/
geometry.rs

1#[derive(Clone, Copy, Debug, Default, PartialEq)]
2pub struct Vec2 {
3    pub x: f32,
4    pub y: f32,
5}
6
7impl Vec2 {
8    pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 };
9}
10
11impl std::ops::Add for Vec2 {
12    type Output = Vec2;
13    fn add(self, other: Vec2) -> Vec2 {
14        Vec2 {
15            x: self.x + other.x,
16            y: self.y + other.y,
17        }
18    }
19}
20
21impl std::ops::Sub for Vec2 {
22    type Output = Vec2;
23    fn sub(self, other: Vec2) -> Vec2 {
24        Vec2 {
25            x: self.x - other.x,
26            y: self.y - other.y,
27        }
28    }
29}
30
31impl std::ops::Neg for Vec2 {
32    type Output = Vec2;
33    fn neg(self) -> Vec2 {
34        Vec2 {
35            x: -self.x,
36            y: -self.y,
37        }
38    }
39}
40
41#[derive(Clone, Copy, Debug, Default, PartialEq)]
42pub struct Size {
43    pub width: f32,
44    pub height: f32,
45}
46
47#[derive(Clone, Copy, Debug, Default, PartialEq)]
48pub struct Rect {
49    pub x: f32,
50    pub y: f32,
51    pub w: f32,
52    pub h: f32,
53}
54
55impl Rect {
56    pub fn contains(&self, p: Vec2) -> bool {
57        p.x >= self.x && p.x <= self.x + self.w && p.y >= self.y && p.y <= self.y + self.h
58    }
59}
60
61#[derive(Clone, Copy, Debug, Default, PartialEq)]
62pub struct Transform {
63    pub translate_x: f32,
64    pub translate_y: f32,
65    pub scale_x: f32,
66    pub scale_y: f32,
67    pub rotate: f32, // radians
68    /// Horizontal shear factor (`x += shear_x * y`), e.g. ASS `\fax`.
69    pub shear_x: f32,
70    /// Vertical shear factor (`y += shear_y * x`), e.g. ASS `\fay`.
71    pub shear_y: f32,
72    /// 3D rotation about the x axis in radians (Compose `rotationX`).
73    pub rotation_x: f32,
74    /// 3D rotation about the y axis in radians (Compose `rotationY`).
75    pub rotation_y: f32,
76    /// Camera distance for the perspective divide. `<= 0` is orthographic.
77    pub camera_distance: f32,
78    /// Normalized transform origin in `[0, 1]` (0.5 = center).
79    ///
80    /// This is a *normalized* pivot, not an absolute point. It is only
81    /// meaningful together with the target [`Rect`]: the absolute pivot is
82    /// `rect.x + rect.w * origin_x` (same for y). The paint bake path
83    /// (`LayoutEngine::walk_paint`) is the single source of truth for
84    /// rendering: it resolves the pivot from the node's `Rect`, folds it
85    /// into `translate_x/y`, and pushes a transform with
86    /// `origin_x/y == 0.0`. Renderers consume transforms origin-free.
87    /// Do not interpret `origin_*` as absolute pixels (see
88    /// [`apply_to_point_in_rect`](Self::apply_to_point_in_rect)).
89    pub origin_x: f32,
90    pub origin_y: f32,
91    /// Projective row of the homogeneous 3x3 map: `w = px * x + py * y + pw`
92    /// and the rendered point is the affine result divided by `w`. Identity
93    /// (pure affine) is `[0.0, 0.0, 1.0]`, e.g. a 3D tilt of a planar layer.
94    ///
95    /// Only the scene-graph translation consumes this (perspective subtrees
96    /// are flattened into offscreen layers and composited projectively, CSS
97    /// style). [`linear`](Self::linear), [`apply_to_point`](Self::apply_to_point)
98    /// and [`combine`](Self::combine) stay affine-only by design.
99    pub perspective: [f32; 3],
100}
101
102impl Transform {
103    pub fn identity() -> Self {
104        Self {
105            translate_x: 0.0,
106            translate_y: 0.0,
107            scale_x: 1.0,
108            scale_y: 1.0,
109            rotate: 0.0,
110            shear_x: 0.0,
111            shear_y: 0.0,
112            rotation_x: 0.0,
113            rotation_y: 0.0,
114            camera_distance: 0.0,
115            origin_x: 0.5,
116            origin_y: 0.5,
117            perspective: [0.0, 0.0, 1.0],
118        }
119    }
120
121    pub fn translate(x: f32, y: f32) -> Self {
122        Self {
123            translate_x: x,
124            translate_y: y,
125            scale_x: 1.0,
126            scale_y: 1.0,
127            rotate: 0.0,
128            shear_x: 0.0,
129            shear_y: 0.0,
130            rotation_x: 0.0,
131            rotation_y: 0.0,
132            camera_distance: 0.0,
133            origin_x: 0.5,
134            origin_y: 0.5,
135            perspective: [0.0, 0.0, 1.0],
136        }
137    }
138
139    /// Forward 2x2 linear part (row-major `[m00, m01, m10, m11]`):
140    /// `M = R(rotate) * H(shear) * S(scale)` applied before translation.
141    pub fn linear(&self) -> [f32; 4] {
142        let c = self.rotate.cos();
143        let s = self.rotate.sin();
144        let hsx = self.scale_x;
145        let hsy = self.scale_y;
146        let k00 = hsx;
147        let k01 = self.shear_x * hsy;
148        let k10 = self.shear_y * hsx;
149        let k11 = hsy;
150        [
151            c * k00 - s * k10,
152            c * k01 - s * k11,
153            s * k00 + c * k10,
154            s * k01 + c * k11,
155        ]
156    }
157
158    /// Inverse of [`linear`](Self::linear), or `None` when singular.
159    pub fn inverse_linear(&self) -> Option<[f32; 4]> {
160        let m = self.linear();
161        let det = m[0] * m[3] - m[1] * m[2];
162        if det.abs() < 1e-12 {
163            return None;
164        }
165        Some([m[3] / det, -m[1] / det, -m[2] / det, m[0] / det])
166    }
167
168    /// Whether scale/rotation/shear are all identity (translation may apply).
169    pub fn linear_is_identity(&self) -> bool {
170        self.scale_x == 1.0
171            && self.scale_y == 1.0
172            && self.rotate == 0.0
173            && self.shear_x == 0.0
174            && self.shear_y == 0.0
175            && self.rotation_x == 0.0
176            && self.rotation_y == 0.0
177    }
178
179    /// Whether the projective row is non-trivial (true perspective).
180    pub fn has_perspective(&self) -> bool {
181        self.perspective != [0.0, 0.0, 1.0]
182            || ((self.rotation_x != 0.0 || self.rotation_y != 0.0) && self.camera_distance > 0.0)
183    }
184
185    /// Full homogeneous 3x3 map (row-major, 9 elements): the affine
186    /// `linear()` + translation in rows 0-1, [`perspective`](Self::perspective)
187    /// in row 2. `world_h = M * [x, y, 1]`, `world = world_h.xy / world_h.z`.
188    ///
189    /// Origin pivots are intentionally not folded in: the renderer consumes
190    /// the affine parts origin-free (see `rect_to_instance_ndc`), so pivots
191    /// must be baked into the rows by the producer (see
192    /// [`from_projective_rows`](Self::from_projective_rows)). The same applies
193    /// to `rotation_x`/`rotation_y`: bake the pivot by translating to it,
194    /// applying this matrix, then translating back.
195    pub fn projective_matrix(&self) -> [f32; 9] {
196        let m = self.linear();
197        let base = [
198            m[0],
199            m[1],
200            self.translate_x,
201            m[2],
202            m[3],
203            self.translate_y,
204            self.perspective[0],
205            self.perspective[1],
206            self.perspective[2],
207        ];
208        if self.rotation_x == 0.0 && self.rotation_y == 0.0 {
209            return base;
210        }
211        let (sa, ca) = (self.rotation_x.sin(), self.rotation_x.cos());
212        let (sb, cb) = (self.rotation_y.sin(), self.rotation_y.cos());
213        let inv_d = if self.camera_distance > 0.0 {
214            1.0 / self.camera_distance
215        } else {
216            0.0
217        };
218        let camera = [
219            cb,
220            sa * sb,
221            0.0,
222            0.0,
223            ca,
224            0.0,
225            sb * inv_d,
226            -sa * cb * inv_d,
227            1.0,
228        ];
229        Self::compose_projective(&camera, &base)
230    }
231
232    /// Build a transform from explicit homogeneous rows: `row0`/`row1` are the
233    /// affine `[a, b, t]` rows, `perspective` the projective `[px, py, pw]`
234    /// row. The affine 2x2 is decomposed into scale/rotate/shear parts (via
235    /// the same decomposition [`combine`](Self::combine) uses), so this
236    /// round-trips any 3D-rotation-of-a-plane + perspective map exactly —
237    /// e.g. ASS `\frx`/`\fry` about an `\org` pivot, where the pivot lives in
238    /// the rows because the renderer ignores `origin_*`.
239    pub fn from_projective_rows(row0: [f32; 3], row1: [f32; 3], perspective: [f32; 3]) -> Self {
240        let (sx, sy, rot, hx, hy) = decompose_linear([row0[0], row0[1], row1[0], row1[1]])
241            .unwrap_or((1.0, 1.0, 0.0, 0.0, 0.0));
242        Self {
243            translate_x: row0[2],
244            translate_y: row1[2],
245            scale_x: sx,
246            scale_y: sy,
247            rotate: rot,
248            shear_x: hx,
249            shear_y: hy,
250            rotation_x: 0.0,
251            rotation_y: 0.0,
252            camera_distance: 0.0,
253            origin_x: 0.5,
254            origin_y: 0.5,
255            perspective,
256        }
257    }
258
259    /// Apply the full projective map to a point, with perspective divide.
260    /// Degenerate `w` (≈ 0, at/behind the viewer) clamps to a tiny epsilon of
261    /// the original sign so output stays finite; callers culling
262    /// behind-camera content should test `w` via [`projective_w`](Self::projective_w).
263    pub fn apply_projective(&self, p: Vec2) -> Vec2 {
264        let m = self.projective_matrix();
265        let x = m[0] * p.x + m[1] * p.y + m[2];
266        let y = m[3] * p.x + m[4] * p.y + m[5];
267        let w = self.projective_w(p);
268        Vec2 { x: x / w, y: y / w }
269    }
270
271    /// The homogeneous `w` of a point under this transform's projective map.
272    pub fn projective_w(&self, p: Vec2) -> f32 {
273        let m = self.projective_matrix();
274        let w = m[6] * p.x + m[7] * p.y + m[8];
275        if w.abs() < 1e-6 {
276            if w < 0.0 { -1e-6 } else { 1e-6 }
277        } else {
278            w
279        }
280    }
281
282    /// Compose two homogeneous 3x3 maps (row-major 9-element arrays, as from
283    /// [`projective_matrix`](Self::projective_matrix)): `world = outer ×
284    /// inner × local`. Used at scene-translation time to fold affine
285    /// ancestors over a perspective node; the result feeds layer-flattening,
286    /// never the part-based [`combine`](Self::combine).
287    pub fn compose_projective(outer: &[f32; 9], inner: &[f32; 9]) -> [f32; 9] {
288        let mut c = [0.0f32; 9];
289        for i in 0..3 {
290            for j in 0..3 {
291                c[i * 3 + j] = outer[i * 3] * inner[j]
292                    + outer[i * 3 + 1] * inner[3 + j]
293                    + outer[i * 3 + 2] * inner[6 + j];
294            }
295        }
296        c
297    }
298
299    /// Axis-aligned bounds of a projectively mapped rect (projects all four
300    /// corners and bounds them; the correct cull rect for flattened layers).
301    pub fn project_rect(&self, r: &Rect) -> Rect {
302        let corners = [
303            Vec2 { x: r.x, y: r.y },
304            Vec2 {
305                x: r.x + r.w,
306                y: r.y,
307            },
308            Vec2 {
309                x: r.x + r.w,
310                y: r.y + r.h,
311            },
312            Vec2 {
313                x: r.x,
314                y: r.y + r.h,
315            },
316        ];
317        let mut min_x = f32::MAX;
318        let mut min_y = f32::MAX;
319        let mut max_x = f32::MIN;
320        let mut max_y = f32::MIN;
321        for c in corners {
322            let p = self.apply_projective(c);
323            min_x = min_x.min(p.x);
324            min_y = min_y.min(p.y);
325            max_x = max_x.max(p.x);
326            max_y = max_y.max(p.y);
327        }
328        Rect {
329            x: min_x,
330            y: min_y,
331            w: (max_x - min_x).max(0.0),
332            h: (max_y - min_y).max(0.0),
333        }
334    }
335
336    pub fn apply_to_point(&self, p: Vec2) -> Vec2 {
337        //
338        let ox = self.origin_x;
339        let oy = self.origin_y;
340        let m = self.linear();
341        let x = p.x - ox;
342        let y = p.y - oy;
343
344        Vec2 {
345            x: m[0] * x + m[1] * y + ox + self.translate_x,
346            y: m[2] * x + m[3] * y + oy + self.translate_y,
347        }
348    }
349
350    /// Absolute pivot for `r` given the normalized `origin_*` (`[0, 1]`).
351    pub fn pivot_for_rect(&self, r: &Rect) -> Vec2 {
352        Vec2 {
353            x: r.x + r.w * self.origin_x,
354            y: r.y + r.h * self.origin_y,
355        }
356    }
357
358    /// Apply with an explicit absolute pivot (same space as `p`).
359    /// This is the pivot-correct primitive; `apply_to_point` is this with
360    /// `pivot == (origin_x, origin_y)`.
361    pub fn apply_to_point_with_pivot(&self, p: Vec2, pivot: Vec2) -> Vec2 {
362        let m = self.linear();
363        let x = p.x - pivot.x;
364        let y = p.y - pivot.y;
365        Vec2 {
366            x: m[0] * x + m[1] * y + pivot.x + self.translate_x,
367            y: m[2] * x + m[3] * y + pivot.y + self.translate_y,
368        }
369    }
370
371    /// Pivot-correct point mapping for a normalized origin + layout rect.
372    /// Use this for hit-testing / bounds of scaled nodes (e.g. dialogs).
373    pub fn apply_to_point_in_rect(&self, p: Vec2, r: &Rect) -> Vec2 {
374        self.apply_to_point_with_pivot(p, self.pivot_for_rect(r))
375    }
376
377    pub fn apply_to_rect(&self, r: Rect) -> Rect {
378        let ox = r.x + r.w * self.origin_x;
379        let oy = r.y + r.h * self.origin_y;
380        let m = self.linear();
381        let corners = [
382            Vec2 { x: r.x, y: r.y },
383            Vec2 {
384                x: r.x + r.w,
385                y: r.y,
386            },
387            Vec2 {
388                x: r.x,
389                y: r.y + r.h,
390            },
391            Vec2 {
392                x: r.x + r.w,
393                y: r.y + r.h,
394            },
395        ];
396        let mut min_x = f32::MAX;
397        let mut min_y = f32::MAX;
398        let mut max_x = f32::MIN;
399        let mut max_y = f32::MIN;
400        for c in corners {
401            let x = c.x - ox;
402            let y = c.y - oy;
403            let tx = m[0] * x + m[1] * y + ox + self.translate_x;
404            let ty = m[2] * x + m[3] * y + oy + self.translate_y;
405            min_x = min_x.min(tx);
406            min_y = min_y.min(ty);
407            max_x = max_x.max(tx);
408            max_y = max_y.max(ty);
409        }
410        Rect {
411            x: min_x,
412            y: min_y,
413            w: max_x - min_x,
414            h: max_y - min_y,
415        }
416    }
417
418    /// Compose two transforms (`self` outer, `other` inner) for a
419    /// transform stack: `current.combine(pushed)` where `pushed` is the
420    /// newly pushed (inner) node.
421    ///
422    /// Returns a transform such that `combined.apply_to_point(p) ==
423    /// self.apply_to_point(other.apply_to_point(p))` for the absolute-pivot
424    /// [`apply_to_point`](Self::apply_to_point) primitive.
425    ///
426    /// Origin semantics: the linear part and translation are composed
427    /// **origin-free** (pure affine composition of `linear()` + translation).
428    /// `origin_*` (normalized `[0, 1]`) cannot be composed part-wise without
429    /// the target rect, so the result inherits the outer (`self`) origin for
430    /// back-compat. Callers that need pivot-correct nesting must bake each
431    /// level against its own `Rect` first (exactly what the paint bake path
432    /// does: resolve pivot from rect, fold into translation, zero the
433    /// origin) and then combine the baked, origin-free transforms. That bake
434    /// path is the single source of truth for rendering; the renderer
435    /// consumes transforms origin-free.
436    ///
437    /// Affine-only by design: a part-based transform cannot represent a
438    /// composed projective map, so `perspective` rows do NOT compose here
439    /// (debug-asserted). Perspective folds at scene-translation time into a
440    /// full 3x3 via [`projective_matrix`](Self::projective_matrix) and
441    /// [`compose_projective`](Self::compose_projective), which is what
442    /// flattens perspective subtrees into projectively composited layers.
443    pub fn combine(&self, other: &Transform) -> Transform {
444        debug_assert!(
445            !self.has_perspective() && !other.has_perspective(),
446            "Transform::combine is affine-only; compose projective rows with compose_projective"
447        );
448        let a = self.linear();
449        let b = other.linear();
450        let m = [
451            a[0] * b[0] + a[1] * b[2],
452            a[0] * b[1] + a[1] * b[3],
453            a[2] * b[0] + a[3] * b[2],
454            a[2] * b[1] + a[3] * b[3],
455        ];
456        let translate_x = a[0] * other.translate_x + a[1] * other.translate_y + self.translate_x;
457        let translate_y = a[2] * other.translate_x + a[3] * other.translate_y + self.translate_y;
458
459        let (scale_x, scale_y, rotate, shear_x, shear_y) =
460            decompose_linear(m).unwrap_or((1.0, 1.0, 0.0, 0.0, 0.0));
461
462        Transform {
463            translate_x,
464            translate_y,
465            scale_x,
466            scale_y,
467            rotate,
468            shear_x,
469            shear_y,
470            rotation_x: 0.0,
471            rotation_y: 0.0,
472            camera_distance: 0.0,
473            origin_x: self.origin_x,
474            origin_y: self.origin_y,
475            // Affine-only (see doc): callers must not push perspective here.
476            perspective: [0.0, 0.0, 1.0],
477        }
478    }
479}
480
481/// Split a 2x2 matrix `[m00, m01, m10, m11]` into
482/// `(scale_x, scale_y, rotate, shear_x, shear_y)` such that
483/// `M = R(rotate) * H(shear) * S(scale)`, or `None` when degenerate.
484///
485/// Uses polar decomposition (`M = R * K` with symmetric `K`), then reads
486/// scale/shear off `K`. Reflections fold their sign into `scale_x`.
487fn decompose_linear(m: [f32; 4]) -> Option<(f32, f32, f32, f32, f32)> {
488    let (mut a, mut b, c, d) = (m[0], m[1], m[2], m[3]);
489    let mut angle_sign = 1.0;
490    if a * d - b * c < 0.0 {
491        a = -a;
492        b = -b;
493        angle_sign = -1.0;
494    }
495    let e = a * a + c * c;
496    let f = a * b + c * d;
497    let g = b * b + d * d;
498    let det_p = (e * g - f * f).max(0.0);
499    let s = (e + g + 2.0 * det_p.sqrt()).sqrt();
500    if s.is_nan() || s <= 1e-12 {
501        return None;
502    }
503    let root_det = det_p.sqrt();
504    let k00 = (e + root_det) / s;
505    let k01 = f / s;
506    let k10 = f / s;
507    let k11 = (g + root_det) / s;
508    let det_k = (k00 * k11 - k01 * k10).max(1e-24);
509    let r00 = (a * k11 - b * k10) / det_k;
510    let r10 = (c * k11 - d * k10) / det_k;
511    let rotate = r10.atan2(r00);
512    let (sx, sy) = (k00, k11);
513    if sx.abs() < 1e-12 || sy.abs() < 1e-12 {
514        return None;
515    }
516    if angle_sign < 0.0 {
517        return Some((-sx, sy, -rotate, -(k01 / sy), -(k10 / sx)));
518    }
519    Some((sx, sy, rotate, k01 / sy, k10 / sx))
520}
521
522#[cfg(test)]
523mod tests {
524    use super::*;
525
526    fn approx(a: f32, b: f32) -> bool {
527        (a - b).abs() < 1e-3
528    }
529
530    fn transform(tx: f32, ty: f32, sx: f32, sy: f32, rot: f32, hx: f32, hy: f32) -> Transform {
531        Transform {
532            translate_x: tx,
533            translate_y: ty,
534            scale_x: sx,
535            scale_y: sy,
536            rotate: rot,
537            shear_x: hx,
538            shear_y: hy,
539            rotation_x: 0.0,
540            rotation_y: 0.0,
541            camera_distance: 0.0,
542            origin_x: 0.0,
543            origin_y: 0.0,
544            perspective: [0.0, 0.0, 1.0],
545        }
546    }
547
548    #[test]
549    fn shear_free_matches_legacy_formula() {
550        let t = transform(5.0, -3.0, 2.0, 0.5, 0.7, 0.0, 0.0);
551        let p = Vec2 { x: 11.0, y: 7.0 };
552        let got = t.apply_to_point(p);
553        let (c, s) = (0.7f32.cos(), 0.7f32.sin());
554        let x = (p.x) * 2.0;
555        let y = (p.y) * 0.5;
556        assert!(approx(got.x, x * c - y * s + 5.0));
557        assert!(approx(got.y, x * s + y * c - 3.0));
558    }
559
560    #[test]
561    fn shear_order_is_scale_then_shear_then_rotate() {
562        let t = transform(0.0, 0.0, 2.0, 3.0, 0.0, 1.0, 0.0);
563        let got = t.apply_to_point(Vec2 { x: 1.0, y: 1.0 });
564        assert!(approx(got.x, 2.0 + 3.0));
565        assert!(approx(got.y, 3.0));
566    }
567
568    #[test]
569    fn combine_round_trips_through_apply() {
570        let cases = [
571            (
572                transform(3.0, 4.0, 1.0, 1.0, 0.0, 0.0, 0.0),
573                transform(0.0, 0.0, 2.0, 2.0, 0.0, 0.0, 0.0),
574            ),
575            (
576                transform(1.0, 2.0, 1.5, 0.5, 0.6, 0.0, 0.0),
577                transform(-2.0, 1.0, 0.7, 1.3, -0.4, 0.0, 0.0),
578            ),
579            (
580                transform(0.0, 0.0, 2.0, 0.5, 0.9, 0.0, 0.0),
581                transform(4.0, -1.0, 1.0, 1.0, 0.3, 0.0, 0.0),
582            ),
583            (
584                transform(2.0, 0.0, 1.0, 1.0, 0.2, 0.8, -0.3),
585                transform(0.0, 5.0, 1.2, 0.9, -0.5, 0.4, 0.1),
586            ),
587            (
588                transform(0.0, 0.0, -1.0, 1.0, 0.0, 0.0, 0.0),
589                transform(7.0, 7.0, 1.0, 1.0, 1.1, 0.2, 0.0),
590            ),
591        ];
592        let points = [
593            Vec2 { x: 0.0, y: 0.0 },
594            Vec2 { x: 10.0, y: -4.0 },
595            Vec2 { x: -3.5, y: 8.25 },
596            Vec2 { x: 100.0, y: 200.0 },
597        ];
598        for (a, b) in cases {
599            let combined = a.combine(&b);
600            for p in points {
601                let expect = a.apply_to_point(b.apply_to_point(p));
602                let got = combined.apply_to_point(p);
603                assert!(
604                    approx(got.x, expect.x) && approx(got.y, expect.y),
605                    "combine mismatch: {a:?} then {b:?} at {p:?}: got {got:?}, want {expect:?}"
606                );
607            }
608        }
609    }
610
611    #[test]
612    fn inverse_linear_round_trips() {
613        let t = transform(3.0, -2.0, 1.5, 0.75, 0.8, 0.6, -0.2);
614        let m = t.linear();
615        let n = t.inverse_linear().expect("invertible");
616        let id = [
617            n[0] * m[0] + n[1] * m[2],
618            n[0] * m[1] + n[1] * m[3],
619            n[2] * m[0] + n[3] * m[2],
620            n[2] * m[1] + n[3] * m[3],
621        ];
622        assert!(approx(id[0], 1.0) && approx(id[3], 1.0));
623        assert!(approx(id[1], 0.0) && approx(id[2], 0.0));
624    }
625}
626
627#[cfg(test)]
628mod projective_tests {
629    use super::*;
630
631    fn approx(a: f32, b: f32) -> bool {
632        (a - b).abs() < 1e-3
633    }
634
635    #[test]
636    fn identity_row_is_affine_noop() {
637        let t = Transform::identity();
638        assert!(!t.has_perspective());
639        let p = Vec2 { x: 13.0, y: -7.0 };
640        let q = t.apply_projective(p);
641        assert!(approx(q.x, p.x) && approx(q.y, p.y));
642        assert!(approx(t.projective_w(p), 1.0));
643    }
644
645    #[test]
646    fn tilt_about_center_matches_hand_computation() {
647        // Rotation about the x-axis through the rect centre, focal length f:
648        // y' = cy + (y - cy) * cos, w = 1 + (y - cy) * sin / f.
649        let (cx, cy, f) = (100.0f32, 100.0f32, 1000.0f32);
650        let th = 0.5f32;
651        let (s, c) = (th.sin(), th.cos());
652        let t = Transform::from_projective_rows(
653            [1.0, 0.0, 0.0],
654            [0.0, c, cy * (1.0 - c)],
655            [0.0, s / f, 1.0 - cy * s / f],
656        );
657        assert!(t.has_perspective());
658        // Centre is fixed; w varies linearly with distance from the axis.
659        let q = t.apply_projective(Vec2 { x: cx, y: cy });
660        assert!(approx(q.x, cx) && approx(q.y, cy));
661        assert!(
662            t.projective_w(Vec2 {
663                x: cx,
664                y: cy - 50.0
665            }) < 1.0
666        );
667        assert!(
668            t.projective_w(Vec2 {
669                x: cx,
670                y: cy + 50.0
671            }) > 1.0
672        );
673    }
674
675    #[test]
676    fn from_projective_rows_round_trips_affine_part() {
677        let t = Transform::from_projective_rows(
678            [2.0, 0.5, 7.0],
679            [-0.5, 3.0, -2.0],
680            [0.001, -0.002, 1.0],
681        );
682        // Affine rows survive the parts round-trip; translation is exact.
683        let m = t.projective_matrix();
684        assert!(approx(m[0], 2.0) && approx(m[1], 0.5) && approx(m[2], 7.0));
685        assert!(approx(m[3], -0.5) && approx(m[4], 3.0) && approx(m[5], -2.0));
686        assert!(approx(m[6], 0.001) && approx(m[7], -0.002) && approx(m[8], 1.0));
687    }
688
689    #[test]
690    fn compose_projective_matches_sequential_apply() {
691        let outer = Transform {
692            translate_x: 5.0,
693            ..Transform::identity()
694        };
695        let inner =
696            Transform::from_projective_rows([1.0, 0.0, 0.0], [0.0, 0.9, 10.0], [0.0, 0.001, 1.0]);
697        let c =
698            Transform::compose_projective(&outer.projective_matrix(), &inner.projective_matrix());
699        for p in [Vec2 { x: 0.0, y: 0.0 }, Vec2 { x: 40.0, y: -25.0 }] {
700            // Sequential: inner (projective) then outer (affine).
701            let q1 = inner.apply_projective(p);
702            let m = outer.projective_matrix();
703            let q1 = Vec2 {
704                x: m[0] * q1.x + m[1] * q1.y + m[2],
705                y: m[3] * q1.x + m[4] * q1.y + m[5],
706            };
707            let w = c[6] * p.x + c[7] * p.y + c[8];
708            let q2 = Vec2 {
709                x: (c[0] * p.x + c[1] * p.y + c[2]) / w,
710                y: (c[3] * p.x + c[4] * p.y + c[5]) / w,
711            };
712            assert!(
713                approx(q1.x, q2.x) && approx(q1.y, q2.y),
714                "mismatch at {p:?}: {q1:?} vs {q2:?}"
715            );
716        }
717    }
718
719    #[test]
720    fn project_rect_bounds_projected_corners() {
721        let t =
722            Transform::from_projective_rows([1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.002, 0.0, 1.0]);
723        let r = Rect {
724            x: 0.0,
725            y: 0.0,
726            w: 100.0,
727            h: 100.0,
728        };
729        let b = t.project_rect(&r);
730        // w grows with x: the left edge (w=1) is unscaled, the right edge
731        // (w=1.2) shrinks in both axes.
732        assert!(approx(b.x, 0.0));
733        assert!(approx(b.w, 100.0 / 1.2));
734        assert!(approx(b.y, 0.0) && approx(b.h, 100.0));
735    }
736}