RigidBody.cpp 33 KB

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