RigidBody.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../IO/Log.h"
  26. #include "../IO/MemoryBuffer.h"
  27. #include "../Physics/CollisionShape.h"
  28. #include "../Physics/Constraint.h"
  29. #include "../Physics/PhysicsUtils.h"
  30. #include "../Physics/PhysicsWorld.h"
  31. #include "../Physics/RigidBody.h"
  32. #include "../Resource/ResourceCache.h"
  33. #include "../Resource/ResourceEvents.h"
  34. #include "../Scene/Scene.h"
  35. #include "../Scene/SceneEvents.h"
  36. #include "../Scene/SmoothedTransform.h"
  37. // ATOMIC BEGIN
  38. #include <Bullet/src/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
  39. #include <Bullet/src/BulletDynamics/Dynamics/btRigidBody.h>
  40. #include <Bullet/src/BulletCollision/CollisionShapes/btCompoundShape.h>
  41. // ATOMIC END
  42. namespace Atomic
  43. {
  44. static const float DEFAULT_MASS = 0.0f;
  45. static const float DEFAULT_FRICTION = 0.5f;
  46. static const float DEFAULT_RESTITUTION = 0.0f;
  47. static const float DEFAULT_ROLLING_FRICTION = 0.0f;
  48. static const unsigned DEFAULT_COLLISION_LAYER = 0x1;
  49. static const unsigned DEFAULT_COLLISION_MASK = M_MAX_UNSIGNED;
  50. static const char* collisionEventModeNames[] =
  51. {
  52. "Never",
  53. "When Active",
  54. "Always",
  55. 0
  56. };
  57. extern const char* PHYSICS_CATEGORY;
  58. RigidBody::RigidBody(Context* context) :
  59. Component(context),
  60. body_(0),
  61. compoundShape_(0),
  62. shiftedCompoundShape_(0),
  63. gravityOverride_(Vector3::ZERO),
  64. centerOfMass_(Vector3::ZERO),
  65. mass_(DEFAULT_MASS),
  66. collisionLayer_(DEFAULT_COLLISION_LAYER),
  67. collisionMask_(DEFAULT_COLLISION_MASK),
  68. collisionEventMode_(COLLISION_ACTIVE),
  69. lastPosition_(Vector3::ZERO),
  70. lastRotation_(Quaternion::IDENTITY),
  71. kinematic_(false),
  72. trigger_(false),
  73. useGravity_(true),
  74. readdBody_(false),
  75. inWorld_(false),
  76. enableMassUpdate_(true),
  77. hasSimulated_(false)
  78. {
  79. compoundShape_ = new btCompoundShape();
  80. shiftedCompoundShape_ = new btCompoundShape();
  81. }
  82. RigidBody::~RigidBody()
  83. {
  84. ReleaseBody();
  85. if (physicsWorld_)
  86. physicsWorld_->RemoveRigidBody(this);
  87. delete compoundShape_;
  88. compoundShape_ = 0;
  89. delete shiftedCompoundShape_;
  90. shiftedCompoundShape_ = 0;
  91. }
  92. void RigidBody::RegisterObject(Context* context)
  93. {
  94. context->RegisterFactory<RigidBody>(PHYSICS_CATEGORY);
  95. ATOMIC_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  96. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Physics Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE | AM_NOEDIT);
  97. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Physics Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE | AM_NOEDIT);
  98. ATOMIC_ATTRIBUTE("Mass", float, mass_, DEFAULT_MASS, AM_DEFAULT);
  99. ATOMIC_ACCESSOR_ATTRIBUTE("Friction", GetFriction, SetFriction, float, DEFAULT_FRICTION, AM_DEFAULT);
  100. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Anisotropic Friction", GetAnisotropicFriction, SetAnisotropicFriction, Vector3, Vector3::ONE,
  101. AM_DEFAULT);
  102. ATOMIC_ACCESSOR_ATTRIBUTE("Rolling Friction", GetRollingFriction, SetRollingFriction, float, DEFAULT_ROLLING_FRICTION, AM_DEFAULT);
  103. ATOMIC_ACCESSOR_ATTRIBUTE("Restitution", GetRestitution, SetRestitution, float, DEFAULT_RESTITUTION, AM_DEFAULT);
  104. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Linear Velocity", GetLinearVelocity, SetLinearVelocity, Vector3, Vector3::ZERO,
  105. AM_DEFAULT | AM_LATESTDATA);
  106. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Angular Velocity", GetAngularVelocity, SetAngularVelocity, Vector3, Vector3::ZERO, AM_FILE);
  107. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Linear Factor", GetLinearFactor, SetLinearFactor, Vector3, Vector3::ONE, AM_DEFAULT);
  108. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Angular Factor", GetAngularFactor, SetAngularFactor, Vector3, Vector3::ONE, AM_DEFAULT);
  109. ATOMIC_ACCESSOR_ATTRIBUTE("Linear Damping", GetLinearDamping, SetLinearDamping, float, 0.0f, AM_DEFAULT);
  110. ATOMIC_ACCESSOR_ATTRIBUTE("Angular Damping", GetAngularDamping, SetAngularDamping, float, 0.0f, AM_DEFAULT);
  111. ATOMIC_ACCESSOR_ATTRIBUTE("Linear Rest Threshold", GetLinearRestThreshold, SetLinearRestThreshold, float, 0.8f, AM_DEFAULT);
  112. ATOMIC_ACCESSOR_ATTRIBUTE("Angular Rest Threshold", GetAngularRestThreshold, SetAngularRestThreshold, float, 1.0f, AM_DEFAULT);
  113. ATOMIC_ATTRIBUTE("Collision Layer", int, collisionLayer_, DEFAULT_COLLISION_LAYER, AM_DEFAULT);
  114. ATOMIC_ATTRIBUTE("Collision Mask", int, collisionMask_, DEFAULT_COLLISION_MASK, AM_DEFAULT);
  115. ATOMIC_ACCESSOR_ATTRIBUTE("Contact Threshold", GetContactProcessingThreshold, SetContactProcessingThreshold, float, BT_LARGE_FLOAT,
  116. AM_DEFAULT);
  117. ATOMIC_ACCESSOR_ATTRIBUTE("CCD Radius", GetCcdRadius, SetCcdRadius, float, 0.0f, AM_DEFAULT);
  118. ATOMIC_ACCESSOR_ATTRIBUTE("CCD Motion Threshold", GetCcdMotionThreshold, SetCcdMotionThreshold, float, 0.0f, AM_DEFAULT);
  119. ATOMIC_ACCESSOR_ATTRIBUTE("Network Angular Velocity", GetNetAngularVelocityAttr, SetNetAngularVelocityAttr, PODVector<unsigned char>,
  120. Variant::emptyBuffer, AM_NET | AM_LATESTDATA | AM_NOEDIT);
  121. ATOMIC_ENUM_ATTRIBUTE("Collision Event Mode", collisionEventMode_, collisionEventModeNames, COLLISION_ACTIVE, AM_DEFAULT);
  122. ATOMIC_ACCESSOR_ATTRIBUTE("Use Gravity", GetUseGravity, SetUseGravity, bool, true, AM_DEFAULT);
  123. ATOMIC_ATTRIBUTE("Is Kinematic", bool, kinematic_, false, AM_DEFAULT);
  124. ATOMIC_ATTRIBUTE("Is Trigger", bool, trigger_, false, AM_DEFAULT);
  125. ATOMIC_ACCESSOR_ATTRIBUTE("Gravity Override", GetGravityOverride, SetGravityOverride, Vector3, Vector3::ZERO, AM_DEFAULT);
  126. }
  127. void RigidBody::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  128. {
  129. Serializable::OnSetAttribute(attr, src);
  130. // Change of any non-accessor attribute requires the rigid body to be re-added to the physics world
  131. if (!attr.accessor_)
  132. readdBody_ = true;
  133. }
  134. void RigidBody::ApplyAttributes()
  135. {
  136. if (readdBody_)
  137. AddBodyToWorld();
  138. }
  139. void RigidBody::OnSetEnabled()
  140. {
  141. bool enabled = IsEnabledEffective();
  142. if (enabled && !inWorld_)
  143. AddBodyToWorld();
  144. else if (!enabled && inWorld_)
  145. RemoveBodyFromWorld();
  146. }
  147. void RigidBody::getWorldTransform(btTransform& worldTrans) const
  148. {
  149. // We may be in a pathological state where a RigidBody exists without a scene node when this callback is fired,
  150. // so check to be sure
  151. if (node_)
  152. {
  153. lastPosition_ = node_->GetWorldPosition();
  154. lastRotation_ = node_->GetWorldRotation();
  155. worldTrans.setOrigin(ToBtVector3(lastPosition_ + lastRotation_ * centerOfMass_));
  156. worldTrans.setRotation(ToBtQuaternion(lastRotation_));
  157. }
  158. hasSimulated_ = true;
  159. }
  160. void RigidBody::setWorldTransform(const btTransform& worldTrans)
  161. {
  162. Quaternion newWorldRotation = ToQuaternion(worldTrans.getRotation());
  163. Vector3 newWorldPosition = ToVector3(worldTrans.getOrigin()) - newWorldRotation * centerOfMass_;
  164. RigidBody* parentRigidBody = 0;
  165. // It is possible that the RigidBody component has been kept alive via a shared pointer,
  166. // while its scene node has already been destroyed
  167. if (node_)
  168. {
  169. // If the rigid body is parented to another rigid body, can not set the transform immediately.
  170. // In that case store it to PhysicsWorld for delayed assignment
  171. Node* parent = node_->GetParent();
  172. if (parent != GetScene() && parent)
  173. parentRigidBody = parent->GetComponent<RigidBody>();
  174. if (!parentRigidBody)
  175. ApplyWorldTransform(newWorldPosition, newWorldRotation);
  176. else
  177. {
  178. DelayedWorldTransform delayed;
  179. delayed.rigidBody_ = this;
  180. delayed.parentRigidBody_ = parentRigidBody;
  181. delayed.worldPosition_ = newWorldPosition;
  182. delayed.worldRotation_ = newWorldRotation;
  183. physicsWorld_->AddDelayedWorldTransform(delayed);
  184. }
  185. MarkNetworkUpdate();
  186. }
  187. hasSimulated_ = true;
  188. }
  189. void RigidBody::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  190. {
  191. if (debug && physicsWorld_ && body_ && IsEnabledEffective())
  192. {
  193. physicsWorld_->SetDebugRenderer(debug);
  194. physicsWorld_->SetDebugDepthTest(depthTest);
  195. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  196. world->debugDrawObject(body_->getWorldTransform(), shiftedCompoundShape_, IsActive() ? btVector3(1.0f, 1.0f, 1.0f) :
  197. btVector3(0.0f, 1.0f, 0.0f));
  198. physicsWorld_->SetDebugRenderer(0);
  199. }
  200. }
  201. void RigidBody::SetMass(float mass)
  202. {
  203. mass = Max(mass, 0.0f);
  204. if (mass != mass_)
  205. {
  206. mass_ = mass;
  207. AddBodyToWorld();
  208. MarkNetworkUpdate();
  209. }
  210. }
  211. void RigidBody::SetPosition(const Vector3& position)
  212. {
  213. if (body_)
  214. {
  215. btTransform& worldTrans = body_->getWorldTransform();
  216. worldTrans.setOrigin(ToBtVector3(position + ToQuaternion(worldTrans.getRotation()) * centerOfMass_));
  217. // When forcing the physics position, set also interpolated position so that there is no jitter
  218. // When not inside the simulation loop, this may lead to erratic movement of parented rigidbodies
  219. // so skip in that case. Exception made before first simulation tick so that interpolation position
  220. // of e.g. instantiated prefabs will be correct from the start
  221. if (!hasSimulated_ || physicsWorld_->IsSimulating())
  222. {
  223. btTransform interpTrans = body_->getInterpolationWorldTransform();
  224. interpTrans.setOrigin(worldTrans.getOrigin());
  225. body_->setInterpolationWorldTransform(interpTrans);
  226. }
  227. Activate();
  228. MarkNetworkUpdate();
  229. }
  230. }
  231. void RigidBody::SetRotation(const Quaternion& rotation)
  232. {
  233. if (body_)
  234. {
  235. Vector3 oldPosition = GetPosition();
  236. btTransform& worldTrans = body_->getWorldTransform();
  237. worldTrans.setRotation(ToBtQuaternion(rotation));
  238. if (!centerOfMass_.Equals(Vector3::ZERO))
  239. worldTrans.setOrigin(ToBtVector3(oldPosition + rotation * centerOfMass_));
  240. if (!hasSimulated_ || physicsWorld_->IsSimulating())
  241. {
  242. btTransform interpTrans = body_->getInterpolationWorldTransform();
  243. interpTrans.setRotation(worldTrans.getRotation());
  244. if (!centerOfMass_.Equals(Vector3::ZERO))
  245. interpTrans.setOrigin(worldTrans.getOrigin());
  246. body_->setInterpolationWorldTransform(interpTrans);
  247. }
  248. body_->updateInertiaTensor();
  249. Activate();
  250. MarkNetworkUpdate();
  251. }
  252. }
  253. void RigidBody::SetTransform(const Vector3& position, const Quaternion& rotation)
  254. {
  255. if (body_)
  256. {
  257. btTransform& worldTrans = body_->getWorldTransform();
  258. worldTrans.setRotation(ToBtQuaternion(rotation));
  259. worldTrans.setOrigin(ToBtVector3(position + rotation * centerOfMass_));
  260. if (!hasSimulated_ || physicsWorld_->IsSimulating())
  261. {
  262. btTransform interpTrans = body_->getInterpolationWorldTransform();
  263. interpTrans.setOrigin(worldTrans.getOrigin());
  264. interpTrans.setRotation(worldTrans.getRotation());
  265. body_->setInterpolationWorldTransform(interpTrans);
  266. }
  267. body_->updateInertiaTensor();
  268. Activate();
  269. MarkNetworkUpdate();
  270. }
  271. }
  272. void RigidBody::SetLinearVelocity(const Vector3& velocity)
  273. {
  274. if (body_)
  275. {
  276. body_->setLinearVelocity(ToBtVector3(velocity));
  277. if (velocity != Vector3::ZERO)
  278. Activate();
  279. MarkNetworkUpdate();
  280. }
  281. }
  282. void RigidBody::SetLinearFactor(const Vector3& factor)
  283. {
  284. if (body_)
  285. {
  286. body_->setLinearFactor(ToBtVector3(factor));
  287. MarkNetworkUpdate();
  288. }
  289. }
  290. void RigidBody::SetLinearRestThreshold(float threshold)
  291. {
  292. if (body_)
  293. {
  294. body_->setSleepingThresholds(threshold, body_->getAngularSleepingThreshold());
  295. MarkNetworkUpdate();
  296. }
  297. }
  298. void RigidBody::SetLinearDamping(float damping)
  299. {
  300. if (body_)
  301. {
  302. body_->setDamping(damping, body_->getAngularDamping());
  303. MarkNetworkUpdate();
  304. }
  305. }
  306. void RigidBody::SetAngularVelocity(const Vector3& velocity)
  307. {
  308. if (body_)
  309. {
  310. body_->setAngularVelocity(ToBtVector3(velocity));
  311. if (velocity != Vector3::ZERO)
  312. Activate();
  313. MarkNetworkUpdate();
  314. }
  315. }
  316. void RigidBody::SetAngularFactor(const Vector3& factor)
  317. {
  318. if (body_)
  319. {
  320. body_->setAngularFactor(ToBtVector3(factor));
  321. MarkNetworkUpdate();
  322. }
  323. }
  324. void RigidBody::SetAngularRestThreshold(float threshold)
  325. {
  326. if (body_)
  327. {
  328. body_->setSleepingThresholds(body_->getLinearSleepingThreshold(), threshold);
  329. MarkNetworkUpdate();
  330. }
  331. }
  332. void RigidBody::SetAngularDamping(float damping)
  333. {
  334. if (body_)
  335. {
  336. body_->setDamping(body_->getLinearDamping(), damping);
  337. MarkNetworkUpdate();
  338. }
  339. }
  340. void RigidBody::SetFriction(float friction)
  341. {
  342. if (body_)
  343. {
  344. body_->setFriction(friction);
  345. MarkNetworkUpdate();
  346. }
  347. }
  348. void RigidBody::SetAnisotropicFriction(const Vector3& friction)
  349. {
  350. if (body_)
  351. {
  352. body_->setAnisotropicFriction(ToBtVector3(friction));
  353. MarkNetworkUpdate();
  354. }
  355. }
  356. void RigidBody::SetRollingFriction(float friction)
  357. {
  358. if (body_)
  359. {
  360. body_->setRollingFriction(friction);
  361. MarkNetworkUpdate();
  362. }
  363. }
  364. void RigidBody::SetRestitution(float restitution)
  365. {
  366. if (body_)
  367. {
  368. body_->setRestitution(restitution);
  369. MarkNetworkUpdate();
  370. }
  371. }
  372. void RigidBody::SetContactProcessingThreshold(float threshold)
  373. {
  374. if (body_)
  375. {
  376. body_->setContactProcessingThreshold(threshold);
  377. MarkNetworkUpdate();
  378. }
  379. }
  380. void RigidBody::SetCcdRadius(float radius)
  381. {
  382. radius = Max(radius, 0.0f);
  383. if (body_)
  384. {
  385. body_->setCcdSweptSphereRadius(radius);
  386. MarkNetworkUpdate();
  387. }
  388. }
  389. void RigidBody::SetCcdMotionThreshold(float threshold)
  390. {
  391. threshold = Max(threshold, 0.0f);
  392. if (body_)
  393. {
  394. body_->setCcdMotionThreshold(threshold);
  395. MarkNetworkUpdate();
  396. }
  397. }
  398. void RigidBody::SetUseGravity(bool enable)
  399. {
  400. if (enable != useGravity_)
  401. {
  402. useGravity_ = enable;
  403. UpdateGravity();
  404. MarkNetworkUpdate();
  405. }
  406. }
  407. void RigidBody::SetGravityOverride(const Vector3& gravity)
  408. {
  409. if (gravity != gravityOverride_)
  410. {
  411. gravityOverride_ = gravity;
  412. UpdateGravity();
  413. MarkNetworkUpdate();
  414. }
  415. }
  416. void RigidBody::SetKinematic(bool enable)
  417. {
  418. if (enable != kinematic_)
  419. {
  420. kinematic_ = enable;
  421. AddBodyToWorld();
  422. MarkNetworkUpdate();
  423. }
  424. }
  425. void RigidBody::SetTrigger(bool enable)
  426. {
  427. if (enable != trigger_)
  428. {
  429. trigger_ = enable;
  430. AddBodyToWorld();
  431. MarkNetworkUpdate();
  432. }
  433. }
  434. void RigidBody::SetCollisionLayer(unsigned layer)
  435. {
  436. if (layer != collisionLayer_)
  437. {
  438. collisionLayer_ = layer;
  439. AddBodyToWorld();
  440. MarkNetworkUpdate();
  441. }
  442. }
  443. void RigidBody::SetCollisionMask(unsigned mask)
  444. {
  445. if (mask != collisionMask_)
  446. {
  447. collisionMask_ = mask;
  448. AddBodyToWorld();
  449. MarkNetworkUpdate();
  450. }
  451. }
  452. void RigidBody::SetCollisionLayerAndMask(unsigned layer, unsigned mask)
  453. {
  454. if (layer != collisionLayer_ || mask != collisionMask_)
  455. {
  456. collisionLayer_ = layer;
  457. collisionMask_ = mask;
  458. AddBodyToWorld();
  459. MarkNetworkUpdate();
  460. }
  461. }
  462. void RigidBody::SetCollisionEventMode(CollisionEventMode mode)
  463. {
  464. collisionEventMode_ = mode;
  465. MarkNetworkUpdate();
  466. }
  467. void RigidBody::ApplyForce(const Vector3& force)
  468. {
  469. if (body_ && force != Vector3::ZERO)
  470. {
  471. Activate();
  472. body_->applyCentralForce(ToBtVector3(force));
  473. }
  474. }
  475. void RigidBody::ApplyForce(const Vector3& force, const Vector3& position)
  476. {
  477. if (body_ && force != Vector3::ZERO)
  478. {
  479. Activate();
  480. body_->applyForce(ToBtVector3(force), ToBtVector3(position - centerOfMass_));
  481. }
  482. }
  483. void RigidBody::ApplyTorque(const Vector3& torque)
  484. {
  485. if (body_ && torque != Vector3::ZERO)
  486. {
  487. Activate();
  488. body_->applyTorque(ToBtVector3(torque));
  489. }
  490. }
  491. void RigidBody::ApplyImpulse(const Vector3& impulse)
  492. {
  493. if (body_ && impulse != Vector3::ZERO)
  494. {
  495. Activate();
  496. body_->applyCentralImpulse(ToBtVector3(impulse));
  497. }
  498. }
  499. void RigidBody::ApplyImpulse(const Vector3& impulse, const Vector3& position)
  500. {
  501. if (body_ && impulse != Vector3::ZERO)
  502. {
  503. Activate();
  504. body_->applyImpulse(ToBtVector3(impulse), ToBtVector3(position - centerOfMass_));
  505. }
  506. }
  507. void RigidBody::ApplyTorqueImpulse(const Vector3& torque)
  508. {
  509. if (body_ && torque != Vector3::ZERO)
  510. {
  511. Activate();
  512. body_->applyTorqueImpulse(ToBtVector3(torque));
  513. }
  514. }
  515. void RigidBody::ResetForces()
  516. {
  517. if (body_)
  518. body_->clearForces();
  519. }
  520. void RigidBody::Activate()
  521. {
  522. if (body_ && mass_ > 0.0f)
  523. body_->activate(true);
  524. }
  525. void RigidBody::ReAddBodyToWorld()
  526. {
  527. if (body_ && inWorld_)
  528. AddBodyToWorld();
  529. }
  530. void RigidBody::DisableMassUpdate()
  531. {
  532. enableMassUpdate_ = false;
  533. }
  534. void RigidBody::EnableMassUpdate()
  535. {
  536. if (!enableMassUpdate_)
  537. {
  538. enableMassUpdate_ = true;
  539. UpdateMass();
  540. }
  541. }
  542. Vector3 RigidBody::GetPosition() const
  543. {
  544. if (body_)
  545. {
  546. const btTransform& transform = body_->getWorldTransform();
  547. return ToVector3(transform.getOrigin()) - ToQuaternion(transform.getRotation()) * centerOfMass_;
  548. }
  549. else
  550. return Vector3::ZERO;
  551. }
  552. Quaternion RigidBody::GetRotation() const
  553. {
  554. return body_ ? ToQuaternion(body_->getWorldTransform().getRotation()) : Quaternion::IDENTITY;
  555. }
  556. Vector3 RigidBody::GetLinearVelocity() const
  557. {
  558. return body_ ? ToVector3(body_->getLinearVelocity()) : Vector3::ZERO;
  559. }
  560. Vector3 RigidBody::GetLinearFactor() const
  561. {
  562. return body_ ? ToVector3(body_->getLinearFactor()) : Vector3::ZERO;
  563. }
  564. Vector3 RigidBody::GetVelocityAtPoint(const Vector3& position) const
  565. {
  566. return body_ ? ToVector3(body_->getVelocityInLocalPoint(ToBtVector3(position - centerOfMass_))) : Vector3::ZERO;
  567. }
  568. float RigidBody::GetLinearRestThreshold() const
  569. {
  570. return body_ ? body_->getLinearSleepingThreshold() : 0.0f;
  571. }
  572. float RigidBody::GetLinearDamping() const
  573. {
  574. return body_ ? body_->getLinearDamping() : 0.0f;
  575. }
  576. Vector3 RigidBody::GetAngularVelocity() const
  577. {
  578. return body_ ? ToVector3(body_->getAngularVelocity()) : Vector3::ZERO;
  579. }
  580. Vector3 RigidBody::GetAngularFactor() const
  581. {
  582. return body_ ? ToVector3(body_->getAngularFactor()) : Vector3::ZERO;
  583. }
  584. float RigidBody::GetAngularRestThreshold() const
  585. {
  586. return body_ ? body_->getAngularSleepingThreshold() : 0.0f;
  587. }
  588. float RigidBody::GetAngularDamping() const
  589. {
  590. return body_ ? body_->getAngularDamping() : 0.0f;
  591. }
  592. float RigidBody::GetFriction() const
  593. {
  594. return body_ ? body_->getFriction() : 0.0f;
  595. }
  596. Vector3 RigidBody::GetAnisotropicFriction() const
  597. {
  598. return body_ ? ToVector3(body_->getAnisotropicFriction()) : Vector3::ZERO;
  599. }
  600. float RigidBody::GetRollingFriction() const
  601. {
  602. return body_ ? body_->getRollingFriction() : 0.0f;
  603. }
  604. float RigidBody::GetRestitution() const
  605. {
  606. return body_ ? body_->getRestitution() : 0.0f;
  607. }
  608. float RigidBody::GetContactProcessingThreshold() const
  609. {
  610. return body_ ? body_->getContactProcessingThreshold() : 0.0f;
  611. }
  612. float RigidBody::GetCcdRadius() const
  613. {
  614. return body_ ? body_->getCcdSweptSphereRadius() : 0.0f;
  615. }
  616. float RigidBody::GetCcdMotionThreshold() const
  617. {
  618. return body_ ? body_->getCcdMotionThreshold() : 0.0f;
  619. }
  620. bool RigidBody::IsActive() const
  621. {
  622. return body_ ? body_->isActive() : false;
  623. }
  624. void RigidBody::GetCollidingBodies(PODVector<RigidBody*>& result) const
  625. {
  626. if (physicsWorld_)
  627. physicsWorld_->GetCollidingBodies(result, this);
  628. else
  629. result.Clear();
  630. }
  631. void RigidBody::ApplyWorldTransform(const Vector3& newWorldPosition, const Quaternion& newWorldRotation)
  632. {
  633. // In case of holding an extra reference to the RigidBody, this could be called in a situation
  634. // where node is already null
  635. if (!node_ || !physicsWorld_)
  636. return;
  637. physicsWorld_->SetApplyingTransforms(true);
  638. // Apply transform to the SmoothedTransform component instead of node transform if available
  639. if (smoothedTransform_)
  640. {
  641. smoothedTransform_->SetTargetWorldPosition(newWorldPosition);
  642. smoothedTransform_->SetTargetWorldRotation(newWorldRotation);
  643. lastPosition_ = newWorldPosition;
  644. lastRotation_ = newWorldRotation;
  645. }
  646. else
  647. {
  648. node_->SetWorldPosition(newWorldPosition);
  649. node_->SetWorldRotation(newWorldRotation);
  650. lastPosition_ = node_->GetWorldPosition();
  651. lastRotation_ = node_->GetWorldRotation();
  652. }
  653. physicsWorld_->SetApplyingTransforms(false);
  654. }
  655. void RigidBody::UpdateMass()
  656. {
  657. if (!body_ || !enableMassUpdate_)
  658. return;
  659. btTransform principal;
  660. principal.setRotation(btQuaternion::getIdentity());
  661. principal.setOrigin(btVector3(0.0f, 0.0f, 0.0f));
  662. // Calculate center of mass shift from all the collision shapes
  663. unsigned numShapes = (unsigned)compoundShape_->getNumChildShapes();
  664. if (numShapes)
  665. {
  666. PODVector<float> masses(numShapes);
  667. for (unsigned i = 0; i < numShapes; ++i)
  668. {
  669. // The actual mass does not matter, divide evenly between child shapes
  670. masses[i] = 1.0f;
  671. }
  672. btVector3 inertia(0.0f, 0.0f, 0.0f);
  673. compoundShape_->calculatePrincipalAxisTransform(&masses[0], principal, inertia);
  674. }
  675. // Add child shapes to shifted compound shape with adjusted offset
  676. while (shiftedCompoundShape_->getNumChildShapes())
  677. shiftedCompoundShape_->removeChildShapeByIndex(shiftedCompoundShape_->getNumChildShapes() - 1);
  678. for (unsigned i = 0; i < numShapes; ++i)
  679. {
  680. btTransform adjusted = compoundShape_->getChildTransform(i);
  681. adjusted.setOrigin(adjusted.getOrigin() - principal.getOrigin());
  682. shiftedCompoundShape_->addChildShape(adjusted, compoundShape_->getChildShape(i));
  683. }
  684. // If shifted compound shape has only one child with no offset/rotation, use the child shape
  685. // directly as the rigid body collision shape for better collision detection performance
  686. bool useCompound = !numShapes || numShapes > 1;
  687. if (!useCompound)
  688. {
  689. const btTransform& childTransform = shiftedCompoundShape_->getChildTransform(0);
  690. if (!ToVector3(childTransform.getOrigin()).Equals(Vector3::ZERO) ||
  691. !ToQuaternion(childTransform.getRotation()).Equals(Quaternion::IDENTITY))
  692. useCompound = true;
  693. }
  694. body_->setCollisionShape(useCompound ? shiftedCompoundShape_ : shiftedCompoundShape_->getChildShape(0));
  695. // If we have one shape and this is a triangle mesh, we use a custom material callback in order to adjust internal edges
  696. if (!useCompound && body_->getCollisionShape()->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE &&
  697. physicsWorld_->GetInternalEdge())
  698. body_->setCollisionFlags(body_->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
  699. else
  700. body_->setCollisionFlags(body_->getCollisionFlags() & ~btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
  701. // Reapply rigid body position with new center of mass shift
  702. Vector3 oldPosition = GetPosition();
  703. centerOfMass_ = ToVector3(principal.getOrigin());
  704. SetPosition(oldPosition);
  705. // Calculate final inertia
  706. btVector3 localInertia(0.0f, 0.0f, 0.0f);
  707. if (mass_ > 0.0f)
  708. shiftedCompoundShape_->calculateLocalInertia(mass_, localInertia);
  709. body_->setMassProps(mass_, localInertia);
  710. body_->updateInertiaTensor();
  711. // Reapply constraint positions for new center of mass shift
  712. if (node_)
  713. {
  714. for (PODVector<Constraint*>::Iterator i = constraints_.Begin(); i != constraints_.End(); ++i)
  715. (*i)->ApplyFrames();
  716. }
  717. }
  718. void RigidBody::UpdateGravity()
  719. {
  720. if (physicsWorld_ && body_)
  721. {
  722. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  723. int flags = body_->getFlags();
  724. if (useGravity_ && gravityOverride_ == Vector3::ZERO)
  725. flags &= ~BT_DISABLE_WORLD_GRAVITY;
  726. else
  727. flags |= BT_DISABLE_WORLD_GRAVITY;
  728. body_->setFlags(flags);
  729. if (useGravity_)
  730. {
  731. // If override vector is zero, use world's gravity
  732. if (gravityOverride_ == Vector3::ZERO)
  733. body_->setGravity(world->getGravity());
  734. else
  735. body_->setGravity(ToBtVector3(gravityOverride_));
  736. }
  737. else
  738. body_->setGravity(btVector3(0.0f, 0.0f, 0.0f));
  739. }
  740. }
  741. void RigidBody::SetNetAngularVelocityAttr(const PODVector<unsigned char>& value)
  742. {
  743. float maxVelocity = physicsWorld_ ? physicsWorld_->GetMaxNetworkAngularVelocity() : DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY;
  744. MemoryBuffer buf(value);
  745. SetAngularVelocity(buf.ReadPackedVector3(maxVelocity));
  746. }
  747. const PODVector<unsigned char>& RigidBody::GetNetAngularVelocityAttr() const
  748. {
  749. float maxVelocity = physicsWorld_ ? physicsWorld_->GetMaxNetworkAngularVelocity() : DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY;
  750. attrBuffer_.Clear();
  751. attrBuffer_.WritePackedVector3(GetAngularVelocity(), maxVelocity);
  752. return attrBuffer_.GetBuffer();
  753. }
  754. void RigidBody::AddConstraint(Constraint* constraint)
  755. {
  756. constraints_.Push(constraint);
  757. }
  758. void RigidBody::RemoveConstraint(Constraint* constraint)
  759. {
  760. constraints_.Remove(constraint);
  761. // A constraint being removed should possibly cause the object to eg. start falling, so activate
  762. Activate();
  763. }
  764. void RigidBody::ReleaseBody()
  765. {
  766. if (body_)
  767. {
  768. // Release all constraints which refer to this body
  769. // Make a copy for iteration
  770. PODVector<Constraint*> constraints = constraints_;
  771. for (PODVector<Constraint*>::Iterator i = constraints.Begin(); i != constraints.End(); ++i)
  772. (*i)->ReleaseConstraint();
  773. RemoveBodyFromWorld();
  774. delete body_;
  775. body_ = 0;
  776. }
  777. }
  778. void RigidBody::OnMarkedDirty(Node* node)
  779. {
  780. // If node transform changes, apply it back to the physics transform. However, do not do this when a SmoothedTransform
  781. // is in use, because in that case the node transform will be constantly updated into smoothed, possibly non-physical
  782. // states; rather follow the SmoothedTransform target transform directly
  783. // Also, for kinematic objects Bullet asks the position from us, so we do not need to apply ourselves
  784. // (exception: initial setting of transform)
  785. if ((!kinematic_ || !hasSimulated_) && (!physicsWorld_ || !physicsWorld_->IsApplyingTransforms()) && !smoothedTransform_)
  786. {
  787. // Physics operations are not safe from worker threads
  788. Scene* scene = GetScene();
  789. if (scene && scene->IsThreadedUpdate())
  790. {
  791. scene->DelayedMarkedDirty(this);
  792. return;
  793. }
  794. // Check if transform has changed from the last one set in ApplyWorldTransform()
  795. Vector3 newPosition = node_->GetWorldPosition();
  796. Quaternion newRotation = node_->GetWorldRotation();
  797. if (!newRotation.Equals(lastRotation_))
  798. {
  799. lastRotation_ = newRotation;
  800. SetRotation(newRotation);
  801. }
  802. if (!newPosition.Equals(lastPosition_))
  803. {
  804. lastPosition_ = newPosition;
  805. SetPosition(newPosition);
  806. }
  807. }
  808. }
  809. void RigidBody::OnNodeSet(Node* node)
  810. {
  811. if (node)
  812. node->AddListener(this);
  813. }
  814. void RigidBody::OnSceneSet(Scene* scene)
  815. {
  816. if (scene)
  817. {
  818. if (scene == node_)
  819. ATOMIC_LOGWARNING(GetTypeName() + " should not be created to the root scene node");
  820. physicsWorld_ = scene->GetOrCreateComponent<PhysicsWorld>();
  821. physicsWorld_->AddRigidBody(this);
  822. AddBodyToWorld();
  823. }
  824. else
  825. {
  826. ReleaseBody();
  827. if (physicsWorld_)
  828. physicsWorld_->RemoveRigidBody(this);
  829. }
  830. }
  831. void RigidBody::AddBodyToWorld()
  832. {
  833. if (!physicsWorld_)
  834. return;
  835. ATOMIC_PROFILE(AddBodyToWorld);
  836. if (mass_ < 0.0f)
  837. mass_ = 0.0f;
  838. if (body_)
  839. RemoveBodyFromWorld();
  840. else
  841. {
  842. // Correct inertia will be calculated below
  843. btVector3 localInertia(0.0f, 0.0f, 0.0f);
  844. body_ = new btRigidBody(mass_, this, shiftedCompoundShape_, localInertia);
  845. body_->setUserPointer(this);
  846. // Check for existence of the SmoothedTransform component, which should be created by now in network client mode.
  847. // If it exists, subscribe to its change events
  848. smoothedTransform_ = GetComponent<SmoothedTransform>();
  849. if (smoothedTransform_)
  850. {
  851. SubscribeToEvent(smoothedTransform_, E_TARGETPOSITION, ATOMIC_HANDLER(RigidBody, HandleTargetPosition));
  852. SubscribeToEvent(smoothedTransform_, E_TARGETROTATION, ATOMIC_HANDLER(RigidBody, HandleTargetRotation));
  853. }
  854. // Check if CollisionShapes already exist in the node and add them to the compound shape.
  855. // Do not update mass yet, but do it once all shapes have been added
  856. PODVector<CollisionShape*> shapes;
  857. node_->GetComponents<CollisionShape>(shapes);
  858. for (PODVector<CollisionShape*>::Iterator i = shapes.Begin(); i != shapes.End(); ++i)
  859. (*i)->NotifyRigidBody(false);
  860. // Check if this node contains Constraint components that were waiting for the rigid body to be created, and signal them
  861. // to create themselves now
  862. PODVector<Constraint*> constraints;
  863. node_->GetComponents<Constraint>(constraints);
  864. for (PODVector<Constraint*>::Iterator i = constraints.Begin(); i != constraints.End(); ++i)
  865. (*i)->CreateConstraint();
  866. }
  867. UpdateMass();
  868. UpdateGravity();
  869. int flags = body_->getCollisionFlags();
  870. if (trigger_)
  871. flags |= btCollisionObject::CF_NO_CONTACT_RESPONSE;
  872. else
  873. flags &= ~btCollisionObject::CF_NO_CONTACT_RESPONSE;
  874. if (kinematic_)
  875. flags |= btCollisionObject::CF_KINEMATIC_OBJECT;
  876. else
  877. flags &= ~btCollisionObject::CF_KINEMATIC_OBJECT;
  878. body_->setCollisionFlags(flags);
  879. body_->forceActivationState(kinematic_ ? DISABLE_DEACTIVATION : ISLAND_SLEEPING);
  880. if (!IsEnabledEffective())
  881. return;
  882. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  883. world->addRigidBody(body_, (short)collisionLayer_, (short)collisionMask_);
  884. inWorld_ = true;
  885. readdBody_ = false;
  886. hasSimulated_ = false;
  887. if (mass_ > 0.0f)
  888. Activate();
  889. else
  890. {
  891. SetLinearVelocity(Vector3::ZERO);
  892. SetAngularVelocity(Vector3::ZERO);
  893. }
  894. }
  895. void RigidBody::RemoveBodyFromWorld()
  896. {
  897. if (physicsWorld_ && body_ && inWorld_)
  898. {
  899. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  900. world->removeRigidBody(body_);
  901. inWorld_ = false;
  902. }
  903. }
  904. void RigidBody::HandleTargetPosition(StringHash eventType, VariantMap& eventData)
  905. {
  906. // Copy the smoothing target position to the rigid body
  907. if (!physicsWorld_ || !physicsWorld_->IsApplyingTransforms())
  908. SetPosition(static_cast<SmoothedTransform*>(GetEventSender())->GetTargetWorldPosition());
  909. }
  910. void RigidBody::HandleTargetRotation(StringHash eventType, VariantMap& eventData)
  911. {
  912. // Copy the smoothing target rotation to the rigid body
  913. if (!physicsWorld_ || !physicsWorld_->IsApplyingTransforms())
  914. SetRotation(static_cast<SmoothedTransform*>(GetEventSender())->GetTargetWorldRotation());
  915. }
  916. }