Quat.h 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Math/Vec3.h>
  6. #include <Jolt/Math/Vec4.h>
  7. JPH_NAMESPACE_BEGIN
  8. /// Quaternion class, quaternions are 4 dimensional vectors which can describe rotations in 3 dimensional
  9. /// space if their length is 1.
  10. ///
  11. /// They are written as:
  12. ///
  13. /// \f$q = w + x \: i + y \: j + z \: k\f$
  14. ///
  15. /// or in vector notation:
  16. ///
  17. /// \f$q = [w, v] = [w, x, y, z]\f$
  18. ///
  19. /// Where:
  20. ///
  21. /// w = the real part
  22. /// v = the imaginary part, (x, y, z)
  23. ///
  24. /// Note that we store the quaternion in a Vec4 as [x, y, z, w] because that makes
  25. /// it easy to extract the rotation axis of the quaternion:
  26. ///
  27. /// q = [cos(angle / 2), sin(angle / 2) * rotation_axis]
  28. class [[nodiscard]] alignas(JPH_VECTOR_ALIGNMENT) Quat
  29. {
  30. public:
  31. JPH_OVERRIDE_NEW_DELETE
  32. ///@name Constructors
  33. ///@{
  34. inline Quat() = default; ///< Intentionally not initialized for performance reasons
  35. Quat(const Quat &inRHS) = default;
  36. inline Quat(float inX, float inY, float inZ, float inW) : mValue(inX, inY, inZ, inW) { }
  37. inline explicit Quat(Vec4Arg inV) : mValue(inV) { }
  38. ///@}
  39. ///@name Tests
  40. ///@{
  41. /// Check if two quaternions are exactly equal
  42. inline bool operator == (QuatArg inRHS) const { return mValue == inRHS.mValue; }
  43. /// Check if two quaternions are different
  44. inline bool operator != (QuatArg inRHS) const { return mValue != inRHS.mValue; }
  45. /// If this quaternion is close to inRHS. Note that q and -q represent the same rotation, this is not checked here.
  46. inline bool IsClose(QuatArg inRHS, float inMaxDistSq = 1.0e-12f) const { return mValue.IsClose(inRHS.mValue, inMaxDistSq); }
  47. /// If the length of this quaternion is 1 +/- inTolerance
  48. inline bool IsNormalized(float inTolerance = 1.0e-5f) const { return mValue.IsNormalized(inTolerance); }
  49. /// If any component of this quaternion is a NaN (not a number)
  50. inline bool IsNaN() const { return mValue.IsNaN(); }
  51. ///@}
  52. ///@name Get components
  53. ///@{
  54. /// Get X component (imaginary part i)
  55. JPH_INLINE float GetX() const { return mValue.GetX(); }
  56. /// Get Y component (imaginary part j)
  57. JPH_INLINE float GetY() const { return mValue.GetY(); }
  58. /// Get Z component (imaginary part k)
  59. JPH_INLINE float GetZ() const { return mValue.GetZ(); }
  60. /// Get W component (real part)
  61. JPH_INLINE float GetW() const { return mValue.GetW(); }
  62. /// Get the imaginary part of the quaternion
  63. JPH_INLINE Vec3 GetXYZ() const { return Vec3(mValue); }
  64. /// Get the quaternion as a Vec4
  65. JPH_INLINE Vec4 GetXYZW() const { return mValue; }
  66. ///@}
  67. ///@name Default quaternions
  68. ///@{
  69. /// @return [0, 0, 0, 0]
  70. JPH_INLINE static Quat sZero() { return Quat(Vec4::sZero()); }
  71. /// @return [1, 0, 0, 0] (or in storage format Quat(0, 0, 0, 1))
  72. JPH_INLINE static Quat sIdentity() { return Quat(0, 0, 0, 1); }
  73. ///@}
  74. /// Rotation from axis and angle
  75. JPH_INLINE static Quat sRotation(Vec3Arg inAxis, float inAngle);
  76. /// Get axis and angle that represents this quaternion, outAngle will always be in the range \f$[0, \pi]\f$
  77. JPH_INLINE void GetAxisAngle(Vec3 &outAxis, float &outAngle) const;
  78. /// Create quaternion that rotates a vector from the direction of inFrom to the direction of inTo along the shortest path
  79. /// @see https://www.euclideanspace.com/maths/algebra/vectors/angleBetween/index.htm
  80. JPH_INLINE static Quat sFromTo(Vec3Arg inFrom, Vec3Arg inTo);
  81. /// Random unit quaternion
  82. template <class Random>
  83. inline static Quat sRandom(Random &inRandom);
  84. /// Conversion from Euler angles
  85. inline static Quat sEulerAngles(Vec3Arg inAngles);
  86. /// Conversion to Euler angles
  87. inline Vec3 GetEulerAngles() const;
  88. ///@name Length / normalization operations
  89. ///@{
  90. /// Squared length of quaternion.
  91. /// @return Squared length of quaternion (\f$|v|^2\f$)
  92. JPH_INLINE float LengthSq() const { return mValue.LengthSq(); }
  93. /// Length of quaternion.
  94. /// @return Length of quaternion (\f$|v|\f$)
  95. JPH_INLINE float Length() const { return mValue.Length(); }
  96. /// Normalize the quaternion (make it length 1)
  97. JPH_INLINE Quat Normalized() const { return Quat(mValue.Normalized()); }
  98. ///@}
  99. ///@name Additions / multiplications
  100. ///@{
  101. JPH_INLINE void operator += (QuatArg inRHS) { mValue += inRHS.mValue; }
  102. JPH_INLINE void operator -= (QuatArg inRHS) { mValue -= inRHS.mValue; }
  103. JPH_INLINE void operator *= (float inValue) { mValue *= inValue; }
  104. JPH_INLINE void operator /= (float inValue) { mValue /= inValue; }
  105. JPH_INLINE Quat operator - () const { return Quat(-mValue); }
  106. JPH_INLINE Quat operator + (QuatArg inRHS) const { return Quat(mValue + inRHS.mValue); }
  107. JPH_INLINE Quat operator - (QuatArg inRHS) const { return Quat(mValue - inRHS.mValue); }
  108. JPH_INLINE Quat operator * (QuatArg inRHS) const;
  109. JPH_INLINE Quat operator * (float inValue) const { return Quat(mValue * inValue); }
  110. inline friend Quat operator * (float inValue, QuatArg inRHS) { return Quat(inRHS.mValue * inValue); }
  111. JPH_INLINE Quat operator / (float inValue) const { return Quat(mValue / inValue); }
  112. ///@}
  113. /// Rotate a vector by this quaternion
  114. JPH_INLINE Vec3 operator * (Vec3Arg inValue) const;
  115. /// Rotate a vector by the inverse of this quaternion
  116. JPH_INLINE Vec3 InverseRotate(Vec3Arg inValue) const;
  117. /// Rotate a the vector (1, 0, 0) with this quaternion
  118. JPH_INLINE Vec3 RotateAxisX() const;
  119. /// Rotate a the vector (0, 1, 0) with this quaternion
  120. JPH_INLINE Vec3 RotateAxisY() const;
  121. /// Rotate a the vector (0, 0, 1) with this quaternion
  122. JPH_INLINE Vec3 RotateAxisZ() const;
  123. /// Dot product
  124. JPH_INLINE float Dot(QuatArg inRHS) const { return mValue.Dot(inRHS.mValue); }
  125. /// The conjugate [w, -x, -y, -z] is the same as the inverse for unit quaternions
  126. JPH_INLINE Quat Conjugated() const { return Quat(Vec4::sXor(mValue, UVec4(0x80000000, 0x80000000, 0x80000000, 0).ReinterpretAsFloat())); }
  127. /// Get inverse quaternion
  128. JPH_INLINE Quat Inversed() const { return Conjugated() / Length(); }
  129. /// Ensures that the W component is positive by negating the entire quaternion if it is not. This is useful when you want to store a quaternion as a 3 vector by discarding W and reconstructing it as sqrt(1 - x^2 - y^2 - z^2).
  130. JPH_INLINE Quat EnsureWPositive() const { return Quat(Vec4::sXor(mValue, Vec4::sAnd(mValue.SplatW(), UVec4::sReplicate(0x80000000).ReinterpretAsFloat()))); }
  131. /// Get a quaternion that is perpendicular to this quaternion
  132. JPH_INLINE Quat GetPerpendicular() const { return Quat(Vec4(1, -1, 1, -1) * mValue.Swizzle<SWIZZLE_Y, SWIZZLE_X, SWIZZLE_W, SWIZZLE_Z>()); }
  133. /// Get rotation angle around inAxis (uses Swing Twist Decomposition to get the twist quaternion and uses q(axis, angle) = [cos(angle / 2), axis * sin(angle / 2)])
  134. JPH_INLINE float GetRotationAngle(Vec3Arg inAxis) const { return GetW() == 0.0f? JPH_PI : 2.0f * ATan(GetXYZ().Dot(inAxis) / GetW()); }
  135. /// Swing Twist Decomposition: any quaternion can be split up as:
  136. ///
  137. /// \f[q = q_{swing} \: q_{twist}\f]
  138. ///
  139. /// where \f$q_{twist}\f$ rotates only around axis v.
  140. ///
  141. /// \f$q_{twist}\f$ is:
  142. ///
  143. /// \f[q_{twist} = \frac{[q_w, q_{ijk} \cdot v \: v]}{\left|[q_w, q_{ijk} \cdot v \: v]\right|}\f]
  144. ///
  145. /// where q_w is the real part of the quaternion and q_i the imaginary part (a 3 vector).
  146. ///
  147. /// The swing can then be calculated as:
  148. ///
  149. /// \f[q_{swing} = q \: q_{twist}^* \f]
  150. ///
  151. /// Where \f$q_{twist}^*\f$ = complex conjugate of \f$q_{twist}\f$
  152. JPH_INLINE Quat GetTwist(Vec3Arg inAxis) const;
  153. /// Decomposes quaternion into swing and twist component:
  154. ///
  155. /// \f$q = q_{swing} \: q_{twist}\f$
  156. ///
  157. /// where \f$q_{swing} \: \hat{x} = q_{twist} \: \hat{y} = q_{twist} \: \hat{z} = 0\f$
  158. ///
  159. /// In other words:
  160. ///
  161. /// - \f$q_{twist}\f$ only rotates around the X-axis.
  162. /// - \f$q_{swing}\f$ only rotates around the Y and Z-axis.
  163. ///
  164. /// @see Gino van den Bergen - Rotational Joint Limits in Quaternion Space - GDC 2016
  165. JPH_INLINE void GetSwingTwist(Quat &outSwing, Quat &outTwist) const;
  166. /// Linear interpolation between two quaternions (for small steps).
  167. /// @param inFraction is in the range [0, 1]
  168. /// @param inDestination The destination quaternion
  169. /// @return (1 - inFraction) * this + fraction * inDestination
  170. JPH_INLINE Quat LERP(QuatArg inDestination, float inFraction) const;
  171. /// Spherical linear interpolation between two quaternions.
  172. /// @param inFraction is in the range [0, 1]
  173. /// @param inDestination The destination quaternion
  174. /// @return When fraction is zero this quaternion is returned, when fraction is 1 inDestination is returned.
  175. /// When fraction is between 0 and 1 an interpolation along the shortest path is returned.
  176. JPH_INLINE Quat SLERP(QuatArg inDestination, float inFraction) const;
  177. /// Load 3 floats from memory (X, Y and Z component and then calculates W) reads 32 bits extra which it doesn't use
  178. static JPH_INLINE Quat sLoadFloat3Unsafe(const Float3 &inV);
  179. /// Store 3 as floats to memory (X, Y and Z component)
  180. JPH_INLINE void StoreFloat3(Float3 *outV) const;
  181. /// To String
  182. friend ostream & operator << (ostream &inStream, QuatArg inQ) { inStream << inQ.mValue; return inStream; }
  183. /// 4 vector that stores [x, y, z, w] parts of the quaternion
  184. Vec4 mValue;
  185. };
  186. static_assert(is_trivial<Quat>(), "Is supposed to be a trivial type!");
  187. JPH_NAMESPACE_END
  188. #include "Quat.inl"