RigidBody.cpp 30 KB

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