e2afb687ac652808c9612898c7cc0a3c6f6e16bb
[blender-staging.git] / extern / bullet2 / src / BulletDynamics / Dynamics / btRigidBody.cpp
1 /*
2 Bullet Continuous Collision Detection and Physics Library
3 Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/
4
5 This software is provided 'as-is', without any express or implied warranty.
6 In no event will the authors be held liable for any damages arising from the use of this software.
7 Permission is granted to anyone to use this software for any purpose, 
8 including commercial applications, and to alter it and redistribute it freely, 
9 subject to the following restrictions:
10
11 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.
12 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
13 3. This notice may not be removed or altered from any source distribution.
14 */
15
16 #include "btRigidBody.h"
17 #include "BulletCollision/CollisionShapes/btConvexShape.h"
18 #include "LinearMath/btMinMax.h"
19 #include "LinearMath/btTransformUtil.h"
20 #include "LinearMath/btMotionState.h"
21 #include "BulletDynamics/ConstraintSolver/btTypedConstraint.h"
22
23 //'temporarily' global variables
24 btScalar        gDeactivationTime = btScalar(2.);
25 bool    gDisableDeactivation = false;
26 static int uniqueId = 0;
27
28
29 btRigidBody::btRigidBody(const btRigidBody::btRigidBodyConstructionInfo& constructionInfo)
30 {
31         setupRigidBody(constructionInfo);
32 }
33
34 btRigidBody::btRigidBody(btScalar mass, btMotionState *motionState, btCollisionShape *collisionShape, const btVector3 &localInertia)
35 {
36         btRigidBodyConstructionInfo cinfo(mass,motionState,collisionShape,localInertia);
37         setupRigidBody(cinfo);
38 }
39
40 void    btRigidBody::setupRigidBody(const btRigidBody::btRigidBodyConstructionInfo& constructionInfo)
41 {
42
43         m_internalType=CO_RIGID_BODY;
44
45         m_linearVelocity.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
46         m_angularVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.));
47         m_angularFactor = btScalar(1.);
48         m_gravity.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
49         m_totalForce.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0));
50         m_totalTorque.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0)),
51         m_linearDamping = btScalar(0.);
52         m_angularDamping = btScalar(0.5);
53         m_linearSleepingThreshold = constructionInfo.m_linearSleepingThreshold;
54         m_angularSleepingThreshold = constructionInfo.m_angularSleepingThreshold;
55         m_optionalMotionState = constructionInfo.m_motionState;
56         m_contactSolverType = 0;
57         m_frictionSolverType = 0;
58         m_additionalDamping = constructionInfo.m_additionalDamping;
59         m_additionalDampingFactor = constructionInfo.m_additionalDampingFactor;
60         m_additionalLinearDampingThresholdSqr = constructionInfo.m_additionalLinearDampingThresholdSqr;
61         m_additionalAngularDampingThresholdSqr = constructionInfo.m_additionalAngularDampingThresholdSqr;
62         m_additionalAngularDampingFactor = constructionInfo.m_additionalAngularDampingFactor;
63
64         if (m_optionalMotionState)
65         {
66                 m_optionalMotionState->getWorldTransform(m_worldTransform);
67         } else
68         {
69                 m_worldTransform = constructionInfo.m_startWorldTransform;
70         }
71
72         m_interpolationWorldTransform = m_worldTransform;
73         m_interpolationLinearVelocity.setValue(0,0,0);
74         m_interpolationAngularVelocity.setValue(0,0,0);
75         
76         //moved to btCollisionObject
77         m_friction = constructionInfo.m_friction;
78         m_restitution = constructionInfo.m_restitution;
79
80         setCollisionShape( constructionInfo.m_collisionShape );
81         m_debugBodyId = uniqueId++;
82         
83         setMassProps(constructionInfo.m_mass, constructionInfo.m_localInertia);
84     setDamping(constructionInfo.m_linearDamping, constructionInfo.m_angularDamping);
85         updateInertiaTensor();
86
87 }
88
89
90 void btRigidBody::predictIntegratedTransform(btScalar timeStep,btTransform& predictedTransform) 
91 {
92         btTransformUtil::integrateTransform(m_worldTransform,m_linearVelocity,m_angularVelocity,timeStep,predictedTransform);
93 }
94
95 void                    btRigidBody::saveKinematicState(btScalar timeStep)
96 {
97         //todo: clamp to some (user definable) safe minimum timestep, to limit maximum angular/linear velocities
98         if (timeStep != btScalar(0.))
99         {
100                 //if we use motionstate to synchronize world transforms, get the new kinematic/animated world transform
101                 if (getMotionState())
102                         getMotionState()->getWorldTransform(m_worldTransform);
103                 btVector3 linVel,angVel;
104                 
105                 btTransformUtil::calculateVelocity(m_interpolationWorldTransform,m_worldTransform,timeStep,m_linearVelocity,m_angularVelocity);
106                 m_interpolationLinearVelocity = m_linearVelocity;
107                 m_interpolationAngularVelocity = m_angularVelocity;
108                 m_interpolationWorldTransform = m_worldTransform;
109                 //printf("angular = %f %f %f\n",m_angularVelocity.getX(),m_angularVelocity.getY(),m_angularVelocity.getZ());
110         }
111 }
112         
113 void    btRigidBody::getAabb(btVector3& aabbMin,btVector3& aabbMax) const
114 {
115         getCollisionShape()->getAabb(m_worldTransform,aabbMin,aabbMax);
116 }
117
118
119
120
121 void btRigidBody::setGravity(const btVector3& acceleration) 
122 {
123         if (m_inverseMass != btScalar(0.0))
124         {
125                 m_gravity = acceleration * (btScalar(1.0) / m_inverseMass);
126         }
127 }
128
129
130
131
132
133
134 void btRigidBody::setDamping(btScalar lin_damping, btScalar ang_damping)
135 {
136         m_linearDamping = GEN_clamped(lin_damping, (btScalar)btScalar(0.0), (btScalar)btScalar(1.0));
137         m_angularDamping = GEN_clamped(ang_damping, (btScalar)btScalar(0.0), (btScalar)btScalar(1.0));
138 }
139
140
141
142
143 ///applyDamping damps the velocity, using the given m_linearDamping and m_angularDamping
144 void                    btRigidBody::applyDamping(btScalar timeStep)
145 {
146         m_linearVelocity *= GEN_clamped((btScalar(1.) - timeStep * m_linearDamping), (btScalar)btScalar(0.0), (btScalar)btScalar(1.0));
147         m_angularVelocity *= GEN_clamped((btScalar(1.) - timeStep * m_angularDamping), (btScalar)btScalar(0.0), (btScalar)btScalar(1.0));
148
149         if (m_additionalDamping)
150         {
151                 //Additional damping can help avoiding lowpass jitter motion, help stability for ragdolls etc.
152                 //Such damping is undesirable, so once the overall simulation quality of the rigid body dynamics system has improved, this should become obsolete
153                 if ((m_angularVelocity.length2() < m_additionalAngularDampingThresholdSqr) &&
154                         (m_linearVelocity.length2() < m_additionalLinearDampingThresholdSqr))
155                 {
156                         m_angularVelocity *= m_additionalDampingFactor;
157                         m_linearVelocity *= m_additionalDampingFactor;
158                 }
159         
160
161                 btScalar speed = m_linearVelocity.length();
162                 if (speed < m_linearDamping)
163                 {
164                         btScalar dampVel = btScalar(0.005);
165                         if (speed > dampVel)
166                         {
167                                 btVector3 dir = m_linearVelocity.normalized();
168                                 m_linearVelocity -=  dir * dampVel;
169                         } else
170                         {
171                                 m_linearVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.));
172                         }
173                 }
174
175                 btScalar angSpeed = m_angularVelocity.length();
176                 if (angSpeed < m_angularDamping)
177                 {
178                         btScalar angDampVel = btScalar(0.005);
179                         if (angSpeed > angDampVel)
180                         {
181                                 btVector3 dir = m_angularVelocity.normalized();
182                                 m_angularVelocity -=  dir * angDampVel;
183                         } else
184                         {
185                                 m_angularVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.));
186                         }
187                 }
188         }
189 }
190
191
192 void btRigidBody::applyGravity()
193 {
194         if (isStaticOrKinematicObject())
195                 return;
196         
197         applyCentralForce(m_gravity);   
198
199 }
200
201 void btRigidBody::proceedToTransform(const btTransform& newTrans)
202 {
203         setCenterOfMassTransform( newTrans );
204 }
205         
206
207 void btRigidBody::setMassProps(btScalar mass, const btVector3& inertia)
208 {
209         if (mass == btScalar(0.))
210         {
211                 m_collisionFlags |= btCollisionObject::CF_STATIC_OBJECT;
212                 m_inverseMass = btScalar(0.);
213         } else
214         {
215                 m_collisionFlags &= (~btCollisionObject::CF_STATIC_OBJECT);
216                 m_inverseMass = btScalar(1.0) / mass;
217         }
218         
219         m_invInertiaLocal.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
223 }
224
225         
226
227 void btRigidBody::updateInertiaTensor() 
228 {
229         m_invInertiaTensorWorld = m_worldTransform.getBasis().scaled(m_invInertiaLocal) * m_worldTransform.getBasis().transpose();
230 }
231
232
233 void btRigidBody::integrateVelocities(btScalar step) 
234 {
235         if (isStaticOrKinematicObject())
236                 return;
237
238         m_linearVelocity += m_totalForce * (m_inverseMass * step);
239         m_angularVelocity += m_invInertiaTensorWorld * m_totalTorque * step;
240
241 #define MAX_ANGVEL SIMD_HALF_PI
242         /// clamp angular velocity. collision calculations will fail on higher angular velocities       
243         btScalar angvel = m_angularVelocity.length();
244         if (angvel*step > MAX_ANGVEL)
245         {
246                 m_angularVelocity *= (MAX_ANGVEL/step) /angvel;
247         }
248
249 }
250
251 btQuaternion btRigidBody::getOrientation() const
252 {
253                 btQuaternion orn;
254                 m_worldTransform.getBasis().getRotation(orn);
255                 return orn;
256 }
257         
258         
259 void btRigidBody::setCenterOfMassTransform(const btTransform& xform)
260 {
261
262         if (isStaticOrKinematicObject())
263         {
264                 m_interpolationWorldTransform = m_worldTransform;
265         } else
266         {
267                 m_interpolationWorldTransform = xform;
268         }
269         m_interpolationLinearVelocity = getLinearVelocity();
270         m_interpolationAngularVelocity = getAngularVelocity();
271         m_worldTransform = xform;
272         updateInertiaTensor();
273 }
274
275
276 bool btRigidBody::checkCollideWithOverride(btCollisionObject* co)
277 {
278         btRigidBody* otherRb = btRigidBody::upcast(co);
279         if (!otherRb)
280                 return true;
281
282         for (int i = 0; i < m_constraintRefs.size(); ++i)
283         {
284                 btTypedConstraint* c = m_constraintRefs[i];
285                 if (&c->getRigidBodyA() == otherRb || &c->getRigidBodyB() == otherRb)
286                         return false;
287         }
288
289         return true;
290 }
291
292 void btRigidBody::addConstraintRef(btTypedConstraint* c)
293 {
294         int index = m_constraintRefs.findLinearSearch(c);
295         if (index == m_constraintRefs.size())
296                 m_constraintRefs.push_back(c); 
297
298         m_checkCollideWith = true;
299 }
300
301 void btRigidBody::removeConstraintRef(btTypedConstraint* c)
302 {
303         m_constraintRefs.remove(c);
304         m_checkCollideWith = m_constraintRefs.size() > 0;
305 }