Debian Codegraph @

debian/missing-sources/glam-0.21.3/src/f32/coresimd/quat.rs

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