RigidBody.cpp 28 KB

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