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, pub shear_x: f32,
70 pub shear_y: f32,
72 pub rotation_x: f32,
74 pub rotation_y: f32,
76 pub camera_distance: f32,
78 pub origin_x: f32,
90 pub origin_y: f32,
91 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 perspective: [0.0, 0.0, 1.0],
477 }
478 }
479}
480
481fn 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 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 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 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 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 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}