BGE modifier: generate correct physic shape, share static derived mesh, share display...
[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 #include <map>
22
23 #include "PHY_IPhysicsController.h"
24
25 ///     PHY_IPhysicsController is the abstract simplified Interface to a physical object.
26 ///     It contains the IMotionState and IDeformableMesh Interfaces.
27 #include "btBulletDynamicsCommon.h"
28 #include "LinearMath/btTransform.h"
29
30 #include "PHY_IMotionState.h"
31
32 extern float gDeactivationTime;
33 extern float gLinearSleepingTreshold;
34 extern float gAngularSleepingTreshold;
35 extern bool gDisableDeactivation;
36 class CcdPhysicsEnvironment;
37 class btMotionState;
38 class RAS_MeshObject;
39 struct DerivedMesh;
40 class btCollisionShape;
41
42
43 #define CCD_BSB_SHAPE_MATCHING  2
44 #define CCD_BSB_BENDING_CONSTRAINTS 8
45 #define CCD_BSB_AERO_VPOINT 16 /* aero model, Vertex normals are oriented toward velocity*/
46 #define CCD_BSB_AERO_VTWOSIDE 32 /* aero model, Vertex normals are flipped to match velocity */
47
48 /* BulletSoftBody.collisionflags */
49 #define CCD_BSB_COL_SDF_RS      2 /* SDF based rigid vs soft */
50 #define CCD_BSB_COL_CL_RS       4 /* Cluster based rigid vs soft */
51 #define CCD_BSB_COL_CL_SS       8 /* Cluster based soft vs soft */
52 #define CCD_BSB_COL_VF_SS       16 /* Vertex/Face based soft vs soft */
53
54
55
56 // Shape contructor
57 // It contains all the information needed to create a simple bullet shape at runtime
58 class CcdShapeConstructionInfo
59 {
60 public:
61         
62
63         static CcdShapeConstructionInfo* FindMesh(class RAS_MeshObject* mesh, struct DerivedMesh* dm, bool polytope, bool gimpact);
64
65         CcdShapeConstructionInfo() :
66                 m_shapeType(PHY_SHAPE_NONE),
67                 m_radius(1.0),
68                 m_height(1.0),
69                 m_halfExtend(0.f,0.f,0.f),
70                 m_childScale(1.0f,1.0f,1.0f),
71                 m_userData(NULL),
72                 m_refCount(1),
73                 m_meshObject(NULL),
74                 m_unscaledShape(NULL),
75                 m_useGimpact(false),
76                 m_weldingThreshold1(0.f),
77                 m_shapeProxy(NULL)
78         {
79                 m_childTrans.setIdentity();
80         }
81
82         ~CcdShapeConstructionInfo();
83
84         CcdShapeConstructionInfo* AddRef()
85         { 
86                 m_refCount++;
87                 return this;
88         }
89
90         int Release()
91         {
92                 if (--m_refCount > 0)
93                         return m_refCount;
94                 delete this;
95                 return 0;
96         }
97
98         bool IsUnused(void)
99         {
100                 return (m_meshObject==NULL && m_shapeArray.size() == 0 && m_shapeProxy == NULL);
101         }
102
103         void AddShape(CcdShapeConstructionInfo* shapeInfo);
104
105         btTriangleMeshShape* GetMeshShape(void)
106         {
107                 return m_unscaledShape;
108         }
109         CcdShapeConstructionInfo* GetChildShape(int i)
110         {
111                 if (i < 0 || i >= (int)m_shapeArray.size())
112                         return NULL;
113
114                 return m_shapeArray.at(i);
115         }
116         int FindChildShape(CcdShapeConstructionInfo* shapeInfo, void* userData)
117         {
118                 if (shapeInfo == NULL)
119                         return -1;
120                 for (int i=0; i<(int)m_shapeArray.size(); i++)
121                 {
122                         CcdShapeConstructionInfo* childInfo = m_shapeArray.at(i);
123                         if ((userData == NULL || userData == childInfo->m_userData) &&
124                                 (childInfo == shapeInfo ||
125                                  (childInfo->m_shapeType == PHY_SHAPE_PROXY && 
126                                   childInfo->m_shapeProxy == shapeInfo)))
127                                 return i;
128                 }
129                 return -1;
130         }
131
132         bool RemoveChildShape(int i)
133         {
134                 if (i < 0 || i >= (int)m_shapeArray.size())
135                         return false;
136                 m_shapeArray.at(i)->Release();
137                 if (i < (int)m_shapeArray.size()-1)
138                         m_shapeArray[i] = m_shapeArray.back();
139                 m_shapeArray.pop_back();
140                 return true;
141         }
142
143         bool SetMesh(class RAS_MeshObject* mesh, struct DerivedMesh* dm, bool polytope,bool useGimpact);
144         RAS_MeshObject* GetMesh(void)
145         {
146                 return m_meshObject;
147         }
148
149         bool SetProxy(CcdShapeConstructionInfo* shapeInfo);
150         CcdShapeConstructionInfo* GetProxy(void)
151         {
152                 return m_shapeProxy;
153         }
154
155         btCollisionShape* CreateBulletShape();
156
157         // member variables
158         PHY_ShapeType                   m_shapeType;
159         btScalar                                m_radius;
160         btScalar                                m_height;
161         btVector3                               m_halfExtend;
162         btTransform                             m_childTrans;
163         btVector3                               m_childScale;
164         void*                                   m_userData;     
165         btAlignedObjectArray<btScalar>  m_vertexArray;  // Contains both vertex array for polytope shape and
166                                                                                         // triangle array for concave mesh shape. Each vertex is 3 consecutive values
167                                                                                         // In this case a triangle is made of 3 consecutive points
168         std::vector<int>                m_polygonIndexArray;    // Contains the array of polygon index in the 
169                                                                                                         // original mesh that correspond to shape triangles.
170                                                                                                         // only set for concave mesh shape.
171         
172         std::vector<int>                m_triFaceArray; // Contains an array of triplets of face indicies
173                                                                                         // quads turn into 2 tris
174
175         void    setVertexWeldingThreshold1(float threshold)
176         {
177                 m_weldingThreshold1  = threshold*threshold;
178         }
179 protected:
180         static std::map<RAS_MeshObject*, CcdShapeConstructionInfo*> m_meshShapeMap;
181         int                                             m_refCount;             // this class is shared between replicas
182                                                                                         // keep track of users so that we can release it 
183         RAS_MeshObject* m_meshObject;                   // Keep a pointer to the original mesh 
184         btBvhTriangleMeshShape* m_unscaledShape;// holds the shared unscale BVH mesh shape, 
185                                                                                         // the actual shape is of type btScaledBvhTriangleMeshShape
186         std::vector<CcdShapeConstructionInfo*> m_shapeArray;    // for compound shapes
187         bool    m_useGimpact; //use gimpact for concave dynamic/moving collision detection
188         float   m_weldingThreshold1;    //welding closeby vertices together can improve softbody stability etc.
189         CcdShapeConstructionInfo* m_shapeProxy; // only used for PHY_SHAPE_PROXY, pointer to actual shape info
190 };
191
192 struct CcdConstructionInfo
193 {
194
195         ///CollisionFilterGroups provides some optional usage of basic collision filtering
196         ///this is done during broadphase, so very early in the pipeline
197         ///more advanced collision filtering should be done in btCollisionDispatcher::NeedsCollision
198         enum CollisionFilterGroups
199         {
200                 DefaultFilter = 1,
201                 StaticFilter = 2,
202                 KinematicFilter = 4,
203                 DebrisFilter = 8,
204                         SensorFilter = 16,
205                 AllFilter = DefaultFilter | StaticFilter | KinematicFilter | DebrisFilter | SensorFilter,
206         };
207
208
209         CcdConstructionInfo()
210                 : m_localInertiaTensor(1.f, 1.f, 1.f),
211                 m_gravity(0,0,0),
212                 m_scaling(1.f,1.f,1.f),
213                 m_mass(0.f),
214                 m_clamp_vel_min(-1.f), 
215                 m_clamp_vel_max(-1.f), 
216                 m_restitution(0.1f),
217                 m_friction(0.5f),
218                 m_linearDamping(0.1f),
219                 m_angularDamping(0.1f),
220                 m_margin(0.06f),
221                 m_gamesoftFlag(0),
222                 m_collisionFlags(0),
223                 m_bRigid(false),
224                 m_bSoft(false),
225                 m_collisionFilterGroup(DefaultFilter),
226                 m_collisionFilterMask(AllFilter),
227                 m_collisionShape(0),
228                 m_MotionState(0),
229                 m_shapeInfo(0),
230                 m_physicsEnv(0),
231                 m_inertiaFactor(1.f),
232                 m_do_anisotropic(false),
233                 m_anisotropicFriction(1.f,1.f,1.f)
234         {
235         }
236
237         btVector3       m_localInertiaTensor;
238         btVector3       m_gravity;
239         btVector3       m_scaling;
240         btScalar        m_mass;
241         btScalar        m_clamp_vel_min;  
242         btScalar        m_clamp_vel_max;  
243         btScalar        m_restitution;
244         btScalar        m_friction;
245         btScalar        m_linearDamping;
246         btScalar        m_angularDamping;
247         btScalar        m_margin;
248
249         ////////////////////
250         int             m_gamesoftFlag;
251         float   m_soft_linStiff;                        /* linear stiffness 0..1 */
252         float   m_soft_angStiff;                /* angular stiffness 0..1 */
253         float   m_soft_volume;                  /* volume preservation 0..1 */
254
255         int             m_soft_viterations;             /* Velocities solver iterations */
256         int             m_soft_piterations;             /* Positions solver iterations */
257         int             m_soft_diterations;             /* Drift solver iterations */
258         int             m_soft_citerations;             /* Cluster solver iterations */
259
260         float   m_soft_kSRHR_CL;                /* Soft vs rigid hardness [0,1] (cluster only) */
261         float   m_soft_kSKHR_CL;                /* Soft vs kinetic hardness [0,1] (cluster only) */
262         float   m_soft_kSSHR_CL;                /* Soft vs soft hardness [0,1] (cluster only) */
263         float   m_soft_kSR_SPLT_CL;     /* Soft vs rigid impulse split [0,1] (cluster only) */
264
265         float   m_soft_kSK_SPLT_CL;     /* Soft vs rigid impulse split [0,1] (cluster only) */
266         float   m_soft_kSS_SPLT_CL;     /* Soft vs rigid impulse split [0,1] (cluster only) */
267         float   m_soft_kVCF;                    /* Velocities correction factor (Baumgarte) */
268         float   m_soft_kDP;                     /* Damping coefficient [0,1] */
269
270         float   m_soft_kDG;                     /* Drag coefficient [0,+inf] */
271         float   m_soft_kLF;                     /* Lift coefficient [0,+inf] */
272         float   m_soft_kPR;                     /* Pressure coefficient [-inf,+inf] */
273         float   m_soft_kVC;                     /* Volume conversation coefficient [0,+inf] */
274
275         float   m_soft_kDF;                     /* Dynamic friction coefficient [0,1] */
276         float   m_soft_kMT;                     /* Pose matching coefficient [0,1] */
277         float   m_soft_kCHR;                    /* Rigid contacts hardness [0,1] */
278         float   m_soft_kKHR;                    /* Kinetic contacts hardness [0,1] */
279
280         float   m_soft_kSHR;                    /* Soft contacts hardness [0,1] */
281         float   m_soft_kAHR;                    /* Anchors hardness [0,1] */
282         int             m_soft_collisionflags;  /* Vertex/Face or Signed Distance Field(SDF) or Clusters, Soft versus Soft or Rigid */
283         int             m_soft_numclusteriterations;    /* number of iterations to refine collision clusters*/
284 ///////////////////
285
286
287
288         int                     m_collisionFlags;
289         bool            m_bRigid;
290         bool            m_bSoft;
291
292         ///optional use of collision group/mask:
293         ///only collision with object goups that match the collision mask.
294         ///this is very basic early out. advanced collision filtering should be
295         ///done in the btCollisionDispatcher::NeedsCollision and NeedsResponse
296         ///both values default to 1
297         short int       m_collisionFilterGroup;
298         short int       m_collisionFilterMask;
299
300         ///these pointers are used as argument passing for the CcdPhysicsController constructor
301         ///and not anymore after that
302         class btCollisionShape* m_collisionShape;
303         class PHY_IMotionState* m_MotionState;
304         class CcdShapeConstructionInfo* m_shapeInfo;
305         
306         CcdPhysicsEnvironment*  m_physicsEnv; //needed for self-replication
307         float   m_inertiaFactor;//tweak the inertia (hooked up to Blender 'formfactor'
308         bool    m_do_anisotropic;
309         btVector3 m_anisotropicFriction;
310
311         bool            m_do_fh;                 ///< Should the object have a linear Fh spring?
312         bool            m_do_rot_fh;             ///< Should the object have an angular Fh spring?
313         btScalar        m_fh_spring;             ///< Spring constant (both linear and angular)
314         btScalar        m_fh_damping;            ///< Damping factor (linear and angular) in range [0, 1]
315         btScalar        m_fh_distance;           ///< The range above the surface where Fh is active.    
316         bool            m_fh_normal;             ///< Should the object slide off slopes?
317         float           m_radius;//for fh backwards compatibility
318
319 };
320
321
322 class btRigidBody;
323 class btCollisionObject;
324 class btSoftBody;
325
326 ///CcdPhysicsController is a physics object that supports continuous collision detection and time of impact based physics resolution.
327 class CcdPhysicsController : public PHY_IPhysicsController      
328 {
329
330         btCollisionObject* m_object;
331         
332
333         class PHY_IMotionState*         m_MotionState;
334         btMotionState*  m_bulletMotionState;
335         class btCollisionShape* m_collisionShape;
336         class CcdShapeConstructionInfo* m_shapeInfo;
337
338         friend class CcdPhysicsEnvironment;     // needed when updating the controller
339
340         //some book keeping for replication
341         bool    m_softbodyMappingDone;
342         bool    m_softBodyTransformInitialized;
343         bool    m_prototypeTransformInitialized;
344         btTransform     m_softbodyStartTrans;
345
346
347         void*           m_newClientInfo;
348         int                     m_registerCount;        // needed when multiple sensors use the same controller
349         CcdConstructionInfo     m_cci;//needed for replication
350
351         CcdPhysicsController* m_parentCtrl;
352
353         void GetWorldOrientation(btMatrix3x3& mat);
354
355         void CreateRigidbody();
356
357         bool Register() { 
358                 return (m_registerCount++ == 0) ? true : false;
359         }
360         bool Unregister() {
361                 return (--m_registerCount == 0) ? true : false;
362         }
363
364         protected:
365                 void setWorldOrientation(const btMatrix3x3& mat);
366
367         public:
368         
369                 int                             m_collisionDelay;
370         
371
372                 CcdPhysicsController (const CcdConstructionInfo& ci);
373
374                 virtual ~CcdPhysicsController();
375
376                 CcdConstructionInfo& getConstructionInfo()
377                 {
378                         return m_cci;
379                 }
380                 const CcdConstructionInfo& getConstructionInfo() const
381                 {
382                         return m_cci;
383                 }
384
385
386                 btRigidBody* GetRigidBody();
387                 btCollisionObject*      GetCollisionObject();
388                 btSoftBody* GetSoftBody();
389
390                 CcdShapeConstructionInfo* GetShapeInfo() { return m_shapeInfo; }
391
392                 btCollisionShape*       GetCollisionShape() { 
393                         return m_object->getCollisionShape();
394                 }
395                 ////////////////////////////////////
396                 // PHY_IPhysicsController interface
397                 ////////////////////////////////////
398
399
400                 /**
401                         SynchronizeMotionStates ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
402                 */
403                 virtual bool            SynchronizeMotionStates(float time);
404                 /**
405                         WriteMotionStateToDynamics ynchronizes dynas, kinematic and deformable entities (and do 'late binding')
406                 */
407                 
408                 virtual void            WriteMotionStateToDynamics(bool nondynaonly);
409                 virtual void            WriteDynamicsToMotionState();
410                 // controller replication
411                 virtual void            PostProcessReplica(class PHY_IMotionState* motionstate,class PHY_IPhysicsController* parentctrl);
412
413                 // kinematic methods
414                 virtual void            RelativeTranslate(float dlocX,float dlocY,float dlocZ,bool local);
415                 virtual void            RelativeRotate(const float drot[9],bool local);
416                 virtual void            getOrientation(float &quatImag0,float &quatImag1,float &quatImag2,float &quatReal);
417                 virtual void            setOrientation(float quatImag0,float quatImag1,float quatImag2,float quatReal);
418                 virtual void            setPosition(float posX,float posY,float posZ);
419                 virtual void            getPosition(PHY__Vector3&       pos) const;
420
421                 virtual void            setScaling(float scaleX,float scaleY,float scaleZ);
422                 
423                 // physics methods
424                 virtual void            ApplyTorque(float torqueX,float torqueY,float torqueZ,bool local);
425                 virtual void            ApplyForce(float forceX,float forceY,float forceZ,bool local);
426                 virtual void            SetAngularVelocity(float ang_velX,float ang_velY,float ang_velZ,bool local);
427                 virtual void            SetLinearVelocity(float lin_velX,float lin_velY,float lin_velZ,bool local);
428                 virtual void            applyImpulse(float attachX,float attachY,float attachZ, float impulseX,float impulseY,float impulseZ);
429                 virtual void            SetActive(bool active);
430
431                 // reading out information from physics
432                 virtual void            GetLinearVelocity(float& linvX,float& linvY,float& linvZ);
433                 virtual void            GetAngularVelocity(float& angVelX,float& angVelY,float& angVelZ);
434                 virtual void            GetVelocity(const float posX,const float posY,const float posZ,float& linvX,float& linvY,float& linvZ); 
435                 virtual void            getReactionForce(float& forceX,float& forceY,float& forceZ);
436
437                 // dyna's that are rigidbody are free in orientation, dyna's with non-rigidbody are restricted 
438                 virtual void            setRigidBody(bool rigid);
439
440                 
441                 virtual void            resolveCombinedVelocities(float linvelX,float linvelY,float linvelZ,float angVelX,float angVelY,float angVelZ);
442
443                 // clientinfo for raycasts for example
444                 virtual void*                           getNewClientInfo();
445                 virtual void                            setNewClientInfo(void* clientinfo);
446                 virtual PHY_IPhysicsController* GetReplica();
447                 
448                 ///There should be no 'SetCollisionFilterGroup' method, as changing this during run-time is will result in errors
449                 short int       GetCollisionFilterGroup() const
450                 {
451                         return m_cci.m_collisionFilterGroup;
452                 }
453                 ///There should be no 'SetCollisionFilterGroup' method, as changing this during run-time is will result in errors
454                 short int       GetCollisionFilterMask() const
455                 {
456                         return m_cci.m_collisionFilterMask;
457                 }
458
459                 virtual void    calcXform() {} ;
460                 virtual void SetMargin(float margin) 
461                 {
462                         if (m_collisionShape)
463                                 m_collisionShape->setMargin(btScalar(margin));
464                 }
465                 virtual float GetMargin() const 
466                 {
467                         return (m_collisionShape) ? m_collisionShape->getMargin() : 0.f;
468                 }
469                 virtual float GetRadius() const 
470                 { 
471                         // this is not the actual shape radius, it's only used for Fh support
472                         return m_cci.m_radius;
473                 }
474                 virtual void  SetRadius(float margin) 
475                 {
476                         if (m_collisionShape && m_collisionShape->getShapeType() == SPHERE_SHAPE_PROXYTYPE)
477                         {
478                                 btSphereShape* sphereShape = static_cast<btSphereShape*>(m_collisionShape);
479                                 sphereShape->setUnscaledRadius(margin);
480                         }
481                         m_cci.m_radius = margin;
482                 }
483                 
484                 // velocity clamping
485                 virtual void SetLinVelocityMin(float val) 
486                 {
487                         m_cci.m_clamp_vel_min= val;
488                 }
489                 virtual float GetLinVelocityMin() const 
490                 {
491                         return m_cci.m_clamp_vel_min;
492                 }
493                 virtual void SetLinVelocityMax(float val) 
494                 {
495                         m_cci.m_clamp_vel_max= val;
496                 }
497                 virtual float GetLinVelocityMax() const 
498                 {
499                         return m_cci.m_clamp_vel_max;
500                 }
501
502                 bool    wantsSleeping();
503
504                 void    UpdateDeactivation(float timeStep);
505
506                 void    SetCenterOfMassTransform(btTransform& xform);
507
508                 static btTransform      GetTransformFromMotionState(PHY_IMotionState* motionState);
509
510                 void    setAabb(const btVector3& aabbMin,const btVector3& aabbMax);
511
512
513                 class   PHY_IMotionState*                       GetMotionState()
514                 {
515                         return m_MotionState;
516                 }
517
518                 const class     PHY_IMotionState*                       GetMotionState() const
519                 {
520                         return m_MotionState;
521                 }
522
523                 class CcdPhysicsEnvironment* GetPhysicsEnvironment()
524                 {
525                         return m_cci.m_physicsEnv;
526                 }
527
528                 void    setParentCtrl(CcdPhysicsController* parentCtrl)
529                 {
530                         m_parentCtrl = parentCtrl;
531                 }
532
533                 CcdPhysicsController*   getParentCtrl()
534                 {
535                         return m_parentCtrl;
536                 }
537
538                 const CcdPhysicsController*     getParentCtrl() const
539                 {
540                         return m_parentCtrl;
541                 }
542
543
544                 
545 };
546
547
548
549
550 ///DefaultMotionState implements standard motionstate, using btTransform
551 class   DefaultMotionState : public PHY_IMotionState
552
553 {
554         public:
555                 DefaultMotionState();
556
557                 virtual ~DefaultMotionState();
558
559                 virtual void    getWorldPosition(float& posX,float& posY,float& posZ);
560                 virtual void    getWorldScaling(float& scaleX,float& scaleY,float& scaleZ);
561                 virtual void    getWorldOrientation(float& quatIma0,float& quatIma1,float& quatIma2,float& quatReal);
562                 
563                 virtual void    setWorldPosition(float posX,float posY,float posZ);
564                 virtual void    setWorldOrientation(float quatIma0,float quatIma1,float quatIma2,float quatReal);
565                 virtual void    getWorldOrientation(float* ori);
566                 
567                 virtual void    calculateWorldTransformations();
568                 
569                 btTransform     m_worldTransform;
570                 btVector3               m_localScaling;
571
572 };
573
574
575 #endif //BULLET2_PHYSICSCONTROLLER_H