PhysicsWorld2D.cpp 27 KB

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