Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/AngleConstraintPart.h
9913 views
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)1// SPDX-FileCopyrightText: 2021 Jorrit Rouwe2// SPDX-License-Identifier: MIT34#pragma once56#include <Jolt/Physics/Body/Body.h>7#include <Jolt/Physics/Constraints/ConstraintPart/SpringPart.h>8#include <Jolt/Physics/Constraints/SpringSettings.h>9#include <Jolt/Physics/StateRecorder.h>1011JPH_NAMESPACE_BEGIN1213/// Constraint that constrains rotation along 1 axis14///15/// Based on: "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, see section 2.4.516///17/// Constraint equation (eq 108):18///19/// \f[C = \theta(t) - \theta_{min}\f]20///21/// Jacobian (eq 109):22///23/// \f[J = \begin{bmatrix}0 & -a^T & 0 & a^T\end{bmatrix}\f]24///25/// Used terms (here and below, everything in world space):\n26/// a = axis around which rotation is constrained (normalized).\n27/// x1, x2 = center of mass for the bodies.\n28/// v = [v1, w1, v2, w2].\n29/// v1, v2 = linear velocity of body 1 and 2.\n30/// w1, w2 = angular velocity of body 1 and 2.\n31/// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n32/// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n33/// b = velocity bias.\n34/// \f$\beta\f$ = baumgarte constant.35class AngleConstraintPart36{37/// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated38JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, float inLambda) const39{40// Apply impulse if delta is not zero41if (inLambda != 0.0f)42{43// Calculate velocity change due to constraint44//45// Impulse:46// P = J^T lambda47//48// Euler velocity integration:49// v' = v + M^-1 P50if (ioBody1.IsDynamic())51ioBody1.GetMotionProperties()->SubAngularVelocityStep(inLambda * mInvI1_Axis);52if (ioBody2.IsDynamic())53ioBody2.GetMotionProperties()->AddAngularVelocityStep(inLambda * mInvI2_Axis);54return true;55}5657return false;58}5960/// Internal helper function to calculate the inverse effective mass61JPH_INLINE float CalculateInverseEffectiveMass(const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis)62{63JPH_ASSERT(inWorldSpaceAxis.IsNormalized(1.0e-4f));6465// Calculate properties used below66mInvI1_Axis = inBody1.IsDynamic()? inBody1.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody1.GetRotation(), inWorldSpaceAxis) : Vec3::sZero();67mInvI2_Axis = inBody2.IsDynamic()? inBody2.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody2.GetRotation(), inWorldSpaceAxis) : Vec3::sZero();6869// Calculate inverse effective mass: K = J M^-1 J^T70return inWorldSpaceAxis.Dot(mInvI1_Axis + mInvI2_Axis);71}7273public:74/// Calculate properties used during the functions below75/// @param inBody1 The first body that this constraint is attached to76/// @param inBody2 The second body that this constraint is attached to77/// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized)78/// Set the following terms to zero if you don't want to drive the constraint to zero with a spring:79/// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b80inline void CalculateConstraintProperties(const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias = 0.0f)81{82float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis);8384if (inv_effective_mass == 0.0f)85Deactivate();86else87{88mEffectiveMass = 1.0f / inv_effective_mass;89mSpringPart.CalculateSpringPropertiesWithBias(inBias);90}91}9293/// Calculate properties used during the functions below94/// @param inDeltaTime Time step95/// @param inBody1 The first body that this constraint is attached to96/// @param inBody2 The second body that this constraint is attached to97/// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized)98/// Set the following terms to zero if you don't want to drive the constraint to zero with a spring:99/// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b100/// @param inC Value of the constraint equation (C)101/// @param inFrequency Oscillation frequency (Hz)102/// @param inDamping Damping factor (0 = no damping, 1 = critical damping)103inline void CalculateConstraintPropertiesWithFrequencyAndDamping(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, float inFrequency, float inDamping)104{105float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis);106107if (inv_effective_mass == 0.0f)108Deactivate();109else110mSpringPart.CalculateSpringPropertiesWithFrequencyAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inFrequency, inDamping, mEffectiveMass);111}112113/// Calculate properties used during the functions below114/// @param inDeltaTime Time step115/// @param inBody1 The first body that this constraint is attached to116/// @param inBody2 The second body that this constraint is attached to117/// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized)118/// Set the following terms to zero if you don't want to drive the constraint to zero with a spring:119/// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b120/// @param inC Value of the constraint equation (C)121/// @param inStiffness Spring stiffness k.122/// @param inDamping Spring damping coefficient c.123inline void CalculateConstraintPropertiesWithStiffnessAndDamping(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, float inStiffness, float inDamping)124{125float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis);126127if (inv_effective_mass == 0.0f)128Deactivate();129else130mSpringPart.CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inStiffness, inDamping, mEffectiveMass);131}132133/// Selects one of the above functions based on the spring settings134inline void CalculateConstraintPropertiesWithSettings(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, const SpringSettings &inSpringSettings)135{136float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis);137138if (inv_effective_mass == 0.0f)139Deactivate();140else if (inSpringSettings.mMode == ESpringMode::FrequencyAndDamping)141mSpringPart.CalculateSpringPropertiesWithFrequencyAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings.mFrequency, inSpringSettings.mDamping, mEffectiveMass);142else143mSpringPart.CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings.mStiffness, inSpringSettings.mDamping, mEffectiveMass);144}145146/// Deactivate this constraint147inline void Deactivate()148{149mEffectiveMass = 0.0f;150mTotalLambda = 0.0f;151}152153/// Check if constraint is active154inline bool IsActive() const155{156return mEffectiveMass != 0.0f;157}158159/// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses160/// @param ioBody1 The first body that this constraint is attached to161/// @param ioBody2 The second body that this constraint is attached to162/// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame163inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)164{165mTotalLambda *= inWarmStartImpulseRatio;166ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);167}168169/// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.170/// @param ioBody1 The first body that this constraint is attached to171/// @param ioBody2 The second body that this constraint is attached to172/// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized)173/// @param inMinLambda Minimum angular impulse to apply (N m s)174/// @param inMaxLambda Maximum angular impulse to apply (N m s)175inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)176{177// Lagrange multiplier is:178//179// lambda = -K^-1 (J v + b)180float lambda = mEffectiveMass * (inWorldSpaceAxis.Dot(ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity()) - mSpringPart.GetBias(mTotalLambda));181float new_lambda = Clamp(mTotalLambda + lambda, inMinLambda, inMaxLambda); // Clamp impulse182lambda = new_lambda - mTotalLambda; // Lambda potentially got clamped, calculate the new impulse to apply183mTotalLambda = new_lambda; // Store accumulated impulse184185return ApplyVelocityStep(ioBody1, ioBody2, lambda);186}187188/// Return lagrange multiplier189float GetTotalLambda() const190{191return mTotalLambda;192}193194/// Iteratively update the position constraint. Makes sure C(...) == 0.195/// @param ioBody1 The first body that this constraint is attached to196/// @param ioBody2 The second body that this constraint is attached to197/// @param inC Value of the constraint equation (C)198/// @param inBaumgarte Baumgarte constant (fraction of the error to correct)199inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inC, float inBaumgarte) const200{201// Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint202if (inC != 0.0f && !mSpringPart.IsActive())203{204// Calculate lagrange multiplier (lambda) for Baumgarte stabilization:205//206// lambda = -K^-1 * beta / dt * C207//208// We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out209float lambda = -mEffectiveMass * inBaumgarte * inC;210211// Directly integrate velocity change for one time step212//213// Euler velocity integration:214// dv = M^-1 P215//216// Impulse:217// P = J^T lambda218//219// Euler position integration:220// x' = x + dv * dt221//222// Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and223// Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte224// stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity225// integrate + a position integrate and then discard the velocity change.226if (ioBody1.IsDynamic())227ioBody1.SubRotationStep(lambda * mInvI1_Axis);228if (ioBody2.IsDynamic())229ioBody2.AddRotationStep(lambda * mInvI2_Axis);230return true;231}232233return false;234}235236/// Save state of this constraint part237void SaveState(StateRecorder &inStream) const238{239inStream.Write(mTotalLambda);240}241242/// Restore state of this constraint part243void RestoreState(StateRecorder &inStream)244{245inStream.Read(mTotalLambda);246}247248private:249Vec3 mInvI1_Axis;250Vec3 mInvI2_Axis;251float mEffectiveMass = 0.0f;252SpringPart mSpringPart;253float mTotalLambda = 0.0f;254};255256JPH_NAMESPACE_END257258259