a685c4669441c3314cb665c59bc79a07bcdf1bf1
[blender-staging.git] / source / gameengine / Physics / Bullet / CcdPhysicsController.h
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
17 #ifndef BULLET2_PHYSICSCONTROLLER_H
18 #define BULLET2_PHYSICSCONTROLLER_H
19
20 #include <vector>
21
22 #include "PHY_IPhysicsController.h"
23
24 ///     PHY_IPhysicsController is the abstract simplified Interface to a physical object.
25 ///     It contains the IMotionState and IDeformableMesh Interfaces.
26 #include "btBulletDynamicsCommon.h"
27 #include "LinearMath/btTransform.h"
28
29 #include "PHY_IMotionState.h"
30
31 extern float gDeactivationTime;
32 extern float gLinearSleepingTreshold;
33 extern float gAngularSleepingTreshold;
34 extern bool gDisableDeactivation;
35 class CcdPhysicsEnvironment;
36 class btMotionState;
37 class RAS_MeshObject;
38 class btCollisionShape;
39
40 // Shape contructor
41 // It contains all the information needed to create a simple bullet shape at runtime
42 class CcdShapeConstructionInfo
43 {
44 public:
45         CcdShapeConstructionInfo() :
46                 m_shapeType(PHY_SHAPE_NONE),
47                 m_radius(1.0),
48                 m_height(1.0),
49                 m_halfExtend(0.f,0.f,0.f),
50                 m_childScale(1.0f,1.0f,1.0f),
51                 m_nextShape(NULL),
52                 m_unscaledShape(NULL),
53                 m_refCount(1)
54         {
55                 m_childTrans.setIdentity();
56         }
57
58         ~CcdShapeConstructionInfo();
59
60         CcdShapeConstructionInfo* AddRef()
61         { 
62                 m_refCount++;
63                 return this;
64         }
65
66         int Release()
67         {
68                 if (--m_refCount > 0)
69                         return m_refCount;
70                 delete this;
71                 return 0;
72         }
73
74         void AddShape(CcdShapeConstructionInfo* shapeInfo);
75
76         btTriangleMeshShape* GetMeshShape(void)
77         {
78                 return m_unscaledShape;
79         }
80         CcdShapeConstructionInfo* GetNextShape()
81         {
82                 return m_nextShape;
83         }
84         CcdShapeConstructionInfo* GetChildShape(int i)
85         {
86                 CcdShapeConstructionInfo* shape = m_nextShape;
87                 while (i > 0 && shape != NULL)
88                 {
89                         shape = shape->m_nextShape;
90                         i--;
91                 }
92                 return shape;
93         }
94
95         bool SetMesh(RAS_MeshObject* mesh, bool polytope);
96
97         btCollisionShape* CreateBulletShape();
98
99         // member variables
100         PHY_ShapeType                   m_shapeType;
101         btScalar                                m_radius;
102         btScalar                                m_height;
103         btVector3                               m_halfExtend;
104         btTransform                             m_childTrans;
105         btVector3                               m_childScale;
106         std::vector<btPoint3>   m_vertexArray;  // Contains both vertex array for polytope shape and
107                                                                                         // triangle array for concave mesh shape.
108                                                                                         // In this case a triangle is made of 3 consecutive points
109         std::vector<int>                m_polygonIndexArray;    // Contains the array of polygon index in the 
110                                                                                                         // original mesh that correspond to shape triangles.
111                                                                                                         // only set for concave mesh shape.
112         const RAS_MeshObject*   m_meshObject;   // Keep a pointer to the original mesh 
113
114 protected:
115         CcdShapeConstructionInfo* m_nextShape;  // for compound shape
116         btBvhTriangleMeshShape* m_unscaledShape;// holds the shared unscale BVH mesh shape, 
117                                                                                         // the actual shape is of type btScaledBvhTriangleMeshShape
118         int                                             m_refCount;             // this class is shared between replicas
119                                                                                         // keep track of users so that we can release it 
120 };
121
122 struct CcdConstructionInfo
123 {
124
125         ///CollisionFilterGroups provides some optional usage of basic collision filtering
126         ///this is done during broadphase, so very early in the pipeline
127         ///more advanced collision filtering should be done in btCollisionDispatcher::NeedsCollision
128         enum CollisionFilterGroups
129         {
130                 DefaultFilter = 1,
131                 StaticFilter = 2,
132                 KinematicFilter = 4,
133                 DebrisFilter = 8,
134                         SensorFilter = 16,
135                 AllFilter = DefaultFilter | StaticFilter | KinematicFilter | DebrisFilter | SensorFilter,
136         };
137
138
139         CcdConstructionInfo()
140                 : m_localInertiaTensor(1.f, 1.f, 1.f),
141                 m_gravity(0,0,0),
142                 m_scaling(1.f,1.f,1.f),
143                 m_mass(0.f),
144                 m_restitution(0.1f),
145                 m_friction(0.5f),
146                 m_linearDamping(0.1f),
147                 m_angularDamping(0.1f),
148                 m_collisionFlags(0),
149                 m_bRigid(false),
150                 m_collisionFilterGroup(DefaultFilter),
151                 m_collisionFilterMask(AllFilter),
152                 m_collisionShape(0),
153                 m_MotionState(0),
154                 m_shapeInfo(0),
155                 m_physicsEnv(0),
156                 m_inertiaFactor(1.f)
157         {
158         }
159
160         btVector3       m_localInertiaTensor;
161         btVector3       m_gravity;
162         btVector3       m_scaling;
163         btScalar        m_mass;
164         btScalar        m_restitution;
165         btScalar        m_friction;
166         btScalar        m_linearDamping;
167         btScalar        m_angularDamping;
168         int                     m_collisionFlags;
169         bool            m_bRigid;
170
171         ///optional use of collision group/mask:
172         ///only collision with object goups that match the collision mask.
173         ///this is very basic early out. advanced collision filtering should be
174         ///done in the btCollisionDispatcher::NeedsCollision and NeedsResponse
175         ///both values default to 1
176         short int       m_collisionFilterGroup;
177         short int       m_collisionFilterMask;
178
179         ///these pointers are used as argument passing for the CcdPhysicsController constructor
180         ///and not anymore after that
181         class btCollisionShape* m_collisionShape;
182         class PHY_IMotionState* m_MotionState;
183         class CcdShapeConstructionInfo* m_shapeInfo;
184         
185         CcdPhysicsEnvironment*  m_physicsEnv; //needed for self-replication
186         float   m_inertiaFactor;//tweak the inertia (hooked up to Blender 'formfactor'
187 };
188
189
190 class btRigidBody;
191
192
193 ///CcdPhysicsController is a physics object that supports continuous collision detection and time of impact based physics resolution.
194 class CcdPhysicsController : public PHY_IPhysicsController      
195 {
196         btRigidBody* m_body;
197         class PHY_IMotionState*         m_MotionState;
198         btMotionState*  m_bulletMotionState;
199         class btCollisionShape* m_collisionShape;
200         class CcdShapeConstructionInfo* m_shapeInfo;
201
202         friend class CcdPhysicsEnvironment;     // needed when updating the controller
203
204
205         void*           m_newClientInfo;
206         int                     m_registerCount;        // needed when multiple sensors use the same controller
207         CcdConstructionInfo     m_cci;//needed for replication
208         void GetWorldOrientation(btMatrix3x3& mat);
209
210         void CreateRigidbody();
211
212         bool Register() { 
213                 return (m_registerCount++ == 0) ? true : false;
214         }
215         bool Unregister() {
216                 return (--m_registerCount == 0) ? true : false;
217         }
218
219         protected:
220                 void setWorldOrientation(const btMatrix3x3& mat);
221
222         public:
223         
224                 int                             m_collisionDelay;
225         
226
227                 CcdPhysicsController (const CcdConstructionInfo& ci);
228
229                 virtual ~CcdPhysicsController();
230
231
232                 btRigidBody* GetRigidBody() { return m_body;}
233                 CcdShapeConstructionInfo* GetShapeInfo() { return m_shapeInfo; }
234
235                 btCollisionShape*       GetCollisionShape() { 
236                         return m_body->getCollisionShape();
237                 }
238                 ////////////////////////////////////
239                 // PHY_IPhysicsController interface
240                 ////////////////////////////////////
241
242
243                 /**
244                         SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
245                 */
246                 virtual bool            SynchronizeMotionStates(float time);
247                 /**
248                         WriteMotionStateToDynamics ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
249                 */
250                 
251                 virtual void            WriteMotionStateToDynamics(bool nondynaonly);
252                 virtual void            WriteDynamicsToMotionState();
253                 // controller replication
254                 virtual void            PostProcessReplica(class PHY_IMotionState* motionstate,class PHY_IPhysicsController* parentctrl);
255
256                 // kinematic methods
257                 virtual void            RelativeTranslate(float dlocX,float dlocY,float dlocZ,bool local);
258                 virtual void            RelativeRotate(const float drot[9],bool local);
259                 virtual void            getOrientation(float &quatImag0,float &quatImag1,float &quatImag2,float &quatReal);
260                 virtual void            setOrientation(float quatImag0,float quatImag1,float quatImag2,float quatReal);
261                 virtual void            setPosition(float posX,float posY,float posZ);
262                 virtual void            getPosition(PHY__Vector3&       pos) const;
263
264                 virtual void            setScaling(float scaleX,float scaleY,float scaleZ);
265                 
266                 // physics methods
267                 virtual void            ApplyTorque(float torqueX,float torqueY,float torqueZ,bool local);
268                 virtual void            ApplyForce(float forceX,float forceY,float forceZ,bool local);
269                 virtual void            SetAngularVelocity(float ang_velX,float ang_velY,float ang_velZ,bool local);
270                 virtual void            SetLinearVelocity(float lin_velX,float lin_velY,float lin_velZ,bool local);
271                 virtual void            applyImpulse(float attachX,float attachY,float attachZ, float impulseX,float impulseY,float impulseZ);
272                 virtual void            SetActive(bool active);
273
274                 // reading out information from physics
275                 virtual void            GetLinearVelocity(float& linvX,float& linvY,float& linvZ);
276                 virtual void            GetAngularVelocity(float& angVelX,float& angVelY,float& angVelZ);
277                 virtual void            GetVelocity(const float posX,const float posY,const float posZ,float& linvX,float& linvY,float& linvZ); 
278                 virtual void            getReactionForce(float& forceX,float& forceY,float& forceZ);
279
280                 // dyna's that are rigidbody are free in orientation, dyna's with non-rigidbody are restricted 
281                 virtual void            setRigidBody(bool rigid);
282
283                 
284                 virtual void            resolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ);
285
286                 // clientinfo for raycasts for example
287                 virtual void*                           getNewClientInfo();
288                 virtual void                            setNewClientInfo(void* clientinfo);
289                 virtual PHY_IPhysicsController* GetReplica();
290                 
291                 ///There should be no 'SetCollisionFilterGroup' method, as changing this during run-time is will result in errors
292                 short int       GetCollisionFilterGroup() const
293                 {
294                         return m_cci.m_collisionFilterGroup;
295                 }
296                 ///There should be no 'SetCollisionFilterGroup' method, as changing this during run-time is will result in errors
297                 short int       GetCollisionFilterMask() const
298                 {
299                         return m_cci.m_collisionFilterMask;
300                 }
301
302                 virtual void    calcXform() {} ;
303                 virtual void SetMargin(float margin) {};
304                 virtual float GetMargin() const {return 0.f;};
305
306
307                 bool    wantsSleeping();
308
309                 void    UpdateDeactivation(float timeStep);
310
311                 static btTransform      GetTransformFromMotionState(PHY_IMotionState* motionState);
312
313                 void    setAabb(const btVector3& aabbMin,const btVector3& aabbMax);
314
315
316                 class   PHY_IMotionState*                       GetMotionState()
317                 {
318                         return m_MotionState;
319                 }
320
321                 const class     PHY_IMotionState*                       GetMotionState() const
322                 {
323                         return m_MotionState;
324                 }
325
326                 class CcdPhysicsEnvironment* GetPhysicsEnvironment()
327                 {
328                         return m_cci.m_physicsEnv;
329                 }
330                 
331 };
332
333
334
335
336 ///DefaultMotionState implements standard motionstate, using btTransform
337 class   DefaultMotionState : public PHY_IMotionState
338
339 {
340         public:
341                 DefaultMotionState();
342
343                 virtual ~DefaultMotionState();
344
345                 virtual void    getWorldPosition(float& posX,float& posY,float& posZ);
346                 virtual void    getWorldScaling(float& scaleX,float& scaleY,float& scaleZ);
347                 virtual void    getWorldOrientation(float& quatIma0,float& quatIma1,float& quatIma2,float& quatReal);
348                 
349                 virtual void    setWorldPosition(float posX,float posY,float posZ);
350                 virtual void    setWorldOrientation(float quatIma0,float quatIma1,float quatIma2,float quatReal);
351                 
352                 virtual void    calculateWorldTransformations();
353                 
354                 btTransform     m_worldTransform;
355                 btVector3               m_localScaling;
356
357 };
358
359
360 #endif //BULLET2_PHYSICSCONTROLLER_H