Debian Codegraph @

debian/missing-sources/glam-0.18.0/src/affine3.rs

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