Debian Codegraph @

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