SuperDex Physics C++ API
Loading...
Searching...
No Matches
quaternion_inl.h
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
19#include "quaternion.h" // For IntelliSense
20
21namespace superdex {
22
23/************************************************************************************
24 Quaternion Inlines
25*/
29
33
35 return Quaternion{Sin(a * 0.5_r), 0_r, 0_r, Cos(a * 0.5_r)};
36}
37
39 return Quaternion{0_r, Sin(a * 0.5_r), 0_r, Cos(a * 0.5_r)};
40}
41
43 return Quaternion{0_r, 0_r, Sin(a * 0.5_r), Cos(a * 0.5_r)};
44}
45
47 return Real4{data[0], data[1], data[2], data[3]};
48}
49
50inline Quaternion Quaternion::FromUnitAxisAngle(Vec4r normalizedAxis, real angleRadians) {
51 // Log a warning in debug builds if the axis is not unit length (non-fatal unlike an assert).
52#if MOCHI_ASSERT_VERBOSE_ENABLED && MOCHI_LOG_ENABLED
53 auto norm = Norm<3>(normalizedAxis);
56 "Quaternion::FromUnitAxisAngle expects a unit length vector, but got [%g, %g, %g] (magnitude %g).",
57 normalizedAxis[0],
58 normalizedAxis[1],
59 normalizedAxis[2],
60 norm);
61 }
62#endif
63 // Use double precision to avoid rounding error in the trig functions.
64 double c = Cos(static_cast<double>(angleRadians) * 0.5);
65 double s = Sin(static_cast<double>(angleRadians) * 0.5);
66 Vec4d v = Set<3>(StaticCast<Vec4d>(normalizedAxis) * s, c);
68}
69
70inline Quaternion Quaternion::FromAxisAngle(Vec4r axis, real angleRadians) {
71 return FromUnitAxisAngle(Normalize<3>(axis), angleRadians);
72}
73
74inline Quaternion Quaternion::FromAxisAngle(Real3 const& axis, real angleRadians) {
75 return FromAxisAngle(Vec4r{axis[0], axis[1], axis[2], 0_r}, angleRadians);
76}
77
79 Vec4r angle = VNorm<3>(rotVector);
80 real rangle = Get0(angle);
81 if (rangle > 1e-9_r) MOCHI_LIKELY {
82 Vec4r axis = ToSimdDirection(rotVector) / angle;
83 return FromUnitAxisAngle(axis, rangle);
84 } else {
85 // q = (xyz, w)
86 // xyz = v/|v| * sin(|v|/2) ≈ v/|v| * |v|/2 = 0.5 * v
87 // w = cos(|v|/2) ≈ 1 - |v|^2/8 ≈ 1
88 return Quaternion(ToSimdPoint(0.5_r * rotVector));
89 }
90}
91
93 Vec4r vrotVector(rotVector[0], rotVector[1], rotVector[2], 0.0_r);
94 return FromRotationVector(vrotVector);
95}
96
97inline real Quaternion::GetAngleImpl(Quaternion& qPositiveNormalized, real& vectorMag) const {
98 // We compute the angle using the part of the quaternion (the vector part (x, y, z) or the scalar
99 // part w) that is smaller, as this provides higher precision.
100 qPositiveNormalized = Quaternion{Normalize<4>(this->data)};
101 // For simplicity, use always the quaternion with positive scalar part.
102 if (qPositiveNormalized.data[3] < 0_r) {
103 qPositiveNormalized.data = -qPositiveNormalized.data;
104 }
105 real w = qPositiveNormalized.data[3]; // Scalar part (always >= 0)
106 vectorMag = Norm<3>(qPositiveNormalized.data); // Norm of the vector part
107 // Note that vectorMag^2 + w^2 = 1. However, we do not compute vectorMag = sqrt(1 - w^2) to avoid
108 // catastrophic cancellation when vectorMag is small but w = 1. This can often happen with single
109 // precision for small angles.
110 return 2_r * (w < vectorMag ? ACos(w) : ASin(vectorMag));
111}
112
114 Quaternion qPositiveNormalized MOCHI_NO_INIT; // discarded
115 real vectorMag MOCHI_NO_INIT; // discarded
116 return GetAngleImpl(qPositiveNormalized, vectorMag);
117}
118
119inline void Quaternion::ToAxisAngle(Real3* outAxis, real* outAngleRad) const {
120 Quaternion qPositiveNormalized MOCHI_NO_INIT;
121 real vectorMag MOCHI_NO_INIT;
122 *outAngleRad = GetAngleImpl(qPositiveNormalized, vectorMag);
123 Vec4r axis{1_r, 0_r, 0_r, 0_r};
124 // Above 1e-9, the squared vector magnitude is well within the normal range in FP32 and FP64.
125 // For smaller magnitudes, dividing by the largest absolute vector component protects the norm
126 // from subnormal precision loss and underflow. The angle uses the small-angle approximation
127 // 2 |v|, where |v| is the original vector magnitude.
128 if (vectorMag > 1e-9_r) MOCHI_LIKELY {
129 axis = qPositiveNormalized.data / vectorMag;
130 } else {
131 real const maxComponent = HMax<3>(Abs(qPositiveNormalized.data));
132 if (maxComponent > 0_r) {
133 Vec4r const scaled = ToSimdDirection(qPositiveNormalized.data) / maxComponent;
134 real const scaledMag = Norm<3>(scaled);
135 axis = scaled / scaledMag;
136 *outAngleRad = 2_r * (maxComponent * scaledMag);
137 }
138 }
139 *outAxis = Real3{axis[0], axis[1], axis[2]};
140}
141
142inline void Quaternion::ToAxisAngle(Vec4r* outAxis, real* outAngleRad) const {
143 Real3 outAxisTemp MOCHI_NO_INIT;
144 this->ToAxisAngle(&outAxisTemp, outAngleRad);
145 *outAxis = Vec4r{outAxisTemp[0], outAxisTemp[1], outAxisTemp[2], 0_r};
146}
147
149 Quaternion qPositiveNormalized MOCHI_NO_INIT;
150 real vectorMag MOCHI_NO_INIT;
151 real const angle = GetAngleImpl(qPositiveNormalized, vectorMag);
152 // For small rotations angle = 2 asin(vectorMag), so angle / vectorMag tends to 2 as
153 // vectorMag vanishes. Below 1e-9, the limit's relative error, vectorMag^2 / 6, is below rounding
154 // in FP32 and FP64.
155 real const scale = vectorMag > 1e-9_r ? angle / vectorMag : 2_r;
156 return ToSimdDirection(qPositiveNormalized.data * scale);
157}
158
160 auto r = VToRotationVector();
161 return Real3{r[0], r[1], r[2]};
162}
163
165 return data == rhs.data;
166}
167
169 return data != rhs.data;
170}
171
184
188
190 // The canonical way to multiply this quaternion q by vector v is:
191 //
192 // v' = q * v * conjugate(q)
193 //
194 // where the vector v is treated as a quaternion with w=0, but that is rather expensive since
195 // quaternion multiplication is not very SIMD friendly (unless you do multiple pairs of
196 // quaternions at once). Fortunately, there is a faster way:
197 //
198 // t = 2 * cross(q.xyz, v)
199 // v' = v + q.w * t + cross(q.xyz, t)
200 //
201 // With the MSVC x64 compiler, this results in 27 total instructions vs 55 instructions for the
202 // canonical approach. A derivation of the formula can be found here:
203 // https://fgiesen.wordpress.com/2019/02/09/rotating-a-single-vector-using-a-quaternion/
204 //
205 Vec4r c = Cross3(this->data, v);
206 Vec4r t = c + c;
207 Vec4r qw = Broadcast<3>(this->data);
208 return MulAdd(qw, t, v) + Cross3(this->data, t);
209}
210
212 auto r = *this * Vec4r{v[0], v[1], v[2], 0_r};
213 return Real3{r[0], r[1], r[2]};
214}
215
219
223
227
228} // namespace superdex
229
230/************************************************************************************
231 Reflection support for Quaternion.
232 Serializes like std::array<real, 4>.
233*/
234#if MOCHI_USE_REFLECTION
235template <>
236struct SReflectTypeTraits<superdex::Quaternion> {
237 static constexpr SReflect::CoreType coreType = SReflect::CoreType::CT_array;
238 static SReflect::ArrayTypeInfo const& GetTypeInfo() {
239 static auto const* s_typeInfo =
240 SReflect::MakeFixedArrayTypeInfo<superdex::Quaternion, superdex::real, 4>("superdex::Quaternion");
241 return *s_typeInfo;
242 }
243};
244#endif // MOCHI_USE_REFLECTION
static Quaternion RotationY(real a)
Quaternion operator*(Quaternion const &rhs) const
static Quaternion FromUnitAxisAngle(Vec4r normalizedAxis, real angleRadians)
Quaternion GetConjugate() const
Real3 ToRotationVector() const
void ToAxisAngle(Real3 *outAxis, real *outAngleRad) const
bool operator!=(Quaternion const &rhs) const
static Quaternion Identity()
static Quaternion RotationX(real a)
bool operator==(Quaternion const &rhs) const
static Quaternion RotationZ(real a)
static Quaternion FromAxisAngle(Vec4r axis, real angleRadians)
static Quaternion Zero()
Quaternion operator-() const
Vec4r VToRotationVector() const
static Quaternion FromRotationVector(Vec4r rotVector)
Quaternion operator+(Quaternion const &a) const
Real4 ToReal4() const
#define MOCHI_LOG_WARNING(...)
Definition log.h:43
#define MOCHI_UNLIKELY
#define MOCHI_FORCE_INLINE
#define MOCHI_LIKELY
#define MOCHI_NO_INIT
constexpr T ACos(T a)
Simd< T, 2 > Shuffle(Simd< T, 2 > a)
Definition simd_inl.h:287
Simd< T, N > Cross3(Simd< T, N > a, Simd< T, N > b)
Definition simd_inl.h:947
constexpr T Sin(T a)
constexpr To StaticCast(From const &a)
Definition basic_utils.h:79
constexpr T kDefaultNearEqualEpsilon
T Norm(Simd< T, N > a)
Definition simd_inl.h:969
V ToSimdDirection(V a)
Definition simd_inl.h:181
Simd< T, N > Set(Simd< T, N > a, T value)
Definition simd_inl.h:327
Simd< real, 4 > Vec4r
Definition simd.h:206
constexpr T Cos(T a)
V SimdZero()
Definition simd_inl.h:148
T HMax(Simd< T, N > a)
Definition simd_inl.h:461
V Broadcast(typename V::Scalar a)
Definition simd_inl.h:117
constexpr T Abs(T a)
Definition basic_utils.h:50
Simd< T, N > Normalize(Simd< T, N > a)
Definition simd_inl.h:974
Simd< double, 4 > Vec4d
Definition simd.h:202
NdArray< real, 3 > Real3
Definition nd_array.h:115
constexpr T ASin(T a)
NdArray< real, 4 > Real4
Definition nd_array.h:116
T Get0(Simd< T, N > v)
Definition simd_inl.h:312
Simd< T, N > VNorm(Simd< T, N > a)
Definition simd_inl.h:959
constexpr T MulAdd(T a, T b, T c)
bool NearEqual(TransformRT const &a, TransformRT const &b, real epsilon=kDefaultNearEqualEpsilon< real >)
Simd< T, N > Neg(Simd< T, N > a)
Definition simd_inl.h:352
V ToSimdPoint(V a)
Definition simd_inl.h:176