PhysicsWorld2D.h 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. //
  2. // Copyright (c) 2008-2016 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 "../Scene/Component.h"
  24. #include <Box2D/Box2D.h>
  25. namespace Atomic
  26. {
  27. class Camera;
  28. class RigidBody2D;
  29. /// 2D Physics raycast hit.
  30. struct ATOMIC_API PhysicsRaycastResult2D
  31. {
  32. /// Construct with defaults.
  33. PhysicsRaycastResult2D() :
  34. body_(0)
  35. {
  36. }
  37. /// Test for inequality, added to prevent GCC from complaining.
  38. bool operator !=(const PhysicsRaycastResult2D& rhs) const
  39. {
  40. return position_ != rhs.position_ || normal_ != rhs.normal_ || distance_ != rhs.distance_ || body_ != rhs.body_;
  41. }
  42. /// Hit worldspace position.
  43. Vector2 position_;
  44. /// Hit worldspace normal.
  45. Vector2 normal_;
  46. /// Hit distance from ray origin.
  47. float distance_;
  48. /// Rigid body that was hit.
  49. RigidBody2D* body_;
  50. };
  51. /// Delayed world transform assignment for parented 2D rigidbodies.
  52. struct DelayedWorldTransform2D
  53. {
  54. /// Rigid body.
  55. RigidBody2D* rigidBody_;
  56. /// Parent rigid body.
  57. RigidBody2D* parentRigidBody_;
  58. /// New world position.
  59. Vector3 worldPosition_;
  60. /// New world rotation.
  61. Quaternion worldRotation_;
  62. };
  63. /// 2D physics simulation world component. Should be added only to the root scene node.
  64. class ATOMIC_API PhysicsWorld2D : public Component, public b2ContactListener, public b2Draw
  65. {
  66. ATOMIC_OBJECT(PhysicsWorld2D, Component);
  67. public:
  68. /// Construct.
  69. PhysicsWorld2D(Context* context);
  70. /// Destruct.
  71. virtual ~PhysicsWorld2D();
  72. /// Register object factory.
  73. static void RegisterObject(Context* context);
  74. /// Visualize the component as debug geometry.
  75. virtual void DrawDebugGeometry(DebugRenderer* debug, bool depthTest);
  76. // Implement b2ContactListener
  77. /// Called when two fixtures begin to touch.
  78. virtual void BeginContact(b2Contact* contact);
  79. /// Called when two fixtures cease to touch.
  80. virtual void EndContact(b2Contact* contact);
  81. // Implement b2Draw
  82. /// Draw a closed polygon provided in CCW order.
  83. virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
  84. /// Draw a solid closed polygon provided in CCW order.
  85. virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
  86. /// Draw a circle.
  87. virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color);
  88. /// Draw a solid circle.
  89. virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color);
  90. /// Draw a line segment.
  91. virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color);
  92. /// Draw a transform. Choose your own length scale.
  93. virtual void DrawTransform(const b2Transform& xf);
  94. /// Step the simulation forward.
  95. void Update(float timeStep);
  96. /// Add debug geometry to the debug renderer.
  97. void DrawDebugGeometry();
  98. /// Enable or disable automatic physics simulation during scene update. Enabled by default.
  99. void SetUpdateEnabled(bool enable);
  100. /// Set draw shape.
  101. void SetDrawShape(bool drawShape);
  102. /// Set draw joint.
  103. void SetDrawJoint(bool drawJoint);
  104. /// Set draw aabb.
  105. void SetDrawAabb(bool drawAabb);
  106. /// Set draw pair.
  107. void SetDrawPair(bool drawPair);
  108. /// Set draw center of mass.
  109. void SetDrawCenterOfMass(bool drawCenterOfMass);
  110. /// Set allow sleeping.
  111. void SetAllowSleeping(bool enable);
  112. /// Set warm starting.
  113. void SetWarmStarting(bool enable);
  114. /// Set continuous physics.
  115. void SetContinuousPhysics(bool enable);
  116. /// Set sub stepping.
  117. void SetSubStepping(bool enable);
  118. /// Set gravity.
  119. void SetGravity(const Vector2& gravity);
  120. /// Set auto clear forces.
  121. void SetAutoClearForces(bool enable);
  122. /// Set velocity iterations.
  123. void SetVelocityIterations(int velocityIterations);
  124. /// Set position iterations.
  125. void SetPositionIterations(int positionIterations);
  126. /// Add rigid body.
  127. void AddRigidBody(RigidBody2D* rigidBody);
  128. /// Remove rigid body.
  129. void RemoveRigidBody(RigidBody2D* rigidBody);
  130. /// Add a delayed world transform assignment. Called by RigidBody2D.
  131. void AddDelayedWorldTransform(const DelayedWorldTransform2D& transform);
  132. /// Perform a physics world raycast and return all hits.
  133. void Raycast(PODVector<PhysicsRaycastResult2D>& results, const Vector2& startPoint, const Vector2& endPoint,
  134. unsigned collisionMask = M_MAX_UNSIGNED);
  135. /// Perform a physics world raycast and return the closest hit.
  136. void RaycastSingle(PhysicsRaycastResult2D& result, const Vector2& startPoint, const Vector2& endPoint,
  137. unsigned collisionMask = M_MAX_UNSIGNED);
  138. /// Return rigid body at point.
  139. RigidBody2D* GetRigidBody(const Vector2& point, unsigned collisionMask = M_MAX_UNSIGNED);
  140. /// Return rigid body at screen point.
  141. RigidBody2D* GetRigidBody(int screenX, int screenY, unsigned collisionMask = M_MAX_UNSIGNED);
  142. /// Return rigid bodies by a box query.
  143. void GetRigidBodies(PODVector<RigidBody2D*>& result, const Rect& aabb, unsigned collisionMask = M_MAX_UNSIGNED);
  144. /// Return whether physics world will automatically simulate during scene update.
  145. bool IsUpdateEnabled() const { return updateEnabled_; }
  146. /// Return draw shape.
  147. bool GetDrawShape() const { return (m_drawFlags & e_shapeBit) != 0; }
  148. /// Return draw joint.
  149. bool GetDrawJoint() const { return (m_drawFlags & e_jointBit) != 0; }
  150. /// Return draw aabb.
  151. bool GetDrawAabb() const { return (m_drawFlags & e_aabbBit) != 0; }
  152. /// Return draw pair.
  153. bool GetDrawPair() const { return (m_drawFlags & e_pairBit) != 0; }
  154. /// Return draw center of mass.
  155. bool GetDrawCenterOfMass() const { return (m_drawFlags & e_centerOfMassBit) != 0; }
  156. /// Return allow sleeping.
  157. bool GetAllowSleeping() const;
  158. /// Return warm starting.
  159. bool GetWarmStarting() const;
  160. /// Return continuous physics.
  161. bool GetContinuousPhysics() const;
  162. /// Return sub stepping.
  163. bool GetSubStepping() const;
  164. /// Return auto clear forces.
  165. bool GetAutoClearForces() const;
  166. /// Return gravity.
  167. const Vector2& GetGravity() const { return gravity_; }
  168. /// Return velocity iterations.
  169. int GetVelocityIterations() const { return velocityIterations_; }
  170. /// Return position iterations.
  171. int GetPositionIterations() const { return positionIterations_; }
  172. /// Return the Box2D physics world.
  173. b2World* GetWorld() { return world_; }
  174. /// Set node dirtying to be disregarded.
  175. void SetApplyingTransforms(bool enable) { applyingTransforms_ = enable; }
  176. /// Return whether node dirtying should be disregarded.
  177. bool IsApplyingTransforms() const { return applyingTransforms_; }
  178. protected:
  179. /// Handle scene being assigned.
  180. virtual void OnSceneSet(Scene* scene);
  181. private:
  182. /// Handle the scene subsystem update event, step simulation here.
  183. void HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData);
  184. /// Send begin contact events.
  185. void SendBeginContactEvents();
  186. /// Send end contact events.
  187. void SendEndContactEvents();
  188. /// Box2D physics world.
  189. b2World* world_;
  190. /// Gravity.
  191. Vector2 gravity_;
  192. /// Velocity iterations.
  193. int velocityIterations_;
  194. /// Position iterations.
  195. int positionIterations_;
  196. /// Extra weak pointer to scene to allow for cleanup in case the world is destroyed before other components.
  197. WeakPtr<Scene> scene_;
  198. /// Debug renderer.
  199. DebugRenderer* debugRenderer_;
  200. /// Debug draw depth test mode.
  201. bool debugDepthTest_;
  202. /// Automatic simulation update enabled flag.
  203. bool updateEnabled_;
  204. /// Whether is currently stepping the world. Used internally.
  205. bool physicsStepping_;
  206. /// Applying transforms.
  207. bool applyingTransforms_;
  208. /// Rigid bodies.
  209. Vector<WeakPtr<RigidBody2D> > rigidBodies_;
  210. /// Delayed (parented) world transform assignments.
  211. HashMap<RigidBody2D*, DelayedWorldTransform2D> delayedWorldTransforms_;
  212. /// Contact info.
  213. struct ContactInfo
  214. {
  215. /// Construct.
  216. ContactInfo();
  217. /// Construct.
  218. ContactInfo(b2Contact* contract);
  219. /// Copy construct.
  220. ContactInfo(const ContactInfo& other);
  221. /// Rigid body A.
  222. SharedPtr<RigidBody2D> bodyA_;
  223. /// Rigid body B.
  224. SharedPtr<RigidBody2D> bodyB_;
  225. /// Node A.
  226. SharedPtr<Node> nodeA_;
  227. /// Node B.
  228. SharedPtr<Node> nodeB_;
  229. /// Box2D contact.
  230. b2Contact* contact_;
  231. };
  232. /// Begin contact infos.
  233. Vector<ContactInfo> beginContactInfos_;
  234. /// End contact infos.
  235. Vector<ContactInfo> endContactInfos_;
  236. };
  237. }