BGE patch: new Physics button and margin parameter in Logic panel. Change subversion.
[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_margin(0.06f),
149                 m_collisionFlags(0),
150                 m_bRigid(false),
151                 m_collisionFilterGroup(DefaultFilter),
152                 m_collisionFilterMask(AllFilter),
153                 m_collisionShape(0),
154                 m_MotionState(0),
155                 m_shapeInfo(0),
156                 m_physicsEnv(0),
157                 m_inertiaFactor(1.f)
158         {
159         }
160
161         btVector3       m_localInertiaTensor;
162         btVector3       m_gravity;
163         btVector3       m_scaling;
164         btScalar        m_mass;
165         btScalar        m_restitution;
166         btScalar        m_friction;
167         btScalar        m_linearDamping;
168         btScalar        m_angularDamping;
169         btScalar        m_margin;
170         int                     m_collisionFlags;
171         bool            m_bRigid;
172
173         ///optional use of collision group/mask:
174         ///only collision with object goups that match the collision mask.
175         ///this is very basic early out. advanced collision filtering should be
176         ///done in the btCollisionDispatcher::NeedsCollision and NeedsResponse
177         ///both values default to 1
178         short int       m_collisionFilterGroup;
179         short int       m_collisionFilterMask;
180
181         ///these pointers are used as argument passing for the CcdPhysicsController constructor
182         ///and not anymore after that
183         class btCollisionShape* m_collisionShape;
184         class PHY_IMotionState* m_MotionState;
185         class CcdShapeConstructionInfo* m_shapeInfo;
186         
187         CcdPhysicsEnvironment*  m_physicsEnv; //needed for self-replication
188         float   m_inertiaFactor;//tweak the inertia (hooked up to Blender 'formfactor'
189 };
190
191
192 class btRigidBody;
193
194
195 ///CcdPhysicsController is a physics object that supports continuous collision detection and time of impact based physics resolution.
196 class CcdPhysicsController : public PHY_IPhysicsController      
197 {
198         btRigidBody* m_body;
199         class PHY_IMotionState*         m_MotionState;
200         btMotionState*  m_bulletMotionState;
201         class btCollisionShape* m_collisionShape;
202         class CcdShapeConstructionInfo* m_shapeInfo;
203
204         friend class CcdPhysicsEnvironment;     // needed when updating the controller
205
206
207         void*           m_newClientInfo;
208         int                     m_registerCount;        // needed when multiple sensors use the same controller
209         CcdConstructionInfo     m_cci;//needed for replication
210         void GetWorldOrientation(btMatrix3x3& mat);
211
212         void CreateRigidbody();
213
214         bool Register() { 
215                 return (m_registerCount++ == 0) ? true : false;
216         }
217         bool Unregister() {
218                 return (--m_registerCount == 0) ? true : false;
219         }
220
221         protected:
222                 void setWorldOrientation(const btMatrix3x3& mat);
223
224         public:
225         
226                 int                             m_collisionDelay;
227         
228
229                 CcdPhysicsController (const CcdConstructionInfo& ci);
230
231                 virtual ~CcdPhysicsController();
232
233
234                 btRigidBody* GetRigidBody() { return m_body;}
235                 CcdShapeConstructionInfo* GetShapeInfo() { return m_shapeInfo; }
236
237                 btCollisionShape*       GetCollisionShape() { 
238                         return m_body->getCollisionShape();
239                 }
240                 ////////////////////////////////////
241                 // PHY_IPhysicsController interface
242                 ////////////////////////////////////
243
244
245                 /**
246                         SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
247                 */
248                 virtual bool            SynchronizeMotionStates(float time);
249                 /**
250                         WriteMotionStateToDynamics ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
251                 */
252                 
253                 virtual void            WriteMotionStateToDynamics(bool nondynaonly);
254                 virtual void            WriteDynamicsToMotionState();
255                 // controller replication
256                 virtual void            PostProcessReplica(class PHY_IMotionState* motionstate,class PHY_IPhysicsController* parentctrl);
257
258                 // kinematic methods
259                 virtual void            RelativeTranslate(float dlocX,float dlocY,float dlocZ,bool local);
260                 virtual void            RelativeRotate(const float drot[9],bool local);
261                 virtual void            getOrientation(float &quatImag0,float &quatImag1,float &quatImag2,float &quatReal);
262                 virtual void            setOrientation(float quatImag0,float quatImag1,float quatImag2,float quatReal);
263                 virtual void            setPosition(float posX,float posY,float posZ);
264                 virtual void            getPosition(PHY__Vector3&       pos) const;
265
266                 virtual void            setScaling(float scaleX,float scaleY,float scaleZ);
267                 
268                 // physics methods
269                 virtual void            ApplyTorque(float torqueX,float torqueY,float torqueZ,bool local);
270                 virtual void            ApplyForce(float forceX,float forceY,float forceZ,bool local);
271                 virtual void            SetAngularVelocity(float ang_velX,float ang_velY,float ang_velZ,bool local);
272                 virtual void            SetLinearVelocity(float lin_velX,float lin_velY,float lin_velZ,bool local);
273                 virtual void            applyImpulse(float attachX,float attachY,float attachZ, float impulseX,float impulseY,float impulseZ);
274                 virtual void            SetActive(bool active);
275
276                 // reading out information from physics
277                 virtual void            GetLinearVelocity(float& linvX,float& linvY,float& linvZ);
278                 virtual void            GetAngularVelocity(float& angVelX,float& angVelY,float& angVelZ);
279                 virtual void            GetVelocity(const float posX,const float posY,const float posZ,float& linvX,float& linvY,float& linvZ); 
280                 virtual void            getReactionForce(float& forceX,float& forceY,float& forceZ);
281
282                 // dyna's that are rigidbody are free in orientation, dyna's with non-rigidbody are restricted 
283                 virtual void            setRigidBody(bool rigid);
284
285                 
286                 virtual void            resolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ);
287
288                 // clientinfo for raycasts for example
289                 virtual void*                           getNewClientInfo();
290                 virtual void                            setNewClientInfo(void* clientinfo);
291                 virtual PHY_IPhysicsController* GetReplica();
292                 
293                 ///There should be no 'SetCollisionFilterGroup' method, as changing this during run-time is will result in errors
294                 short int       GetCollisionFilterGroup() const
295                 {
296                         return m_cci.m_collisionFilterGroup;
297                 }
298                 ///There should be no 'SetCollisionFilterGroup' method, as changing this during run-time is will result in errors
299                 short int       GetCollisionFilterMask() const
300                 {
301                         return m_cci.m_collisionFilterMask;
302                 }
303
304                 virtual void    calcXform() {} ;
305                 virtual void SetMargin(float margin) {};
306                 virtual float GetMargin() const {return 0.f;};
307
308
309                 bool    wantsSleeping();
310
311                 void    UpdateDeactivation(float timeStep);
312
313                 static btTransform      GetTransformFromMotionState(PHY_IMotionState* motionState);
314
315                 void    setAabb(const btVector3& aabbMin,const btVector3& aabbMax);
316
317
318                 class   PHY_IMotionState*                       GetMotionState()
319                 {
320                         return m_MotionState;
321                 }
322
323                 const class     PHY_IMotionState*                       GetMotionState() const
324                 {
325                         return m_MotionState;
326                 }
327
328                 class CcdPhysicsEnvironment* GetPhysicsEnvironment()
329                 {
330                         return m_cci.m_physicsEnv;
331                 }
332                 
333 };
334
335
336
337
338 ///DefaultMotionState implements standard motionstate, using btTransform
339 class   DefaultMotionState : public PHY_IMotionState
340
341 {
342         public:
343                 DefaultMotionState();
344
345                 virtual ~DefaultMotionState();
346
347                 virtual void    getWorldPosition(float& posX,float& posY,float& posZ);
348                 virtual void    getWorldScaling(float& scaleX,float& scaleY,float& scaleZ);
349                 virtual void    getWorldOrientation(float& quatIma0,float& quatIma1,float& quatIma2,float& quatReal);
350                 
351                 virtual void    setWorldPosition(float posX,float posY,float posZ);
352                 virtual void    setWorldOrientation(float quatIma0,float quatIma1,float quatIma2,float quatReal);
353                 
354                 virtual void    calculateWorldTransformations();
355                 
356                 btTransform     m_worldTransform;
357                 btVector3               m_localScaling;
358
359 };
360
361
362 #endif //BULLET2_PHYSICSCONTROLLER_H