2
0

RigidBody.cpp 32 KB

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