RigidBody.cpp 33 KB

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