Debian Codegraph @

debian/missing-sources/glam-0.23.0/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, Mat3A, 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 SIMD aligned rotation matrix.
237 #[inline]
238 pub fn from_mat3a(mat: &Mat3A) -> Self {
239 Self::from_rotation_axes(mat.x_axis.into(), mat.y_axis.into(), mat.z_axis.into())
240 }
241
242 /// Creates a quaternion from a 3x3 rotation matrix inside a homogeneous 4x4 matrix.
243 #[inline]
244 pub fn from_mat4(mat: &Mat4) -> Self {
245 Self::from_rotation_axes(
246 mat.x_axis.truncate(),
247 mat.y_axis.truncate(),
248 mat.z_axis.truncate(),
249 )
250 }
251
252 /// Gets the minimal rotation for transforming `from` to `to`. The rotation is in the
253 /// plane spanned by the two vectors. Will rotate at most 180 degrees.
254 ///
255 /// The input vectors must be normalized (unit-length).
256 ///
257 /// `from_rotation_arc(from, to) * from ≈ to`.
258 ///
259 /// For near-singular cases (from≈to and from≈-to) the current implementation
260 /// is only accurate to about 0.001 (for `f32`).
261 ///
262 /// # Panics
263 ///
264 /// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
265 pub fn from_rotation_arc(from: Vec3, to: Vec3) -> Self {
266 glam_assert!(from.is_normalized());
267 glam_assert!(to.is_normalized());
268
269 const ONE_MINUS_EPS: f32 = 1.0 - 2.0 * core::f32::EPSILON;
270 let dot = from.dot(to);
271 if dot > ONE_MINUS_EPS {
272 // 0° singulary: from ≈ to
273 Self::IDENTITY
274 } else if dot < -ONE_MINUS_EPS {
275 // 180° singulary: from ≈ -to
276 use core::f32::consts::PI; // half a turn = 𝛕/2 = 180°
277 Self::from_axis_angle(from.any_orthonormal_vector(), PI)
278 } else {
279 let c = from.cross(to);
280 Self::from_xyzw(c.x, c.y, c.z, 1.0 + dot).normalize()
281 }
282 }
283
284 /// Gets the minimal rotation for transforming `from` to either `to` or `-to`. This means
285 /// that the resulting quaternion will rotate `from` so that it is colinear with `to`.
286 ///
287 /// The rotation is in the plane spanned by the two vectors. Will rotate at most 90
288 /// degrees.
289 ///
290 /// The input vectors must be normalized (unit-length).
291 ///
292 /// `to.dot(from_rotation_arc_colinear(from, to) * from).abs() ≈ 1`.
293 ///
294 /// # Panics
295 ///
296 /// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
297 #[inline]
298 pub fn from_rotation_arc_colinear(from: Vec3, to: Vec3) -> Self {
299 if from.dot(to) < 0.0 {
300 Self::from_rotation_arc(from, -to)
301 } else {
302 Self::from_rotation_arc(from, to)
303 }
304 }
305
306 /// Gets the minimal rotation for transforming `from` to `to`. The resulting rotation is
307 /// around the z axis. Will rotate at most 180 degrees.
308 ///
309 /// The input vectors must be normalized (unit-length).
310 ///
311 /// `from_rotation_arc_2d(from, to) * from ≈ to`.
312 ///
313 /// For near-singular cases (from≈to and from≈-to) the current implementation
314 /// is only accurate to about 0.001 (for `f32`).
315 ///
316 /// # Panics
317 ///
318 /// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
319 pub fn from_rotation_arc_2d(from: Vec2, to: Vec2) -> Self {
320 glam_assert!(from.is_normalized());
321 glam_assert!(to.is_normalized());
322
323 const ONE_MINUS_EPSILON: f32 = 1.0 - 2.0 * core::f32::EPSILON;
324 let dot = from.dot(to);
325 if dot > ONE_MINUS_EPSILON {
326 // 0° singulary: from ≈ to
327 Self::IDENTITY
328 } else if dot < -ONE_MINUS_EPSILON {
329 // 180° singulary: from ≈ -to
330 const COS_FRAC_PI_2: f32 = 0.0;
331 const SIN_FRAC_PI_2: f32 = 1.0;
332 // rotation around z by PI radians
333 Self::from_xyzw(0.0, 0.0, SIN_FRAC_PI_2, COS_FRAC_PI_2)
334 } else {
335 // vector3 cross where z=0
336 let z = from.x * to.y - to.x * from.y;
337 let w = 1.0 + dot;
338 // calculate length with x=0 and y=0 to normalize
339 let len_rcp = 1.0 / (z * z + w * w).sqrt();
340 Self::from_xyzw(0.0, 0.0, z * len_rcp, w * len_rcp)
341 }
342 }
343
344 /// Returns the rotation axis and angle (in radians) of `self`.
345 #[inline]
346 pub fn to_axis_angle(self) -> (Vec3, f32) {
347 const EPSILON: f32 = 1.0e-8;
348 const EPSILON_SQUARED: f32 = EPSILON * EPSILON;
349 let w = self.w;
350 let angle = w.acos_approx() * 2.0;
351 let scale_sq = f32::max(1.0 - w * w, 0.0);
352 if scale_sq >= EPSILON_SQUARED {
353 (
354 Vec3::new(self.x, self.y, self.z) * scale_sq.sqrt().recip(),
355 angle,
356 )
357 } else {
358 (Vec3::X, angle)
359 }
360 }
361
362 /// Returns the rotation axis scaled by the rotation in radians.
363 #[inline]
364 pub fn to_scaled_axis(self) -> Vec3 {
365 let (axis, angle) = self.to_axis_angle();
366 axis * angle
367 }
368
369 /// Returns the rotation angles for the given euler rotation sequence.
370 #[inline]
371 pub fn to_euler(self, euler: EulerRot) -> (f32, f32, f32) {
372 euler.convert_quat(self)
373 }
374
375 /// `[x, y, z, w]`
376 #[inline]
377 pub fn to_array(&self) -> [f32; 4] {
378 [self.x, self.y, self.z, self.w]
379 }
380
381 /// Returns the vector part of the quaternion.
382 #[inline]
383 pub fn xyz(self) -> Vec3 {
384 Vec3::new(self.x, self.y, self.z)
385 }
386
387 /// Returns the quaternion conjugate of `self`. For a unit quaternion the
388 /// conjugate is also the inverse.
389 #[must_use]
390 #[inline]
391 pub fn conjugate(self) -> Self {
392 const SIGN: v128 = v128_from_f32x4([-1.0, -1.0, -1.0, 1.0]);
393 Self(f32x4_mul(self.0, SIGN))
394 }
395
396 /// Returns the inverse of a normalized quaternion.
397 ///
398 /// Typically quaternion inverse returns the conjugate of a normalized quaternion.
399 /// Because `self` is assumed to already be unit length this method *does not* normalize
400 /// before returning the conjugate.
401 ///
402 /// # Panics
403 ///
404 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
405 #[must_use]
406 #[inline]
407 pub fn inverse(self) -> Self {
408 glam_assert!(self.is_normalized());
409 self.conjugate()
410 }
411
412 /// Computes the dot product of `self` and `rhs`. The dot product is
413 /// equal to the cosine of the angle between two quaternion rotations.
414 #[inline]
415 pub fn dot(self, rhs: Self) -> f32 {
416 Vec4::from(self).dot(Vec4::from(rhs))
417 }
418
419 /// Computes the length of `self`.
420 #[doc(alias = "magnitude")]
421 #[inline]
422 pub fn length(self) -> f32 {
423 Vec4::from(self).length()
424 }
425
426 /// Computes the squared length of `self`.
427 ///
428 /// This is generally faster than `length()` as it avoids a square
429 /// root operation.
430 #[doc(alias = "magnitude2")]
431 #[inline]
432 pub fn length_squared(self) -> f32 {
433 Vec4::from(self).length_squared()
434 }
435
436 /// Computes `1.0 / length()`.
437 ///
438 /// For valid results, `self` must _not_ be of length zero.
439 #[inline]
440 pub fn length_recip(self) -> f32 {
441 Vec4::from(self).length_recip()
442 }
443
444 /// Returns `self` normalized to length 1.0.
445 ///
446 /// For valid results, `self` must _not_ be of length zero.
447 ///
448 /// Panics
449 ///
450 /// Will panic if `self` is zero length when `glam_assert` is enabled.
451 #[must_use]
452 #[inline]
453 pub fn normalize(self) -> Self {
454 Self::from_vec4(Vec4::from(self).normalize())
455 }
456
457 /// Returns `true` if, and only if, all elements are finite.
458 /// If any element is either `NaN`, positive or negative infinity, this will return `false`.
459 #[inline]
460 pub fn is_finite(self) -> bool {
461 Vec4::from(self).is_finite()
462 }
463
464 #[inline]
465 pub fn is_nan(self) -> bool {
466 Vec4::from(self).is_nan()
467 }
468
469 /// Returns whether `self` of length `1.0` or not.
470 ///
471 /// Uses a precision threshold of `1e-6`.
472 #[inline]
473 pub fn is_normalized(self) -> bool {
474 Vec4::from(self).is_normalized()
475 }
476
477 #[inline]
478 pub fn is_near_identity(self) -> bool {
479 // Based on https://github.com/nfrechette/rtm `rtm::quat_near_identity`
480 let threshold_angle = 0.002_847_144_6;
481 // Because of floating point precision, we cannot represent very small rotations.
482 // The closest f32 to 1.0 that is not 1.0 itself yields:
483 // 0.99999994.acos() * 2.0 = 0.000690533954 rad
484 //
485 // An error threshold of 1.e-6 is used by default.
486 // (1.0 - 1.e-6).acos() * 2.0 = 0.00284714461 rad
487 // (1.0 - 1.e-7).acos() * 2.0 = 0.00097656250 rad
488 //
489 // We don't really care about the angle value itself, only if it's close to 0.
490 // This will happen whenever quat.w is close to 1.0.
491 // If the quat.w is close to -1.0, the angle will be near 2*PI which is close to
492 // a negative 0 rotation. By forcing quat.w to be positive, we'll end up with
493 // the shortest path.
494 let positive_w_angle = self.w.abs().acos_approx() * 2.0;
495 positive_w_angle < threshold_angle
496 }
497
498 /// Returns the angle (in radians) for the minimal rotation
499 /// for transforming this quaternion into another.
500 ///
501 /// Both quaternions must be normalized.
502 ///
503 /// # Panics
504 ///
505 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
506 #[inline]
507 pub fn angle_between(self, rhs: Self) -> f32 {
508 glam_assert!(self.is_normalized() && rhs.is_normalized());
509 self.dot(rhs).abs().acos_approx() * 2.0
510 }
511
512 /// Returns true if the absolute difference of all elements between `self` and `rhs`
513 /// is less than or equal to `max_abs_diff`.
514 ///
515 /// This can be used to compare if two quaternions contain similar elements. It works
516 /// best when comparing with a known value. The `max_abs_diff` that should be used used
517 /// depends on the values being compared against.
518 ///
519 /// For more see
520 /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
521 #[inline]
522 pub fn abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool {
523 Vec4::from(self).abs_diff_eq(Vec4::from(rhs), max_abs_diff)
524 }
525
526 /// Performs a linear interpolation between `self` and `rhs` based on
527 /// the value `s`.
528 ///
529 /// When `s` is `0.0`, the result will be equal to `self`. When `s`
530 /// is `1.0`, the result will be equal to `rhs`.
531 ///
532 /// # Panics
533 ///
534 /// Will panic if `self` or `end` are not normalized when `glam_assert` is enabled.
535 #[inline]
536 #[doc(alias = "mix")]
537 pub fn lerp(self, end: Self, s: f32) -> Self {
538 glam_assert!(self.is_normalized());
539 glam_assert!(end.is_normalized());
540
541 const NEG_ZERO: v128 = v128_from_f32x4([-0.0; 4]);
542 let start = self.0;
543 let end = end.0;
544 let dot = dot4_into_v128(start, end);
545 // Calculate the bias, if the dot product is positive or zero, there is no bias
546 // but if it is negative, we want to flip the 'end' rotation XYZW components
547 let bias = v128_and(dot, NEG_ZERO);
548 let interpolated = f32x4_add(
549 f32x4_mul(f32x4_sub(v128_xor(end, bias), start), f32x4_splat(s)),
550 start,
551 );
552 Quat(interpolated).normalize()
553 }
554
555 /// Performs a spherical linear interpolation between `self` and `end`
556 /// based on the value `s`.
557 ///
558 /// When `s` is `0.0`, the result will be equal to `self`. When `s`
559 /// is `1.0`, the result will be equal to `end`.
560 ///
561 /// # Panics
562 ///
563 /// Will panic if `self` or `end` are not normalized when `glam_assert` is enabled.
564 #[inline]
565 pub fn slerp(self, mut end: Self, s: f32) -> Self {
566 // http://number-none.com/product/Understanding%20Slerp,%20Then%20Not%20Using%20It/
567 glam_assert!(self.is_normalized());
568 glam_assert!(end.is_normalized());
569
570 const DOT_THRESHOLD: f32 = 0.9995;
571
572 // Note that a rotation can be represented by two quaternions: `q` and
573 // `-q`. The slerp path between `q` and `end` will be different from the
574 // path between `-q` and `end`. One path will take the long way around and
575 // one will take the short way. In order to correct for this, the `dot`
576 // product between `self` and `end` should be positive. If the `dot`
577 // product is negative, slerp between `self` and `-end`.
578 let mut dot = self.dot(end);
579 if dot < 0.0 {
580 end = -end;
581 dot = -dot;
582 }
583
584 if dot > DOT_THRESHOLD {
585 // assumes lerp returns a normalized quaternion
586 self.lerp(end, s)
587 } else {
588 let theta = dot.acos_approx();
589
590 // TODO: v128_sin is broken
591 // let x = 1.0 - s;
592 // let y = s;
593 // let z = 1.0;
594 // let w = 0.0;
595 // let tmp = f32x4_mul(f32x4_splat(theta), f32x4(x, y, z, w));
596 // let tmp = v128_sin(tmp);
597 let x = (theta * (1.0 - s)).sin();
598 let y = (theta * s).sin();
599 let z = theta.sin();
600 let w = 0.0;
601 let tmp = f32x4(x, y, z, w);
602
603 let scale1 = i32x4_shuffle::<0, 0, 4, 4>(tmp, tmp);
604 let scale2 = i32x4_shuffle::<1, 1, 5, 5>(tmp, tmp);
605 let theta_sin = i32x4_shuffle::<2, 2, 6, 6>(tmp, tmp);
606
607 Self(f32x4_div(
608 f32x4_add(f32x4_mul(self.0, scale1), f32x4_mul(end.0, scale2)),
609 theta_sin,
610 ))
611 }
612 }
613
614 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
615 ///
616 /// # Panics
617 ///
618 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
619 #[inline]
620 pub fn mul_vec3(self, rhs: Vec3) -> Vec3 {
621 glam_assert!(self.is_normalized());
622
623 self.mul_vec3a(rhs.into()).into()
624 }
625
626 /// Multiplies two quaternions. If they each represent a rotation, the result will
627 /// represent the combined rotation.
628 ///
629 /// Note that due to floating point rounding the result may not be perfectly normalized.
630 ///
631 /// # Panics
632 ///
633 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
634 #[inline]
635 pub fn mul_quat(self, rhs: Self) -> Self {
636 glam_assert!(self.is_normalized());
637 glam_assert!(rhs.is_normalized());
638
639 let lhs = self.0;
640 let rhs = rhs.0;
641
642 const CONTROL_WZYX: v128 = v128_from_f32x4([1.0, -1.0, 1.0, -1.0]);
643 const CONTROL_ZWXY: v128 = v128_from_f32x4([1.0, 1.0, -1.0, -1.0]);
644 const CONTROL_YXWZ: v128 = v128_from_f32x4([-1.0, 1.0, 1.0, -1.0]);
645
646 let r_xxxx = i32x4_shuffle::<0, 0, 4, 4>(lhs, lhs);
647 let r_yyyy = i32x4_shuffle::<1, 1, 5, 5>(lhs, lhs);
648 let r_zzzz = i32x4_shuffle::<2, 2, 6, 6>(lhs, lhs);
649 let r_wwww = i32x4_shuffle::<3, 3, 7, 7>(lhs, lhs);
650
651 let lxrw_lyrw_lzrw_lwrw = f32x4_mul(r_wwww, rhs);
652 let l_wzyx = i32x4_shuffle::<3, 2, 5, 4>(rhs, rhs);
653
654 let lwrx_lzrx_lyrx_lxrx = f32x4_mul(r_xxxx, l_wzyx);
655 let l_zwxy = i32x4_shuffle::<1, 0, 7, 6>(l_wzyx, l_wzyx);
656
657 let lwrx_nlzrx_lyrx_nlxrx = f32x4_mul(lwrx_lzrx_lyrx_lxrx, CONTROL_WZYX);
658
659 let lzry_lwry_lxry_lyry = f32x4_mul(r_yyyy, l_zwxy);
660 let l_yxwz = i32x4_shuffle::<3, 2, 5, 4>(l_zwxy, l_zwxy);
661
662 let lzry_lwry_nlxry_nlyry = f32x4_mul(lzry_lwry_lxry_lyry, CONTROL_ZWXY);
663
664 let lyrz_lxrz_lwrz_lzrz = f32x4_mul(r_zzzz, l_yxwz);
665 let result0 = f32x4_add(lxrw_lyrw_lzrw_lwrw, lwrx_nlzrx_lyrx_nlxrx);
666
667 let nlyrz_lxrz_lwrz_wlzrz = f32x4_mul(lyrz_lxrz_lwrz_lzrz, CONTROL_YXWZ);
668 let result1 = f32x4_add(lzry_lwry_nlxry_nlyry, nlyrz_lxrz_lwrz_wlzrz);
669
670 Self(f32x4_add(result0, result1))
671 }
672
673 /// Creates a quaternion from a 3x3 rotation matrix inside a 3D affine transform.
674 #[inline]
675 pub fn from_affine3(a: &crate::Affine3A) -> Self {
676 #[allow(clippy::useless_conversion)]
677 Self::from_rotation_axes(
678 a.matrix3.x_axis.into(),
679 a.matrix3.y_axis.into(),
680 a.matrix3.z_axis.into(),
681 )
682 }
683
684 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
685 #[inline]
686 pub fn mul_vec3a(self, rhs: Vec3A) -> Vec3A {
687 const TWO: v128 = v128_from_f32x4([2.0; 4]);
688 let w = i32x4_shuffle::<3, 3, 7, 7>(self.0, self.0);
689 let b = self.0;
690 let b2 = dot3_into_v128(b, b);
691 Vec3A(f32x4_add(
692 f32x4_add(
693 f32x4_mul(rhs.0, f32x4_sub(f32x4_mul(w, w), b2)),
694 f32x4_mul(b, f32x4_mul(dot3_into_v128(rhs.0, b), TWO)),
695 ),
696 f32x4_mul(Vec3A(b).cross(rhs).into(), f32x4_mul(w, TWO)),
697 ))
698 }
699
700 #[inline]
701 pub fn as_f64(self) -> DQuat {
702 DQuat::from_xyzw(self.x as f64, self.y as f64, self.z as f64, self.w as f64)
703 }
704 }
705
706 #[cfg(not(target_arch = "spirv"))]
707 impl fmt::Debug for Quat {
708 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
709 fmt.debug_tuple(stringify!(Quat))
710 .field(&self.x)
711 .field(&self.y)
712 .field(&self.z)
713 .field(&self.w)
714 .finish()
715 }
716 }
717
718 #[cfg(not(target_arch = "spirv"))]
719 impl fmt::Display for Quat {
720 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
721 write!(fmt, "[{}, {}, {}, {}]", self.x, self.y, self.z, self.w)
722 }
723 }
724
725 impl Add<Quat> for Quat {
726 type Output = Self;
727 /// Adds two quaternions.
728 ///
729 /// The sum is not guaranteed to be normalized.
730 ///
731 /// Note that addition is not the same as combining the rotations represented by the
732 /// two quaternions! That corresponds to multiplication.
733 #[inline]
734 fn add(self, rhs: Self) -> Self {
735 Self::from_vec4(Vec4::from(self) + Vec4::from(rhs))
736 }
737 }
738
739 impl Sub<Quat> for Quat {
740 type Output = Self;
741 /// Subtracts the `rhs` quaternion from `self`.
742 ///
743 /// The difference is not guaranteed to be normalized.
744 #[inline]
745 fn sub(self, rhs: Self) -> Self {
746 Self::from_vec4(Vec4::from(self) - Vec4::from(rhs))
747 }
748 }
749
750 impl Mul<f32> for Quat {
751 type Output = Self;
752 /// Multiplies a quaternion by a scalar value.
753 ///
754 /// The product is not guaranteed to be normalized.
755 #[inline]
756 fn mul(self, rhs: f32) -> Self {
757 Self::from_vec4(Vec4::from(self) * rhs)
758 }
759 }
760
761 impl Div<f32> for Quat {
762 type Output = Self;
763 /// Divides a quaternion by a scalar value.
764 /// The quotient is not guaranteed to be normalized.
765 #[inline]
766 fn div(self, rhs: f32) -> Self {
767 Self::from_vec4(Vec4::from(self) / rhs)
768 }
769 }
770
771 impl Mul<Quat> for Quat {
772 type Output = Self;
773 /// Multiplies two quaternions. If they each represent a rotation, the result will
774 /// represent the combined rotation.
775 ///
776 /// Note that due to floating point rounding the result may not be perfectly
777 /// normalized.
778 ///
779 /// # Panics
780 ///
781 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
782 #[inline]
783 fn mul(self, rhs: Self) -> Self {
784 self.mul_quat(rhs)
785 }
786 }
787
788 impl MulAssign<Quat> for Quat {
789 /// Multiplies two quaternions. If they each represent a rotation, the result will
790 /// represent the combined rotation.
791 ///
792 /// Note that due to floating point rounding the result may not be perfectly
793 /// normalized.
794 ///
795 /// # Panics
796 ///
797 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
798 #[inline]
799 fn mul_assign(&mut self, rhs: Self) {
800 *self = self.mul_quat(rhs);
801 }
802 }
803
804 impl Mul<Vec3> for Quat {
805 type Output = Vec3;
806 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
807 ///
808 /// # Panics
809 ///
810 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
811 #[inline]
812 fn mul(self, rhs: Vec3) -> Self::Output {
813 self.mul_vec3(rhs)
814 }
815 }
816
817 impl Neg for Quat {
818 type Output = Self;
819 #[inline]
820 fn neg(self) -> Self {
821 self * -1.0
822 }
823 }
824
825 impl Default for Quat {
826 #[inline]
827 fn default() -> Self {
828 Self::IDENTITY
829 }
830 }
831
832 impl PartialEq for Quat {
833 #[inline]
834 fn eq(&self, rhs: &Self) -> bool {
835 Vec4::from(*self).eq(&Vec4::from(*rhs))
836 }
837 }
838
839 #[cfg(not(target_arch = "spirv"))]
840 impl AsRef<[f32; 4]> for Quat {
841 #[inline]
842 fn as_ref(&self) -> &[f32; 4] {
843 unsafe { &*(self as *const Self as *const [f32; 4]) }
844 }
845 }
846
847 impl Sum<Self> for Quat {
848 fn sum<I>(iter: I) -> Self
849 where
850 I: Iterator<Item = Self>,
851 {
852 iter.fold(Self::ZERO, Self::add)
853 }
854 }
855
856 impl<'a> Sum<&'a Self> for Quat {
857 fn sum<I>(iter: I) -> Self
858 where
859 I: Iterator<Item = &'a Self>,
860 {
861 iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
862 }
863 }
864
865 impl Product for Quat {
866 fn product<I>(iter: I) -> Self
867 where
868 I: Iterator<Item = Self>,
869 {
870 iter.fold(Self::IDENTITY, Self::mul)
871 }
872 }
873
874 impl<'a> Product<&'a Self> for Quat {
875 fn product<I>(iter: I) -> Self
876 where
877 I: Iterator<Item = &'a Self>,
878 {
879 iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
880 }
881 }
882
883 impl Mul<Vec3A> for Quat {
884 type Output = Vec3A;
885 #[inline]
886 fn mul(self, rhs: Vec3A) -> Self::Output {
887 self.mul_vec3a(rhs)
888 }
889 }
890
891 impl From<Quat> for Vec4 {
892 #[inline]
893 fn from(q: Quat) -> Self {
894 Self(q.0)
895 }
896 }
897
898 impl From<Quat> for (f32, f32, f32, f32) {
899 #[inline]
900 fn from(q: Quat) -> Self {
901 Vec4::from(q).into()
902 }
903 }
904
905 impl From<Quat> for [f32; 4] {
906 #[inline]
907 fn from(q: Quat) -> Self {
908 Vec4::from(q).into()
909 }
910 }
911
912 impl From<Quat> for v128 {
913 #[inline]
914 fn from(q: Quat) -> Self {
915 q.0
916 }
917 }
918
919 impl Deref for Quat {
920 type Target = crate::deref::Vec4<f32>;
921 #[inline]
922 fn deref(&self) -> &Self::Target {
923 unsafe { &*(self as *const Self).cast() }
924 }
925 }
926
927 impl DerefMut for Quat {
928 #[inline]
929 fn deref_mut(&mut self) -> &mut Self::Target {
930 unsafe { &mut *(self as *mut Self).cast() }
931 }
932 }