PhysicsWorld2D.cpp 27 KB

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