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