Debian Codegraph @

thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/HingeRotationConstraintPart.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 #include <Jolt/Math/Vector.h>
10 #include <Jolt/Math/Matrix.h>
11
12 JPH_NAMESPACE_BEGIN
13
14 /**
15 Constrains rotation around 2 axis so that it only allows rotation around 1 axis
16
17 Based on: "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, section 2.4.1
18
19 Constraint equation (eq 87):
20
21 \f[C = \begin{bmatrix}a_1 \cdot b_2 \\ a_1 \cdot c_2\end{bmatrix}\f]
22
23 Jacobian (eq 90):
24
25 \f[J = \begin{bmatrix}
26 0 & -b_2 \times a_1 & 0 & b_2 \times a_1 \\
27 0 & -c_2 \times a_1 & 0 & c2 \times a_1
28 \end{bmatrix}\f]
29
30 Used terms (here and below, everything in world space):\n
31 a1 = hinge axis on body 1.\n
32 b2, c2 = axis perpendicular to hinge axis on body 2.\n
33 x1, x2 = center of mass for the bodies.\n
34 v = [v1, w1, v2, w2].\n
35 v1, v2 = linear velocity of body 1 and 2.\n
36 w1, w2 = angular velocity of body 1 and 2.\n
37 M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n
38 \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n
39 b = velocity bias.\n
40 \f$\beta\f$ = baumgarte constant.\n
41 E = identity matrix.
42 **/
43 class HingeRotationConstraintPart
44 {
45 public:
46 using Vec2 = Vector<2>;
47 using Mat22 = Matrix<2, 2>;
48
49 private:
50 /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
51 JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, const Vec2 &inLambda) const
52 {
53 // Apply impulse if delta is not zero
54 if (!inLambda.IsZero())
55 {
56 // Calculate velocity change due to constraint
57 //
58 // Impulse:
59 // P = J^T lambda
60 //
61 // Euler velocity integration:
62 // v' = v + M^-1 P
63 Vec3 impulse = mB2xA1 * inLambda[0] + mC2xA1 * inLambda[1];
64 if (ioBody1.IsDynamic())
65 ioBody1.GetMotionProperties()->SubAngularVelocityStep(mInvI1.Multiply3x3(impulse));
66 if (ioBody2.IsDynamic())
67 ioBody2.GetMotionProperties()->AddAngularVelocityStep(mInvI2.Multiply3x3(impulse));
68 return true;
69 }
70
71 return false;
72 }
73
74 public:
75 /// Calculate properties used during the functions below
76 inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, Vec3Arg inWorldSpaceHingeAxis1, const Body &inBody2, Mat44Arg inRotation2, Vec3Arg inWorldSpaceHingeAxis2)
77 {
78 JPH_ASSERT(inWorldSpaceHingeAxis1.IsNormalized(1.0e-5f));
79 JPH_ASSERT(inWorldSpaceHingeAxis2.IsNormalized(1.0e-5f));
80
81 // Calculate hinge axis in world space
82 mA1 = inWorldSpaceHingeAxis1;
83 Vec3 a2 = inWorldSpaceHingeAxis2;
84 float dot = mA1.Dot(a2);
85 if (dot <= 1.0e-3f)
86 {
87 // World space axes are more than 90 degrees apart, get a perpendicular vector in the plane formed by mA1 and a2 as hinge axis until the rotation is less than 90 degrees
88 Vec3 perp = a2 - dot * mA1;
89 if (perp.LengthSq() < 1.0e-6f)
90 {
91 // mA1 ~ -a2, take random perpendicular
92 perp = mA1.GetNormalizedPerpendicular();
93 }
94
95 // Blend in a little bit from mA1 so we're less than 90 degrees apart
96 a2 = (0.99f * perp.Normalized() + 0.01f * mA1).Normalized();
97 }
98 mB2 = a2.GetNormalizedPerpendicular();
99 mC2 = a2.Cross(mB2);
100
101 // Calculate properties used during constraint solving
102 mInvI1 = inBody1.IsDynamic()? inBody1.GetMotionProperties()->GetInverseInertiaForRotation(inRotation1) : Mat44::sZero();
103 mInvI2 = inBody2.IsDynamic()? inBody2.GetMotionProperties()->GetInverseInertiaForRotation(inRotation2) : Mat44::sZero();
104 mB2xA1 = mB2.Cross(mA1);
105 mC2xA1 = mC2.Cross(mA1);
106
107 // Calculate effective mass: K^-1 = (J M^-1 J^T)^-1
108 Mat44 summed_inv_inertia = mInvI1 + mInvI2;
109 Mat22 inv_effective_mass;
110 inv_effective_mass(0, 0) = mB2xA1.Dot(summed_inv_inertia.Multiply3x3(mB2xA1));
111 inv_effective_mass(0, 1) = mB2xA1.Dot(summed_inv_inertia.Multiply3x3(mC2xA1));
112 inv_effective_mass(1, 0) = mC2xA1.Dot(summed_inv_inertia.Multiply3x3(mB2xA1));
113 inv_effective_mass(1, 1) = mC2xA1.Dot(summed_inv_inertia.Multiply3x3(mC2xA1));
114 if (!mEffectiveMass.SetInversed(inv_effective_mass))
115 Deactivate();
116 }
117
118 /// Deactivate this constraint
119 inline void Deactivate()
120 {
121 mEffectiveMass.SetZero();
122 mTotalLambda.SetZero();
123 }
124
125 /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
126 inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
127 {
128 mTotalLambda *= inWarmStartImpulseRatio;
129 ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
130 }
131
132 /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
133 inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)
134 {
135 // Calculate lagrange multiplier:
136 //
137 // lambda = -K^-1 (J v + b)
138 Vec3 delta_ang = ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity();
139 Vec2 jv;
140 jv[0] = mB2xA1.Dot(delta_ang);
141 jv[1] = mC2xA1.Dot(delta_ang);
142 Vec2 lambda = mEffectiveMass * jv;
143
144 // Store accumulated lambda
145 mTotalLambda += lambda;
146
147 return ApplyVelocityStep(ioBody1, ioBody2, lambda);
148 }
149
150 /// Iteratively update the position constraint. Makes sure C(...) = 0.
151 inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inBaumgarte) const
152 {
153 // Constraint needs Axis of body 1 perpendicular to both B and C from body 2 (which are both perpendicular to the Axis of body 2)
154 Vec2 c;
155 c[0] = mA1.Dot(mB2);
156 c[1] = mA1.Dot(mC2);
157 if (!c.IsZero())
158 {
159 // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
160 //
161 // lambda = -K^-1 * beta / dt * C
162 //
163 // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
164 Vec2 lambda = -inBaumgarte * (mEffectiveMass * c);
165
166 // Directly integrate velocity change for one time step
167 //
168 // Euler velocity integration:
169 // dv = M^-1 P
170 //
171 // Impulse:
172 // P = J^T lambda
173 //
174 // Euler position integration:
175 // x' = x + dv * dt
176 //
177 // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
178 // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
179 // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
180 // integrate + a position integrate and then discard the velocity change.
181 Vec3 impulse = mB2xA1 * lambda[0] + mC2xA1 * lambda[1];
182 if (ioBody1.IsDynamic())
183 ioBody1.SubRotationStep(mInvI1.Multiply3x3(impulse));
184 if (ioBody2.IsDynamic())
185 ioBody2.AddRotationStep(mInvI2.Multiply3x3(impulse));
186 return true;
187 }
188
189 return false;
190 }
191
192 /// Return lagrange multiplier
193 const Vec2 & GetTotalLambda() const
194 {
195 return mTotalLambda;
196 }
197
198 /// Save state of this constraint part
199 void SaveState(StateRecorder &inStream) const
200 {
201 inStream.Write(mTotalLambda);
202 }
203
204 /// Restore state of this constraint part
205 void RestoreState(StateRecorder &inStream)
206 {
207 inStream.Read(mTotalLambda);
208 }
209
210 private:
211 Vec3 mA1; ///< World space hinge axis for body 1
212 Vec3 mB2; ///< World space perpendiculars of hinge axis for body 2
213 Vec3 mC2;
214 Mat44 mInvI1;
215 Mat44 mInvI2;
216 Vec3 mB2xA1;
217 Vec3 mC2xA1;
218 Mat22 mEffectiveMass;
219 Vec2 mTotalLambda { Vec2::sZero() };
220 };
221
222 JPH_NAMESPACE_END