PhysicsWorld2D.cpp 21 KB

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