RigidBody.cpp 28 KB

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