Debian Codegraph @

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