btRigidBody.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library
  3. Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
  4. This software is provided 'as-is', without any express or implied warranty.
  5. In no event will the authors be held liable for any damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it freely,
  8. subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  10. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  11. 3. This notice may not be removed or altered from any source distribution.
  12. */
  13. #ifndef BT_RIGIDBODY_H
  14. #define BT_RIGIDBODY_H
  15. #include "bullet/LinearMath/btAlignedObjectArray.h"
  16. #include "bullet/LinearMath/btTransform.h"
  17. #include "bullet/BulletCollision//BroadphaseCollision/btBroadphaseProxy.h"
  18. #include "bullet/BulletCollision//CollisionDispatch/btCollisionObject.h"
  19. class btCollisionShape;
  20. class btMotionState;
  21. class btTypedConstraint;
  22. extern btScalar gDeactivationTime;
  23. extern bool gDisableDeactivation;
  24. #ifdef BT_USE_DOUBLE_PRECISION
  25. #define btRigidBodyData btRigidBodyDoubleData
  26. #define btRigidBodyDataName "btRigidBodyDoubleData"
  27. #else
  28. #define btRigidBodyData btRigidBodyFloatData
  29. #define btRigidBodyDataName "btRigidBodyFloatData"
  30. #endif //BT_USE_DOUBLE_PRECISION
  31. enum btRigidBodyFlags
  32. {
  33. BT_DISABLE_WORLD_GRAVITY = 1,
  34. ///The BT_ENABLE_GYROPSCOPIC_FORCE can easily introduce instability
  35. ///So generally it is best to not enable it.
  36. ///If really needed, run at a high frequency like 1000 Hertz: ///See Demos/GyroscopicDemo for an example use
  37. BT_ENABLE_GYROPSCOPIC_FORCE = 2
  38. };
  39. ///The btRigidBody is the main class for rigid body objects. It is derived from btCollisionObject, so it keeps a pointer to a btCollisionShape.
  40. ///It is recommended for performance and memory use to share btCollisionShape objects whenever possible.
  41. ///There are 3 types of rigid bodies:
  42. ///- A) Dynamic rigid bodies, with positive mass. Motion is controlled by rigid body dynamics.
  43. ///- B) Fixed objects with zero mass. They are not moving (basically collision objects)
  44. ///- C) Kinematic objects, which are objects without mass, but the user can move them. There is on-way interaction, and Bullet calculates a velocity based on the timestep and previous and current world transform.
  45. ///Bullet automatically deactivates dynamic rigid bodies, when the velocity is below a threshold for a given time.
  46. ///Deactivated (sleeping) rigid bodies don't take any processing time, except a minor broadphase collision detection impact (to allow active objects to activate/wake up sleeping objects)
  47. class btRigidBody : public btCollisionObject
  48. {
  49. btMatrix3x3 m_invInertiaTensorWorld;
  50. btVector3 m_linearVelocity;
  51. btVector3 m_angularVelocity;
  52. btScalar m_inverseMass;
  53. btVector3 m_linearFactor;
  54. btVector3 m_gravity;
  55. btVector3 m_gravity_acceleration;
  56. btVector3 m_invInertiaLocal;
  57. btVector3 m_totalForce;
  58. btVector3 m_totalTorque;
  59. btScalar m_linearDamping;
  60. btScalar m_angularDamping;
  61. bool m_additionalDamping;
  62. btScalar m_additionalDampingFactor;
  63. btScalar m_additionalLinearDampingThresholdSqr;
  64. btScalar m_additionalAngularDampingThresholdSqr;
  65. btScalar m_additionalAngularDampingFactor;
  66. btScalar m_linearSleepingThreshold;
  67. btScalar m_angularSleepingThreshold;
  68. //m_optionalMotionState allows to automatic synchronize the world transform for active objects
  69. btMotionState* m_optionalMotionState;
  70. //keep track of typed constraints referencing this rigid body
  71. btAlignedObjectArray<btTypedConstraint*> m_constraintRefs;
  72. int m_rigidbodyFlags;
  73. int m_debugBodyId;
  74. protected:
  75. ATTRIBUTE_ALIGNED16(btVector3 m_deltaLinearVelocity);
  76. btVector3 m_deltaAngularVelocity;
  77. btVector3 m_angularFactor;
  78. btVector3 m_invMass;
  79. btVector3 m_pushVelocity;
  80. btVector3 m_turnVelocity;
  81. public:
  82. ///The btRigidBodyConstructionInfo structure provides information to create a rigid body. Setting mass to zero creates a fixed (non-dynamic) rigid body.
  83. ///For dynamic objects, you can use the collision shape to approximate the local inertia tensor, otherwise use the zero vector (default argument)
  84. ///You can use the motion state to synchronize the world transform between physics and graphics objects.
  85. ///And if the motion state is provided, the rigid body will initialize its initial world transform from the motion state,
  86. ///m_startWorldTransform is only used when you don't provide a motion state.
  87. struct btRigidBodyConstructionInfo
  88. {
  89. btScalar m_mass;
  90. ///When a motionState is provided, the rigid body will initialize its world transform from the motion state
  91. ///In this case, m_startWorldTransform is ignored.
  92. btMotionState* m_motionState;
  93. btTransform m_startWorldTransform;
  94. btCollisionShape* m_collisionShape;
  95. btVector3 m_localInertia;
  96. btScalar m_linearDamping;
  97. btScalar m_angularDamping;
  98. ///best simulation results when friction is non-zero
  99. btScalar m_friction;
  100. ///the m_rollingFriction prevents rounded shapes, such as spheres, cylinders and capsules from rolling forever.
  101. ///See Bullet/Demos/RollingFrictionDemo for usage
  102. btScalar m_rollingFriction;
  103. ///best simulation results using zero restitution.
  104. btScalar m_restitution;
  105. btScalar m_linearSleepingThreshold;
  106. btScalar m_angularSleepingThreshold;
  107. //Additional damping can help avoiding lowpass jitter motion, help stability for ragdolls etc.
  108. //Such damping is undesirable, so once the overall simulation quality of the rigid body dynamics system has improved, this should become obsolete
  109. bool m_additionalDamping;
  110. btScalar m_additionalDampingFactor;
  111. btScalar m_additionalLinearDampingThresholdSqr;
  112. btScalar m_additionalAngularDampingThresholdSqr;
  113. btScalar m_additionalAngularDampingFactor;
  114. btRigidBodyConstructionInfo( btScalar mass, btMotionState* motionState, btCollisionShape* collisionShape, const btVector3& localInertia=btVector3(0,0,0)):
  115. m_mass(mass),
  116. m_motionState(motionState),
  117. m_collisionShape(collisionShape),
  118. m_localInertia(localInertia),
  119. m_linearDamping(btScalar(0.)),
  120. m_angularDamping(btScalar(0.)),
  121. m_friction(btScalar(0.5)),
  122. m_rollingFriction(btScalar(0)),
  123. m_restitution(btScalar(0.)),
  124. m_linearSleepingThreshold(btScalar(0.8)),
  125. m_angularSleepingThreshold(btScalar(1.f)),
  126. m_additionalDamping(false),
  127. m_additionalDampingFactor(btScalar(0.005)),
  128. m_additionalLinearDampingThresholdSqr(btScalar(0.01)),
  129. m_additionalAngularDampingThresholdSqr(btScalar(0.01)),
  130. m_additionalAngularDampingFactor(btScalar(0.01))
  131. {
  132. m_startWorldTransform.setIdentity();
  133. }
  134. };
  135. ///btRigidBody constructor using construction info
  136. btRigidBody( const btRigidBodyConstructionInfo& constructionInfo);
  137. ///btRigidBody constructor for backwards compatibility.
  138. ///To specify friction (etc) during rigid body construction, please use the other constructor (using btRigidBodyConstructionInfo)
  139. btRigidBody( btScalar mass, btMotionState* motionState, btCollisionShape* collisionShape, const btVector3& localInertia=btVector3(0,0,0));
  140. virtual ~btRigidBody()
  141. {
  142. //No constraints should point to this rigidbody
  143. //Remove constraints from the dynamics world before you delete the related rigidbodies.
  144. btAssert(m_constraintRefs.size()==0);
  145. }
  146. protected:
  147. ///setupRigidBody is only used internally by the constructor
  148. void setupRigidBody(const btRigidBodyConstructionInfo& constructionInfo);
  149. public:
  150. void proceedToTransform(const btTransform& newTrans);
  151. ///to keep collision detection and dynamics separate we don't store a rigidbody pointer
  152. ///but a rigidbody is derived from btCollisionObject, so we can safely perform an upcast
  153. static const btRigidBody* upcast(const btCollisionObject* colObj)
  154. {
  155. if (colObj->getInternalType()&btCollisionObject::CO_RIGID_BODY)
  156. return (const btRigidBody*)colObj;
  157. return 0;
  158. }
  159. static btRigidBody* upcast(btCollisionObject* colObj)
  160. {
  161. if (colObj->getInternalType()&btCollisionObject::CO_RIGID_BODY)
  162. return (btRigidBody*)colObj;
  163. return 0;
  164. }
  165. /// continuous collision detection needs prediction
  166. void predictIntegratedTransform(btScalar step, btTransform& predictedTransform) ;
  167. void saveKinematicState(btScalar step);
  168. void applyGravity();
  169. void setGravity(const btVector3& acceleration);
  170. const btVector3& getGravity() const
  171. {
  172. return m_gravity_acceleration;
  173. }
  174. void setDamping(btScalar lin_damping, btScalar ang_damping);
  175. btScalar getLinearDamping() const
  176. {
  177. return m_linearDamping;
  178. }
  179. btScalar getAngularDamping() const
  180. {
  181. return m_angularDamping;
  182. }
  183. btScalar getLinearSleepingThreshold() const
  184. {
  185. return m_linearSleepingThreshold;
  186. }
  187. btScalar getAngularSleepingThreshold() const
  188. {
  189. return m_angularSleepingThreshold;
  190. }
  191. void applyDamping(btScalar timeStep);
  192. SIMD_FORCE_INLINE const btCollisionShape* getCollisionShape() const {
  193. return m_collisionShape;
  194. }
  195. SIMD_FORCE_INLINE btCollisionShape* getCollisionShape() {
  196. return m_collisionShape;
  197. }
  198. void setMassProps(btScalar mass, const btVector3& inertia);
  199. const btVector3& getLinearFactor() const
  200. {
  201. return m_linearFactor;
  202. }
  203. void setLinearFactor(const btVector3& linearFactor)
  204. {
  205. m_linearFactor = linearFactor;
  206. m_invMass = m_linearFactor*m_inverseMass;
  207. }
  208. btScalar getInvMass() const { return m_inverseMass; }
  209. const btMatrix3x3& getInvInertiaTensorWorld() const {
  210. return m_invInertiaTensorWorld;
  211. }
  212. void integrateVelocities(btScalar step);
  213. void setCenterOfMassTransform(const btTransform& xform);
  214. void applyCentralForce(const btVector3& force)
  215. {
  216. m_totalForce += force*m_linearFactor;
  217. }
  218. const btVector3& getTotalForce() const
  219. {
  220. return m_totalForce;
  221. };
  222. const btVector3& getTotalTorque() const
  223. {
  224. return m_totalTorque;
  225. };
  226. const btVector3& getInvInertiaDiagLocal() const
  227. {
  228. return m_invInertiaLocal;
  229. };
  230. void setInvInertiaDiagLocal(const btVector3& diagInvInertia)
  231. {
  232. m_invInertiaLocal = diagInvInertia;
  233. }
  234. void setSleepingThresholds(btScalar linear,btScalar angular)
  235. {
  236. m_linearSleepingThreshold = linear;
  237. m_angularSleepingThreshold = angular;
  238. }
  239. void applyTorque(const btVector3& torque)
  240. {
  241. m_totalTorque += torque*m_angularFactor;
  242. }
  243. void applyForce(const btVector3& force, const btVector3& rel_pos)
  244. {
  245. applyCentralForce(force);
  246. applyTorque(rel_pos.cross(force*m_linearFactor));
  247. }
  248. void applyCentralImpulse(const btVector3& impulse)
  249. {
  250. m_linearVelocity += impulse *m_linearFactor * m_inverseMass;
  251. }
  252. void applyTorqueImpulse(const btVector3& torque)
  253. {
  254. m_angularVelocity += m_invInertiaTensorWorld * torque * m_angularFactor;
  255. }
  256. void applyImpulse(const btVector3& impulse, const btVector3& rel_pos)
  257. {
  258. if (m_inverseMass != btScalar(0.))
  259. {
  260. applyCentralImpulse(impulse);
  261. if (m_angularFactor)
  262. {
  263. applyTorqueImpulse(rel_pos.cross(impulse*m_linearFactor));
  264. }
  265. }
  266. }
  267. void clearForces()
  268. {
  269. m_totalForce.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
  270. m_totalTorque.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
  271. }
  272. void updateInertiaTensor();
  273. const btVector3& getCenterOfMassPosition() const {
  274. return m_worldTransform.getOrigin();
  275. }
  276. btQuaternion getOrientation() const;
  277. const btTransform& getCenterOfMassTransform() const {
  278. return m_worldTransform;
  279. }
  280. const btVector3& getLinearVelocity() const {
  281. return m_linearVelocity;
  282. }
  283. const btVector3& getAngularVelocity() const {
  284. return m_angularVelocity;
  285. }
  286. inline void setLinearVelocity(const btVector3& lin_vel)
  287. {
  288. m_updateRevision++;
  289. m_linearVelocity = lin_vel;
  290. }
  291. inline void setAngularVelocity(const btVector3& ang_vel)
  292. {
  293. m_updateRevision++;
  294. m_angularVelocity = ang_vel;
  295. }
  296. btVector3 getVelocityInLocalPoint(const btVector3& rel_pos) const
  297. {
  298. //we also calculate lin/ang velocity for kinematic objects
  299. return m_linearVelocity + m_angularVelocity.cross(rel_pos);
  300. //for kinematic objects, we could also use use:
  301. // return (m_worldTransform(rel_pos) - m_interpolationWorldTransform(rel_pos)) / m_kinematicTimeStep;
  302. }
  303. void translate(const btVector3& v)
  304. {
  305. m_worldTransform.getOrigin() += v;
  306. }
  307. void getAabb(btVector3& aabbMin,btVector3& aabbMax) const;
  308. SIMD_FORCE_INLINE btScalar computeImpulseDenominator(const btVector3& pos, const btVector3& normal) const
  309. {
  310. btVector3 r0 = pos - getCenterOfMassPosition();
  311. btVector3 c0 = (r0).cross(normal);
  312. btVector3 vec = (c0 * getInvInertiaTensorWorld()).cross(r0);
  313. return m_inverseMass + normal.dot(vec);
  314. }
  315. SIMD_FORCE_INLINE btScalar computeAngularImpulseDenominator(const btVector3& axis) const
  316. {
  317. btVector3 vec = axis * getInvInertiaTensorWorld();
  318. return axis.dot(vec);
  319. }
  320. SIMD_FORCE_INLINE void updateDeactivation(btScalar timeStep)
  321. {
  322. if ( (getActivationState() == ISLAND_SLEEPING) || (getActivationState() == DISABLE_DEACTIVATION))
  323. return;
  324. if ((getLinearVelocity().length2() < m_linearSleepingThreshold*m_linearSleepingThreshold) &&
  325. (getAngularVelocity().length2() < m_angularSleepingThreshold*m_angularSleepingThreshold))
  326. {
  327. m_deactivationTime += timeStep;
  328. } else
  329. {
  330. m_deactivationTime=btScalar(0.);
  331. setActivationState(0);
  332. }
  333. }
  334. SIMD_FORCE_INLINE bool wantsSleeping()
  335. {
  336. if (getActivationState() == DISABLE_DEACTIVATION)
  337. return false;
  338. //disable deactivation
  339. if (gDisableDeactivation || (gDeactivationTime == btScalar(0.)))
  340. return false;
  341. if ( (getActivationState() == ISLAND_SLEEPING) || (getActivationState() == WANTS_DEACTIVATION))
  342. return true;
  343. if (m_deactivationTime> gDeactivationTime)
  344. {
  345. return true;
  346. }
  347. return false;
  348. }
  349. const btBroadphaseProxy* getBroadphaseProxy() const
  350. {
  351. return m_broadphaseHandle;
  352. }
  353. btBroadphaseProxy* getBroadphaseProxy()
  354. {
  355. return m_broadphaseHandle;
  356. }
  357. void setNewBroadphaseProxy(btBroadphaseProxy* broadphaseProxy)
  358. {
  359. m_broadphaseHandle = broadphaseProxy;
  360. }
  361. //btMotionState allows to automatic synchronize the world transform for active objects
  362. btMotionState* getMotionState()
  363. {
  364. return m_optionalMotionState;
  365. }
  366. const btMotionState* getMotionState() const
  367. {
  368. return m_optionalMotionState;
  369. }
  370. void setMotionState(btMotionState* motionState)
  371. {
  372. m_optionalMotionState = motionState;
  373. if (m_optionalMotionState)
  374. motionState->getWorldTransform(m_worldTransform);
  375. }
  376. //for experimental overriding of friction/contact solver func
  377. int m_contactSolverType;
  378. int m_frictionSolverType;
  379. void setAngularFactor(const btVector3& angFac)
  380. {
  381. m_updateRevision++;
  382. m_angularFactor = angFac;
  383. }
  384. void setAngularFactor(btScalar angFac)
  385. {
  386. m_updateRevision++;
  387. m_angularFactor.setValue(angFac,angFac,angFac);
  388. }
  389. const btVector3& getAngularFactor() const
  390. {
  391. return m_angularFactor;
  392. }
  393. //is this rigidbody added to a btCollisionWorld/btDynamicsWorld/btBroadphase?
  394. bool isInWorld() const
  395. {
  396. return (getBroadphaseProxy() != 0);
  397. }
  398. virtual bool checkCollideWithOverride(const btCollisionObject* co) const;
  399. void addConstraintRef(btTypedConstraint* c);
  400. void removeConstraintRef(btTypedConstraint* c);
  401. btTypedConstraint* getConstraintRef(int index)
  402. {
  403. return m_constraintRefs[index];
  404. }
  405. int getNumConstraintRefs() const
  406. {
  407. return m_constraintRefs.size();
  408. }
  409. void setFlags(int flags)
  410. {
  411. m_rigidbodyFlags = flags;
  412. }
  413. int getFlags() const
  414. {
  415. return m_rigidbodyFlags;
  416. }
  417. btVector3 computeGyroscopicForce(btScalar maxGyroscopicForce) const;
  418. ///////////////////////////////////////////////
  419. virtual int calculateSerializeBufferSize() const;
  420. ///fills the dataBuffer and returns the struct name (and 0 on failure)
  421. virtual const char* serialize(void* dataBuffer, class btSerializer* serializer) const;
  422. virtual void serializeSingleObject(class btSerializer* serializer) const;
  423. };
  424. //@todo add m_optionalMotionState and m_constraintRefs to btRigidBodyData
  425. ///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
  426. struct btRigidBodyFloatData
  427. {
  428. btCollisionObjectFloatData m_collisionObjectData;
  429. btMatrix3x3FloatData m_invInertiaTensorWorld;
  430. btVector3FloatData m_linearVelocity;
  431. btVector3FloatData m_angularVelocity;
  432. btVector3FloatData m_angularFactor;
  433. btVector3FloatData m_linearFactor;
  434. btVector3FloatData m_gravity;
  435. btVector3FloatData m_gravity_acceleration;
  436. btVector3FloatData m_invInertiaLocal;
  437. btVector3FloatData m_totalForce;
  438. btVector3FloatData m_totalTorque;
  439. float m_inverseMass;
  440. float m_linearDamping;
  441. float m_angularDamping;
  442. float m_additionalDampingFactor;
  443. float m_additionalLinearDampingThresholdSqr;
  444. float m_additionalAngularDampingThresholdSqr;
  445. float m_additionalAngularDampingFactor;
  446. float m_linearSleepingThreshold;
  447. float m_angularSleepingThreshold;
  448. int m_additionalDamping;
  449. };
  450. ///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
  451. struct btRigidBodyDoubleData
  452. {
  453. btCollisionObjectDoubleData m_collisionObjectData;
  454. btMatrix3x3DoubleData m_invInertiaTensorWorld;
  455. btVector3DoubleData m_linearVelocity;
  456. btVector3DoubleData m_angularVelocity;
  457. btVector3DoubleData m_angularFactor;
  458. btVector3DoubleData m_linearFactor;
  459. btVector3DoubleData m_gravity;
  460. btVector3DoubleData m_gravity_acceleration;
  461. btVector3DoubleData m_invInertiaLocal;
  462. btVector3DoubleData m_totalForce;
  463. btVector3DoubleData m_totalTorque;
  464. double m_inverseMass;
  465. double m_linearDamping;
  466. double m_angularDamping;
  467. double m_additionalDampingFactor;
  468. double m_additionalLinearDampingThresholdSqr;
  469. double m_additionalAngularDampingThresholdSqr;
  470. double m_additionalAngularDampingFactor;
  471. double m_linearSleepingThreshold;
  472. double m_angularSleepingThreshold;
  473. int m_additionalDamping;
  474. char m_padding[4];
  475. };
  476. #endif //BT_RIGIDBODY_H