RigidBody.cpp 32 KB

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