RigidBody.cpp 33 KB

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