Debian Codegraph @

thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/RotationQuatConstraintPart.h

raw symbols SCIP
1 // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
2 // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
3 // SPDX-License-Identifier: MIT
4
5 #pragma once
6
7 #include <Jolt/Physics/Body/Body.h>
8 #include <Jolt/Physics/StateRecorder.h>
9
10 JPH_NAMESPACE_BEGIN
11
12 /// Quaternion based constraint that constrains rotation around all axis so that only translation is allowed.
13 ///
14 /// NOTE: This constraint part is more expensive than the RotationEulerConstraintPart and slightly more correct since
15 /// RotationEulerConstraintPart::SolvePositionConstraint contains an approximation. In practice the difference
16 /// is small, so the RotationEulerConstraintPart is probably the better choice.
17 ///
18 /// Rotation is fixed between bodies like this:
19 ///
20 /// q2 = q1 r0
21 ///
22 /// Where:
23 /// q1, q2 = world space quaternions representing rotation of body 1 and 2.
24 /// r0 = initial rotation between bodies in local space of body 1, this can be calculated by:
25 ///
26 /// q20 = q10 r0
27 /// <=> r0 = q10^* q20
28 ///
29 /// Where:
30 /// q10, q20 = initial world space rotations of body 1 and 2.
31 /// q10^* = conjugate of quaternion q10 (which is the same as the inverse for a unit quaternion)
32 ///
33 /// We exclusively use the conjugate below:
34 ///
35 /// r0^* = q20^* q10
36 ///
37 /// The error in the rotation is (in local space of body 1):
38 ///
39 /// q2 = q1 error r0
40 /// <=> error = q1^* q2 r0^*
41 ///
42 /// The imaginary part of the quaternion represents the rotation axis * sin(angle / 2). The real part of the quaternion
43 /// does not add any additional information (we know the quaternion in normalized) and we're removing 3 degrees of freedom
44 /// so we want 3 parameters. Therefore we define the constraint equation like:
45 ///
46 /// C = A q1^* q2 r0^* = 0
47 ///
48 /// Where (if you write a quaternion as [real-part, i-part, j-part, k-part]):
49 ///
50 /// [0, 1, 0, 0]
51 /// A = [0, 0, 1, 0]
52 /// [0, 0, 0, 1]
53 ///
54 /// or in our case since we store a quaternion like [i-part, j-part, k-part, real-part]:
55 ///
56 /// [1, 0, 0, 0]
57 /// A = [0, 1, 0, 0]
58 /// [0, 0, 1, 0]
59 ///
60 /// Time derivative:
61 ///
62 /// d/dt C = A (q1^* d/dt(q2) + d/dt(q1^*) q2) r0^*
63 /// = A (q1^* (1/2 W2 q2) + (1/2 W1 q1)^* q2) r0^*
64 /// = 1/2 A (q1^* W2 q2 + q1^* W1^* q2) r0^*
65 /// = 1/2 A (q1^* W2 q2 - q1^* W1 * q2) r0^*
66 /// = 1/2 A ML(q1^*) MR(q2 r0^*) (W2 - W1)
67 /// = 1/2 A ML(q1^*) MR(q2 r0^*) A^T (w2 - w1)
68 ///
69 /// Where:
70 /// W1 = [0, w1], W2 = [0, w2] (converting angular velocity to imaginary part of quaternion).
71 /// w1, w2 = angular velocity of body 1 and 2.
72 /// d/dt(q) = 1/2 W q (time derivative of a quaternion).
73 /// W^* = -W (conjugate negates angular velocity as quaternion).
74 /// ML(q): 4x4 matrix so that q * p = ML(q) * p, where q and p are quaternions.
75 /// MR(p): 4x4 matrix so that q * p = MR(p) * q, where q and p are quaternions.
76 /// A^T: Transpose of A.
77 ///
78 /// Jacobian:
79 ///
80 /// J = [0, -1/2 A ML(q1^*) MR(q2 r0^*) A^T, 0, 1/2 A ML(q1^*) MR(q2 r0^*) A^T]
81 /// = [0, -JP, 0, JP]
82 ///
83 /// Suggested reading:
84 /// - 3D Constraint Derivations for Impulse Solvers - Marijn Tamis
85 /// - Game Physics Pearls - Section 9 - Quaternion Based Constraints - Claude Lacoursiere
86 class RotationQuatConstraintPart
87 {
88 private:
89 /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
90 JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, Vec3Arg inLambda) const
91 {
92 // Apply impulse if delta is not zero
93 if (inLambda != Vec3::sZero())
94 {
95 // Calculate velocity change due to constraint
96 //
97 // Impulse:
98 // P = J^T lambda
99 //
100 // Euler velocity integration:
101 // v' = v + M^-1 P
102 if (ioBody1.IsDynamic())
103 ioBody1.GetMotionProperties()->SubAngularVelocityStep(mInvI1_JPT.Multiply3x3(inLambda));
104 if (ioBody2.IsDynamic())
105 ioBody2.GetMotionProperties()->AddAngularVelocityStep(mInvI2_JPT.Multiply3x3(inLambda));
106 return true;
107 }
108
109 return false;
110 }
111
112 public:
113 /// Return inverse of initial rotation from body 1 to body 2 in body 1 space
114 static Quat sGetInvInitialOrientation(const Body &inBody1, const Body &inBody2)
115 {
116 // q20 = q10 r0
117 // <=> r0 = q10^-1 q20
118 // <=> r0^-1 = q20^-1 q10
119 //
120 // where:
121 //
122 // q20 = initial orientation of body 2
123 // q10 = initial orientation of body 1
124 // r0 = initial rotation from body 1 to body 2
125 return inBody2.GetRotation().Conjugated() * inBody1.GetRotation();
126 }
127
128 /// Calculate properties used during the functions below
129 inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, const Body &inBody2, Mat44Arg inRotation2, QuatArg inInvInitialOrientation)
130 {
131 // Calculate: JP = 1/2 A ML(q1^*) MR(q2 r0^*) A^T
132 Mat44 jp = (Mat44::sQuatLeftMultiply(0.5f * inBody1.GetRotation().Conjugated()) * Mat44::sQuatRightMultiply(inBody2.GetRotation() * inInvInitialOrientation)).GetRotationSafe();
133
134 // Calculate properties used during constraint solving
135 Mat44 inv_i1 = inBody1.IsDynamic()? inBody1.GetMotionProperties()->GetInverseInertiaForRotation(inRotation1) : Mat44::sZero();
136 Mat44 inv_i2 = inBody2.IsDynamic()? inBody2.GetMotionProperties()->GetInverseInertiaForRotation(inRotation2) : Mat44::sZero();
137 mInvI1_JPT = inv_i1.Multiply3x3RightTransposed(jp);
138 mInvI2_JPT = inv_i2.Multiply3x3RightTransposed(jp);
139
140 // Calculate effective mass: K^-1 = (J M^-1 J^T)^-1
141 // = (JP * I1^-1 * JP^T + JP * I2^-1 * JP^T)^-1
142 // = (JP * (I1^-1 + I2^-1) * JP^T)^-1
143 if (!mEffectiveMass.SetInversed3x3(jp.Multiply3x3(inv_i1 + inv_i2).Multiply3x3RightTransposed(jp)))
144 Deactivate();
145 else
146 mEffectiveMass_JP = mEffectiveMass.Multiply3x3(jp);
147 }
148
149 /// Deactivate this constraint
150 inline void Deactivate()
151 {
152 mEffectiveMass = Mat44::sZero();
153 mEffectiveMass_JP = Mat44::sZero();
154 mTotalLambda = Vec3::sZero();
155 }
156
157 /// Check if constraint is active
158 inline bool IsActive() const
159 {
160 return mEffectiveMass(3, 3) != 0.0f;
161 }
162
163 /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
164 inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
165 {
166 mTotalLambda *= inWarmStartImpulseRatio;
167 ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
168 }
169
170 /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
171 inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)
172 {
173 // Calculate lagrange multiplier:
174 //
175 // lambda = -K^-1 (J v + b)
176 Vec3 lambda = mEffectiveMass_JP.Multiply3x3(ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity());
177 mTotalLambda += lambda;
178 return ApplyVelocityStep(ioBody1, ioBody2, lambda);
179 }
180
181 /// Iteratively update the position constraint. Makes sure C(...) = 0.
182 inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, QuatArg inInvInitialOrientation, float inBaumgarte) const
183 {
184 // Calculate constraint equation
185 Vec3 c = (ioBody1.GetRotation().Conjugated() * ioBody2.GetRotation() * inInvInitialOrientation).GetXYZ();
186 if (c != Vec3::sZero())
187 {
188 // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
189 //
190 // lambda = -K^-1 * beta / dt * C
191 //
192 // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
193 Vec3 lambda = -inBaumgarte * mEffectiveMass * c;
194
195 // Directly integrate velocity change for one time step
196 //
197 // Euler velocity integration:
198 // dv = M^-1 P
199 //
200 // Impulse:
201 // P = J^T lambda
202 //
203 // Euler position integration:
204 // x' = x + dv * dt
205 //
206 // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
207 // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
208 // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
209 // integrate + a position integrate and then discard the velocity change.
210 if (ioBody1.IsDynamic())
211 ioBody1.SubRotationStep(mInvI1_JPT.Multiply3x3(lambda));
212 if (ioBody2.IsDynamic())
213 ioBody2.AddRotationStep(mInvI2_JPT.Multiply3x3(lambda));
214 return true;
215 }
216
217 return false;
218 }
219
220 /// Return lagrange multiplier
221 Vec3 GetTotalLambda() const
222 {
223 return mTotalLambda;
224 }
225
226 /// Save state of this constraint part
227 void SaveState(StateRecorder &inStream) const
228 {
229 inStream.Write(mTotalLambda);
230 }
231
232 /// Restore state of this constraint part
233 void RestoreState(StateRecorder &inStream)
234 {
235 inStream.Read(mTotalLambda);
236 }
237
238 private:
239 Mat44 mInvI1_JPT;
240 Mat44 mInvI2_JPT;
241 Mat44 mEffectiveMass;
242 Mat44 mEffectiveMass_JP;
243 Vec3 mTotalLambda { Vec3::sZero() };
244 };
245
246 JPH_NAMESPACE_END