Debian Codegraph @

debian/missing-sources/glam/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::{EulerRot, FromEuler, ToEuler},
5 f32::math,
6 DQuat, Mat3, Mat3A, Mat4, Vec2, Vec3, Vec3A, Vec4,
7 };
8
9 use core::fmt;
10 use core::iter::{Product, Sum};
11 use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
12
13 #[cfg(feature = "zerocopy")]
14 use zerocopy_derive::*;
15
16 /// Creates a quaternion from `x`, `y`, `z` and `w` values.
17 ///
18 /// This should generally not be called manually unless you know what you are doing. Use
19 /// one of the other constructors instead such as `identity` or `from_axis_angle`.
20 #[inline]
21 #[must_use]
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(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]
33 #[cfg_attr(
34 feature = "zerocopy",
35 derive(FromBytes, Immutable, IntoBytes, KnownLayout)
36 )]
37 #[cfg_attr(not(feature = "scalar-math"), repr(align(16)))]
38 #[repr(C)]
39 #[cfg_attr(target_arch = "spirv", rust_gpu::vector::v1)]
40 pub struct Quat {
41 pub x: f32,
42 pub y: f32,
43 pub z: f32,
44 pub w: f32,
45 }
46
47 impl Quat {
48 /// All zeros.
49 const ZERO: Self = Self::from_array([0.0; 4]);
50
51 /// The identity quaternion. Corresponds to no rotation.
52 pub const IDENTITY: Self = Self::from_xyzw(0.0, 0.0, 0.0, 1.0);
53
54 /// All NANs.
55 pub const NAN: Self = Self::from_array([f32::NAN; 4]);
56
57 /// Creates a new rotation quaternion.
58 ///
59 /// This should generally not be called manually unless you know what you are doing.
60 /// Use one of the other constructors instead such as `identity` or `from_axis_angle`.
61 ///
62 /// `from_xyzw` is mostly used by unit tests and `serde` deserialization.
63 ///
64 /// # Preconditions
65 ///
66 /// This function does not check if the input is normalized, it is up to the user to
67 /// provide normalized input or to normalized the resulting quaternion.
68 #[inline(always)]
69 #[must_use]
70 pub const fn from_xyzw(x: f32, y: f32, z: f32, w: f32) -> Self {
71 Self { x, y, z, w }
72 }
73
74 /// Creates a rotation quaternion from an array.
75 ///
76 /// # Preconditions
77 ///
78 /// This function does not check if the input is normalized, it is up to the user to
79 /// provide normalized input or to normalized the resulting quaternion.
80 #[inline]
81 #[must_use]
82 pub const fn from_array(a: [f32; 4]) -> Self {
83 Self::from_xyzw(a[0], a[1], a[2], a[3])
84 }
85
86 /// Creates a new rotation quaternion from a 4D vector.
87 ///
88 /// # Preconditions
89 ///
90 /// This function does not check if the input is normalized, it is up to the user to
91 /// provide normalized input or to normalized the resulting quaternion.
92 #[inline]
93 #[must_use]
94 pub const fn from_vec4(v: Vec4) -> Self {
95 Self {
96 x: v.x,
97 y: v.y,
98 z: v.z,
99 w: v.w,
100 }
101 }
102
103 /// Creates a rotation quaternion from a slice.
104 ///
105 /// # Preconditions
106 ///
107 /// This function does not check if the input is normalized, it is up to the user to
108 /// provide normalized input or to normalized the resulting quaternion.
109 ///
110 /// # Panics
111 ///
112 /// Panics if `slice` length is less than 4.
113 #[inline]
114 #[must_use]
115 pub fn from_slice(slice: &[f32]) -> Self {
116 Self::from_xyzw(slice[0], slice[1], slice[2], slice[3])
117 }
118
119 /// Writes the quaternion to an unaligned slice.
120 ///
121 /// # Panics
122 ///
123 /// Panics if `slice` length is less than 4.
124 #[inline]
125 pub fn write_to_slice(self, slice: &mut [f32]) {
126 slice[0] = self.x;
127 slice[1] = self.y;
128 slice[2] = self.z;
129 slice[3] = self.w;
130 }
131
132 /// Create a quaternion for a normalized rotation `axis` and `angle` (in radians).
133 ///
134 /// The axis must be a unit vector.
135 ///
136 /// # Panics
137 ///
138 /// Will panic if `axis` is not normalized when `glam_assert` is enabled.
139 #[inline]
140 #[must_use]
141 pub fn from_axis_angle(axis: Vec3, angle: f32) -> Self {
142 glam_assert!(axis.is_normalized());
143 let (s, c) = math::sin_cos(angle * 0.5);
144 let v = axis * s;
145 Self::from_xyzw(v.x, v.y, v.z, c)
146 }
147
148 /// Create a quaternion that rotates `v.length()` radians around `v.normalize()`.
149 ///
150 /// `from_scaled_axis(Vec3::ZERO)` results in the identity quaternion.
151 #[inline]
152 #[must_use]
153 pub fn from_scaled_axis(v: Vec3) -> Self {
154 let length = v.length();
155 if length == 0.0 {
156 Self::IDENTITY
157 } else {
158 Self::from_axis_angle(v / length, length)
159 }
160 }
161
162 /// Creates a quaternion from the `angle` (in radians) around the x axis.
163 #[inline]
164 #[must_use]
165 pub fn from_rotation_x(angle: f32) -> Self {
166 let (s, c) = math::sin_cos(angle * 0.5);
167 Self::from_xyzw(s, 0.0, 0.0, c)
168 }
169
170 /// Creates a quaternion from the `angle` (in radians) around the y axis.
171 #[inline]
172 #[must_use]
173 pub fn from_rotation_y(angle: f32) -> Self {
174 let (s, c) = math::sin_cos(angle * 0.5);
175 Self::from_xyzw(0.0, s, 0.0, c)
176 }
177
178 /// Creates a quaternion from the `angle` (in radians) around the z axis.
179 #[inline]
180 #[must_use]
181 pub fn from_rotation_z(angle: f32) -> Self {
182 let (s, c) = math::sin_cos(angle * 0.5);
183 Self::from_xyzw(0.0, 0.0, s, c)
184 }
185
186 /// Creates a quaternion from the given Euler rotation sequence and the angles (in radians).
187 #[inline]
188 #[must_use]
189 pub fn from_euler(euler: EulerRot, a: f32, b: f32, c: f32) -> Self {
190 Self::from_euler_angles(euler, a, b, c)
191 }
192
193 /// From the columns of a 3x3 rotation matrix.
194 ///
195 /// Note if the input axes contain scales, shears, or other non-rotation transformations then
196 /// the output of this function is ill-defined.
197 ///
198 /// # Panics
199 ///
200 /// Will panic if any axis is not normalized when `glam_assert` is enabled.
201 #[inline]
202 #[must_use]
203 pub(crate) fn from_rotation_axes(x_axis: Vec3, y_axis: Vec3, z_axis: Vec3) -> Self {
204 glam_assert!(x_axis.is_normalized() && y_axis.is_normalized() && z_axis.is_normalized());
205 // Based on https://github.com/microsoft/DirectXMath `XMQuaternionRotationMatrix`
206 let (m00, m01, m02) = x_axis.into();
207 let (m10, m11, m12) = y_axis.into();
208 let (m20, m21, m22) = z_axis.into();
209 if m22 <= 0.0 {
210 // x^2 + y^2 >= z^2 + w^2
211 let dif10 = m11 - m00;
212 let omm22 = 1.0 - m22;
213 if dif10 <= 0.0 {
214 // x^2 >= y^2
215 let four_xsq = omm22 - dif10;
216 let inv4x = 0.5 / math::sqrt(four_xsq);
217 Self::from_xyzw(
218 four_xsq * inv4x,
219 (m01 + m10) * inv4x,
220 (m02 + m20) * inv4x,
221 (m12 - m21) * inv4x,
222 )
223 } else {
224 // y^2 >= x^2
225 let four_ysq = omm22 + dif10;
226 let inv4y = 0.5 / math::sqrt(four_ysq);
227 Self::from_xyzw(
228 (m01 + m10) * inv4y,
229 four_ysq * inv4y,
230 (m12 + m21) * inv4y,
231 (m20 - m02) * inv4y,
232 )
233 }
234 } else {
235 // z^2 + w^2 >= x^2 + y^2
236 let sum10 = m11 + m00;
237 let opm22 = 1.0 + m22;
238 if sum10 <= 0.0 {
239 // z^2 >= w^2
240 let four_zsq = opm22 - sum10;
241 let inv4z = 0.5 / math::sqrt(four_zsq);
242 Self::from_xyzw(
243 (m02 + m20) * inv4z,
244 (m12 + m21) * inv4z,
245 four_zsq * inv4z,
246 (m01 - m10) * inv4z,
247 )
248 } else {
249 // w^2 >= z^2
250 let four_wsq = opm22 + sum10;
251 let inv4w = 0.5 / math::sqrt(four_wsq);
252 Self::from_xyzw(
253 (m12 - m21) * inv4w,
254 (m20 - m02) * inv4w,
255 (m01 - m10) * inv4w,
256 four_wsq * inv4w,
257 )
258 }
259 }
260 }
261
262 /// Creates a quaternion from a 3x3 rotation matrix.
263 ///
264 /// Note if the input matrix contain scales, shears, or other non-rotation transformations then
265 /// the resulting quaternion will be ill-defined.
266 ///
267 /// # Panics
268 ///
269 /// Will panic if any input matrix column is not normalized when `glam_assert` is enabled.
270 #[inline]
271 #[must_use]
272 pub fn from_mat3(mat: &Mat3) -> Self {
273 Self::from_rotation_axes(mat.x_axis, mat.y_axis, mat.z_axis)
274 }
275
276 /// Creates a quaternion from a 3x3 SIMD aligned rotation matrix.
277 ///
278 /// Note if the input matrix contain scales, shears, or other non-rotation transformations then
279 /// the resulting quaternion will be ill-defined.
280 ///
281 /// # Panics
282 ///
283 /// Will panic if any input matrix column is not normalized when `glam_assert` is enabled.
284 #[inline]
285 #[must_use]
286 pub fn from_mat3a(mat: &Mat3A) -> Self {
287 Self::from_rotation_axes(mat.x_axis.into(), mat.y_axis.into(), mat.z_axis.into())
288 }
289
290 /// Creates a quaternion from the upper 3x3 rotation matrix inside a homogeneous 4x4 matrix.
291 ///
292 /// Note if the upper 3x3 matrix contain scales, shears, or other non-rotation transformations
293 /// then the resulting quaternion will be ill-defined.
294 ///
295 /// # Panics
296 ///
297 /// Will panic if any column of the upper 3x3 rotation matrix is not normalized when
298 /// `glam_assert` is enabled.
299 #[inline]
300 #[must_use]
301 pub fn from_mat4(mat: &Mat4) -> Self {
302 Self::from_rotation_axes(
303 mat.x_axis.truncate(),
304 mat.y_axis.truncate(),
305 mat.z_axis.truncate(),
306 )
307 }
308
309 /// Gets the minimal rotation for transforming `from` to `to`. The rotation is in the
310 /// plane spanned by the two vectors. Will rotate at most 180 degrees.
311 ///
312 /// The inputs must be unit vectors.
313 ///
314 /// `from_rotation_arc(from, to) * from ≈ to`.
315 ///
316 /// For near-singular cases (from≈to and from≈-to) the current implementation
317 /// is only accurate to about 0.001 (for `f32`).
318 ///
319 /// # Panics
320 ///
321 /// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
322 #[must_use]
323 pub fn from_rotation_arc(from: Vec3, to: Vec3) -> Self {
324 glam_assert!(from.is_normalized());
325 glam_assert!(to.is_normalized());
326
327 const ONE_MINUS_EPS: f32 = 1.0 - 2.0 * f32::EPSILON;
328 let dot = from.dot(to);
329 if dot > ONE_MINUS_EPS {
330 // 0° singularity: from ≈ to
331 Self::IDENTITY
332 } else if dot < -ONE_MINUS_EPS {
333 // 180° singularity: from ≈ -to
334 use core::f32::consts::PI; // half a turn = 𝛕/2 = 180°
335 Self::from_axis_angle(from.any_orthonormal_vector(), PI)
336 } else {
337 let c = from.cross(to);
338 Self::from_xyzw(c.x, c.y, c.z, 1.0 + dot).normalize()
339 }
340 }
341
342 /// Gets the minimal rotation for transforming `from` to either `to` or `-to`. This means
343 /// that the resulting quaternion will rotate `from` so that it is colinear with `to`.
344 ///
345 /// The rotation is in the plane spanned by the two vectors. Will rotate at most 90
346 /// degrees.
347 ///
348 /// The inputs must be unit vectors.
349 ///
350 /// `to.dot(from_rotation_arc_colinear(from, to) * from).abs() ≈ 1`.
351 ///
352 /// # Panics
353 ///
354 /// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
355 #[inline]
356 #[must_use]
357 pub fn from_rotation_arc_colinear(from: Vec3, to: Vec3) -> Self {
358 if from.dot(to) < 0.0 {
359 Self::from_rotation_arc(from, -to)
360 } else {
361 Self::from_rotation_arc(from, to)
362 }
363 }
364
365 /// Gets the minimal rotation for transforming `from` to `to`. The resulting rotation is
366 /// around the z axis. Will rotate at most 180 degrees.
367 ///
368 /// The inputs must be unit vectors.
369 ///
370 /// `from_rotation_arc_2d(from, to) * from ≈ to`.
371 ///
372 /// For near-singular cases (from≈to and from≈-to) the current implementation
373 /// is only accurate to about 0.001 (for `f32`).
374 ///
375 /// # Panics
376 ///
377 /// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
378 #[must_use]
379 pub fn from_rotation_arc_2d(from: Vec2, to: Vec2) -> Self {
380 glam_assert!(from.is_normalized());
381 glam_assert!(to.is_normalized());
382
383 const ONE_MINUS_EPSILON: f32 = 1.0 - 2.0 * f32::EPSILON;
384 let dot = from.dot(to);
385 if dot > ONE_MINUS_EPSILON {
386 // 0° singularity: from ≈ to
387 Self::IDENTITY
388 } else if dot < -ONE_MINUS_EPSILON {
389 // 180° singularity: from ≈ -to
390 const COS_FRAC_PI_2: f32 = 0.0;
391 const SIN_FRAC_PI_2: f32 = 1.0;
392 // rotation around z by PI radians
393 Self::from_xyzw(0.0, 0.0, SIN_FRAC_PI_2, COS_FRAC_PI_2)
394 } else {
395 // vector3 cross where z=0
396 let z = from.x * to.y - to.x * from.y;
397 let w = 1.0 + dot;
398 // calculate length with x=0 and y=0 to normalize
399 let len_rcp = 1.0 / math::sqrt(z * z + w * w);
400 Self::from_xyzw(0.0, 0.0, z * len_rcp, w * len_rcp)
401 }
402 }
403
404 /// Creates a quaterion rotation from a facing direction and an up direction.
405 ///
406 /// For a left-handed view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`.
407 ///
408 /// # Panics
409 ///
410 /// Will panic if `up` is not normalized when `glam_assert` is enabled.
411 #[inline]
412 #[must_use]
413 pub fn look_to_lh(dir: Vec3, up: Vec3) -> Self {
414 Self::look_to_rh(-dir, up)
415 }
416
417 /// Creates a quaterion rotation from facing direction and an up direction.
418 ///
419 /// For a right-handed view coordinate system with `+X=right`, `+Y=up` and `+Z=back`.
420 ///
421 /// # Panics
422 ///
423 /// Will panic if `dir` and `up` are not normalized when `glam_assert` is enabled.
424 #[inline]
425 #[must_use]
426 pub fn look_to_rh(dir: Vec3, up: Vec3) -> Self {
427 glam_assert!(dir.is_normalized());
428 glam_assert!(up.is_normalized());
429 let f = dir;
430 let s = f.cross(up).normalize();
431 let u = s.cross(f);
432
433 Self::from_rotation_axes(
434 Vec3::new(s.x, u.x, -f.x),
435 Vec3::new(s.y, u.y, -f.y),
436 Vec3::new(s.z, u.z, -f.z),
437 )
438 }
439
440 /// Creates a left-handed view matrix using a camera position, a focal point, and an up
441 /// direction.
442 ///
443 /// For a left-handed view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`.
444 ///
445 /// # Panics
446 ///
447 /// Will panic if `up` is not normalized when `glam_assert` is enabled.
448 #[inline]
449 #[must_use]
450 pub fn look_at_lh(eye: Vec3, center: Vec3, up: Vec3) -> Self {
451 Self::look_to_lh(center.sub(eye).normalize(), up)
452 }
453
454 /// Creates a right-handed view matrix using a camera position, an up direction, and a focal
455 /// point.
456 ///
457 /// For a right-handed view coordinate system with `+X=right`, `+Y=up` and `+Z=back`.
458 ///
459 /// # Panics
460 ///
461 /// Will panic if `up` is not normalized when `glam_assert` is enabled.
462 #[inline]
463 #[must_use]
464 pub fn look_at_rh(eye: Vec3, center: Vec3, up: Vec3) -> Self {
465 Self::look_to_rh(center.sub(eye).normalize(), up)
466 }
467
468 /// Returns the rotation axis (normalized) and angle (in radians) of `self`.
469 #[inline]
470 #[must_use]
471 pub fn to_axis_angle(self) -> (Vec3, f32) {
472 const EPSILON: f32 = 1.0e-8;
473 let v = Vec3::new(self.x, self.y, self.z);
474 let length = v.length();
475 if length >= EPSILON {
476 let angle = 2.0 * math::atan2(length, self.w);
477 let axis = v / length;
478 (axis, angle)
479 } else {
480 (Vec3::X, 0.0)
481 }
482 }
483
484 /// Returns the rotation axis scaled by the rotation in radians.
485 #[inline]
486 #[must_use]
487 pub fn to_scaled_axis(self) -> Vec3 {
488 let (axis, angle) = self.to_axis_angle();
489 axis * angle
490 }
491
492 /// Returns the rotation angles for the given euler rotation sequence.
493 #[inline]
494 #[must_use]
495 pub fn to_euler(self, order: EulerRot) -> (f32, f32, f32) {
496 self.to_euler_angles(order)
497 }
498
499 /// `[x, y, z, w]`
500 #[inline]
501 #[must_use]
502 pub fn to_array(&self) -> [f32; 4] {
503 [self.x, self.y, self.z, self.w]
504 }
505
506 /// Returns the vector part of the quaternion.
507 #[inline]
508 #[must_use]
509 pub fn xyz(self) -> Vec3 {
510 Vec3::new(self.x, self.y, self.z)
511 }
512
513 /// Returns the quaternion conjugate of `self`. For a unit quaternion the
514 /// conjugate is also the inverse.
515 #[inline]
516 #[must_use]
517 pub fn conjugate(self) -> Self {
518 Self {
519 x: -self.x,
520 y: -self.y,
521 z: -self.z,
522 w: self.w,
523 }
524 }
525
526 /// Returns the inverse of a normalized quaternion.
527 ///
528 /// Typically quaternion inverse returns the conjugate of a normalized quaternion.
529 /// Because `self` is assumed to already be unit length this method *does not* normalize
530 /// before returning the conjugate.
531 ///
532 /// # Panics
533 ///
534 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
535 #[inline]
536 #[must_use]
537 pub fn inverse(self) -> Self {
538 glam_assert!(self.is_normalized());
539 self.conjugate()
540 }
541
542 /// Computes the dot product of `self` and `rhs`. The dot product is
543 /// equal to the cosine of the angle between two quaternion rotations.
544 #[inline]
545 #[must_use]
546 pub fn dot(self, rhs: Self) -> f32 {
547 Vec4::from(self).dot(Vec4::from(rhs))
548 }
549
550 /// Computes the length of `self`.
551 #[doc(alias = "magnitude")]
552 #[inline]
553 #[must_use]
554 pub fn length(self) -> f32 {
555 Vec4::from(self).length()
556 }
557
558 /// Computes the squared length of `self`.
559 ///
560 /// This is generally faster than `length()` as it avoids a square
561 /// root operation.
562 #[doc(alias = "magnitude2")]
563 #[inline]
564 #[must_use]
565 pub fn length_squared(self) -> f32 {
566 Vec4::from(self).length_squared()
567 }
568
569 /// Computes `1.0 / length()`.
570 ///
571 /// For valid results, `self` must _not_ be of length zero.
572 #[inline]
573 #[must_use]
574 pub fn length_recip(self) -> f32 {
575 Vec4::from(self).length_recip()
576 }
577
578 /// Returns `self` normalized to length 1.0.
579 ///
580 /// For valid results, `self` must _not_ be of length zero.
581 ///
582 /// Panics
583 ///
584 /// Will panic if `self` is zero length when `glam_assert` is enabled.
585 #[inline]
586 #[must_use]
587 pub fn normalize(self) -> Self {
588 Self::from_vec4(Vec4::from(self).normalize())
589 }
590
591 /// Returns `true` if, and only if, all elements are finite.
592 /// If any element is either `NaN`, positive or negative infinity, this will return `false`.
593 #[inline]
594 #[must_use]
595 pub fn is_finite(self) -> bool {
596 Vec4::from(self).is_finite()
597 }
598
599 /// Returns `true` if any elements are `NAN`.
600 #[inline]
601 #[must_use]
602 pub fn is_nan(self) -> bool {
603 Vec4::from(self).is_nan()
604 }
605
606 /// Returns whether `self` of length `1.0` or not.
607 ///
608 /// Uses a precision threshold of `1e-6`.
609 #[inline]
610 #[must_use]
611 pub fn is_normalized(self) -> bool {
612 Vec4::from(self).is_normalized()
613 }
614
615 #[inline]
616 #[must_use]
617 pub fn is_near_identity(self) -> bool {
618 // Based on https://github.com/nfrechette/rtm `rtm::quat_near_identity`
619 // Because of floating point precision, we cannot represent very small rotations.
620 // The closest f32 to 1.0 that is not 1.0 itself yields:
621 // 0.99999994.acos() * 2.0 = 0.000690533954 rad
622 //
623 // An error threshold of 1.e-6 is used by default.
624 // (1.0 - 1.e-6).acos() * 2.0 = 0.00284714461 rad
625 // (1.0 - 1.e-7).acos() * 2.0 = 0.00097656250 rad
626 //
627 // We don't really care about the angle value itself, only if it's close to 0.
628 // This will happen whenever quat.w is close to 1.0.
629 // If the quat.w is close to -1.0, the angle will be near 2*PI which is close to
630 // a negative 0 rotation. By forcing quat.w to be positive, we'll end up with
631 // the shortest path.
632 //
633 // For f64 we're using a threshhold of
634 // (1.0 - 1e-14).acos() * 2.0
635 const THRESHOLD_ANGLE: f32 = 0.002_847_144_6;
636 let positive_w_angle = math::acos_approx(math::abs(self.w)) * 2.0;
637 positive_w_angle < THRESHOLD_ANGLE
638 }
639
640 /// Returns the angle (in radians) for the minimal rotation
641 /// for transforming this quaternion into another.
642 ///
643 /// Both quaternions must be normalized.
644 ///
645 /// # Panics
646 ///
647 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
648 #[inline]
649 #[must_use]
650 pub fn angle_between(self, rhs: Self) -> f32 {
651 glam_assert!(self.is_normalized() && rhs.is_normalized());
652 math::acos_approx(math::abs(self.dot(rhs))) * 2.0
653 }
654
655 /// Rotates towards `rhs` up to `max_angle` (in radians).
656 ///
657 /// When `max_angle` is `0.0`, the result will be equal to `self`. When `max_angle` is equal to
658 /// `self.angle_between(rhs)`, the result will be equal to `rhs`. If `max_angle` is negative,
659 /// rotates towards the exact opposite of `rhs`. Will not go past the target.
660 ///
661 /// Both quaternions must be normalized.
662 ///
663 /// # Panics
664 ///
665 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
666 #[inline]
667 #[must_use]
668 pub fn rotate_towards(&self, rhs: Self, max_angle: f32) -> Self {
669 glam_assert!(self.is_normalized() && rhs.is_normalized());
670 let angle = self.angle_between(rhs);
671 if angle <= 1e-4 {
672 return rhs;
673 }
674 let s = (max_angle / angle).clamp(-1.0, 1.0);
675 self.slerp(rhs, s)
676 }
677
678 /// Returns true if the absolute difference of all elements between `self` and `rhs`
679 /// is less than or equal to `max_abs_diff`.
680 ///
681 /// This can be used to compare if two quaternions contain similar elements. It works
682 /// best when comparing with a known value. The `max_abs_diff` that should be used used
683 /// depends on the values being compared against.
684 ///
685 /// For more see
686 /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
687 #[inline]
688 #[must_use]
689 pub fn abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool {
690 Vec4::from(self).abs_diff_eq(Vec4::from(rhs), max_abs_diff)
691 }
692
693 #[inline(always)]
694 #[must_use]
695 fn lerp_impl(self, end: Self, s: f32) -> Self {
696 (self * (1.0 - s) + end * s).normalize()
697 }
698
699 /// Performs a linear interpolation between `self` and `rhs` based on
700 /// the value `s`.
701 ///
702 /// When `s` is `0.0`, the result will be equal to `self`. When `s`
703 /// is `1.0`, the result will be equal to `rhs`.
704 ///
705 /// # Panics
706 ///
707 /// Will panic if `self` or `end` are not normalized when `glam_assert` is enabled.
708 #[doc(alias = "mix")]
709 #[inline]
710 #[must_use]
711 pub fn lerp(self, end: Self, s: f32) -> Self {
712 glam_assert!(self.is_normalized());
713 glam_assert!(end.is_normalized());
714
715 let dot = self.dot(end);
716 let bias = if dot >= 0.0 { 1.0 } else { -1.0 };
717 self.lerp_impl(end * bias, s)
718 }
719
720 /// Performs a spherical linear interpolation between `self` and `end`
721 /// based on the value `s`.
722 ///
723 /// When `s` is `0.0`, the result will be equal to `self`. When `s`
724 /// is `1.0`, the result will be equal to `end`.
725 ///
726 /// # Panics
727 ///
728 /// Will panic if `self` or `end` are not normalized when `glam_assert` is enabled.
729 #[inline]
730 #[must_use]
731 pub fn slerp(self, mut end: Self, s: f32) -> Self {
732 // http://number-none.com/product/Understanding%20Slerp,%20Then%20Not%20Using%20It/
733 glam_assert!(self.is_normalized());
734 glam_assert!(end.is_normalized());
735
736 // Note that a rotation can be represented by two quaternions: `q` and
737 // `-q`. The slerp path between `q` and `end` will be different from the
738 // path between `-q` and `end`. One path will take the long way around and
739 // one will take the short way. In order to correct for this, the `dot`
740 // product between `self` and `end` should be positive. If the `dot`
741 // product is negative, slerp between `self` and `-end`.
742 let mut dot = self.dot(end);
743 if dot < 0.0 {
744 end = -end;
745 dot = -dot;
746 }
747
748 const DOT_THRESHOLD: f32 = 1.0 - f32::EPSILON;
749 if dot > DOT_THRESHOLD {
750 // if above threshold perform linear interpolation to avoid divide by zero
751 self.lerp_impl(end, s)
752 } else {
753 let theta = math::acos_approx(dot);
754
755 let scale1 = math::sin(theta * (1.0 - s));
756 let scale2 = math::sin(theta * s);
757 let theta_sin = math::sin(theta);
758 ((self * scale1) + (end * scale2)) * (1.0 / theta_sin)
759 }
760 }
761
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 #[must_use]
769 pub fn mul_vec3(self, rhs: Vec3) -> Vec3 {
770 glam_assert!(self.is_normalized());
771
772 let w = self.w;
773 let b = Vec3::new(self.x, self.y, self.z);
774 let b2 = b.dot(b);
775 rhs.mul(w * w - b2)
776 .add(b.mul(rhs.dot(b) * 2.0))
777 .add(b.cross(rhs).mul(w * 2.0))
778 }
779
780 /// Multiplies two quaternions. If they each represent a rotation, the result will
781 /// represent the combined rotation.
782 ///
783 /// Note that due to floating point rounding the result may not be perfectly normalized.
784 ///
785 /// # Panics
786 ///
787 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
788 #[inline]
789 #[must_use]
790 pub fn mul_quat(self, rhs: Self) -> Self {
791 let (x0, y0, z0, w0) = self.into();
792 let (x1, y1, z1, w1) = rhs.into();
793 Self::from_xyzw(
794 w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1,
795 w0 * y1 - x0 * z1 + y0 * w1 + z0 * x1,
796 w0 * z1 + x0 * y1 - y0 * x1 + z0 * w1,
797 w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1,
798 )
799 }
800
801 /// Creates a quaternion from a 3x3 rotation matrix inside a 3D affine transform.
802 ///
803 /// Note if the input affine matrix contain scales, shears, or other non-rotation
804 /// transformations then the resulting quaternion will be ill-defined.
805 ///
806 /// # Panics
807 ///
808 /// Will panic if any input affine matrix column is not normalized when `glam_assert` is
809 /// enabled.
810 #[inline]
811 #[must_use]
812 pub fn from_affine3(a: &crate::Affine3A) -> Self {
813 #[allow(clippy::useless_conversion)]
814 Self::from_rotation_axes(
815 a.matrix3.x_axis.into(),
816 a.matrix3.y_axis.into(),
817 a.matrix3.z_axis.into(),
818 )
819 }
820
821 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
822 #[inline]
823 #[must_use]
824 pub fn mul_vec3a(self, rhs: Vec3A) -> Vec3A {
825 self.mul_vec3(rhs.into()).into()
826 }
827
828 #[inline]
829 #[must_use]
830 pub fn as_dquat(self) -> DQuat {
831 DQuat::from_xyzw(self.x as f64, self.y as f64, self.z as f64, self.w as f64)
832 }
833 }
834
835 impl fmt::Debug for Quat {
836 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
837 fmt.debug_tuple(stringify!(Quat))
838 .field(&self.x)
839 .field(&self.y)
840 .field(&self.z)
841 .field(&self.w)
842 .finish()
843 }
844 }
845
846 impl fmt::Display for Quat {
847 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
848 if let Some(p) = f.precision() {
849 write!(
850 f,
851 "[{:.*}, {:.*}, {:.*}, {:.*}]",
852 p, self.x, p, self.y, p, self.z, p, self.w
853 )
854 } else {
855 write!(f, "[{}, {}, {}, {}]", self.x, self.y, self.z, self.w)
856 }
857 }
858 }
859
860 impl Add for Quat {
861 type Output = Self;
862 /// Adds two quaternions.
863 ///
864 /// The sum is not guaranteed to be normalized.
865 ///
866 /// Note that addition is not the same as combining the rotations represented by the
867 /// two quaternions! That corresponds to multiplication.
868 #[inline]
869 fn add(self, rhs: Self) -> Self {
870 Self::from_vec4(Vec4::from(self) + Vec4::from(rhs))
871 }
872 }
873
874 impl Add<&Self> for Quat {
875 type Output = Self;
876 #[inline]
877 fn add(self, rhs: &Self) -> Self {
878 self.add(*rhs)
879 }
880 }
881
882 impl Add<&Quat> for &Quat {
883 type Output = Quat;
884 #[inline]
885 fn add(self, rhs: &Quat) -> Quat {
886 (*self).add(*rhs)
887 }
888 }
889
890 impl Add<Quat> for &Quat {
891 type Output = Quat;
892 #[inline]
893 fn add(self, rhs: Quat) -> Quat {
894 (*self).add(rhs)
895 }
896 }
897
898 impl AddAssign for Quat {
899 #[inline]
900 fn add_assign(&mut self, rhs: Self) {
901 *self = self.add(rhs);
902 }
903 }
904
905 impl AddAssign<&Self> for Quat {
906 #[inline]
907 fn add_assign(&mut self, rhs: &Self) {
908 self.add_assign(*rhs);
909 }
910 }
911
912 impl Sub for Quat {
913 type Output = Self;
914 /// Subtracts the `rhs` quaternion from `self`.
915 ///
916 /// The difference is not guaranteed to be normalized.
917 #[inline]
918 fn sub(self, rhs: Self) -> Self {
919 Self::from_vec4(Vec4::from(self) - Vec4::from(rhs))
920 }
921 }
922
923 impl Sub<&Self> for Quat {
924 type Output = Self;
925 #[inline]
926 fn sub(self, rhs: &Self) -> Self {
927 self.sub(*rhs)
928 }
929 }
930
931 impl Sub<&Quat> for &Quat {
932 type Output = Quat;
933 #[inline]
934 fn sub(self, rhs: &Quat) -> Quat {
935 (*self).sub(*rhs)
936 }
937 }
938
939 impl Sub<Quat> for &Quat {
940 type Output = Quat;
941 #[inline]
942 fn sub(self, rhs: Quat) -> Quat {
943 (*self).sub(rhs)
944 }
945 }
946
947 impl SubAssign for Quat {
948 #[inline]
949 fn sub_assign(&mut self, rhs: Self) {
950 *self = self.sub(rhs);
951 }
952 }
953
954 impl SubAssign<&Self> for Quat {
955 #[inline]
956 fn sub_assign(&mut self, rhs: &Self) {
957 self.sub_assign(*rhs);
958 }
959 }
960
961 impl Mul<f32> for Quat {
962 type Output = Self;
963 /// Multiplies a quaternion by a scalar value.
964 ///
965 /// The product is not guaranteed to be normalized.
966 #[inline]
967 fn mul(self, rhs: f32) -> Self {
968 Self::from_vec4(Vec4::from(self) * rhs)
969 }
970 }
971
972 impl Mul<&f32> for Quat {
973 type Output = Self;
974 #[inline]
975 fn mul(self, rhs: &f32) -> Self {
976 self.mul(*rhs)
977 }
978 }
979
980 impl Mul<&f32> for &Quat {
981 type Output = Quat;
982 #[inline]
983 fn mul(self, rhs: &f32) -> Quat {
984 (*self).mul(*rhs)
985 }
986 }
987
988 impl Mul<f32> for &Quat {
989 type Output = Quat;
990 #[inline]
991 fn mul(self, rhs: f32) -> Quat {
992 (*self).mul(rhs)
993 }
994 }
995
996 impl MulAssign<f32> for Quat {
997 #[inline]
998 fn mul_assign(&mut self, rhs: f32) {
999 *self = self.mul(rhs);
1000 }
1001 }
1002
1003 impl MulAssign<&f32> for Quat {
1004 #[inline]
1005 fn mul_assign(&mut self, rhs: &f32) {
1006 self.mul_assign(*rhs);
1007 }
1008 }
1009
1010 impl Div<f32> for Quat {
1011 type Output = Self;
1012 /// Divides a quaternion by a scalar value.
1013 /// The quotient is not guaranteed to be normalized.
1014 #[inline]
1015 fn div(self, rhs: f32) -> Self {
1016 Self::from_vec4(Vec4::from(self) / rhs)
1017 }
1018 }
1019
1020 impl Div<&f32> for Quat {
1021 type Output = Self;
1022 #[inline]
1023 fn div(self, rhs: &f32) -> Self {
1024 self.div(*rhs)
1025 }
1026 }
1027
1028 impl Div<&f32> for &Quat {
1029 type Output = Quat;
1030 #[inline]
1031 fn div(self, rhs: &f32) -> Quat {
1032 (*self).div(*rhs)
1033 }
1034 }
1035
1036 impl Div<f32> for &Quat {
1037 type Output = Quat;
1038 #[inline]
1039 fn div(self, rhs: f32) -> Quat {
1040 (*self).div(rhs)
1041 }
1042 }
1043
1044 impl DivAssign<f32> for Quat {
1045 #[inline]
1046 fn div_assign(&mut self, rhs: f32) {
1047 *self = self.div(rhs);
1048 }
1049 }
1050
1051 impl DivAssign<&f32> for Quat {
1052 #[inline]
1053 fn div_assign(&mut self, rhs: &f32) {
1054 self.div_assign(*rhs);
1055 }
1056 }
1057
1058 impl Mul for Quat {
1059 type Output = Self;
1060 /// Multiplies two quaternions. If they each represent a rotation, the result will
1061 /// represent the combined rotation.
1062 ///
1063 /// Note that due to floating point rounding the result may not be perfectly
1064 /// normalized.
1065 ///
1066 /// # Panics
1067 ///
1068 /// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
1069 #[inline]
1070 fn mul(self, rhs: Self) -> Self {
1071 self.mul_quat(rhs)
1072 }
1073 }
1074
1075 impl Mul<&Self> for Quat {
1076 type Output = Self;
1077 #[inline]
1078 fn mul(self, rhs: &Self) -> Self {
1079 self.mul(*rhs)
1080 }
1081 }
1082
1083 impl Mul<&Quat> for &Quat {
1084 type Output = Quat;
1085 #[inline]
1086 fn mul(self, rhs: &Quat) -> Quat {
1087 (*self).mul(*rhs)
1088 }
1089 }
1090
1091 impl Mul<Quat> for &Quat {
1092 type Output = Quat;
1093 #[inline]
1094 fn mul(self, rhs: Quat) -> Quat {
1095 (*self).mul(rhs)
1096 }
1097 }
1098
1099 impl MulAssign for Quat {
1100 #[inline]
1101 fn mul_assign(&mut self, rhs: Self) {
1102 *self = self.mul(rhs);
1103 }
1104 }
1105
1106 impl MulAssign<&Self> for Quat {
1107 #[inline]
1108 fn mul_assign(&mut self, rhs: &Self) {
1109 self.mul_assign(*rhs);
1110 }
1111 }
1112
1113 impl Mul<Vec3> for Quat {
1114 type Output = Vec3;
1115 /// Multiplies a quaternion and a 3D vector, returning the rotated vector.
1116 ///
1117 /// # Panics
1118 ///
1119 /// Will panic if `self` is not normalized when `glam_assert` is enabled.
1120 #[inline]
1121 fn mul(self, rhs: Vec3) -> Self::Output {
1122 self.mul_vec3(rhs)
1123 }
1124 }
1125
1126 impl Mul<&Vec3> for Quat {
1127 type Output = Vec3;
1128 #[inline]
1129 fn mul(self, rhs: &Vec3) -> Vec3 {
1130 self.mul(*rhs)
1131 }
1132 }
1133
1134 impl Mul<&Vec3> for &Quat {
1135 type Output = Vec3;
1136 #[inline]
1137 fn mul(self, rhs: &Vec3) -> Vec3 {
1138 (*self).mul(*rhs)
1139 }
1140 }
1141
1142 impl Mul<Vec3> for &Quat {
1143 type Output = Vec3;
1144 #[inline]
1145 fn mul(self, rhs: Vec3) -> Vec3 {
1146 (*self).mul(rhs)
1147 }
1148 }
1149
1150 impl Mul<Vec3A> for Quat {
1151 type Output = Vec3A;
1152 #[inline]
1153 fn mul(self, rhs: Vec3A) -> Self::Output {
1154 self.mul_vec3a(rhs)
1155 }
1156 }
1157
1158 impl Mul<&Vec3A> for Quat {
1159 type Output = Vec3A;
1160 #[inline]
1161 fn mul(self, rhs: &Vec3A) -> Vec3A {
1162 self.mul(*rhs)
1163 }
1164 }
1165
1166 impl Mul<&Vec3A> for &Quat {
1167 type Output = Vec3A;
1168 #[inline]
1169 fn mul(self, rhs: &Vec3A) -> Vec3A {
1170 (*self).mul(*rhs)
1171 }
1172 }
1173
1174 impl Mul<Vec3A> for &Quat {
1175 type Output = Vec3A;
1176 #[inline]
1177 fn mul(self, rhs: Vec3A) -> Vec3A {
1178 (*self).mul(rhs)
1179 }
1180 }
1181
1182 impl Neg for Quat {
1183 type Output = Self;
1184 #[inline]
1185 fn neg(self) -> Self {
1186 self * -1.0
1187 }
1188 }
1189
1190 impl Neg for &Quat {
1191 type Output = Quat;
1192 #[inline]
1193 fn neg(self) -> Quat {
1194 (*self).neg()
1195 }
1196 }
1197
1198 impl Default for Quat {
1199 #[inline]
1200 fn default() -> Self {
1201 Self::IDENTITY
1202 }
1203 }
1204
1205 impl PartialEq for Quat {
1206 #[inline]
1207 fn eq(&self, rhs: &Self) -> bool {
1208 Vec4::from(*self).eq(&Vec4::from(*rhs))
1209 }
1210 }
1211
1212 impl AsRef<[f32; 4]> for Quat {
1213 #[inline]
1214 fn as_ref(&self) -> &[f32; 4] {
1215 unsafe { &*(self as *const Self as *const [f32; 4]) }
1216 }
1217 }
1218
1219 impl Sum<Self> for Quat {
1220 fn sum<I>(iter: I) -> Self
1221 where
1222 I: Iterator<Item = Self>,
1223 {
1224 iter.fold(Self::ZERO, Self::add)
1225 }
1226 }
1227
1228 impl<'a> Sum<&'a Self> for Quat {
1229 fn sum<I>(iter: I) -> Self
1230 where
1231 I: Iterator<Item = &'a Self>,
1232 {
1233 iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
1234 }
1235 }
1236
1237 impl Product for Quat {
1238 fn product<I>(iter: I) -> Self
1239 where
1240 I: Iterator<Item = Self>,
1241 {
1242 iter.fold(Self::IDENTITY, Self::mul)
1243 }
1244 }
1245
1246 impl<'a> Product<&'a Self> for Quat {
1247 fn product<I>(iter: I) -> Self
1248 where
1249 I: Iterator<Item = &'a Self>,
1250 {
1251 iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
1252 }
1253 }
1254
1255 impl From<Quat> for Vec4 {
1256 #[inline]
1257 fn from(q: Quat) -> Self {
1258 Self::new(q.x, q.y, q.z, q.w)
1259 }
1260 }
1261
1262 impl From<Quat> for (f32, f32, f32, f32) {
1263 #[inline]
1264 fn from(q: Quat) -> Self {
1265 (q.x, q.y, q.z, q.w)
1266 }
1267 }
1268
1269 impl From<Quat> for [f32; 4] {
1270 #[inline]
1271 fn from(q: Quat) -> Self {
1272 [q.x, q.y, q.z, q.w]
1273 }
1274 }