PhysicsWorld.h 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #pragma once
  24. #include "Component.h"
  25. #include "HashSet.h"
  26. #include "PhysicsDefs.h"
  27. #include "Vector3.h"
  28. class CollisionShape;
  29. class DebugRenderer;
  30. class Deserializer;
  31. class Joint;
  32. class Node;
  33. class Ray;
  34. class RigidBody;
  35. class Scene;
  36. class Serializer;
  37. class XMLElement;
  38. struct HeightfieldData;
  39. struct TriangleMeshData;
  40. /// Physics raycast hit.
  41. struct PhysicsRaycastResult
  42. {
  43. /// Hit position.
  44. Vector3 position_;
  45. /// Hit normal.
  46. Vector3 normal_;
  47. /// Hit distance from ray origin.
  48. float distance_;
  49. /// Collision shape that was hit.
  50. CollisionShape* collisionShape_;
  51. };
  52. /// Internal physics contact info
  53. struct PhysicsContactInfo
  54. {
  55. /// World position.
  56. Vector3 position_;
  57. /// World normal from perspective of first rigid body.
  58. Vector3 normal_;
  59. /// Penetration depth.
  60. float depth_;
  61. /// Velocity.
  62. float velocity_;
  63. };
  64. /// Internal physics collision info.
  65. struct PhysicsCollisionInfo
  66. {
  67. /// First scene node.
  68. WeakPtr<Node> nodeA_;
  69. /// Second scene node.
  70. WeakPtr<Node> nodeB_;
  71. /// First collision shape.
  72. WeakPtr<CollisionShape> shapeA_;
  73. /// Second collision shape.
  74. WeakPtr<CollisionShape> shapeB_;
  75. /// New collision flag.
  76. bool newCollision_;
  77. /// Contacts.
  78. PODVector<PhysicsContactInfo> contacts_;
  79. };
  80. static const float DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY = 100.0f;
  81. /// Physics simulation world component. Should be added only to the root scene node.
  82. class PhysicsWorld : public Component
  83. {
  84. OBJECT(PhysicsWorld);
  85. public:
  86. /// Construct.
  87. PhysicsWorld(Context* context);
  88. /// Destruct.
  89. virtual ~PhysicsWorld();
  90. /// Register object factory.
  91. static void RegisterObject(Context* context);
  92. /// Step the simulation forward.
  93. void Update(float timeStep);
  94. /// %Set simulation steps per second.
  95. void SetFps(int fps);
  96. /// %Set maximum contacts in one collision.
  97. void SetMaxContacts(unsigned num);
  98. /// %Set gravity.
  99. void SetGravity(Vector3 gravity);
  100. /// %Set default linear velocity deactivation threshold for new rigid bodies.
  101. void SetLinearRestThreshold(float threshold);
  102. /// %Set default linear velocity damping threshold.
  103. void SetLinearDampingThreshold(float threshold);
  104. /// %Set default linear velocity damping scale.
  105. void SetLinearDampingScale(float scale);
  106. /// %Set default angular velocity deactivation threshold for new rigid bodies.
  107. void SetAngularRestThreshold(float threshold);
  108. /// %Set default angular velocity damping threshold.
  109. void SetAngularDampingThreshold(float threshold);
  110. /// %Set default angular velocity damping scale.
  111. void SetAngularDampingScale(float scale);
  112. /// %Set collision bounce velocity threshold (apply bounce if above.)
  113. void SetBounceThreshold(float threshold);
  114. /// %Set maximum angular velocity for network replication.
  115. void SetMaxNetworkAngularVelocity(float velocity);
  116. /// %Set simulation ERP parameter.
  117. void SetERP(float erp);
  118. /// %Set simulation CFM parameter.
  119. void SetCFM(float cfm);
  120. /// %Set depth of contact surface.
  121. void SetContactSurfaceLayer(float depth);
  122. /// %Set simulation step time accumulator.
  123. void SetTimeAccumulator(float time);
  124. /// Perform a physics world raycast.
  125. void Raycast(PODVector<PhysicsRaycastResult>& result, const Ray& ray, float maxDistance, unsigned collisionMask =
  126. M_MAX_UNSIGNED);
  127. /// Return ODE world ID.
  128. dWorldID GetWorld() const { return physicsWorld_; }
  129. /// Return ODE space ID.
  130. dSpaceID GetSpace() const { return space_; }
  131. /// Return gravity.
  132. Vector3 GetGravity() const;
  133. /// Return simulation steps per second.
  134. int GetFps() const { return fps_; }
  135. /// Return maximum contacts per collision.
  136. unsigned GetMaxContacts() const { return maxContacts_; }
  137. /// Return default linear velocity deactivation threshold.
  138. float GetLinearRestThreshold() const;
  139. /// Return default linear velocity damping threshold.
  140. float GetLinearDampingThreshold() const;
  141. /// Return default linear velocity damping scale.
  142. float GetLinearDampingScale() const;
  143. /// Return default angular velocity damping threshold.
  144. float GetAngularRestThreshold() const;
  145. /// Return default angular velocity damping threshold.
  146. float GetAngularDampingThreshold() const;
  147. /// Return default angular velocity damping scale.
  148. float GetAngularDampingScale() const;
  149. /// Return collision bounce velocity threshold.
  150. float GetBounceThreshold() const { return bounceThreshold_; }
  151. /// Return maximum angular velocity for network replication.
  152. float GetMaxNetworkAngularVelocity() const { return maxNetworkAngularVelocity_; }
  153. /// Return simulation ERP parameter.
  154. float GetERP() const;
  155. /// Return simulation CFM parameter.
  156. float GetCFM() const;
  157. /// Return depth of contact surface.
  158. float GetContactSurfaceLayer() const;
  159. /// Return simulation step time accumulator.
  160. float GetTimeAccumulator() const { return timeAcc_; }
  161. /// Add a rigid body to keep track of. Called by RigidBody.
  162. void AddRigidBody(RigidBody* body);
  163. /// Remove a rigid body. Called by RigidBody.
  164. void RemoveRigidBody(RigidBody* body);
  165. /// Add a collision shape to keep track of. Called by CollisionShape.
  166. void AddCollisionShape(CollisionShape* shape);
  167. /// Remove a collision shape. Called by CollisionShape.
  168. void RemoveCollisionShape(CollisionShape* shape);
  169. /// Add a joint to keep track of. Called by Joint.
  170. void AddJoint(Joint* joint);
  171. /// Remove a joint. Called by Joint.
  172. void RemoveJoint(Joint* joint);
  173. /// Send accumulated collision events.
  174. void SendCollisionEvents();
  175. /// Add debug geometry to the debug renderer.
  176. void DrawDebugGeometry(bool depthTest);
  177. /// Clean up the geometry cache.
  178. void CleanupGeometryCache();
  179. /// Return the triangle mesh cache.
  180. Map<String, SharedPtr<TriangleMeshData> >& GetTriangleMeshCache() { return triangleMeshCache_; }
  181. /// Return the heightfield cache.
  182. Map<String, SharedPtr<HeightfieldData> >& GetHeightfieldCache() { return heightfieldCache_; }
  183. protected:
  184. /// Handle node being assigned.
  185. virtual void OnNodeSet(Node* node);
  186. private:
  187. /// ODE collision callback.
  188. static void NearCallback(void *userData, dGeomID geomA, dGeomID geomB);
  189. /// ODE raycast callback.
  190. static void RaycastCallback(void *userData, dGeomID geomA, dGeomID geomB);
  191. /// Handle the scene subsystem update event, step simulation here.
  192. void HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData);
  193. /// Extra weak pointer to scene to allow for cleanup in case the world is destroyed before other components.
  194. WeakPtr<Scene> scene_;
  195. /// ODE world ID.
  196. dWorldID physicsWorld_;
  197. /// ODE space ID.
  198. dSpaceID space_;
  199. /// ODE ray geometry ID (for raycast.)
  200. dGeomID rayGeometry_;
  201. /// ODE contact joint group ID.
  202. dJointGroupID contactJoints_;
  203. /// Simulation steps per second.
  204. unsigned fps_;
  205. /// Maximum contacts per collision.
  206. unsigned maxContacts_;
  207. /// Collision bounce velocity threshold.
  208. float bounceThreshold_;
  209. /// Maximum angular velocity for network replication.
  210. float maxNetworkAngularVelocity_;
  211. /// Simulation step time accumulator.
  212. float timeAcc_;
  213. /// Simulation random seed.
  214. unsigned randomSeed_;
  215. /// Rigid bodies in the world.
  216. PODVector<RigidBody*> rigidBodies_;
  217. /// Collision shapes in the world.
  218. PODVector<CollisionShape*> collisionShapes_;
  219. /// Joints in the world.
  220. PODVector<Joint*> joints_;
  221. /// Collision contacts (PODVector<dContact>.)
  222. void* contacts_;
  223. /// Collision pairs on this frame.
  224. HashSet<Pair<RigidBody*, RigidBody*> > currentCollisions_;
  225. /// Collision pairs on the previous frame. Used to check if a collision is "new."
  226. HashSet<Pair<RigidBody*, RigidBody*> > previousCollisions_;
  227. /// Already processed rigid bodies during a poststep.
  228. HashSet<RigidBody*> processedBodies_;
  229. /// Collision infos to be sent as events.
  230. Vector<PhysicsCollisionInfo> collisionInfos_;
  231. /// Cache for triangle mesh geometries.
  232. Map<String, SharedPtr<TriangleMeshData> > triangleMeshCache_;
  233. /// Cache for heightfield geometries.
  234. Map<String, SharedPtr<HeightfieldData> > heightfieldCache_;
  235. };
  236. /// Register Physics library objects.
  237. void RegisterPhysicsLibrary(Context* context);