Constraint.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. JPH_DECLARE_SERIALIZABLE_VIRTUAL(JPH_EXPORT, ConstraintSettings)
  58. public:
  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 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. /// Used only when the constraint is active. Override for the number of solver velocity iterations to run, 0 means use the default in PhysicsSettings::mNumVelocitySteps. The number of iterations to use is the max of all contacts and constraints in the island.
  70. uint mNumVelocityStepsOverride = 0;
  71. /// Used only when the constraint is active. Override for the number of solver position iterations to run, 0 means use the default in PhysicsSettings::mNumPositionSteps. The number of iterations to use is the max of all contacts and constraints in the island.
  72. uint 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. /// Don't allow (copy) constructing this base class, but allow derived classes to (copy) construct themselves
  79. ConstraintSettings() = default;
  80. ConstraintSettings(const ConstraintSettings &) = default;
  81. ConstraintSettings & operator = (const ConstraintSettings &) = default;
  82. /// This function should not be called directly, it is used by sRestoreFromBinaryState.
  83. virtual void RestoreBinaryState(StreamIn &inStream);
  84. };
  85. /// Base class for all physics constraints. A constraint removes one or more degrees of freedom for a rigid body.
  86. class JPH_EXPORT Constraint : public RefTarget<Constraint>, public NonCopyable
  87. {
  88. public:
  89. JPH_OVERRIDE_NEW_DELETE
  90. /// Constructor
  91. explicit Constraint(const ConstraintSettings &inSettings) :
  92. #ifdef JPH_DEBUG_RENDERER
  93. mDrawConstraintSize(inSettings.mDrawConstraintSize),
  94. #endif // JPH_DEBUG_RENDERER
  95. mConstraintPriority(inSettings.mConstraintPriority),
  96. mNumVelocityStepsOverride(uint8(inSettings.mNumVelocityStepsOverride)),
  97. mNumPositionStepsOverride(uint8(inSettings.mNumPositionStepsOverride)),
  98. mEnabled(inSettings.mEnabled),
  99. mUserData(inSettings.mUserData)
  100. {
  101. JPH_ASSERT(inSettings.mNumVelocityStepsOverride < 256);
  102. JPH_ASSERT(inSettings.mNumPositionStepsOverride < 256);
  103. }
  104. /// Virtual destructor
  105. virtual ~Constraint() = default;
  106. /// Get the type of a constraint
  107. virtual EConstraintType GetType() const { return EConstraintType::Constraint; }
  108. /// Get the sub type of a constraint
  109. virtual EConstraintSubType GetSubType() const = 0;
  110. /// Priority of the constraint when solving. Higher numbers have are more likely to be solved correctly.
  111. /// 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.
  112. uint32 GetConstraintPriority() const { return mConstraintPriority; }
  113. void SetConstraintPriority(uint32 inPriority) { mConstraintPriority = inPriority; }
  114. /// Used only when the constraint is active. Override for the number of solver velocity iterations to run, 0 means use the default in PhysicsSettings::mNumVelocitySteps. The number of iterations to use is the max of all contacts and constraints in the island.
  115. void SetNumVelocityStepsOverride(uint inN) { JPH_ASSERT(inN < 256); mNumVelocityStepsOverride = uint8(inN); }
  116. uint GetNumVelocityStepsOverride() const { return mNumVelocityStepsOverride; }
  117. /// Used only when the constraint is active. Override for the number of solver position iterations to run, 0 means use the default in PhysicsSettings::mNumPositionSteps. The number of iterations to use is the max of all contacts and constraints in the island.
  118. void SetNumPositionStepsOverride(uint inN) { JPH_ASSERT(inN < 256); mNumPositionStepsOverride = uint8(inN); }
  119. uint GetNumPositionStepsOverride() const { return mNumPositionStepsOverride; }
  120. /// Enable / disable this constraint. This can e.g. be used to implement a breakable constraint by detecting that the constraint impulse
  121. /// (see e.g. PointConstraint::GetTotalLambdaPosition) went over a certain limit and then disabling the constraint.
  122. /// Note that although a disabled constraint will not affect the simulation in any way anymore, it does incur some processing overhead.
  123. /// 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).
  124. void SetEnabled(bool inEnabled) { mEnabled = inEnabled; }
  125. /// Test if a constraint is enabled.
  126. bool GetEnabled() const { return mEnabled; }
  127. /// Access to the user data, can be used for anything by the application
  128. uint64 GetUserData() const { return mUserData; }
  129. void SetUserData(uint64 inUserData) { mUserData = inUserData; }
  130. /// Notify the constraint that the shape of a body has changed and that its center of mass has moved by inDeltaCOM.
  131. /// Bodies don't know which constraints are connected to them so the user is responsible for notifying the relevant constraints when a body changes.
  132. /// @param inBodyID ID of the body that has changed
  133. /// @param inDeltaCOM The delta of the center of mass of the body (shape->GetCenterOfMass() - shape_before_change->GetCenterOfMass())
  134. virtual void NotifyShapeChanged(const BodyID &inBodyID, Vec3Arg inDeltaCOM) = 0;
  135. /// Notify the system that the configuration of the bodies and/or constraint has changed enough so that the warm start impulses should not be applied the next frame.
  136. /// You can use this function for example when repositioning a ragdoll through Ragdoll::SetPose in such a way that the orientation of the bodies completely changes so that
  137. /// the previous frame impulses are no longer a good approximation of what the impulses will be in the next frame. Calling this function when there are no big changes
  138. /// will result in the constraints being much 'softer' than usual so they are more easily violated (e.g. a long chain of bodies might sag a bit if you call this every frame).
  139. virtual void ResetWarmStart() = 0;
  140. ///@name Solver interface
  141. ///@{
  142. virtual bool IsActive() const { return mEnabled; }
  143. virtual void SetupVelocityConstraint(float inDeltaTime) = 0;
  144. virtual void WarmStartVelocityConstraint(float inWarmStartImpulseRatio) = 0;
  145. virtual bool SolveVelocityConstraint(float inDeltaTime) = 0;
  146. virtual bool SolvePositionConstraint(float inDeltaTime, float inBaumgarte) = 0;
  147. ///@}
  148. /// Link bodies that are connected by this constraint in the island builder
  149. virtual void BuildIslands(uint32 inConstraintIndex, IslandBuilder &ioBuilder, BodyManager &inBodyManager) = 0;
  150. /// Link bodies that are connected by this constraint in the same split. Returns the split index.
  151. virtual uint BuildIslandSplits(LargeIslandSplitter &ioSplitter) const = 0;
  152. #ifdef JPH_DEBUG_RENDERER
  153. // Drawing interface
  154. virtual void DrawConstraint(DebugRenderer *inRenderer) const = 0;
  155. virtual void DrawConstraintLimits([[maybe_unused]] DebugRenderer *inRenderer) const { }
  156. virtual void DrawConstraintReferenceFrame([[maybe_unused]] DebugRenderer *inRenderer) const { }
  157. /// Size of constraint when drawing it through the debug renderer
  158. float GetDrawConstraintSize() const { return mDrawConstraintSize; }
  159. void SetDrawConstraintSize(float inSize) { mDrawConstraintSize = inSize; }
  160. #endif // JPH_DEBUG_RENDERER
  161. /// Saving state for replay
  162. virtual void SaveState(StateRecorder &inStream) const;
  163. /// Restoring state for replay
  164. virtual void RestoreState(StateRecorder &inStream);
  165. /// Debug function to convert a constraint to its settings, note that this will not save to which bodies the constraint is connected to
  166. virtual Ref<ConstraintSettings> GetConstraintSettings() const = 0;
  167. protected:
  168. /// Helper function to copy settings back to constraint settings for this base class
  169. void ToConstraintSettings(ConstraintSettings &outSettings) const;
  170. #ifdef JPH_DEBUG_RENDERER
  171. /// Size of constraint when drawing it through the debug renderer
  172. float mDrawConstraintSize;
  173. #endif // JPH_DEBUG_RENDERER
  174. private:
  175. friend class ConstraintManager;
  176. /// Index that indicates this constraint is not in the constraint manager
  177. static constexpr uint32 cInvalidConstraintIndex = 0xffffffff;
  178. /// Index in the mConstraints list of the ConstraintManager for easy finding
  179. uint32 mConstraintIndex = cInvalidConstraintIndex;
  180. /// Priority of the constraint when solving. Higher numbers have are more likely to be solved correctly.
  181. uint32 mConstraintPriority = 0;
  182. /// Used only when the constraint is active. Override for the number of solver velocity iterations to run, 0 means use the default in PhysicsSettings::mNumVelocitySteps. The number of iterations to use is the max of all contacts and constraints in the island.
  183. uint8 mNumVelocityStepsOverride = 0;
  184. /// Used only when the constraint is active. Override for the number of solver position iterations to run, 0 means use the default in PhysicsSettings::mNumPositionSteps. The number of iterations to use is the max of all contacts and constraints in the island.
  185. uint8 mNumPositionStepsOverride = 0;
  186. /// If this constraint is currently enabled
  187. bool mEnabled = true;
  188. /// User data value (can be used by application)
  189. uint64 mUserData;
  190. };
  191. JPH_NAMESPACE_END