RackAndPinionConstraintPart.h 6.8 KB

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