thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/AngleConstraintPart.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/Constraints/ConstraintPart/SpringPart.h> |
| 9 | #include <Jolt/Physics/Constraints/SpringSettings.h> |
| 10 | #include <Jolt/Physics/StateRecorder.h> |
| 11 | |
| 12 | JPH_NAMESPACE_BEGIN |
| 13 | |
| 14 | /// Constraint that constrains rotation along 1 axis |
| 15 | /// |
| 16 | /// Based on: "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, see section 2.4.5 |
| 17 | /// |
| 18 | /// Constraint equation (eq 108): |
| 19 | /// |
| 20 | /// \f[C = \theta(t) - \theta_{min}\f] |
| 21 | /// |
| 22 | /// Jacobian (eq 109): |
| 23 | /// |
| 24 | /// \f[J = \begin{bmatrix}0 & -a^T & 0 & a^T\end{bmatrix}\f] |
| 25 | /// |
| 26 | /// Used terms (here and below, everything in world space):\n |
| 27 | /// a = axis around which rotation is constrained (normalized).\n |
| 28 | /// x1, x2 = center of mass for the bodies.\n |
| 29 | /// v = [v1, w1, v2, w2].\n |
| 30 | /// v1, v2 = linear velocity of body 1 and 2.\n |
| 31 | /// w1, w2 = angular velocity of body 1 and 2.\n |
| 32 | /// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n |
| 33 | /// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n |
| 34 | /// b = velocity bias.\n |
| 35 | /// \f$\beta\f$ = baumgarte constant. |
| 36 | class AngleConstraintPart |
| 37 | { |
| 38 | /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated |
| 39 | JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, float inLambda) const |
| 40 | { |
| 41 | // Apply impulse if delta is not zero |
| 42 | if (inLambda != 0.0f) |
| 43 | { |
| 44 | // Calculate velocity change due to constraint |
| 45 | // |
| 46 | // Impulse: |
| 47 | // P = J^T lambda |
| 48 | // |
| 49 | // Euler velocity integration: |
| 50 | // v' = v + M^-1 P |
| 51 | if (ioBody1.IsDynamic()) |
| 52 | ioBody1.GetMotionProperties()->SubAngularVelocityStep(inLambda * mInvI1_Axis); |
| 53 | if (ioBody2.IsDynamic()) |
| 54 | ioBody2.GetMotionProperties()->AddAngularVelocityStep(inLambda * mInvI2_Axis); |
| 55 | return true; |
| 56 | } |
| 57 | |
| 58 | return false; |
| 59 | } |
| 60 | |
| 61 | /// Internal helper function to calculate the inverse effective mass |
| 62 | JPH_INLINE float CalculateInverseEffectiveMass(const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis) |
| 63 | { |
| 64 | JPH_ASSERT(inWorldSpaceAxis.IsNormalized(1.0e-4f)); |
| 65 | |
| 66 | // Calculate properties used below |
| 67 | mInvI1_Axis = inBody1.IsDynamic()? inBody1.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody1.GetRotation(), inWorldSpaceAxis) : Vec3::sZero(); |
| 68 | mInvI2_Axis = inBody2.IsDynamic()? inBody2.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody2.GetRotation(), inWorldSpaceAxis) : Vec3::sZero(); |
| 69 | |
| 70 | // Calculate inverse effective mass: K = J M^-1 J^T |
| 71 | return inWorldSpaceAxis.Dot(mInvI1_Axis + mInvI2_Axis); |
| 72 | } |
| 73 | |
| 74 | public: |
| 75 | /// Calculate properties used during the functions below |
| 76 | /// @param inBody1 The first body that this constraint is attached to |
| 77 | /// @param inBody2 The second body that this constraint is attached to |
| 78 | /// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized) |
| 79 | /// Set the following terms to zero if you don't want to drive the constraint to zero with a spring: |
| 80 | /// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b |
| 81 | inline void CalculateConstraintProperties(const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias = 0.0f) |
| 82 | { |
| 83 | float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis); |
| 84 | |
| 85 | if (inv_effective_mass == 0.0f) |
| 86 | Deactivate(); |
| 87 | else |
| 88 | { |
| 89 | mEffectiveMass = 1.0f / inv_effective_mass; |
| 90 | mSpringPart.CalculateSpringPropertiesWithBias(inBias); |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | /// Calculate properties used during the functions below |
| 95 | /// @param inDeltaTime Time step |
| 96 | /// @param inBody1 The first body that this constraint is attached to |
| 97 | /// @param inBody2 The second body that this constraint is attached to |
| 98 | /// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized) |
| 99 | /// Set the following terms to zero if you don't want to drive the constraint to zero with a spring: |
| 100 | /// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b |
| 101 | /// @param inC Value of the constraint equation (C) |
| 102 | /// @param inFrequency Oscillation frequency (Hz) |
| 103 | /// @param inDamping Damping factor (0 = no damping, 1 = critical damping) |
| 104 | inline void CalculateConstraintPropertiesWithFrequencyAndDamping(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, float inFrequency, float inDamping) |
| 105 | { |
| 106 | float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis); |
| 107 | |
| 108 | if (inv_effective_mass == 0.0f) |
| 109 | Deactivate(); |
| 110 | else |
| 111 | mSpringPart.CalculateSpringPropertiesWithFrequencyAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inFrequency, inDamping, mEffectiveMass); |
| 112 | } |
| 113 | |
| 114 | /// Calculate properties used during the functions below |
| 115 | /// @param inDeltaTime Time step |
| 116 | /// @param inBody1 The first body that this constraint is attached to |
| 117 | /// @param inBody2 The second body that this constraint is attached to |
| 118 | /// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized) |
| 119 | /// Set the following terms to zero if you don't want to drive the constraint to zero with a spring: |
| 120 | /// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b |
| 121 | /// @param inC Value of the constraint equation (C) |
| 122 | /// @param inStiffness Spring stiffness k. |
| 123 | /// @param inDamping Spring damping coefficient c. |
| 124 | inline void CalculateConstraintPropertiesWithStiffnessAndDamping(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, float inStiffness, float inDamping) |
| 125 | { |
| 126 | float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis); |
| 127 | |
| 128 | if (inv_effective_mass == 0.0f) |
| 129 | Deactivate(); |
| 130 | else |
| 131 | mSpringPart.CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inStiffness, inDamping, mEffectiveMass); |
| 132 | } |
| 133 | |
| 134 | /// Selects one of the above functions based on the spring settings |
| 135 | inline void CalculateConstraintPropertiesWithSettings(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, const SpringSettings &inSpringSettings) |
| 136 | { |
| 137 | float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis); |
| 138 | |
| 139 | if (inv_effective_mass == 0.0f) |
| 140 | Deactivate(); |
| 141 | else if (inSpringSettings.mMode == ESpringMode::FrequencyAndDamping) |
| 142 | mSpringPart.CalculateSpringPropertiesWithFrequencyAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings.mFrequency, inSpringSettings.mDamping, mEffectiveMass); |
| 143 | else |
| 144 | mSpringPart.CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings.mStiffness, inSpringSettings.mDamping, mEffectiveMass); |
| 145 | } |
| 146 | |
| 147 | /// Deactivate this constraint |
| 148 | inline void Deactivate() |
| 149 | { |
| 150 | mEffectiveMass = 0.0f; |
| 151 | mTotalLambda = 0.0f; |
| 152 | } |
| 153 | |
| 154 | /// Check if constraint is active |
| 155 | inline bool IsActive() const |
| 156 | { |
| 157 | return mEffectiveMass != 0.0f; |
| 158 | } |
| 159 | |
| 160 | /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses |
| 161 | /// @param ioBody1 The first body that this constraint is attached to |
| 162 | /// @param ioBody2 The second body that this constraint is attached to |
| 163 | /// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame |
| 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 | /// @param ioBody1 The first body that this constraint is attached to |
| 172 | /// @param ioBody2 The second body that this constraint is attached to |
| 173 | /// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized) |
| 174 | /// @param inMinLambda Minimum angular impulse to apply (N m s) |
| 175 | /// @param inMaxLambda Maximum angular impulse to apply (N m s) |
| 176 | inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda) |
| 177 | { |
| 178 | // Lagrange multiplier is: |
| 179 | // |
| 180 | // lambda = -K^-1 (J v + b) |
| 181 | float lambda = mEffectiveMass * (inWorldSpaceAxis.Dot(ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity()) - mSpringPart.GetBias(mTotalLambda)); |
| 182 | float new_lambda = Clamp(mTotalLambda + lambda, inMinLambda, inMaxLambda); // Clamp impulse |
| 183 | lambda = new_lambda - mTotalLambda; // Lambda potentially got clamped, calculate the new impulse to apply |
| 184 | mTotalLambda = new_lambda; // Store accumulated impulse |
| 185 | |
| 186 | return ApplyVelocityStep(ioBody1, ioBody2, lambda); |
| 187 | } |
| 188 | |
| 189 | /// Return lagrange multiplier |
| 190 | float GetTotalLambda() const |
| 191 | { |
| 192 | return mTotalLambda; |
| 193 | } |
| 194 | |
| 195 | /// Iteratively update the position constraint. Makes sure C(...) == 0. |
| 196 | /// @param ioBody1 The first body that this constraint is attached to |
| 197 | /// @param ioBody2 The second body that this constraint is attached to |
| 198 | /// @param inC Value of the constraint equation (C) |
| 199 | /// @param inBaumgarte Baumgarte constant (fraction of the error to correct) |
| 200 | inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inC, float inBaumgarte) const |
| 201 | { |
| 202 | // Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint |
| 203 | if (inC != 0.0f && !mSpringPart.IsActive()) |
| 204 | { |
| 205 | // Calculate lagrange multiplier (lambda) for Baumgarte stabilization: |
| 206 | // |
| 207 | // lambda = -K^-1 * beta / dt * C |
| 208 | // |
| 209 | // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out |
| 210 | float lambda = -mEffectiveMass * inBaumgarte * inC; |
| 211 | |
| 212 | // Directly integrate velocity change for one time step |
| 213 | // |
| 214 | // Euler velocity integration: |
| 215 | // dv = M^-1 P |
| 216 | // |
| 217 | // Impulse: |
| 218 | // P = J^T lambda |
| 219 | // |
| 220 | // Euler position integration: |
| 221 | // x' = x + dv * dt |
| 222 | // |
| 223 | // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and |
| 224 | // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte |
| 225 | // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity |
| 226 | // integrate + a position integrate and then discard the velocity change. |
| 227 | if (ioBody1.IsDynamic()) |
| 228 | ioBody1.SubRotationStep(lambda * mInvI1_Axis); |
| 229 | if (ioBody2.IsDynamic()) |
| 230 | ioBody2.AddRotationStep(lambda * mInvI2_Axis); |
| 231 | return true; |
| 232 | } |
| 233 | |
| 234 | return false; |
| 235 | } |
| 236 | |
| 237 | /// Save state of this constraint part |
| 238 | void SaveState(StateRecorder &inStream) const |
| 239 | { |
| 240 | inStream.Write(mTotalLambda); |
| 241 | } |
| 242 | |
| 243 | /// Restore state of this constraint part |
| 244 | void RestoreState(StateRecorder &inStream) |
| 245 | { |
| 246 | inStream.Read(mTotalLambda); |
| 247 | } |
| 248 | |
| 249 | private: |
| 250 | Vec3 mInvI1_Axis; |
| 251 | Vec3 mInvI2_Axis; |
| 252 | float mEffectiveMass = 0.0f; |
| 253 | SpringPart mSpringPart; |
| 254 | float mTotalLambda = 0.0f; |
| 255 | }; |
| 256 | |
| 257 | JPH_NAMESPACE_END |