Debian Codegraph @

debian/missing-sources/glam-0.28.0/src/f32/neon/quat.rs

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