RigidBody.cpp 33 KB

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