PhysicsWorld2D.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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. #include "Precompiled.h"
  23. #include "Context.h"
  24. #include "DebugRenderer.h"
  25. #include "Graphics.h"
  26. #include "Log.h"
  27. #include "PhysicsEvents2D.h"
  28. #include "PhysicsUtils2D.h"
  29. #include "PhysicsWorld2D.h"
  30. #include "Profiler.h"
  31. #include "Renderer.h"
  32. #include "RigidBody2D.h"
  33. #include "Scene.h"
  34. #include "SceneEvents.h"
  35. #include "Viewport.h"
  36. #include "DebugNew.h"
  37. namespace Urho3D
  38. {
  39. extern const char* SUBSYSTEM_CATEGORY;
  40. static const Vector2 DEFAULT_GRAVITY(0.0f, -9.81f);
  41. static const int DEFAULT_VELOCITY_ITERATIONS = 8;
  42. static const int DEFAULT_POSITION_ITERATIONS = 3;
  43. PhysicsWorld2D::PhysicsWorld2D(Context* context) :
  44. Component(context),
  45. world_(0),
  46. gravity_(DEFAULT_GRAVITY),
  47. velocityIterations_(DEFAULT_VELOCITY_ITERATIONS),
  48. positionIterations_(DEFAULT_POSITION_ITERATIONS),
  49. debugRenderer_(0),
  50. physicsSteping_(false),
  51. applyingTransforms_(false)
  52. {
  53. // Set default debug draw flags
  54. m_drawFlags = e_shapeBit;
  55. // Create Box2D world
  56. world_ = new b2World(ToB2Vec2(gravity_));
  57. // Set contact listener
  58. world_->SetContactListener(this);
  59. // Set debug draw
  60. world_->SetDebugDraw(this);
  61. world_->SetContinuousPhysics(true);
  62. world_->SetSubStepping(true);
  63. }
  64. PhysicsWorld2D::~PhysicsWorld2D()
  65. {
  66. for (unsigned i = 0; i < rigidBodies_.Size(); ++i)
  67. if (rigidBodies_[i])
  68. rigidBodies_[i]->ReleaseBody();
  69. delete world_;
  70. world_ = 0;
  71. }
  72. void PhysicsWorld2D::RegisterObject(Context* context)
  73. {
  74. context->RegisterFactory<PhysicsWorld2D>(SUBSYSTEM_CATEGORY);
  75. ACCESSOR_ATTRIBUTE("Draw Shape", GetDrawShape, SetDrawShape, bool, false, AM_DEFAULT);
  76. ACCESSOR_ATTRIBUTE("Draw Joint", GetDrawJoint, SetDrawJoint, bool, false, AM_DEFAULT);
  77. ACCESSOR_ATTRIBUTE("Draw Aabb", GetDrawAabb, SetDrawAabb, bool, false, AM_DEFAULT);
  78. ACCESSOR_ATTRIBUTE("Draw Pair", GetDrawPair, SetDrawPair, bool, false, AM_DEFAULT);
  79. ACCESSOR_ATTRIBUTE("Draw CenterOfMass", GetDrawCenterOfMass, SetDrawCenterOfMass, bool, false, AM_DEFAULT);
  80. ACCESSOR_ATTRIBUTE("Allow Sleeping", GetAllowSleeping, SetAllowSleeping, bool, false, AM_DEFAULT);
  81. ACCESSOR_ATTRIBUTE("Warm Starting", GetWarmStarting, SetWarmStarting, bool, false, AM_DEFAULT);
  82. ACCESSOR_ATTRIBUTE("Continuous Physics", GetContinuousPhysics, SetContinuousPhysics, bool, false, AM_DEFAULT);
  83. ACCESSOR_ATTRIBUTE("Sub Stepping", GetSubStepping, SetSubStepping, bool, false, AM_DEFAULT);
  84. ACCESSOR_ATTRIBUTE("Gravity", GetGravity, SetGravity, Vector2, DEFAULT_GRAVITY, AM_DEFAULT);
  85. ACCESSOR_ATTRIBUTE("Auto Clear Forces", GetAutoClearForces, SetAutoClearForces, bool, false, AM_DEFAULT);
  86. ACCESSOR_ATTRIBUTE("Velocity Iterations", GetVelocityIterations, SetVelocityIterations, int, DEFAULT_VELOCITY_ITERATIONS, AM_DEFAULT);
  87. ACCESSOR_ATTRIBUTE("Position Iterations", GetPositionIterations, SetPositionIterations, int, DEFAULT_POSITION_ITERATIONS, AM_DEFAULT);
  88. }
  89. void PhysicsWorld2D::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  90. {
  91. if (debug)
  92. {
  93. PROFILE(Physics2DDrawDebug);
  94. debugRenderer_ = debug;
  95. debugDepthTest_ = depthTest;
  96. world_->DrawDebugData();
  97. debugRenderer_ = 0;
  98. }
  99. }
  100. void PhysicsWorld2D::BeginContact(b2Contact* contact)
  101. {
  102. // Only handle contact event when physics steping
  103. if (!physicsSteping_)
  104. return;
  105. b2Fixture* fixtureA = contact->GetFixtureA();
  106. b2Fixture* fixtureB = contact->GetFixtureB();
  107. if (!fixtureA || !fixtureB)
  108. return;
  109. beginContactInfos_.Push(ContactInfo(contact));
  110. }
  111. void PhysicsWorld2D::EndContact(b2Contact* contact)
  112. {
  113. // Only handle contact event when physics steping
  114. if (!physicsSteping_)
  115. return;
  116. b2Fixture* fixtureA = contact->GetFixtureA();
  117. b2Fixture* fixtureB = contact->GetFixtureB();
  118. if (!fixtureA || !fixtureB)
  119. return;
  120. endContactInfos_.Push(ContactInfo(contact));
  121. }
  122. void PhysicsWorld2D::DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color)
  123. {
  124. if (!debugRenderer_)
  125. return;
  126. Color c = ToColor(color);
  127. for (int i = 0; i < vertexCount - 1; ++i)
  128. debugRenderer_->AddLine(ToVector3(vertices[i]), ToVector3(vertices[i + 1]), c, debugDepthTest_);
  129. debugRenderer_->AddLine(ToVector3(vertices[vertexCount - 1]), ToVector3(vertices[0]), c, debugDepthTest_);
  130. }
  131. void PhysicsWorld2D::DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color)
  132. {
  133. if (!debugRenderer_)
  134. return;
  135. Vector3 v = ToVector3(vertices[0]);
  136. Color c(color.r, color.g, color.b, 0.5f);
  137. for (int i = 1; i < vertexCount - 1; ++i)
  138. debugRenderer_->AddTriangle(v, ToVector3(vertices[i]), ToVector3(vertices[i + 1]), c, debugDepthTest_);
  139. }
  140. void PhysicsWorld2D::DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color)
  141. {
  142. if (!debugRenderer_)
  143. return;
  144. Vector3 p = ToVector3(center);
  145. Color c = ToColor(color);
  146. for (unsigned i = 0; i < 360; i += 30)
  147. {
  148. unsigned j = i + 30;
  149. float x1 = radius * Cos((float)i);
  150. float y1 = radius * Sin((float)i);
  151. float x2 = radius * Cos((float)j);
  152. float y2 = radius * Sin((float)j);
  153. debugRenderer_->AddLine(p + Vector3(x1, y1, 0.0f), p + Vector3(x2, y2, 0.0f), c, debugDepthTest_);
  154. }
  155. }
  156. void PhysicsWorld2D::DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color)
  157. {
  158. if (!debugRenderer_)
  159. return;
  160. Vector3 p = ToVector3(center);
  161. Color c(color.r, color.g, color.b, 0.5f);
  162. for (unsigned i = 0; i < 360; i += 30)
  163. {
  164. unsigned j = i + 30;
  165. float x1 = radius * Cos((float)i);
  166. float y1 = radius * Sin((float)i);
  167. float x2 = radius * Cos((float)j);
  168. float y2 = radius * Sin((float)j);
  169. debugRenderer_->AddTriangle(p, p + Vector3(x1, y1, 0.0f), p + Vector3(x2, y2, 0.0f), c, debugDepthTest_);
  170. }
  171. }
  172. void PhysicsWorld2D::DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color)
  173. {
  174. if (debugRenderer_)
  175. debugRenderer_->AddLine(ToVector3(p1), ToVector3(p2), ToColor(color), debugDepthTest_);
  176. }
  177. void PhysicsWorld2D::DrawTransform(const b2Transform& xf)
  178. {
  179. if (!debugRenderer_)
  180. return;
  181. const float32 axisScale = 0.4f;
  182. b2Vec2 p1 = xf.p, p2;
  183. p2 = p1 + axisScale * xf.q.GetXAxis();
  184. debugRenderer_->AddLine(Vector3(p1.x, p1.y, 0.0f), Vector3(p2.x, p2.y, 0.0f), Color::RED, debugDepthTest_);
  185. p2 = p1 + axisScale * xf.q.GetYAxis();
  186. debugRenderer_->AddLine(Vector3(p1.x, p1.y, 0.0f), Vector3(p2.x, p2.y, 0.0f), Color::GREEN, debugDepthTest_);
  187. }
  188. void PhysicsWorld2D::Update(float timeStep)
  189. {
  190. using namespace Physics2DPreStep2D;
  191. VariantMap& eventData = GetEventDataMap();
  192. eventData[P_WORLD] = this;
  193. eventData[P_TIMESTEP] = timeStep;
  194. SendEvent(E_PHYSICSPRESTEP2D, eventData);
  195. physicsSteping_ = true;
  196. world_->Step(timeStep, velocityIterations_, positionIterations_);
  197. physicsSteping_ = false;
  198. for (unsigned i = 0; i < rigidBodies_.Size(); ++i)
  199. rigidBodies_[i]->ApplyWorldTransform();
  200. SendBeginContactEvents();
  201. SendEndContactEvents();
  202. using namespace PhysicsPostStep2D;
  203. SendEvent(E_PHYSICSPOSTSTEP2D, eventData);
  204. }
  205. void PhysicsWorld2D::DrawDebugGeometry()
  206. {
  207. DebugRenderer* debug = GetComponent<DebugRenderer>();
  208. if (debug)
  209. DrawDebugGeometry(debug, false);
  210. }
  211. void PhysicsWorld2D::SetDrawShape(bool drawShape)
  212. {
  213. if (drawShape)
  214. m_drawFlags |= e_shapeBit;
  215. else
  216. m_drawFlags &= ~e_shapeBit;
  217. }
  218. void PhysicsWorld2D::SetDrawJoint(bool drawJoint)
  219. {
  220. if (drawJoint)
  221. m_drawFlags |= e_jointBit;
  222. else
  223. m_drawFlags &= ~e_jointBit;
  224. }
  225. void PhysicsWorld2D::SetDrawAabb(bool drawAabb)
  226. {
  227. if (drawAabb)
  228. m_drawFlags |= e_aabbBit;
  229. else
  230. m_drawFlags &= ~e_aabbBit;
  231. }
  232. void PhysicsWorld2D::SetDrawPair(bool drawPair)
  233. {
  234. if (drawPair)
  235. m_drawFlags |= e_pairBit;
  236. else
  237. m_drawFlags &= ~e_pairBit;
  238. }
  239. void PhysicsWorld2D::SetDrawCenterOfMass(bool drawCenterOfMass)
  240. {
  241. if (drawCenterOfMass)
  242. m_drawFlags |= e_centerOfMassBit;
  243. else
  244. m_drawFlags &= ~e_centerOfMassBit;
  245. }
  246. void PhysicsWorld2D::SetAllowSleeping(bool enable)
  247. {
  248. world_->SetAllowSleeping(enable);
  249. }
  250. void PhysicsWorld2D::SetWarmStarting(bool enable)
  251. {
  252. world_->SetWarmStarting(enable);
  253. }
  254. void PhysicsWorld2D::SetContinuousPhysics(bool enable)
  255. {
  256. world_->SetContinuousPhysics(enable);
  257. }
  258. void PhysicsWorld2D::SetSubStepping(bool enable)
  259. {
  260. world_->SetSubStepping(enable);
  261. }
  262. void PhysicsWorld2D::SetGravity(const Vector2& gravity)
  263. {
  264. gravity_ = gravity;
  265. world_->SetGravity(ToB2Vec2(gravity_));
  266. }
  267. void PhysicsWorld2D::SetAutoClearForces(bool enable)
  268. {
  269. world_->SetAutoClearForces(enable);
  270. }
  271. void PhysicsWorld2D::SetVelocityIterations(int velocityIterations)
  272. {
  273. velocityIterations_ = velocityIterations;
  274. }
  275. void PhysicsWorld2D::SetPositionIterations(int positionIterations)
  276. {
  277. positionIterations_ = positionIterations;
  278. }
  279. void PhysicsWorld2D::AddRigidBody(RigidBody2D* rigidBody)
  280. {
  281. if (!rigidBody)
  282. return;
  283. WeakPtr<RigidBody2D> rigidBodyPtr(rigidBody);
  284. if (rigidBodies_.Contains(rigidBodyPtr))
  285. return;
  286. rigidBodies_.Push(rigidBodyPtr);
  287. }
  288. void PhysicsWorld2D::RemoveRigidBody(RigidBody2D* rigidBody)
  289. {
  290. if (!rigidBody)
  291. return;
  292. WeakPtr<RigidBody2D> rigidBodyPtr(rigidBody);
  293. rigidBodies_.Remove(rigidBodyPtr);
  294. }
  295. // Ray cast call back class.
  296. class RayCastCallback : public b2RayCastCallback
  297. {
  298. public:
  299. // Construct.
  300. RayCastCallback(PODVector<PhysicsRaycastResult2D>& results, const Vector2& startPoint, unsigned collisionMask) :
  301. results_(results),
  302. startPoint_(startPoint),
  303. collisionMask_(collisionMask)
  304. {
  305. }
  306. // Called for each fixture found in the query.
  307. virtual float32 ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float32 fraction)
  308. {
  309. // Ignore sensor
  310. if (fixture->IsSensor())
  311. return true;
  312. if ((fixture->GetFilterData().maskBits & collisionMask_) == 0)
  313. return true;
  314. PhysicsRaycastResult2D result;
  315. result.position_ = ToVector2(point);
  316. result.normal_ = ToVector2(normal);
  317. result.distance_ = (result.position_ - startPoint_).Length();
  318. result.body_ = (RigidBody2D*)(fixture->GetBody()->GetUserData());
  319. results_.Push(result);
  320. return true;
  321. }
  322. protected:
  323. // Physics raycast results.
  324. PODVector<PhysicsRaycastResult2D>& results_;
  325. // Start point.
  326. Vector2 startPoint_;
  327. // Collision mask.
  328. unsigned collisionMask_;
  329. };
  330. void PhysicsWorld2D::Raycast(PODVector<PhysicsRaycastResult2D>& results, const Vector2& startPoint, const Vector2& endPoint, unsigned collisionMask)
  331. {
  332. results.Clear();
  333. RayCastCallback callback(results, startPoint, collisionMask);
  334. world_->RayCast(&callback, ToB2Vec2(startPoint), ToB2Vec2(endPoint));
  335. }
  336. // Single ray cast call back class.
  337. class SingleRayCastCallback : public b2RayCastCallback
  338. {
  339. public:
  340. // Construct.
  341. SingleRayCastCallback(PhysicsRaycastResult2D& result, const Vector2& startPoint, unsigned collisionMask) :
  342. result_(result),
  343. startPoint_(startPoint),
  344. collisionMask_(collisionMask),
  345. minDistance_(M_INFINITY)
  346. {
  347. }
  348. // Called for each fixture found in the query.
  349. virtual float32 ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float32 fraction)
  350. {
  351. // Ignore sensor
  352. if (fixture->IsSensor())
  353. return true;
  354. if ((fixture->GetFilterData().maskBits & collisionMask_) == 0)
  355. return true;
  356. float distance = (ToVector2(point)- startPoint_).Length();
  357. if (distance < minDistance_)
  358. {
  359. minDistance_ = distance;
  360. result_.position_ = ToVector2(point);
  361. result_.normal_ = ToVector2(normal);
  362. result_.distance_ = distance;
  363. result_.body_ = (RigidBody2D*)(fixture->GetBody()->GetUserData());
  364. }
  365. return true;
  366. }
  367. private:
  368. // Physics raycast result.
  369. PhysicsRaycastResult2D& result_;
  370. // Start point.
  371. Vector2 startPoint_;
  372. // Collision mask.
  373. unsigned collisionMask_;
  374. // Minimum distance.
  375. float minDistance_;
  376. };
  377. void PhysicsWorld2D::RaycastSingle(PhysicsRaycastResult2D& result, const Vector2& startPoint, const Vector2& endPoint, unsigned collisionMask)
  378. {
  379. result.body_ = 0;
  380. SingleRayCastCallback callback(result, startPoint, collisionMask);
  381. world_->RayCast(&callback, ToB2Vec2(startPoint), ToB2Vec2(endPoint));
  382. }
  383. // Point query callback class.
  384. class PointQueryCallback : public b2QueryCallback
  385. {
  386. public:
  387. // Construct.
  388. PointQueryCallback(const b2Vec2& point, unsigned collisionMask) :
  389. point_(point),
  390. collisionMask_(collisionMask),
  391. rigidBody_(0)
  392. {
  393. }
  394. // Called for each fixture found in the query AABB.
  395. virtual bool ReportFixture(b2Fixture* fixture)
  396. {
  397. // Ignore sensor
  398. if (fixture->IsSensor())
  399. return true;
  400. if ((fixture->GetFilterData().maskBits & collisionMask_) == 0)
  401. return true;
  402. if (fixture->TestPoint(point_))
  403. {
  404. rigidBody_ = (RigidBody2D*)(fixture->GetBody()->GetUserData());
  405. return false;
  406. }
  407. return true;
  408. }
  409. // Return rigid body.
  410. RigidBody2D* GetRigidBody() const { return rigidBody_; }
  411. private:
  412. // Point.
  413. b2Vec2 point_;
  414. // Collision mask.
  415. unsigned collisionMask_;
  416. // Rigid body.
  417. RigidBody2D* rigidBody_;
  418. };
  419. RigidBody2D* PhysicsWorld2D::GetRigidBody(const Vector2& point, unsigned collisionMask)
  420. {
  421. PointQueryCallback callback(ToB2Vec2(point), collisionMask);
  422. b2AABB b2Aabb;
  423. Vector2 delta(M_EPSILON, M_EPSILON);
  424. b2Aabb.lowerBound = ToB2Vec2(point - delta);
  425. b2Aabb.upperBound = ToB2Vec2(point + delta);
  426. world_->QueryAABB(&callback, b2Aabb);
  427. return callback.GetRigidBody();
  428. }
  429. RigidBody2D* PhysicsWorld2D::GetRigidBody(int screenX, int screenY, unsigned collisionMask)
  430. {
  431. Renderer* renderer = GetSubsystem<Renderer>();
  432. for (unsigned i = 0; i < renderer->GetNumViewports(); ++i)
  433. {
  434. Viewport* viewport = renderer->GetViewport(i);
  435. // Find a viewport with same scene
  436. if (viewport && viewport->GetScene() == GetScene())
  437. {
  438. Vector3 worldPoint = viewport->ScreenToWorldPoint(screenX, screenY, 0.0f);
  439. return GetRigidBody(Vector2(worldPoint.x_, worldPoint.y_), collisionMask);
  440. }
  441. }
  442. return 0;
  443. }
  444. // Aabb query callback class.
  445. class AabbQueryCallback : public b2QueryCallback
  446. {
  447. public:
  448. // Construct.
  449. AabbQueryCallback(PODVector<RigidBody2D*>& results, unsigned collisionMask) :
  450. results_(results),
  451. collisionMask_(collisionMask)
  452. {
  453. }
  454. // Called for each fixture found in the query AABB.
  455. virtual bool ReportFixture(b2Fixture* fixture)
  456. {
  457. // Ignore sensor
  458. if (fixture->IsSensor())
  459. return true;
  460. if ((fixture->GetFilterData().maskBits & collisionMask_) == 0)
  461. return true;
  462. results_.Push((RigidBody2D*)(fixture->GetBody()->GetUserData()));
  463. return true;
  464. }
  465. private:
  466. // Results.
  467. PODVector<RigidBody2D*>& results_;
  468. // Collision mask.
  469. unsigned collisionMask_;
  470. };
  471. void PhysicsWorld2D::GetRigidBodies(PODVector<RigidBody2D*>& results, const Rect& aabb, unsigned collisionMask)
  472. {
  473. AabbQueryCallback callback(results, collisionMask);
  474. b2AABB b2Aabb;
  475. b2Aabb.lowerBound = ToB2Vec2(aabb.min_);
  476. b2Aabb.upperBound = ToB2Vec2(aabb.max_);
  477. world_->QueryAABB(&callback, b2Aabb);
  478. }
  479. bool PhysicsWorld2D::GetAllowSleeping() const
  480. {
  481. return world_->GetAllowSleeping();
  482. }
  483. bool PhysicsWorld2D::GetWarmStarting() const
  484. {
  485. return world_->GetWarmStarting();
  486. }
  487. bool PhysicsWorld2D::GetContinuousPhysics() const
  488. {
  489. return world_->GetContinuousPhysics();
  490. }
  491. bool PhysicsWorld2D::GetSubStepping() const
  492. {
  493. return world_->GetSubStepping();
  494. }
  495. bool PhysicsWorld2D::GetAutoClearForces() const
  496. {
  497. return world_->GetAutoClearForces();
  498. }
  499. void PhysicsWorld2D::OnNodeSet(Node* node)
  500. {
  501. // Subscribe to the scene subsystem update, which will trigger the physics simulation step
  502. if (node)
  503. {
  504. scene_ = GetScene();
  505. SubscribeToEvent(node, E_SCENESUBSYSTEMUPDATE, HANDLER(PhysicsWorld2D, HandleSceneSubsystemUpdate));
  506. }
  507. }
  508. void PhysicsWorld2D::HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData)
  509. {
  510. using namespace SceneSubsystemUpdate;
  511. Update(eventData[P_TIMESTEP].GetFloat());
  512. }
  513. void PhysicsWorld2D::SendBeginContactEvents()
  514. {
  515. if (beginContactInfos_.Empty())
  516. return;
  517. using namespace PhysicsBeginContact2D;
  518. VariantMap& eventData = GetEventDataMap();
  519. eventData[P_WORLD] = this;
  520. for (unsigned i = 0; i < beginContactInfos_.Size(); ++i)
  521. {
  522. ContactInfo& contactInfo = beginContactInfos_[i];
  523. eventData[P_BODYA] = contactInfo.bodyA_.Get();
  524. eventData[P_BODYB] = contactInfo.bodyB_.Get();
  525. eventData[P_NODEA] = contactInfo.nodeA_.Get();
  526. eventData[P_NODEB] = contactInfo.nodeB_.Get();
  527. SendEvent(E_PHYSICSBEGINCONTACT2D, eventData);
  528. }
  529. beginContactInfos_.Clear();
  530. }
  531. void PhysicsWorld2D::SendEndContactEvents()
  532. {
  533. if (endContactInfos_.Empty())
  534. return;
  535. using namespace PhysicsEndContact2D;
  536. VariantMap& eventData = GetEventDataMap();
  537. eventData[P_WORLD] = this;
  538. for (unsigned i = 0; i < endContactInfos_.Size(); ++i)
  539. {
  540. ContactInfo& contactInfo = endContactInfos_[i];
  541. eventData[P_BODYA] = contactInfo.bodyA_.Get();
  542. eventData[P_BODYB] = contactInfo.bodyB_.Get();
  543. eventData[P_NODEA] = contactInfo.nodeA_.Get();
  544. eventData[P_NODEB] = contactInfo.nodeB_.Get();
  545. SendEvent(E_PHYSICSENDCONTACT2D, eventData);
  546. }
  547. endContactInfos_.Clear();
  548. }
  549. PhysicsWorld2D::ContactInfo::ContactInfo()
  550. {
  551. }
  552. PhysicsWorld2D::ContactInfo::ContactInfo(b2Contact* contact)
  553. {
  554. b2Fixture* fixtureA = contact->GetFixtureA();
  555. b2Fixture* fixtureB = contact->GetFixtureB();
  556. bodyA_ = (RigidBody2D*)(fixtureA->GetBody()->GetUserData());
  557. bodyB_ = (RigidBody2D*)(fixtureB->GetBody()->GetUserData());
  558. nodeA_ = bodyA_->GetNode();
  559. nodeB_ = bodyB_->GetNode();
  560. }
  561. PhysicsWorld2D::ContactInfo::ContactInfo(const ContactInfo& other) :
  562. bodyA_(other.bodyA_),
  563. bodyB_(other.bodyB_),
  564. nodeA_(other.nodeA_),
  565. nodeB_(other.nodeB_)
  566. {
  567. }
  568. }