Debian Codegraph @

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