Debian Codegraph @

thirdparty/jolt_physics/Jolt/Math/Quat.inl

raw
1 // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
2 // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
3 // SPDX-License-Identifier: MIT
4
5 JPH_NAMESPACE_BEGIN
6
7 Quat Quat::operator * (QuatArg inRHS) const
8 {
9 #if defined(JPH_USE_SSE4_1)
10 // Taken from: http://momchil-velikov.blogspot.nl/2013/10/fast-sse-quternion-multiplication.html
11 __m128 abcd = mValue.mValue;
12 __m128 xyzw = inRHS.mValue.mValue;
13
14 __m128 t0 = _mm_shuffle_ps(abcd, abcd, _MM_SHUFFLE(3, 3, 3, 3));
15 __m128 t1 = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(2, 3, 0, 1));
16
17 __m128 t3 = _mm_shuffle_ps(abcd, abcd, _MM_SHUFFLE(0, 0, 0, 0));
18 __m128 t4 = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(1, 0, 3, 2));
19
20 __m128 t5 = _mm_shuffle_ps(abcd, abcd, _MM_SHUFFLE(1, 1, 1, 1));
21 __m128 t6 = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(2, 0, 3, 1));
22
23 // [d,d,d,d] * [z,w,x,y] = [dz,dw,dx,dy]
24 __m128 m0 = _mm_mul_ps(t0, t1);
25
26 // [a,a,a,a] * [y,x,w,z] = [ay,ax,aw,az]
27 __m128 m1 = _mm_mul_ps(t3, t4);
28
29 // [b,b,b,b] * [z,x,w,y] = [bz,bx,bw,by]
30 __m128 m2 = _mm_mul_ps(t5, t6);
31
32 // [c,c,c,c] * [w,z,x,y] = [cw,cz,cx,cy]
33 __m128 t7 = _mm_shuffle_ps(abcd, abcd, _MM_SHUFFLE(2, 2, 2, 2));
34 __m128 t8 = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(3, 2, 0, 1));
35 __m128 m3 = _mm_mul_ps(t7, t8);
36
37 // [dz,dw,dx,dy] + -[ay,ax,aw,az] = [dz+ay,dw-ax,dx+aw,dy-az]
38 __m128 e = _mm_addsub_ps(m0, m1);
39
40 // [dx+aw,dz+ay,dy-az,dw-ax]
41 e = _mm_shuffle_ps(e, e, _MM_SHUFFLE(1, 3, 0, 2));
42
43 // [dx+aw,dz+ay,dy-az,dw-ax] + -[bz,bx,bw,by] = [dx+aw+bz,dz+ay-bx,dy-az+bw,dw-ax-by]
44 e = _mm_addsub_ps(e, m2);
45
46 // [dz+ay-bx,dw-ax-by,dy-az+bw,dx+aw+bz]
47 e = _mm_shuffle_ps(e, e, _MM_SHUFFLE(2, 0, 1, 3));
48
49 // [dz+ay-bx,dw-ax-by,dy-az+bw,dx+aw+bz] + -[cw,cz,cx,cy] = [dz+ay-bx+cw,dw-ax-by-cz,dy-az+bw+cx,dx+aw+bz-cy]
50 e = _mm_addsub_ps(e, m3);
51
52 // [dw-ax-by-cz,dz+ay-bx+cw,dy-az+bw+cx,dx+aw+bz-cy]
53 return Quat(Vec4(_mm_shuffle_ps(e, e, _MM_SHUFFLE(2, 3, 1, 0))));
54 #else
55 float lx = mValue.GetX();
56 float ly = mValue.GetY();
57 float lz = mValue.GetZ();
58 float lw = mValue.GetW();
59
60 float rx = inRHS.mValue.GetX();
61 float ry = inRHS.mValue.GetY();
62 float rz = inRHS.mValue.GetZ();
63 float rw = inRHS.mValue.GetW();
64
65 float x = lw * rx + lx * rw + ly * rz - lz * ry;
66 float y = lw * ry - lx * rz + ly * rw + lz * rx;
67 float z = lw * rz + lx * ry - ly * rx + lz * rw;
68 float w = lw * rw - lx * rx - ly * ry - lz * rz;
69
70 return Quat(x, y, z, w);
71 #endif
72 }
73
74 Quat Quat::sMultiplyImaginary(Vec3Arg inLHS, QuatArg inRHS)
75 {
76 #if defined(JPH_USE_SSE4_1)
77 __m128 abc0 = inLHS.mValue;
78 __m128 xyzw = inRHS.mValue.mValue;
79
80 // [a,a,a,a] * [w,y,z,x] = [aw,ay,az,ax]
81 __m128 aaaa = _mm_shuffle_ps(abc0, abc0, _MM_SHUFFLE(0, 0, 0, 0));
82 __m128 xzyw = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(3, 1, 2, 0));
83 __m128 axazayaw = _mm_mul_ps(aaaa, xzyw);
84
85 // [b,b,b,b] * [z,x,w,y] = [bz,bx,bw,by]
86 __m128 bbbb = _mm_shuffle_ps(abc0, abc0, _MM_SHUFFLE(1, 1, 1, 1));
87 __m128 ywxz = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(2, 0, 3, 1));
88 __m128 bybwbxbz = _mm_mul_ps(bbbb, ywxz);
89
90 // [c,c,c,c] * [w,z,x,y] = [cw,cz,cx,cy]
91 __m128 cccc = _mm_shuffle_ps(abc0, abc0, _MM_SHUFFLE(2, 2, 2, 2));
92 __m128 yxzw = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(3, 2, 0, 1));
93 __m128 cycxczcw = _mm_mul_ps(cccc, yxzw);
94
95 // [+aw,+ay,-az,-ax]
96 __m128 e = _mm_xor_ps(axazayaw, _mm_set_ps(0.0f, 0.0f, -0.0f, -0.0f));
97
98 // [+aw,+ay,-az,-ax] + -[bz,bx,bw,by] = [+aw+bz,+ay-bx,-az+bw,-ax-by]
99 e = _mm_addsub_ps(e, bybwbxbz);
100
101 // [+ay-bx,-ax-by,-az+bw,+aw+bz]
102 e = _mm_shuffle_ps(e, e, _MM_SHUFFLE(2, 0, 1, 3));
103
104 // [+ay-bx,-ax-by,-az+bw,+aw+bz] + -[cw,cz,cx,cy] = [+ay-bx+cw,-ax-by-cz,-az+bw+cx,+aw+bz-cy]
105 e = _mm_addsub_ps(e, cycxczcw);
106
107 // [-ax-by-cz,+ay-bx+cw,-az+bw+cx,+aw+bz-cy]
108 return Quat(Vec4(_mm_shuffle_ps(e, e, _MM_SHUFFLE(2, 3, 1, 0))));
109 #else
110 float lx = inLHS.GetX();
111 float ly = inLHS.GetY();
112 float lz = inLHS.GetZ();
113
114 float rx = inRHS.mValue.GetX();
115 float ry = inRHS.mValue.GetY();
116 float rz = inRHS.mValue.GetZ();
117 float rw = inRHS.mValue.GetW();
118
119 float x = (lx * rw) + ly * rz - lz * ry;
120 float y = -(lx * rz) + ly * rw + lz * rx;
121 float z = (lx * ry) - ly * rx + lz * rw;
122 float w = -(lx * rx) - ly * ry - lz * rz;
123
124 return Quat(x, y, z, w);
125 #endif
126 }
127
128 Quat Quat::sRotation(Vec3Arg inAxis, float inAngle)
129 {
130 // returns [inAxis * sin(0.5f * inAngle), cos(0.5f * inAngle)]
131 JPH_ASSERT(inAxis.IsNormalized());
132 Vec4 s, c;
133 Vec4::sReplicate(0.5f * inAngle).SinCos(s, c);
134 return Quat(Vec4::sSelect(Vec4(inAxis) * s, c, UVec4(0, 0, 0, 0xffffffffU)));
135 }
136
137 void Quat::GetAxisAngle(Vec3 &outAxis, float &outAngle) const
138 {
139 JPH_ASSERT(IsNormalized());
140 Quat w_pos = EnsureWPositive();
141 float abs_w = w_pos.GetW();
142 if (abs_w >= 1.0f)
143 {
144 outAxis = Vec3::sZero();
145 outAngle = 0.0f;
146 }
147 else
148 {
149 outAngle = 2.0f * ACos(abs_w);
150 outAxis = w_pos.GetXYZ().NormalizedOr(Vec3::sZero());
151 }
152 }
153
154 Vec3 Quat::GetAngularVelocity(float inDeltaTime) const
155 {
156 JPH_ASSERT(IsNormalized());
157
158 // w = cos(angle / 2), ensure it is positive so that we get an angle in the range [0, PI]
159 Quat w_pos = EnsureWPositive();
160
161 // The imaginary part of the quaternion is axis * sin(angle / 2),
162 // if the length is small use the approximation sin(x) = x to calculate angular velocity
163 Vec3 xyz = w_pos.GetXYZ();
164 float xyz_len_sq = xyz.LengthSq();
165 if (xyz_len_sq < 4.0e-4f) // Max error introduced is sin(0.02) - 0.02 = 7e-5 (when w is near 1 the angle becomes more inaccurate in the code below, so don't make this number too small)
166 return (2.0f / inDeltaTime) * xyz;
167
168 // Otherwise calculate the angle from w = cos(angle / 2) and determine the axis by normalizing the imaginary part
169 // Note that it is also possible to calculate the angle through angle = 2 * atan2(|xyz|, w). This is more accurate but also 2x as expensive.
170 float angle = 2.0f * ACos(w_pos.GetW());
171 return (xyz / (sqrt(xyz_len_sq) * inDeltaTime)) * angle;
172 }
173
174 Quat Quat::sFromTo(Vec3Arg inFrom, Vec3Arg inTo)
175 {
176 /*
177 Uses (inFrom = v1, inTo = v2):
178
179 angle = arcos(v1 . v2 / |v1||v2|)
180 axis = normalize(v1 x v2)
181
182 Quaternion is then:
183
184 s = sin(angle / 2)
185 x = axis.x * s
186 y = axis.y * s
187 z = axis.z * s
188 w = cos(angle / 2)
189
190 Using identities:
191
192 sin(2 * a) = 2 * sin(a) * cos(a)
193 cos(2 * a) = cos(a)^2 - sin(a)^2
194 sin(a)^2 + cos(a)^2 = 1
195
196 This reduces to:
197
198 x = (v1 x v2).x
199 y = (v1 x v2).y
200 z = (v1 x v2).z
201 w = |v1||v2| + v1 . v2
202
203 which then needs to be normalized because the whole equation was multiplied by 2 cos(angle / 2)
204 */
205
206 float len_v1_v2 = sqrt(inFrom.LengthSq() * inTo.LengthSq());
207 float w = len_v1_v2 + inFrom.Dot(inTo);
208
209 if (w == 0.0f)
210 {
211 if (len_v1_v2 == 0.0f)
212 {
213 // If either of the vectors has zero length, there is no rotation and we return identity
214 return Quat::sIdentity();
215 }
216 else
217 {
218 // If vectors are perpendicular, take one of the many 180 degree rotations that exist
219 return Quat(Vec4(inFrom.GetNormalizedPerpendicular(), 0));
220 }
221 }
222
223 Vec3 v = inFrom.Cross(inTo);
224 return Quat(Vec4(v, w)).Normalized();
225 }
226
227 template <class Random>
228 Quat Quat::sRandom(Random &inRandom)
229 {
230 std::uniform_real_distribution<float> zero_to_one(0.0f, 1.0f);
231 float x0 = zero_to_one(inRandom);
232 float r1 = sqrt(1.0f - x0), r2 = sqrt(x0);
233 std::uniform_real_distribution<float> zero_to_two_pi(0.0f, 2.0f * JPH_PI);
234 Vec4 s, c;
235 Vec4(zero_to_two_pi(inRandom), zero_to_two_pi(inRandom), 0, 0).SinCos(s, c);
236 return Quat(s.GetX() * r1, c.GetX() * r1, s.GetY() * r2, c.GetY() * r2);
237 }
238
239 Quat Quat::sEulerAngles(Vec3Arg inAngles)
240 {
241 Vec4 half(0.5f * inAngles);
242 Vec4 s, c;
243 half.SinCos(s, c);
244
245 float cx = c.GetX();
246 float sx = s.GetX();
247 float cy = c.GetY();
248 float sy = s.GetY();
249 float cz = c.GetZ();
250 float sz = s.GetZ();
251
252 return Quat(
253 cz * sx * cy - sz * cx * sy,
254 cz * cx * sy + sz * sx * cy,
255 sz * cx * cy - cz * sx * sy,
256 cz * cx * cy + sz * sx * sy);
257 }
258
259 Vec3 Quat::GetEulerAngles() const
260 {
261 float y_sq = GetY() * GetY();
262
263 // X
264 float t0 = 2.0f * (GetW() * GetX() + GetY() * GetZ());
265 float t1 = 1.0f - 2.0f * (GetX() * GetX() + y_sq);
266
267 // Y
268 float t2 = 2.0f * (GetW() * GetY() - GetZ() * GetX());
269 t2 = t2 > 1.0f? 1.0f : t2;
270 t2 = t2 < -1.0f? -1.0f : t2;
271
272 // Z
273 float t3 = 2.0f * (GetW() * GetZ() + GetX() * GetY());
274 float t4 = 1.0f - 2.0f * (y_sq + GetZ() * GetZ());
275
276 return Vec3(ATan2(t0, t1), ASin(t2), ATan2(t3, t4));
277 }
278
279 Quat Quat::GetTwist(Vec3Arg inAxis) const
280 {
281 Quat twist(Vec4(GetXYZ().Dot(inAxis) * inAxis, GetW()));
282 float twist_len = twist.LengthSq();
283 if (twist_len != 0.0f)
284 return twist / sqrt(twist_len);
285 else
286 return Quat::sIdentity();
287 }
288
289 void Quat::GetSwingTwist(Quat &outSwing, Quat &outTwist) const
290 {
291 float x = GetX(), y = GetY(), z = GetZ(), w = GetW();
292 float s = sqrt(Square(w) + Square(x));
293 if (s != 0.0f)
294 {
295 outTwist = Quat(x / s, 0, 0, w / s);
296 outSwing = Quat(0, (w * y - x * z) / s, (w * z + x * y) / s, s);
297 }
298 else
299 {
300 // If both x and w are zero, this must be a 180 degree rotation around either y or z
301 outTwist = Quat::sIdentity();
302 outSwing = *this;
303 }
304 }
305
306 Quat Quat::LERP(QuatArg inDestination, float inFraction) const
307 {
308 float scale0 = 1.0f - inFraction;
309 return Quat(Vec4::sReplicate(scale0) * mValue + Vec4::sReplicate(inFraction) * inDestination.mValue);
310 }
311
312 Quat Quat::SLERP(QuatArg inDestination, float inFraction) const
313 {
314 // Difference at which to LERP instead of SLERP
315 const float delta = 0.0001f;
316
317 // Calc cosine
318 float sign_scale1 = 1.0f;
319 float cos_omega = Dot(inDestination);
320
321 // Adjust signs (if necessary)
322 if (cos_omega < 0.0f)
323 {
324 cos_omega = -cos_omega;
325 sign_scale1 = -1.0f;
326 }
327
328 // Calculate coefficients
329 float scale0, scale1;
330 if (1.0f - cos_omega > delta)
331 {
332 // Standard case (slerp)
333 float omega = ACos(cos_omega);
334 float sin_omega = Sin(omega);
335 scale0 = Sin((1.0f - inFraction) * omega) / sin_omega;
336 scale1 = sign_scale1 * Sin(inFraction * omega) / sin_omega;
337 }
338 else
339 {
340 // Quaternions are very close so we can do a linear interpolation
341 scale0 = 1.0f - inFraction;
342 scale1 = sign_scale1 * inFraction;
343 }
344
345 // Interpolate between the two quaternions
346 return Quat(Vec4::sReplicate(scale0) * mValue + Vec4::sReplicate(scale1) * inDestination.mValue).Normalized();
347 }
348
349 Vec3 Quat::operator * (Vec3Arg inValue) const
350 {
351 // Rotating a vector by a quaternion is done by: p' = q * (p, 0) * q^-1 (q^-1 = conjugated(q) for a unit quaternion)
352 // Using Rodrigues formula: https://en.m.wikipedia.org/wiki/Euler%E2%80%93Rodrigues_formula
353 // This is equivalent to: p' = p + 2 * (q.w * q.xyz x p + q.xyz x (q.xyz x p))
354 //
355 // This is:
356 //
357 // Vec3 xyz = GetXYZ();
358 // Vec3 q_cross_p = xyz.Cross(inValue);
359 // Vec3 q_cross_q_cross_p = xyz.Cross(q_cross_p);
360 // Vec3 v = mValue.SplatW3() * q_cross_p + q_cross_q_cross_p;
361 // return inValue + (v + v);
362 //
363 // But we can write out the cross products in a more efficient way:
364 JPH_ASSERT(IsNormalized());
365 Vec3 xyz = GetXYZ();
366 Vec3 yzx = xyz.Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>();
367 Vec3 q_cross_p = (inValue.Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>() * xyz - yzx * inValue).Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>();
368 Vec3 q_cross_q_cross_p = (q_cross_p.Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>() * xyz - yzx * q_cross_p).Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>();
369 Vec3 v = mValue.SplatW3() * q_cross_p + q_cross_q_cross_p;
370 return inValue + (v + v);
371 }
372
373 Vec3 Quat::InverseRotate(Vec3Arg inValue) const
374 {
375 JPH_ASSERT(IsNormalized());
376 Vec3 xyz = GetXYZ(); // Needs to be negated, but we do this in the equations below
377 Vec3 yzx = xyz.Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>();
378 Vec3 q_cross_p = (yzx * inValue - inValue.Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>() * xyz).Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>();
379 Vec3 q_cross_q_cross_p = (yzx * q_cross_p - q_cross_p.Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>() * xyz).Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>();
380 Vec3 v = mValue.SplatW3() * q_cross_p + q_cross_q_cross_p;
381 return inValue + (v + v);
382 }
383
384 Vec3 Quat::RotateAxisX() const
385 {
386 // This is *this * Vec3::sAxisX() written out:
387 JPH_ASSERT(IsNormalized());
388 Vec4 t = mValue + mValue;
389 return Vec3(t.SplatX() * mValue + (t.SplatW() * mValue.Swizzle<SWIZZLE_W, SWIZZLE_Z, SWIZZLE_Y, SWIZZLE_X>()).FlipSign<1, 1, -1, 1>() - Vec4(1, 0, 0, 0));
390 }
391
392 Vec3 Quat::RotateAxisY() const
393 {
394 // This is *this * Vec3::sAxisY() written out:
395 JPH_ASSERT(IsNormalized());
396 Vec4 t = mValue + mValue;
397 return Vec3(t.SplatY() * mValue + (t.SplatW() * mValue.Swizzle<SWIZZLE_Z, SWIZZLE_W, SWIZZLE_X, SWIZZLE_Y>()).FlipSign<-1, 1, 1, 1>() - Vec4(0, 1, 0, 0));
398 }
399
400 Vec3 Quat::RotateAxisZ() const
401 {
402 // This is *this * Vec3::sAxisZ() written out:
403 JPH_ASSERT(IsNormalized());
404 Vec4 t = mValue + mValue;
405 return Vec3(t.SplatZ() * mValue + (t.SplatW() * mValue.Swizzle<SWIZZLE_Y, SWIZZLE_X, SWIZZLE_W, SWIZZLE_Z>()).FlipSign<1, -1, 1, 1>() - Vec4(0, 0, 1, 0));
406 }
407
408 void Quat::StoreFloat3(Float3 *outV) const
409 {
410 JPH_ASSERT(IsNormalized());
411 EnsureWPositive().GetXYZ().StoreFloat3(outV);
412 }
413
414 void Quat::StoreFloat4(Float4 *outV) const
415 {
416 mValue.StoreFloat4(outV);
417 }
418
419 Quat Quat::sLoadFloat3Unsafe(const Float3 &inV)
420 {
421 Vec3 v = Vec3::sLoadFloat3Unsafe(inV);
422 float w = sqrt(max(1.0f - v.LengthSq(), 0.0f)); // It is possible that the length of v is a fraction above 1, and we don't want to introduce NaN's in that case so we clamp to 0
423 return Quat(Vec4(v, w));
424 }
425
426 JPH_NAMESPACE_END