1use crate::{Point, Rect};
2
3#[derive(Clone, Copy, Debug, PartialEq)]
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9#[cfg_attr(feature = "serde", serde(transparent))]
10pub struct Matrix(glam::Mat4);
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum MatrixKind {
15 AxisAligned,
17 Affine,
19 General,
21}
22
23const W_EPSILON: f32 = 1e-6;
25
26impl Matrix {
27 pub const IDENTITY: Matrix = Matrix(glam::Mat4::IDENTITY);
29
30 pub fn translation(tx: f32, ty: f32) -> Self {
32 Matrix(glam::Mat4::from_translation(glam::Vec3::new(tx, ty, 0.0)))
33 }
34
35 pub fn scale(sx: f32, sy: f32) -> Self {
37 Matrix(glam::Mat4::from_scale(glam::Vec3::new(sx, sy, 1.0)))
38 }
39
40 pub fn rotation(radians: f32) -> Self {
44 Matrix(glam::Mat4::from_rotation_z(radians))
45 }
46
47 pub fn from_affine(a: f32, b: f32, c: f32, d: f32, tx: f32, ty: f32) -> Self {
51 Matrix(glam::Mat4::from_cols_array(&[
52 a, b, 0.0, 0.0, c, d, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, tx, ty, 0.0, 1.0,
56 ]))
57 }
58
59 pub fn from_flutter_array(values: &[f32; 16]) -> Self {
61 Matrix(glam::Mat4::from_cols_array(values))
62 }
63
64 pub fn to_flutter_array(&self) -> [f32; 16] {
66 self.0.to_cols_array()
67 }
68
69 pub fn to_mat4(self) -> glam::Mat4 {
71 self.0
72 }
73
74 pub fn then(&self, other: &Matrix) -> Matrix {
78 Matrix(self.0 * other.0)
79 }
80
81 pub fn is_affine(&self) -> bool {
83 let m = &self.0;
84 m.x_axis.w == 0.0 && m.y_axis.w == 0.0 && m.w_axis.w == 1.0
85 }
86
87 pub fn kind(&self) -> MatrixKind {
89 if !self.is_affine() {
90 return MatrixKind::General;
91 }
92 let m = &self.0;
93 let axis_aligned =
94 m.x_axis.y == 0.0 && m.y_axis.x == 0.0 && m.x_axis.x > 0.0 && m.y_axis.y > 0.0;
95 if axis_aligned {
96 MatrixKind::AxisAligned
97 } else {
98 MatrixKind::Affine
99 }
100 }
101
102 pub(crate) fn rect_stays_rect(&self) -> bool {
107 if !self.is_affine() {
108 return false;
109 }
110 let [a, b, c, d, ..] = self.to_affine();
111 let scales = b == 0.0 && c == 0.0 && a != 0.0 && d != 0.0;
112 let turns = a == 0.0 && d == 0.0 && b != 0.0 && c != 0.0;
113 scales || turns
114 }
115
116 pub fn map_point(&self, p: Point) -> Point {
120 let v = self.0 * glam::Vec4::new(p.x, p.y, 0.0, 1.0);
121 let w = if v.w > W_EPSILON { v.w } else { W_EPSILON };
122 Point::new(v.x / w, v.y / w)
123 }
124
125 pub fn map_rect(&self, r: &Rect) -> Rect {
130 let (mut left, mut top) = (f32::MAX, f32::MAX);
131 let (mut right, mut bottom) = (f32::MIN, f32::MIN);
132 for corner in r.corners() {
133 let v = self.0 * glam::Vec4::new(corner.x, corner.y, 0.0, 1.0);
134 if v.w <= W_EPSILON {
135 return Rect::EVERYTHING;
136 }
137 let (x, y) = (v.x / v.w, v.y / v.w);
138 left = left.min(x);
139 top = top.min(y);
140 right = right.max(x);
141 bottom = bottom.max(y);
142 }
143 Rect::from_ltrb(left, top, right, bottom)
144 }
145
146 pub fn max_scale(&self) -> f32 {
150 let m = &self.0;
151 let sx = (m.x_axis.x * m.x_axis.x + m.x_axis.y * m.x_axis.y).sqrt();
152 let sy = (m.y_axis.x * m.y_axis.x + m.y_axis.y * m.y_axis.y).sqrt();
153 sx.max(sy)
154 }
155
156 pub fn to_affine(&self) -> [f32; 6] {
161 let m = &self.0;
162 [
163 m.x_axis.x, m.x_axis.y, m.y_axis.x, m.y_axis.y, m.w_axis.x, m.w_axis.y,
164 ]
165 }
166
167 pub fn determinant(&self) -> f32 {
169 let m = &self.0;
170 m.x_axis.x * m.y_axis.y - m.x_axis.y * m.y_axis.x
171 }
172
173 pub fn invert(&self) -> Option<Matrix> {
175 let det = self.0.determinant();
176 if det == 0.0 || !det.is_finite() {
177 return None;
178 }
179 let inverse = self.0.inverse();
180 inverse.is_finite().then_some(Matrix(inverse))
181 }
182}
183
184impl Default for Matrix {
185 fn default() -> Self {
186 Self::IDENTITY
187 }
188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193
194 fn close(a: Point, b: Point) -> bool {
195 (a.x - b.x).abs() < 1e-4 && (a.y - b.y).abs() < 1e-4
196 }
197
198 #[test]
199 fn near_singular_matrices_invert_to_none() {
200 assert!(Matrix::scale(1e-20, 1e-20).invert().is_none());
201 assert!(Matrix::scale(0.0, 1.0).invert().is_none());
202 }
203
204 #[test]
205 fn then_applies_local_first() {
206 let t = Matrix::translation(10.0, 0.0).then(&Matrix::scale(2.0, 2.0));
208 assert!(close(
209 t.map_point(Point::new(1.0, 1.0)),
210 Point::new(12.0, 2.0)
211 ));
212 }
213
214 #[test]
215 fn rotation_quarter_turn() {
216 let t = Matrix::rotation(std::f32::consts::FRAC_PI_2);
217 assert!(close(
219 t.map_point(Point::new(1.0, 0.0)),
220 Point::new(0.0, 1.0)
221 ));
222 }
223
224 #[test]
225 fn invert_roundtrip() {
226 let t = Matrix::translation(5.0, -3.0)
227 .then(&Matrix::rotation(0.7))
228 .then(&Matrix::scale(2.0, 0.5));
229 let inv = t.invert().unwrap();
230 let p = Point::new(3.0, 4.0);
231 assert!(close(inv.map_point(t.map_point(p)), p));
232 }
233
234 #[test]
235 fn map_rect_rotation_is_conservative_bounds() {
236 let t = Matrix::rotation(std::f32::consts::FRAC_PI_4);
237 let r = t.map_rect(&Rect::new(-1.0, -1.0, 2.0, 2.0));
238 let d = 2.0_f32.sqrt();
239 assert!((r.width - 2.0 * d).abs() < 1e-4 && (r.height - 2.0 * d).abs() < 1e-4);
240 }
241
242 #[test]
243 fn perspective_divides_by_w() {
244 let mut values = Matrix::IDENTITY.to_flutter_array();
248 values[3] = 0.001; let t = Matrix::from_flutter_array(&values);
250 assert!(close(
251 t.map_point(Point::new(100.0, 100.0)),
252 Point::new(100.0 / 1.1, 100.0 / 1.1)
253 ));
254 assert_eq!(t.kind(), MatrixKind::General);
255 }
256
257 #[test]
258 fn concatenation_stays_four_by_four() {
259 let mut tilt_values = Matrix::IDENTITY.to_flutter_array();
264 tilt_values[11] = 0.001; let tilt = Matrix::from_flutter_array(&tilt_values);
266 let mut rotate_x = Matrix::IDENTITY.to_flutter_array();
267 let (sin, cos) = 0.5_f32.sin_cos();
269 rotate_x[5] = cos;
270 rotate_x[6] = sin;
271 rotate_x[9] = -sin;
272 rotate_x[10] = cos;
273 let full = tilt.then(&Matrix::from_flutter_array(&rotate_x));
274 assert_eq!(full.kind(), MatrixKind::General);
276 let p = full.map_point(Point::new(0.0, 100.0));
277 let expected_y = 100.0 * cos / (1.0 + 0.001 * 100.0 * sin);
279 assert!((p.y - expected_y).abs() < 1e-2, "{} vs {expected_y}", p.y);
280 }
281
282 #[test]
283 fn eye_plane_bounds_are_everything() {
284 let mut values = Matrix::IDENTITY.to_flutter_array();
285 values[3] = -0.1; let t = Matrix::from_flutter_array(&values);
287 assert_eq!(
288 t.map_rect(&Rect::new(0.0, 0.0, 100.0, 10.0)),
289 Rect::EVERYTHING
290 );
291 }
292}