Path: blob/master/thirdparty/jolt_physics/Jolt/Math/Quat.h
21732 views
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)1// SPDX-FileCopyrightText: 2021 Jorrit Rouwe2// SPDX-License-Identifier: MIT34#pragma once56#include <Jolt/Math/Vec3.h>7#include <Jolt/Math/Vec4.h>89JPH_NAMESPACE_BEGIN1011/// Quaternion class, quaternions are 4 dimensional vectors which can describe rotations in 3 dimensional12/// space if their length is 1.13///14/// They are written as:15///16/// \f$q = w + x \: i + y \: j + z \: k\f$17///18/// or in vector notation:19///20/// \f$q = [w, v] = [w, x, y, z]\f$21///22/// Where:23///24/// w = the real part25/// v = the imaginary part, (x, y, z)26///27/// Note that we store the quaternion in a Vec4 as [x, y, z, w] because that makes28/// it easy to extract the rotation axis of the quaternion:29///30/// q = [cos(angle / 2), sin(angle / 2) * rotation_axis]31class [[nodiscard]] alignas(JPH_VECTOR_ALIGNMENT) Quat32{33public:34JPH_OVERRIDE_NEW_DELETE3536///@name Constructors37///@{38inline Quat() = default; ///< Intentionally not initialized for performance reasons39Quat(const Quat &inRHS) = default;40Quat & operator = (const Quat &inRHS) = default;41inline Quat(float inX, float inY, float inZ, float inW) : mValue(inX, inY, inZ, inW) { }42inline explicit Quat(const Float4 &inV) : mValue(Vec4::sLoadFloat4(&inV)) { }43inline explicit Quat(Vec4Arg inV) : mValue(inV) { }44///@}4546///@name Tests47///@{4849/// Check if two quaternions are exactly equal50inline bool operator == (QuatArg inRHS) const { return mValue == inRHS.mValue; }5152/// Check if two quaternions are different53inline bool operator != (QuatArg inRHS) const { return mValue != inRHS.mValue; }5455/// If this quaternion is close to inRHS. Note that q and -q represent the same rotation, this is not checked here.56inline bool IsClose(QuatArg inRHS, float inMaxDistSq = 1.0e-12f) const { return mValue.IsClose(inRHS.mValue, inMaxDistSq); }5758/// If the length of this quaternion is 1 +/- inTolerance59inline bool IsNormalized(float inTolerance = 1.0e-5f) const { return mValue.IsNormalized(inTolerance); }6061/// If any component of this quaternion is a NaN (not a number)62inline bool IsNaN() const { return mValue.IsNaN(); }6364///@}65///@name Get components66///@{6768/// Get X component (imaginary part i)69JPH_INLINE float GetX() const { return mValue.GetX(); }7071/// Get Y component (imaginary part j)72JPH_INLINE float GetY() const { return mValue.GetY(); }7374/// Get Z component (imaginary part k)75JPH_INLINE float GetZ() const { return mValue.GetZ(); }7677/// Get W component (real part)78JPH_INLINE float GetW() const { return mValue.GetW(); }7980/// Get the imaginary part of the quaternion81JPH_INLINE Vec3 GetXYZ() const { return Vec3(mValue); }8283/// Get the quaternion as a Vec484JPH_INLINE Vec4 GetXYZW() const { return mValue; }8586/// Set individual components87JPH_INLINE void SetX(float inX) { mValue.SetX(inX); }88JPH_INLINE void SetY(float inY) { mValue.SetY(inY); }89JPH_INLINE void SetZ(float inZ) { mValue.SetZ(inZ); }90JPH_INLINE void SetW(float inW) { mValue.SetW(inW); }9192/// Set all components93JPH_INLINE void Set(float inX, float inY, float inZ, float inW) { mValue.Set(inX, inY, inZ, inW); }9495///@}96///@name Default quaternions97///@{9899/// @return [0, 0, 0, 0]100JPH_INLINE static Quat sZero() { return Quat(Vec4::sZero()); }101102/// @return [1, 0, 0, 0] (or in storage format Quat(0, 0, 0, 1))103JPH_INLINE static Quat sIdentity() { return Quat(0, 0, 0, 1); }104105///@}106107/// Rotation from axis and angle108JPH_INLINE static Quat sRotation(Vec3Arg inAxis, float inAngle);109110/// Get axis and angle that represents this quaternion, outAngle will always be in the range \f$[0, \pi]\f$111JPH_INLINE void GetAxisAngle(Vec3 &outAxis, float &outAngle) const;112113/// Calculate angular velocity given that this quaternion represents the rotation that is reached after inDeltaTime when starting from identity rotation114JPH_INLINE Vec3 GetAngularVelocity(float inDeltaTime) const;115116/// Create quaternion that rotates a vector from the direction of inFrom to the direction of inTo along the shortest path117/// @see https://www.euclideanspace.com/maths/algebra/vectors/angleBetween/index.htm118JPH_INLINE static Quat sFromTo(Vec3Arg inFrom, Vec3Arg inTo);119120/// Random unit quaternion121template <class Random>122inline static Quat sRandom(Random &inRandom);123124/// Conversion from Euler angles. Rotation order is X then Y then Z (RotZ * RotY * RotX). Angles in radians.125inline static Quat sEulerAngles(Vec3Arg inAngles);126127/// Conversion to Euler angles. Rotation order is X then Y then Z (RotZ * RotY * RotX). Angles in radians.128inline Vec3 GetEulerAngles() const;129130///@name Length / normalization operations131///@{132133/// Squared length of quaternion.134/// @return Squared length of quaternion (\f$|v|^2\f$)135JPH_INLINE float LengthSq() const { return mValue.LengthSq(); }136137/// Length of quaternion.138/// @return Length of quaternion (\f$|v|\f$)139JPH_INLINE float Length() const { return mValue.Length(); }140141/// Normalize the quaternion (make it length 1)142JPH_INLINE Quat Normalized() const { return Quat(mValue.Normalized()); }143144///@}145///@name Additions / multiplications146///@{147148JPH_INLINE void operator += (QuatArg inRHS) { mValue += inRHS.mValue; }149JPH_INLINE void operator -= (QuatArg inRHS) { mValue -= inRHS.mValue; }150JPH_INLINE void operator *= (float inValue) { mValue *= inValue; }151JPH_INLINE void operator /= (float inValue) { mValue /= inValue; }152JPH_INLINE Quat operator - () const { return Quat(-mValue); }153JPH_INLINE Quat operator + (QuatArg inRHS) const { return Quat(mValue + inRHS.mValue); }154JPH_INLINE Quat operator - (QuatArg inRHS) const { return Quat(mValue - inRHS.mValue); }155JPH_INLINE Quat operator * (QuatArg inRHS) const;156JPH_INLINE Quat operator * (float inValue) const { return Quat(mValue * inValue); }157inline friend Quat operator * (float inValue, QuatArg inRHS) { return Quat(inRHS.mValue * inValue); }158JPH_INLINE Quat operator / (float inValue) const { return Quat(mValue / inValue); }159160///@}161162/// Rotate a vector by this quaternion163JPH_INLINE Vec3 operator * (Vec3Arg inValue) const;164165/// Multiply a quaternion with imaginary components and no real component (x, y, z, 0) with a quaternion166static JPH_INLINE Quat sMultiplyImaginary(Vec3Arg inLHS, QuatArg inRHS);167168/// Rotate a vector by the inverse of this quaternion169JPH_INLINE Vec3 InverseRotate(Vec3Arg inValue) const;170171/// Rotate a the vector (1, 0, 0) with this quaternion172JPH_INLINE Vec3 RotateAxisX() const;173174/// Rotate a the vector (0, 1, 0) with this quaternion175JPH_INLINE Vec3 RotateAxisY() const;176177/// Rotate a the vector (0, 0, 1) with this quaternion178JPH_INLINE Vec3 RotateAxisZ() const;179180/// Dot product181JPH_INLINE float Dot(QuatArg inRHS) const { return mValue.Dot(inRHS.mValue); }182183/// The conjugate [w, -x, -y, -z] is the same as the inverse for unit quaternions184JPH_INLINE Quat Conjugated() const { return Quat(mValue.FlipSign<-1, -1, -1, 1>()); }185186/// Get inverse quaternion187JPH_INLINE Quat Inversed() const { return Conjugated() / Length(); }188189/// 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).190JPH_INLINE Quat EnsureWPositive() const { return Quat(Vec4::sXor(mValue, Vec4::sAnd(mValue.SplatW(), UVec4::sReplicate(0x80000000).ReinterpretAsFloat()))); }191192/// Get a quaternion that is perpendicular to this quaternion193JPH_INLINE Quat GetPerpendicular() const { return Quat(mValue.Swizzle<SWIZZLE_Y, SWIZZLE_X, SWIZZLE_W, SWIZZLE_Z>().FlipSign<1, -1, 1, -1>()); }194195/// 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)])196JPH_INLINE float GetRotationAngle(Vec3Arg inAxis) const { return GetW() == 0.0f? JPH_PI : 2.0f * ATan(GetXYZ().Dot(inAxis) / GetW()); }197198/// Swing Twist Decomposition: any quaternion can be split up as:199///200/// \f[q = q_{swing} \: q_{twist}\f]201///202/// where \f$q_{twist}\f$ rotates only around axis v.203///204/// \f$q_{twist}\f$ is:205///206/// \f[q_{twist} = \frac{[q_w, q_{ijk} \cdot v \: v]}{\left|[q_w, q_{ijk} \cdot v \: v]\right|}\f]207///208/// where q_w is the real part of the quaternion and q_i the imaginary part (a 3 vector).209///210/// The swing can then be calculated as:211///212/// \f[q_{swing} = q \: q_{twist}^* \f]213///214/// Where \f$q_{twist}^*\f$ = complex conjugate of \f$q_{twist}\f$215JPH_INLINE Quat GetTwist(Vec3Arg inAxis) const;216217/// Decomposes quaternion into swing and twist component:218///219/// \f$q = q_{swing} \: q_{twist}\f$220///221/// where \f$q_{swing} \: \hat{x} = q_{twist} \: \hat{y} = q_{twist} \: \hat{z} = 0\f$222///223/// In other words:224///225/// - \f$q_{twist}\f$ only rotates around the X-axis.226/// - \f$q_{swing}\f$ only rotates around the Y and Z-axis.227///228/// @see Gino van den Bergen - Rotational Joint Limits in Quaternion Space - GDC 2016229JPH_INLINE void GetSwingTwist(Quat &outSwing, Quat &outTwist) const;230231/// Linear interpolation between two quaternions (for small steps).232/// @param inFraction is in the range [0, 1]233/// @param inDestination The destination quaternion234/// @return (1 - inFraction) * this + fraction * inDestination235JPH_INLINE Quat LERP(QuatArg inDestination, float inFraction) const;236237/// Spherical linear interpolation between two quaternions.238/// @param inFraction is in the range [0, 1]239/// @param inDestination The destination quaternion240/// @return When fraction is zero this quaternion is returned, when fraction is 1 inDestination is returned.241/// When fraction is between 0 and 1 an interpolation along the shortest path is returned.242JPH_INLINE Quat SLERP(QuatArg inDestination, float inFraction) const;243244/// Load 3 floats from memory (X, Y and Z component and then calculates W) reads 32 bits extra which it doesn't use245static JPH_INLINE Quat sLoadFloat3Unsafe(const Float3 &inV);246247/// Store as 3 floats to memory (X, Y and Z component). Ensures that W is positive before storing.248JPH_INLINE void StoreFloat3(Float3 *outV) const;249250/// Store as 4 floats251JPH_INLINE void StoreFloat4(Float4 *outV) const;252253/// Compress a unit quaternion to a 32 bit value, precision is around 0.5 degree254JPH_INLINE uint32 CompressUnitQuat() const { return mValue.CompressUnitVector(); }255256/// Decompress a unit quaternion from a 32 bit value257JPH_INLINE static Quat sDecompressUnitQuat(uint32 inValue) { return Quat(Vec4::sDecompressUnitVector(inValue)); }258259/// To String260friend ostream & operator << (ostream &inStream, QuatArg inQ) { inStream << inQ.mValue; return inStream; }261262/// 4 vector that stores [x, y, z, w] parts of the quaternion263Vec4 mValue;264};265266static_assert(std::is_trivial<Quat>(), "Is supposed to be a trivial type!");267268JPH_NAMESPACE_END269270#include "Quat.inl"271272273