RackAndPinionConstraintPart.h 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Physics/Body/Body.h>
  6. #include <Jolt/Physics/StateRecorder.h>
  7. JPH_NAMESPACE_BEGIN
  8. /// Constraint that constrains a rotation to a translation
  9. ///
  10. /// Constraint equation:
  11. ///
  12. /// C = Theta(t) - r d(t)
  13. ///
  14. /// Derivative:
  15. ///
  16. /// d/dt C = 0
  17. /// <=> w1 . a - r v2 . b = 0
  18. ///
  19. /// Jacobian:
  20. ///
  21. /// \f[J = \begin{bmatrix}0 & a^T & -r b^T & 0\end{bmatrix}\f]
  22. ///
  23. /// Used terms (here and below, everything in world space):\n
  24. /// a = axis around which body 1 rotates (normalized).\n
  25. /// b = axis along which body 2 slides (normalized).\n
  26. /// Theta(t) = rotation around a of body 1.\n
  27. /// d(t) = distance body 2 slides.\n
  28. /// r = ratio between rotation and translation.\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. /// \f$\beta\f$ = baumgarte constant.
  35. class RackAndPinionConstraintPart
  36. {
  37. /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
  38. JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, float inLambda) const
  39. {
  40. // Apply impulse if delta is not zero
  41. if (inLambda != 0.0f)
  42. {
  43. // Calculate velocity change due to constraint
  44. //
  45. // Impulse:
  46. // P = J^T lambda
  47. //
  48. // Euler velocity integration:
  49. // v' = v + M^-1 P
  50. ioBody1.GetMotionProperties()->AddAngularVelocityStep(inLambda * mInvI1_A);
  51. ioBody2.GetMotionProperties()->SubLinearVelocityStep(inLambda * mRatio_InvM2_B);
  52. return true;
  53. }
  54. return false;
  55. }
  56. public:
  57. /// Calculate properties used during the functions below
  58. /// @param inBody1 The first body that this constraint is attached to
  59. /// @param inBody2 The second body that this constraint is attached to
  60. /// @param inWorldSpaceHingeAxis The axis around which body 1 rotates
  61. /// @param inWorldSpaceSliderAxis The axis along which body 2 slides
  62. /// @param inRatio The ratio between rotation and translation
  63. inline void CalculateConstraintProperties(const Body &inBody1, Vec3Arg inWorldSpaceHingeAxis, const Body &inBody2, Vec3Arg inWorldSpaceSliderAxis, float inRatio)
  64. {
  65. JPH_ASSERT(inWorldSpaceHingeAxis.IsNormalized(1.0e-4f));
  66. JPH_ASSERT(inWorldSpaceSliderAxis.IsNormalized(1.0e-4f));
  67. // Calculate: I1^-1 a
  68. mInvI1_A = inBody1.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody1.GetRotation(), inWorldSpaceHingeAxis);
  69. // Calculate: r/m2 b
  70. float inv_m2 = inBody2.GetMotionProperties()->GetInverseMass();
  71. mRatio_InvM2_B = inRatio * inv_m2 * inWorldSpaceSliderAxis;
  72. // K^-1 = 1 / (J M^-1 J^T) = 1 / (a^T I1^-1 a + 1/m2 * r^2 * b . b)
  73. float inv_effective_mass = (inWorldSpaceHingeAxis.Dot(mInvI1_A) + inv_m2 * Square(inRatio));
  74. if (inv_effective_mass == 0.0f)
  75. Deactivate();
  76. else
  77. mEffectiveMass = 1.0f / inv_effective_mass;
  78. }
  79. /// Deactivate this constraint
  80. inline void Deactivate()
  81. {
  82. mEffectiveMass = 0.0f;
  83. mTotalLambda = 0.0f;
  84. }
  85. /// Check if constraint is active
  86. inline bool IsActive() const
  87. {
  88. return mEffectiveMass != 0.0f;
  89. }
  90. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  91. /// @param ioBody1 The first body that this constraint is attached to
  92. /// @param ioBody2 The second body that this constraint is attached to
  93. /// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame
  94. inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
  95. {
  96. mTotalLambda *= inWarmStartImpulseRatio;
  97. ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
  98. }
  99. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  100. /// @param ioBody1 The first body that this constraint is attached to
  101. /// @param ioBody2 The second body that this constraint is attached to
  102. /// @param inWorldSpaceHingeAxis The axis around which body 1 rotates
  103. /// @param inWorldSpaceSliderAxis The axis along which body 2 slides
  104. /// @param inRatio The ratio between rotation and translation
  105. inline bool SolveVelocityConstraint(Body &ioBody1, Vec3Arg inWorldSpaceHingeAxis, Body &ioBody2, Vec3Arg inWorldSpaceSliderAxis, float inRatio)
  106. {
  107. // Lagrange multiplier is:
  108. //
  109. // lambda = -K^-1 (J v + b)
  110. float lambda = mEffectiveMass * (inRatio * inWorldSpaceSliderAxis.Dot(ioBody2.GetLinearVelocity()) - inWorldSpaceHingeAxis.Dot(ioBody1.GetAngularVelocity()));
  111. mTotalLambda += lambda; // Store accumulated impulse
  112. return ApplyVelocityStep(ioBody1, ioBody2, lambda);
  113. }
  114. /// Return lagrange multiplier
  115. float GetTotalLambda() const
  116. {
  117. return mTotalLambda;
  118. }
  119. /// Iteratively update the position constraint. Makes sure C(...) == 0.
  120. /// @param ioBody1 The first body that this constraint is attached to
  121. /// @param ioBody2 The second body that this constraint is attached to
  122. /// @param inC Value of the constraint equation (C)
  123. /// @param inBaumgarte Baumgarte constant (fraction of the error to correct)
  124. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inC, float inBaumgarte) const
  125. {
  126. // Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint
  127. if (inC != 0.0f)
  128. {
  129. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  130. //
  131. // lambda = -K^-1 * beta / dt * C
  132. //
  133. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  134. float lambda = -mEffectiveMass * inBaumgarte * inC;
  135. // Directly integrate velocity change for one time step
  136. //
  137. // Euler velocity integration:
  138. // dv = M^-1 P
  139. //
  140. // Impulse:
  141. // P = J^T lambda
  142. //
  143. // Euler position integration:
  144. // x' = x + dv * dt
  145. //
  146. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  147. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  148. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  149. // integrate + a position integrate and then discard the velocity change.
  150. if (ioBody1.IsDynamic())
  151. ioBody1.AddRotationStep(lambda * mInvI1_A);
  152. if (ioBody2.IsDynamic())
  153. ioBody2.SubPositionStep(lambda * mRatio_InvM2_B);
  154. return true;
  155. }
  156. return false;
  157. }
  158. /// Save state of this constraint part
  159. void SaveState(StateRecorder &inStream) const
  160. {
  161. inStream.Write(mTotalLambda);
  162. }
  163. /// Restore state of this constraint part
  164. void RestoreState(StateRecorder &inStream)
  165. {
  166. inStream.Read(mTotalLambda);
  167. }
  168. private:
  169. Vec3 mInvI1_A;
  170. Vec3 mRatio_InvM2_B;
  171. float mEffectiveMass = 0.0f;
  172. float mTotalLambda = 0.0f;
  173. };
  174. JPH_NAMESPACE_END