Debian Codegraph @

debian/missing-sources/glam-0.20.5/src/quat.rs

raw symbols SCIP
1 use crate::core::traits::{
2 quaternion::Quaternion,
3 vector::{FloatVector4, MaskVector4, Vector, Vector4, Vector4Const},
4 };
5 use crate::euler::{EulerFromQuaternion, EulerRot, EulerToQuaternion};
6 use crate::{DMat3, DMat4, DVec2, DVec3, DVec4};
7 use crate::{Mat3, Mat4, Vec2, Vec3, Vec3A, Vec4};
8
9 #[cfg(not(feature = "std"))]
10 use num_traits::Float;
11
12 #[cfg(all(
13 target_arch = "x86",
14 target_feature = "sse2",
15 not(feature = "scalar-math")
16 ))]
17 use core::arch::x86::*;
18 #[cfg(all(
19 target_arch = "x86_64",
20 target_feature = "sse2",
21 not(feature = "scalar-math")
22 ))]
23 use core::arch::x86_64::*;
24
25 #[cfg(all(target_feature = "simd128", not(feature = "scalar-math")))]
26 use core::arch::wasm32::v128;
27
28 #[cfg(not(target_arch = "spirv"))]
29 use core::fmt;
30 use core::iter::{Product, Sum};
31 use core::ops::{Add, Deref, Div, Mul, MulAssign, Neg, Sub};
32
33 macro_rules! impl_quat_methods {
34 ($t:ident, $quat:ident, $vec2:ident, $vec3:ident, $vec4:ident, $mat3:ident, $mat4:ident, $inner:ident) => {
35 /// The identity quaternion. Corresponds to no rotation.
36 pub const IDENTITY: Self = Self($inner::W);
37
38 /// All NAN:s.
39 pub const NAN: Self = Self(<$inner as crate::core::traits::scalar::NanConstEx>::NAN);
40
41 /// Creates a new rotation quaternion.
42 ///
43 /// This should generally not be called manually unless you know what you are doing.
44 /// Use one of the other constructors instead such as `identity` or `from_axis_angle`.
45 ///
46 /// `from_xyzw` is mostly used by unit tests and `serde` deserialization.
47 ///
48 /// # Preconditions
49 ///
50 /// This function does not check if the input is normalized, it is up to the user to
51 /// provide normalized input or to normalized the resulting quaternion.
52 #[inline(always)]
53 pub fn from_xyzw(x: $t, y: $t, z: $t, w: $t) -> Self {
54 Self(Vector4::new(x, y, z, w))
55 }
56
57 /// Creates a rotation quaternion from an array.
58 ///
59 /// # Preconditions
60 ///
61 /// This function does not check if the input is normalized, it is up to the user to
62 /// provide normalized input or to normalized the resulting quaternion.
63 #[inline(always)]
64 pub fn from_array(a: [$t; 4]) -> Self {
65 let q = Vector4::from_array(a);
66 Self(q)
67 }
68
69 /// Creates a new rotation quaternion from a 4D vector.
70 ///
71 /// # Preconditions
72 ///
73 /// This function does not check if the input is normalized, it is up to the user to
74 /// provide normalized input or to normalized the resulting quaternion.
75 #[inline(always)]
76 pub fn from_vec4(v: $vec4) -> Self {
77 Self(v.0)
78 }
79
80 /// Creates a rotation quaternion from a slice.
81 ///
82 /// # Preconditions
83 ///
84 /// This function does not check if the input is normalized, it is up to the user to
85 /// provide normalized input or to normalized the resulting quaternion.
86 ///
87 /// # Panics
88 ///
89 /// Panics if `slice` length is less than 4.
90 #[inline(always)]
91 pub fn from_slice(slice: &[$t]) -> Self {
92 Self(Vector4::from_slice_unaligned(slice))
93 }
94
95 /// Writes the quaternion to an unaligned slice.
96 ///
97 /// # Panics
98 ///
99 /// Panics if `slice` length is less than 4.
100 #[inline(always)]
101 pub fn write_to_slice(self, slice: &mut [$t]) {
102 Vector4::write_to_slice_unaligned(self.0, slice)
103 }
104
105 /// Create a quaternion for a normalized rotation `axis` and `angle` (in radians).
106 /// The axis must be normalized (unit-length).
107 ///
108 /// # Panics
109 ///
110 /// Will panic if `axis` is not normalized when `glam_assert` is enabled.
111 #[inline(always)]
112 pub fn from_axis_angle(axis: $vec3, angle: $t) -> Self {
113 Self($inner::from_axis_angle(axis.0, angle))
114 }
115
116 /// Create a quaternion that rotates `v.length()` radians around `v.normalize()`.
117 ///
118 /// `from_scaled_axis(Vec3::ZERO)` results in the identity quaternion.
119 #[inline(always)]
120 pub fn from_scaled_axis(v: $vec3) -> Self {
121 // Self($inner::from_scaled_axis(v.0))
122 let length = v.length();
123 if length == 0.0 {
124 Self::IDENTITY
125 } else {
126 Self::from_axis_angle(v / length, length)
127 }
128 }
129
130 /// Creates a quaternion from the `angle` (in radians) around the x axis.
131 #[inline(always)]
132 pub fn from_rotation_x(angle: $t) -> Self {
133 Self($inner::from_rotation_x(angle))
134 }
135
136 /// Creates a quaternion from the `angle` (in radians) around the y axis.
137 #[inline(always)]
138 pub fn from_rotation_y(angle: $t) -> Self {
139 Self($inner::from_rotation_y(angle))
140 }
141
142 /// Creates a quaternion from the `angle` (in radians) around the z axis.
143 #[inline(always)]
144 pub fn from_rotation_z(angle: $t) -> Self {
145 Self($inner::from_rotation_z(angle))
146 }
147
148 #[inline(always)]
149 /// Creates a quaternion from the given euler rotation sequence and the angles (in radians).
150 pub fn from_euler(euler: EulerRot, a: $t, b: $t, c: $t) -> Self {
151 euler.new_quat(a, b, c)
152 }
153
154 /// Creates a quaternion from a 3x3 rotation matrix.
155 #[inline]
156 pub fn from_mat3(mat: &$mat3) -> Self {
157 Self(Quaternion::from_rotation_axes(
158 mat.x_axis.0,
159 mat.y_axis.0,
160 mat.z_axis.0,
161 ))
162 }
163
164 /// Creates a quaternion from a 3x3 rotation matrix inside a homogeneous 4x4 matrix.
165 #[inline]
166 pub fn from_mat4(mat: &$mat4) -> Self {
167 Self(Quaternion::from_rotation_axes(
168 mat.x_axis.0.into(),
169 mat.y_axis.0.into(),
170 mat.z_axis.0.into(),
171 ))
172 }
173
174 /// Gets the minimal rotation for transforming `from` to `to`. The rotation is in the
175 /// plane spanned by the two vectors. Will rotate at most 180 degrees.
176 ///
177 /// The input vectors must be normalized (unit-length).
178 ///
179 /// `from_rotation_arc(from, to) * from ≈ to`.
180 ///
181 /// For near-singular cases (from≈to and from≈-to) the current implementation
182 /// is only accurate to about 0.001 (for `f32`).
183 ///
184 /// # Panics
185 ///
186 /// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
187 pub fn from_rotation_arc(from: $vec3, to: $vec3) -> Self {
188 glam_assert!(from.is_normalized());
189 glam_assert!(to.is_normalized());
190
191 const ONE_MINUS_EPS: $t = 1.0 - 2.0 * core::$t::EPSILON;
192 let dot = from.dot(to);
193 if dot > ONE_MINUS_EPS {
194 // 0° singulary: from ≈ to
195 Self::IDENTITY
196 } else if dot < -ONE_MINUS_EPS {
197 // 180° singulary: from ≈ -to
198 use core::$t::consts::PI; // half a turn = 𝛕/2 = 180°
199 Self::from_axis_angle(from.any_orthonormal_vector(), PI)
200 } else {
201 let c = from.cross(to);
202 Self::from_xyzw(c.x, c.y, c.z, 1.0 + dot).normalize()
203 }
204 }
205
206 /// Gets the minimal rotation for transforming `from` to either `to` or `-to`. This means
207 /// that the resulting quaternion will rotate `from` so that it is colinear with `to`.
208 ///
209 /// The rotation is in the plane spanned by the two vectors. Will rotate at most 90
210 /// degrees.
211 ///
212 /// The input vectors must be normalized (unit-length).
213 ///
214 /// `to.dot(from_rotation_arc_colinear(from, to) * from).abs() ≈ 1`.
215 ///
216 /// # Panics
217 ///
218 /// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
219 pub fn from_rotation_arc_colinear(from: $vec3, to: $vec3) -> Self {
220 if from.dot(to) < 0.0 {
221 Self::from_rotation_arc(from, -to)
222 } else {
223 Self::from_rotation_arc(from, to)
224 }
225 }
226
227 /// Gets the minimal rotation for transforming `from` to `to`. The resulting rotation is
228 /// around the z axis. Will rotate at most 180 degrees.
229 ///
230 /// The input vectors must be normalized (unit-length).
231 ///
232 /// `from_rotation_arc_2d(from, to) * from ≈ to`.
233 ///
234 /// For near-singular cases (from≈to and from≈-to) the current implementation
235 /// is only accurate to about 0.001 (for `f32`).
236 ///
237 /// # Panics
238 ///
239 /// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
240 pub fn from_rotation_arc_2d(from: $vec2, to: $vec2) -> Self {
241 glam_assert!(from.is_normalized());
242 glam_assert!(to.is_normalized());
243
244 const ONE_MINUS_EPSILON: $t = 1.0 - 2.0 * core::$t::EPSILON;
245 let dot = from.dot(to);
246 if dot > ONE_MINUS_EPSILON {
247 // 0° singulary: from ≈ to
248 Self::IDENTITY
249 } else if dot < -ONE_MINUS_EPSILON {
250 // 180° singulary: from ≈ -to
251 const COS_FRAC_PI_2: $t = 0.0;
252 const SIN_FRAC_PI_2: $t = 1.0;
253 // rotation around z by PI radians
254 Self::from_xyzw(0.0, 0.0, SIN_FRAC_PI_2, COS_FRAC_PI_2)
255 } else {
256 // vector3 cross where z=0
257 let z = from.x * to.y - to.x * from.y;
258 let w = 1.0 + dot;
259 // calculate length with x=0 and y=0 to normalize
260 let len_rcp = 1.0 / (z * z + w * w).sqrt();
261 Self::from_xyzw(0.0, 0.0, z * len_rcp, w * len_rcp)
262 }
263 }
264
265 /// Returns the rotation axis and angle (in radians) of `self`.
266 #[inline(always)]
267 pub fn to_axis_angle(self) -> ($vec3, $t) {
268 let (axis, angle) = self.0.to_axis_angle();
269 ($vec3(axis), angle)
270 }
271
272 /// Returns the rotation axis scaled by the rotation in radians.
273 #[inline(always)]
274 pub fn to_scaled_axis(self) -> $vec3 {
275 let (axis, angle) = self.0.to_axis_angle();
276 $vec3(axis) * angle
277 }
278
279 /// Returns the rotation angles for the given euler rotation sequence.
280 #[inline(always)]
281 pub fn to_euler(self, euler: EulerRot) -> ($t, $t, $t) {
282 euler.convert_quat(self)
283 }
284
285 /// `[x, y, z, w]`
286 #[inline(always)]
287 pub fn to_array(&self) -> [$t; 4] {
288 [self.x, self.y, self.z, self.w]
289 }
290
291 /// Returns the vector part of the quaternion.
292 #[inline(always)]
293 pub fn xyz(self) -> $vec3 {
294 $vec3::new(self.x, self.y, self.z)
295 }
296
297 /// Returns the quaternion conjugate of `self`. For a unit quaternion the
298 /// conjugate is also the inverse.
299 #[must_use]
300 #[inline(always)]
301 pub fn conjugate(self) -> Self {
302 Self(self.0.conjugate())
303 }
304
305 /// Returns the inverse of a normalized quaternion.
306 ///
307 /// Typically quaternion inverse returns the conjugate of a normalized quaternion.
308 /// Because `self` is assumed to already be unit length this method *does not* normalize
309 /// before returning the conjugate.
310 ///
311 /// # Panics
312 ///
313 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
314 #[must_use]
315 #[inline(always)]
316 pub fn inverse(self) -> Self {
317 glam_assert!(self.is_normalized());
318 self.conjugate()
319 }
320
321 /// Computes the dot product of `self` and `other`. The dot product is
322 /// equal to the the cosine of the angle between two quaternion rotations.
323 #[inline(always)]
324 pub fn dot(self, other: Self) -> $t {
325 Vector4::dot(self.0, other.0)
326 }
327
328 /// Computes the length of `self`.
329 #[doc(alias = "magnitude")]
330 #[inline(always)]
331 pub fn length(self) -> $t {
332 FloatVector4::length(self.0)
333 }
334
335 /// Computes the squared length of `self`.
336 ///
337 /// This is generally faster than `length()` as it avoids a square
338 /// root operation.
339 #[doc(alias = "magnitude2")]
340 #[inline(always)]
341 pub fn length_squared(self) -> $t {
342 FloatVector4::length_squared(self.0)
343 }
344
345 /// Computes `1.0 / length()`.
346 ///
347 /// For valid results, `self` must _not_ be of length zero.
348 #[inline(always)]
349 pub fn length_recip(self) -> $t {
350 FloatVector4::length_recip(self.0)
351 }
352
353 /// Returns `self` normalized to length 1.0.
354 ///
355 /// For valid results, `self` must _not_ be of length zero.
356 ///
357 /// Panics
358 ///
359 /// Will panic if `self` is zero length when `glam_assert` is enabled.
360 #[must_use]
361 #[inline(always)]
362 pub fn normalize(self) -> Self {
363 Self(FloatVector4::normalize(self.0))
364 }
365
366 /// Returns `true` if, and only if, all elements are finite.
367 /// If any element is either `NaN`, positive or negative infinity, this will return `false`.
368 #[inline(always)]
369 pub fn is_finite(self) -> bool {
370 FloatVector4::is_finite(self.0)
371 }
372
373 #[inline(always)]
374 pub fn is_nan(self) -> bool {
375 FloatVector4::is_nan(self.0)
376 }
377
378 /// Returns whether `self` of length `1.0` or not.
379 ///
380 /// Uses a precision threshold of `1e-6`.
381 #[inline(always)]
382 pub fn is_normalized(self) -> bool {
383 FloatVector4::is_normalized(self.0)
384 }
385
386 #[inline(always)]
387 pub fn is_near_identity(self) -> bool {
388 self.0.is_near_identity()
389 }
390
391 /// Returns the angle (in radians) for the minimal rotation
392 /// for transforming this quaternion into another.
393 ///
394 /// Both quaternions must be normalized.
395 ///
396 /// # Panics
397 ///
398 /// Will panic if `self` or `other` are not normalized when `glam_assert` is enabled.
399 pub fn angle_between(self, other: Self) -> $t {
400 glam_assert!(self.is_normalized() && other.is_normalized());
401 use crate::core::traits::scalar::FloatEx;
402 self.dot(other).abs().acos_approx() * 2.0
403 }
404
405 /// Returns true if the absolute difference of all elements between `self` and `other`
406 /// is less than or equal to `max_abs_diff`.
407 ///
408 /// This can be used to compare if two quaternions contain similar elements. It works
409 /// best when comparing with a known value. The `max_abs_diff` that should be used used
410 /// depends on the values being compared against.
411 ///
412 /// For more see
413 /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
414 #[inline(always)]
415 pub fn abs_diff_eq(self, other: Self, max_abs_diff: $t) -> bool {
416 FloatVector4::abs_diff_eq(self.0, other.0, max_abs_diff)
417 }
418
419 /// Performs a linear interpolation between `self` and `other` based on
420 /// the value `s`.
421 ///
422 /// When `s` is `0.0`, the result will be equal to `self`. When `s`
423 /// is `1.0`, the result will be equal to `other`.
424 ///
425 /// # Panics
426 ///
427 /// Will panic if `self` or `end` are not normalized when `glam_assert` is enabled.
428 #[inline(always)]
429 #[doc(alias = "mix")]
430 pub fn lerp(self, end: Self, s: $t) -> Self {
431 Self(self.0.lerp(end.0, s))
432 }
433
434 /// Performs a spherical linear interpolation between `self` and `end`
435 /// based on the value `s`.
436 ///
437 /// When `s` is `0.0`, the result will be equal to `self`. When `s`
438 /// is `1.0`, the result will be equal to `end`.
439 ///
440 /// # Panics
441 ///
442 /// Will panic if `self` or `end` are not normalized when `glam_assert` is enabled.
443 #[inline(always)]
444 pub fn slerp(self, end: Self, s: $t) -> Self {
445 Self(self.0.slerp(end.0, s))
446 }
447
448 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
449 ///
450 /// # Panics
451 ///
452 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
453 #[inline(always)]
454 pub fn mul_vec3(self, other: $vec3) -> $vec3 {
455 $vec3(self.0.mul_vector3(other.0))
456 }
457
458 /// Multiplies two quaternions. If they each represent a rotation, the result will
459 /// represent the combined rotation.
460 ///
461 /// Note that due to floating point rounding the result may not be perfectly normalized.
462 ///
463 /// # Panics
464 ///
465 /// Will panic if `self` or `other` are not normalized when `glam_assert` is enabled.
466 #[inline(always)]
467 pub fn mul_quat(self, other: Self) -> Self {
468 Self(self.0.mul_quaternion(other.0))
469 }
470 };
471 }
472
473 macro_rules! impl_quat_traits {
474 ($t:ty, $new:ident, $quat:ident, $vec3:ident, $vec4:ident, $inner:ident) => {
475 /// Creates a quaternion from `x`, `y`, `z` and `w` values.
476 ///
477 /// This should generally not be called manually unless you know what you are doing. Use
478 /// one of the other constructors instead such as `identity` or `from_axis_angle`.
479 #[inline]
480 pub fn $new(x: $t, y: $t, z: $t, w: $t) -> $quat {
481 $quat::from_xyzw(x, y, z, w)
482 }
483
484 #[cfg(not(target_arch = "spirv"))]
485 impl fmt::Debug for $quat {
486 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
487 fmt.debug_tuple(stringify!($quat))
488 .field(&self.x)
489 .field(&self.y)
490 .field(&self.z)
491 .field(&self.w)
492 .finish()
493 }
494 }
495
496 #[cfg(not(target_arch = "spirv"))]
497 impl fmt::Display for $quat {
498 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
499 write!(fmt, "[{}, {}, {}, {}]", self.x, self.y, self.z, self.w)
500 }
501 }
502
503 impl Add<$quat> for $quat {
504 type Output = Self;
505 /// Adds two quaternions.
506 ///
507 /// The sum is not guaranteed to be normalized.
508 ///
509 /// Note that addition is not the same as combining the rotations represented by the
510 /// two quaternions! That corresponds to multiplication.
511 #[inline]
512 fn add(self, other: Self) -> Self {
513 Self(self.0.add(other.0))
514 }
515 }
516
517 impl Sub<$quat> for $quat {
518 type Output = Self;
519 /// Subtracts the other quaternion from self.
520 ///
521 /// The difference is not guaranteed to be normalized.
522 #[inline]
523 fn sub(self, other: Self) -> Self {
524 Self(self.0.sub(other.0))
525 }
526 }
527
528 impl Mul<$t> for $quat {
529 type Output = Self;
530 /// Multiplies a quaternion by a scalar value.
531 ///
532 /// The product is not guaranteed to be normalized.
533 #[inline]
534 fn mul(self, other: $t) -> Self {
535 Self(self.0.scale(other))
536 }
537 }
538
539 impl Div<$t> for $quat {
540 type Output = Self;
541 /// Divides a quaternion by a scalar value.
542 /// The quotient is not guaranteed to be normalized.
543 #[inline]
544 fn div(self, other: $t) -> Self {
545 Self(self.0.scale(other.recip()))
546 }
547 }
548
549 impl Mul<$quat> for $quat {
550 type Output = Self;
551 /// Multiplies two quaternions. If they each represent a rotation, the result will
552 /// represent the combined rotation.
553 ///
554 /// Note that due to floating point rounding the result may not be perfectly
555 /// normalized.
556 ///
557 /// # Panics
558 ///
559 /// Will panic if `self` or `other` are not normalized when `glam_assert` is enabled.
560 #[inline]
561 fn mul(self, other: Self) -> Self {
562 Self(self.0.mul_quaternion(other.0))
563 }
564 }
565
566 impl MulAssign<$quat> for $quat {
567 /// Multiplies two quaternions. If they each represent a rotation, the result will
568 /// represent the combined rotation.
569 ///
570 /// Note that due to floating point rounding the result may not be perfectly
571 /// normalized.
572 ///
573 /// # Panics
574 ///
575 /// Will panic if `self` or `other` are not normalized when `glam_assert` is enabled.
576 #[inline]
577 fn mul_assign(&mut self, other: Self) {
578 self.0 = self.0.mul_quaternion(other.0);
579 }
580 }
581
582 impl Mul<$vec3> for $quat {
583 type Output = $vec3;
584 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
585 ///
586 /// # Panics
587 ///
588 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
589 #[inline]
590 fn mul(self, other: $vec3) -> Self::Output {
591 $vec3(self.0.mul_vector3(other.0))
592 }
593 }
594
595 impl Neg for $quat {
596 type Output = Self;
597 #[inline]
598 fn neg(self) -> Self {
599 Self(self.0.scale(-1.0))
600 }
601 }
602
603 impl Default for $quat {
604 #[inline]
605 fn default() -> Self {
606 Self::IDENTITY
607 }
608 }
609
610 impl PartialEq for $quat {
611 #[inline]
612 fn eq(&self, other: &Self) -> bool {
613 MaskVector4::all(self.0.cmpeq(other.0))
614 }
615 }
616
617 #[cfg(not(target_arch = "spirv"))]
618 impl AsRef<[$t; 4]> for $quat {
619 #[inline(always)]
620 fn as_ref(&self) -> &[$t; 4] {
621 unsafe { &*(self as *const Self as *const [$t; 4]) }
622 }
623 }
624
625 #[cfg(not(target_arch = "spirv"))]
626 impl AsMut<[$t; 4]> for $quat {
627 #[inline(always)]
628 fn as_mut(&mut self) -> &mut [$t; 4] {
629 unsafe { &mut *(self as *mut Self as *mut [$t; 4]) }
630 }
631 }
632
633 impl From<$quat> for $vec4 {
634 #[inline(always)]
635 fn from(q: $quat) -> Self {
636 $vec4(q.0)
637 }
638 }
639
640 impl From<$quat> for ($t, $t, $t, $t) {
641 #[inline(always)]
642 fn from(q: $quat) -> Self {
643 Vector4::into_tuple(q.0)
644 }
645 }
646
647 impl From<$quat> for [$t; 4] {
648 #[inline(always)]
649 fn from(q: $quat) -> Self {
650 Vector4::into_array(q.0)
651 }
652 }
653
654 impl From<$quat> for $inner {
655 // TODO: write test
656 #[inline(always)]
657 fn from(q: $quat) -> Self {
658 q.0
659 }
660 }
661
662 impl Deref for $quat {
663 type Target = crate::XYZW<$t>;
664 #[inline(always)]
665 fn deref(&self) -> &Self::Target {
666 self.0.as_ref_xyzw()
667 }
668 }
669
670 impl<'a> Sum<&'a Self> for $quat {
671 fn sum<I>(iter: I) -> Self
672 where
673 I: Iterator<Item = &'a Self>,
674 {
675 use crate::core::traits::vector::VectorConst;
676 iter.fold(Self($inner::ZERO), |a, &b| Self::add(a, b))
677 }
678 }
679
680 impl<'a> Product<&'a Self> for $quat {
681 fn product<I>(iter: I) -> Self
682 where
683 I: Iterator<Item = &'a Self>,
684 {
685 iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
686 }
687 }
688 };
689 }
690
691 #[cfg(all(target_feature = "sse2", not(feature = "scalar-math")))]
692 type InnerF32 = __m128;
693
694 #[cfg(all(target_feature = "simd128", not(feature = "scalar-math")))]
695 type InnerF32 = v128;
696
697 #[cfg(any(
698 not(any(target_feature = "sse2", target_feature = "simd128")),
699 feature = "scalar-math"
700 ))]
701 type InnerF32 = crate::XYZW<f32>;
702
703 /// A quaternion representing an orientation.
704 ///
705 /// This quaternion is intended to be of unit length but may denormalize due to
706 /// floating point "error creep" which can occur when successive quaternion
707 /// operations are applied.
708 ///
709 /// This type is 16 byte aligned.
710 #[derive(Clone, Copy)]
711 #[cfg_attr(
712 not(any(
713 feature = "scalar-math",
714 target_arch = "spirv",
715 target_feature = "sse2",
716 target_feature = "simd128"
717 )),
718 repr(C, align(16))
719 )]
720 #[cfg_attr(
721 any(
722 feature = "scalar-math",
723 target_arch = "spirv",
724 target_feature = "sse2",
725 target_feature = "simd128"
726 ),
727 repr(transparent)
728 )]
729 pub struct Quat(pub(crate) InnerF32);
730
731 impl Quat {
732 impl_quat_methods!(f32, Quat, Vec2, Vec3, Vec4, Mat3, Mat4, InnerF32);
733
734 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
735 #[inline(always)]
736 pub fn mul_vec3a(self, other: Vec3A) -> Vec3A {
737 #[allow(clippy::useless_conversion)]
738 Vec3A(self.0.mul_float4_as_vector3(other.0.into()).into())
739 }
740
741 #[inline(always)]
742 pub fn as_f64(self) -> DQuat {
743 DQuat::from_xyzw(self.x as f64, self.y as f64, self.z as f64, self.w as f64)
744 }
745
746 /// Creates a quaternion from a 3x3 rotation matrix inside a 3D affine transform.
747 #[inline]
748 pub fn from_affine3(mat: &crate::Affine3A) -> Self {
749 Self(Quaternion::from_rotation_axes(
750 mat.x_axis.0.into(),
751 mat.y_axis.0.into(),
752 mat.z_axis.0.into(),
753 ))
754 }
755 }
756 impl_quat_traits!(f32, quat, Quat, Vec3, Vec4, InnerF32);
757
758 impl Mul<Vec3A> for Quat {
759 type Output = Vec3A;
760 #[inline(always)]
761 fn mul(self, other: Vec3A) -> Self::Output {
762 self.mul_vec3a(other)
763 }
764 }
765
766 type InnerF64 = crate::XYZW<f64>;
767
768 /// A quaternion representing an orientation.
769 ///
770 /// This quaternion is intended to be of unit length but may denormalize due to
771 /// floating point "error creep" which can occur when successive quaternion
772 /// operations are applied.
773 #[derive(Clone, Copy)]
774 #[repr(transparent)]
775 pub struct DQuat(pub(crate) InnerF64);
776
777 impl DQuat {
778 impl_quat_methods!(f64, DQuat, DVec2, DVec3, DVec4, DMat3, DMat4, InnerF64);
779
780 #[inline(always)]
781 pub fn as_f32(self) -> Quat {
782 Quat::from_xyzw(self.x as f32, self.y as f32, self.z as f32, self.w as f32)
783 }
784
785 /// Creates a quaternion from a 3x3 rotation matrix inside a 3D affine transform.
786 #[inline]
787 pub fn from_affine3(mat: &crate::DAffine3) -> Self {
788 Self(Quaternion::from_rotation_axes(
789 mat.x_axis.0,
790 mat.y_axis.0,
791 mat.z_axis.0,
792 ))
793 }
794 }
795 impl_quat_traits!(f64, dquat, DQuat, DVec3, DVec4, InnerF64);
796
797 #[cfg(any(feature = "scalar-math", target_arch = "spirv"))]
798 mod const_test_quat {
799 const_assert_eq!(
800 core::mem::align_of::<f32>(),
801 core::mem::align_of::<super::Quat>()
802 );
803 const_assert_eq!(16, core::mem::size_of::<super::Quat>());
804 }
805
806 #[cfg(not(any(feature = "scalar-math", target_arch = "spirv")))]
807 mod const_test_quat {
808 const_assert_eq!(16, core::mem::align_of::<super::Quat>());
809 const_assert_eq!(16, core::mem::size_of::<super::Quat>());
810 }
811
812 mod const_test_dquat {
813 const_assert_eq!(
814 core::mem::align_of::<f64>(),
815 core::mem::align_of::<super::DQuat>()
816 );
817 const_assert_eq!(32, core::mem::size_of::<super::DQuat>());
818 }