glam/f32/
affine2.rs

1// Generated from affine.rs.tera template. Edit the template, not the generated file.
2
3use crate::{Mat2, Mat3, Mat3A, Vec2, Vec3A};
4use core::ops::{Deref, DerefMut, Mul, MulAssign};
5
6/// A 2D affine transform, which can represent translation, rotation, scaling and shear.
7#[derive(Copy, Clone)]
8#[cfg_attr(
9    all(feature = "bytemuck", not(feature = "scalar-math")),
10    derive(bytemuck::AnyBitPattern)
11)]
12#[cfg_attr(
13    all(feature = "bytemuck", feature = "scalar-math"),
14    derive(bytemuck::Pod, bytemuck::Zeroable)
15)]
16#[repr(C)]
17pub struct Affine2 {
18    pub matrix2: Mat2,
19    pub translation: Vec2,
20}
21
22impl Affine2 {
23    /// The degenerate zero transform.
24    ///
25    /// This transforms any finite vector and point to zero.
26    /// The zero transform is non-invertible.
27    pub const ZERO: Self = Self {
28        matrix2: Mat2::ZERO,
29        translation: Vec2::ZERO,
30    };
31
32    /// The identity transform.
33    ///
34    /// Multiplying a vector with this returns the same vector.
35    pub const IDENTITY: Self = Self {
36        matrix2: Mat2::IDENTITY,
37        translation: Vec2::ZERO,
38    };
39
40    /// All NAN:s.
41    pub const NAN: Self = Self {
42        matrix2: Mat2::NAN,
43        translation: Vec2::NAN,
44    };
45
46    /// Creates an affine transform from three column vectors.
47    #[inline(always)]
48    #[must_use]
49    pub const fn from_cols(x_axis: Vec2, y_axis: Vec2, z_axis: Vec2) -> Self {
50        Self {
51            matrix2: Mat2::from_cols(x_axis, y_axis),
52            translation: z_axis,
53        }
54    }
55
56    /// Creates an affine transform from a `[f32; 6]` array stored in column major order.
57    #[inline]
58    #[must_use]
59    pub fn from_cols_array(m: &[f32; 6]) -> Self {
60        Self {
61            matrix2: Mat2::from_cols_array(&[m[0], m[1], m[2], m[3]]),
62            translation: Vec2::from_array([m[4], m[5]]),
63        }
64    }
65
66    /// Creates a `[f32; 6]` array storing data in column major order.
67    #[inline]
68    #[must_use]
69    pub fn to_cols_array(&self) -> [f32; 6] {
70        let x = &self.matrix2.x_axis;
71        let y = &self.matrix2.y_axis;
72        let z = &self.translation;
73        [x.x, x.y, y.x, y.y, z.x, z.y]
74    }
75
76    /// Creates an affine transform from a `[[f32; 2]; 3]`
77    /// 2D array stored in column major order.
78    /// If your data is in row major order you will need to `transpose` the returned
79    /// matrix.
80    #[inline]
81    #[must_use]
82    pub fn from_cols_array_2d(m: &[[f32; 2]; 3]) -> Self {
83        Self {
84            matrix2: Mat2::from_cols(m[0].into(), m[1].into()),
85            translation: m[2].into(),
86        }
87    }
88
89    /// Creates a `[[f32; 2]; 3]` 2D array storing data in
90    /// column major order.
91    /// If you require data in row major order `transpose` the matrix first.
92    #[inline]
93    #[must_use]
94    pub fn to_cols_array_2d(&self) -> [[f32; 2]; 3] {
95        [
96            self.matrix2.x_axis.into(),
97            self.matrix2.y_axis.into(),
98            self.translation.into(),
99        ]
100    }
101
102    /// Creates an affine transform from the first 6 values in `slice`.
103    ///
104    /// # Panics
105    ///
106    /// Panics if `slice` is less than 6 elements long.
107    #[inline]
108    #[must_use]
109    pub fn from_cols_slice(slice: &[f32]) -> Self {
110        Self {
111            matrix2: Mat2::from_cols_slice(&slice[0..4]),
112            translation: Vec2::from_slice(&slice[4..6]),
113        }
114    }
115
116    /// Writes the columns of `self` to the first 6 elements in `slice`.
117    ///
118    /// # Panics
119    ///
120    /// Panics if `slice` is less than 6 elements long.
121    #[inline]
122    pub fn write_cols_to_slice(self, slice: &mut [f32]) {
123        self.matrix2.write_cols_to_slice(&mut slice[0..4]);
124        self.translation.write_to_slice(&mut slice[4..6]);
125    }
126
127    /// Creates an affine transform that changes scale.
128    /// Note that if any scale is zero the transform will be non-invertible.
129    #[inline]
130    #[must_use]
131    pub fn from_scale(scale: Vec2) -> Self {
132        Self {
133            matrix2: Mat2::from_diagonal(scale),
134            translation: Vec2::ZERO,
135        }
136    }
137
138    /// Creates an affine transform from the given rotation `angle`.
139    #[inline]
140    #[must_use]
141    pub fn from_angle(angle: f32) -> Self {
142        Self {
143            matrix2: Mat2::from_angle(angle),
144            translation: Vec2::ZERO,
145        }
146    }
147
148    /// Creates an affine transformation from the given 2D `translation`.
149    #[inline]
150    #[must_use]
151    pub fn from_translation(translation: Vec2) -> Self {
152        Self {
153            matrix2: Mat2::IDENTITY,
154            translation,
155        }
156    }
157
158    /// Creates an affine transform from a 2x2 matrix (expressing scale, shear and rotation)
159    #[inline]
160    #[must_use]
161    pub fn from_mat2(matrix2: Mat2) -> Self {
162        Self {
163            matrix2,
164            translation: Vec2::ZERO,
165        }
166    }
167
168    /// Creates an affine transform from a 2x2 matrix (expressing scale, shear and rotation) and a
169    /// translation vector.
170    ///
171    /// Equivalent to
172    /// `Affine2::from_translation(translation) * Affine2::from_mat2(mat2)`
173    #[inline]
174    #[must_use]
175    pub fn from_mat2_translation(matrix2: Mat2, translation: Vec2) -> Self {
176        Self {
177            matrix2,
178            translation,
179        }
180    }
181
182    /// Creates an affine transform from the given 2D `scale`, rotation `angle` (in radians) and
183    /// `translation`.
184    ///
185    /// Equivalent to `Affine2::from_translation(translation) *
186    /// Affine2::from_angle(angle) * Affine2::from_scale(scale)`
187    #[inline]
188    #[must_use]
189    pub fn from_scale_angle_translation(scale: Vec2, angle: f32, translation: Vec2) -> Self {
190        let rotation = Mat2::from_angle(angle);
191        Self {
192            matrix2: Mat2::from_cols(rotation.x_axis * scale.x, rotation.y_axis * scale.y),
193            translation,
194        }
195    }
196
197    /// Creates an affine transform from the given 2D rotation `angle` (in radians) and
198    /// `translation`.
199    ///
200    /// Equivalent to `Affine2::from_translation(translation) * Affine2::from_angle(angle)`
201    #[inline]
202    #[must_use]
203    pub fn from_angle_translation(angle: f32, translation: Vec2) -> Self {
204        Self {
205            matrix2: Mat2::from_angle(angle),
206            translation,
207        }
208    }
209
210    /// The given `Mat3` must be an affine transform,
211    #[inline]
212    #[must_use]
213    pub fn from_mat3(m: Mat3) -> Self {
214        use crate::swizzles::Vec3Swizzles;
215        Self {
216            matrix2: Mat2::from_cols(m.x_axis.xy(), m.y_axis.xy()),
217            translation: m.z_axis.xy(),
218        }
219    }
220
221    /// The given [`Mat3A`] must be an affine transform,
222    #[inline]
223    #[must_use]
224    pub fn from_mat3a(m: Mat3A) -> Self {
225        use crate::swizzles::Vec3Swizzles;
226        Self {
227            matrix2: Mat2::from_cols(m.x_axis.xy(), m.y_axis.xy()),
228            translation: m.z_axis.xy(),
229        }
230    }
231
232    /// Extracts `scale`, `angle` and `translation` from `self`.
233    ///
234    /// The transform is expected to be non-degenerate and without shearing, or the output
235    /// will be invalid.
236    ///
237    /// # Panics
238    ///
239    /// Will panic if the determinant `self.matrix2` is zero or if the resulting scale
240    /// vector contains any zero elements when `glam_assert` is enabled.
241    #[inline]
242    #[must_use]
243    pub fn to_scale_angle_translation(self) -> (Vec2, f32, Vec2) {
244        use crate::f32::math;
245        let det = self.matrix2.determinant();
246        glam_assert!(det != 0.0);
247
248        let scale = Vec2::new(
249            self.matrix2.x_axis.length() * math::signum(det),
250            self.matrix2.y_axis.length(),
251        );
252
253        glam_assert!(scale.cmpne(Vec2::ZERO).all());
254
255        let angle = math::atan2(-self.matrix2.y_axis.x, self.matrix2.y_axis.y);
256
257        (scale, angle, self.translation)
258    }
259
260    /// Transforms the given 2D point, applying shear, scale, rotation and translation.
261    #[inline]
262    #[must_use]
263    pub fn transform_point2(&self, rhs: Vec2) -> Vec2 {
264        self.matrix2 * rhs + self.translation
265    }
266
267    /// Transforms the given 2D vector, applying shear, scale and rotation (but NOT
268    /// translation).
269    ///
270    /// To also apply translation, use [`Self::transform_point2()`] instead.
271    #[inline]
272    pub fn transform_vector2(&self, rhs: Vec2) -> Vec2 {
273        self.matrix2 * rhs
274    }
275
276    /// Returns `true` if, and only if, all elements are finite.
277    ///
278    /// If any element is either `NaN`, positive or negative infinity, this will return
279    /// `false`.
280    #[inline]
281    #[must_use]
282    pub fn is_finite(&self) -> bool {
283        self.matrix2.is_finite() && self.translation.is_finite()
284    }
285
286    /// Returns `true` if any elements are `NaN`.
287    #[inline]
288    #[must_use]
289    pub fn is_nan(&self) -> bool {
290        self.matrix2.is_nan() || self.translation.is_nan()
291    }
292
293    /// Returns true if the absolute difference of all elements between `self` and `rhs`
294    /// is less than or equal to `max_abs_diff`.
295    ///
296    /// This can be used to compare if two 3x4 matrices contain similar elements. It works
297    /// best when comparing with a known value. The `max_abs_diff` that should be used used
298    /// depends on the values being compared against.
299    ///
300    /// For more see
301    /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
302    #[inline]
303    #[must_use]
304    pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
305        self.matrix2.abs_diff_eq(rhs.matrix2, max_abs_diff)
306            && self.translation.abs_diff_eq(rhs.translation, max_abs_diff)
307    }
308
309    /// Return the inverse of this transform.
310    ///
311    /// Note that if the transform is not invertible the result will be invalid.
312    #[inline]
313    #[must_use]
314    pub fn inverse(&self) -> Self {
315        let matrix2 = self.matrix2.inverse();
316        // transform negative translation by the matrix inverse:
317        let translation = -(matrix2 * self.translation);
318
319        Self {
320            matrix2,
321            translation,
322        }
323    }
324
325    /// Casts all elements of `self` to `f64`.
326    #[inline]
327    #[must_use]
328    pub fn as_daffine2(&self) -> crate::DAffine2 {
329        crate::DAffine2::from_mat2_translation(self.matrix2.as_dmat2(), self.translation.as_dvec2())
330    }
331}
332
333impl Default for Affine2 {
334    #[inline(always)]
335    fn default() -> Self {
336        Self::IDENTITY
337    }
338}
339
340impl Deref for Affine2 {
341    type Target = crate::deref::Cols3<Vec2>;
342    #[inline(always)]
343    fn deref(&self) -> &Self::Target {
344        unsafe { &*(self as *const Self as *const Self::Target) }
345    }
346}
347
348impl DerefMut for Affine2 {
349    #[inline(always)]
350    fn deref_mut(&mut self) -> &mut Self::Target {
351        unsafe { &mut *(self as *mut Self as *mut Self::Target) }
352    }
353}
354
355impl PartialEq for Affine2 {
356    #[inline]
357    fn eq(&self, rhs: &Self) -> bool {
358        self.matrix2.eq(&rhs.matrix2) && self.translation.eq(&rhs.translation)
359    }
360}
361
362impl core::fmt::Debug for Affine2 {
363    fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
364        fmt.debug_struct(stringify!(Affine2))
365            .field("matrix2", &self.matrix2)
366            .field("translation", &self.translation)
367            .finish()
368    }
369}
370
371impl core::fmt::Display for Affine2 {
372    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
373        if let Some(p) = f.precision() {
374            write!(
375                f,
376                "[{:.*}, {:.*}, {:.*}]",
377                p, self.matrix2.x_axis, p, self.matrix2.y_axis, p, self.translation
378            )
379        } else {
380            write!(
381                f,
382                "[{}, {}, {}]",
383                self.matrix2.x_axis, self.matrix2.y_axis, self.translation
384            )
385        }
386    }
387}
388
389impl<'a> core::iter::Product<&'a Self> for Affine2 {
390    fn product<I>(iter: I) -> Self
391    where
392        I: Iterator<Item = &'a Self>,
393    {
394        iter.fold(Self::IDENTITY, |a, &b| a * b)
395    }
396}
397
398impl Mul for Affine2 {
399    type Output = Self;
400
401    #[inline]
402    fn mul(self, rhs: Self) -> Self {
403        Self {
404            matrix2: self.matrix2 * rhs.matrix2,
405            translation: self.matrix2 * rhs.translation + self.translation,
406        }
407    }
408}
409
410impl Mul<&Self> for Affine2 {
411    type Output = Self;
412    #[inline]
413    fn mul(self, rhs: &Self) -> Self {
414        self.mul(*rhs)
415    }
416}
417
418impl Mul<&Affine2> for &Affine2 {
419    type Output = Affine2;
420    #[inline]
421    fn mul(self, rhs: &Affine2) -> Affine2 {
422        (*self).mul(*rhs)
423    }
424}
425
426impl Mul<Affine2> for &Affine2 {
427    type Output = Affine2;
428    #[inline]
429    fn mul(self, rhs: Affine2) -> Affine2 {
430        (*self).mul(rhs)
431    }
432}
433
434impl MulAssign for Affine2 {
435    #[inline]
436    fn mul_assign(&mut self, rhs: Self) {
437        *self = self.mul(rhs);
438    }
439}
440
441impl MulAssign<&Self> for Affine2 {
442    #[inline]
443    fn mul_assign(&mut self, rhs: &Self) {
444        self.mul_assign(*rhs);
445    }
446}
447
448impl From<Affine2> for Mat3 {
449    #[inline]
450    fn from(m: Affine2) -> Self {
451        Self::from_cols(
452            m.matrix2.x_axis.extend(0.0),
453            m.matrix2.y_axis.extend(0.0),
454            m.translation.extend(1.0),
455        )
456    }
457}
458
459impl Mul<Mat3> for Affine2 {
460    type Output = Mat3;
461
462    #[inline]
463    fn mul(self, rhs: Mat3) -> Self::Output {
464        Mat3::from(self) * rhs
465    }
466}
467
468impl Mul<&Mat3> for Affine2 {
469    type Output = Mat3;
470    #[inline]
471    fn mul(self, rhs: &Mat3) -> Mat3 {
472        self.mul(*rhs)
473    }
474}
475
476impl Mul<&Mat3> for &Affine2 {
477    type Output = Mat3;
478    #[inline]
479    fn mul(self, rhs: &Mat3) -> Mat3 {
480        (*self).mul(*rhs)
481    }
482}
483
484impl Mul<Mat3> for &Affine2 {
485    type Output = Mat3;
486    #[inline]
487    fn mul(self, rhs: Mat3) -> Mat3 {
488        (*self).mul(rhs)
489    }
490}
491
492impl Mul<Affine2> for Mat3 {
493    type Output = Self;
494
495    #[inline]
496    fn mul(self, rhs: Affine2) -> Self {
497        self * Self::from(rhs)
498    }
499}
500
501impl Mul<&Affine2> for Mat3 {
502    type Output = Self;
503    #[inline]
504    fn mul(self, rhs: &Affine2) -> Self {
505        self.mul(*rhs)
506    }
507}
508
509impl Mul<&Affine2> for &Mat3 {
510    type Output = Mat3;
511    #[inline]
512    fn mul(self, rhs: &Affine2) -> Mat3 {
513        (*self).mul(*rhs)
514    }
515}
516
517impl Mul<Affine2> for &Mat3 {
518    type Output = Mat3;
519    #[inline]
520    fn mul(self, rhs: Affine2) -> Mat3 {
521        (*self).mul(rhs)
522    }
523}
524
525impl MulAssign<Affine2> for Mat3 {
526    #[inline]
527    fn mul_assign(&mut self, rhs: Affine2) {
528        *self = self.mul(rhs);
529    }
530}
531
532impl MulAssign<&Affine2> for Mat3 {
533    #[inline]
534    fn mul_assign(&mut self, rhs: &Affine2) {
535        self.mul_assign(*rhs);
536    }
537}
538
539impl Mul<Mat3A> for Affine2 {
540    type Output = Mat3A;
541
542    #[inline]
543    fn mul(self, rhs: Mat3A) -> Self::Output {
544        Mat3A::from(self) * rhs
545    }
546}
547
548impl Mul<&Mat3A> for Affine2 {
549    type Output = Mat3A;
550    #[inline]
551    fn mul(self, rhs: &Mat3A) -> Mat3A {
552        self.mul(*rhs)
553    }
554}
555
556impl Mul<&Mat3A> for &Affine2 {
557    type Output = Mat3A;
558    #[inline]
559    fn mul(self, rhs: &Mat3A) -> Mat3A {
560        (*self).mul(*rhs)
561    }
562}
563
564impl Mul<Mat3A> for &Affine2 {
565    type Output = Mat3A;
566    #[inline]
567    fn mul(self, rhs: Mat3A) -> Mat3A {
568        (*self).mul(rhs)
569    }
570}
571
572impl Mul<Affine2> for Mat3A {
573    type Output = Self;
574
575    #[inline]
576    fn mul(self, rhs: Affine2) -> Self {
577        self * Self::from(rhs)
578    }
579}
580
581impl Mul<&Affine2> for Mat3A {
582    type Output = Self;
583    #[inline]
584    fn mul(self, rhs: &Affine2) -> Self {
585        self.mul(*rhs)
586    }
587}
588
589impl Mul<&Affine2> for &Mat3A {
590    type Output = Mat3A;
591    #[inline]
592    fn mul(self, rhs: &Affine2) -> Mat3A {
593        (*self).mul(*rhs)
594    }
595}
596
597impl Mul<Affine2> for &Mat3A {
598    type Output = Mat3A;
599    #[inline]
600    fn mul(self, rhs: Affine2) -> Mat3A {
601        (*self).mul(rhs)
602    }
603}
604
605impl MulAssign<Affine2> for Mat3A {
606    #[inline]
607    fn mul_assign(&mut self, rhs: Affine2) {
608        *self = self.mul(rhs);
609    }
610}
611
612impl MulAssign<&Affine2> for Mat3A {
613    #[inline]
614    fn mul_assign(&mut self, rhs: &Affine2) {
615        self.mul_assign(*rhs);
616    }
617}
618
619impl From<Affine2> for Mat3A {
620    #[inline]
621    fn from(m: Affine2) -> Self {
622        Self::from_cols(
623            Vec3A::from((m.matrix2.x_axis, 0.0)),
624            Vec3A::from((m.matrix2.y_axis, 0.0)),
625            Vec3A::from((m.translation, 1.0)),
626        )
627    }
628}