RigidBody.cpp 32 KB

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