btRigidBody.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. #include "btRigidBody.h"
  14. #include "BulletCollision/CollisionShapes/btConvexShape.h"
  15. #include "LinearMath/btMinMax.h"
  16. #include "LinearMath/btTransformUtil.h"
  17. #include "LinearMath/btMotionState.h"
  18. #include "BulletDynamics/ConstraintSolver/btTypedConstraint.h"
  19. #include "LinearMath/btSerializer.h"
  20. //'temporarily' global variables
  21. btScalar gDeactivationTime = btScalar(2.);
  22. bool gDisableDeactivation = false;
  23. static int uniqueId = 0;
  24. btRigidBody::btRigidBody(const btRigidBody::btRigidBodyConstructionInfo& constructionInfo)
  25. {
  26. setupRigidBody(constructionInfo);
  27. }
  28. btRigidBody::btRigidBody(btScalar mass, btMotionState* motionState, btCollisionShape* collisionShape, const btVector3& localInertia)
  29. {
  30. btRigidBodyConstructionInfo cinfo(mass, motionState, collisionShape, localInertia);
  31. setupRigidBody(cinfo);
  32. }
  33. void btRigidBody::setupRigidBody(const btRigidBody::btRigidBodyConstructionInfo& constructionInfo)
  34. {
  35. m_internalType = CO_RIGID_BODY;
  36. m_linearVelocity.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
  37. m_angularVelocity.setValue(btScalar(0.), btScalar(0.), btScalar(0.));
  38. m_angularFactor.setValue(1, 1, 1);
  39. m_linearFactor.setValue(1, 1, 1);
  40. m_gravity.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
  41. m_gravity_acceleration.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
  42. m_totalForce.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
  43. m_totalTorque.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0)),
  44. setDamping(constructionInfo.m_linearDamping, constructionInfo.m_angularDamping);
  45. m_linearSleepingThreshold = constructionInfo.m_linearSleepingThreshold;
  46. m_angularSleepingThreshold = constructionInfo.m_angularSleepingThreshold;
  47. m_optionalMotionState = constructionInfo.m_motionState;
  48. m_contactSolverType = 0;
  49. m_frictionSolverType = 0;
  50. m_additionalDamping = constructionInfo.m_additionalDamping;
  51. m_additionalDampingFactor = constructionInfo.m_additionalDampingFactor;
  52. m_additionalLinearDampingThresholdSqr = constructionInfo.m_additionalLinearDampingThresholdSqr;
  53. m_additionalAngularDampingThresholdSqr = constructionInfo.m_additionalAngularDampingThresholdSqr;
  54. m_additionalAngularDampingFactor = constructionInfo.m_additionalAngularDampingFactor;
  55. if (m_optionalMotionState)
  56. {
  57. m_optionalMotionState->getWorldTransform(m_worldTransform);
  58. }
  59. else
  60. {
  61. m_worldTransform = constructionInfo.m_startWorldTransform;
  62. }
  63. m_interpolationWorldTransform = m_worldTransform;
  64. m_interpolationLinearVelocity.setValue(0, 0, 0);
  65. m_interpolationAngularVelocity.setValue(0, 0, 0);
  66. //moved to btCollisionObject
  67. m_friction = constructionInfo.m_friction;
  68. m_rollingFriction = constructionInfo.m_rollingFriction;
  69. m_spinningFriction = constructionInfo.m_spinningFriction;
  70. m_restitution = constructionInfo.m_restitution;
  71. setCollisionShape(constructionInfo.m_collisionShape);
  72. m_debugBodyId = uniqueId++;
  73. setMassProps(constructionInfo.m_mass, constructionInfo.m_localInertia);
  74. updateInertiaTensor();
  75. m_rigidbodyFlags = BT_ENABLE_GYROSCOPIC_FORCE_IMPLICIT_BODY;
  76. m_deltaLinearVelocity.setZero();
  77. m_deltaAngularVelocity.setZero();
  78. m_invMass = m_inverseMass * m_linearFactor;
  79. m_pushVelocity.setZero();
  80. m_turnVelocity.setZero();
  81. }
  82. void btRigidBody::predictIntegratedTransform(btScalar timeStep, btTransform& predictedTransform)
  83. {
  84. btTransformUtil::integrateTransform(m_worldTransform, m_linearVelocity, m_angularVelocity, timeStep, predictedTransform);
  85. }
  86. void btRigidBody::saveKinematicState(btScalar timeStep)
  87. {
  88. //todo: clamp to some (user definable) safe minimum timestep, to limit maximum angular/linear velocities
  89. if (timeStep != btScalar(0.))
  90. {
  91. //if we use motionstate to synchronize world transforms, get the new kinematic/animated world transform
  92. if (getMotionState())
  93. getMotionState()->getWorldTransform(m_worldTransform);
  94. btVector3 linVel, angVel;
  95. btTransformUtil::calculateVelocity(m_interpolationWorldTransform, m_worldTransform, timeStep, m_linearVelocity, m_angularVelocity);
  96. m_interpolationLinearVelocity = m_linearVelocity;
  97. m_interpolationAngularVelocity = m_angularVelocity;
  98. m_interpolationWorldTransform = m_worldTransform;
  99. //printf("angular = %f %f %f\n",m_angularVelocity.getX(),m_angularVelocity.getY(),m_angularVelocity.getZ());
  100. }
  101. }
  102. void btRigidBody::getAabb(btVector3& aabbMin, btVector3& aabbMax) const
  103. {
  104. getCollisionShape()->getAabb(m_worldTransform, aabbMin, aabbMax);
  105. }
  106. void btRigidBody::setGravity(const btVector3& acceleration)
  107. {
  108. if (m_inverseMass != btScalar(0.0))
  109. {
  110. m_gravity = acceleration * (btScalar(1.0) / m_inverseMass);
  111. }
  112. m_gravity_acceleration = acceleration;
  113. }
  114. void btRigidBody::setDamping(btScalar lin_damping, btScalar ang_damping)
  115. {
  116. #ifdef BT_USE_OLD_DAMPING_METHOD
  117. m_linearDamping = btMax(lin_damping, btScalar(0.0));
  118. m_angularDamping = btMax(ang_damping, btScalar(0.0));
  119. #else
  120. m_linearDamping = btClamped(lin_damping, btScalar(0.0), btScalar(1.0));
  121. m_angularDamping = btClamped(ang_damping, btScalar(0.0), btScalar(1.0));
  122. #endif
  123. }
  124. ///applyDamping damps the velocity, using the given m_linearDamping and m_angularDamping
  125. void btRigidBody::applyDamping(btScalar timeStep)
  126. {
  127. //On new damping: see discussion/issue report here: http://code.google.com/p/bullet/issues/detail?id=74
  128. //todo: do some performance comparisons (but other parts of the engine are probably bottleneck anyway
  129. #ifdef BT_USE_OLD_DAMPING_METHOD
  130. m_linearVelocity *= btMax((btScalar(1.0) - timeStep * m_linearDamping), btScalar(0.0));
  131. m_angularVelocity *= btMax((btScalar(1.0) - timeStep * m_angularDamping), btScalar(0.0));
  132. #else
  133. m_linearVelocity *= btPow(btScalar(1) - m_linearDamping, timeStep);
  134. m_angularVelocity *= btPow(btScalar(1) - m_angularDamping, timeStep);
  135. #endif
  136. if (m_additionalDamping)
  137. {
  138. //Additional damping can help avoiding lowpass jitter motion, help stability for ragdolls etc.
  139. //Such damping is undesirable, so once the overall simulation quality of the rigid body dynamics system has improved, this should become obsolete
  140. if ((m_angularVelocity.length2() < m_additionalAngularDampingThresholdSqr) &&
  141. (m_linearVelocity.length2() < m_additionalLinearDampingThresholdSqr))
  142. {
  143. m_angularVelocity *= m_additionalDampingFactor;
  144. m_linearVelocity *= m_additionalDampingFactor;
  145. }
  146. btScalar speed = m_linearVelocity.length();
  147. if (speed < m_linearDamping)
  148. {
  149. btScalar dampVel = btScalar(0.005);
  150. if (speed > dampVel)
  151. {
  152. btVector3 dir = m_linearVelocity.normalized();
  153. m_linearVelocity -= dir * dampVel;
  154. }
  155. else
  156. {
  157. m_linearVelocity.setValue(btScalar(0.), btScalar(0.), btScalar(0.));
  158. }
  159. }
  160. btScalar angSpeed = m_angularVelocity.length();
  161. if (angSpeed < m_angularDamping)
  162. {
  163. btScalar angDampVel = btScalar(0.005);
  164. if (angSpeed > angDampVel)
  165. {
  166. btVector3 dir = m_angularVelocity.normalized();
  167. m_angularVelocity -= dir * angDampVel;
  168. }
  169. else
  170. {
  171. m_angularVelocity.setValue(btScalar(0.), btScalar(0.), btScalar(0.));
  172. }
  173. }
  174. }
  175. }
  176. void btRigidBody::applyGravity()
  177. {
  178. if (isStaticOrKinematicObject())
  179. return;
  180. applyCentralForce(m_gravity);
  181. }
  182. void btRigidBody::clearGravity()
  183. {
  184. if (isStaticOrKinematicObject())
  185. return;
  186. applyCentralForce(-m_gravity);
  187. }
  188. void btRigidBody::proceedToTransform(const btTransform& newTrans)
  189. {
  190. setCenterOfMassTransform(newTrans);
  191. }
  192. void btRigidBody::setMassProps(btScalar mass, const btVector3& inertia)
  193. {
  194. if (mass == btScalar(0.))
  195. {
  196. m_collisionFlags |= btCollisionObject::CF_STATIC_OBJECT;
  197. m_inverseMass = btScalar(0.);
  198. }
  199. else
  200. {
  201. m_collisionFlags &= (~btCollisionObject::CF_STATIC_OBJECT);
  202. m_inverseMass = btScalar(1.0) / mass;
  203. }
  204. //Fg = m * a
  205. m_gravity = mass * m_gravity_acceleration;
  206. m_invInertiaLocal.setValue(inertia.x() != btScalar(0.0) ? btScalar(1.0) / inertia.x() : btScalar(0.0),
  207. inertia.y() != btScalar(0.0) ? btScalar(1.0) / inertia.y() : btScalar(0.0),
  208. inertia.z() != btScalar(0.0) ? btScalar(1.0) / inertia.z() : btScalar(0.0));
  209. m_invMass = m_linearFactor * m_inverseMass;
  210. }
  211. void btRigidBody::updateInertiaTensor()
  212. {
  213. m_invInertiaTensorWorld = m_worldTransform.getBasis().scaled(m_invInertiaLocal) * m_worldTransform.getBasis().transpose();
  214. }
  215. btVector3 btRigidBody::getLocalInertia() const
  216. {
  217. btVector3 inertiaLocal;
  218. const btVector3 inertia = m_invInertiaLocal;
  219. inertiaLocal.setValue(inertia.x() != btScalar(0.0) ? btScalar(1.0) / inertia.x() : btScalar(0.0),
  220. inertia.y() != btScalar(0.0) ? btScalar(1.0) / inertia.y() : btScalar(0.0),
  221. inertia.z() != btScalar(0.0) ? btScalar(1.0) / inertia.z() : btScalar(0.0));
  222. return inertiaLocal;
  223. }
  224. inline btVector3 evalEulerEqn(const btVector3& w1, const btVector3& w0, const btVector3& T, const btScalar dt,
  225. const btMatrix3x3& I)
  226. {
  227. const btVector3 w2 = I * w1 + w1.cross(I * w1) * dt - (T * dt + I * w0);
  228. return w2;
  229. }
  230. inline btMatrix3x3 evalEulerEqnDeriv(const btVector3& w1, const btVector3& w0, const btScalar dt,
  231. const btMatrix3x3& I)
  232. {
  233. btMatrix3x3 w1x, Iw1x;
  234. const btVector3 Iwi = (I * w1);
  235. w1.getSkewSymmetricMatrix(&w1x[0], &w1x[1], &w1x[2]);
  236. Iwi.getSkewSymmetricMatrix(&Iw1x[0], &Iw1x[1], &Iw1x[2]);
  237. const btMatrix3x3 dfw1 = I + (w1x * I - Iw1x) * dt;
  238. return dfw1;
  239. }
  240. btVector3 btRigidBody::computeGyroscopicForceExplicit(btScalar maxGyroscopicForce) const
  241. {
  242. btVector3 inertiaLocal = getLocalInertia();
  243. btMatrix3x3 inertiaTensorWorld = getWorldTransform().getBasis().scaled(inertiaLocal) * getWorldTransform().getBasis().transpose();
  244. btVector3 tmp = inertiaTensorWorld * getAngularVelocity();
  245. btVector3 gf = getAngularVelocity().cross(tmp);
  246. btScalar l2 = gf.length2();
  247. if (l2 > maxGyroscopicForce * maxGyroscopicForce)
  248. {
  249. gf *= btScalar(1.) / btSqrt(l2) * maxGyroscopicForce;
  250. }
  251. return gf;
  252. }
  253. btVector3 btRigidBody::computeGyroscopicImpulseImplicit_Body(btScalar step) const
  254. {
  255. btVector3 idl = getLocalInertia();
  256. btVector3 omega1 = getAngularVelocity();
  257. btQuaternion q = getWorldTransform().getRotation();
  258. // Convert to body coordinates
  259. btVector3 omegab = quatRotate(q.inverse(), omega1);
  260. btMatrix3x3 Ib;
  261. Ib.setValue(idl.x(), 0, 0,
  262. 0, idl.y(), 0,
  263. 0, 0, idl.z());
  264. btVector3 ibo = Ib * omegab;
  265. // Residual vector
  266. btVector3 f = step * omegab.cross(ibo);
  267. btMatrix3x3 skew0;
  268. omegab.getSkewSymmetricMatrix(&skew0[0], &skew0[1], &skew0[2]);
  269. btVector3 om = Ib * omegab;
  270. btMatrix3x3 skew1;
  271. om.getSkewSymmetricMatrix(&skew1[0], &skew1[1], &skew1[2]);
  272. // Jacobian
  273. btMatrix3x3 J = Ib + (skew0 * Ib - skew1) * step;
  274. // btMatrix3x3 Jinv = J.inverse();
  275. // btVector3 omega_div = Jinv*f;
  276. btVector3 omega_div = J.solve33(f);
  277. // Single Newton-Raphson update
  278. omegab = omegab - omega_div; //Solve33(J, f);
  279. // Back to world coordinates
  280. btVector3 omega2 = quatRotate(q, omegab);
  281. btVector3 gf = omega2 - omega1;
  282. return gf;
  283. }
  284. btVector3 btRigidBody::computeGyroscopicImpulseImplicit_World(btScalar step) const
  285. {
  286. // use full newton-euler equations. common practice to drop the wxIw term. want it for better tumbling behavior.
  287. // calculate using implicit euler step so it's stable.
  288. const btVector3 inertiaLocal = getLocalInertia();
  289. const btVector3 w0 = getAngularVelocity();
  290. btMatrix3x3 I;
  291. I = m_worldTransform.getBasis().scaled(inertiaLocal) *
  292. m_worldTransform.getBasis().transpose();
  293. // use newtons method to find implicit solution for new angular velocity (w')
  294. // f(w') = -(T*step + Iw) + Iw' + w' + w'xIw'*step = 0
  295. // df/dw' = I + 1xIw'*step + w'xI*step
  296. btVector3 w1 = w0;
  297. // one step of newton's method
  298. {
  299. const btVector3 fw = evalEulerEqn(w1, w0, btVector3(0, 0, 0), step, I);
  300. const btMatrix3x3 dfw = evalEulerEqnDeriv(w1, w0, step, I);
  301. btVector3 dw;
  302. dw = dfw.solve33(fw);
  303. //const btMatrix3x3 dfw_inv = dfw.inverse();
  304. //dw = dfw_inv*fw;
  305. w1 -= dw;
  306. }
  307. btVector3 gf = (w1 - w0);
  308. return gf;
  309. }
  310. void btRigidBody::integrateVelocities(btScalar step)
  311. {
  312. if (isStaticOrKinematicObject())
  313. return;
  314. m_linearVelocity += m_totalForce * (m_inverseMass * step);
  315. m_angularVelocity += m_invInertiaTensorWorld * m_totalTorque * step;
  316. #define MAX_ANGVEL SIMD_HALF_PI
  317. /// clamp angular velocity. collision calculations will fail on higher angular velocities
  318. btScalar angvel = m_angularVelocity.length();
  319. if (angvel * step > MAX_ANGVEL)
  320. {
  321. m_angularVelocity *= (MAX_ANGVEL / step) / angvel;
  322. }
  323. #if defined(BT_CLAMP_VELOCITY_TO) && BT_CLAMP_VELOCITY_TO > 0
  324. clampVelocity(m_angularVelocity);
  325. #endif
  326. }
  327. btQuaternion btRigidBody::getOrientation() const
  328. {
  329. btQuaternion orn;
  330. m_worldTransform.getBasis().getRotation(orn);
  331. return orn;
  332. }
  333. void btRigidBody::setCenterOfMassTransform(const btTransform& xform)
  334. {
  335. if (isKinematicObject())
  336. {
  337. m_interpolationWorldTransform = m_worldTransform;
  338. }
  339. else
  340. {
  341. m_interpolationWorldTransform = xform;
  342. }
  343. m_interpolationLinearVelocity = getLinearVelocity();
  344. m_interpolationAngularVelocity = getAngularVelocity();
  345. m_worldTransform = xform;
  346. updateInertiaTensor();
  347. }
  348. void btRigidBody::addConstraintRef(btTypedConstraint* c)
  349. {
  350. ///disable collision with the 'other' body
  351. int index = m_constraintRefs.findLinearSearch(c);
  352. //don't add constraints that are already referenced
  353. //btAssert(index == m_constraintRefs.size());
  354. if (index == m_constraintRefs.size())
  355. {
  356. m_constraintRefs.push_back(c);
  357. btCollisionObject* colObjA = &c->getRigidBodyA();
  358. btCollisionObject* colObjB = &c->getRigidBodyB();
  359. if (colObjA == this)
  360. {
  361. colObjA->setIgnoreCollisionCheck(colObjB, true);
  362. }
  363. else
  364. {
  365. colObjB->setIgnoreCollisionCheck(colObjA, true);
  366. }
  367. }
  368. }
  369. void btRigidBody::removeConstraintRef(btTypedConstraint* c)
  370. {
  371. int index = m_constraintRefs.findLinearSearch(c);
  372. //don't remove constraints that are not referenced
  373. if (index < m_constraintRefs.size())
  374. {
  375. m_constraintRefs.remove(c);
  376. btCollisionObject* colObjA = &c->getRigidBodyA();
  377. btCollisionObject* colObjB = &c->getRigidBodyB();
  378. if (colObjA == this)
  379. {
  380. colObjA->setIgnoreCollisionCheck(colObjB, false);
  381. }
  382. else
  383. {
  384. colObjB->setIgnoreCollisionCheck(colObjA, false);
  385. }
  386. }
  387. }
  388. int btRigidBody::calculateSerializeBufferSize() const
  389. {
  390. int sz = sizeof(btRigidBodyData);
  391. return sz;
  392. }
  393. ///fills the dataBuffer and returns the struct name (and 0 on failure)
  394. const char* btRigidBody::serialize(void* dataBuffer, class btSerializer* serializer) const
  395. {
  396. btRigidBodyData* rbd = (btRigidBodyData*)dataBuffer;
  397. btCollisionObject::serialize(&rbd->m_collisionObjectData, serializer);
  398. m_invInertiaTensorWorld.serialize(rbd->m_invInertiaTensorWorld);
  399. m_linearVelocity.serialize(rbd->m_linearVelocity);
  400. m_angularVelocity.serialize(rbd->m_angularVelocity);
  401. rbd->m_inverseMass = m_inverseMass;
  402. m_angularFactor.serialize(rbd->m_angularFactor);
  403. m_linearFactor.serialize(rbd->m_linearFactor);
  404. m_gravity.serialize(rbd->m_gravity);
  405. m_gravity_acceleration.serialize(rbd->m_gravity_acceleration);
  406. m_invInertiaLocal.serialize(rbd->m_invInertiaLocal);
  407. m_totalForce.serialize(rbd->m_totalForce);
  408. m_totalTorque.serialize(rbd->m_totalTorque);
  409. rbd->m_linearDamping = m_linearDamping;
  410. rbd->m_angularDamping = m_angularDamping;
  411. rbd->m_additionalDamping = m_additionalDamping;
  412. rbd->m_additionalDampingFactor = m_additionalDampingFactor;
  413. rbd->m_additionalLinearDampingThresholdSqr = m_additionalLinearDampingThresholdSqr;
  414. rbd->m_additionalAngularDampingThresholdSqr = m_additionalAngularDampingThresholdSqr;
  415. rbd->m_additionalAngularDampingFactor = m_additionalAngularDampingFactor;
  416. rbd->m_linearSleepingThreshold = m_linearSleepingThreshold;
  417. rbd->m_angularSleepingThreshold = m_angularSleepingThreshold;
  418. // Fill padding with zeros to appease msan.
  419. #ifdef BT_USE_DOUBLE_PRECISION
  420. memset(rbd->m_padding, 0, sizeof(rbd->m_padding));
  421. #endif
  422. return btRigidBodyDataName;
  423. }
  424. void btRigidBody::serializeSingleObject(class btSerializer* serializer) const
  425. {
  426. btChunk* chunk = serializer->allocate(calculateSerializeBufferSize(), 1);
  427. const char* structType = serialize(chunk->m_oldPtr, serializer);
  428. serializer->finalizeChunk(chunk, structType, BT_RIGIDBODY_CODE, (void*)this);
  429. }