1#[derive(Debug, Clone, Copy, PartialEq)]
5pub struct Point {
6 pub x: f64,
8 pub y: f64,
10}
11
12impl Point {
13 pub const fn new(x: f64, y: f64) -> Self {
15 Self { x, y }
16 }
17}
18
19#[derive(Debug, Clone, Copy, PartialEq)]
21pub struct Matrix {
22 pub a: f64,
24 pub b: f64,
26 pub c: f64,
28 pub d: f64,
30 pub e: f64,
32 pub f: f64,
34}
35
36impl Matrix {
37 pub const IDENTITY: Self = Self {
39 a: 1.0,
40 b: 0.0,
41 c: 0.0,
42 d: 1.0,
43 e: 0.0,
44 f: 0.0,
45 };
46
47 pub const fn new(a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) -> Self {
49 Self { a, b, c, d, e, f }
50 }
51
52 pub fn multiply(self, other: Self) -> Self {
56 Self {
57 a: self.a * other.a + self.b * other.c,
58 b: self.a * other.b + self.b * other.d,
59 c: self.c * other.a + self.d * other.c,
60 d: self.c * other.b + self.d * other.d,
61 e: self.e * other.a + self.f * other.c + other.e,
62 f: self.e * other.b + self.f * other.d + other.f,
63 }
64 }
65
66 pub fn apply(self, point: Point) -> Point {
68 Point {
69 x: self.a * point.x + self.c * point.y + self.e,
70 y: self.b * point.x + self.d * point.y + self.f,
71 }
72 }
73
74 pub fn invert(self) -> Option<Self> {
76 let determinant = self.a * self.d - self.b * self.c;
77 if determinant.abs() < 1e-12 {
78 return None;
79 }
80 let scale = 1.0 / determinant;
81 Some(Self {
82 a: self.d * scale,
83 b: -self.b * scale,
84 c: -self.c * scale,
85 d: self.a * scale,
86 e: (self.c * self.f - self.d * self.e) * scale,
87 f: (self.b * self.e - self.a * self.f) * scale,
88 })
89 }
90}
91
92#[cfg(test)]
93mod tests {
94 use super::{Matrix, Point};
95
96 #[test]
97 fn the_identity_leaves_points_alone() {
98 assert_eq!(
99 Matrix::IDENTITY.apply(Point::new(3.0, -4.0)),
100 Point::new(3.0, -4.0)
101 );
102 }
103
104 #[test]
105 fn multiplication_applies_the_first_matrix_first() {
106 let translate = Matrix::new(1.0, 0.0, 0.0, 1.0, 10.0, 0.0);
107 let scale = Matrix::new(2.0, 0.0, 0.0, 2.0, 0.0, 0.0);
108 assert_eq!(
110 translate.multiply(scale).apply(Point::new(1.0, 0.0)),
111 Point::new(22.0, 0.0)
112 );
113 assert_eq!(
115 scale.multiply(translate).apply(Point::new(1.0, 0.0)),
116 Point::new(12.0, 0.0)
117 );
118 }
119
120 #[test]
121 fn inversion_round_trips_a_point() {
122 let matrix = Matrix::new(2.0, 0.5, -0.5, 3.0, 7.0, -9.0);
123 let inverse = matrix.invert().expect("invertible");
124 let point = Point::new(4.0, 5.0);
125 let back = inverse.apply(matrix.apply(point));
126 assert!((back.x - point.x).abs() < 1e-9 && (back.y - point.y).abs() < 1e-9);
127 }
128
129 #[test]
130 fn singular_matrices_have_no_inverse() {
131 assert!(Matrix::new(0.0, 0.0, 0.0, 0.0, 1.0, 1.0).invert().is_none());
132 }
133}