PhysicsWorld2D.h 11 KB

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