Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/DualAxisConstraintPart.h
9913 views
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
#include <Jolt/Math/Vector.h>
10
#include <Jolt/Math/Matrix.h>
11
12
JPH_NAMESPACE_BEGIN
13
14
/**
15
Constrains movement on 2 axis
16
17
@see "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, section 2.3.1
18
19
Constraint equation (eq 51):
20
21
\f[C = \begin{bmatrix} (p_2 - p_1) \cdot n_1 \\ (p_2 - p_1) \cdot n_2\end{bmatrix}\f]
22
23
Jacobian (transposed) (eq 55):
24
25
\f[J^T = \begin{bmatrix}
26
-n_1 & -n_2 \\
27
-(r_1 + u) \times n_1 & -(r_1 + u) \times n_2 \\
28
n_1 & n_2 \\
29
r_2 \times n_1 & r_2 \times n_2
30
\end{bmatrix}\f]
31
32
Used terms (here and below, everything in world space):\n
33
n1, n2 = constraint axis (normalized).\n
34
p1, p2 = constraint points.\n
35
r1 = p1 - x1.\n
36
r2 = p2 - x2.\n
37
u = x2 + r2 - x1 - r1 = p2 - p1.\n
38
x1, x2 = center of mass for the bodies.\n
39
v = [v1, w1, v2, w2].\n
40
v1, v2 = linear velocity of body 1 and 2.\n
41
w1, w2 = angular velocity of body 1 and 2.\n
42
M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n
43
\f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n
44
b = velocity bias.\n
45
\f$\beta\f$ = baumgarte constant.
46
**/
47
class DualAxisConstraintPart
48
{
49
public:
50
using Vec2 = Vector<2>;
51
using Mat22 = Matrix<2, 2>;
52
53
private:
54
/// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
55
JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, const Vec2 &inLambda) const
56
{
57
// Apply impulse if delta is not zero
58
if (!inLambda.IsZero())
59
{
60
// Calculate velocity change due to constraint
61
//
62
// Impulse:
63
// P = J^T lambda
64
//
65
// Euler velocity integration:
66
// v' = v + M^-1 P
67
Vec3 impulse = inN1 * inLambda[0] + inN2 * inLambda[1];
68
if (ioBody1.IsDynamic())
69
{
70
MotionProperties *mp1 = ioBody1.GetMotionProperties();
71
mp1->SubLinearVelocityStep(mp1->GetInverseMass() * impulse);
72
mp1->SubAngularVelocityStep(mInvI1_R1PlusUxN1 * inLambda[0] + mInvI1_R1PlusUxN2 * inLambda[1]);
73
}
74
if (ioBody2.IsDynamic())
75
{
76
MotionProperties *mp2 = ioBody2.GetMotionProperties();
77
mp2->AddLinearVelocityStep(mp2->GetInverseMass() * impulse);
78
mp2->AddAngularVelocityStep(mInvI2_R2xN1 * inLambda[0] + mInvI2_R2xN2 * inLambda[1]);
79
}
80
return true;
81
}
82
83
return false;
84
}
85
86
/// Internal helper function to calculate the lagrange multiplier
87
inline void CalculateLagrangeMultiplier(const Body &inBody1, const Body &inBody2, Vec3Arg inN1, Vec3Arg inN2, Vec2 &outLambda) const
88
{
89
// Calculate lagrange multiplier:
90
//
91
// lambda = -K^-1 (J v + b)
92
Vec3 delta_lin = inBody1.GetLinearVelocity() - inBody2.GetLinearVelocity();
93
Vec2 jv;
94
jv[0] = inN1.Dot(delta_lin) + mR1PlusUxN1.Dot(inBody1.GetAngularVelocity()) - mR2xN1.Dot(inBody2.GetAngularVelocity());
95
jv[1] = inN2.Dot(delta_lin) + mR1PlusUxN2.Dot(inBody1.GetAngularVelocity()) - mR2xN2.Dot(inBody2.GetAngularVelocity());
96
outLambda = mEffectiveMass * jv;
97
}
98
99
public:
100
/// Calculate properties used during the functions below
101
/// All input vectors are in world space
102
inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, Vec3Arg inR1PlusU, const Body &inBody2, Mat44Arg inRotation2, Vec3Arg inR2, Vec3Arg inN1, Vec3Arg inN2)
103
{
104
JPH_ASSERT(inN1.IsNormalized(1.0e-5f));
105
JPH_ASSERT(inN2.IsNormalized(1.0e-5f));
106
107
// Calculate properties used during constraint solving
108
mR1PlusUxN1 = inR1PlusU.Cross(inN1);
109
mR1PlusUxN2 = inR1PlusU.Cross(inN2);
110
mR2xN1 = inR2.Cross(inN1);
111
mR2xN2 = inR2.Cross(inN2);
112
113
// Calculate effective mass: K^-1 = (J M^-1 J^T)^-1, eq 59
114
Mat22 inv_effective_mass;
115
if (inBody1.IsDynamic())
116
{
117
const MotionProperties *mp1 = inBody1.GetMotionProperties();
118
Mat44 inv_i1 = mp1->GetInverseInertiaForRotation(inRotation1);
119
mInvI1_R1PlusUxN1 = inv_i1.Multiply3x3(mR1PlusUxN1);
120
mInvI1_R1PlusUxN2 = inv_i1.Multiply3x3(mR1PlusUxN2);
121
122
inv_effective_mass(0, 0) = mp1->GetInverseMass() + mR1PlusUxN1.Dot(mInvI1_R1PlusUxN1);
123
inv_effective_mass(0, 1) = mR1PlusUxN1.Dot(mInvI1_R1PlusUxN2);
124
inv_effective_mass(1, 0) = mR1PlusUxN2.Dot(mInvI1_R1PlusUxN1);
125
inv_effective_mass(1, 1) = mp1->GetInverseMass() + mR1PlusUxN2.Dot(mInvI1_R1PlusUxN2);
126
}
127
else
128
{
129
JPH_IF_DEBUG(mInvI1_R1PlusUxN1 = Vec3::sNaN();)
130
JPH_IF_DEBUG(mInvI1_R1PlusUxN2 = Vec3::sNaN();)
131
132
inv_effective_mass = Mat22::sZero();
133
}
134
135
if (inBody2.IsDynamic())
136
{
137
const MotionProperties *mp2 = inBody2.GetMotionProperties();
138
Mat44 inv_i2 = mp2->GetInverseInertiaForRotation(inRotation2);
139
mInvI2_R2xN1 = inv_i2.Multiply3x3(mR2xN1);
140
mInvI2_R2xN2 = inv_i2.Multiply3x3(mR2xN2);
141
142
inv_effective_mass(0, 0) += mp2->GetInverseMass() + mR2xN1.Dot(mInvI2_R2xN1);
143
inv_effective_mass(0, 1) += mR2xN1.Dot(mInvI2_R2xN2);
144
inv_effective_mass(1, 0) += mR2xN2.Dot(mInvI2_R2xN1);
145
inv_effective_mass(1, 1) += mp2->GetInverseMass() + mR2xN2.Dot(mInvI2_R2xN2);
146
}
147
else
148
{
149
JPH_IF_DEBUG(mInvI2_R2xN1 = Vec3::sNaN();)
150
JPH_IF_DEBUG(mInvI2_R2xN2 = Vec3::sNaN();)
151
}
152
153
if (!mEffectiveMass.SetInversed(inv_effective_mass))
154
Deactivate();
155
}
156
157
/// Deactivate this constraint
158
inline void Deactivate()
159
{
160
mEffectiveMass.SetZero();
161
mTotalLambda.SetZero();
162
}
163
164
/// Check if constraint is active
165
inline bool IsActive() const
166
{
167
return !mEffectiveMass.IsZero();
168
}
169
170
/// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
171
/// All input vectors are in world space
172
inline void WarmStart(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, float inWarmStartImpulseRatio)
173
{
174
mTotalLambda *= inWarmStartImpulseRatio;
175
ApplyVelocityStep(ioBody1, ioBody2, inN1, inN2, mTotalLambda);
176
}
177
178
/// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
179
/// All input vectors are in world space
180
inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2)
181
{
182
Vec2 lambda;
183
CalculateLagrangeMultiplier(ioBody1, ioBody2, inN1, inN2, lambda);
184
185
// Store accumulated lambda
186
mTotalLambda += lambda;
187
188
return ApplyVelocityStep(ioBody1, ioBody2, inN1, inN2, lambda);
189
}
190
191
/// Iteratively update the position constraint. Makes sure C(...) = 0.
192
/// All input vectors are in world space
193
inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inU, Vec3Arg inN1, Vec3Arg inN2, float inBaumgarte) const
194
{
195
Vec2 c;
196
c[0] = inU.Dot(inN1);
197
c[1] = inU.Dot(inN2);
198
if (!c.IsZero())
199
{
200
// Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
201
//
202
// lambda = -K^-1 * beta / dt * C
203
//
204
// We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
205
Vec2 lambda = -inBaumgarte * (mEffectiveMass * c);
206
207
// Directly integrate velocity change for one time step
208
//
209
// Euler velocity integration:
210
// dv = M^-1 P
211
//
212
// Impulse:
213
// P = J^T lambda
214
//
215
// Euler position integration:
216
// x' = x + dv * dt
217
//
218
// Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
219
// Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
220
// stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
221
// integrate + a position integrate and then discard the velocity change.
222
Vec3 impulse = inN1 * lambda[0] + inN2 * lambda[1];
223
if (ioBody1.IsDynamic())
224
{
225
ioBody1.SubPositionStep(ioBody1.GetMotionProperties()->GetInverseMass() * impulse);
226
ioBody1.SubRotationStep(mInvI1_R1PlusUxN1 * lambda[0] + mInvI1_R1PlusUxN2 * lambda[1]);
227
}
228
if (ioBody2.IsDynamic())
229
{
230
ioBody2.AddPositionStep(ioBody2.GetMotionProperties()->GetInverseMass() * impulse);
231
ioBody2.AddRotationStep(mInvI2_R2xN1 * lambda[0] + mInvI2_R2xN2 * lambda[1]);
232
}
233
return true;
234
}
235
236
return false;
237
}
238
239
/// Override total lagrange multiplier, can be used to set the initial value for warm starting
240
inline void SetTotalLambda(const Vec2 &inLambda)
241
{
242
mTotalLambda = inLambda;
243
}
244
245
/// Return lagrange multiplier
246
inline const Vec2 & GetTotalLambda() const
247
{
248
return mTotalLambda;
249
}
250
251
/// Save state of this constraint part
252
void SaveState(StateRecorder &inStream) const
253
{
254
inStream.Write(mTotalLambda);
255
}
256
257
/// Restore state of this constraint part
258
void RestoreState(StateRecorder &inStream)
259
{
260
inStream.Read(mTotalLambda);
261
}
262
263
private:
264
Vec3 mR1PlusUxN1;
265
Vec3 mR1PlusUxN2;
266
Vec3 mR2xN1;
267
Vec3 mR2xN2;
268
Vec3 mInvI1_R1PlusUxN1;
269
Vec3 mInvI1_R1PlusUxN2;
270
Vec3 mInvI2_R2xN1;
271
Vec3 mInvI2_R2xN2;
272
Mat22 mEffectiveMass;
273
Vec2 mTotalLambda { Vec2::sZero() };
274
};
275
276
JPH_NAMESPACE_END
277
278