Jolt Physics
A multi core friendly Game Physics Engine
Loading...
Searching...
No Matches
HingeRotationConstraintPart.h
Go to the documentation of this file.
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
9#include <Jolt/Math/Vector.h>
10#include <Jolt/Math/Matrix.h>
11
13
42{
43public:
44 using Vec2 = Vector<2>;
46
47private:
49 JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, const Vec2 &inLambda) const
50 {
51 // Apply impulse if delta is not zero
52 if (!inLambda.IsZero())
53 {
54 // Calculate velocity change due to constraint
55 //
56 // Impulse:
57 // P = J^T lambda
58 //
59 // Euler velocity integration:
60 // v' = v + M^-1 P
61 Vec3 impulse = mB2xA1 * inLambda[0] + mC2xA1 * inLambda[1];
62 if (ioBody1.IsDynamic())
63 ioBody1.GetMotionProperties()->SubAngularVelocityStep(mInvI1.Multiply3x3(impulse));
64 if (ioBody2.IsDynamic())
65 ioBody2.GetMotionProperties()->AddAngularVelocityStep(mInvI2.Multiply3x3(impulse));
66 return true;
67 }
68
69 return false;
70 }
71
72public:
74 inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, Vec3Arg inWorldSpaceHingeAxis1, const Body &inBody2, Mat44Arg inRotation2, Vec3Arg inWorldSpaceHingeAxis2)
75 {
76 JPH_ASSERT(inWorldSpaceHingeAxis1.IsNormalized(1.0e-5f));
77 JPH_ASSERT(inWorldSpaceHingeAxis2.IsNormalized(1.0e-5f));
78
79 // Calculate hinge axis in world space
80 mA1 = inWorldSpaceHingeAxis1;
81 Vec3 a2 = inWorldSpaceHingeAxis2;
82 float dot = mA1.Dot(a2);
83 if (dot <= 1.0e-3f)
84 {
85 // 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
86 Vec3 perp = a2 - dot * mA1;
87 if (perp.LengthSq() < 1.0e-6f)
88 {
89 // mA1 ~ -a2, take random perpendicular
90 perp = mA1.GetNormalizedPerpendicular();
91 }
92
93 // Blend in a little bit from mA1 so we're less than 90 degrees apart
94 a2 = (0.99f * perp.Normalized() + 0.01f * mA1).Normalized();
95 }
97 mC2 = a2.Cross(mB2);
98
99 // Calculate properties used during constraint solving
100 mInvI1 = inBody1.IsDynamic()? inBody1.GetMotionProperties()->GetInverseInertiaForRotation(inRotation1) : Mat44::sZero();
101 mInvI2 = inBody2.IsDynamic()? inBody2.GetMotionProperties()->GetInverseInertiaForRotation(inRotation2) : Mat44::sZero();
102 mB2xA1 = mB2.Cross(mA1);
103 mC2xA1 = mC2.Cross(mA1);
104
105 // Calculate effective mass: K^-1 = (J M^-1 J^T)^-1
106 Mat44 summed_inv_inertia = mInvI1 + mInvI2;
107 Mat22 inv_effective_mass;
108 inv_effective_mass(0, 0) = mB2xA1.Dot(summed_inv_inertia.Multiply3x3(mB2xA1));
109 inv_effective_mass(0, 1) = mB2xA1.Dot(summed_inv_inertia.Multiply3x3(mC2xA1));
110 inv_effective_mass(1, 0) = mC2xA1.Dot(summed_inv_inertia.Multiply3x3(mB2xA1));
111 inv_effective_mass(1, 1) = mC2xA1.Dot(summed_inv_inertia.Multiply3x3(mC2xA1));
112 if (!mEffectiveMass.SetInversed(inv_effective_mass))
113 {
114 JPH_ASSERT(false, "Determinant is zero!");
115 Deactivate();
116 }
117 }
118
120 inline void Deactivate()
121 {
122 mEffectiveMass.SetZero();
123 mTotalLambda.SetZero();
124 }
125
127 inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
128 {
129 mTotalLambda *= inWarmStartImpulseRatio;
130 ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
131 }
132
134 inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)
135 {
136 // Calculate lagrange multiplier:
137 //
138 // lambda = -K^-1 (J v + b)
139 Vec3 delta_ang = ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity();
140 Vec2 jv;
141 jv[0] = mB2xA1.Dot(delta_ang);
142 jv[1] = mC2xA1.Dot(delta_ang);
143 Vec2 lambda = mEffectiveMass * jv;
144
145 // Store accumulated lambda
146 mTotalLambda += lambda;
147
148 return ApplyVelocityStep(ioBody1, ioBody2, lambda);
149 }
150
152 inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inBaumgarte) const
153 {
154 // 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)
155 Vec2 c;
156 c[0] = mA1.Dot(mB2);
157 c[1] = mA1.Dot(mC2);
158 if (!c.IsZero())
159 {
160 // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
161 //
162 // lambda = -K^-1 * beta / dt * C
163 //
164 // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
165 Vec2 lambda = -inBaumgarte * (mEffectiveMass * c);
166
167 // Directly integrate velocity change for one time step
168 //
169 // Euler velocity integration:
170 // dv = M^-1 P
171 //
172 // Impulse:
173 // P = J^T lambda
174 //
175 // Euler position integration:
176 // x' = x + dv * dt
177 //
178 // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
179 // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
180 // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
181 // integrate + a position integrate and then discard the velocity change.
182 Vec3 impulse = mB2xA1 * lambda[0] + mC2xA1 * lambda[1];
183 if (ioBody1.IsDynamic())
184 ioBody1.SubRotationStep(mInvI1.Multiply3x3(impulse));
185 if (ioBody2.IsDynamic())
186 ioBody2.AddRotationStep(mInvI2.Multiply3x3(impulse));
187 return true;
188 }
189
190 return false;
191 }
192
194 const Vec2 & GetTotalLambda() const
195 {
196 return mTotalLambda;
197 }
198
200 void SaveState(StateRecorder &inStream) const
201 {
202 inStream.Write(mTotalLambda);
203 }
204
207 {
208 inStream.Read(mTotalLambda);
209 }
210
211private:
212 Vec3 mA1;
213 Vec3 mB2;
214 Vec3 mC2;
215 Mat44 mInvI1;
216 Mat44 mInvI2;
217 Vec3 mB2xA1;
218 Vec3 mC2xA1;
219 Mat22 mEffectiveMass;
220 Vec2 mTotalLambda { Vec2::sZero() };
221};
222
#define JPH_NAMESPACE_END
Definition: Core.h:240
#define JPH_NAMESPACE_BEGIN
Definition: Core.h:234
#define JPH_ASSERT(...)
Definition: IssueReporting.h:33
Definition: Body.h:33
const MotionProperties * GetMotionProperties() const
Access to the motion properties.
Definition: Body.h:205
bool IsDynamic() const
Check if this body is dynamic, which means that it moves and forces can act on it.
Definition: Body.h:56
void AddRotationStep(Vec3Arg inAngularVelocityTimesDeltaTime)
Update rotation using an Euler step (using during position integrate & constraint solving)
Definition: Body.inl:75
void SubRotationStep(Vec3Arg inAngularVelocityTimesDeltaTime)
Definition: Body.inl:93
Vec3 GetAngularVelocity() const
Get world space angular velocity of the center of mass (unit: rad/s)
Definition: Body.h:118
Definition: HingeRotationConstraintPart.h:42
bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inBaumgarte) const
Iteratively update the position constraint. Makes sure C(...) = 0.
Definition: HingeRotationConstraintPart.h:152
void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, Vec3Arg inWorldSpaceHingeAxis1, const Body &inBody2, Mat44Arg inRotation2, Vec3Arg inWorldSpaceHingeAxis2)
Calculate properties used during the functions below.
Definition: HingeRotationConstraintPart.h:74
void Deactivate()
Deactivate this constraint.
Definition: HingeRotationConstraintPart.h:120
void SaveState(StateRecorder &inStream) const
Save state of this constraint part.
Definition: HingeRotationConstraintPart.h:200
void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses.
Definition: HingeRotationConstraintPart.h:127
const Vec2 & GetTotalLambda() const
Return lagrange multiplier.
Definition: HingeRotationConstraintPart.h:194
bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)
Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equ...
Definition: HingeRotationConstraintPart.h:134
Matrix< 2, 2 > Mat22
Definition: HingeRotationConstraintPart.h:45
void RestoreState(StateRecorder &inStream)
Restore state of this constraint part.
Definition: HingeRotationConstraintPart.h:206
Vector< 2 > Vec2
Definition: HingeRotationConstraintPart.h:44
Holds a 4x4 matrix of floats, but supports also operations on the 3x3 upper left part of the matrix.
Definition: Mat44.h:13
static JPH_INLINE Mat44 sZero()
Zero matrix.
Definition: Mat44.inl:30
JPH_INLINE Vec3 Multiply3x3(Vec3Arg inV) const
Multiply vector by only 3x3 part of the matrix.
Definition: Mat44.inl:307
bool SetInversed(const Matrix &inM)
Inverse matrix.
Definition: Matrix.h:200
void SetZero()
Zero matrix.
Definition: Matrix.h:26
void SubAngularVelocityStep(Vec3Arg inAngularVelocityChange)
Definition: MotionProperties.h:129
Mat44 GetInverseInertiaForRotation(Mat44Arg inRotation) const
Get inverse inertia matrix ( ) for a given object rotation (translation will be ignored)....
Definition: MotionProperties.inl:81
void AddAngularVelocityStep(Vec3Arg inAngularVelocityChange)
Definition: MotionProperties.h:128
Definition: StateRecorder.h:15
void Read(T &outT)
Read a primitive (e.g. float, int, etc.) from the binary stream.
Definition: StreamIn.h:27
void Write(const T &inT)
Write a primitive (e.g. float, int, etc.) to the binary stream.
Definition: StreamOut.h:24
Definition: Vec3.h:16
JPH_INLINE float Dot(Vec3Arg inV2) const
Dot product.
Definition: Vec3.inl:637
JPH_INLINE Vec3 Normalized() const
Normalize vector.
Definition: Vec3.inl:694
JPH_INLINE Vec3 Cross(Vec3Arg inV2) const
Cross product.
Definition: Vec3.inl:582
JPH_INLINE Vec3 GetNormalizedPerpendicular() const
Get normalized vector that is perpendicular to this vector.
Definition: Vec3.inl:812
JPH_INLINE bool IsNormalized(float inTolerance=1.0e-6f) const
Test if vector is normalized.
Definition: Vec3.inl:737
JPH_INLINE float LengthSq() const
Squared length of vector.
Definition: Vec3.inl:653
void SetZero()
Vector with all zeros.
Definition: Vector.h:22
bool IsZero() const
Test if vector consists of all zeros.
Definition: Vector.h:69
static Vector sZero()
Definition: Vector.h:28