RigidBody2D.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. //
  2. // Copyright (c) 2008-2020 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 "../IO/Log.h"
  25. #include "../Scene/Scene.h"
  26. #include "../Urho2D/CollisionShape2D.h"
  27. #include "../Urho2D/Constraint2D.h"
  28. #include "../Urho2D/PhysicsUtils2D.h"
  29. #include "../Urho2D/PhysicsWorld2D.h"
  30. #include "../Urho2D/RigidBody2D.h"
  31. #include "../DebugNew.h"
  32. namespace Urho3D
  33. {
  34. extern const char* URHO2D_CATEGORY;
  35. static const BodyType2D DEFAULT_BODYTYPE = BT_STATIC;
  36. static const char* bodyTypeNames[] =
  37. {
  38. "Static",
  39. "Kinematic",
  40. "Dynamic",
  41. nullptr
  42. };
  43. RigidBody2D::RigidBody2D(Context* context) :
  44. Component(context),
  45. useFixtureMass_(true),
  46. body_(nullptr)
  47. {
  48. // Make sure the massData members are zero-initialized.
  49. massData_.mass = 0.0f;
  50. massData_.I = 0.0f;
  51. massData_.center.SetZero();
  52. }
  53. RigidBody2D::~RigidBody2D()
  54. {
  55. if (physicsWorld_)
  56. {
  57. ReleaseBody();
  58. physicsWorld_->RemoveRigidBody(this);
  59. }
  60. }
  61. void RigidBody2D::RegisterObject(Context* context)
  62. {
  63. context->RegisterFactory<RigidBody2D>(URHO2D_CATEGORY);
  64. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  65. URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Body Type", GetBodyType, SetBodyType, BodyType2D, bodyTypeNames, DEFAULT_BODYTYPE, AM_DEFAULT);
  66. URHO3D_ACCESSOR_ATTRIBUTE("Mass", GetMass, SetMass, float, 0.0f, AM_DEFAULT);
  67. URHO3D_ACCESSOR_ATTRIBUTE("Inertia", GetInertia, SetInertia, float, 0.0f, AM_DEFAULT);
  68. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Mass Center", GetMassCenter, SetMassCenter, Vector2, Vector2::ZERO, AM_DEFAULT);
  69. URHO3D_ACCESSOR_ATTRIBUTE("Use Fixture Mass", GetUseFixtureMass, SetUseFixtureMass, bool, true, AM_DEFAULT);
  70. URHO3D_ACCESSOR_ATTRIBUTE("Linear Damping", GetLinearDamping, SetLinearDamping, float, 0.0f, AM_DEFAULT);
  71. URHO3D_ACCESSOR_ATTRIBUTE("Angular Damping", GetAngularDamping, SetAngularDamping, float, 0.0f, AM_DEFAULT);
  72. URHO3D_ACCESSOR_ATTRIBUTE("Allow Sleep", IsAllowSleep, SetAllowSleep, bool, true, AM_DEFAULT);
  73. URHO3D_ACCESSOR_ATTRIBUTE("Fixed Rotation", IsFixedRotation, SetFixedRotation, bool, false, AM_DEFAULT);
  74. URHO3D_ACCESSOR_ATTRIBUTE("Bullet", IsBullet, SetBullet, bool, false, AM_DEFAULT);
  75. URHO3D_ACCESSOR_ATTRIBUTE("Gravity Scale", GetGravityScale, SetGravityScale, float, 1.0f, AM_DEFAULT);
  76. URHO3D_ACCESSOR_ATTRIBUTE("Awake", IsAwake, SetAwake, bool, true, AM_DEFAULT);
  77. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Linear Velocity", GetLinearVelocity, SetLinearVelocity, Vector2, Vector2::ZERO, AM_DEFAULT);
  78. URHO3D_ACCESSOR_ATTRIBUTE("Angular Velocity", GetAngularVelocity, SetAngularVelocity, float, 0.0f, AM_DEFAULT);
  79. }
  80. void RigidBody2D::OnSetEnabled()
  81. {
  82. bool enabled = IsEnabledEffective();
  83. bodyDef_.active = enabled;
  84. if (body_)
  85. body_->SetActive(enabled);
  86. MarkNetworkUpdate();
  87. }
  88. void RigidBody2D::SetBodyType(BodyType2D type)
  89. {
  90. auto bodyType = (b2BodyType)type;
  91. if (body_)
  92. {
  93. body_->SetType(bodyType);
  94. // Mass data was reset to keep it legal (e.g. static body should have mass 0).
  95. // If not using fixture mass, reassign our mass data now
  96. if (!useFixtureMass_)
  97. body_->SetMassData(&massData_);
  98. }
  99. else
  100. {
  101. if (bodyDef_.type == bodyType)
  102. return;
  103. bodyDef_.type = bodyType;
  104. }
  105. MarkNetworkUpdate();
  106. }
  107. void RigidBody2D::SetMass(float mass)
  108. {
  109. mass = Max(mass, 0.0f);
  110. if (massData_.mass == mass)
  111. return;
  112. massData_.mass = mass;
  113. if (!useFixtureMass_ && body_)
  114. body_->SetMassData(&massData_);
  115. MarkNetworkUpdate();
  116. }
  117. void RigidBody2D::SetInertia(float inertia)
  118. {
  119. inertia = Max(inertia, 0.0f);
  120. if (massData_.I == inertia)
  121. return;
  122. massData_.I = inertia;
  123. if (!useFixtureMass_ && body_)
  124. body_->SetMassData(&massData_);
  125. MarkNetworkUpdate();
  126. }
  127. void RigidBody2D::SetMassCenter(const Vector2& center)
  128. {
  129. b2Vec2 b2Center = ToB2Vec2(center);
  130. if (massData_.center == b2Center)
  131. return;
  132. massData_.center = b2Center;
  133. if (!useFixtureMass_ && body_)
  134. body_->SetMassData(&massData_);
  135. MarkNetworkUpdate();
  136. }
  137. void RigidBody2D::SetUseFixtureMass(bool useFixtureMass)
  138. {
  139. if (useFixtureMass_ == useFixtureMass)
  140. return;
  141. useFixtureMass_ = useFixtureMass;
  142. if (body_)
  143. {
  144. if (useFixtureMass_)
  145. body_->ResetMassData();
  146. else
  147. body_->SetMassData(&massData_);
  148. }
  149. MarkNetworkUpdate();
  150. }
  151. void RigidBody2D::SetLinearDamping(float linearDamping)
  152. {
  153. if (body_)
  154. body_->SetLinearDamping(linearDamping);
  155. else
  156. {
  157. if (bodyDef_.linearDamping == linearDamping)
  158. return;
  159. bodyDef_.linearDamping = linearDamping;
  160. }
  161. MarkNetworkUpdate();
  162. }
  163. void RigidBody2D::SetAngularDamping(float angularDamping)
  164. {
  165. if (body_)
  166. body_->SetAngularDamping(angularDamping);
  167. else
  168. {
  169. if (bodyDef_.angularDamping == angularDamping)
  170. return;
  171. bodyDef_.angularDamping = angularDamping;
  172. }
  173. MarkNetworkUpdate();
  174. }
  175. void RigidBody2D::SetAllowSleep(bool allowSleep)
  176. {
  177. if (body_)
  178. body_->SetSleepingAllowed(allowSleep);
  179. else
  180. {
  181. if (bodyDef_.allowSleep == allowSleep)
  182. return;
  183. bodyDef_.allowSleep = allowSleep;
  184. }
  185. MarkNetworkUpdate();
  186. }
  187. void RigidBody2D::SetFixedRotation(bool fixedRotation)
  188. {
  189. if (body_)
  190. {
  191. body_->SetFixedRotation(fixedRotation);
  192. // Mass data was reset to keep it legal (e.g. non-rotating body should have inertia 0).
  193. // If not using fixture mass, reassign our mass data now
  194. if (!useFixtureMass_)
  195. body_->SetMassData(&massData_);
  196. }
  197. else
  198. {
  199. if (bodyDef_.fixedRotation == fixedRotation)
  200. return;
  201. bodyDef_.fixedRotation = fixedRotation;
  202. }
  203. MarkNetworkUpdate();
  204. }
  205. void RigidBody2D::SetBullet(bool bullet)
  206. {
  207. if (body_)
  208. body_->SetBullet(bullet);
  209. else
  210. {
  211. if (bodyDef_.bullet == bullet)
  212. return;
  213. bodyDef_.bullet = bullet;
  214. }
  215. MarkNetworkUpdate();
  216. }
  217. void RigidBody2D::SetGravityScale(float gravityScale)
  218. {
  219. if (body_)
  220. body_->SetGravityScale(gravityScale);
  221. else
  222. {
  223. if (bodyDef_.gravityScale == gravityScale)
  224. return;
  225. bodyDef_.gravityScale = gravityScale;
  226. }
  227. MarkNetworkUpdate();
  228. }
  229. void RigidBody2D::SetAwake(bool awake)
  230. {
  231. if (body_)
  232. body_->SetAwake(awake);
  233. else
  234. {
  235. if (bodyDef_.awake == awake)
  236. return;
  237. bodyDef_.awake = awake;
  238. }
  239. MarkNetworkUpdate();
  240. }
  241. void RigidBody2D::SetLinearVelocity(const Vector2& linearVelocity)
  242. {
  243. b2Vec2 b2linearVelocity = ToB2Vec2(linearVelocity);
  244. if (body_)
  245. body_->SetLinearVelocity(b2linearVelocity);
  246. else
  247. {
  248. if (bodyDef_.linearVelocity == b2linearVelocity)
  249. return;
  250. bodyDef_.linearVelocity = b2linearVelocity;
  251. }
  252. MarkNetworkUpdate();
  253. }
  254. void RigidBody2D::SetAngularVelocity(float angularVelocity)
  255. {
  256. if (body_)
  257. body_->SetAngularVelocity(angularVelocity);
  258. else
  259. {
  260. if (bodyDef_.angularVelocity == angularVelocity)
  261. return;
  262. bodyDef_.angularVelocity = angularVelocity;
  263. }
  264. MarkNetworkUpdate();
  265. }
  266. void RigidBody2D::ApplyForce(const Vector2& force, const Vector2& point, bool wake)
  267. {
  268. if (body_ && force != Vector2::ZERO)
  269. body_->ApplyForce(ToB2Vec2(force), ToB2Vec2(point), wake);
  270. }
  271. void RigidBody2D::ApplyForceToCenter(const Vector2& force, bool wake)
  272. {
  273. if (body_ && force != Vector2::ZERO)
  274. body_->ApplyForceToCenter(ToB2Vec2(force), wake);
  275. }
  276. void RigidBody2D::ApplyTorque(float torque, bool wake)
  277. {
  278. if (body_ && torque != 0)
  279. body_->ApplyTorque(torque, wake);
  280. }
  281. void RigidBody2D::ApplyLinearImpulse(const Vector2& impulse, const Vector2& point, bool wake)
  282. {
  283. if (body_ && impulse != Vector2::ZERO)
  284. body_->ApplyLinearImpulse(ToB2Vec2(impulse), ToB2Vec2(point), wake);
  285. }
  286. void RigidBody2D::ApplyLinearImpulseToCenter(const Vector2& impulse, bool wake)
  287. {
  288. if (body_ && impulse != Vector2::ZERO)
  289. body_->ApplyLinearImpulseToCenter(ToB2Vec2(impulse), wake);
  290. }
  291. void RigidBody2D::ApplyAngularImpulse(float impulse, bool wake)
  292. {
  293. if (body_)
  294. body_->ApplyAngularImpulse(impulse, wake);
  295. }
  296. void RigidBody2D::CreateBody()
  297. {
  298. if (body_)
  299. return;
  300. if (!physicsWorld_ || !physicsWorld_->GetWorld())
  301. return;
  302. bodyDef_.position = ToB2Vec2(node_->GetWorldPosition());
  303. bodyDef_.angle = node_->GetWorldRotation().RollAngle() * M_DEGTORAD;
  304. body_ = physicsWorld_->GetWorld()->CreateBody(&bodyDef_);
  305. body_->SetUserData(this);
  306. for (unsigned i = 0; i < collisionShapes_.Size(); ++i)
  307. {
  308. if (collisionShapes_[i])
  309. collisionShapes_[i]->CreateFixture();
  310. }
  311. if (!useFixtureMass_)
  312. body_->SetMassData(&massData_);
  313. for (unsigned i = 0; i < constraints_.Size(); ++i)
  314. {
  315. if (constraints_[i])
  316. constraints_[i]->CreateJoint();
  317. }
  318. }
  319. void RigidBody2D::ReleaseBody()
  320. {
  321. if (!body_)
  322. return;
  323. if (!physicsWorld_ || !physicsWorld_->GetWorld())
  324. return;
  325. // Make a copy for iteration
  326. Vector<WeakPtr<Constraint2D> > constraints = constraints_;
  327. for (unsigned i = 0; i < constraints.Size(); ++i)
  328. {
  329. if (constraints[i])
  330. constraints[i]->ReleaseJoint();
  331. }
  332. for (unsigned i = 0; i < collisionShapes_.Size(); ++i)
  333. {
  334. if (collisionShapes_[i])
  335. collisionShapes_[i]->ReleaseFixture();
  336. }
  337. physicsWorld_->GetWorld()->DestroyBody(body_);
  338. body_ = nullptr;
  339. }
  340. void RigidBody2D::ApplyWorldTransform()
  341. {
  342. if (!body_ || !node_)
  343. return;
  344. // If the rigid body is parented to another rigid body, can not set the transform immediately.
  345. // In that case store it to PhysicsWorld2D for delayed assignment
  346. RigidBody2D* parentRigidBody = nullptr;
  347. Node* parent = node_->GetParent();
  348. if (parent != GetScene() && parent)
  349. parentRigidBody = parent->GetComponent<RigidBody2D>();
  350. // If body is not parented and is static or sleeping, no need to update
  351. if (!parentRigidBody && (!body_->IsActive() || body_->GetType() == b2_staticBody || !body_->IsAwake()))
  352. return;
  353. const b2Transform& transform = body_->GetTransform();
  354. Vector3 newWorldPosition = node_->GetWorldPosition();
  355. newWorldPosition.x_ = transform.p.x;
  356. newWorldPosition.y_ = transform.p.y;
  357. Quaternion newWorldRotation(transform.q.GetAngle() * M_RADTODEG, Vector3::FORWARD);
  358. if (parentRigidBody)
  359. {
  360. DelayedWorldTransform2D delayed;
  361. delayed.rigidBody_ = this;
  362. delayed.parentRigidBody_ = parentRigidBody;
  363. delayed.worldPosition_ = newWorldPosition;
  364. delayed.worldRotation_ = newWorldRotation;
  365. physicsWorld_->AddDelayedWorldTransform(delayed);
  366. }
  367. else
  368. ApplyWorldTransform(newWorldPosition, newWorldRotation);
  369. }
  370. void RigidBody2D::ApplyWorldTransform(const Vector3& newWorldPosition, const Quaternion& newWorldRotation)
  371. {
  372. if (newWorldPosition != node_->GetWorldPosition() || newWorldRotation != node_->GetWorldRotation())
  373. {
  374. // Do not feed changed position back to simulation now
  375. physicsWorld_->SetApplyingTransforms(true);
  376. node_->SetWorldPosition(newWorldPosition);
  377. node_->SetWorldRotation(newWorldRotation);
  378. physicsWorld_->SetApplyingTransforms(false);
  379. }
  380. }
  381. void RigidBody2D::AddCollisionShape2D(CollisionShape2D* collisionShape)
  382. {
  383. if (!collisionShape)
  384. return;
  385. WeakPtr<CollisionShape2D> collisionShapePtr(collisionShape);
  386. if (collisionShapes_.Contains(collisionShapePtr))
  387. return;
  388. collisionShapes_.Push(collisionShapePtr);
  389. }
  390. void RigidBody2D::RemoveCollisionShape2D(CollisionShape2D* collisionShape)
  391. {
  392. if (!collisionShape)
  393. return;
  394. WeakPtr<CollisionShape2D> collisionShapePtr(collisionShape);
  395. collisionShapes_.Remove(collisionShapePtr);
  396. }
  397. void RigidBody2D::AddConstraint2D(Constraint2D* constraint)
  398. {
  399. if (!constraint)
  400. return;
  401. WeakPtr<Constraint2D> constraintPtr(constraint);
  402. if (constraints_.Contains(constraintPtr))
  403. return;
  404. constraints_.Push(constraintPtr);
  405. }
  406. void RigidBody2D::RemoveConstraint2D(Constraint2D* constraint)
  407. {
  408. if (!constraint)
  409. return;
  410. WeakPtr<Constraint2D> constraintPtr(constraint);
  411. constraints_.Remove(constraintPtr);
  412. }
  413. float RigidBody2D::GetMass() const
  414. {
  415. if (!useFixtureMass_)
  416. return massData_.mass;
  417. else
  418. return body_ ? body_->GetMass() : 0.0f;
  419. }
  420. float RigidBody2D::GetInertia() const
  421. {
  422. if (!useFixtureMass_)
  423. return massData_.I;
  424. else
  425. return body_ ? body_->GetInertia() : 0.0f;
  426. }
  427. Vector2 RigidBody2D::GetMassCenter() const
  428. {
  429. if (!useFixtureMass_)
  430. return ToVector2(massData_.center);
  431. else
  432. return body_ ? ToVector2(body_->GetLocalCenter()) : Vector2::ZERO;
  433. }
  434. bool RigidBody2D::IsAwake() const
  435. {
  436. return body_ ? body_->IsAwake() : bodyDef_.awake;
  437. }
  438. Vector2 RigidBody2D::GetLinearVelocity() const
  439. {
  440. return ToVector2(body_ ? body_->GetLinearVelocity() : bodyDef_.linearVelocity);
  441. }
  442. float RigidBody2D::GetAngularVelocity() const
  443. {
  444. return body_ ? body_->GetAngularVelocity() : bodyDef_.angularVelocity;
  445. }
  446. void RigidBody2D::OnNodeSet(Node* node)
  447. {
  448. if (node)
  449. {
  450. node->AddListener(this);
  451. PODVector<CollisionShape2D*> shapes;
  452. node_->GetDerivedComponents<CollisionShape2D>(shapes);
  453. for (PODVector<CollisionShape2D*>::Iterator i = shapes.Begin(); i != shapes.End(); ++i)
  454. {
  455. (*i)->CreateFixture();
  456. AddCollisionShape2D(*i);
  457. }
  458. }
  459. }
  460. void RigidBody2D::OnSceneSet(Scene* scene)
  461. {
  462. if (scene)
  463. {
  464. physicsWorld_ = scene->GetDerivedComponent<PhysicsWorld2D>();
  465. if (!physicsWorld_)
  466. physicsWorld_ = scene->CreateComponent<PhysicsWorld2D>();
  467. CreateBody();
  468. physicsWorld_->AddRigidBody(this);
  469. }
  470. else
  471. {
  472. if (physicsWorld_)
  473. {
  474. ReleaseBody();
  475. physicsWorld_->RemoveRigidBody(this);
  476. physicsWorld_.Reset();
  477. }
  478. }
  479. }
  480. void RigidBody2D::OnMarkedDirty(Node* node)
  481. {
  482. if (physicsWorld_ && physicsWorld_->IsApplyingTransforms())
  483. return;
  484. // Physics operations are not safe from worker threads
  485. Scene* scene = GetScene();
  486. if (scene && scene->IsThreadedUpdate())
  487. {
  488. scene->DelayedMarkedDirty(this);
  489. return;
  490. }
  491. // Check if transform has changed from the last one set in ApplyWorldTransform()
  492. b2Vec2 newPosition = ToB2Vec2(node_->GetWorldPosition());
  493. float newAngle = node_->GetWorldRotation().RollAngle() * M_DEGTORAD;
  494. if (!body_)
  495. {
  496. bodyDef_.position = newPosition;
  497. bodyDef_.angle = newAngle;
  498. }
  499. else if (newPosition != body_->GetPosition() || newAngle != body_->GetAngle())
  500. body_->SetTransform(newPosition, newAngle);
  501. }
  502. }