RigidBody.cpp 33 KB

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