AngleConstraintPart.h 7.6 KB

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