Constraint.h 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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/Core/Reference.h>
  6. #include <Jolt/Core/NonCopyable.h>
  7. #include <Jolt/Core/Result.h>
  8. #include <Jolt/ObjectStream/SerializableObject.h>
  9. JPH_NAMESPACE_BEGIN
  10. class BodyID;
  11. class IslandBuilder;
  12. class LargeIslandSplitter;
  13. class BodyManager;
  14. class StateRecorder;
  15. class StreamIn;
  16. class StreamOut;
  17. #ifdef JPH_DEBUG_RENDERER
  18. class DebugRenderer;
  19. #endif // JPH_DEBUG_RENDERER
  20. /// Enum to identify constraint type
  21. enum class EConstraintType
  22. {
  23. Constraint,
  24. TwoBodyConstraint,
  25. };
  26. /// Enum to identify constraint sub type
  27. enum class EConstraintSubType
  28. {
  29. Fixed,
  30. Point,
  31. Hinge,
  32. Slider,
  33. Distance,
  34. Cone,
  35. SwingTwist,
  36. SixDOF,
  37. Path,
  38. Vehicle,
  39. RackAndPinion,
  40. Gear,
  41. Pulley,
  42. /// User defined constraint types start here
  43. User1,
  44. User2,
  45. User3,
  46. User4
  47. };
  48. /// Certain constraints support setting them up in local or world space. This governs what is used.
  49. enum class EConstraintSpace
  50. {
  51. LocalToBodyCOM, ///< All constraint properties are specified in local space to center of mass of the bodies that are being constrained (so e.g. 'constraint position 1' will be local to body 1 COM, 'constraint position 2' will be local to body 2 COM). Note that this means you need to subtract Shape::GetCenterOfMass() from positions!
  52. WorldSpace, ///< All constraint properties are specified in world space
  53. };
  54. /// Class used to store the configuration of a constraint. Allows run-time creation of constraints.
  55. class JPH_EXPORT ConstraintSettings : public SerializableObject, public RefTarget<ConstraintSettings>
  56. {
  57. public:
  58. JPH_DECLARE_SERIALIZABLE_VIRTUAL(JPH_EXPORT, ConstraintSettings)
  59. using ConstraintResult = Result<Ref<ConstraintSettings>>;
  60. /// Saves the contents of the constraint settings in binary form to inStream.
  61. virtual void SaveBinaryState(StreamOut &inStream) const;
  62. /// Creates a constraint of the correct type and restores its contents from the binary stream inStream.
  63. static ConstraintResult sRestoreFromBinaryState(StreamIn &inStream);
  64. /// If this constraint is enabled initially. Use Constraint::SetEnabled to toggle after creation.
  65. bool mEnabled = true;
  66. /// Priority of the constraint when solving. Higher numbers have are more likely to be solved correctly.
  67. /// Note that if you want a deterministic simulation and you cannot guarantee the order in which constraints are added/removed, you can make the priority for all constraints unique to get a deterministic ordering.
  68. uint32 mConstraintPriority = 0;
  69. /// Override for the number of solver velocity iterations to run, the total amount of iterations is the max of PhysicsSettings::mNumVelocitySteps and this for all constraints in the island.
  70. int mNumVelocityStepsOverride = 0;
  71. /// Override for the number of position velocity iterations to run, the total amount of iterations is the max of PhysicsSettings::mNumPositionSteps and this for all constraints in the island.
  72. int mNumPositionStepsOverride = 0;
  73. /// Size of constraint when drawing it through the debug renderer
  74. float mDrawConstraintSize = 1.0f;
  75. /// User data value (can be used by application)
  76. uint64 mUserData = 0;
  77. protected:
  78. /// This function should not be called directly, it is used by sRestoreFromBinaryState.
  79. virtual void RestoreBinaryState(StreamIn &inStream);
  80. };
  81. /// Base class for all physics constraints. A constraint removes one or more degrees of freedom for a rigid body.
  82. class JPH_EXPORT Constraint : public RefTarget<Constraint>, public NonCopyable
  83. {
  84. public:
  85. JPH_OVERRIDE_NEW_DELETE
  86. /// Constructor
  87. explicit Constraint(const ConstraintSettings &inSettings) :
  88. #ifdef JPH_DEBUG_RENDERER
  89. mDrawConstraintSize(inSettings.mDrawConstraintSize),
  90. #endif // JPH_DEBUG_RENDERER
  91. mConstraintPriority(inSettings.mConstraintPriority),
  92. mNumVelocityStepsOverride(inSettings.mNumVelocityStepsOverride),
  93. mNumPositionStepsOverride(inSettings.mNumPositionStepsOverride),
  94. mEnabled(inSettings.mEnabled),
  95. mUserData(inSettings.mUserData)
  96. {
  97. }
  98. /// Virtual destructor
  99. virtual ~Constraint() = default;
  100. /// Get the type of a constraint
  101. virtual EConstraintType GetType() const { return EConstraintType::Constraint; }
  102. /// Get the sub type of a constraint
  103. virtual EConstraintSubType GetSubType() const = 0;
  104. /// Priority of the constraint when solving. Higher numbers have are more likely to be solved correctly.
  105. /// Note that if you want a deterministic simulation and you cannot guarantee the order in which constraints are added/removed, you can make the priority for all constraints unique to get a deterministic ordering.
  106. uint32 GetConstraintPriority() const { return mConstraintPriority; }
  107. void SetConstraintPriority(uint32 inPriority) { mConstraintPriority = inPriority; }
  108. /// Override for the number of solver velocity iterations to run, the total amount of iterations is the max of PhysicsSettings::mNumVelocitySteps and this for all constraints in the island.
  109. void SetNumVelocityStepsOverride(int inN) { mNumVelocityStepsOverride = inN; }
  110. int GetNumVelocityStepsOverride() const { return mNumVelocityStepsOverride; }
  111. /// Override for the number of position velocity iterations to run, the total amount of iterations is the max of PhysicsSettings::mNumPositionSteps and this for all constraints in the island.
  112. void SetNumPositionStepsOverride(int inN) { mNumPositionStepsOverride = inN; }
  113. int GetNumPositionStepsOverride() const { return mNumPositionStepsOverride; }
  114. /// Enable / disable this constraint. This can e.g. be used to implement a breakable constraint by detecting that the constraint impulse
  115. /// (see e.g. PointConstraint::GetTotalLambdaPosition) went over a certain limit and then disabling the constraint.
  116. /// Note that although a disabled constraint will not affect the simulation in any way anymore, it does incur some processing overhead.
  117. /// Alternatively you can remove a constraint from the constraint manager (which may be more costly if you want to disable the constraint for a short while).
  118. void SetEnabled(bool inEnabled) { mEnabled = inEnabled; }
  119. /// Test if a constraint is enabled.
  120. bool GetEnabled() const { return mEnabled; }
  121. /// Access to the user data, can be used for anything by the application
  122. uint64 GetUserData() const { return mUserData; }
  123. void SetUserData(uint64 inUserData) { mUserData = inUserData; }
  124. /// Notify the constraint that the shape of a body has changed and that its center of mass has moved by inDeltaCOM.
  125. /// Bodies don't know which constraints are connected to them so the user is responsible for notifying the relevant constraints when a body changes.
  126. /// @param inBodyID ID of the body that has changed
  127. /// @param inDeltaCOM The delta of the center of mass of the body (shape->GetCenterOfMass() - shape_before_change->GetCenterOfMass())
  128. virtual void NotifyShapeChanged(const BodyID &inBodyID, Vec3Arg inDeltaCOM) = 0;
  129. ///@name Solver interface
  130. ///@{
  131. virtual bool IsActive() const { return mEnabled; }
  132. virtual void SetupVelocityConstraint(float inDeltaTime) = 0;
  133. virtual void WarmStartVelocityConstraint(float inWarmStartImpulseRatio) = 0;
  134. virtual bool SolveVelocityConstraint(float inDeltaTime) = 0;
  135. virtual bool SolvePositionConstraint(float inDeltaTime, float inBaumgarte) = 0;
  136. ///@}
  137. /// Link bodies that are connected by this constraint in the island builder
  138. virtual void BuildIslands(uint32 inConstraintIndex, IslandBuilder &ioBuilder, BodyManager &inBodyManager) = 0;
  139. /// Link bodies that are connected by this constraint in the same split. Returns the split index.
  140. virtual uint BuildIslandSplits(LargeIslandSplitter &ioSplitter) const = 0;
  141. #ifdef JPH_DEBUG_RENDERER
  142. // Drawing interface
  143. virtual void DrawConstraint(DebugRenderer *inRenderer) const = 0;
  144. virtual void DrawConstraintLimits([[maybe_unused]] DebugRenderer *inRenderer) const { }
  145. virtual void DrawConstraintReferenceFrame([[maybe_unused]] DebugRenderer *inRenderer) const { }
  146. /// Size of constraint when drawing it through the debug renderer
  147. float GetDrawConstraintSize() const { return mDrawConstraintSize; }
  148. void SetDrawConstraintSize(float inSize) { mDrawConstraintSize = inSize; }
  149. #endif // JPH_DEBUG_RENDERER
  150. /// Saving state for replay
  151. virtual void SaveState(StateRecorder &inStream) const;
  152. /// Restoring state for replay
  153. virtual void RestoreState(StateRecorder &inStream);
  154. /// Debug function to convert a constraint to its settings, note that this will not save to which bodies the constraint is connected to
  155. virtual Ref<ConstraintSettings> GetConstraintSettings() const = 0;
  156. protected:
  157. /// Helper function to copy settings back to constraint settings for this base class
  158. void ToConstraintSettings(ConstraintSettings &outSettings) const;
  159. #ifdef JPH_DEBUG_RENDERER
  160. /// Size of constraint when drawing it through the debug renderer
  161. float mDrawConstraintSize;
  162. #endif // JPH_DEBUG_RENDERER
  163. private:
  164. friend class ConstraintManager;
  165. /// Index that indicates this constraint is not in the constraint manager
  166. static constexpr uint32 cInvalidConstraintIndex = 0xffffffff;
  167. /// Index in the mConstraints list of the ConstraintManager for easy finding
  168. uint32 mConstraintIndex = cInvalidConstraintIndex;
  169. /// Priority of the constraint when solving. Higher numbers have are more likely to be solved correctly.
  170. uint32 mConstraintPriority = 0;
  171. /// Override for the number of solver velocity iterations to run, the total amount of iterations is the max of PhysicsSettings::mNumVelocitySteps and this for all constraints in the island.
  172. int mNumVelocityStepsOverride = 0;
  173. /// Override for the number of position velocity iterations to run, the total amount of iterations is the max of PhysicsSettings::mNumPositionSteps and this for all constraints in the island.
  174. int mNumPositionStepsOverride = 0;
  175. /// If this constraint is currently enabled
  176. bool mEnabled = true;
  177. /// User data value (can be used by application)
  178. uint64 mUserData;
  179. };
  180. JPH_NAMESPACE_END