Skip to main content

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