PhysicsWorld.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #pragma once
  23. #include "BoundingBox.h"
  24. #include "Component.h"
  25. #include "HashSet.h"
  26. #include "Sphere.h"
  27. #include "Vector3.h"
  28. #include "VectorBuffer.h"
  29. #include <LinearMath/btIDebugDraw.h>
  30. class btCollisionConfiguration;
  31. class btCollisionShape;
  32. class btBroadphaseInterface;
  33. class btConstraintSolver;
  34. class btDiscreteDynamicsWorld;
  35. class btDispatcher;
  36. class btDynamicsWorld;
  37. class btPersistentManifold;
  38. namespace Urho3D
  39. {
  40. class CollisionShape;
  41. class Deserializer;
  42. class Constraint;
  43. class Model;
  44. class Node;
  45. class Ray;
  46. class RigidBody;
  47. class Scene;
  48. class Serializer;
  49. class XMLElement;
  50. struct CollisionGeometryData;
  51. /// Physics raycast hit.
  52. struct URHO3D_API PhysicsRaycastResult
  53. {
  54. /// Construct with defaults.
  55. PhysicsRaycastResult() :
  56. body_(0)
  57. {
  58. }
  59. /// Test for inequality, added to prevent GCC from complaining.
  60. bool operator != (const PhysicsRaycastResult& rhs) const { return position_ != rhs.position_ || normal_ != rhs.normal_ || distance_ != rhs.distance_ || body_ != rhs.body_; }
  61. /// Hit worldspace position.
  62. Vector3 position_;
  63. /// Hit worldspace normal.
  64. Vector3 normal_;
  65. /// Hit distance from ray origin.
  66. float distance_;
  67. /// Rigid body that was hit.
  68. RigidBody* body_;
  69. };
  70. /// Delayed world transform assignment for parented rigidbodies.
  71. struct DelayedWorldTransform
  72. {
  73. /// Rigid body.
  74. RigidBody* rigidBody_;
  75. /// Parent rigid body.
  76. RigidBody* parentRigidBody_;
  77. /// New world position.
  78. Vector3 worldPosition_;
  79. /// New world rotation.
  80. Quaternion worldRotation_;
  81. };
  82. static const float DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY = 100.0f;
  83. /// Physics simulation world component. Should be added only to the root scene node.
  84. class URHO3D_API PhysicsWorld : public Component, public btIDebugDraw
  85. {
  86. OBJECT(PhysicsWorld);
  87. friend void InternalPreTickCallback(btDynamicsWorld *world, btScalar timeStep);
  88. friend void InternalTickCallback(btDynamicsWorld *world, btScalar timeStep);
  89. public:
  90. /// Construct.
  91. PhysicsWorld(Context* scontext);
  92. /// Destruct.
  93. virtual ~PhysicsWorld();
  94. /// Register object factory.
  95. static void RegisterObject(Context* context);
  96. /// Check if an AABB is visible for debug drawing.
  97. virtual bool isVisible(const btVector3& aabbMin, const btVector3& aabbMax);
  98. /// Draw a physics debug line.
  99. virtual void drawLine(const btVector3& from, const btVector3& to, const btVector3& color);
  100. /// Log warning from the physics engine.
  101. virtual void reportErrorWarning(const char* warningString);
  102. /// Draw a physics debug contact point. Not implemented.
  103. virtual void drawContactPoint(const btVector3& pointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, const btVector3& color);
  104. /// Draw physics debug 3D text. Not implemented.
  105. virtual void draw3dText(const btVector3& location,const char* textString);
  106. /// Set debug draw flags.
  107. virtual void setDebugMode(int debugMode) { debugMode_ = debugMode; }
  108. /// Return debug draw flags.
  109. virtual int getDebugMode() const { return debugMode_; }
  110. /// Visualize the component as debug geometry.
  111. virtual void DrawDebugGeometry(DebugRenderer* debug, bool depthTest);
  112. /// Step the simulation forward.
  113. void Update(float timeStep);
  114. /// Refresh collisions only without updating dynamics.
  115. void UpdateCollisions();
  116. /// Set simulation substeps per second.
  117. void SetFps(int fps);
  118. /// Set gravity.
  119. void SetGravity(const Vector3& gravity);
  120. /// Set maximum number of physics substeps per frame. 0 (default) is unlimited. Positive values cap the amount. Use a negative value to enable an adaptive timestep. This may cause inconsistent physics behavior.
  121. void SetMaxSubSteps(int num);
  122. /// Set number of constraint solver iterations.
  123. void SetNumIterations(int num);
  124. /// Set whether to interpolate between simulation steps.
  125. void SetInterpolation(bool enable);
  126. /// Set whether to use Bullet's internal edge utility for trimesh collisions. Disabled by default.
  127. void SetInternalEdge(bool enable);
  128. /// Set split impulse collision mode. This is more accurate, but slower. Disabled by default.
  129. void SetSplitImpulse(bool enable);
  130. /// Set maximum angular velocity for network replication.
  131. void SetMaxNetworkAngularVelocity(float velocity);
  132. /// Perform a physics world raycast and return all hits.
  133. void Raycast(PODVector<PhysicsRaycastResult>& result, const Ray& ray, float maxDistance, unsigned collisionMask = M_MAX_UNSIGNED);
  134. /// Perform a physics world raycast and return the closest hit.
  135. void RaycastSingle(PhysicsRaycastResult& result, const Ray& ray, float maxDistance, unsigned collisionMask = M_MAX_UNSIGNED);
  136. /// Perform a physics world swept sphere test and return the closest hit.
  137. void SphereCast(PhysicsRaycastResult& result, const Ray& ray, float radius, float maxDistance, unsigned collisionMask = M_MAX_UNSIGNED);
  138. /// Perform a physics world swept convex test using a user-supplied collision shape and return the first hit.
  139. void ConvexCast(PhysicsRaycastResult& result, CollisionShape* shape, const Vector3& startPos, const Quaternion& startRot, const Vector3& endPos, const Quaternion& endRot, unsigned collisionMask = M_MAX_UNSIGNED);
  140. /// Perform a physics world swept convex test using a user-supplied Bullet collision shape and return the first hit.
  141. void ConvexCast(PhysicsRaycastResult& result, btCollisionShape* shape, const Vector3& startPos, const Quaternion& startRot, const Vector3& endPos, const Quaternion& endRot, unsigned collisionMask = M_MAX_UNSIGNED);
  142. /// Invalidate cached collision geometry for a model.
  143. void RemoveCachedGeometry(Model* model);
  144. /// Return rigid bodies by a sphere query.
  145. void GetRigidBodies(PODVector<RigidBody*>& result, const Sphere& sphere, unsigned collisionMask = M_MAX_UNSIGNED);
  146. /// Return rigid bodies by a box query.
  147. void GetRigidBodies(PODVector<RigidBody*>& result, const BoundingBox& box, unsigned collisionMask = M_MAX_UNSIGNED);
  148. /// Return rigid bodies that have been in collision with a specific body on the last simulation step.
  149. void GetRigidBodies(PODVector<RigidBody*>& result, const RigidBody* body);
  150. /// Return gravity.
  151. Vector3 GetGravity() const;
  152. /// Return maximum number of physics substeps per frame.
  153. int GetMaxSubSteps() const { return maxSubSteps_; }
  154. /// Return number of constraint solver iterations.
  155. int GetNumIterations() const;
  156. /// Return whether interpolation between simulation steps is enabled.
  157. bool GetInterpolation() const { return interpolation_; }
  158. /// Return whether Bullet's internal edge utility for trimesh collisions is enabled.
  159. bool GetInternalEdge() const { return internalEdge_; }
  160. /// Return whether split impulse collision mode is enabled.
  161. bool GetSplitImpulse() const;
  162. /// Return simulation steps per second.
  163. int GetFps() const { return fps_; }
  164. /// Return maximum angular velocity for network replication.
  165. float GetMaxNetworkAngularVelocity() const { return maxNetworkAngularVelocity_; }
  166. /// Add a rigid body to keep track of. Called by RigidBody.
  167. void AddRigidBody(RigidBody* body);
  168. /// Remove a rigid body. Called by RigidBody.
  169. void RemoveRigidBody(RigidBody* body);
  170. /// Add a collision shape to keep track of. Called by CollisionShape.
  171. void AddCollisionShape(CollisionShape* shape);
  172. /// Remove a collision shape. Called by CollisionShape.
  173. void RemoveCollisionShape(CollisionShape* shape);
  174. /// Add a constraint to keep track of. Called by Constraint.
  175. void AddConstraint(Constraint* joint);
  176. /// Remove a constraint. Called by Constraint.
  177. void RemoveConstraint(Constraint* joint);
  178. /// Add a delayed world transform assignment. Called by RigidBody.
  179. void AddDelayedWorldTransform(const DelayedWorldTransform& transform);
  180. /// Add debug geometry to the debug renderer.
  181. void DrawDebugGeometry(bool depthTest);
  182. /// Set debug renderer to use. Called both by PhysicsWorld itself and physics components.
  183. void SetDebugRenderer(DebugRenderer* debug);
  184. /// Set debug geometry depth test mode. Called both by PhysicsWorld itself and physics components.
  185. void SetDebugDepthTest(bool enable);
  186. /// Return the Bullet physics world.
  187. btDiscreteDynamicsWorld* GetWorld() { return world_; }
  188. /// Clean up the geometry cache.
  189. void CleanupGeometryCache();
  190. /// Return trimesh collision geometry cache.
  191. HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> >& GetTriMeshCache() { return triMeshCache_; }
  192. /// Return convex collision geometry cache.
  193. HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> >& GetConvexCache() { return convexCache_; }
  194. /// Set node dirtying to be disregarded.
  195. void SetApplyingTransforms(bool enable) { applyingTransforms_ = enable; }
  196. /// Return whether node dirtying should be disregarded.
  197. bool IsApplyingTransforms() const { return applyingTransforms_; }
  198. protected:
  199. /// Handle node being assigned.
  200. virtual void OnNodeSet(Node* node);
  201. private:
  202. /// Handle the scene subsystem update event, step simulation here.
  203. void HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData);
  204. /// Handle collision model reload finished.
  205. void HandleModelReloadFinished(StringHash eventType, VariantMap& eventData);
  206. /// Trigger update before each physics simulation step.
  207. void PreStep(float timeStep);
  208. /// Trigger update after ecah physics simulation step.
  209. void PostStep(float timeStep);
  210. /// Send accumulated collision events.
  211. void SendCollisionEvents();
  212. /// Bullet collision configuration.
  213. btCollisionConfiguration* collisionConfiguration_;
  214. /// Bullet collision dispatcher.
  215. btDispatcher* collisionDispatcher_;
  216. /// Bullet collision broadphase.
  217. btBroadphaseInterface* broadphase_;
  218. /// Bullet constraint solver.
  219. btConstraintSolver* solver_;
  220. /// Bullet physics world.
  221. btDiscreteDynamicsWorld* world_;
  222. /// Extra weak pointer to scene to allow for cleanup in case the world is destroyed before other components.
  223. WeakPtr<Scene> scene_;
  224. /// Rigid bodies in the world.
  225. PODVector<RigidBody*> rigidBodies_;
  226. /// Collision shapes in the world.
  227. PODVector<CollisionShape*> collisionShapes_;
  228. /// Constraints in the world.
  229. PODVector<Constraint*> constraints_;
  230. /// Collision pairs on this frame.
  231. HashMap<Pair<WeakPtr<RigidBody>, WeakPtr<RigidBody> >, btPersistentManifold* > currentCollisions_;
  232. /// Collision pairs on the previous frame. Used to check if a collision is "new." Manifolds are not guaranteed to exist anymore.
  233. HashMap<Pair<WeakPtr<RigidBody>, WeakPtr<RigidBody> >, btPersistentManifold* > previousCollisions_;
  234. /// Delayed (parented) world transform assignments.
  235. HashMap<RigidBody*, DelayedWorldTransform> delayedWorldTransforms_;
  236. /// Cache for trimesh geometry data by model and LOD level.
  237. HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> > triMeshCache_;
  238. /// Cache for convex geometry data by model and LOD level.
  239. HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> > convexCache_;
  240. /// Preallocated event data map for physics collision events.
  241. VariantMap physicsCollisionData_;
  242. /// Preallocated event data map for node collision events.
  243. VariantMap nodeCollisionData_;
  244. /// Preallocated buffer for physics collision contact data.
  245. VectorBuffer contacts_;
  246. /// Simulation substeps per second.
  247. unsigned fps_;
  248. /// Maximum number of simulation substeps per frame. 0 (default) unlimited, or negative values for adaptive timestep.
  249. int maxSubSteps_;
  250. /// Time accumulator for non-interpolated mode.
  251. float timeAcc_;
  252. /// Maximum angular velocity for network replication.
  253. float maxNetworkAngularVelocity_;
  254. /// Interpolation flag.
  255. bool interpolation_;
  256. /// Use internal edge utility flag.
  257. bool internalEdge_;
  258. /// Applying transforms flag.
  259. bool applyingTransforms_;
  260. /// Debug renderer.
  261. DebugRenderer* debugRenderer_;
  262. /// Debug draw flags.
  263. int debugMode_;
  264. /// Debug draw depth test mode.
  265. bool debugDepthTest_;
  266. };
  267. /// Register Physics library objects.
  268. void URHO3D_API RegisterPhysicsLibrary(Context* context);
  269. }