PhysicsWorld2D.cpp 28 KB

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