PhysicsWorld.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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 steps per second.
  117. void SetFps(int fps);
  118. /// Set gravity.
  119. void SetGravity(Vector3 gravity);
  120. /// Set number of constraint solver iterations.
  121. void SetNumIterations(int num);
  122. /// Set whether to interpolate between simulation steps.
  123. void SetInterpolation(bool enable);
  124. /// Set whether to use Bullet's internal edge utility for trimesh collisions. Disabled by default.
  125. void SetInternalEdge(bool enable);
  126. /// Set split impulse collision mode. This is more accurate, but slower. Disabled by default.
  127. void SetSplitImpulse(bool enable);
  128. /// Set maximum angular velocity for network replication.
  129. void SetMaxNetworkAngularVelocity(float velocity);
  130. /// Perform a physics world raycast and return all hits.
  131. void Raycast(PODVector<PhysicsRaycastResult>& result, const Ray& ray, float maxDistance, unsigned collisionMask = M_MAX_UNSIGNED);
  132. /// Perform a physics world raycast and return the closest hit.
  133. void RaycastSingle(PhysicsRaycastResult& result, const Ray& ray, float maxDistance, unsigned collisionMask = M_MAX_UNSIGNED);
  134. /// Perform a physics world swept sphere test and return the closest hit.
  135. void SphereCast(PhysicsRaycastResult& result, const Ray& ray, float radius, float maxDistance, unsigned collisionMask = M_MAX_UNSIGNED);
  136. /// Perform a physics world swept convex test using a user-supplied collision shape and return the first hit.
  137. void ConvexCast(PhysicsRaycastResult& result, CollisionShape* shape, const Vector3& startPos, const Quaternion& startRot, const Vector3& endPos, const Quaternion& endRot, unsigned collisionMask = M_MAX_UNSIGNED);
  138. /// Perform a physics world swept convex test using a user-supplied Bullet collision shape and return the first hit.
  139. void ConvexCast(PhysicsRaycastResult& result, btCollisionShape* shape, const Vector3& startPos, const Quaternion& startRot, const Vector3& endPos, const Quaternion& endRot, unsigned collisionMask = M_MAX_UNSIGNED);
  140. /// Invalidate cached collision geometry for a model.
  141. void RemoveCachedGeometry(Model* model);
  142. /// Return rigid bodies by a sphere query.
  143. void GetRigidBodies(PODVector<RigidBody*>& result, const Sphere& sphere, unsigned collisionMask = M_MAX_UNSIGNED);
  144. /// Return rigid bodies by a box query.
  145. void GetRigidBodies(PODVector<RigidBody*>& result, const BoundingBox& box, unsigned collisionMask = M_MAX_UNSIGNED);
  146. /// Return rigid bodies that have been in collision with a specific body on the last simulation step.
  147. void GetRigidBodies(PODVector<RigidBody*>& result, const RigidBody* body);
  148. /// Return gravity.
  149. Vector3 GetGravity() const;
  150. /// Return number of constraint solver iterations.
  151. int GetNumIterations() const;
  152. /// Return whether interpolation between simulation steps is enabled.
  153. bool GetInterpolation() const { return interpolation_; }
  154. /// Return whether Bullet's internal edge utility for trimesh collisions is enabled.
  155. bool GetInternalEdge() const { return internalEdge_; }
  156. /// Return whether split impulse collision mode is enabled.
  157. bool GetSplitImpulse() const;
  158. /// Return simulation steps per second.
  159. int GetFps() const { return fps_; }
  160. /// Return maximum angular velocity for network replication.
  161. float GetMaxNetworkAngularVelocity() const { return maxNetworkAngularVelocity_; }
  162. /// Add a rigid body to keep track of. Called by RigidBody.
  163. void AddRigidBody(RigidBody* body);
  164. /// Remove a rigid body. Called by RigidBody.
  165. void RemoveRigidBody(RigidBody* body);
  166. /// Add a collision shape to keep track of. Called by CollisionShape.
  167. void AddCollisionShape(CollisionShape* shape);
  168. /// Remove a collision shape. Called by CollisionShape.
  169. void RemoveCollisionShape(CollisionShape* shape);
  170. /// Add a constraint to keep track of. Called by Constraint.
  171. void AddConstraint(Constraint* joint);
  172. /// Remove a constraint. Called by Constraint.
  173. void RemoveConstraint(Constraint* joint);
  174. /// Add a delayed world transform assignment. Called by RigidBody.
  175. void AddDelayedWorldTransform(const DelayedWorldTransform& transform);
  176. /// Add debug geometry to the debug renderer.
  177. void DrawDebugGeometry(bool depthTest);
  178. /// Set debug renderer to use. Called both by PhysicsWorld itself and physics components.
  179. void SetDebugRenderer(DebugRenderer* debug);
  180. /// Set debug geometry depth test mode. Called both by PhysicsWorld itself and physics components.
  181. void SetDebugDepthTest(bool enable);
  182. /// Return the Bullet physics world.
  183. btDiscreteDynamicsWorld* GetWorld() { return world_; }
  184. /// Clean up the geometry cache.
  185. void CleanupGeometryCache();
  186. /// Return trimesh collision geometry cache.
  187. HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> >& GetTriMeshCache() { return triMeshCache_; }
  188. /// Return convex collision geometry cache.
  189. HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> >& GetConvexCache() { return convexCache_; }
  190. /// Set node dirtying to be disregarded.
  191. void SetApplyingTransforms(bool enable) { applyingTransforms_ = enable; }
  192. /// Return whether node dirtying should be disregarded.
  193. bool IsApplyingTransforms() const { return applyingTransforms_; }
  194. protected:
  195. /// Handle node being assigned.
  196. virtual void OnNodeSet(Node* node);
  197. private:
  198. /// Handle the scene subsystem update event, step simulation here.
  199. void HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData);
  200. /// Handle collision model reload finished.
  201. void HandleModelReloadFinished(StringHash eventType, VariantMap& eventData);
  202. /// Trigger update before each physics simulation step.
  203. void PreStep(float timeStep);
  204. /// Trigger update after ecah physics simulation step.
  205. void PostStep(float timeStep);
  206. /// Send accumulated collision events.
  207. void SendCollisionEvents();
  208. /// Bullet collision configuration.
  209. btCollisionConfiguration* collisionConfiguration_;
  210. /// Bullet collision dispatcher.
  211. btDispatcher* collisionDispatcher_;
  212. /// Bullet collision broadphase.
  213. btBroadphaseInterface* broadphase_;
  214. /// Bullet constraint solver.
  215. btConstraintSolver* solver_;
  216. /// Bullet physics world.
  217. btDiscreteDynamicsWorld* world_;
  218. /// Extra weak pointer to scene to allow for cleanup in case the world is destroyed before other components.
  219. WeakPtr<Scene> scene_;
  220. /// Rigid bodies in the world.
  221. PODVector<RigidBody*> rigidBodies_;
  222. /// Collision shapes in the world.
  223. PODVector<CollisionShape*> collisionShapes_;
  224. /// Constraints in the world.
  225. PODVector<Constraint*> constraints_;
  226. /// Collision pairs on this frame.
  227. HashMap<Pair<WeakPtr<RigidBody>, WeakPtr<RigidBody> >, btPersistentManifold* > currentCollisions_;
  228. /// Collision pairs on the previous frame. Used to check if a collision is "new." Manifolds are not guaranteed to exist anymore.
  229. HashMap<Pair<WeakPtr<RigidBody>, WeakPtr<RigidBody> >, btPersistentManifold* > previousCollisions_;
  230. /// Delayed (parented) world transform assignments.
  231. HashMap<RigidBody*, DelayedWorldTransform> delayedWorldTransforms_;
  232. /// Cache for trimesh geometry data by model and LOD level.
  233. HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> > triMeshCache_;
  234. /// Cache for convex geometry data by model and LOD level.
  235. HashMap<Pair<Model*, unsigned>, SharedPtr<CollisionGeometryData> > convexCache_;
  236. /// Preallocated event data map for physics collision events.
  237. VariantMap physicsCollisionData_;
  238. /// Preallocated event data map for node collision events.
  239. VariantMap nodeCollisionData_;
  240. /// Preallocated buffer for physics collision contact data.
  241. VectorBuffer contacts_;
  242. /// Simulation steps per second.
  243. unsigned fps_;
  244. /// Time accumulator for non-interpolated mode.
  245. float timeAcc_;
  246. /// Maximum angular velocity for network replication.
  247. float maxNetworkAngularVelocity_;
  248. /// Interpolation flag.
  249. bool interpolation_;
  250. /// Use internal edge utility flag.
  251. bool internalEdge_;
  252. /// Applying transforms flag.
  253. bool applyingTransforms_;
  254. /// Debug renderer.
  255. DebugRenderer* debugRenderer_;
  256. /// Debug draw flags.
  257. int debugMode_;
  258. /// Debug draw depth test mode.
  259. bool debugDepthTest_;
  260. };
  261. /// Register Physics library objects.
  262. void URHO3D_API RegisterPhysicsLibrary(Context* context);
  263. }