1// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution.
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10#![cfg_attr(feature = "cargo-clippy", allow(just_underscores_and_digits))]
11
12use super::{UnknownUnit, Angle};
13#[cfg(feature = "mint")]
14use mint;
15use crate::num::{One, Zero};
16use crate::point::{Point2D, point2};
17use crate::vector::{Vector2D, vec2};
18use crate::rect::Rect;
19use crate::box2d::Box2D;
20use crate::transform3d::Transform3D;
21use core::ops::{Add, Mul, Div, Sub};
22use core::marker::PhantomData;
23use core::cmp::{Eq, PartialEq};
24use core::hash::{Hash};
25use crate::approxeq::ApproxEq;
26use crate::trig::Trig;
27use core::fmt;
28use num_traits::NumCast;
29#[cfg(feature = "serde")]
30use serde::{Deserialize, Serialize};
31#[cfg(feature = "bytemuck")]
32use bytemuck::{Zeroable, Pod};
33
34/// A 2d transform represented by a column-major 3 by 3 matrix, compressed down to 3 by 2.
35///
36/// Transforms can be parametrized over the source and destination units, to describe a
37/// transformation from a space to another.
38/// For example, `Transform2D<f32, WorldSpace, ScreenSpace>::transform_point4d`
39/// takes a `Point2D<f32, WorldSpace>` and returns a `Point2D<f32, ScreenSpace>`.
40///
41/// Transforms expose a set of convenience methods for pre- and post-transformations.
42/// Pre-transformations (`pre_*` methods) correspond to adding an operation that is
43/// applied before the rest of the transformation, while post-transformations (`then_*`
44/// methods) add an operation that is applied after.
45///
46/// The matrix representation is conceptually equivalent to a 3 by 3 matrix transformation
47/// compressed to 3 by 2 with the components that aren't needed to describe the set of 2d
48/// transformations we are interested in implicitly defined:
49///
50/// ```text
51/// | m11 m12 0 | |x| |x'|
52/// | m21 m22 0 | x |y| = |y'|
53/// | m31 m32 1 | |1| |w |
54/// ```
55///
56/// When translating Transform2D into general matrix representations, consider that the
57/// representation follows the column-major notation with column vectors.
58///
59/// The translation terms are m31 and m32.
60#[repr(C)]
61#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
62#[cfg_attr(
63 feature = "serde",
64 serde(bound(serialize = "T: Serialize", deserialize = "T: Deserialize<'de>"))
65)]
66pub struct Transform2D<T, Src, Dst> {
67 pub m11: T, pub m12: T,
68 pub m21: T, pub m22: T,
69 pub m31: T, pub m32: T,
70 #[doc(hidden)]
71 pub _unit: PhantomData<(Src, Dst)>,
72}
73
74#[cfg(feature = "arbitrary")]
75impl<'a, T, Src, Dst> arbitrary::Arbitrary<'a> for Transform2D<T, Src, Dst>
76where
77 T: arbitrary::Arbitrary<'a>,
78{
79 fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self>
80 {
81 let (m11, m12, m21, m22, m31, m32) = arbitrary::Arbitrary::arbitrary(u)?;
82 Ok(Transform2D {
83 m11, m12, m21, m22, m31, m32,
84 _unit: PhantomData,
85 })
86 }
87}
88
89#[cfg(feature = "bytemuck")]
90unsafe impl<T: Zeroable, Src, Dst> Zeroable for Transform2D<T, Src, Dst> {}
91
92#[cfg(feature = "bytemuck")]
93unsafe impl<T: Pod, Src: 'static, Dst: 'static> Pod for Transform2D<T, Src, Dst> {}
94
95impl<T: Copy, Src, Dst> Copy for Transform2D<T, Src, Dst> {}
96
97impl<T: Clone, Src, Dst> Clone for Transform2D<T, Src, Dst> {
98 fn clone(&self) -> Self {
99 Transform2D {
100 m11: self.m11.clone(),
101 m12: self.m12.clone(),
102 m21: self.m21.clone(),
103 m22: self.m22.clone(),
104 m31: self.m31.clone(),
105 m32: self.m32.clone(),
106 _unit: PhantomData,
107 }
108 }
109}
110
111impl<T, Src, Dst> Eq for Transform2D<T, Src, Dst> where T: Eq {}
112
113impl<T, Src, Dst> PartialEq for Transform2D<T, Src, Dst>
114 where T: PartialEq
115{
116 fn eq(&self, other: &Self) -> bool {
117 self.m11 == other.m11 &&
118 self.m12 == other.m12 &&
119 self.m21 == other.m21 &&
120 self.m22 == other.m22 &&
121 self.m31 == other.m31 &&
122 self.m32 == other.m32
123 }
124}
125
126impl<T, Src, Dst> Hash for Transform2D<T, Src, Dst>
127 where T: Hash
128{
129 fn hash<H: core::hash::Hasher>(&self, h: &mut H) {
130 self.m11.hash(state:h);
131 self.m12.hash(state:h);
132 self.m21.hash(state:h);
133 self.m22.hash(state:h);
134 self.m31.hash(state:h);
135 self.m32.hash(state:h);
136 }
137}
138
139
140impl<T, Src, Dst> Transform2D<T, Src, Dst> {
141 /// Create a transform specifying its components in using the column-major-column-vector
142 /// matrix notation.
143 ///
144 /// For example, the translation terms m31 and m32 are the last two parameters parameters.
145 ///
146 /// ```
147 /// use euclid::default::Transform2D;
148 /// let tx = 1.0;
149 /// let ty = 2.0;
150 /// let translation = Transform2D::new(
151 /// 1.0, 0.0,
152 /// 0.0, 1.0,
153 /// tx, ty,
154 /// );
155 /// ```
156 pub const fn new(m11: T, m12: T, m21: T, m22: T, m31: T, m32: T) -> Self {
157 Transform2D {
158 m11, m12,
159 m21, m22,
160 m31, m32,
161 _unit: PhantomData,
162 }
163 }
164
165 /// Returns true is this transform is approximately equal to the other one, using
166 /// T's default epsilon value.
167 ///
168 /// The same as [`ApproxEq::approx_eq()`] but available without importing trait.
169 ///
170 /// [`ApproxEq::approx_eq()`]: ./approxeq/trait.ApproxEq.html#method.approx_eq
171 #[inline]
172 pub fn approx_eq(&self, other: &Self) -> bool
173 where T : ApproxEq<T> {
174 <Self as ApproxEq<T>>::approx_eq(&self, &other)
175 }
176
177 /// Returns true is this transform is approximately equal to the other one, using
178 /// a provided epsilon value.
179 ///
180 /// The same as [`ApproxEq::approx_eq_eps()`] but available without importing trait.
181 ///
182 /// [`ApproxEq::approx_eq_eps()`]: ./approxeq/trait.ApproxEq.html#method.approx_eq_eps
183 #[inline]
184 pub fn approx_eq_eps(&self, other: &Self, eps: &T) -> bool
185 where T : ApproxEq<T> {
186 <Self as ApproxEq<T>>::approx_eq_eps(&self, &other, &eps)
187 }
188}
189
190impl<T: Copy, Src, Dst> Transform2D<T, Src, Dst> {
191 /// Returns an array containing this transform's terms.
192 ///
193 /// The terms are laid out in the same order as they are
194 /// specified in `Transform2D::new`, that is following the
195 /// column-major-column-vector matrix notation.
196 ///
197 /// For example the translation terms are found in the
198 /// last two slots of the array.
199 #[inline]
200 pub fn to_array(&self) -> [T; 6] {
201 [
202 self.m11, self.m12,
203 self.m21, self.m22,
204 self.m31, self.m32
205 ]
206 }
207
208 /// Returns an array containing this transform's terms transposed.
209 ///
210 /// The terms are laid out in transposed order from the same order of
211 /// `Transform3D::new` and `Transform3D::to_array`, that is following
212 /// the row-major-column-vector matrix notation.
213 ///
214 /// For example the translation terms are found at indices 2 and 5
215 /// in the array.
216 #[inline]
217 pub fn to_array_transposed(&self) -> [T; 6] {
218 [
219 self.m11, self.m21, self.m31,
220 self.m12, self.m22, self.m32
221 ]
222 }
223
224 /// Equivalent to `to_array` with elements packed two at a time
225 /// in an array of arrays.
226 #[inline]
227 pub fn to_arrays(&self) -> [[T; 2]; 3] {
228 [
229 [self.m11, self.m12],
230 [self.m21, self.m22],
231 [self.m31, self.m32],
232 ]
233 }
234
235 /// Create a transform providing its components via an array
236 /// of 6 elements instead of as individual parameters.
237 ///
238 /// The order of the components corresponds to the
239 /// column-major-column-vector matrix notation (the same order
240 /// as `Transform2D::new`).
241 #[inline]
242 pub fn from_array(array: [T; 6]) -> Self {
243 Self::new(
244 array[0], array[1],
245 array[2], array[3],
246 array[4], array[5],
247 )
248 }
249
250 /// Equivalent to `from_array` with elements packed two at a time
251 /// in an array of arrays.
252 ///
253 /// The order of the components corresponds to the
254 /// column-major-column-vector matrix notation (the same order
255 /// as `Transform3D::new`).
256 #[inline]
257 pub fn from_arrays(array: [[T; 2]; 3]) -> Self {
258 Self::new(
259 array[0][0], array[0][1],
260 array[1][0], array[1][1],
261 array[2][0], array[2][1],
262 )
263 }
264
265 /// Drop the units, preserving only the numeric value.
266 #[inline]
267 pub fn to_untyped(&self) -> Transform2D<T, UnknownUnit, UnknownUnit> {
268 Transform2D::new(
269 self.m11, self.m12,
270 self.m21, self.m22,
271 self.m31, self.m32
272 )
273 }
274
275 /// Tag a unitless value with units.
276 #[inline]
277 pub fn from_untyped(p: &Transform2D<T, UnknownUnit, UnknownUnit>) -> Self {
278 Transform2D::new(
279 p.m11, p.m12,
280 p.m21, p.m22,
281 p.m31, p.m32
282 )
283 }
284
285 /// Returns the same transform with a different source unit.
286 #[inline]
287 pub fn with_source<NewSrc>(&self) -> Transform2D<T, NewSrc, Dst> {
288 Transform2D::new(
289 self.m11, self.m12,
290 self.m21, self.m22,
291 self.m31, self.m32,
292 )
293 }
294
295 /// Returns the same transform with a different destination unit.
296 #[inline]
297 pub fn with_destination<NewDst>(&self) -> Transform2D<T, Src, NewDst> {
298 Transform2D::new(
299 self.m11, self.m12,
300 self.m21, self.m22,
301 self.m31, self.m32,
302 )
303 }
304
305 /// Create a 3D transform from the current transform
306 pub fn to_3d(&self) -> Transform3D<T, Src, Dst>
307 where
308 T: Zero + One,
309 {
310 Transform3D::new_2d(self.m11, self.m12, self.m21, self.m22, self.m31, self.m32)
311 }
312}
313
314impl<T: NumCast + Copy, Src, Dst> Transform2D<T, Src, Dst> {
315 /// Cast from one numeric representation to another, preserving the units.
316 #[inline]
317 pub fn cast<NewT: NumCast>(&self) -> Transform2D<NewT, Src, Dst> {
318 self.try_cast().unwrap()
319 }
320
321 /// Fallible cast from one numeric representation to another, preserving the units.
322 pub fn try_cast<NewT: NumCast>(&self) -> Option<Transform2D<NewT, Src, Dst>> {
323 match (NumCast::from(self.m11), NumCast::from(self.m12),
324 NumCast::from(self.m21), NumCast::from(self.m22),
325 NumCast::from(self.m31), NumCast::from(self.m32)) {
326 (Some(m11), Some(m12),
327 Some(m21), Some(m22),
328 Some(m31), Some(m32)) => {
329 Some(Transform2D::new(
330 m11, m12,
331 m21, m22,
332 m31, m32
333 ))
334 },
335 _ => None
336 }
337 }
338}
339
340impl<T, Src, Dst> Transform2D<T, Src, Dst>
341where
342 T: Zero + One,
343{
344 /// Create an identity matrix:
345 ///
346 /// ```text
347 /// 1 0
348 /// 0 1
349 /// 0 0
350 /// ```
351 #[inline]
352 pub fn identity() -> Self {
353 Self::translation(T::zero(), T::zero())
354 }
355
356 /// Intentional not public, because it checks for exact equivalence
357 /// while most consumers will probably want some sort of approximate
358 /// equivalence to deal with floating-point errors.
359 fn is_identity(&self) -> bool
360 where
361 T: PartialEq,
362 {
363 *self == Self::identity()
364 }
365}
366
367
368/// Methods for combining generic transformations
369impl<T, Src, Dst> Transform2D<T, Src, Dst>
370where
371 T: Copy + Add<Output = T> + Mul<Output = T>,
372{
373 /// Returns the multiplication of the two matrices such that mat's transformation
374 /// applies after self's transformation.
375 #[must_use]
376 pub fn then<NewDst>(&self, mat: &Transform2D<T, Dst, NewDst>) -> Transform2D<T, Src, NewDst> {
377 Transform2D::new(
378 self.m11 * mat.m11 + self.m12 * mat.m21,
379 self.m11 * mat.m12 + self.m12 * mat.m22,
380
381 self.m21 * mat.m11 + self.m22 * mat.m21,
382 self.m21 * mat.m12 + self.m22 * mat.m22,
383
384 self.m31 * mat.m11 + self.m32 * mat.m21 + mat.m31,
385 self.m31 * mat.m12 + self.m32 * mat.m22 + mat.m32,
386 )
387 }
388}
389
390/// Methods for creating and combining translation transformations
391impl<T, Src, Dst> Transform2D<T, Src, Dst>
392where
393 T: Zero + One,
394{
395 /// Create a 2d translation transform:
396 ///
397 /// ```text
398 /// 1 0
399 /// 0 1
400 /// x y
401 /// ```
402 #[inline]
403 pub fn translation(x: T, y: T) -> Self {
404 let _0 = || T::zero();
405 let _1 = || T::one();
406
407 Self::new(
408 _1(), _0(),
409 _0(), _1(),
410 x, y,
411 )
412 }
413
414 /// Applies a translation after self's transformation and returns the resulting transform.
415 #[inline]
416 #[must_use]
417 pub fn then_translate(&self, v: Vector2D<T, Dst>) -> Self
418 where
419 T: Copy + Add<Output = T> + Mul<Output = T>,
420 {
421 self.then(&Transform2D::translation(v.x, v.y))
422 }
423
424 /// Applies a translation before self's transformation and returns the resulting transform.
425 #[inline]
426 #[must_use]
427 pub fn pre_translate(&self, v: Vector2D<T, Src>) -> Self
428 where
429 T: Copy + Add<Output = T> + Mul<Output = T>,
430 {
431 Transform2D::translation(v.x, v.y).then(self)
432 }
433}
434
435/// Methods for creating and combining rotation transformations
436impl<T, Src, Dst> Transform2D<T, Src, Dst>
437where
438 T: Copy + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Zero + Trig,
439{
440 /// Returns a rotation transform.
441 #[inline]
442 pub fn rotation(theta: Angle<T>) -> Self {
443 let _0 = Zero::zero();
444 let cos = theta.get().cos();
445 let sin = theta.get().sin();
446 Transform2D::new(
447 cos, sin,
448 _0 - sin, cos,
449 _0, _0
450 )
451 }
452
453 /// Applies a rotation after self's transformation and returns the resulting transform.
454 #[inline]
455 #[must_use]
456 pub fn then_rotate(&self, theta: Angle<T>) -> Self {
457 self.then(&Transform2D::rotation(theta))
458 }
459
460 /// Applies a rotation before self's transformation and returns the resulting transform.
461 #[inline]
462 #[must_use]
463 pub fn pre_rotate(&self, theta: Angle<T>) -> Self {
464 Transform2D::rotation(theta).then(self)
465 }
466}
467
468/// Methods for creating and combining scale transformations
469impl<T, Src, Dst> Transform2D<T, Src, Dst> {
470 /// Create a 2d scale transform:
471 ///
472 /// ```text
473 /// x 0
474 /// 0 y
475 /// 0 0
476 /// ```
477 #[inline]
478 pub fn scale(x: T, y: T) -> Self
479 where
480 T: Zero,
481 {
482 let _0 = || Zero::zero();
483
484 Self::new(
485 x, _0(),
486 _0(), y,
487 _0(), _0(),
488 )
489 }
490
491 /// Applies a scale after self's transformation and returns the resulting transform.
492 #[inline]
493 #[must_use]
494 pub fn then_scale(&self, x: T, y: T) -> Self
495 where
496 T: Copy + Add<Output = T> + Mul<Output = T> + Zero,
497 {
498 self.then(&Transform2D::scale(x, y))
499 }
500
501 /// Applies a scale before self's transformation and returns the resulting transform.
502 #[inline]
503 #[must_use]
504 pub fn pre_scale(&self, x: T, y: T) -> Self
505 where
506 T: Copy + Mul<Output = T>,
507 {
508 Transform2D::new(
509 self.m11 * x, self.m12 * x,
510 self.m21 * y, self.m22 * y,
511 self.m31, self.m32
512 )
513 }
514}
515
516/// Methods for apply transformations to objects
517impl<T, Src, Dst> Transform2D<T, Src, Dst>
518where
519 T: Copy + Add<Output = T> + Mul<Output = T>,
520{
521 /// Returns the given point transformed by this transform.
522 #[inline]
523 #[must_use]
524 pub fn transform_point(&self, point: Point2D<T, Src>) -> Point2D<T, Dst> {
525 Point2D::new(
526 point.x * self.m11 + point.y * self.m21 + self.m31,
527 point.x * self.m12 + point.y * self.m22 + self.m32
528 )
529 }
530
531 /// Returns the given vector transformed by this matrix.
532 #[inline]
533 #[must_use]
534 pub fn transform_vector(&self, vec: Vector2D<T, Src>) -> Vector2D<T, Dst> {
535 vec2(vec.x * self.m11 + vec.y * self.m21,
536 vec.x * self.m12 + vec.y * self.m22)
537 }
538
539 /// Returns a rectangle that encompasses the result of transforming the given rectangle by this
540 /// transform.
541 #[inline]
542 #[must_use]
543 pub fn outer_transformed_rect(&self, rect: &Rect<T, Src>) -> Rect<T, Dst>
544 where
545 T: Sub<Output = T> + Zero + PartialOrd,
546 {
547 let min = rect.min();
548 let max = rect.max();
549 Rect::from_points(&[
550 self.transform_point(min),
551 self.transform_point(max),
552 self.transform_point(point2(max.x, min.y)),
553 self.transform_point(point2(min.x, max.y)),
554 ])
555 }
556
557
558 /// Returns a box that encompasses the result of transforming the given box by this
559 /// transform.
560 #[inline]
561 #[must_use]
562 pub fn outer_transformed_box(&self, b: &Box2D<T, Src>) -> Box2D<T, Dst>
563 where
564 T: Sub<Output = T> + Zero + PartialOrd,
565 {
566 Box2D::from_points(&[
567 self.transform_point(b.min),
568 self.transform_point(b.max),
569 self.transform_point(point2(b.max.x, b.min.y)),
570 self.transform_point(point2(b.min.x, b.max.y)),
571 ])
572 }
573}
574
575
576impl<T, Src, Dst> Transform2D<T, Src, Dst>
577where
578 T: Copy + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + PartialEq + Zero + One,
579{
580 /// Computes and returns the determinant of this transform.
581 pub fn determinant(&self) -> T {
582 self.m11 * self.m22 - self.m12 * self.m21
583 }
584
585 /// Returns whether it is possible to compute the inverse transform.
586 #[inline]
587 pub fn is_invertible(&self) -> bool {
588 self.determinant() != Zero::zero()
589 }
590
591 /// Returns the inverse transform if possible.
592 #[must_use]
593 pub fn inverse(&self) -> Option<Transform2D<T, Dst, Src>> {
594 let det = self.determinant();
595
596 let _0: T = Zero::zero();
597 let _1: T = One::one();
598
599 if det == _0 {
600 return None;
601 }
602
603 let inv_det = _1 / det;
604 Some(Transform2D::new(
605 inv_det * self.m22,
606 inv_det * (_0 - self.m12),
607 inv_det * (_0 - self.m21),
608 inv_det * self.m11,
609 inv_det * (self.m21 * self.m32 - self.m22 * self.m31),
610 inv_det * (self.m31 * self.m12 - self.m11 * self.m32),
611 ))
612 }
613}
614
615impl <T, Src, Dst> Default for Transform2D<T, Src, Dst>
616 where T: Zero + One
617{
618 /// Returns the [identity transform](#method.identity).
619 fn default() -> Self {
620 Self::identity()
621 }
622}
623
624impl<T: ApproxEq<T>, Src, Dst> ApproxEq<T> for Transform2D<T, Src, Dst> {
625 #[inline]
626 fn approx_epsilon() -> T { T::approx_epsilon() }
627
628 /// Returns true is this transform is approximately equal to the other one, using
629 /// a provided epsilon value.
630 fn approx_eq_eps(&self, other: &Self, eps: &T) -> bool {
631 self.m11.approx_eq_eps(&other.m11, approx_epsilon:eps) && self.m12.approx_eq_eps(&other.m12, approx_epsilon:eps) &&
632 self.m21.approx_eq_eps(&other.m21, approx_epsilon:eps) && self.m22.approx_eq_eps(&other.m22, approx_epsilon:eps) &&
633 self.m31.approx_eq_eps(&other.m31, approx_epsilon:eps) && self.m32.approx_eq_eps(&other.m32, approx_epsilon:eps)
634 }
635}
636
637impl<T, Src, Dst> fmt::Debug for Transform2D<T, Src, Dst>
638where T: Copy + fmt::Debug +
639 PartialEq +
640 One + Zero {
641 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
642 if self.is_identity() {
643 write!(f, "[I]")
644 } else {
645 self.to_array().fmt(f)
646 }
647 }
648}
649
650#[cfg(feature = "mint")]
651impl<T, Src, Dst> From<mint::RowMatrix3x2<T>> for Transform2D<T, Src, Dst> {
652 fn from(m: mint::RowMatrix3x2<T>) -> Self {
653 Transform2D {
654 m11: m.x.x, m12: m.x.y,
655 m21: m.y.x, m22: m.y.y,
656 m31: m.z.x, m32: m.z.y,
657 _unit: PhantomData,
658 }
659 }
660}
661#[cfg(feature = "mint")]
662impl<T, Src, Dst> Into<mint::RowMatrix3x2<T>> for Transform2D<T, Src, Dst> {
663 fn into(self) -> mint::RowMatrix3x2<T> {
664 mint::RowMatrix3x2 {
665 x: mint::Vector2 { x: self.m11, y: self.m12 },
666 y: mint::Vector2 { x: self.m21, y: self.m22 },
667 z: mint::Vector2 { x: self.m31, y: self.m32 },
668 }
669 }
670}
671
672
673#[cfg(test)]
674mod test {
675 use super::*;
676 use crate::default;
677 use crate::approxeq::ApproxEq;
678 #[cfg(feature = "mint")]
679 use mint;
680
681 use core::f32::consts::FRAC_PI_2;
682
683 type Mat = default::Transform2D<f32>;
684
685 fn rad(v: f32) -> Angle<f32> { Angle::radians(v) }
686
687 #[test]
688 pub fn test_translation() {
689 let t1 = Mat::translation(1.0, 2.0);
690 let t2 = Mat::identity().pre_translate(vec2(1.0, 2.0));
691 let t3 = Mat::identity().then_translate(vec2(1.0, 2.0));
692 assert_eq!(t1, t2);
693 assert_eq!(t1, t3);
694
695 assert_eq!(t1.transform_point(Point2D::new(1.0, 1.0)), Point2D::new(2.0, 3.0));
696
697 assert_eq!(t1.then(&t1), Mat::translation(2.0, 4.0));
698 }
699
700 #[test]
701 pub fn test_rotation() {
702 let r1 = Mat::rotation(rad(FRAC_PI_2));
703 let r2 = Mat::identity().pre_rotate(rad(FRAC_PI_2));
704 let r3 = Mat::identity().then_rotate(rad(FRAC_PI_2));
705 assert_eq!(r1, r2);
706 assert_eq!(r1, r3);
707
708 assert!(r1.transform_point(Point2D::new(1.0, 2.0)).approx_eq(&Point2D::new(-2.0, 1.0)));
709
710 assert!(r1.then(&r1).approx_eq(&Mat::rotation(rad(FRAC_PI_2*2.0))));
711 }
712
713 #[test]
714 pub fn test_scale() {
715 let s1 = Mat::scale(2.0, 3.0);
716 let s2 = Mat::identity().pre_scale(2.0, 3.0);
717 let s3 = Mat::identity().then_scale(2.0, 3.0);
718 assert_eq!(s1, s2);
719 assert_eq!(s1, s3);
720
721 assert!(s1.transform_point(Point2D::new(2.0, 2.0)).approx_eq(&Point2D::new(4.0, 6.0)));
722 }
723
724
725 #[test]
726 pub fn test_pre_then_scale() {
727 let m = Mat::rotation(rad(FRAC_PI_2)).then_translate(vec2(6.0, 7.0));
728 let s = Mat::scale(2.0, 3.0);
729 assert_eq!(m.then(&s), m.then_scale(2.0, 3.0));
730 }
731
732 #[test]
733 pub fn test_inverse_simple() {
734 let m1 = Mat::identity();
735 let m2 = m1.inverse().unwrap();
736 assert!(m1.approx_eq(&m2));
737 }
738
739 #[test]
740 pub fn test_inverse_scale() {
741 let m1 = Mat::scale(1.5, 0.3);
742 let m2 = m1.inverse().unwrap();
743 assert!(m1.then(&m2).approx_eq(&Mat::identity()));
744 assert!(m2.then(&m1).approx_eq(&Mat::identity()));
745 }
746
747 #[test]
748 pub fn test_inverse_translate() {
749 let m1 = Mat::translation(-132.0, 0.3);
750 let m2 = m1.inverse().unwrap();
751 assert!(m1.then(&m2).approx_eq(&Mat::identity()));
752 assert!(m2.then(&m1).approx_eq(&Mat::identity()));
753 }
754
755 #[test]
756 fn test_inverse_none() {
757 assert!(Mat::scale(2.0, 0.0).inverse().is_none());
758 assert!(Mat::scale(2.0, 2.0).inverse().is_some());
759 }
760
761 #[test]
762 pub fn test_pre_post() {
763 let m1 = default::Transform2D::identity().then_scale(1.0, 2.0).then_translate(vec2(1.0, 2.0));
764 let m2 = default::Transform2D::identity().pre_translate(vec2(1.0, 2.0)).pre_scale(1.0, 2.0);
765 assert!(m1.approx_eq(&m2));
766
767 let r = Mat::rotation(rad(FRAC_PI_2));
768 let t = Mat::translation(2.0, 3.0);
769
770 let a = Point2D::new(1.0, 1.0);
771
772 assert!(r.then(&t).transform_point(a).approx_eq(&Point2D::new(1.0, 4.0)));
773 assert!(t.then(&r).transform_point(a).approx_eq(&Point2D::new(-4.0, 3.0)));
774 assert!(t.then(&r).transform_point(a).approx_eq(&r.transform_point(t.transform_point(a))));
775 }
776
777 #[test]
778 fn test_size_of() {
779 use core::mem::size_of;
780 assert_eq!(size_of::<default::Transform2D<f32>>(), 6*size_of::<f32>());
781 assert_eq!(size_of::<default::Transform2D<f64>>(), 6*size_of::<f64>());
782 }
783
784 #[test]
785 pub fn test_is_identity() {
786 let m1 = default::Transform2D::identity();
787 assert!(m1.is_identity());
788 let m2 = m1.then_translate(vec2(0.1, 0.0));
789 assert!(!m2.is_identity());
790 }
791
792 #[test]
793 pub fn test_transform_vector() {
794 // Translation does not apply to vectors.
795 let m1 = Mat::translation(1.0, 1.0);
796 let v1 = vec2(10.0, -10.0);
797 assert_eq!(v1, m1.transform_vector(v1));
798 }
799
800 #[cfg(feature = "mint")]
801 #[test]
802 pub fn test_mint() {
803 let m1 = Mat::rotation(rad(FRAC_PI_2));
804 let mm: mint::RowMatrix3x2<_> = m1.into();
805 let m2 = Mat::from(mm);
806
807 assert_eq!(m1, m2);
808 }
809}
810