Debian Codegraph @

debian/missing-sources/glam-0.23.0/src/f32/sse2/mat4.rs

raw symbols SCIP
1 // Generated from mat.rs.tera template. Edit the template, not the generated file.
2
3 use crate::{sse2::*, swizzles::*, DMat4, EulerRot, Mat3, Mat3A, Quat, Vec3, Vec3A, Vec4};
4 #[cfg(not(target_arch = "spirv"))]
5 use core::fmt;
6 use core::iter::{Product, Sum};
7 use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
8
9 #[cfg(target_arch = "x86")]
10 use core::arch::x86::*;
11 #[cfg(target_arch = "x86_64")]
12 use core::arch::x86_64::*;
13
14 #[cfg(feature = "libm")]
15 #[allow(unused_imports)]
16 use num_traits::Float;
17
18 /// Creates a 4x4 matrix from column vectors.
19 #[inline(always)]
20 pub const fn mat4(x_axis: Vec4, y_axis: Vec4, z_axis: Vec4, w_axis: Vec4) -> Mat4 {
21 Mat4::from_cols(x_axis, y_axis, z_axis, w_axis)
22 }
23
24 /// A 4x4 column major matrix.
25 ///
26 /// This 4x4 matrix type features convenience methods for creating and using affine transforms and
27 /// perspective projections. If you are primarily dealing with 3D affine transformations
28 /// considering using [`Affine3A`](crate::Affine3A) which is faster than a 4x4 matrix
29 /// for some affine operations.
30 ///
31 /// Affine transformations including 3D translation, rotation and scale can be created
32 /// using methods such as [`Self::from_translation()`], [`Self::from_quat()`],
33 /// [`Self::from_scale()`] and [`Self::from_scale_rotation_translation()`].
34 ///
35 /// Othographic projections can be created using the methods [`Self::orthographic_lh()`] for
36 /// left-handed coordinate systems and [`Self::orthographic_rh()`] for right-handed
37 /// systems. The resulting matrix is also an affine transformation.
38 ///
39 /// The [`Self::transform_point3()`] and [`Self::transform_vector3()`] convenience methods
40 /// are provided for performing affine transformations on 3D vectors and points. These
41 /// multiply 3D inputs as 4D vectors with an implicit `w` value of `1` for points and `0`
42 /// for vectors respectively. These methods assume that `Self` contains a valid affine
43 /// transform.
44 ///
45 /// Perspective projections can be created using methods such as
46 /// [`Self::perspective_lh()`], [`Self::perspective_infinite_lh()`] and
47 /// [`Self::perspective_infinite_reverse_lh()`] for left-handed co-ordinate systems and
48 /// [`Self::perspective_rh()`], [`Self::perspective_infinite_rh()`] and
49 /// [`Self::perspective_infinite_reverse_rh()`] for right-handed co-ordinate systems.
50 ///
51 /// The resulting perspective project can be use to transform 3D vectors as points with
52 /// perspective correction using the [`Self::project_point3()`] convenience method.
53 #[derive(Clone, Copy)]
54 #[repr(C)]
55 pub struct Mat4 {
56 pub x_axis: Vec4,
57 pub y_axis: Vec4,
58 pub z_axis: Vec4,
59 pub w_axis: Vec4,
60 }
61
62 impl Mat4 {
63 /// A 4x4 matrix with all elements set to `0.0`.
64 pub const ZERO: Self = Self::from_cols(Vec4::ZERO, Vec4::ZERO, Vec4::ZERO, Vec4::ZERO);
65
66 /// A 4x4 identity matrix, where all diagonal elements are `1`, and all off-diagonal elements are `0`.
67 pub const IDENTITY: Self = Self::from_cols(Vec4::X, Vec4::Y, Vec4::Z, Vec4::W);
68
69 /// All NAN:s.
70 pub const NAN: Self = Self::from_cols(Vec4::NAN, Vec4::NAN, Vec4::NAN, Vec4::NAN);
71
72 #[allow(clippy::too_many_arguments)]
73 #[inline(always)]
74 const fn new(
75 m00: f32,
76 m01: f32,
77 m02: f32,
78 m03: f32,
79 m10: f32,
80 m11: f32,
81 m12: f32,
82 m13: f32,
83 m20: f32,
84 m21: f32,
85 m22: f32,
86 m23: f32,
87 m30: f32,
88 m31: f32,
89 m32: f32,
90 m33: f32,
91 ) -> Self {
92 Self {
93 x_axis: Vec4::new(m00, m01, m02, m03),
94 y_axis: Vec4::new(m10, m11, m12, m13),
95 z_axis: Vec4::new(m20, m21, m22, m23),
96 w_axis: Vec4::new(m30, m31, m32, m33),
97 }
98 }
99
100 /// Creates a 4x4 matrix from two column vectors.
101 #[inline(always)]
102 pub const fn from_cols(x_axis: Vec4, y_axis: Vec4, z_axis: Vec4, w_axis: Vec4) -> Self {
103 Self {
104 x_axis,
105 y_axis,
106 z_axis,
107 w_axis,
108 }
109 }
110
111 /// Creates a 4x4 matrix from a `[f32; 16]` array stored in column major order.
112 /// If your data is stored in row major you will need to `transpose` the returned
113 /// matrix.
114 #[inline]
115 pub const fn from_cols_array(m: &[f32; 16]) -> Self {
116 Self::new(
117 m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13],
118 m[14], m[15],
119 )
120 }
121
122 /// Creates a `[f32; 16]` array storing data in column major order.
123 /// If you require data in row major order `transpose` the matrix first.
124 #[inline]
125 pub const fn to_cols_array(&self) -> [f32; 16] {
126 let [x_axis_x, x_axis_y, x_axis_z, x_axis_w] = self.x_axis.to_array();
127 let [y_axis_x, y_axis_y, y_axis_z, y_axis_w] = self.y_axis.to_array();
128 let [z_axis_x, z_axis_y, z_axis_z, z_axis_w] = self.z_axis.to_array();
129 let [w_axis_x, w_axis_y, w_axis_z, w_axis_w] = self.w_axis.to_array();
130
131 [
132 x_axis_x, x_axis_y, x_axis_z, x_axis_w, y_axis_x, y_axis_y, y_axis_z, y_axis_w,
133 z_axis_x, z_axis_y, z_axis_z, z_axis_w, w_axis_x, w_axis_y, w_axis_z, w_axis_w,
134 ]
135 }
136
137 /// Creates a 4x4 matrix from a `[[f32; 4]; 4]` 4D array stored in column major order.
138 /// If your data is in row major order you will need to `transpose` the returned
139 /// matrix.
140 #[inline]
141 pub const fn from_cols_array_2d(m: &[[f32; 4]; 4]) -> Self {
142 Self::from_cols(
143 Vec4::from_array(m[0]),
144 Vec4::from_array(m[1]),
145 Vec4::from_array(m[2]),
146 Vec4::from_array(m[3]),
147 )
148 }
149
150 /// Creates a `[[f32; 4]; 4]` 4D array storing data in column major order.
151 /// If you require data in row major order `transpose` the matrix first.
152 #[inline]
153 pub const fn to_cols_array_2d(&self) -> [[f32; 4]; 4] {
154 [
155 self.x_axis.to_array(),
156 self.y_axis.to_array(),
157 self.z_axis.to_array(),
158 self.w_axis.to_array(),
159 ]
160 }
161
162 /// Creates a 4x4 matrix with its diagonal set to `diagonal` and all other entries set to 0.
163 #[doc(alias = "scale")]
164 #[inline]
165 pub const fn from_diagonal(diagonal: Vec4) -> Self {
166 // diagonal.x, diagonal.y etc can't be done in a const-context
167 let [x, y, z, w] = diagonal.to_array();
168 Self::new(
169 x, 0.0, 0.0, 0.0, 0.0, y, 0.0, 0.0, 0.0, 0.0, z, 0.0, 0.0, 0.0, 0.0, w,
170 )
171 }
172
173 #[inline]
174 fn quat_to_axes(rotation: Quat) -> (Vec4, Vec4, Vec4) {
175 glam_assert!(rotation.is_normalized());
176
177 let (x, y, z, w) = rotation.into();
178 let x2 = x + x;
179 let y2 = y + y;
180 let z2 = z + z;
181 let xx = x * x2;
182 let xy = x * y2;
183 let xz = x * z2;
184 let yy = y * y2;
185 let yz = y * z2;
186 let zz = z * z2;
187 let wx = w * x2;
188 let wy = w * y2;
189 let wz = w * z2;
190
191 let x_axis = Vec4::new(1.0 - (yy + zz), xy + wz, xz - wy, 0.0);
192 let y_axis = Vec4::new(xy - wz, 1.0 - (xx + zz), yz + wx, 0.0);
193 let z_axis = Vec4::new(xz + wy, yz - wx, 1.0 - (xx + yy), 0.0);
194 (x_axis, y_axis, z_axis)
195 }
196
197 /// Creates an affine transformation matrix from the given 3D `scale`, `rotation` and
198 /// `translation`.
199 ///
200 /// The resulting matrix can be used to transform 3D points and vectors. See
201 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
202 ///
203 /// # Panics
204 ///
205 /// Will panic if `rotation` is not normalized when `glam_assert` is enabled.
206 #[inline]
207 pub fn from_scale_rotation_translation(scale: Vec3, rotation: Quat, translation: Vec3) -> Self {
208 let (x_axis, y_axis, z_axis) = Self::quat_to_axes(rotation);
209 Self::from_cols(
210 x_axis.mul(scale.x),
211 y_axis.mul(scale.y),
212 z_axis.mul(scale.z),
213 Vec4::from((translation, 1.0)),
214 )
215 }
216
217 /// Creates an affine transformation matrix from the given 3D `translation`.
218 ///
219 /// The resulting matrix can be used to transform 3D points and vectors. See
220 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
221 ///
222 /// # Panics
223 ///
224 /// Will panic if `rotation` is not normalized when `glam_assert` is enabled.
225 #[inline]
226 pub fn from_rotation_translation(rotation: Quat, translation: Vec3) -> Self {
227 let (x_axis, y_axis, z_axis) = Self::quat_to_axes(rotation);
228 Self::from_cols(x_axis, y_axis, z_axis, Vec4::from((translation, 1.0)))
229 }
230
231 /// Extracts `scale`, `rotation` and `translation` from `self`. The input matrix is
232 /// expected to be a 3D affine transformation matrix otherwise the output will be invalid.
233 ///
234 /// # Panics
235 ///
236 /// Will panic if the determinant of `self` is zero or if the resulting scale vector
237 /// contains any zero elements when `glam_assert` is enabled.
238 #[inline]
239 pub fn to_scale_rotation_translation(&self) -> (Vec3, Quat, Vec3) {
240 let det = self.determinant();
241 glam_assert!(det != 0.0);
242
243 let scale = Vec3::new(
244 self.x_axis.length() * det.signum(),
245 self.y_axis.length(),
246 self.z_axis.length(),
247 );
248
249 glam_assert!(scale.cmpne(Vec3::ZERO).all());
250
251 let inv_scale = scale.recip();
252
253 let rotation = Quat::from_rotation_axes(
254 self.x_axis.mul(inv_scale.x).xyz(),
255 self.y_axis.mul(inv_scale.y).xyz(),
256 self.z_axis.mul(inv_scale.z).xyz(),
257 );
258
259 let translation = self.w_axis.xyz();
260
261 (scale, rotation, translation)
262 }
263
264 /// Creates an affine transformation matrix from the given `rotation` quaternion.
265 ///
266 /// The resulting matrix can be used to transform 3D points and vectors. See
267 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
268 ///
269 /// # Panics
270 ///
271 /// Will panic if `rotation` is not normalized when `glam_assert` is enabled.
272 #[inline]
273 pub fn from_quat(rotation: Quat) -> Self {
274 let (x_axis, y_axis, z_axis) = Self::quat_to_axes(rotation);
275 Self::from_cols(x_axis, y_axis, z_axis, Vec4::W)
276 }
277
278 /// Creates an affine transformation matrix from the given 3x3 linear transformation
279 /// matrix.
280 ///
281 /// The resulting matrix can be used to transform 3D points and vectors. See
282 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
283 #[inline]
284 pub fn from_mat3(m: Mat3) -> Self {
285 Self::from_cols(
286 Vec4::from((m.x_axis, 0.0)),
287 Vec4::from((m.y_axis, 0.0)),
288 Vec4::from((m.z_axis, 0.0)),
289 Vec4::W,
290 )
291 }
292
293 /// Creates an affine transformation matrix from the given 3x3 linear transformation
294 /// matrix.
295 ///
296 /// The resulting matrix can be used to transform 3D points and vectors. See
297 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
298 #[inline]
299 pub fn from_mat3a(m: Mat3A) -> Self {
300 Self::from_cols(
301 Vec4::from((m.x_axis, 0.0)),
302 Vec4::from((m.y_axis, 0.0)),
303 Vec4::from((m.z_axis, 0.0)),
304 Vec4::W,
305 )
306 }
307
308 /// Creates an affine transformation matrix from the given 3D `translation`.
309 ///
310 /// The resulting matrix can be used to transform 3D points and vectors. See
311 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
312 #[inline]
313 pub fn from_translation(translation: Vec3) -> Self {
314 Self::from_cols(
315 Vec4::X,
316 Vec4::Y,
317 Vec4::Z,
318 Vec4::new(translation.x, translation.y, translation.z, 1.0),
319 )
320 }
321
322 /// Creates an affine transformation matrix containing a 3D rotation around a normalized
323 /// rotation `axis` of `angle` (in radians).
324 ///
325 /// The resulting matrix can be used to transform 3D points and vectors. See
326 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
327 ///
328 /// # Panics
329 ///
330 /// Will panic if `axis` is not normalized when `glam_assert` is enabled.
331 #[inline]
332 pub fn from_axis_angle(axis: Vec3, angle: f32) -> Self {
333 glam_assert!(axis.is_normalized());
334
335 let (sin, cos) = angle.sin_cos();
336 let axis_sin = axis.mul(sin);
337 let axis_sq = axis.mul(axis);
338 let omc = 1.0 - cos;
339 let xyomc = axis.x * axis.y * omc;
340 let xzomc = axis.x * axis.z * omc;
341 let yzomc = axis.y * axis.z * omc;
342 Self::from_cols(
343 Vec4::new(
344 axis_sq.x * omc + cos,
345 xyomc + axis_sin.z,
346 xzomc - axis_sin.y,
347 0.0,
348 ),
349 Vec4::new(
350 xyomc - axis_sin.z,
351 axis_sq.y * omc + cos,
352 yzomc + axis_sin.x,
353 0.0,
354 ),
355 Vec4::new(
356 xzomc + axis_sin.y,
357 yzomc - axis_sin.x,
358 axis_sq.z * omc + cos,
359 0.0,
360 ),
361 Vec4::W,
362 )
363 }
364
365 #[inline]
366 /// Creates a affine transformation matrix containing a rotation from the given euler
367 /// rotation sequence and angles (in radians).
368 ///
369 /// The resulting matrix can be used to transform 3D points and vectors. See
370 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
371 pub fn from_euler(order: EulerRot, a: f32, b: f32, c: f32) -> Self {
372 let quat = Quat::from_euler(order, a, b, c);
373 Self::from_quat(quat)
374 }
375
376 /// Creates an affine transformation matrix containing a 3D rotation around the x axis of
377 /// `angle` (in radians).
378 ///
379 /// The resulting matrix can be used to transform 3D points and vectors. See
380 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
381 #[inline]
382 pub fn from_rotation_x(angle: f32) -> Self {
383 let (sina, cosa) = angle.sin_cos();
384 Self::from_cols(
385 Vec4::X,
386 Vec4::new(0.0, cosa, sina, 0.0),
387 Vec4::new(0.0, -sina, cosa, 0.0),
388 Vec4::W,
389 )
390 }
391
392 /// Creates an affine transformation matrix containing a 3D rotation around the y axis of
393 /// `angle` (in radians).
394 ///
395 /// The resulting matrix can be used to transform 3D points and vectors. See
396 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
397 #[inline]
398 pub fn from_rotation_y(angle: f32) -> Self {
399 let (sina, cosa) = angle.sin_cos();
400 Self::from_cols(
401 Vec4::new(cosa, 0.0, -sina, 0.0),
402 Vec4::Y,
403 Vec4::new(sina, 0.0, cosa, 0.0),
404 Vec4::W,
405 )
406 }
407
408 /// Creates an affine transformation matrix containing a 3D rotation around the z axis of
409 /// `angle` (in radians).
410 ///
411 /// The resulting matrix can be used to transform 3D points and vectors. See
412 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
413 #[inline]
414 pub fn from_rotation_z(angle: f32) -> Self {
415 let (sina, cosa) = angle.sin_cos();
416 Self::from_cols(
417 Vec4::new(cosa, sina, 0.0, 0.0),
418 Vec4::new(-sina, cosa, 0.0, 0.0),
419 Vec4::Z,
420 Vec4::W,
421 )
422 }
423
424 /// Creates an affine transformation matrix containing the given 3D non-uniform `scale`.
425 ///
426 /// The resulting matrix can be used to transform 3D points and vectors. See
427 /// [`Self::transform_point3()`] and [`Self::transform_vector3()`].
428 ///
429 /// # Panics
430 ///
431 /// Will panic if all elements of `scale` are zero when `glam_assert` is enabled.
432 #[inline]
433 pub fn from_scale(scale: Vec3) -> Self {
434 // Do not panic as long as any component is non-zero
435 glam_assert!(scale.cmpne(Vec3::ZERO).any());
436
437 Self::from_cols(
438 Vec4::new(scale.x, 0.0, 0.0, 0.0),
439 Vec4::new(0.0, scale.y, 0.0, 0.0),
440 Vec4::new(0.0, 0.0, scale.z, 0.0),
441 Vec4::W,
442 )
443 }
444
445 /// Creates a 4x4 matrix from the first 16 values in `slice`.
446 ///
447 /// # Panics
448 ///
449 /// Panics if `slice` is less than 16 elements long.
450 #[inline]
451 pub const fn from_cols_slice(slice: &[f32]) -> Self {
452 Self::new(
453 slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
454 slice[8], slice[9], slice[10], slice[11], slice[12], slice[13], slice[14], slice[15],
455 )
456 }
457
458 /// Writes the columns of `self` to the first 16 elements in `slice`.
459 ///
460 /// # Panics
461 ///
462 /// Panics if `slice` is less than 16 elements long.
463 #[inline]
464 pub fn write_cols_to_slice(self, slice: &mut [f32]) {
465 slice[0] = self.x_axis.x;
466 slice[1] = self.x_axis.y;
467 slice[2] = self.x_axis.z;
468 slice[3] = self.x_axis.w;
469 slice[4] = self.y_axis.x;
470 slice[5] = self.y_axis.y;
471 slice[6] = self.y_axis.z;
472 slice[7] = self.y_axis.w;
473 slice[8] = self.z_axis.x;
474 slice[9] = self.z_axis.y;
475 slice[10] = self.z_axis.z;
476 slice[11] = self.z_axis.w;
477 slice[12] = self.w_axis.x;
478 slice[13] = self.w_axis.y;
479 slice[14] = self.w_axis.z;
480 slice[15] = self.w_axis.w;
481 }
482
483 /// Returns the matrix column for the given `index`.
484 ///
485 /// # Panics
486 ///
487 /// Panics if `index` is greater than 3.
488 #[inline]
489 pub fn col(&self, index: usize) -> Vec4 {
490 match index {
491 0 => self.x_axis,
492 1 => self.y_axis,
493 2 => self.z_axis,
494 3 => self.w_axis,
495 _ => panic!("index out of bounds"),
496 }
497 }
498
499 /// Returns a mutable reference to the matrix column for the given `index`.
500 ///
501 /// # Panics
502 ///
503 /// Panics if `index` is greater than 3.
504 #[inline]
505 pub fn col_mut(&mut self, index: usize) -> &mut Vec4 {
506 match index {
507 0 => &mut self.x_axis,
508 1 => &mut self.y_axis,
509 2 => &mut self.z_axis,
510 3 => &mut self.w_axis,
511 _ => panic!("index out of bounds"),
512 }
513 }
514
515 /// Returns the matrix row for the given `index`.
516 ///
517 /// # Panics
518 ///
519 /// Panics if `index` is greater than 3.
520 #[inline]
521 pub fn row(&self, index: usize) -> Vec4 {
522 match index {
523 0 => Vec4::new(self.x_axis.x, self.y_axis.x, self.z_axis.x, self.w_axis.x),
524 1 => Vec4::new(self.x_axis.y, self.y_axis.y, self.z_axis.y, self.w_axis.y),
525 2 => Vec4::new(self.x_axis.z, self.y_axis.z, self.z_axis.z, self.w_axis.z),
526 3 => Vec4::new(self.x_axis.w, self.y_axis.w, self.z_axis.w, self.w_axis.w),
527 _ => panic!("index out of bounds"),
528 }
529 }
530
531 /// Returns `true` if, and only if, all elements are finite.
532 /// If any element is either `NaN`, positive or negative infinity, this will return `false`.
533 #[inline]
534 pub fn is_finite(&self) -> bool {
535 self.x_axis.is_finite()
536 && self.y_axis.is_finite()
537 && self.z_axis.is_finite()
538 && self.w_axis.is_finite()
539 }
540
541 /// Returns `true` if any elements are `NaN`.
542 #[inline]
543 pub fn is_nan(&self) -> bool {
544 self.x_axis.is_nan() || self.y_axis.is_nan() || self.z_axis.is_nan() || self.w_axis.is_nan()
545 }
546
547 /// Returns the transpose of `self`.
548 #[must_use]
549 #[inline]
550 pub fn transpose(&self) -> Self {
551 unsafe {
552 // Based on https://github.com/microsoft/DirectXMath `XMMatrixTranspose`
553 let tmp0 = _mm_shuffle_ps(self.x_axis.0, self.y_axis.0, 0b01_00_01_00);
554 let tmp1 = _mm_shuffle_ps(self.x_axis.0, self.y_axis.0, 0b11_10_11_10);
555 let tmp2 = _mm_shuffle_ps(self.z_axis.0, self.w_axis.0, 0b01_00_01_00);
556 let tmp3 = _mm_shuffle_ps(self.z_axis.0, self.w_axis.0, 0b11_10_11_10);
557
558 Self {
559 x_axis: Vec4(_mm_shuffle_ps(tmp0, tmp2, 0b10_00_10_00)),
560 y_axis: Vec4(_mm_shuffle_ps(tmp0, tmp2, 0b11_01_11_01)),
561 z_axis: Vec4(_mm_shuffle_ps(tmp1, tmp3, 0b10_00_10_00)),
562 w_axis: Vec4(_mm_shuffle_ps(tmp1, tmp3, 0b11_01_11_01)),
563 }
564 }
565 }
566
567 /// Returns the determinant of `self`.
568 pub fn determinant(&self) -> f32 {
569 unsafe {
570 // Based on https://github.com/g-truc/glm `glm_mat4_determinant_lowp`
571 let swp2a = _mm_shuffle_ps(self.z_axis.0, self.z_axis.0, 0b00_01_01_10);
572 let swp3a = _mm_shuffle_ps(self.w_axis.0, self.w_axis.0, 0b11_10_11_11);
573 let swp2b = _mm_shuffle_ps(self.z_axis.0, self.z_axis.0, 0b11_10_11_11);
574 let swp3b = _mm_shuffle_ps(self.w_axis.0, self.w_axis.0, 0b00_01_01_10);
575 let swp2c = _mm_shuffle_ps(self.z_axis.0, self.z_axis.0, 0b00_00_01_10);
576 let swp3c = _mm_shuffle_ps(self.w_axis.0, self.w_axis.0, 0b01_10_00_00);
577
578 let mula = _mm_mul_ps(swp2a, swp3a);
579 let mulb = _mm_mul_ps(swp2b, swp3b);
580 let mulc = _mm_mul_ps(swp2c, swp3c);
581 let sube = _mm_sub_ps(mula, mulb);
582 let subf = _mm_sub_ps(_mm_movehl_ps(mulc, mulc), mulc);
583
584 let subfaca = _mm_shuffle_ps(sube, sube, 0b10_01_00_00);
585 let swpfaca = _mm_shuffle_ps(self.y_axis.0, self.y_axis.0, 0b00_00_00_01);
586 let mulfaca = _mm_mul_ps(swpfaca, subfaca);
587
588 let subtmpb = _mm_shuffle_ps(sube, subf, 0b00_00_11_01);
589 let subfacb = _mm_shuffle_ps(subtmpb, subtmpb, 0b11_01_01_00);
590 let swpfacb = _mm_shuffle_ps(self.y_axis.0, self.y_axis.0, 0b01_01_10_10);
591 let mulfacb = _mm_mul_ps(swpfacb, subfacb);
592
593 let subres = _mm_sub_ps(mulfaca, mulfacb);
594 let subtmpc = _mm_shuffle_ps(sube, subf, 0b01_00_10_10);
595 let subfacc = _mm_shuffle_ps(subtmpc, subtmpc, 0b11_11_10_00);
596 let swpfacc = _mm_shuffle_ps(self.y_axis.0, self.y_axis.0, 0b10_11_11_11);
597 let mulfacc = _mm_mul_ps(swpfacc, subfacc);
598
599 let addres = _mm_add_ps(subres, mulfacc);
600 let detcof = _mm_mul_ps(addres, _mm_setr_ps(1.0, -1.0, 1.0, -1.0));
601
602 dot4(self.x_axis.0, detcof)
603 }
604 }
605
606 /// Returns the inverse of `self`.
607 ///
608 /// If the matrix is not invertible the returned matrix will be invalid.
609 ///
610 /// # Panics
611 ///
612 /// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
613 #[must_use]
614 pub fn inverse(&self) -> Self {
615 unsafe {
616 // Based on https://github.com/g-truc/glm `glm_mat4_inverse`
617 let fac0 = {
618 let swp0a = _mm_shuffle_ps(self.w_axis.0, self.z_axis.0, 0b11_11_11_11);
619 let swp0b = _mm_shuffle_ps(self.w_axis.0, self.z_axis.0, 0b10_10_10_10);
620
621 let swp00 = _mm_shuffle_ps(self.z_axis.0, self.y_axis.0, 0b10_10_10_10);
622 let swp01 = _mm_shuffle_ps(swp0a, swp0a, 0b10_00_00_00);
623 let swp02 = _mm_shuffle_ps(swp0b, swp0b, 0b10_00_00_00);
624 let swp03 = _mm_shuffle_ps(self.z_axis.0, self.y_axis.0, 0b11_11_11_11);
625
626 let mul00 = _mm_mul_ps(swp00, swp01);
627 let mul01 = _mm_mul_ps(swp02, swp03);
628 _mm_sub_ps(mul00, mul01)
629 };
630 let fac1 = {
631 let swp0a = _mm_shuffle_ps(self.w_axis.0, self.z_axis.0, 0b11_11_11_11);
632 let swp0b = _mm_shuffle_ps(self.w_axis.0, self.z_axis.0, 0b01_01_01_01);
633
634 let swp00 = _mm_shuffle_ps(self.z_axis.0, self.y_axis.0, 0b01_01_01_01);
635 let swp01 = _mm_shuffle_ps(swp0a, swp0a, 0b10_00_00_00);
636 let swp02 = _mm_shuffle_ps(swp0b, swp0b, 0b10_00_00_00);
637 let swp03 = _mm_shuffle_ps(self.z_axis.0, self.y_axis.0, 0b11_11_11_11);
638
639 let mul00 = _mm_mul_ps(swp00, swp01);
640 let mul01 = _mm_mul_ps(swp02, swp03);
641 _mm_sub_ps(mul00, mul01)
642 };
643 let fac2 = {
644 let swp0a = _mm_shuffle_ps(self.w_axis.0, self.z_axis.0, 0b10_10_10_10);
645 let swp0b = _mm_shuffle_ps(self.w_axis.0, self.z_axis.0, 0b01_01_01_01);
646
647 let swp00 = _mm_shuffle_ps(self.z_axis.0, self.y_axis.0, 0b01_01_01_01);
648 let swp01 = _mm_shuffle_ps(swp0a, swp0a, 0b10_00_00_00);
649 let swp02 = _mm_shuffle_ps(swp0b, swp0b, 0b10_00_00_00);
650 let swp03 = _mm_shuffle_ps(self.z_axis.0, self.y_axis.0, 0b10_10_10_10);
651
652 let mul00 = _mm_mul_ps(swp00, swp01);
653 let mul01 = _mm_mul_ps(swp02, swp03);
654 _mm_sub_ps(mul00, mul01)
655 };
656 let fac3 = {
657 let swp0a = _mm_shuffle_ps(self.w_axis.0, self.z_axis.0, 0b11_11_11_11);
658 let swp0b = _mm_shuffle_ps(self.w_axis.0, self.z_axis.0, 0b00_00_00_00);
659
660 let swp00 = _mm_shuffle_ps(self.z_axis.0, self.y_axis.0, 0b00_00_00_00);
661 let swp01 = _mm_shuffle_ps(swp0a, swp0a, 0b10_00_00_00);
662 let swp02 = _mm_shuffle_ps(swp0b, swp0b, 0b10_00_00_00);
663 let swp03 = _mm_shuffle_ps(self.z_axis.0, self.y_axis.0, 0b11_11_11_11);
664
665 let mul00 = _mm_mul_ps(swp00, swp01);
666 let mul01 = _mm_mul_ps(swp02, swp03);
667 _mm_sub_ps(mul00, mul01)
668 };
669 let fac4 = {
670 let swp0a = _mm_shuffle_ps(self.w_axis.0, self.z_axis.0, 0b10_10_10_10);
671 let swp0b = _mm_shuffle_ps(self.w_axis.0, self.z_axis.0, 0b00_00_00_00);
672
673 let swp00 = _mm_shuffle_ps(self.z_axis.0, self.y_axis.0, 0b00_00_00_00);
674 let swp01 = _mm_shuffle_ps(swp0a, swp0a, 0b10_00_00_00);
675 let swp02 = _mm_shuffle_ps(swp0b, swp0b, 0b10_00_00_00);
676 let swp03 = _mm_shuffle_ps(self.z_axis.0, self.y_axis.0, 0b10_10_10_10);
677
678 let mul00 = _mm_mul_ps(swp00, swp01);
679 let mul01 = _mm_mul_ps(swp02, swp03);
680 _mm_sub_ps(mul00, mul01)
681 };
682 let fac5 = {
683 let swp0a = _mm_shuffle_ps(self.w_axis.0, self.z_axis.0, 0b01_01_01_01);
684 let swp0b = _mm_shuffle_ps(self.w_axis.0, self.z_axis.0, 0b00_00_00_00);
685
686 let swp00 = _mm_shuffle_ps(self.z_axis.0, self.y_axis.0, 0b00_00_00_00);
687 let swp01 = _mm_shuffle_ps(swp0a, swp0a, 0b10_00_00_00);
688 let swp02 = _mm_shuffle_ps(swp0b, swp0b, 0b10_00_00_00);
689 let swp03 = _mm_shuffle_ps(self.z_axis.0, self.y_axis.0, 0b01_01_01_01);
690
691 let mul00 = _mm_mul_ps(swp00, swp01);
692 let mul01 = _mm_mul_ps(swp02, swp03);
693 _mm_sub_ps(mul00, mul01)
694 };
695 let sign_a = _mm_set_ps(1.0, -1.0, 1.0, -1.0);
696 let sign_b = _mm_set_ps(-1.0, 1.0, -1.0, 1.0);
697
698 let temp0 = _mm_shuffle_ps(self.y_axis.0, self.x_axis.0, 0b00_00_00_00);
699 let vec0 = _mm_shuffle_ps(temp0, temp0, 0b10_10_10_00);
700
701 let temp1 = _mm_shuffle_ps(self.y_axis.0, self.x_axis.0, 0b01_01_01_01);
702 let vec1 = _mm_shuffle_ps(temp1, temp1, 0b10_10_10_00);
703
704 let temp2 = _mm_shuffle_ps(self.y_axis.0, self.x_axis.0, 0b10_10_10_10);
705 let vec2 = _mm_shuffle_ps(temp2, temp2, 0b10_10_10_00);
706
707 let temp3 = _mm_shuffle_ps(self.y_axis.0, self.x_axis.0, 0b11_11_11_11);
708 let vec3 = _mm_shuffle_ps(temp3, temp3, 0b10_10_10_00);
709
710 let mul00 = _mm_mul_ps(vec1, fac0);
711 let mul01 = _mm_mul_ps(vec2, fac1);
712 let mul02 = _mm_mul_ps(vec3, fac2);
713 let sub00 = _mm_sub_ps(mul00, mul01);
714 let add00 = _mm_add_ps(sub00, mul02);
715 let inv0 = _mm_mul_ps(sign_b, add00);
716
717 let mul03 = _mm_mul_ps(vec0, fac0);
718 let mul04 = _mm_mul_ps(vec2, fac3);
719 let mul05 = _mm_mul_ps(vec3, fac4);
720 let sub01 = _mm_sub_ps(mul03, mul04);
721 let add01 = _mm_add_ps(sub01, mul05);
722 let inv1 = _mm_mul_ps(sign_a, add01);
723
724 let mul06 = _mm_mul_ps(vec0, fac1);
725 let mul07 = _mm_mul_ps(vec1, fac3);
726 let mul08 = _mm_mul_ps(vec3, fac5);
727 let sub02 = _mm_sub_ps(mul06, mul07);
728 let add02 = _mm_add_ps(sub02, mul08);
729 let inv2 = _mm_mul_ps(sign_b, add02);
730
731 let mul09 = _mm_mul_ps(vec0, fac2);
732 let mul10 = _mm_mul_ps(vec1, fac4);
733 let mul11 = _mm_mul_ps(vec2, fac5);
734 let sub03 = _mm_sub_ps(mul09, mul10);
735 let add03 = _mm_add_ps(sub03, mul11);
736 let inv3 = _mm_mul_ps(sign_a, add03);
737
738 let row0 = _mm_shuffle_ps(inv0, inv1, 0b00_00_00_00);
739 let row1 = _mm_shuffle_ps(inv2, inv3, 0b00_00_00_00);
740 let row2 = _mm_shuffle_ps(row0, row1, 0b10_00_10_00);
741
742 let dot0 = dot4(self.x_axis.0, row2);
743 glam_assert!(dot0 != 0.0);
744
745 let rcp0 = _mm_set1_ps(dot0.recip());
746
747 Self {
748 x_axis: Vec4(_mm_mul_ps(inv0, rcp0)),
749 y_axis: Vec4(_mm_mul_ps(inv1, rcp0)),
750 z_axis: Vec4(_mm_mul_ps(inv2, rcp0)),
751 w_axis: Vec4(_mm_mul_ps(inv3, rcp0)),
752 }
753 }
754 }
755
756 /// Creates a left-handed view matrix using a camera position, an up direction, and a facing
757 /// direction.
758 ///
759 /// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`.
760 #[inline]
761 pub fn look_to_lh(eye: Vec3, dir: Vec3, up: Vec3) -> Self {
762 Self::look_to_rh(eye, -dir, up)
763 }
764
765 /// Creates a right-handed view matrix using a camera position, an up direction, and a facing
766 /// direction.
767 ///
768 /// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`.
769 #[inline]
770 pub fn look_to_rh(eye: Vec3, dir: Vec3, up: Vec3) -> Self {
771 let f = dir.normalize();
772 let s = f.cross(up).normalize();
773 let u = s.cross(f);
774
775 Self::from_cols(
776 Vec4::new(s.x, u.x, -f.x, 0.0),
777 Vec4::new(s.y, u.y, -f.y, 0.0),
778 Vec4::new(s.z, u.z, -f.z, 0.0),
779 Vec4::new(-eye.dot(s), -eye.dot(u), eye.dot(f), 1.0),
780 )
781 }
782
783 /// Creates a left-handed view matrix using a camera position, an up direction, and a focal
784 /// point.
785 /// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`.
786 ///
787 /// # Panics
788 ///
789 /// Will panic if `up` is not normalized when `glam_assert` is enabled.
790 #[inline]
791 pub fn look_at_lh(eye: Vec3, center: Vec3, up: Vec3) -> Self {
792 glam_assert!(up.is_normalized());
793 Self::look_to_lh(eye, center.sub(eye), up)
794 }
795
796 /// Creates a right-handed view matrix using a camera position, an up direction, and a focal
797 /// point.
798 /// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`.
799 ///
800 /// # Panics
801 ///
802 /// Will panic if `up` is not normalized when `glam_assert` is enabled.
803 #[inline]
804 pub fn look_at_rh(eye: Vec3, center: Vec3, up: Vec3) -> Self {
805 glam_assert!(up.is_normalized());
806 Self::look_to_rh(eye, center.sub(eye), up)
807 }
808
809 /// Creates a right-handed perspective projection matrix with [-1,1] depth range.
810 /// This is the same as the OpenGL `gluPerspective` function.
811 /// See <https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluPerspective.xml>
812 #[inline]
813 pub fn perspective_rh_gl(
814 fov_y_radians: f32,
815 aspect_ratio: f32,
816 z_near: f32,
817 z_far: f32,
818 ) -> Self {
819 let inv_length = 1.0 / (z_near - z_far);
820 let f = 1.0 / (0.5 * fov_y_radians).tan();
821 let a = f / aspect_ratio;
822 let b = (z_near + z_far) * inv_length;
823 let c = (2.0 * z_near * z_far) * inv_length;
824 Self::from_cols(
825 Vec4::new(a, 0.0, 0.0, 0.0),
826 Vec4::new(0.0, f, 0.0, 0.0),
827 Vec4::new(0.0, 0.0, b, -1.0),
828 Vec4::new(0.0, 0.0, c, 0.0),
829 )
830 }
831
832 /// Creates a left-handed perspective projection matrix with `[0,1]` depth range.
833 ///
834 /// # Panics
835 ///
836 /// Will panic if `z_near` or `z_far` are less than or equal to zero when `glam_assert` is
837 /// enabled.
838 #[inline]
839 pub fn perspective_lh(fov_y_radians: f32, aspect_ratio: f32, z_near: f32, z_far: f32) -> Self {
840 glam_assert!(z_near > 0.0 && z_far > 0.0);
841 let (sin_fov, cos_fov) = (0.5 * fov_y_radians).sin_cos();
842 let h = cos_fov / sin_fov;
843 let w = h / aspect_ratio;
844 let r = z_far / (z_far - z_near);
845 Self::from_cols(
846 Vec4::new(w, 0.0, 0.0, 0.0),
847 Vec4::new(0.0, h, 0.0, 0.0),
848 Vec4::new(0.0, 0.0, r, 1.0),
849 Vec4::new(0.0, 0.0, -r * z_near, 0.0),
850 )
851 }
852
853 /// Creates a right-handed perspective projection matrix with `[0,1]` depth range.
854 ///
855 /// # Panics
856 ///
857 /// Will panic if `z_near` or `z_far` are less than or equal to zero when `glam_assert` is
858 /// enabled.
859 #[inline]
860 pub fn perspective_rh(fov_y_radians: f32, aspect_ratio: f32, z_near: f32, z_far: f32) -> Self {
861 glam_assert!(z_near > 0.0 && z_far > 0.0);
862 let (sin_fov, cos_fov) = (0.5 * fov_y_radians).sin_cos();
863 let h = cos_fov / sin_fov;
864 let w = h / aspect_ratio;
865 let r = z_far / (z_near - z_far);
866 Self::from_cols(
867 Vec4::new(w, 0.0, 0.0, 0.0),
868 Vec4::new(0.0, h, 0.0, 0.0),
869 Vec4::new(0.0, 0.0, r, -1.0),
870 Vec4::new(0.0, 0.0, r * z_near, 0.0),
871 )
872 }
873
874 /// Creates an infinite left-handed perspective projection matrix with `[0,1]` depth range.
875 ///
876 /// # Panics
877 ///
878 /// Will panic if `z_near` is less than or equal to zero when `glam_assert` is enabled.
879 #[inline]
880 pub fn perspective_infinite_lh(fov_y_radians: f32, aspect_ratio: f32, z_near: f32) -> Self {
881 glam_assert!(z_near > 0.0);
882 let (sin_fov, cos_fov) = (0.5 * fov_y_radians).sin_cos();
883 let h = cos_fov / sin_fov;
884 let w = h / aspect_ratio;
885 Self::from_cols(
886 Vec4::new(w, 0.0, 0.0, 0.0),
887 Vec4::new(0.0, h, 0.0, 0.0),
888 Vec4::new(0.0, 0.0, 1.0, 1.0),
889 Vec4::new(0.0, 0.0, -z_near, 0.0),
890 )
891 }
892
893 /// Creates an infinite left-handed perspective projection matrix with `[0,1]` depth range.
894 ///
895 /// # Panics
896 ///
897 /// Will panic if `z_near` is less than or equal to zero when `glam_assert` is enabled.
898 #[inline]
899 pub fn perspective_infinite_reverse_lh(
900 fov_y_radians: f32,
901 aspect_ratio: f32,
902 z_near: f32,
903 ) -> Self {
904 glam_assert!(z_near > 0.0);
905 let (sin_fov, cos_fov) = (0.5 * fov_y_radians).sin_cos();
906 let h = cos_fov / sin_fov;
907 let w = h / aspect_ratio;
908 Self::from_cols(
909 Vec4::new(w, 0.0, 0.0, 0.0),
910 Vec4::new(0.0, h, 0.0, 0.0),
911 Vec4::new(0.0, 0.0, 0.0, 1.0),
912 Vec4::new(0.0, 0.0, z_near, 0.0),
913 )
914 }
915
916 /// Creates an infinite right-handed perspective projection matrix with
917 /// `[0,1]` depth range.
918 #[inline]
919 pub fn perspective_infinite_rh(fov_y_radians: f32, aspect_ratio: f32, z_near: f32) -> Self {
920 glam_assert!(z_near > 0.0);
921 let f = 1.0 / (0.5 * fov_y_radians).tan();
922 Self::from_cols(
923 Vec4::new(f / aspect_ratio, 0.0, 0.0, 0.0),
924 Vec4::new(0.0, f, 0.0, 0.0),
925 Vec4::new(0.0, 0.0, -1.0, -1.0),
926 Vec4::new(0.0, 0.0, -z_near, 0.0),
927 )
928 }
929
930 /// Creates an infinite reverse right-handed perspective projection matrix
931 /// with `[0,1]` depth range.
932 #[inline]
933 pub fn perspective_infinite_reverse_rh(
934 fov_y_radians: f32,
935 aspect_ratio: f32,
936 z_near: f32,
937 ) -> Self {
938 glam_assert!(z_near > 0.0);
939 let f = 1.0 / (0.5 * fov_y_radians).tan();
940 Self::from_cols(
941 Vec4::new(f / aspect_ratio, 0.0, 0.0, 0.0),
942 Vec4::new(0.0, f, 0.0, 0.0),
943 Vec4::new(0.0, 0.0, 0.0, -1.0),
944 Vec4::new(0.0, 0.0, z_near, 0.0),
945 )
946 }
947
948 /// Creates a right-handed orthographic projection matrix with `[-1,1]` depth
949 /// range. This is the same as the OpenGL `glOrtho` function in OpenGL.
950 /// See
951 /// <https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glOrtho.xml>
952 #[inline]
953 pub fn orthographic_rh_gl(
954 left: f32,
955 right: f32,
956 bottom: f32,
957 top: f32,
958 near: f32,
959 far: f32,
960 ) -> Self {
961 let a = 2.0 / (right - left);
962 let b = 2.0 / (top - bottom);
963 let c = -2.0 / (far - near);
964 let tx = -(right + left) / (right - left);
965 let ty = -(top + bottom) / (top - bottom);
966 let tz = -(far + near) / (far - near);
967
968 Self::from_cols(
969 Vec4::new(a, 0.0, 0.0, 0.0),
970 Vec4::new(0.0, b, 0.0, 0.0),
971 Vec4::new(0.0, 0.0, c, 0.0),
972 Vec4::new(tx, ty, tz, 1.0),
973 )
974 }
975
976 /// Creates a left-handed orthographic projection matrix with `[0,1]` depth range.
977 #[inline]
978 pub fn orthographic_lh(
979 left: f32,
980 right: f32,
981 bottom: f32,
982 top: f32,
983 near: f32,
984 far: f32,
985 ) -> Self {
986 let rcp_width = 1.0 / (right - left);
987 let rcp_height = 1.0 / (top - bottom);
988 let r = 1.0 / (far - near);
989 Self::from_cols(
990 Vec4::new(rcp_width + rcp_width, 0.0, 0.0, 0.0),
991 Vec4::new(0.0, rcp_height + rcp_height, 0.0, 0.0),
992 Vec4::new(0.0, 0.0, r, 0.0),
993 Vec4::new(
994 -(left + right) * rcp_width,
995 -(top + bottom) * rcp_height,
996 -r * near,
997 1.0,
998 ),
999 )
1000 }
1001
1002 /// Creates a right-handed orthographic projection matrix with `[0,1]` depth range.
1003 #[inline]
1004 pub fn orthographic_rh(
1005 left: f32,
1006 right: f32,
1007 bottom: f32,
1008 top: f32,
1009 near: f32,
1010 far: f32,
1011 ) -> Self {
1012 let rcp_width = 1.0 / (right - left);
1013 let rcp_height = 1.0 / (top - bottom);
1014 let r = 1.0 / (near - far);
1015 Self::from_cols(
1016 Vec4::new(rcp_width + rcp_width, 0.0, 0.0, 0.0),
1017 Vec4::new(0.0, rcp_height + rcp_height, 0.0, 0.0),
1018 Vec4::new(0.0, 0.0, r, 0.0),
1019 Vec4::new(
1020 -(left + right) * rcp_width,
1021 -(top + bottom) * rcp_height,
1022 r * near,
1023 1.0,
1024 ),
1025 )
1026 }
1027
1028 /// Transforms the given 3D vector as a point, applying perspective correction.
1029 ///
1030 /// This is the equivalent of multiplying the 3D vector as a 4D vector where `w` is `1.0`.
1031 /// The perspective divide is performed meaning the resulting 3D vector is divided by `w`.
1032 ///
1033 /// This method assumes that `self` contains a projective transform.
1034 #[inline]
1035 pub fn project_point3(&self, rhs: Vec3) -> Vec3 {
1036 let mut res = self.x_axis.mul(rhs.x);
1037 res = self.y_axis.mul(rhs.y).add(res);
1038 res = self.z_axis.mul(rhs.z).add(res);
1039 res = self.w_axis.add(res);
1040 res = res.mul(res.wwww().recip());
1041 res.xyz()
1042 }
1043
1044 /// Transforms the given 3D vector as a point.
1045 ///
1046 /// This is the equivalent of multiplying the 3D vector as a 4D vector where `w` is
1047 /// `1.0`.
1048 ///
1049 /// This method assumes that `self` contains a valid affine transform. It does not perform
1050 /// a persective divide, if `self` contains a perspective transform, or if you are unsure,
1051 /// the [`Self::project_point3()`] method should be used instead.
1052 ///
1053 /// # Panics
1054 ///
1055 /// Will panic if the 3rd row of `self` is not `(0, 0, 0, 1)` when `glam_assert` is enabled.
1056 #[inline]
1057 pub fn transform_point3(&self, rhs: Vec3) -> Vec3 {
1058 glam_assert!(self.row(3).abs_diff_eq(Vec4::W, 1e-6));
1059 let mut res = self.x_axis.mul(rhs.x);
1060 res = self.y_axis.mul(rhs.y).add(res);
1061 res = self.z_axis.mul(rhs.z).add(res);
1062 res = self.w_axis.add(res);
1063 res.xyz()
1064 }
1065
1066 /// Transforms the give 3D vector as a direction.
1067 ///
1068 /// This is the equivalent of multiplying the 3D vector as a 4D vector where `w` is
1069 /// `0.0`.
1070 ///
1071 /// This method assumes that `self` contains a valid affine transform.
1072 ///
1073 /// # Panics
1074 ///
1075 /// Will panic if the 3rd row of `self` is not `(0, 0, 0, 1)` when `glam_assert` is enabled.
1076 #[inline]
1077 pub fn transform_vector3(&self, rhs: Vec3) -> Vec3 {
1078 glam_assert!(self.row(3).abs_diff_eq(Vec4::W, 1e-6));
1079 let mut res = self.x_axis.mul(rhs.x);
1080 res = self.y_axis.mul(rhs.y).add(res);
1081 res = self.z_axis.mul(rhs.z).add(res);
1082 res.xyz()
1083 }
1084
1085 /// Transforms the given `Vec3A` as 3D point.
1086 ///
1087 /// This is the equivalent of multiplying the `Vec3A` as a 4D vector where `w` is `1.0`.
1088 #[inline]
1089 pub fn transform_point3a(&self, rhs: Vec3A) -> Vec3A {
1090 glam_assert!(self.row(3).abs_diff_eq(Vec4::W, 1e-6));
1091 let mut res = self.x_axis.mul(rhs.xxxx());
1092 res = self.y_axis.mul(rhs.yyyy()).add(res);
1093 res = self.z_axis.mul(rhs.zzzz()).add(res);
1094 res = self.w_axis.add(res);
1095 res.into()
1096 }
1097
1098 /// Transforms the give `Vec3A` as 3D vector.
1099 ///
1100 /// This is the equivalent of multiplying the `Vec3A` as a 4D vector where `w` is `0.0`.
1101 #[inline]
1102 pub fn transform_vector3a(&self, rhs: Vec3A) -> Vec3A {
1103 glam_assert!(self.row(3).abs_diff_eq(Vec4::W, 1e-6));
1104 let mut res = self.x_axis.mul(rhs.xxxx());
1105 res = self.y_axis.mul(rhs.yyyy()).add(res);
1106 res = self.z_axis.mul(rhs.zzzz()).add(res);
1107 res.into()
1108 }
1109
1110 /// Transforms a 4D vector.
1111 #[inline]
1112 pub fn mul_vec4(&self, rhs: Vec4) -> Vec4 {
1113 let mut res = self.x_axis.mul(rhs.xxxx());
1114 res = res.add(self.y_axis.mul(rhs.yyyy()));
1115 res = res.add(self.z_axis.mul(rhs.zzzz()));
1116 res = res.add(self.w_axis.mul(rhs.wwww()));
1117 res
1118 }
1119
1120 /// Multiplies two 4x4 matrices.
1121 #[inline]
1122 pub fn mul_mat4(&self, rhs: &Self) -> Self {
1123 Self::from_cols(
1124 self.mul(rhs.x_axis),
1125 self.mul(rhs.y_axis),
1126 self.mul(rhs.z_axis),
1127 self.mul(rhs.w_axis),
1128 )
1129 }
1130
1131 /// Adds two 4x4 matrices.
1132 #[inline]
1133 pub fn add_mat4(&self, rhs: &Self) -> Self {
1134 Self::from_cols(
1135 self.x_axis.add(rhs.x_axis),
1136 self.y_axis.add(rhs.y_axis),
1137 self.z_axis.add(rhs.z_axis),
1138 self.w_axis.add(rhs.w_axis),
1139 )
1140 }
1141
1142 /// Subtracts two 4x4 matrices.
1143 #[inline]
1144 pub fn sub_mat4(&self, rhs: &Self) -> Self {
1145 Self::from_cols(
1146 self.x_axis.sub(rhs.x_axis),
1147 self.y_axis.sub(rhs.y_axis),
1148 self.z_axis.sub(rhs.z_axis),
1149 self.w_axis.sub(rhs.w_axis),
1150 )
1151 }
1152
1153 /// Multiplies a 4x4 matrix by a scalar.
1154 #[inline]
1155 pub fn mul_scalar(&self, rhs: f32) -> Self {
1156 Self::from_cols(
1157 self.x_axis.mul(rhs),
1158 self.y_axis.mul(rhs),
1159 self.z_axis.mul(rhs),
1160 self.w_axis.mul(rhs),
1161 )
1162 }
1163
1164 /// Returns true if the absolute difference of all elements between `self` and `rhs`
1165 /// is less than or equal to `max_abs_diff`.
1166 ///
1167 /// This can be used to compare if two matrices contain similar elements. It works best
1168 /// when comparing with a known value. The `max_abs_diff` that should be used used
1169 /// depends on the values being compared against.
1170 ///
1171 /// For more see
1172 /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
1173 #[inline]
1174 pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
1175 self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
1176 && self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
1177 && self.z_axis.abs_diff_eq(rhs.z_axis, max_abs_diff)
1178 && self.w_axis.abs_diff_eq(rhs.w_axis, max_abs_diff)
1179 }
1180
1181 #[inline]
1182 pub fn as_dmat4(&self) -> DMat4 {
1183 DMat4::from_cols(
1184 self.x_axis.as_dvec4(),
1185 self.y_axis.as_dvec4(),
1186 self.z_axis.as_dvec4(),
1187 self.w_axis.as_dvec4(),
1188 )
1189 }
1190 }
1191
1192 impl Default for Mat4 {
1193 #[inline]
1194 fn default() -> Self {
1195 Self::IDENTITY
1196 }
1197 }
1198
1199 impl Add<Mat4> for Mat4 {
1200 type Output = Self;
1201 #[inline]
1202 fn add(self, rhs: Self) -> Self::Output {
1203 self.add_mat4(&rhs)
1204 }
1205 }
1206
1207 impl AddAssign<Mat4> for Mat4 {
1208 #[inline]
1209 fn add_assign(&mut self, rhs: Self) {
1210 *self = self.add_mat4(&rhs);
1211 }
1212 }
1213
1214 impl Sub<Mat4> for Mat4 {
1215 type Output = Self;
1216 #[inline]
1217 fn sub(self, rhs: Self) -> Self::Output {
1218 self.sub_mat4(&rhs)
1219 }
1220 }
1221
1222 impl SubAssign<Mat4> for Mat4 {
1223 #[inline]
1224 fn sub_assign(&mut self, rhs: Self) {
1225 *self = self.sub_mat4(&rhs);
1226 }
1227 }
1228
1229 impl Neg for Mat4 {
1230 type Output = Self;
1231 #[inline]
1232 fn neg(self) -> Self::Output {
1233 Self::from_cols(
1234 self.x_axis.neg(),
1235 self.y_axis.neg(),
1236 self.z_axis.neg(),
1237 self.w_axis.neg(),
1238 )
1239 }
1240 }
1241
1242 impl Mul<Mat4> for Mat4 {
1243 type Output = Self;
1244 #[inline]
1245 fn mul(self, rhs: Self) -> Self::Output {
1246 self.mul_mat4(&rhs)
1247 }
1248 }
1249
1250 impl MulAssign<Mat4> for Mat4 {
1251 #[inline]
1252 fn mul_assign(&mut self, rhs: Self) {
1253 *self = self.mul_mat4(&rhs);
1254 }
1255 }
1256
1257 impl Mul<Vec4> for Mat4 {
1258 type Output = Vec4;
1259 #[inline]
1260 fn mul(self, rhs: Vec4) -> Self::Output {
1261 self.mul_vec4(rhs)
1262 }
1263 }
1264
1265 impl Mul<Mat4> for f32 {
1266 type Output = Mat4;
1267 #[inline]
1268 fn mul(self, rhs: Mat4) -> Self::Output {
1269 rhs.mul_scalar(self)
1270 }
1271 }
1272
1273 impl Mul<f32> for Mat4 {
1274 type Output = Self;
1275 #[inline]
1276 fn mul(self, rhs: f32) -> Self::Output {
1277 self.mul_scalar(rhs)
1278 }
1279 }
1280
1281 impl MulAssign<f32> for Mat4 {
1282 #[inline]
1283 fn mul_assign(&mut self, rhs: f32) {
1284 *self = self.mul_scalar(rhs);
1285 }
1286 }
1287
1288 impl Sum<Self> for Mat4 {
1289 fn sum<I>(iter: I) -> Self
1290 where
1291 I: Iterator<Item = Self>,
1292 {
1293 iter.fold(Self::ZERO, Self::add)
1294 }
1295 }
1296
1297 impl<'a> Sum<&'a Self> for Mat4 {
1298 fn sum<I>(iter: I) -> Self
1299 where
1300 I: Iterator<Item = &'a Self>,
1301 {
1302 iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
1303 }
1304 }
1305
1306 impl Product for Mat4 {
1307 fn product<I>(iter: I) -> Self
1308 where
1309 I: Iterator<Item = Self>,
1310 {
1311 iter.fold(Self::IDENTITY, Self::mul)
1312 }
1313 }
1314
1315 impl<'a> Product<&'a Self> for Mat4 {
1316 fn product<I>(iter: I) -> Self
1317 where
1318 I: Iterator<Item = &'a Self>,
1319 {
1320 iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
1321 }
1322 }
1323
1324 impl PartialEq for Mat4 {
1325 #[inline]
1326 fn eq(&self, rhs: &Self) -> bool {
1327 self.x_axis.eq(&rhs.x_axis)
1328 && self.y_axis.eq(&rhs.y_axis)
1329 && self.z_axis.eq(&rhs.z_axis)
1330 && self.w_axis.eq(&rhs.w_axis)
1331 }
1332 }
1333
1334 #[cfg(not(target_arch = "spirv"))]
1335 impl AsRef<[f32; 16]> for Mat4 {
1336 #[inline]
1337 fn as_ref(&self) -> &[f32; 16] {
1338 unsafe { &*(self as *const Self as *const [f32; 16]) }
1339 }
1340 }
1341
1342 #[cfg(not(target_arch = "spirv"))]
1343 impl AsMut<[f32; 16]> for Mat4 {
1344 #[inline]
1345 fn as_mut(&mut self) -> &mut [f32; 16] {
1346 unsafe { &mut *(self as *mut Self as *mut [f32; 16]) }
1347 }
1348 }
1349
1350 #[cfg(not(target_arch = "spirv"))]
1351 impl fmt::Debug for Mat4 {
1352 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1353 fmt.debug_struct(stringify!(Mat4))
1354 .field("x_axis", &self.x_axis)
1355 .field("y_axis", &self.y_axis)
1356 .field("z_axis", &self.z_axis)
1357 .field("w_axis", &self.w_axis)
1358 .finish()
1359 }
1360 }
1361
1362 #[cfg(not(target_arch = "spirv"))]
1363 impl fmt::Display for Mat4 {
1364 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1365 write!(
1366 f,
1367 "[{}, {}, {}, {}]",
1368 self.x_axis, self.y_axis, self.z_axis, self.w_axis
1369 )
1370 }
1371 }