RigidBody.cpp 32 KB

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