AngleConstraintPart.h 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Physics/Body/Body.h>
  5. #include <Jolt/Physics/Constraints/ConstraintPart/SpringPart.h>
  6. #include <Jolt/Physics/StateRecorder.h>
  7. JPH_NAMESPACE_BEGIN
  8. /// Constraint that constrains rotation along 1 axis
  9. ///
  10. /// Based on: "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, see section 2.4.5
  11. ///
  12. /// Constraint equation (eq 108):
  13. ///
  14. /// \f[C = \theta(t) - \theta_{min}\f]
  15. ///
  16. /// Jacobian (eq 109):
  17. ///
  18. /// \f[J = \begin{bmatrix}0 & -a^T & 0 & a^T\end{bmatrix}\f]
  19. ///
  20. /// Used terms (here and below, everything in world space):\n
  21. /// a = axis around which rotation is constrained (normalized).\n
  22. /// x1, x2 = center of mass for the bodies.\n
  23. /// v = [v1, w1, v2, w2].\n
  24. /// v1, v2 = linear velocity of body 1 and 2.\n
  25. /// w1, w2 = angular velocity of body 1 and 2.\n
  26. /// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n
  27. /// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n
  28. /// b = velocity bias.\n
  29. /// \f$\beta\f$ = baumgarte constant.
  30. class AngleConstraintPart
  31. {
  32. /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
  33. JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, float inLambda) const
  34. {
  35. // Apply impulse if delta is not zero
  36. if (inLambda != 0.0f)
  37. {
  38. // Calculate velocity change due to constraint
  39. //
  40. // Impulse:
  41. // P = J^T lambda
  42. //
  43. // Euler velocity integration:
  44. // v' = v + M^-1 P
  45. if (ioBody1.IsDynamic())
  46. ioBody1.GetMotionProperties()->SubAngularVelocityStep(inLambda * mInvI1_Axis);
  47. if (ioBody2.IsDynamic())
  48. ioBody2.GetMotionProperties()->AddAngularVelocityStep(inLambda * mInvI2_Axis);
  49. return true;
  50. }
  51. return false;
  52. }
  53. public:
  54. /// Calculate properties used during the functions below
  55. /// @param inDeltaTime Time step
  56. /// @param inBody1 The first body that this constraint is attached to
  57. /// @param inBody2 The second body that this constraint is attached to
  58. /// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized)
  59. /// Set the following terms to zero if you don't want to drive the constraint to zero with a spring:
  60. /// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b
  61. /// @param inC Value of the constraint equation (C)
  62. /// @param inFrequency Oscillation frequency (Hz)
  63. /// @param inDamping Damping factor (0 = no damping, 1 = critical damping)
  64. inline void CalculateConstraintProperties(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias = 0.0f, float inC = 0.0f, float inFrequency = 0.0f, float inDamping = 0.0f)
  65. {
  66. JPH_ASSERT(inWorldSpaceAxis.IsNormalized(1.0e-4f));
  67. // Calculate properties used below
  68. mInvI1_Axis = inBody1.IsDynamic()? inBody1.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody1.GetRotation(), inWorldSpaceAxis) : Vec3::sZero();
  69. mInvI2_Axis = inBody2.IsDynamic()? inBody2.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody2.GetRotation(), inWorldSpaceAxis) : Vec3::sZero();
  70. // Calculate inverse effective mass: K = J M^-1 J^T
  71. float inv_effective_mass = inWorldSpaceAxis.Dot(mInvI1_Axis + mInvI2_Axis);
  72. // Calculate effective mass and spring properties
  73. mSpringPart.CalculateSpringProperties(inDeltaTime, inv_effective_mass, inBias, inC, inFrequency, inDamping, mEffectiveMass);
  74. }
  75. /// Deactivate this constraint
  76. inline void Deactivate()
  77. {
  78. mEffectiveMass = 0.0f;
  79. mTotalLambda = 0.0f;
  80. }
  81. /// Check if constraint is active
  82. inline bool IsActive() const
  83. {
  84. return mEffectiveMass != 0.0f;
  85. }
  86. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  87. /// @param ioBody1 The first body that this constraint is attached to
  88. /// @param ioBody2 The second body that this constraint is attached to
  89. /// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame
  90. inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
  91. {
  92. mTotalLambda *= inWarmStartImpulseRatio;
  93. ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
  94. }
  95. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  96. /// @param ioBody1 The first body that this constraint is attached to
  97. /// @param ioBody2 The second body that this constraint is attached to
  98. /// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized)
  99. /// @param inMinLambda Minimum angular impulse to apply (N m s)
  100. /// @param inMaxLambda Maximum angular impulse to apply (N m s)
  101. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)
  102. {
  103. // Lagrange multiplier is:
  104. //
  105. // lambda = -K^-1 (J v + b)
  106. float lambda = mEffectiveMass * (inWorldSpaceAxis.Dot(ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity()) - mSpringPart.GetBias(mTotalLambda));
  107. float new_lambda = Clamp(mTotalLambda + lambda, inMinLambda, inMaxLambda); // Clamp impulse
  108. lambda = new_lambda - mTotalLambda; // Lambda potentially got clamped, calculate the new impulse to apply
  109. mTotalLambda = new_lambda; // Store accumulated impulse
  110. return ApplyVelocityStep(ioBody1, ioBody2, lambda);
  111. }
  112. /// Return lagrange multiplier
  113. float GetTotalLambda() const
  114. {
  115. return mTotalLambda;
  116. }
  117. /// Iteratively update the position constraint. Makes sure C(...) == 0.
  118. /// @param ioBody1 The first body that this constraint is attached to
  119. /// @param ioBody2 The second body that this constraint is attached to
  120. /// @param inC Value of the constraint equation (C)
  121. /// @param inBaumgarte Baumgarte constant (fraction of the error to correct)
  122. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inC, float inBaumgarte) const
  123. {
  124. // Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint
  125. if (inC != 0.0f && !mSpringPart.IsActive())
  126. {
  127. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  128. //
  129. // lambda = -K^-1 * beta / dt * C
  130. //
  131. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  132. float lambda = -mEffectiveMass * inBaumgarte * inC;
  133. // Directly integrate velocity change for one time step
  134. //
  135. // Euler velocity integration:
  136. // dv = M^-1 P
  137. //
  138. // Impulse:
  139. // P = J^T lambda
  140. //
  141. // Euler position integration:
  142. // x' = x + dv * dt
  143. //
  144. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  145. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  146. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  147. // integrate + a position integrate and then discard the velocity change.
  148. if (ioBody1.IsDynamic())
  149. ioBody1.SubRotationStep(lambda * mInvI1_Axis);
  150. if (ioBody2.IsDynamic())
  151. ioBody2.AddRotationStep(lambda * mInvI2_Axis);
  152. return true;
  153. }
  154. return false;
  155. }
  156. /// Save state of this constraint part
  157. void SaveState(StateRecorder &inStream) const
  158. {
  159. inStream.Write(mTotalLambda);
  160. }
  161. /// Restore state of this constraint part
  162. void RestoreState(StateRecorder &inStream)
  163. {
  164. inStream.Read(mTotalLambda);
  165. }
  166. private:
  167. Vec3 mInvI1_Axis;
  168. Vec3 mInvI2_Axis;
  169. float mEffectiveMass = 0.0f;
  170. SpringPart mSpringPart;
  171. float mTotalLambda = 0.0f;
  172. };
  173. JPH_NAMESPACE_END