Debian Codegraph @

debian/missing-sources/glam-0.21.3/src/f32/wasm32/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 wasm32::*,
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::arch::wasm32::*;
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) v128);
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(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::from_xyzw(a[0], a[1], a[2], a[3])
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: v128 = v128_from_f32x4([-1.0, -1.0, -1.0, 1.0]);
387 Self(f32x4_mul(self.0, 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: v128 = v128_from_f32x4([-0.0; 4]);
536 let start = self.0;
537 let end = end.0;
538 let dot = dot4_into_v128(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 = v128_and(dot, NEG_ZERO);
542 let interpolated = f32x4_add(
543 f32x4_mul(f32x4_sub(v128_xor(end, bias), start), f32x4_splat(s)),
544 start,
545 );
546 Quat(interpolated).normalize()
547 }
548
549 /// Performs a spherical linear interpolation between `self` and `end`
550 /// based on the value `s`.
551 ///
552 /// When `s` is `0.0`, the result will be equal to `self`. When `s`
553 /// is `1.0`, the result will be equal to `end`.
554 ///
555 /// # Panics
556 ///
557 /// Will panic if `self` or `end` are not normalized when `glam_assert` is enabled.
558 #[inline]
559 pub fn slerp(self, mut end: Self, s: f32) -> Self {
560 // http://number-none.com/product/Understanding%20Slerp,%20Then%20Not%20Using%20It/
561 glam_assert!(self.is_normalized());
562 glam_assert!(end.is_normalized());
563
564 const DOT_THRESHOLD: f32 = 0.9995;
565
566 // Note that a rotation can be represented by two quaternions: `q` and
567 // `-q`. The slerp path between `q` and `end` will be different from the
568 // path between `-q` and `end`. One path will take the long way around and
569 // one will take the short way. In order to correct for this, the `dot`
570 // product between `self` and `end` should be positive. If the `dot`
571 // product is negative, slerp between `self` and `-end`.
572 let mut dot = self.dot(end);
573 if dot < 0.0 {
574 end = -end;
575 dot = -dot;
576 }
577
578 if dot > DOT_THRESHOLD {
579 // assumes lerp returns a normalized quaternion
580 self.lerp(end, s)
581 } else {
582 let theta = dot.acos_approx();
583
584 // TODO: v128_sin is broken
585 // let x = 1.0 - s;
586 // let y = s;
587 // let z = 1.0;
588 // let w = 0.0;
589 // let tmp = f32x4_mul(f32x4_splat(theta), f32x4(x, y, z, w));
590 // let tmp = v128_sin(tmp);
591 let x = (theta * (1.0 - s)).sin();
592 let y = (theta * s).sin();
593 let z = theta.sin();
594 let w = 0.0;
595 let tmp = f32x4(x, y, z, w);
596
597 let scale1 = i32x4_shuffle::<0, 0, 4, 4>(tmp, tmp);
598 let scale2 = i32x4_shuffle::<1, 1, 5, 5>(tmp, tmp);
599 let theta_sin = i32x4_shuffle::<2, 2, 6, 6>(tmp, tmp);
600
601 Self(f32x4_div(
602 f32x4_add(f32x4_mul(self.0, scale1), f32x4_mul(end.0, scale2)),
603 theta_sin,
604 ))
605 }
606 }
607
608 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
609 ///
610 /// # Panics
611 ///
612 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
613 #[inline]
614 pub fn mul_vec3(self, rhs: Vec3) -> Vec3 {
615 glam_assert!(self.is_normalized());
616
617 self.mul_vec3a(rhs.into()).into()
618 }
619
620 /// Multiplies two quaternions. If they each represent a rotation, the result will
621 /// represent the combined rotation.
622 ///
623 /// Note that due to floating point rounding the result may not be perfectly normalized.
624 ///
625 /// # Panics
626 ///
627 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
628 #[inline]
629 pub fn mul_quat(self, rhs: Self) -> Self {
630 glam_assert!(self.is_normalized());
631 glam_assert!(rhs.is_normalized());
632
633 let lhs = self.0;
634 let rhs = rhs.0;
635
636 const CONTROL_WZYX: v128 = v128_from_f32x4([1.0, -1.0, 1.0, -1.0]);
637 const CONTROL_ZWXY: v128 = v128_from_f32x4([1.0, 1.0, -1.0, -1.0]);
638 const CONTROL_YXWZ: v128 = v128_from_f32x4([-1.0, 1.0, 1.0, -1.0]);
639
640 let r_xxxx = i32x4_shuffle::<0, 0, 4, 4>(lhs, lhs);
641 let r_yyyy = i32x4_shuffle::<1, 1, 5, 5>(lhs, lhs);
642 let r_zzzz = i32x4_shuffle::<2, 2, 6, 6>(lhs, lhs);
643 let r_wwww = i32x4_shuffle::<3, 3, 7, 7>(lhs, lhs);
644
645 let lxrw_lyrw_lzrw_lwrw = f32x4_mul(r_wwww, rhs);
646 let l_wzyx = i32x4_shuffle::<3, 2, 5, 4>(rhs, rhs);
647
648 let lwrx_lzrx_lyrx_lxrx = f32x4_mul(r_xxxx, l_wzyx);
649 let l_zwxy = i32x4_shuffle::<1, 0, 7, 6>(l_wzyx, l_wzyx);
650
651 let lwrx_nlzrx_lyrx_nlxrx = f32x4_mul(lwrx_lzrx_lyrx_lxrx, CONTROL_WZYX);
652
653 let lzry_lwry_lxry_lyry = f32x4_mul(r_yyyy, l_zwxy);
654 let l_yxwz = i32x4_shuffle::<3, 2, 5, 4>(l_zwxy, l_zwxy);
655
656 let lzry_lwry_nlxry_nlyry = f32x4_mul(lzry_lwry_lxry_lyry, CONTROL_ZWXY);
657
658 let lyrz_lxrz_lwrz_lzrz = f32x4_mul(r_zzzz, l_yxwz);
659 let result0 = f32x4_add(lxrw_lyrw_lzrw_lwrw, lwrx_nlzrx_lyrx_nlxrx);
660
661 let nlyrz_lxrz_lwrz_wlzrz = f32x4_mul(lyrz_lxrz_lwrz_lzrz, CONTROL_YXWZ);
662 let result1 = f32x4_add(lzry_lwry_nlxry_nlyry, nlyrz_lxrz_lwrz_wlzrz);
663
664 Self(f32x4_add(result0, result1))
665 }
666
667 /// Creates a quaternion from a 3x3 rotation matrix inside a 3D affine transform.
668 #[inline]
669 pub fn from_affine3(a: &crate::Affine3A) -> Self {
670 #[allow(clippy::useless_conversion)]
671 Self::from_rotation_axes(
672 a.matrix3.x_axis.into(),
673 a.matrix3.y_axis.into(),
674 a.matrix3.z_axis.into(),
675 )
676 }
677
678 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
679 #[inline]
680 pub fn mul_vec3a(self, rhs: Vec3A) -> Vec3A {
681 const TWO: v128 = v128_from_f32x4([2.0; 4]);
682 let w = i32x4_shuffle::<3, 3, 7, 7>(self.0, self.0);
683 let b = self.0;
684 let b2 = dot3_into_v128(b, b);
685 Vec3A(f32x4_add(
686 f32x4_add(
687 f32x4_mul(rhs.0, f32x4_sub(f32x4_mul(w, w), b2)),
688 f32x4_mul(b, f32x4_mul(dot3_into_v128(rhs.0, b), TWO)),
689 ),
690 f32x4_mul(Vec3A(b).cross(rhs).into(), f32x4_mul(w, TWO)),
691 ))
692 }
693
694 #[inline]
695 pub fn as_f64(self) -> DQuat {
696 DQuat::from_xyzw(self.x as f64, self.y as f64, self.z as f64, self.w as f64)
697 }
698 }
699
700 #[cfg(not(target_arch = "spirv"))]
701 impl fmt::Debug for Quat {
702 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
703 fmt.debug_tuple(stringify!(Quat))
704 .field(&self.x)
705 .field(&self.y)
706 .field(&self.z)
707 .field(&self.w)
708 .finish()
709 }
710 }
711
712 #[cfg(not(target_arch = "spirv"))]
713 impl fmt::Display for Quat {
714 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
715 write!(fmt, "[{}, {}, {}, {}]", self.x, self.y, self.z, self.w)
716 }
717 }
718
719 impl Add<Quat> for Quat {
720 type Output = Self;
721 /// Adds two quaternions.
722 ///
723 /// The sum is not guaranteed to be normalized.
724 ///
725 /// Note that addition is not the same as combining the rotations represented by the
726 /// two quaternions! That corresponds to multiplication.
727 #[inline]
728 fn add(self, rhs: Self) -> Self {
729 Self::from_vec4(Vec4::from(self) + Vec4::from(rhs))
730 }
731 }
732
733 impl Sub<Quat> for Quat {
734 type Output = Self;
735 /// Subtracts the `rhs` quaternion from `self`.
736 ///
737 /// The difference is not guaranteed to be normalized.
738 #[inline]
739 fn sub(self, rhs: Self) -> Self {
740 Self::from_vec4(Vec4::from(self) - Vec4::from(rhs))
741 }
742 }
743
744 impl Mul<f32> for Quat {
745 type Output = Self;
746 /// Multiplies a quaternion by a scalar value.
747 ///
748 /// The product is not guaranteed to be normalized.
749 #[inline]
750 fn mul(self, rhs: f32) -> Self {
751 Self::from_vec4(Vec4::from(self) * rhs)
752 }
753 }
754
755 impl Div<f32> for Quat {
756 type Output = Self;
757 /// Divides a quaternion by a scalar value.
758 /// The quotient is not guaranteed to be normalized.
759 #[inline]
760 fn div(self, rhs: f32) -> Self {
761 Self::from_vec4(Vec4::from(self) / rhs)
762 }
763 }
764
765 impl Mul<Quat> for Quat {
766 type Output = Self;
767 /// Multiplies two quaternions. If they each represent a rotation, the result will
768 /// represent the combined rotation.
769 ///
770 /// Note that due to floating point rounding the result may not be perfectly
771 /// normalized.
772 ///
773 /// # Panics
774 ///
775 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
776 #[inline]
777 fn mul(self, rhs: Self) -> Self {
778 self.mul_quat(rhs)
779 }
780 }
781
782 impl MulAssign<Quat> for Quat {
783 /// Multiplies two quaternions. If they each represent a rotation, the result will
784 /// represent the combined rotation.
785 ///
786 /// Note that due to floating point rounding the result may not be perfectly
787 /// normalized.
788 ///
789 /// # Panics
790 ///
791 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
792 #[inline]
793 fn mul_assign(&mut self, rhs: Self) {
794 *self = self.mul_quat(rhs);
795 }
796 }
797
798 impl Mul<Vec3> for Quat {
799 type Output = Vec3;
800 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
801 ///
802 /// # Panics
803 ///
804 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
805 #[inline]
806 fn mul(self, rhs: Vec3) -> Self::Output {
807 self.mul_vec3(rhs)
808 }
809 }
810
811 impl Neg for Quat {
812 type Output = Self;
813 #[inline]
814 fn neg(self) -> Self {
815 self * -1.0
816 }
817 }
818
819 impl Default for Quat {
820 #[inline]
821 fn default() -> Self {
822 Self::IDENTITY
823 }
824 }
825
826 impl PartialEq for Quat {
827 #[inline]
828 fn eq(&self, rhs: &Self) -> bool {
829 Vec4::from(*self).eq(&Vec4::from(*rhs))
830 }
831 }
832
833 #[cfg(not(target_arch = "spirv"))]
834 impl AsRef<[f32; 4]> for Quat {
835 #[inline]
836 fn as_ref(&self) -> &[f32; 4] {
837 unsafe { &*(self as *const Self as *const [f32; 4]) }
838 }
839 }
840
841 impl<'a> Sum<&'a Self> for Quat {
842 fn sum<I>(iter: I) -> Self
843 where
844 I: Iterator<Item = &'a Self>,
845 {
846 iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
847 }
848 }
849
850 impl<'a> Product<&'a Self> for Quat {
851 fn product<I>(iter: I) -> Self
852 where
853 I: Iterator<Item = &'a Self>,
854 {
855 iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
856 }
857 }
858
859 impl Mul<Vec3A> for Quat {
860 type Output = Vec3A;
861 #[inline]
862 fn mul(self, rhs: Vec3A) -> Self::Output {
863 self.mul_vec3a(rhs)
864 }
865 }
866
867 impl From<Quat> for Vec4 {
868 #[inline]
869 fn from(q: Quat) -> Self {
870 Self(q.0)
871 }
872 }
873
874 impl From<Quat> for (f32, f32, f32, f32) {
875 #[inline]
876 fn from(q: Quat) -> Self {
877 Vec4::from(q).into()
878 }
879 }
880
881 impl From<Quat> for [f32; 4] {
882 #[inline]
883 fn from(q: Quat) -> Self {
884 Vec4::from(q).into()
885 }
886 }
887
888 impl From<Quat> for v128 {
889 #[inline]
890 fn from(q: Quat) -> Self {
891 q.0
892 }
893 }
894
895 impl Deref for Quat {
896 type Target = crate::deref::Vec4<f32>;
897 #[inline]
898 fn deref(&self) -> &Self::Target {
899 unsafe { &*(self as *const Self).cast() }
900 }
901 }
902
903 impl DerefMut for Quat {
904 #[inline]
905 fn deref_mut(&mut self) -> &mut Self::Target {
906 unsafe { &mut *(self as *mut Self).cast() }
907 }
908 }