RigidBody.cpp 32 KB

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