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