Skip to main content

strata_primitives/
geom.rs

1//! Zero-dependency 2D geometry, subpixel snapping, and affine transformations.
2
3use std::ops::{Add, Div, Mul, Neg, Sub};
4
5/// 2D Cartesian Coordinate Point.
6#[repr(C)]
7#[derive(Debug, Clone, Copy, PartialEq, Default)]
8pub struct Point<T = f32> {
9    pub x: T,
10    pub y: T,
11}
12
13impl<T> Point<T> {
14    #[inline(always)]
15    pub const fn new(x: T, y: T) -> Self {
16        Self { x, y }
17    }
18}
19
20impl Point<f32> {
21    pub const ZERO: Self = Self::new(0.0, 0.0);
22
23    #[inline(always)]
24    pub fn distance_to(self, other: Self) -> f32 {
25        let dx = self.x - other.x;
26        let dy = self.y - other.y;
27        (dx * dx + dy * dy).sqrt()
28    }
29
30    #[inline(always)]
31    pub fn dot(self, other: Self) -> f32 {
32        self.x * other.x + self.y * other.y
33    }
34
35    #[inline(always)]
36    pub fn lerp(self, other: Self, t: f32) -> Self {
37        Self {
38            x: self.x + (other.x - self.x) * t,
39            y: self.y + (other.y - self.y) * t,
40        }
41    }
42}
43
44impl<T: Add<Output = T>> Add for Point<T> {
45    type Output = Self;
46    #[inline(always)]
47    fn add(self, rhs: Self) -> Self::Output {
48        Self::new(self.x + rhs.x, self.y + rhs.y)
49    }
50}
51
52impl<T: Sub<Output = T>> Sub for Point<T> {
53    type Output = Self;
54    #[inline(always)]
55    fn sub(self, rhs: Self) -> Self::Output {
56        Self::new(self.x - rhs.x, self.y - rhs.y)
57    }
58}
59
60impl<T: Mul<Output = T> + Copy> Mul<T> for Point<T> {
61    type Output = Self;
62    #[inline(always)]
63    fn mul(self, rhs: T) -> Self::Output {
64        Self::new(self.x * rhs, self.y * rhs)
65    }
66}
67
68impl<T: Div<Output = T> + Copy> Div<T> for Point<T> {
69    type Output = Self;
70    #[inline(always)]
71    fn div(self, rhs: T) -> Self::Output {
72        Self::new(self.x / rhs, self.y / rhs)
73    }
74}
75
76impl<T: Neg<Output = T>> Neg for Point<T> {
77    type Output = Self;
78    #[inline(always)]
79    fn neg(self) -> Self::Output {
80        Self::new(-self.x, -self.y)
81    }
82}
83
84/// 2D Size Dimensions.
85#[repr(C)]
86#[derive(Debug, Clone, Copy, PartialEq, Default)]
87pub struct Size<T = f32> {
88    pub width: T,
89    pub height: T,
90}
91
92impl<T> Size<T> {
93    #[inline(always)]
94    pub const fn new(width: T, height: T) -> Self {
95        Self { width, height }
96    }
97}
98
99impl Size<f32> {
100    pub const ZERO: Self = Self::new(0.0, 0.0);
101
102    #[inline(always)]
103    pub fn is_empty(self) -> bool {
104        self.width <= 0.0 || self.height <= 0.0
105    }
106
107    #[inline(always)]
108    pub fn aspect_ratio(self) -> f32 {
109        if self.height == 0.0 {
110            0.0
111        } else {
112            self.width / self.height
113        }
114    }
115
116    #[inline(always)]
117    pub fn clamp(self, min: Self, max: Self) -> Self {
118        Self {
119            width: self.width.clamp(min.width, max.width),
120            height: self.height.clamp(min.height, max.height),
121        }
122    }
123}
124
125/// Axis-Aligned Bounding Box (AABB) Rectangle.
126#[repr(C)]
127#[derive(Debug, Clone, Copy, PartialEq, Default)]
128pub struct Rect<T = f32> {
129    pub origin: Point<T>,
130    pub size: Size<T>,
131}
132
133impl<T> Rect<T> {
134    #[inline(always)]
135    pub const fn new(origin: Point<T>, size: Size<T>) -> Self {
136        Self { origin, size }
137    }
138}
139
140impl Rect<f32> {
141    pub const ZERO: Self = Self::new(Point::ZERO, Size::ZERO);
142
143    #[inline(always)]
144    pub const fn from_xywh(x: f32, y: f32, width: f32, height: f32) -> Self {
145        Self {
146            origin: Point::new(x, y),
147            size: Size::new(width, height),
148        }
149    }
150
151    #[inline(always)]
152    pub fn x(self) -> f32 {
153        self.origin.x
154    }
155    #[inline(always)]
156    pub fn y(self) -> f32 {
157        self.origin.y
158    }
159    #[inline(always)]
160    pub fn width(self) -> f32 {
161        self.size.width
162    }
163    #[inline(always)]
164    pub fn height(self) -> f32 {
165        self.size.height
166    }
167
168    #[inline(always)]
169    pub fn min_x(self) -> f32 {
170        self.origin.x
171    }
172    #[inline(always)]
173    pub fn max_x(self) -> f32 {
174        self.origin.x + self.size.width
175    }
176    #[inline(always)]
177    pub fn min_y(self) -> f32 {
178        self.origin.y
179    }
180    #[inline(always)]
181    pub fn max_y(self) -> f32 {
182        self.origin.y + self.size.height
183    }
184
185    #[inline(always)]
186    pub fn contains_point(self, p: Point<f32>) -> bool {
187        p.x >= self.min_x() && p.x <= self.max_x() && p.y >= self.min_y() && p.y <= self.max_y()
188    }
189
190    #[inline(always)]
191    pub fn intersects(self, other: Self) -> bool {
192        self.min_x() < other.max_x()
193            && self.max_x() > other.min_x()
194            && self.min_y() < other.max_y()
195            && self.max_y() > other.min_y()
196    }
197
198    /// Computes intersection rect with another rectangle.
199    pub fn intersection(self, other: Self) -> Option<Self> {
200        let x0 = self.min_x().max(other.min_x());
201        let y0 = self.min_y().max(other.min_y());
202        let x1 = self.max_x().min(other.max_x());
203        let y1 = self.max_y().min(other.max_y());
204
205        if x1 > x0 && y1 > y0 {
206            Some(Self::from_xywh(x0, y0, x1 - x0, y1 - y0))
207        } else {
208            None
209        }
210    }
211
212    /// Computes minimal bounding rect containing both rectangles.
213    pub fn union(self, other: Self) -> Self {
214        if self.size.is_empty() {
215            return other;
216        }
217        if other.size.is_empty() {
218            return self;
219        }
220
221        let x0 = self.min_x().min(other.min_x());
222        let y0 = self.min_y().min(other.min_y());
223        let x1 = self.max_x().max(other.max_x());
224        let y1 = self.max_y().max(other.max_y());
225
226        Self::from_xywh(x0, y0, x1 - x0, y1 - y0)
227    }
228
229    /// Deflates rectangle by insets (e.g. for padding/borders).
230    #[inline(always)]
231    pub fn deflate(self, insets: EdgeInsets<f32>) -> Self {
232        Self::from_xywh(
233            self.origin.x + insets.left,
234            self.origin.y + insets.top,
235            (self.size.width - insets.left - insets.right).max(0.0),
236            (self.size.height - insets.top - insets.bottom).max(0.0),
237        )
238    }
239
240    /// Inflates rectangle by insets (e.g. for margins/hit-testing).
241    #[inline(always)]
242    pub fn inflate(self, insets: EdgeInsets<f32>) -> Self {
243        Self::from_xywh(
244            self.origin.x - insets.left,
245            self.origin.y - insets.top,
246            self.size.width + insets.left + insets.right,
247            self.size.height + insets.top + insets.bottom,
248        )
249    }
250}
251
252/// 4-Directional Insets (Padding, Margin, Border widths, Safe Areas).
253#[repr(C)]
254#[derive(Debug, Clone, Copy, PartialEq, Default)]
255pub struct EdgeInsets<T = f32> {
256    pub top: T,
257    pub right: T,
258    pub bottom: T,
259    pub left: T,
260}
261
262impl<T> EdgeInsets<T> {
263    #[inline(always)]
264    pub const fn new(top: T, right: T, bottom: T, left: T) -> Self {
265        Self {
266            top,
267            right,
268            bottom,
269            left,
270        }
271    }
272}
273
274impl<T: Clone> EdgeInsets<T> {
275    #[inline(always)]
276    pub fn all(value: T) -> Self {
277        Self {
278            top: value.clone(),
279            right: value.clone(),
280            bottom: value.clone(),
281            left: value,
282        }
283    }
284
285    #[inline(always)]
286    pub fn symmetric(vertical: T, horizontal: T) -> Self {
287        Self {
288            top: vertical.clone(),
289            right: horizontal.clone(),
290            bottom: vertical,
291            left: horizontal,
292        }
293    }
294}
295
296impl EdgeInsets<f32> {
297    pub const ZERO: Self = Self::new(0.0, 0.0, 0.0, 0.0);
298
299    #[inline(always)]
300    pub fn horizontal(self) -> f32 {
301        self.left + self.right
302    }
303    #[inline(always)]
304    pub fn vertical(self) -> f32 {
305        self.top + self.bottom
306    }
307}
308
309/// 2x3 Affine Transformation Matrix.
310///
311/// | a  c  tx |
312/// | b  d  ty |
313/// | 0  0  1  |
314#[repr(C)]
315#[derive(Debug, Clone, Copy, PartialEq)]
316pub struct Transform2D {
317    pub a: f32,  // scale x / cos
318    pub b: f32,  // shear y / sin
319    pub c: f32,  // shear x / -sin
320    pub d: f32,  // scale y / cos
321    pub tx: f32, // translate x
322    pub ty: f32, // translate y
323}
324
325impl Default for Transform2D {
326    #[inline(always)]
327    fn default() -> Self {
328        Self::IDENTITY
329    }
330}
331
332impl Transform2D {
333    pub const IDENTITY: Self = Self {
334        a: 1.0,
335        b: 0.0,
336        c: 0.0,
337        d: 1.0,
338        tx: 0.0,
339        ty: 0.0,
340    };
341
342    #[inline(always)]
343    pub const fn translation(tx: f32, ty: f32) -> Self {
344        Self {
345            a: 1.0,
346            b: 0.0,
347            c: 0.0,
348            d: 1.0,
349            tx,
350            ty,
351        }
352    }
353
354    #[inline(always)]
355    pub const fn scale(sx: f32, sy: f32) -> Self {
356        Self {
357            a: sx,
358            b: 0.0,
359            c: 0.0,
360            d: sy,
361            tx: 0.0,
362            ty: 0.0,
363        }
364    }
365
366    #[inline(always)]
367    pub fn rotation(radians: f32) -> Self {
368        let (sin, cos) = radians.sin_cos();
369        Self {
370            a: cos,
371            b: sin,
372            c: -sin,
373            d: cos,
374            tx: 0.0,
375            ty: 0.0,
376        }
377    }
378
379    #[inline(always)]
380    pub fn transform_point(self, p: Point<f32>) -> Point<f32> {
381        Point::new(
382            self.a * p.x + self.c * p.y + self.tx,
383            self.b * p.x + self.d * p.y + self.ty,
384        )
385    }
386
387    /// Creates a 2D affine transform from standard W3C 6-parameter coefficients:
388    /// `a` (scale x), `b` (shear y), `c` (shear x), `d` (scale y), `e` (translate x), `f` (translate y).
389    #[inline(always)]
390    pub const fn from_w3c(a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) -> Self {
391        Self {
392            a,
393            b,
394            c,
395            d,
396            tx: e,
397            ty: f,
398        }
399    }
400
401    #[inline(always)]
402    pub fn transform_xy(&self, x: f32, y: f32) -> (f32, f32) {
403        (
404            self.a * x + self.c * y + self.tx,
405            self.b * x + self.d * y + self.ty,
406        )
407    }
408
409    #[inline(always)]
410    pub fn translate(&mut self, dx: f32, dy: f32) {
411        *self = self.multiply(Self::translation(dx, dy));
412    }
413
414    #[inline(always)]
415    pub fn scale_mut(&mut self, sx: f32, sy: f32) {
416        *self = self.multiply(Self::scale(sx, sy));
417    }
418
419    #[inline(always)]
420    pub fn rotate_mut(&mut self, radians: f32) {
421        *self = self.multiply(Self::rotation(radians));
422    }
423
424    /// Concatenates this transform with another (`self * other`).
425    pub fn multiply(self, rhs: Self) -> Self {
426        Self {
427            a: self.a * rhs.a + self.c * rhs.b,
428            b: self.b * rhs.a + self.d * rhs.b,
429            c: self.a * rhs.c + self.c * rhs.d,
430            d: self.b * rhs.c + self.d * rhs.d,
431            tx: self.a * rhs.tx + self.c * rhs.ty + self.tx,
432            ty: self.b * rhs.tx + self.d * rhs.ty + self.ty,
433        }
434    }
435
436    /// Computes determinant of transformation.
437    #[inline(always)]
438    pub fn determinant(self) -> f32 {
439        self.a * self.d - self.b * self.c
440    }
441
442    /// Inverts the affine transform if non-singular.
443    pub fn inverse(self) -> Option<Self> {
444        let det = self.determinant();
445        if det.abs() < 1e-6 {
446            return None;
447        }
448        let inv_det = 1.0 / det;
449        Some(Self {
450            a: self.d * inv_det,
451            b: -self.b * inv_det,
452            c: -self.c * inv_det,
453            d: self.a * inv_det,
454            tx: (self.c * self.ty - self.d * self.tx) * inv_det,
455            ty: (self.b * self.tx - self.a * self.ty) * inv_det,
456        })
457    }
458}
459
460/// Fixed-point 1/64th pixel scalar coordinate (Chromium Blink LayoutUnit parity).
461#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash)]
462pub struct LayoutUnit(pub i32);
463
464impl LayoutUnit {
465    pub const SCALE: f32 = 64.0;
466    pub const ZERO: Self = Self(0);
467
468    #[inline(always)]
469    pub fn from_f32(val: f32) -> Self {
470        Self((val * Self::SCALE).round() as i32)
471    }
472
473    #[inline(always)]
474    pub fn to_f32(self) -> f32 {
475        self.0 as f32 / Self::SCALE
476    }
477
478    /// Snaps coordinate to physical device grid based on Device Pixel Ratio (DPR).
479    #[inline(always)]
480    pub fn snap_to_device_grid(self, dpr: f32) -> f32 {
481        let logical = self.to_f32();
482        (logical * dpr).round() / dpr
483    }
484
485    /// Chromium border snapping formula: guarantees at least 1 physical pixel width.
486    #[inline(always)]
487    pub fn snap_border(self, dpr: f32) -> f32 {
488        let physical = (self.to_f32() * dpr).round();
489        if physical < 1.0 && self.0 > 0 {
490            1.0 / dpr
491        } else {
492            physical / dpr
493        }
494    }
495}
496
497impl Add for LayoutUnit {
498    type Output = Self;
499    #[inline(always)]
500    fn add(self, rhs: Self) -> Self::Output {
501        Self(self.0 + rhs.0)
502    }
503}
504
505impl Sub for LayoutUnit {
506    type Output = Self;
507    #[inline(always)]
508    fn sub(self, rhs: Self) -> Self::Output {
509        Self(self.0 - rhs.0)
510    }
511}
512
513impl Mul<i32> for LayoutUnit {
514    type Output = Self;
515    #[inline(always)]
516    fn mul(self, rhs: i32) -> Self::Output {
517        Self(self.0 * rhs)
518    }
519}
520
521impl Div<i32> for LayoutUnit {
522    type Output = Self;
523    #[inline(always)]
524    fn div(self, rhs: i32) -> Self::Output {
525        Self(self.0 / rhs)
526    }
527}
528
529/// Cache-aligned 1/64th fixed-point integer layout rectangle.
530#[repr(C)]
531#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
532pub struct FixedRect {
533    pub x: i32,
534    pub y: i32,
535    pub width: i32,
536    pub height: i32,
537}
538
539impl FixedRect {
540    pub const ZERO: Self = Self {
541        x: 0,
542        y: 0,
543        width: 0,
544        height: 0,
545    };
546
547    #[inline(always)]
548    pub fn from_f32(x: f32, y: f32, width: f32, height: f32) -> Self {
549        Self {
550            x: (x * LayoutUnit::SCALE).round() as i32,
551            y: (y * LayoutUnit::SCALE).round() as i32,
552            width: (width * LayoutUnit::SCALE).round() as i32,
553            height: (height * LayoutUnit::SCALE).round() as i32,
554        }
555    }
556
557    #[inline(always)]
558    pub fn to_rect_f32(self) -> Rect<f32> {
559        Rect::from_xywh(
560            self.x as f32 / LayoutUnit::SCALE,
561            self.y as f32 / LayoutUnit::SCALE,
562            self.width as f32 / LayoutUnit::SCALE,
563            self.height as f32 / LayoutUnit::SCALE,
564        )
565    }
566
567    #[inline(always)]
568    pub fn snap_to_grid(self, dpr: f32) -> Rect<f32> {
569        let r = self.to_rect_f32();
570        Rect::from_xywh(
571            (r.origin.x * dpr).round() / dpr,
572            (r.origin.y * dpr).round() / dpr,
573            (r.size.width * dpr).round() / dpr,
574            (r.size.height * dpr).round() / dpr,
575        )
576    }
577}
578
579/// 4x4 homogeneous transformation matrix stored in column-major order.
580///
581/// Matrix indices:
582/// [ 0  4  8 12 ]
583/// [ 1  5  9 13 ]
584/// [ 2  6 10 14 ]
585/// [ 3  7 11 15 ]
586#[repr(C)]
587#[derive(Debug, Clone, Copy, PartialEq)]
588pub struct Matrix4x4 {
589    pub m: [f32; 16],
590}
591
592impl Default for Matrix4x4 {
593    #[inline(always)]
594    fn default() -> Self {
595        Self::identity()
596    }
597}
598
599impl Matrix4x4 {
600    pub const IDENTITY: Self = Self {
601        m: [
602            1.0, 0.0, 0.0, 0.0, // col 0
603            0.0, 1.0, 0.0, 0.0, // col 1
604            0.0, 0.0, 1.0, 0.0, // col 2
605            0.0, 0.0, 0.0, 1.0, // col 3
606        ],
607    };
608
609    #[inline(always)]
610    pub const fn identity() -> Self {
611        Self::IDENTITY
612    }
613
614    #[inline(always)]
615    pub const fn from_array(m: [f32; 16]) -> Self {
616        Self { m }
617    }
618
619    /// Constructs a 4x4 matrix from 2D affine matrix components:
620    /// `matrix(a, b, c, d, e, f)` where `a, c, e` are row 0, `b, d, f` are row 1.
621    #[inline(always)]
622    pub const fn from_2d(a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) -> Self {
623        Self {
624            m: [
625                a, b, 0.0, 0.0, c, d, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, e, f, 0.0, 1.0,
626            ],
627        }
628    }
629
630    /// Creates a 3D translation matrix.
631    #[inline(always)]
632    pub fn translation(tx: f32, ty: f32, tz: f32) -> Self {
633        Self {
634            m: [
635                1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, tx, ty, tz, 1.0,
636            ],
637        }
638    }
639
640    /// Creates a 3D scaling matrix.
641    #[inline(always)]
642    pub fn scaling(sx: f32, sy: f32, sz: f32) -> Self {
643        Self {
644            m: [
645                sx, 0.0, 0.0, 0.0, 0.0, sy, 0.0, 0.0, 0.0, 0.0, sz, 0.0, 0.0, 0.0, 0.0, 1.0,
646            ],
647        }
648    }
649
650    /// Creates a rotation matrix around the Z axis (standard 2D rotation).
651    #[inline(always)]
652    pub fn rotation_z(rad: f32) -> Self {
653        let (sin, cos) = rad.sin_cos();
654        Self {
655            m: [
656                cos, sin, 0.0, 0.0, -sin, cos, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
657            ],
658        }
659    }
660
661    /// Creates a rotation matrix around the X axis.
662    #[inline(always)]
663    pub fn rotation_x(rad: f32) -> Self {
664        let (sin, cos) = rad.sin_cos();
665        Self {
666            m: [
667                1.0, 0.0, 0.0, 0.0, 0.0, cos, sin, 0.0, 0.0, -sin, cos, 0.0, 0.0, 0.0, 0.0, 1.0,
668            ],
669        }
670    }
671
672    /// Creates a rotation matrix around the Y axis.
673    #[inline(always)]
674    pub fn rotation_y(rad: f32) -> Self {
675        let (sin, cos) = rad.sin_cos();
676        Self {
677            m: [
678                cos, 0.0, -sin, 0.0, 0.0, 1.0, 0.0, 0.0, sin, 0.0, cos, 0.0, 0.0, 0.0, 0.0, 1.0,
679            ],
680        }
681    }
682
683    /// Creates a rotation matrix around an arbitrary 3D axis `[x, y, z]`.
684    pub fn rotation_axis(x: f32, y: f32, z: f32, rad: f32) -> Self {
685        let len = (x * x + y * y + z * z).sqrt();
686        if len < 1e-6 {
687            return Self::identity();
688        }
689        let (x, y, z) = (x / len, y / len, z / len);
690        let (sin, cos) = rad.sin_cos();
691        let one_minus_cos = 1.0 - cos;
692
693        Self {
694            m: [
695                cos + x * x * one_minus_cos,
696                y * x * one_minus_cos + z * sin,
697                z * x * one_minus_cos - y * sin,
698                0.0,
699                x * y * one_minus_cos - z * sin,
700                cos + y * y * one_minus_cos,
701                z * y * one_minus_cos + x * sin,
702                0.0,
703                x * z * one_minus_cos + y * sin,
704                y * z * one_minus_cos - x * sin,
705                cos + z * z * one_minus_cos,
706                0.0,
707                0.0,
708                0.0,
709                0.0,
710                1.0,
711            ],
712        }
713    }
714
715    /// Creates a 2D skew matrix given horizontal and vertical angles in radians.
716    #[inline(always)]
717    pub fn skew(ax_rad: f32, ay_rad: f32) -> Self {
718        Self {
719            m: [
720                1.0,
721                ay_rad.tan(),
722                0.0,
723                0.0,
724                ax_rad.tan(),
725                1.0,
726                0.0,
727                0.0,
728                0.0,
729                0.0,
730                1.0,
731                0.0,
732                0.0,
733                0.0,
734                0.0,
735                1.0,
736            ],
737        }
738    }
739
740    /// Creates a perspective projection matrix where `d` is the distance to the projection plane.
741    #[inline(always)]
742    pub fn perspective(d: f32) -> Self {
743        let p = if d > 0.0 { -1.0 / d } else { 0.0 };
744        Self {
745            m: [
746                1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, p, 0.0, 0.0, 0.0, 1.0,
747            ],
748        }
749    }
750
751    /// Multiplies `self` by `rhs`: `Result = self * rhs`.
752    pub fn multiply(&self, rhs: &Self) -> Self {
753        let a = &self.m;
754        let b = &rhs.m;
755        let mut r = [0.0f32; 16];
756
757        for col in 0..4 {
758            for row in 0..4 {
759                r[col * 4 + row] = a[row] * b[col * 4]
760                    + a[4 + row] * b[col * 4 + 1]
761                    + a[8 + row] * b[col * 4 + 2]
762                    + a[12 + row] * b[col * 4 + 3];
763            }
764        }
765
766        Self { m: r }
767    }
768
769    /// Computes the determinant of the 4x4 matrix using Laplace expansion.
770    pub fn determinant(&self) -> f32 {
771        let m = &self.m;
772        let s0 = m[0] * m[5] - m[1] * m[4];
773        let s1 = m[0] * m[6] - m[2] * m[4];
774        let s2 = m[0] * m[7] - m[3] * m[4];
775        let s3 = m[1] * m[6] - m[2] * m[5];
776        let s4 = m[1] * m[7] - m[3] * m[5];
777        let s5 = m[2] * m[7] - m[3] * m[6];
778
779        let c5 = m[10] * m[15] - m[11] * m[14];
780        let c4 = m[9] * m[15] - m[11] * m[13];
781        let c3 = m[9] * m[14] - m[10] * m[13];
782        let c2 = m[8] * m[15] - m[11] * m[12];
783        let c1 = m[8] * m[14] - m[10] * m[12];
784        let c0 = m[8] * m[13] - m[9] * m[12];
785
786        s0 * c5 - s1 * c4 + s2 * c3 + s3 * c2 - s4 * c1 + s5 * c0
787    }
788
789    /// Computes the analytical inverse of the 4x4 matrix.
790    pub fn inverse(&self) -> Option<Self> {
791        let m = &self.m;
792        let s0 = m[0] * m[5] - m[1] * m[4];
793        let s1 = m[0] * m[6] - m[2] * m[4];
794        let s2 = m[0] * m[7] - m[3] * m[4];
795        let s3 = m[1] * m[6] - m[2] * m[5];
796        let s4 = m[1] * m[7] - m[3] * m[5];
797        let s5 = m[2] * m[7] - m[3] * m[6];
798
799        let c5 = m[10] * m[15] - m[11] * m[14];
800        let c4 = m[9] * m[15] - m[11] * m[13];
801        let c3 = m[9] * m[14] - m[10] * m[13];
802        let c2 = m[8] * m[15] - m[11] * m[12];
803        let c1 = m[8] * m[14] - m[10] * m[12];
804        let c0 = m[8] * m[13] - m[9] * m[12];
805
806        let det = s0 * c5 - s1 * c4 + s2 * c3 + s3 * c2 - s4 * c1 + s5 * c0;
807        if det.abs() < 1e-7 {
808            return None;
809        }
810
811        let inv_det = 1.0 / det;
812        let mut inv = [0.0f32; 16];
813
814        inv[0] = (m[5] * c5 - m[6] * c4 + m[7] * c3) * inv_det;
815        inv[1] = (-m[1] * c5 + m[2] * c4 - m[3] * c3) * inv_det;
816        inv[2] = (m[13] * s5 - m[14] * s4 + m[15] * s3) * inv_det;
817        inv[3] = (-m[9] * s5 + m[10] * s4 - m[11] * s3) * inv_det;
818
819        inv[4] = (-m[4] * c5 + m[6] * c2 - m[7] * c1) * inv_det;
820        inv[5] = (m[0] * c5 - m[2] * c2 + m[3] * c1) * inv_det;
821        inv[6] = (-m[12] * s5 + m[14] * s2 - m[15] * s1) * inv_det;
822        inv[7] = (m[8] * s5 - m[10] * s2 + m[11] * s1) * inv_det;
823
824        inv[8] = (m[4] * c4 - m[5] * c2 + m[7] * c0) * inv_det;
825        inv[9] = (-m[0] * c4 + m[1] * c2 - m[3] * c0) * inv_det;
826        inv[10] = (m[12] * s4 - m[13] * s2 + m[15] * s0) * inv_det;
827        inv[11] = (-m[8] * s4 + m[9] * s2 - m[11] * s0) * inv_det;
828
829        inv[12] = (-m[4] * c3 + m[5] * c1 - m[6] * c0) * inv_det;
830        inv[13] = (m[0] * c3 - m[1] * c1 + m[2] * c0) * inv_det;
831        inv[14] = (-m[12] * s3 + m[13] * s1 - m[14] * s0) * inv_det;
832        inv[15] = (m[8] * s3 - m[9] * s1 + m[10] * s0) * inv_det;
833
834        Some(Self { m: inv })
835    }
836
837    /// Transforms a 2D point using homogeneous coordinates with perspective divide.
838    pub fn transform_point2d(&self, p: Point<f32>) -> Point<f32> {
839        let m = &self.m;
840        let x = m[0] * p.x + m[4] * p.y + m[12];
841        let y = m[1] * p.x + m[5] * p.y + m[13];
842        let w = m[3] * p.x + m[7] * p.y + m[15];
843
844        if w.abs() > 1e-6 && (w - 1.0).abs() > 1e-6 {
845            Point::new(x / w, y / w)
846        } else {
847            Point::new(x, y)
848        }
849    }
850
851    /// Transforms 2D coordinates `(x, y)` using homogeneous coordinates with perspective divide.
852    #[inline]
853    pub fn transform_point(&self, x: f32, y: f32) -> (f32, f32) {
854        let p = self.transform_point2d(Point::new(x, y));
855        (p.x, p.y)
856    }
857
858    /// Transforms an axis-aligned rectangle, computing its new bounding box.
859    pub fn transform_rect(&self, r: Rect<f32>) -> Rect<f32> {
860        let p1 = self.transform_point2d(Point::new(r.origin.x, r.origin.y));
861        let p2 = self.transform_point2d(Point::new(r.origin.x + r.size.width, r.origin.y));
862        let p3 = self.transform_point2d(Point::new(r.origin.x, r.origin.y + r.size.height));
863        let p4 = self.transform_point2d(Point::new(
864            r.origin.x + r.size.width,
865            r.origin.y + r.size.height,
866        ));
867
868        let min_x = p1.x.min(p2.x).min(p3.x).min(p4.x);
869        let max_x = p1.x.max(p2.x).max(p3.x).max(p4.x);
870        let min_y = p1.y.min(p2.y).min(p3.y).min(p4.y);
871        let max_y = p1.y.max(p2.y).max(p3.y).max(p4.y);
872
873        Rect::from_xywh(min_x, min_y, max_x - min_x, max_y - min_y)
874    }
875
876    /// Transforms an axis-aligned rectangle `(x, y, width, height)` returning the new bounding box `(min_x, min_y, w, h)`.
877    #[inline]
878    pub fn transform_bounds(
879        &self,
880        x: f32,
881        y: f32,
882        width: f32,
883        height: f32,
884    ) -> (f32, f32, f32, f32) {
885        let r = self.transform_rect(Rect::from_xywh(x, y, width, height));
886        (r.origin.x, r.origin.y, r.size.width, r.size.height)
887    }
888
889    /// Returns true if this matrix is approximately the identity matrix.
890    pub fn is_identity(&self) -> bool {
891        let id = Self::IDENTITY.m;
892        for (i, &expected) in id.iter().enumerate() {
893            if (self.m[i] - expected).abs() > 1e-5 {
894                return false;
895            }
896        }
897        true
898    }
899
900    /// Returns true if this matrix represents a pure 2D affine transformation (no Z or perspective).
901    pub fn is_2d(&self) -> bool {
902        let m = &self.m;
903        m[2].abs() < 1e-5
904            && m[3].abs() < 1e-5
905            && m[6].abs() < 1e-5
906            && m[7].abs() < 1e-5
907            && m[8].abs() < 1e-5
908            && m[9].abs() < 1e-5
909            && (m[10] - 1.0).abs() < 1e-5
910            && m[11].abs() < 1e-5
911            && m[14].abs() < 1e-5
912            && (m[15] - 1.0).abs() < 1e-5
913    }
914}