Skip to main content

glam/f32/
mat3.rs

1// Generated from mat.rs.tera template. Edit the template, not the generated file.
2
3#[cfg(feature = "f64")]
4use crate::DMat3;
5
6use crate::{
7    EulerRot, Mat2, Mat3A, Mat4, Quat, Vec2, Vec3, Vec3A,
8    euler::{FromEuler, ToEuler},
9    f32::math,
10    swizzles::*,
11};
12use core::fmt;
13use core::iter::{Product, Sum};
14use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
15
16#[cfg(feature = "zerocopy-08")]
17use zerocopy_derive_08::*;
18
19/// Creates a 3x3 matrix from three column vectors.
20#[inline(always)]
21#[must_use]
22pub const fn mat3(x_axis: Vec3, y_axis: Vec3, z_axis: Vec3) -> Mat3 {
23    Mat3::from_cols(x_axis, y_axis, z_axis)
24}
25
26/// A 3x3 column major matrix.
27///
28/// This 3x3 matrix type features convenience methods for creating and using linear and
29/// affine transformations. If you are primarily dealing with 2D affine transformations the
30/// [`Affine2`](crate::Affine2) type is much faster and more space efficient than
31/// using a 3x3 matrix.
32///
33/// Linear transformations including 3D rotation and scale can be created using methods
34/// such as [`Self::from_diagonal()`], [`Self::from_quat()`], [`Self::from_axis_angle()`],
35/// [`Self::from_rotation_x()`], [`Self::from_rotation_y()`], or
36/// [`Self::from_rotation_z()`].
37///
38/// The resulting matrices can be use to transform 3D vectors using regular vector
39/// multiplication.
40///
41/// Affine transformations including 2D translation, rotation and scale can be created
42/// using methods such as [`Self::from_translation()`], [`Self::from_angle()`],
43/// [`Self::from_scale()`] and [`Self::from_scale_angle_translation()`].
44///
45/// The [`Self::transform_point2()`] and [`Self::transform_vector2()`] convenience methods
46/// are provided for performing affine transforms on 2D vectors and points. These multiply
47/// 2D inputs as 3D vectors with an implicit `z` value of `1` for points and `0` for
48/// vectors respectively. These methods assume that `Self` contains a valid affine
49/// transform.
50#[derive(Clone, Copy)]
51#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]
52#[cfg_attr(
53    feature = "zerocopy-08",
54    derive(FromBytes, Immutable, IntoBytes, KnownLayout)
55)]
56#[repr(C)]
57pub struct Mat3 {
58    pub x_axis: Vec3,
59    pub y_axis: Vec3,
60    pub z_axis: Vec3,
61}
62
63impl Mat3 {
64    /// A 3x3 matrix with all elements set to `0.0`.
65    pub const ZERO: Self = Self::from_cols(Vec3::ZERO, Vec3::ZERO, Vec3::ZERO);
66
67    /// A 3x3 identity matrix, where all diagonal elements are `1`, and all off-diagonal elements are `0`.
68    pub const IDENTITY: Self = Self::from_cols(Vec3::X, Vec3::Y, Vec3::Z);
69
70    /// All NAN:s.
71    pub const NAN: Self = Self::from_cols(Vec3::NAN, Vec3::NAN, Vec3::NAN);
72
73    #[allow(clippy::too_many_arguments)]
74    #[inline(always)]
75    #[must_use]
76    const fn new(
77        m00: f32,
78        m01: f32,
79        m02: f32,
80        m10: f32,
81        m11: f32,
82        m12: f32,
83        m20: f32,
84        m21: f32,
85        m22: f32,
86    ) -> Self {
87        Self {
88            x_axis: Vec3::new(m00, m01, m02),
89            y_axis: Vec3::new(m10, m11, m12),
90            z_axis: Vec3::new(m20, m21, m22),
91        }
92    }
93
94    /// Creates a 3x3 matrix from three column vectors.
95    ///
96    /// See also [`Self::from_rows`] when the data is in row major order.
97    #[inline(always)]
98    #[must_use]
99    pub const fn from_cols(x_axis: Vec3, y_axis: Vec3, z_axis: Vec3) -> Self {
100        Self {
101            x_axis,
102            y_axis,
103            z_axis,
104        }
105    }
106
107    /// Creates a 3x3 matrix from three row vectors.
108    ///
109    /// Matrices are stored in column major order, so the given rows are permuted into
110    /// the matrix layout. Use [`Self::from_cols`] instead when the data is already in
111    /// column major order.
112    #[inline(always)]
113    #[must_use]
114    pub const fn from_rows(row0: Vec3, row1: Vec3, row2: Vec3) -> Self {
115        let [m00, m01, m02] = row0.to_array();
116        let [m10, m11, m12] = row1.to_array();
117        let [m20, m21, m22] = row2.to_array();
118        Self::new(m00, m10, m20, m01, m11, m21, m02, m12, m22)
119    }
120
121    /// Creates a 3x3 matrix from a `[f32; 9]` array stored in column major order.
122    ///
123    /// If the data is in row major order use [`Self::from_rows_array`] instead.
124    #[inline]
125    #[must_use]
126    pub const fn from_cols_array(m: &[f32; 9]) -> Self {
127        Self::new(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8])
128    }
129
130    /// Creates a `[f32; 9]` array storing data in column major order.
131    ///
132    /// If you require the data in row major order use [`Self::to_rows_array`] instead.
133    #[inline]
134    #[must_use]
135    pub const fn to_cols_array(&self) -> [f32; 9] {
136        [
137            self.x_axis.x,
138            self.x_axis.y,
139            self.x_axis.z,
140            self.y_axis.x,
141            self.y_axis.y,
142            self.y_axis.z,
143            self.z_axis.x,
144            self.z_axis.y,
145            self.z_axis.z,
146        ]
147    }
148
149    /// Creates a 3x3 matrix from a `[[f32; 3]; 3]` 3D array stored in column major order.
150    ///
151    /// If the data is in row major order `transpose` the returned matrix.
152    #[inline]
153    #[must_use]
154    pub const fn from_cols_array_2d(m: &[[f32; 3]; 3]) -> Self {
155        Self::from_cols(
156            Vec3::from_array(m[0]),
157            Vec3::from_array(m[1]),
158            Vec3::from_array(m[2]),
159        )
160    }
161
162    /// Creates a `[[f32; 3]; 3]` 3D array storing data in column major order.
163    ///
164    /// If you require row major order `transpose` the matrix first.
165    #[inline]
166    #[must_use]
167    pub const fn to_cols_array_2d(&self) -> [[f32; 3]; 3] {
168        [
169            self.x_axis.to_array(),
170            self.y_axis.to_array(),
171            self.z_axis.to_array(),
172        ]
173    }
174
175    /// Creates a 3x3 matrix from a `[f32; 9]` array stored in row major order.
176    ///
177    /// Matrices are stored in column major order, so the array is permuted into the
178    /// matrix layout. Use [`Self::from_cols_array`] instead when the data is already in
179    /// column major order.
180    #[inline]
181    #[must_use]
182    pub const fn from_rows_array(m: &[f32; 9]) -> Self {
183        Self::new(m[0], m[3], m[6], m[1], m[4], m[7], m[2], m[5], m[8])
184    }
185
186    /// Creates a `[f32; 9]` array storing data in row major order.
187    ///
188    /// Matrices are stored in column major order, so the array is permuted out of the
189    /// column major storage. Use [`Self::to_cols_array`] instead when you want data in
190    /// column major order.
191    #[inline]
192    #[must_use]
193    pub const fn to_rows_array(&self) -> [f32; 9] {
194        let m = self.to_cols_array();
195        [m[0], m[3], m[6], m[1], m[4], m[7], m[2], m[5], m[8]]
196    }
197
198    /// Creates a 3x3 matrix with its diagonal set to `diagonal` and all other entries set to 0.
199    #[doc(alias = "scale")]
200    #[inline]
201    #[must_use]
202    pub const fn from_diagonal(diagonal: Vec3) -> Self {
203        Self::new(
204            diagonal.x, 0.0, 0.0, 0.0, diagonal.y, 0.0, 0.0, 0.0, diagonal.z,
205        )
206    }
207
208    /// Creates a 3x3 matrix from a 4x4 matrix, discarding the 4th row and column.
209    #[inline]
210    #[must_use]
211    pub fn from_mat4(m: Mat4) -> Self {
212        Self::from_cols(
213            Vec3::from_vec4(m.x_axis),
214            Vec3::from_vec4(m.y_axis),
215            Vec3::from_vec4(m.z_axis),
216        )
217    }
218
219    /// Creates a 3x3 matrix from the minor of the given 4x4 matrix, discarding the `i`th column
220    /// and `j`th row.
221    ///
222    /// # Panics
223    ///
224    /// Panics if `i` or `j` is greater than 3.
225    #[inline]
226    #[must_use]
227    #[track_caller]
228    pub fn from_mat4_minor(m: Mat4, i: usize, j: usize) -> Self {
229        match (i, j) {
230            (0, 0) => Self::from_cols(m.y_axis.yzw(), m.z_axis.yzw(), m.w_axis.yzw()),
231            (0, 1) => Self::from_cols(m.y_axis.xzw(), m.z_axis.xzw(), m.w_axis.xzw()),
232            (0, 2) => Self::from_cols(m.y_axis.xyw(), m.z_axis.xyw(), m.w_axis.xyw()),
233            (0, 3) => Self::from_cols(m.y_axis.xyz(), m.z_axis.xyz(), m.w_axis.xyz()),
234            (1, 0) => Self::from_cols(m.x_axis.yzw(), m.z_axis.yzw(), m.w_axis.yzw()),
235            (1, 1) => Self::from_cols(m.x_axis.xzw(), m.z_axis.xzw(), m.w_axis.xzw()),
236            (1, 2) => Self::from_cols(m.x_axis.xyw(), m.z_axis.xyw(), m.w_axis.xyw()),
237            (1, 3) => Self::from_cols(m.x_axis.xyz(), m.z_axis.xyz(), m.w_axis.xyz()),
238            (2, 0) => Self::from_cols(m.x_axis.yzw(), m.y_axis.yzw(), m.w_axis.yzw()),
239            (2, 1) => Self::from_cols(m.x_axis.xzw(), m.y_axis.xzw(), m.w_axis.xzw()),
240            (2, 2) => Self::from_cols(m.x_axis.xyw(), m.y_axis.xyw(), m.w_axis.xyw()),
241            (2, 3) => Self::from_cols(m.x_axis.xyz(), m.y_axis.xyz(), m.w_axis.xyz()),
242            (3, 0) => Self::from_cols(m.x_axis.yzw(), m.y_axis.yzw(), m.z_axis.yzw()),
243            (3, 1) => Self::from_cols(m.x_axis.xzw(), m.y_axis.xzw(), m.z_axis.xzw()),
244            (3, 2) => Self::from_cols(m.x_axis.xyw(), m.y_axis.xyw(), m.z_axis.xyw()),
245            (3, 3) => Self::from_cols(m.x_axis.xyz(), m.y_axis.xyz(), m.z_axis.xyz()),
246            _ => panic!("index out of bounds"),
247        }
248    }
249
250    /// Creates a 3D rotation matrix from the given quaternion.
251    ///
252    /// # Panics
253    ///
254    /// Will panic if `rotation` is not normalized when `glam_assert` is enabled.
255    #[inline]
256    #[must_use]
257    #[cfg_attr(any(debug_assertions, feature = "glam-assert"), track_caller)]
258    pub fn from_quat(rotation: Quat) -> Self {
259        glam_assert!(rotation.is_normalized());
260
261        let x2 = rotation.x + rotation.x;
262        let y2 = rotation.y + rotation.y;
263        let z2 = rotation.z + rotation.z;
264        let xx = rotation.x * x2;
265        let xy = rotation.x * y2;
266        let xz = rotation.x * z2;
267        let yy = rotation.y * y2;
268        let yz = rotation.y * z2;
269        let zz = rotation.z * z2;
270        let wx = rotation.w * x2;
271        let wy = rotation.w * y2;
272        let wz = rotation.w * z2;
273
274        Self::from_cols(
275            Vec3::new(1.0 - (yy + zz), xy + wz, xz - wy),
276            Vec3::new(xy - wz, 1.0 - (xx + zz), yz + wx),
277            Vec3::new(xz + wy, yz - wx, 1.0 - (xx + yy)),
278        )
279    }
280
281    /// Creates a 3D rotation matrix from a normalized rotation `axis` and `angle` (in
282    /// radians).
283    ///
284    /// # Panics
285    ///
286    /// Will panic if `axis` is not normalized when `glam_assert` is enabled.
287    #[inline]
288    #[must_use]
289    #[cfg_attr(any(debug_assertions, feature = "glam-assert"), track_caller)]
290    pub fn from_axis_angle(axis: Vec3, angle: f32) -> Self {
291        glam_assert!(axis.is_normalized());
292
293        let (sin, cos) = math::sin_cos(angle);
294        let (xsin, ysin, zsin) = axis.mul(sin).into();
295        let (x, y, z) = axis.into();
296        let (x2, y2, z2) = axis.mul(axis).into();
297        let omc = 1.0 - cos;
298        let xyomc = x * y * omc;
299        let xzomc = x * z * omc;
300        let yzomc = y * z * omc;
301        Self::from_cols(
302            Vec3::new(x2 * omc + cos, xyomc + zsin, xzomc - ysin),
303            Vec3::new(xyomc - zsin, y2 * omc + cos, yzomc + xsin),
304            Vec3::new(xzomc + ysin, yzomc - xsin, z2 * omc + cos),
305        )
306    }
307
308    /// Creates a 3D rotation matrix from the given euler rotation sequence and the angles (in
309    /// radians).
310    #[inline]
311    #[must_use]
312    pub fn from_euler(order: EulerRot, a: f32, b: f32, c: f32) -> Self {
313        Self::from_euler_angles(order, a, b, c)
314    }
315
316    /// Extract Euler angles with the given Euler rotation order.
317    ///
318    /// Note if the input matrix contains scales, shears, or other non-rotation transformations then
319    /// the resulting Euler angles will be ill-defined.
320    ///
321    /// # Panics
322    ///
323    /// Will panic if any input matrix column is not normalized when `glam_assert` is enabled.
324    #[inline]
325    #[must_use]
326    #[cfg_attr(any(debug_assertions, feature = "glam-assert"), track_caller)]
327    pub fn to_euler(&self, order: EulerRot) -> (f32, f32, f32) {
328        glam_assert!(
329            self.x_axis.is_normalized()
330                && self.y_axis.is_normalized()
331                && self.z_axis.is_normalized()
332        );
333        self.to_euler_angles(order)
334    }
335
336    /// Creates a 3D rotation matrix from `angle` (in radians) around the x axis.
337    #[inline]
338    #[must_use]
339    pub fn from_rotation_x(angle: f32) -> Self {
340        let (sina, cosa) = math::sin_cos(angle);
341        Self::from_cols(
342            Vec3::X,
343            Vec3::new(0.0, cosa, sina),
344            Vec3::new(0.0, -sina, cosa),
345        )
346    }
347
348    /// Creates a 3D rotation matrix from `angle` (in radians) around the y axis.
349    #[inline]
350    #[must_use]
351    pub fn from_rotation_y(angle: f32) -> Self {
352        let (sina, cosa) = math::sin_cos(angle);
353        Self::from_cols(
354            Vec3::new(cosa, 0.0, -sina),
355            Vec3::Y,
356            Vec3::new(sina, 0.0, cosa),
357        )
358    }
359
360    /// Creates a 3D rotation matrix from `angle` (in radians) around the z axis.
361    #[inline]
362    #[must_use]
363    pub fn from_rotation_z(angle: f32) -> Self {
364        let (sina, cosa) = math::sin_cos(angle);
365        Self::from_cols(
366            Vec3::new(cosa, sina, 0.0),
367            Vec3::new(-sina, cosa, 0.0),
368            Vec3::Z,
369        )
370    }
371
372    /// Creates an affine transformation matrix from the given 2D `translation`.
373    ///
374    /// The resulting matrix can be used to transform 2D points and vectors. See
375    /// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
376    #[inline]
377    #[must_use]
378    pub fn from_translation(translation: Vec2) -> Self {
379        Self::from_cols(
380            Vec3::X,
381            Vec3::Y,
382            Vec3::new(translation.x, translation.y, 1.0),
383        )
384    }
385
386    /// Creates an affine transformation matrix from the given 2D rotation `angle` (in
387    /// radians).
388    ///
389    /// The resulting matrix can be used to transform 2D points and vectors. See
390    /// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
391    #[inline]
392    #[must_use]
393    pub fn from_angle(angle: f32) -> Self {
394        let (sin, cos) = math::sin_cos(angle);
395        Self::from_cols(Vec3::new(cos, sin, 0.0), Vec3::new(-sin, cos, 0.0), Vec3::Z)
396    }
397
398    /// Creates an affine transformation matrix from the given 2D `scale`, rotation `angle` (in
399    /// radians) and `translation`.
400    ///
401    /// The resulting matrix can be used to transform 2D points and vectors. See
402    /// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
403    #[inline]
404    #[must_use]
405    pub fn from_scale_angle_translation(scale: Vec2, angle: f32, translation: Vec2) -> Self {
406        let (sin, cos) = math::sin_cos(angle);
407        Self::from_cols(
408            Vec3::new(cos * scale.x, sin * scale.x, 0.0),
409            Vec3::new(-sin * scale.y, cos * scale.y, 0.0),
410            Vec3::new(translation.x, translation.y, 1.0),
411        )
412    }
413
414    /// Creates an affine transformation matrix from the given non-uniform 2D `scale`.
415    ///
416    /// The resulting matrix can be used to transform 2D points and vectors. See
417    /// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
418    ///
419    /// # Panics
420    ///
421    /// Will panic if all elements of `scale` are zero when `glam_assert` is enabled.
422    #[inline]
423    #[must_use]
424    #[cfg_attr(any(debug_assertions, feature = "glam-assert"), track_caller)]
425    pub fn from_scale(scale: Vec2) -> Self {
426        // Do not panic as long as any component is non-zero
427        glam_assert!(scale.cmpne(Vec2::ZERO).any());
428
429        Self::from_cols(
430            Vec3::new(scale.x, 0.0, 0.0),
431            Vec3::new(0.0, scale.y, 0.0),
432            Vec3::Z,
433        )
434    }
435
436    /// Creates an affine transformation matrix from the given 2x2 matrix.
437    ///
438    /// The resulting matrix can be used to transform 2D points and vectors. See
439    /// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
440    #[inline]
441    pub fn from_mat2(m: Mat2) -> Self {
442        Self::from_cols((m.x_axis, 0.0).into(), (m.y_axis, 0.0).into(), Vec3::Z)
443    }
444
445    /// Creates a 3x3 matrix from the first 9 values in `slice`.
446    ///
447    /// See also [`Self::from_rows_slice`] when the slice is in row major order.
448    ///
449    /// # Panics
450    ///
451    /// Panics if `slice` is less than 9 elements long.
452    #[inline]
453    #[must_use]
454    #[track_caller]
455    pub const fn from_cols_slice(slice: &[f32]) -> Self {
456        Self::new(
457            slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
458            slice[8],
459        )
460    }
461
462    /// Writes the columns of `self` to the first 9 elements in `slice`.
463    ///
464    /// # Panics
465    ///
466    /// Panics if `slice` is less than 9 elements long.
467    #[inline]
468    #[track_caller]
469    pub fn write_cols_to_slice(&self, slice: &mut [f32]) {
470        slice[0] = self.x_axis.x;
471        slice[1] = self.x_axis.y;
472        slice[2] = self.x_axis.z;
473        slice[3] = self.y_axis.x;
474        slice[4] = self.y_axis.y;
475        slice[5] = self.y_axis.z;
476        slice[6] = self.z_axis.x;
477        slice[7] = self.z_axis.y;
478        slice[8] = self.z_axis.z;
479    }
480
481    /// Creates a 3x3 matrix from the first 9 values in `slice`, stored in row
482    /// major order.
483    ///
484    /// Matrices are stored in column major order, so the slice is permuted into the
485    /// matrix layout. Use [`Self::from_cols_slice`] instead when the slice is already in
486    /// column major order.
487    ///
488    /// # Panics
489    ///
490    /// Panics if `slice` is less than 9 elements long.
491    #[inline]
492    #[must_use]
493    #[track_caller]
494    pub const fn from_rows_slice(slice: &[f32]) -> Self {
495        Self::new(
496            slice[0], slice[3], slice[6], slice[1], slice[4], slice[7], slice[2], slice[5],
497            slice[8],
498        )
499    }
500
501    /// Returns the matrix column for the given `index`.
502    ///
503    /// # Panics
504    ///
505    /// Panics if `index` is greater than 2.
506    #[inline]
507    #[must_use]
508    #[track_caller]
509    pub fn col(&self, index: usize) -> Vec3 {
510        match index {
511            0 => self.x_axis,
512            1 => self.y_axis,
513            2 => self.z_axis,
514            _ => panic!("index out of bounds"),
515        }
516    }
517
518    /// Returns a mutable reference to the matrix column for the given `index`.
519    ///
520    /// # Panics
521    ///
522    /// Panics if `index` is greater than 2.
523    #[inline]
524    #[track_caller]
525    pub fn col_mut(&mut self, index: usize) -> &mut Vec3 {
526        match index {
527            0 => &mut self.x_axis,
528            1 => &mut self.y_axis,
529            2 => &mut self.z_axis,
530            _ => panic!("index out of bounds"),
531        }
532    }
533
534    /// Returns the matrix row for the given `index`.
535    ///
536    /// See also [`Self::set_row`] when you need to change the row.
537    ///
538    /// # Panics
539    ///
540    /// Panics if `index` is greater than 2.
541    #[inline]
542    #[must_use]
543    #[track_caller]
544    pub fn row(&self, index: usize) -> Vec3 {
545        match index {
546            0 => Vec3::new(self.x_axis.x, self.y_axis.x, self.z_axis.x),
547            1 => Vec3::new(self.x_axis.y, self.y_axis.y, self.z_axis.y),
548            2 => Vec3::new(self.x_axis.z, self.y_axis.z, self.z_axis.z),
549            _ => panic!("index out of bounds"),
550        }
551    }
552
553    /// Sets the matrix row for the given `index`.
554    ///
555    /// Matrices are stored in column major order, so the row is spread across all
556    /// 3 columns and writing it touches every column. Use [`Self::col_mut`]
557    /// instead when you can work with columns. See also [`Self::row`].
558    ///
559    /// # Panics
560    ///
561    /// Panics if `index` is greater than 2.
562    #[inline]
563    #[track_caller]
564    pub fn set_row(&mut self, index: usize, row: Vec3) {
565        match index {
566            0 => {
567                self.x_axis.x = row.x;
568                self.y_axis.x = row.y;
569                self.z_axis.x = row.z;
570            }
571            1 => {
572                self.x_axis.y = row.x;
573                self.y_axis.y = row.y;
574                self.z_axis.y = row.z;
575            }
576            2 => {
577                self.x_axis.z = row.x;
578                self.y_axis.z = row.y;
579                self.z_axis.z = row.z;
580            }
581            _ => panic!("index out of bounds"),
582        }
583    }
584
585    /// Returns `true` if, and only if, all elements are finite.
586    /// If any element is either `NaN`, positive or negative infinity, this will return `false`.
587    #[inline]
588    #[must_use]
589    pub fn is_finite(&self) -> bool {
590        self.x_axis.is_finite() && self.y_axis.is_finite() && self.z_axis.is_finite()
591    }
592
593    /// Returns `true` if any elements are `NaN`.
594    #[inline]
595    #[must_use]
596    pub fn is_nan(&self) -> bool {
597        self.x_axis.is_nan() || self.y_axis.is_nan() || self.z_axis.is_nan()
598    }
599
600    /// Returns the transpose of `self`.
601    #[inline]
602    #[must_use]
603    pub fn transpose(&self) -> Self {
604        Self {
605            x_axis: Vec3::new(self.x_axis.x, self.y_axis.x, self.z_axis.x),
606            y_axis: Vec3::new(self.x_axis.y, self.y_axis.y, self.z_axis.y),
607            z_axis: Vec3::new(self.x_axis.z, self.y_axis.z, self.z_axis.z),
608        }
609    }
610
611    /// Returns the diagonal of `self`.
612    #[inline]
613    #[must_use]
614    pub fn diagonal(&self) -> Vec3 {
615        Vec3::new(self.x_axis.x, self.y_axis.y, self.z_axis.z)
616    }
617
618    /// Returns the determinant of `self`.
619    #[inline]
620    #[must_use]
621    pub fn determinant(&self) -> f32 {
622        self.x_axis.dot(self.y_axis.cross(self.z_axis))
623    }
624
625    /// If `CHECKED` is true then if the determinant is zero this function will return a tuple
626    /// containing a zero matrix and false. If the determinant is non zero a tuple containing the
627    /// inverted matrix and true is returned.
628    ///
629    /// If `CHECKED` is false then the determinant is not checked and if it is zero the resulting
630    /// inverted matrix will be invalid. Will panic if the resulting inverted matrix is not finite
631    /// when `glam_assert` is enabled.
632    ///
633    /// A tuple containing the inverted matrix and a bool is used instead of an option here as
634    /// regular Rust enums put the discriminant first which can result in a lot of padding if the
635    /// matrix is aligned.
636    #[inline(always)]
637    #[must_use]
638    #[cfg_attr(any(debug_assertions, feature = "glam-assert"), track_caller)]
639    fn inverse_checked<const CHECKED: bool>(&self) -> (Self, bool) {
640        let tmp0 = self.y_axis.cross(self.z_axis);
641        let tmp1 = self.z_axis.cross(self.x_axis);
642        let tmp2 = self.x_axis.cross(self.y_axis);
643        let inv_det = Vec3::splat(1.0 / self.x_axis.dot(tmp0));
644        let m =
645            Self::from_cols(tmp0.mul(inv_det), tmp1.mul(inv_det), tmp2.mul(inv_det)).transpose();
646        if CHECKED {
647            if !m.is_finite() {
648                return (Self::ZERO, false);
649            }
650        } else {
651            glam_assert!(m.is_finite());
652        }
653        (m, true)
654    }
655
656    /// Returns the inverse of `self`.
657    ///
658    /// If the matrix is not invertible the returned matrix will be invalid. The
659    /// returned matrix will also be invalid if the inverse is not finite, which can
660    /// happen when `self` contains very large or very small values. Use
661    /// [`Self::try_inverse`] or [`Self::inverse_or_zero`] to detect these cases.
662    ///
663    /// # Panics
664    ///
665    /// Will panic if the resulting inverted matrix is not finite when `glam_assert`
666    /// is enabled.
667    #[inline]
668    #[must_use]
669    #[cfg_attr(any(debug_assertions, feature = "glam-assert"), track_caller)]
670    pub fn inverse(&self) -> Self {
671        self.inverse_checked::<false>().0
672    }
673
674    /// Returns the inverse of `self` or `None` if the matrix is not invertible, or if
675    /// the inverse is not finite.
676    #[inline]
677    #[must_use]
678    pub fn try_inverse(&self) -> Option<Self> {
679        let (m, is_valid) = self.inverse_checked::<true>();
680        if is_valid { Some(m) } else { None }
681    }
682
683    /// Returns the inverse of `self` or `Mat3::ZERO` if the matrix is not
684    /// invertible, or if the inverse is not finite.
685    #[inline]
686    #[must_use]
687    pub fn inverse_or_zero(&self) -> Self {
688        self.inverse_checked::<true>().0
689    }
690
691    /// Transforms the given 2D vector as a point.
692    ///
693    /// This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `1`.
694    ///
695    /// This method assumes that `self` contains a valid affine transform.
696    ///
697    /// # Panics
698    ///
699    /// Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled.
700    #[inline]
701    #[must_use]
702    #[cfg_attr(any(debug_assertions, feature = "glam-assert"), track_caller)]
703    pub fn transform_point2(&self, rhs: Vec2) -> Vec2 {
704        glam_assert!(self.row(2).abs_diff_eq(Vec3::Z, 1e-6));
705        Mat2::from_cols(self.x_axis.xy(), self.y_axis.xy()) * rhs + self.z_axis.xy()
706    }
707
708    /// Rotates the given 2D vector.
709    ///
710    /// This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `0`.
711    ///
712    /// This method assumes that `self` contains a valid affine transform.
713    ///
714    /// # Panics
715    ///
716    /// Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled.
717    #[inline]
718    #[must_use]
719    #[cfg_attr(any(debug_assertions, feature = "glam-assert"), track_caller)]
720    pub fn transform_vector2(&self, rhs: Vec2) -> Vec2 {
721        glam_assert!(self.row(2).abs_diff_eq(Vec3::Z, 1e-6));
722        Mat2::from_cols(self.x_axis.xy(), self.y_axis.xy()) * rhs
723    }
724
725    /// Transforms a 3D vector.
726    #[inline]
727    #[must_use]
728    pub fn mul_vec3(&self, rhs: Vec3) -> Vec3 {
729        let mut res = self.x_axis.mul(rhs.x);
730        res = res.add(self.y_axis.mul(rhs.y));
731        res = res.add(self.z_axis.mul(rhs.z));
732        res
733    }
734
735    /// Transforms a [`Vec3A`].
736    #[inline]
737    #[must_use]
738    pub fn mul_vec3a(&self, rhs: Vec3A) -> Vec3A {
739        self.mul_vec3(rhs.into()).into()
740    }
741
742    /// Transforms a 3D vector by the transpose of `self`.
743    #[inline]
744    #[must_use]
745    pub fn mul_transpose_vec3(&self, rhs: Vec3) -> Vec3 {
746        Vec3::new(
747            self.x_axis.dot(rhs),
748            self.y_axis.dot(rhs),
749            self.z_axis.dot(rhs),
750        )
751    }
752
753    /// Multiplies two 3x3 matrices.
754    #[inline]
755    #[must_use]
756    pub fn mul_mat3(&self, rhs: &Self) -> Self {
757        self.mul(rhs)
758    }
759
760    /// Adds two 3x3 matrices.
761    #[inline]
762    #[must_use]
763    pub fn add_mat3(&self, rhs: &Self) -> Self {
764        self.add(rhs)
765    }
766
767    /// Subtracts two 3x3 matrices.
768    #[inline]
769    #[must_use]
770    pub fn sub_mat3(&self, rhs: &Self) -> Self {
771        self.sub(rhs)
772    }
773
774    /// Multiplies a 3x3 matrix by a scalar.
775    #[inline]
776    #[must_use]
777    pub fn mul_scalar(&self, rhs: f32) -> Self {
778        Self::from_cols(
779            self.x_axis.mul(rhs),
780            self.y_axis.mul(rhs),
781            self.z_axis.mul(rhs),
782        )
783    }
784
785    /// Multiply `self` by a scaling vector `scale`.
786    /// This is faster than creating a whole diagonal scaling matrix and then multiplying that.
787    /// This operation is commutative.
788    #[inline]
789    #[must_use]
790    pub fn mul_diagonal_scale(&self, scale: Vec3) -> Self {
791        Self::from_cols(
792            self.x_axis * scale.x,
793            self.y_axis * scale.y,
794            self.z_axis * scale.z,
795        )
796    }
797
798    /// Divides a 3x3 matrix by a scalar.
799    #[inline]
800    #[must_use]
801    pub fn div_scalar(&self, rhs: f32) -> Self {
802        let rhs = Vec3::splat(rhs);
803        Self::from_cols(
804            self.x_axis.div(rhs),
805            self.y_axis.div(rhs),
806            self.z_axis.div(rhs),
807        )
808    }
809
810    /// Returns a matrix containing the reciprocal `1.0/n` of each element of `self`.
811    #[inline]
812    #[must_use]
813    pub fn recip(&self) -> Self {
814        Self::from_cols(
815            self.x_axis.recip(),
816            self.y_axis.recip(),
817            self.z_axis.recip(),
818        )
819    }
820
821    /// Returns true if the absolute difference of all elements between `self` and `rhs`
822    /// is less than or equal to `max_abs_diff`.
823    ///
824    /// This can be used to compare if two matrices contain similar elements. It works best
825    /// when comparing with a known value. The `max_abs_diff` that should be used used
826    /// depends on the values being compared against.
827    ///
828    /// For more see
829    /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
830    #[inline]
831    #[must_use]
832    pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
833        self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
834            && self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
835            && self.z_axis.abs_diff_eq(rhs.z_axis, max_abs_diff)
836    }
837
838    /// Takes the absolute value of each element in `self`
839    #[inline]
840    #[must_use]
841    pub fn abs(&self) -> Self {
842        Self::from_cols(self.x_axis.abs(), self.y_axis.abs(), self.z_axis.abs())
843    }
844
845    #[cfg(feature = "f64")]
846    #[inline]
847    #[must_use]
848    pub fn as_dmat3(&self) -> DMat3 {
849        DMat3::from_cols(
850            self.x_axis.as_dvec3(),
851            self.y_axis.as_dvec3(),
852            self.z_axis.as_dvec3(),
853        )
854    }
855}
856
857impl Default for Mat3 {
858    #[inline]
859    fn default() -> Self {
860        Self::IDENTITY
861    }
862}
863
864impl Add for Mat3 {
865    type Output = Self;
866    #[inline]
867    fn add(self, rhs: Self) -> Self {
868        Self::from_cols(
869            self.x_axis.add(rhs.x_axis),
870            self.y_axis.add(rhs.y_axis),
871            self.z_axis.add(rhs.z_axis),
872        )
873    }
874}
875
876impl Add<&Self> for Mat3 {
877    type Output = Self;
878    #[inline]
879    fn add(self, rhs: &Self) -> Self {
880        self.add(*rhs)
881    }
882}
883
884impl Add<&Mat3> for &Mat3 {
885    type Output = Mat3;
886    #[inline]
887    fn add(self, rhs: &Mat3) -> Mat3 {
888        (*self).add(*rhs)
889    }
890}
891
892impl Add<Mat3> for &Mat3 {
893    type Output = Mat3;
894    #[inline]
895    fn add(self, rhs: Mat3) -> Mat3 {
896        (*self).add(rhs)
897    }
898}
899
900impl AddAssign for Mat3 {
901    #[inline]
902    fn add_assign(&mut self, rhs: Self) {
903        *self = self.add(rhs);
904    }
905}
906
907impl AddAssign<&Self> for Mat3 {
908    #[inline]
909    fn add_assign(&mut self, rhs: &Self) {
910        self.add_assign(*rhs);
911    }
912}
913
914impl Sub for Mat3 {
915    type Output = Self;
916    #[inline]
917    fn sub(self, rhs: Self) -> Self {
918        Self::from_cols(
919            self.x_axis.sub(rhs.x_axis),
920            self.y_axis.sub(rhs.y_axis),
921            self.z_axis.sub(rhs.z_axis),
922        )
923    }
924}
925
926impl Sub<&Self> for Mat3 {
927    type Output = Self;
928    #[inline]
929    fn sub(self, rhs: &Self) -> Self {
930        self.sub(*rhs)
931    }
932}
933
934impl Sub<&Mat3> for &Mat3 {
935    type Output = Mat3;
936    #[inline]
937    fn sub(self, rhs: &Mat3) -> Mat3 {
938        (*self).sub(*rhs)
939    }
940}
941
942impl Sub<Mat3> for &Mat3 {
943    type Output = Mat3;
944    #[inline]
945    fn sub(self, rhs: Mat3) -> Mat3 {
946        (*self).sub(rhs)
947    }
948}
949
950impl SubAssign for Mat3 {
951    #[inline]
952    fn sub_assign(&mut self, rhs: Self) {
953        *self = self.sub(rhs);
954    }
955}
956
957impl SubAssign<&Self> for Mat3 {
958    #[inline]
959    fn sub_assign(&mut self, rhs: &Self) {
960        self.sub_assign(*rhs);
961    }
962}
963
964impl Neg for Mat3 {
965    type Output = Self;
966    #[inline]
967    fn neg(self) -> Self::Output {
968        Self::from_cols(self.x_axis.neg(), self.y_axis.neg(), self.z_axis.neg())
969    }
970}
971
972impl Neg for &Mat3 {
973    type Output = Mat3;
974    #[inline]
975    fn neg(self) -> Mat3 {
976        (*self).neg()
977    }
978}
979
980impl Mul for Mat3 {
981    type Output = Self;
982    #[inline]
983    fn mul(self, rhs: Self) -> Self {
984        Self::from_cols(
985            self.mul(rhs.x_axis),
986            self.mul(rhs.y_axis),
987            self.mul(rhs.z_axis),
988        )
989    }
990}
991
992impl Mul<&Self> for Mat3 {
993    type Output = Self;
994    #[inline]
995    fn mul(self, rhs: &Self) -> Self {
996        self.mul(*rhs)
997    }
998}
999
1000impl Mul<&Mat3> for &Mat3 {
1001    type Output = Mat3;
1002    #[inline]
1003    fn mul(self, rhs: &Mat3) -> Mat3 {
1004        (*self).mul(*rhs)
1005    }
1006}
1007
1008impl Mul<Mat3> for &Mat3 {
1009    type Output = Mat3;
1010    #[inline]
1011    fn mul(self, rhs: Mat3) -> Mat3 {
1012        (*self).mul(rhs)
1013    }
1014}
1015
1016impl MulAssign for Mat3 {
1017    #[inline]
1018    fn mul_assign(&mut self, rhs: Self) {
1019        *self = self.mul(rhs);
1020    }
1021}
1022
1023impl MulAssign<&Self> for Mat3 {
1024    #[inline]
1025    fn mul_assign(&mut self, rhs: &Self) {
1026        self.mul_assign(*rhs);
1027    }
1028}
1029
1030impl Mul<Vec3> for Mat3 {
1031    type Output = Vec3;
1032    #[inline]
1033    fn mul(self, rhs: Vec3) -> Self::Output {
1034        self.mul_vec3(rhs)
1035    }
1036}
1037
1038impl Mul<&Vec3> for Mat3 {
1039    type Output = Vec3;
1040    #[inline]
1041    fn mul(self, rhs: &Vec3) -> Vec3 {
1042        self.mul(*rhs)
1043    }
1044}
1045
1046impl Mul<&Vec3> for &Mat3 {
1047    type Output = Vec3;
1048    #[inline]
1049    fn mul(self, rhs: &Vec3) -> Vec3 {
1050        (*self).mul(*rhs)
1051    }
1052}
1053
1054impl Mul<Vec3> for &Mat3 {
1055    type Output = Vec3;
1056    #[inline]
1057    fn mul(self, rhs: Vec3) -> Vec3 {
1058        (*self).mul(rhs)
1059    }
1060}
1061
1062impl Mul<Mat3> for f32 {
1063    type Output = Mat3;
1064    #[inline]
1065    fn mul(self, rhs: Mat3) -> Self::Output {
1066        rhs.mul_scalar(self)
1067    }
1068}
1069
1070impl Mul<&Mat3> for f32 {
1071    type Output = Mat3;
1072    #[inline]
1073    fn mul(self, rhs: &Mat3) -> Mat3 {
1074        self.mul(*rhs)
1075    }
1076}
1077
1078impl Mul<&Mat3> for &f32 {
1079    type Output = Mat3;
1080    #[inline]
1081    fn mul(self, rhs: &Mat3) -> Mat3 {
1082        (*self).mul(*rhs)
1083    }
1084}
1085
1086impl Mul<Mat3> for &f32 {
1087    type Output = Mat3;
1088    #[inline]
1089    fn mul(self, rhs: Mat3) -> Mat3 {
1090        (*self).mul(rhs)
1091    }
1092}
1093
1094impl Mul<f32> for Mat3 {
1095    type Output = Self;
1096    #[inline]
1097    fn mul(self, rhs: f32) -> Self {
1098        self.mul_scalar(rhs)
1099    }
1100}
1101
1102impl Mul<&f32> for Mat3 {
1103    type Output = Self;
1104    #[inline]
1105    fn mul(self, rhs: &f32) -> Self {
1106        self.mul(*rhs)
1107    }
1108}
1109
1110impl Mul<&f32> for &Mat3 {
1111    type Output = Mat3;
1112    #[inline]
1113    fn mul(self, rhs: &f32) -> Mat3 {
1114        (*self).mul(*rhs)
1115    }
1116}
1117
1118impl Mul<f32> for &Mat3 {
1119    type Output = Mat3;
1120    #[inline]
1121    fn mul(self, rhs: f32) -> Mat3 {
1122        (*self).mul(rhs)
1123    }
1124}
1125
1126impl MulAssign<f32> for Mat3 {
1127    #[inline]
1128    fn mul_assign(&mut self, rhs: f32) {
1129        *self = self.mul(rhs);
1130    }
1131}
1132
1133impl MulAssign<&f32> for Mat3 {
1134    #[inline]
1135    fn mul_assign(&mut self, rhs: &f32) {
1136        self.mul_assign(*rhs);
1137    }
1138}
1139
1140impl Div<Mat3> for f32 {
1141    type Output = Mat3;
1142    #[inline]
1143    fn div(self, rhs: Mat3) -> Self::Output {
1144        Mat3::from_cols(
1145            self.div(rhs.x_axis),
1146            self.div(rhs.y_axis),
1147            self.div(rhs.z_axis),
1148        )
1149    }
1150}
1151
1152impl Div<&Mat3> for f32 {
1153    type Output = Mat3;
1154    #[inline]
1155    fn div(self, rhs: &Mat3) -> Mat3 {
1156        self.div(*rhs)
1157    }
1158}
1159
1160impl Div<&Mat3> for &f32 {
1161    type Output = Mat3;
1162    #[inline]
1163    fn div(self, rhs: &Mat3) -> Mat3 {
1164        (*self).div(*rhs)
1165    }
1166}
1167
1168impl Div<Mat3> for &f32 {
1169    type Output = Mat3;
1170    #[inline]
1171    fn div(self, rhs: Mat3) -> Mat3 {
1172        (*self).div(rhs)
1173    }
1174}
1175
1176impl Div<f32> for Mat3 {
1177    type Output = Self;
1178    #[inline]
1179    fn div(self, rhs: f32) -> Self {
1180        self.div_scalar(rhs)
1181    }
1182}
1183
1184impl Div<&f32> for Mat3 {
1185    type Output = Self;
1186    #[inline]
1187    fn div(self, rhs: &f32) -> Self {
1188        self.div(*rhs)
1189    }
1190}
1191
1192impl Div<&f32> for &Mat3 {
1193    type Output = Mat3;
1194    #[inline]
1195    fn div(self, rhs: &f32) -> Mat3 {
1196        (*self).div(*rhs)
1197    }
1198}
1199
1200impl Div<f32> for &Mat3 {
1201    type Output = Mat3;
1202    #[inline]
1203    fn div(self, rhs: f32) -> Mat3 {
1204        (*self).div(rhs)
1205    }
1206}
1207
1208impl DivAssign<f32> for Mat3 {
1209    #[inline]
1210    fn div_assign(&mut self, rhs: f32) {
1211        *self = self.div(rhs);
1212    }
1213}
1214
1215impl DivAssign<&f32> for Mat3 {
1216    #[inline]
1217    fn div_assign(&mut self, rhs: &f32) {
1218        self.div_assign(*rhs);
1219    }
1220}
1221
1222impl Mul<Vec3A> for Mat3 {
1223    type Output = Vec3A;
1224    #[inline]
1225    fn mul(self, rhs: Vec3A) -> Vec3A {
1226        self.mul_vec3a(rhs)
1227    }
1228}
1229
1230impl Mul<&Vec3A> for Mat3 {
1231    type Output = Vec3A;
1232    #[inline]
1233    fn mul(self, rhs: &Vec3A) -> Vec3A {
1234        self.mul(*rhs)
1235    }
1236}
1237
1238impl Mul<&Vec3A> for &Mat3 {
1239    type Output = Vec3A;
1240    #[inline]
1241    fn mul(self, rhs: &Vec3A) -> Vec3A {
1242        (*self).mul(*rhs)
1243    }
1244}
1245
1246impl Mul<Vec3A> for &Mat3 {
1247    type Output = Vec3A;
1248    #[inline]
1249    fn mul(self, rhs: Vec3A) -> Vec3A {
1250        (*self).mul(rhs)
1251    }
1252}
1253
1254impl From<Mat3A> for Mat3 {
1255    #[inline]
1256    fn from(m: Mat3A) -> Self {
1257        Self {
1258            x_axis: m.x_axis.into(),
1259            y_axis: m.y_axis.into(),
1260            z_axis: m.z_axis.into(),
1261        }
1262    }
1263}
1264
1265impl Sum<Self> for Mat3 {
1266    fn sum<I>(iter: I) -> Self
1267    where
1268        I: Iterator<Item = Self>,
1269    {
1270        iter.fold(Self::ZERO, Self::add)
1271    }
1272}
1273
1274impl<'a> Sum<&'a Self> for Mat3 {
1275    fn sum<I>(iter: I) -> Self
1276    where
1277        I: Iterator<Item = &'a Self>,
1278    {
1279        iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
1280    }
1281}
1282
1283impl Product for Mat3 {
1284    fn product<I>(iter: I) -> Self
1285    where
1286        I: Iterator<Item = Self>,
1287    {
1288        iter.fold(Self::IDENTITY, Self::mul)
1289    }
1290}
1291
1292impl<'a> Product<&'a Self> for Mat3 {
1293    fn product<I>(iter: I) -> Self
1294    where
1295        I: Iterator<Item = &'a Self>,
1296    {
1297        iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
1298    }
1299}
1300
1301impl PartialEq for Mat3 {
1302    #[inline]
1303    fn eq(&self, rhs: &Self) -> bool {
1304        self.x_axis.eq(&rhs.x_axis) && self.y_axis.eq(&rhs.y_axis) && self.z_axis.eq(&rhs.z_axis)
1305    }
1306}
1307
1308impl AsRef<[f32; 9]> for Mat3 {
1309    #[inline]
1310    fn as_ref(&self) -> &[f32; 9] {
1311        unsafe { &*(self as *const Self as *const [f32; 9]) }
1312    }
1313}
1314
1315impl AsMut<[f32; 9]> for Mat3 {
1316    #[inline]
1317    fn as_mut(&mut self) -> &mut [f32; 9] {
1318        unsafe { &mut *(self as *mut Self as *mut [f32; 9]) }
1319    }
1320}
1321
1322impl fmt::Debug for Mat3 {
1323    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1324        fmt.debug_struct(stringify!(Mat3))
1325            .field("x_axis", &self.x_axis)
1326            .field("y_axis", &self.y_axis)
1327            .field("z_axis", &self.z_axis)
1328            .finish()
1329    }
1330}
1331
1332impl fmt::Display for Mat3 {
1333    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1334        if let Some(p) = f.precision() {
1335            write!(
1336                f,
1337                "[{:.*}, {:.*}, {:.*}]",
1338                p, self.x_axis, p, self.y_axis, p, self.z_axis
1339            )
1340        } else {
1341            write!(f, "[{}, {}, {}]", self.x_axis, self.y_axis, self.z_axis)
1342        }
1343    }
1344}