RigidBody.cpp 33 KB

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