Merging r47612 through r47623 from trunk into soc-2011-tomato
[blender.git] / extern / bullet2 / src / BulletSoftBody / btSoftBody.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 ///btSoftBody implementation by Nathanael Presson
16
17 #ifndef _BT_SOFT_BODY_H
18 #define _BT_SOFT_BODY_H
19
20 #include "LinearMath/btAlignedObjectArray.h"
21 #include "LinearMath/btTransform.h"
22 #include "LinearMath/btIDebugDraw.h"
23 #include "BulletDynamics/Dynamics/btRigidBody.h"
24
25 #include "BulletCollision/CollisionShapes/btConcaveShape.h"
26 #include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
27 #include "btSparseSDF.h"
28 #include "BulletCollision/BroadphaseCollision/btDbvt.h"
29
30 //#ifdef BT_USE_DOUBLE_PRECISION
31 //#define btRigidBodyData       btRigidBodyDoubleData
32 //#define btRigidBodyDataName   "btRigidBodyDoubleData"
33 //#else
34 #define btSoftBodyData  btSoftBodyFloatData
35 #define btSoftBodyDataName      "btSoftBodyFloatData"
36 //#endif //BT_USE_DOUBLE_PRECISION
37
38 class btBroadphaseInterface;
39 class btDispatcher;
40 class btSoftBodySolver;
41
42 /* btSoftBodyWorldInfo  */ 
43 struct  btSoftBodyWorldInfo
44 {
45         btScalar                                air_density;
46         btScalar                                water_density;
47         btScalar                                water_offset;
48         btVector3                               water_normal;
49         btBroadphaseInterface*  m_broadphase;
50         btDispatcher*   m_dispatcher;
51         btVector3                               m_gravity;
52         btSparseSdf<3>                  m_sparsesdf;
53
54         btSoftBodyWorldInfo()
55                 :air_density((btScalar)1.2),
56                 water_density(0),
57                 water_offset(0),
58                 water_normal(0,0,0),
59                 m_broadphase(0),
60                 m_dispatcher(0),
61                 m_gravity(0,-10,0)
62         {
63         }
64 };      
65
66
67 ///The btSoftBody is an class to simulate cloth and volumetric soft bodies. 
68 ///There is two-way interaction between btSoftBody and btRigidBody/btCollisionObject.
69 class   btSoftBody : public btCollisionObject
70 {
71 public:
72         btAlignedObjectArray<class btCollisionObject*> m_collisionDisabledObjects;
73
74         // The solver object that handles this soft body
75         btSoftBodySolver *m_softBodySolver;
76
77         //
78         // Enumerations
79         //
80
81         ///eAeroModel 
82         struct eAeroModel { enum _ {
83                 V_Point,                        ///Vertex normals are oriented toward velocity
84                 V_TwoSided,                     ///Vertex normals are flipped to match velocity 
85                 V_TwoSidedLiftDrag, ///Vertex normals are flipped to match velocity and lift and drag forces are applied
86                 V_OneSided,                     ///Vertex normals are taken as it is    
87                 F_TwoSided,                     ///Face normals are flipped to match velocity
88                 F_TwoSidedLiftDrag,     ///Face normals are flipped to match velocity and lift and drag forces are applied 
89                 F_OneSided,                     ///Face normals are taken as it is              
90                 END
91         };};
92
93         ///eVSolver : velocities solvers
94         struct  eVSolver { enum _ {
95                 Linear,         ///Linear solver
96                 END
97         };};
98
99         ///ePSolver : positions solvers
100         struct  ePSolver { enum _ {
101                 Linear,         ///Linear solver
102                 Anchors,        ///Anchor solver
103                 RContacts,      ///Rigid contacts solver
104                 SContacts,      ///Soft contacts solver
105                 END
106         };};
107
108         ///eSolverPresets
109         struct  eSolverPresets { enum _ {
110                 Positions,
111                 Velocities,
112                 Default =       Positions,
113                 END
114         };};
115
116         ///eFeature
117         struct  eFeature { enum _ {
118                 None,
119                 Node,
120                 Link,
121                 Face,
122                 Tetra,
123                 END
124         };};
125
126         typedef btAlignedObjectArray<eVSolver::_>       tVSolverArray;
127         typedef btAlignedObjectArray<ePSolver::_>       tPSolverArray;
128
129         //
130         // Flags
131         //
132
133         ///fCollision
134         struct fCollision { enum _ {
135                 RVSmask =       0x000f, ///Rigid versus soft mask
136                 SDF_RS  =       0x0001, ///SDF based rigid vs soft
137                 CL_RS   =       0x0002, ///Cluster vs convex rigid vs soft
138
139                 SVSmask =       0x0030, ///Rigid versus soft mask               
140                 VF_SS   =       0x0010, ///Vertex vs face soft vs soft handling
141                 CL_SS   =       0x0020, ///Cluster vs cluster soft vs soft handling
142                 CL_SELF =       0x0040, ///Cluster soft body self collision
143                 /* presets      */ 
144                 Default =       SDF_RS,
145                 END
146         };};
147
148         ///fMaterial
149         struct fMaterial { enum _ {
150                 DebugDraw       =       0x0001, /// Enable debug draw
151                 /* presets      */ 
152                 Default         =       DebugDraw,
153                 END
154         };};
155
156         //
157         // API Types
158         //
159
160         /* sRayCast             */ 
161         struct sRayCast
162         {
163                 btSoftBody*     body;           /// soft body
164                 eFeature::_     feature;        /// feature type
165                 int                     index;          /// feature index
166                 btScalar        fraction;               /// time of impact fraction (rayorg+(rayto-rayfrom)*fraction)
167         };
168
169         /* ImplicitFn   */ 
170         struct  ImplicitFn
171         {
172                 virtual btScalar        Eval(const btVector3& x)=0;
173         };
174
175         //
176         // Internal types
177         //
178
179         typedef btAlignedObjectArray<btScalar>  tScalarArray;
180         typedef btAlignedObjectArray<btVector3> tVector3Array;
181
182         /* sCti is Softbody contact info        */ 
183         struct  sCti
184         {
185                 btCollisionObject*      m_colObj;               /* Rigid body                   */ 
186                 btVector3               m_normal;       /* Outward normal               */ 
187                 btScalar                m_offset;       /* Offset from origin   */ 
188         };      
189
190         /* sMedium              */ 
191         struct  sMedium
192         {
193                 btVector3               m_velocity;     /* Velocity                             */ 
194                 btScalar                m_pressure;     /* Pressure                             */ 
195                 btScalar                m_density;      /* Density                              */ 
196         };
197
198         /* Base type    */ 
199         struct  Element
200         {
201                 void*                   m_tag;                  // User data
202                 Element() : m_tag(0) {}
203         };
204         /* Material             */ 
205         struct  Material : Element
206         {
207                 btScalar                                m_kLST;                 // Linear stiffness coefficient [0,1]
208                 btScalar                                m_kAST;                 // Area/Angular stiffness coefficient [0,1]
209                 btScalar                                m_kVST;                 // Volume stiffness coefficient [0,1]
210                 int                                             m_flags;                // Flags
211         };
212
213         /* Feature              */ 
214         struct  Feature : Element
215         {
216                 Material*                               m_material;             // Material
217         };
218         /* Node                 */ 
219         struct  Node : Feature
220         {
221                 btVector3                               m_x;                    // Position
222                 btVector3                               m_q;                    // Previous step position
223                 btVector3                               m_v;                    // Velocity
224                 btVector3                               m_f;                    // Force accumulator
225                 btVector3                               m_n;                    // Normal
226                 btScalar                                m_im;                   // 1/mass
227                 btScalar                                m_area;                 // Area
228                 btDbvtNode*                             m_leaf;                 // Leaf data
229                 int                                             m_battach:1;    // Attached
230         };
231         /* Link                 */ 
232         struct  Link : Feature
233         {
234                 Node*                                   m_n[2];                 // Node pointers
235                 btScalar                                m_rl;                   // Rest length          
236                 int                                             m_bbending:1;   // Bending link
237                 btScalar                                m_c0;                   // (ima+imb)*kLST
238                 btScalar                                m_c1;                   // rl^2
239                 btScalar                                m_c2;                   // |gradient|^2/c0
240                 btVector3                               m_c3;                   // gradient
241         };
242         /* Face                 */ 
243         struct  Face : Feature
244         {
245                 Node*                                   m_n[3];                 // Node pointers
246                 btVector3                               m_normal;               // Normal
247                 btScalar                                m_ra;                   // Rest area
248                 btDbvtNode*                             m_leaf;                 // Leaf data
249         };
250         /* Tetra                */ 
251         struct  Tetra : Feature
252         {
253                 Node*                                   m_n[4];                 // Node pointers                
254                 btScalar                                m_rv;                   // Rest volume
255                 btDbvtNode*                             m_leaf;                 // Leaf data
256                 btVector3                               m_c0[4];                // gradients
257                 btScalar                                m_c1;                   // (4*kVST)/(im0+im1+im2+im3)
258                 btScalar                                m_c2;                   // m_c1/sum(|g0..3|^2)
259         };
260         /* RContact             */ 
261         struct  RContact
262         {
263                 sCti            m_cti;                  // Contact infos
264                 Node*                                   m_node;                 // Owner node
265                 btMatrix3x3                             m_c0;                   // Impulse matrix
266                 btVector3                               m_c1;                   // Relative anchor
267                 btScalar                                m_c2;                   // ima*dt
268                 btScalar                                m_c3;                   // Friction
269                 btScalar                                m_c4;                   // Hardness
270         };
271         /* SContact             */ 
272         struct  SContact
273         {
274                 Node*                                   m_node;                 // Node
275                 Face*                                   m_face;                 // Face
276                 btVector3                               m_weights;              // Weigths
277                 btVector3                               m_normal;               // Normal
278                 btScalar                                m_margin;               // Margin
279                 btScalar                                m_friction;             // Friction
280                 btScalar                                m_cfm[2];               // Constraint force mixing
281         };
282         /* Anchor               */ 
283         struct  Anchor
284         {
285                 Node*                                   m_node;                 // Node pointer
286                 btVector3                               m_local;                // Anchor position in body space
287                 btRigidBody*                    m_body;                 // Body
288                 btScalar                                m_influence;
289                 btMatrix3x3                             m_c0;                   // Impulse matrix
290                 btVector3                               m_c1;                   // Relative anchor
291                 btScalar                                m_c2;                   // ima*dt
292         };
293         /* Note                 */ 
294         struct  Note : Element
295         {
296                 const char*                             m_text;                 // Text
297                 btVector3                               m_offset;               // Offset
298                 int                                             m_rank;                 // Rank
299                 Node*                                   m_nodes[4];             // Nodes
300                 btScalar                                m_coords[4];    // Coordinates
301         };      
302         /* Pose                 */ 
303         struct  Pose
304         {
305                 bool                                    m_bvolume;              // Is valid
306                 bool                                    m_bframe;               // Is frame
307                 btScalar                                m_volume;               // Rest volume
308                 tVector3Array                   m_pos;                  // Reference positions
309                 tScalarArray                    m_wgh;                  // Weights
310                 btVector3                               m_com;                  // COM
311                 btMatrix3x3                             m_rot;                  // Rotation
312                 btMatrix3x3                             m_scl;                  // Scale
313                 btMatrix3x3                             m_aqq;                  // Base scaling
314         };
315         /* Cluster              */ 
316         struct  Cluster
317         {
318                 tScalarArray                            m_masses;
319                 btAlignedObjectArray<Node*>     m_nodes;                
320                 tVector3Array                           m_framerefs;
321                 btTransform                                     m_framexform;
322                 btScalar                                        m_idmass;
323                 btScalar                                        m_imass;
324                 btMatrix3x3                                     m_locii;
325                 btMatrix3x3                                     m_invwi;
326                 btVector3                                       m_com;
327                 btVector3                                       m_vimpulses[2];
328                 btVector3                                       m_dimpulses[2];
329                 int                                                     m_nvimpulses;
330                 int                                                     m_ndimpulses;
331                 btVector3                                       m_lv;
332                 btVector3                                       m_av;
333                 btDbvtNode*                                     m_leaf;
334                 btScalar                                        m_ndamping;     /* Node damping         */ 
335                 btScalar                                        m_ldamping;     /* Linear damping       */ 
336                 btScalar                                        m_adamping;     /* Angular damping      */ 
337                 btScalar                                        m_matching;
338                 btScalar                                        m_maxSelfCollisionImpulse;
339                 btScalar                                        m_selfCollisionImpulseFactor;
340                 bool                                            m_containsAnchor;
341                 bool                                            m_collide;
342                 int                                                     m_clusterIndex;
343                 Cluster() : m_leaf(0),m_ndamping(0),m_ldamping(0),m_adamping(0),m_matching(0) 
344                 ,m_maxSelfCollisionImpulse(100.f),
345                 m_selfCollisionImpulseFactor(0.01f),
346                 m_containsAnchor(false)
347                 {}
348         };
349         /* Impulse              */ 
350         struct  Impulse
351         {
352                 btVector3                                       m_velocity;
353                 btVector3                                       m_drift;
354                 int                                                     m_asVelocity:1;
355                 int                                                     m_asDrift:1;
356                 Impulse() : m_velocity(0,0,0),m_drift(0,0,0),m_asVelocity(0),m_asDrift(0)       {}
357                 Impulse                                         operator -() const
358                 {
359                         Impulse i=*this;
360                         i.m_velocity=-i.m_velocity;
361                         i.m_drift=-i.m_drift;
362                         return(i);
363                 }
364                 Impulse                                         operator*(btScalar x) const
365                 {
366                         Impulse i=*this;
367                         i.m_velocity*=x;
368                         i.m_drift*=x;
369                         return(i);
370                 }
371         };
372         /* Body                 */ 
373         struct  Body
374         {
375                 Cluster*                        m_soft;
376                 btRigidBody*            m_rigid;
377                 btCollisionObject*      m_collisionObject;
378
379                 Body() : m_soft(0),m_rigid(0),m_collisionObject(0)                              {}
380                 Body(Cluster* p) : m_soft(p),m_rigid(0),m_collisionObject(0)    {}
381                 Body(btCollisionObject* colObj) : m_soft(0),m_collisionObject(colObj)
382                 {
383                         m_rigid = btRigidBody::upcast(m_collisionObject);
384                 }
385
386                 void                                            activate() const
387                 {
388                         if(m_rigid) 
389                                 m_rigid->activate();
390                         if (m_collisionObject)
391                                 m_collisionObject->activate();
392
393                 }
394                 const btMatrix3x3&                      invWorldInertia() const
395                 {
396                         static const btMatrix3x3        iwi(0,0,0,0,0,0,0,0,0);
397                         if(m_rigid) return(m_rigid->getInvInertiaTensorWorld());
398                         if(m_soft)      return(m_soft->m_invwi);
399                         return(iwi);
400                 }
401                 btScalar                                        invMass() const
402                 {
403                         if(m_rigid) return(m_rigid->getInvMass());
404                         if(m_soft)      return(m_soft->m_imass);
405                         return(0);
406                 }
407                 const btTransform&                      xform() const
408                 {
409                         static const btTransform        identity=btTransform::getIdentity();            
410                         if(m_collisionObject) return(m_collisionObject->getWorldTransform());
411                         if(m_soft)      return(m_soft->m_framexform);
412                         return(identity);
413                 }
414                 btVector3                                       linearVelocity() const
415                 {
416                         if(m_rigid) return(m_rigid->getLinearVelocity());
417                         if(m_soft)      return(m_soft->m_lv);
418                         return(btVector3(0,0,0));
419                 }
420                 btVector3                                       angularVelocity(const btVector3& rpos) const
421                 {                       
422                         if(m_rigid) return(btCross(m_rigid->getAngularVelocity(),rpos));
423                         if(m_soft)      return(btCross(m_soft->m_av,rpos));
424                         return(btVector3(0,0,0));
425                 }
426                 btVector3                                       angularVelocity() const
427                 {                       
428                         if(m_rigid) return(m_rigid->getAngularVelocity());
429                         if(m_soft)      return(m_soft->m_av);
430                         return(btVector3(0,0,0));
431                 }
432                 btVector3                                       velocity(const btVector3& rpos) const
433                 {
434                         return(linearVelocity()+angularVelocity(rpos));
435                 }
436                 void                                            applyVImpulse(const btVector3& impulse,const btVector3& rpos) const
437                 {
438                         if(m_rigid)     m_rigid->applyImpulse(impulse,rpos);
439                         if(m_soft)      btSoftBody::clusterVImpulse(m_soft,rpos,impulse);
440                 }
441                 void                                            applyDImpulse(const btVector3& impulse,const btVector3& rpos) const
442                 {
443                         if(m_rigid)     m_rigid->applyImpulse(impulse,rpos);
444                         if(m_soft)      btSoftBody::clusterDImpulse(m_soft,rpos,impulse);
445                 }               
446                 void                                            applyImpulse(const Impulse& impulse,const btVector3& rpos) const
447                 {
448                         if(impulse.m_asVelocity)        
449                         {
450 //                              printf("impulse.m_velocity = %f,%f,%f\n",impulse.m_velocity.getX(),impulse.m_velocity.getY(),impulse.m_velocity.getZ());
451                                 applyVImpulse(impulse.m_velocity,rpos);
452                         }
453                         if(impulse.m_asDrift)           
454                         {
455 //                              printf("impulse.m_drift = %f,%f,%f\n",impulse.m_drift.getX(),impulse.m_drift.getY(),impulse.m_drift.getZ());
456                                 applyDImpulse(impulse.m_drift,rpos);
457                         }
458                 }
459                 void                                            applyVAImpulse(const btVector3& impulse) const
460                 {
461                         if(m_rigid)     m_rigid->applyTorqueImpulse(impulse);
462                         if(m_soft)      btSoftBody::clusterVAImpulse(m_soft,impulse);
463                 }
464                 void                                            applyDAImpulse(const btVector3& impulse) const
465                 {
466                         if(m_rigid)     m_rigid->applyTorqueImpulse(impulse);
467                         if(m_soft)      btSoftBody::clusterDAImpulse(m_soft,impulse);
468                 }
469                 void                                            applyAImpulse(const Impulse& impulse) const
470                 {
471                         if(impulse.m_asVelocity)        applyVAImpulse(impulse.m_velocity);
472                         if(impulse.m_asDrift)           applyDAImpulse(impulse.m_drift);
473                 }
474                 void                                            applyDCImpulse(const btVector3& impulse) const
475                 {
476                         if(m_rigid)     m_rigid->applyCentralImpulse(impulse);
477                         if(m_soft)      btSoftBody::clusterDCImpulse(m_soft,impulse);
478                 }
479         };
480         /* Joint                */ 
481         struct  Joint
482         {
483                 struct eType { enum _ {
484                         Linear=0,
485                         Angular,
486                         Contact
487                 };};
488                 struct Specs
489                 {
490                         Specs() : erp(1),cfm(1),split(1) {}
491                         btScalar        erp;
492                         btScalar        cfm;
493                         btScalar        split;
494                 };
495                 Body                                            m_bodies[2];
496                 btVector3                                       m_refs[2];
497                 btScalar                                        m_cfm;
498                 btScalar                                        m_erp;
499                 btScalar                                        m_split;
500                 btVector3                                       m_drift;
501                 btVector3                                       m_sdrift;
502                 btMatrix3x3                                     m_massmatrix;
503                 bool                                            m_delete;
504                 virtual                                         ~Joint() {}
505                 Joint() : m_delete(false) {}
506                 virtual void                            Prepare(btScalar dt,int iterations);
507                 virtual void                            Solve(btScalar dt,btScalar sor)=0;
508                 virtual void                            Terminate(btScalar dt)=0;
509                 virtual eType::_                        Type() const=0;
510         };
511         /* LJoint               */ 
512         struct  LJoint : Joint
513         {
514                 struct Specs : Joint::Specs
515                 {
516                         btVector3       position;
517                 };              
518                 btVector3                                       m_rpos[2];
519                 void                                            Prepare(btScalar dt,int iterations);
520                 void                                            Solve(btScalar dt,btScalar sor);
521                 void                                            Terminate(btScalar dt);
522                 eType::_                                        Type() const { return(eType::Linear); }
523         };
524         /* AJoint               */ 
525         struct  AJoint : Joint
526         {
527                 struct IControl
528                 {
529                         virtual void                    Prepare(AJoint*)                                {}
530                         virtual btScalar                Speed(AJoint*,btScalar current) { return(current); }
531                         static IControl*                Default()                                               { static IControl def;return(&def); }
532                 };
533                 struct Specs : Joint::Specs
534                 {
535                         Specs() : icontrol(IControl::Default()) {}
536                         btVector3       axis;
537                         IControl*       icontrol;
538                 };              
539                 btVector3                                       m_axis[2];
540                 IControl*                                       m_icontrol;
541                 void                                            Prepare(btScalar dt,int iterations);
542                 void                                            Solve(btScalar dt,btScalar sor);
543                 void                                            Terminate(btScalar dt);
544                 eType::_                                        Type() const { return(eType::Angular); }
545         };
546         /* CJoint               */ 
547         struct  CJoint : Joint
548         {               
549                 int                                                     m_life;
550                 int                                                     m_maxlife;
551                 btVector3                                       m_rpos[2];
552                 btVector3                                       m_normal;
553                 btScalar                                        m_friction;
554                 void                                            Prepare(btScalar dt,int iterations);
555                 void                                            Solve(btScalar dt,btScalar sor);
556                 void                                            Terminate(btScalar dt);
557                 eType::_                                        Type() const { return(eType::Contact); }
558         };
559         /* Config               */ 
560         struct  Config
561         {
562                 eAeroModel::_                   aeromodel;              // Aerodynamic model (default: V_Point)
563                 btScalar                                kVCF;                   // Velocities correction factor (Baumgarte)
564                 btScalar                                kDP;                    // Damping coefficient [0,1]
565                 btScalar                                kDG;                    // Drag coefficient [0,+inf]
566                 btScalar                                kLF;                    // Lift coefficient [0,+inf]
567                 btScalar                                kPR;                    // Pressure coefficient [-inf,+inf]
568                 btScalar                                kVC;                    // Volume conversation coefficient [0,+inf]
569                 btScalar                                kDF;                    // Dynamic friction coefficient [0,1]
570                 btScalar                                kMT;                    // Pose matching coefficient [0,1]              
571                 btScalar                                kCHR;                   // Rigid contacts hardness [0,1]
572                 btScalar                                kKHR;                   // Kinetic contacts hardness [0,1]
573                 btScalar                                kSHR;                   // Soft contacts hardness [0,1]
574                 btScalar                                kAHR;                   // Anchors hardness [0,1]
575                 btScalar                                kSRHR_CL;               // Soft vs rigid hardness [0,1] (cluster only)
576                 btScalar                                kSKHR_CL;               // Soft vs kinetic hardness [0,1] (cluster only)
577                 btScalar                                kSSHR_CL;               // Soft vs soft hardness [0,1] (cluster only)
578                 btScalar                                kSR_SPLT_CL;    // Soft vs rigid impulse split [0,1] (cluster only)
579                 btScalar                                kSK_SPLT_CL;    // Soft vs rigid impulse split [0,1] (cluster only)
580                 btScalar                                kSS_SPLT_CL;    // Soft vs rigid impulse split [0,1] (cluster only)
581                 btScalar                                maxvolume;              // Maximum volume ratio for pose
582                 btScalar                                timescale;              // Time scale
583                 int                                             viterations;    // Velocities solver iterations
584                 int                                             piterations;    // Positions solver iterations
585                 int                                             diterations;    // Drift solver iterations
586                 int                                             citerations;    // Cluster solver iterations
587                 int                                             collisions;             // Collisions flags
588                 tVSolverArray                   m_vsequence;    // Velocity solvers sequence
589                 tPSolverArray                   m_psequence;    // Position solvers sequence
590                 tPSolverArray                   m_dsequence;    // Drift solvers sequence
591         };
592         /* SolverState  */ 
593         struct  SolverState
594         {
595                 btScalar                                sdt;                    // dt*timescale
596                 btScalar                                isdt;                   // 1/sdt
597                 btScalar                                velmrg;                 // velocity margin
598                 btScalar                                radmrg;                 // radial margin
599                 btScalar                                updmrg;                 // Update margin
600         };      
601         /// RayFromToCaster takes a ray from, ray to (instead of direction!)
602         struct  RayFromToCaster : btDbvt::ICollide
603         {
604                 btVector3                       m_rayFrom;
605                 btVector3                       m_rayTo;
606                 btVector3                       m_rayNormalizedDirection;
607                 btScalar                        m_mint;
608                 Face*                           m_face;
609                 int                                     m_tests;
610                 RayFromToCaster(const btVector3& rayFrom,const btVector3& rayTo,btScalar mxt);
611                 void                                    Process(const btDbvtNode* leaf);
612
613                 static inline btScalar  rayFromToTriangle(const btVector3& rayFrom,
614                         const btVector3& rayTo,
615                         const btVector3& rayNormalizedDirection,
616                         const btVector3& a,
617                         const btVector3& b,
618                         const btVector3& c,
619                         btScalar maxt=SIMD_INFINITY);
620         };
621
622         //
623         // Typedefs
624         //
625
626         typedef void                                                            (*psolver_t)(btSoftBody*,btScalar,btScalar);
627         typedef void                                                            (*vsolver_t)(btSoftBody*,btScalar);
628         typedef btAlignedObjectArray<Cluster*>          tClusterArray;
629         typedef btAlignedObjectArray<Note>                      tNoteArray;
630         typedef btAlignedObjectArray<Node>                      tNodeArray;
631         typedef btAlignedObjectArray<btDbvtNode*>       tLeafArray;
632         typedef btAlignedObjectArray<Link>                      tLinkArray;
633         typedef btAlignedObjectArray<Face>                      tFaceArray;
634         typedef btAlignedObjectArray<Tetra>                     tTetraArray;
635         typedef btAlignedObjectArray<Anchor>            tAnchorArray;
636         typedef btAlignedObjectArray<RContact>          tRContactArray;
637         typedef btAlignedObjectArray<SContact>          tSContactArray;
638         typedef btAlignedObjectArray<Material*>         tMaterialArray;
639         typedef btAlignedObjectArray<Joint*>            tJointArray;
640         typedef btAlignedObjectArray<btSoftBody*>       tSoftBodyArray; 
641
642         //
643         // Fields
644         //
645
646         Config                                  m_cfg;                  // Configuration
647         SolverState                             m_sst;                  // Solver state
648         Pose                                    m_pose;                 // Pose
649         void*                                   m_tag;                  // User data
650         btSoftBodyWorldInfo*    m_worldInfo;    // World info
651         tNoteArray                              m_notes;                // Notes
652         tNodeArray                              m_nodes;                // Nodes
653         tLinkArray                              m_links;                // Links
654         tFaceArray                              m_faces;                // Faces
655         tTetraArray                             m_tetras;               // Tetras
656         tAnchorArray                    m_anchors;              // Anchors
657         tRContactArray                  m_rcontacts;    // Rigid contacts
658         tSContactArray                  m_scontacts;    // Soft contacts
659         tJointArray                             m_joints;               // Joints
660         tMaterialArray                  m_materials;    // Materials
661         btScalar                                m_timeacc;              // Time accumulator
662         btVector3                               m_bounds[2];    // Spatial bounds       
663         bool                                    m_bUpdateRtCst; // Update runtime constants
664         btDbvt                                  m_ndbvt;                // Nodes tree
665         btDbvt                                  m_fdbvt;                // Faces tree
666         btDbvt                                  m_cdbvt;                // Clusters tree
667         tClusterArray                   m_clusters;             // Clusters
668
669         btAlignedObjectArray<bool>m_clusterConnectivity;//cluster connectivity, for self-collision
670
671         btTransform                     m_initialWorldTransform;
672
673         btVector3                       m_windVelocity;
674         //
675         // Api
676         //
677
678         /* ctor                                                                                                                                 */ 
679         btSoftBody(     btSoftBodyWorldInfo* worldInfo,int node_count,          const btVector3* x,             const btScalar* m);
680
681         /* ctor                                                                                                                                 */ 
682         btSoftBody(     btSoftBodyWorldInfo* worldInfo);
683
684         void    initDefaults();
685
686         /* dtor                                                                                                                                 */ 
687         virtual ~btSoftBody();
688         /* Check for existing link                                                                                              */ 
689
690         btAlignedObjectArray<int>       m_userIndexMapping;
691
692         btSoftBodyWorldInfo*    getWorldInfo()
693         {
694                 return m_worldInfo;
695         }
696
697         ///@todo: avoid internal softbody shape hack and move collision code to collision library
698         virtual void    setCollisionShape(btCollisionShape* collisionShape)
699         {
700                 
701         }
702
703         bool                            checkLink(      int node0,
704                 int node1) const;
705         bool                            checkLink(      const Node* node0,
706                 const Node* node1) const;
707         /* Check for existring face                                                                                             */ 
708         bool                            checkFace(      int node0,
709                 int node1,
710                 int node2) const;
711         /* Append material                                                                                                              */ 
712         Material*                       appendMaterial();
713         /* Append note                                                                                                                  */ 
714         void                            appendNote(     const char* text,
715                 const btVector3& o,
716                 const btVector4& c=btVector4(1,0,0,0),
717                 Node* n0=0,
718                 Node* n1=0,
719                 Node* n2=0,
720                 Node* n3=0);
721         void                            appendNote(     const char* text,
722                 const btVector3& o,
723                 Node* feature);
724         void                            appendNote(     const char* text,
725                 const btVector3& o,
726                 Link* feature);
727         void                            appendNote(     const char* text,
728                 const btVector3& o,
729                 Face* feature);
730         /* Append node                                                                                                                  */ 
731         void                            appendNode(     const btVector3& x,btScalar m);
732         /* Append link                                                                                                                  */ 
733         void                            appendLink(int model=-1,Material* mat=0);
734         void                            appendLink(     int node0,
735                 int node1,
736                 Material* mat=0,
737                 bool bcheckexist=false);
738         void                            appendLink(     Node* node0,
739                 Node* node1,
740                 Material* mat=0,
741                 bool bcheckexist=false);
742         /* Append face                                                                                                                  */ 
743         void                            appendFace(int model=-1,Material* mat=0);
744         void                            appendFace(     int node0,
745                 int node1,
746                 int node2,
747                 Material* mat=0);
748         void                    appendTetra(int model,Material* mat);
749         //
750         void                    appendTetra(int node0,
751                                                                                 int node1,
752                                                                                 int node2,
753                                                                                 int node3,
754                                                                                 Material* mat=0);
755
756
757         /* Append anchor                                                                                                                */ 
758         void                            appendAnchor(   int node,
759                 btRigidBody* body, bool disableCollisionBetweenLinkedBodies=false,btScalar influence = 1);
760         void                    appendAnchor(int node,btRigidBody* body, const btVector3& localPivot,bool disableCollisionBetweenLinkedBodies=false,btScalar influence = 1);
761         /* Append linear joint                                                                                                  */ 
762         void                            appendLinearJoint(const LJoint::Specs& specs,Cluster* body0,Body body1);
763         void                            appendLinearJoint(const LJoint::Specs& specs,Body body=Body());
764         void                            appendLinearJoint(const LJoint::Specs& specs,btSoftBody* body);
765         /* Append linear joint                                                                                                  */ 
766         void                            appendAngularJoint(const AJoint::Specs& specs,Cluster* body0,Body body1);
767         void                            appendAngularJoint(const AJoint::Specs& specs,Body body=Body());
768         void                            appendAngularJoint(const AJoint::Specs& specs,btSoftBody* body);
769         /* Add force (or gravity) to the entire body                                                    */ 
770         void                            addForce(               const btVector3& force);
771         /* Add force (or gravity) to a node of the body                                                 */ 
772         void                            addForce(               const btVector3& force,
773                 int node);
774         /* Add aero force to a node of the body */
775         void                        addAeroForceToNode(const btVector3& windVelocity,int nodeIndex);
776
777         /* Add aero force to a face of the body */
778         void                        addAeroForceToFace(const btVector3& windVelocity,int faceIndex);
779
780         /* Add velocity to the entire body                                                                              */ 
781         void                            addVelocity(    const btVector3& velocity);
782
783         /* Set velocity for the entire body                                                                             */ 
784         void                            setVelocity(    const btVector3& velocity);
785
786         /* Add velocity to a node of the body                                                                   */ 
787         void                            addVelocity(    const btVector3& velocity,
788                 int node);
789         /* Set mass                                                                                                                             */ 
790         void                            setMass(                int node,
791                 btScalar mass);
792         /* Get mass                                                                                                                             */ 
793         btScalar                        getMass(                int node) const;
794         /* Get total mass                                                                                                               */ 
795         btScalar                        getTotalMass() const;
796         /* Set total mass (weighted by previous masses)                                                 */ 
797         void                            setTotalMass(   btScalar mass,
798                 bool fromfaces=false);
799         /* Set total density                                                                                                    */ 
800         void                            setTotalDensity(btScalar density);
801         /* Set volume mass (using tetrahedrons)                                                                 */
802         void                            setVolumeMass(          btScalar mass);
803         /* Set volume density (using tetrahedrons)                                                              */
804         void                            setVolumeDensity(       btScalar density);
805         /* Transform                                                                                                                    */ 
806         void                            transform(              const btTransform& trs);
807         /* Translate                                                                                                                    */ 
808         void                            translate(              const btVector3& trs);
809         /* Rotate                                                                                                                       */ 
810         void                            rotate( const btQuaternion& rot);
811         /* Scale                                                                                                                                */ 
812         void                            scale(  const btVector3& scl);
813         /* Set current state as pose                                                                                    */ 
814         void                            setPose(                bool bvolume,
815                 bool bframe);
816         /* Return the volume                                                                                                    */ 
817         btScalar                        getVolume() const;
818         /* Cluster count                                                                                                                */ 
819         int                                     clusterCount() const;
820         /* Cluster center of mass                                                                                               */ 
821         static btVector3        clusterCom(const Cluster* cluster);
822         btVector3                       clusterCom(int cluster) const;
823         /* Cluster velocity at rpos                                                                                             */ 
824         static btVector3        clusterVelocity(const Cluster* cluster,const btVector3& rpos);
825         /* Cluster impulse                                                                                                              */ 
826         static void                     clusterVImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse);
827         static void                     clusterDImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse);
828         static void                     clusterImpulse(Cluster* cluster,const btVector3& rpos,const Impulse& impulse);
829         static void                     clusterVAImpulse(Cluster* cluster,const btVector3& impulse);
830         static void                     clusterDAImpulse(Cluster* cluster,const btVector3& impulse);
831         static void                     clusterAImpulse(Cluster* cluster,const Impulse& impulse);
832         static void                     clusterDCImpulse(Cluster* cluster,const btVector3& impulse);
833         /* Generate bending constraints based on distance in the adjency graph  */ 
834         int                                     generateBendingConstraints(     int distance,
835                 Material* mat=0);
836         /* Randomize constraints to reduce solver bias                                                  */ 
837         void                            randomizeConstraints();
838         /* Release clusters                                                                                                             */ 
839         void                            releaseCluster(int index);
840         void                            releaseClusters();
841         /* Generate clusters (K-mean)                                                                                   */ 
842         ///generateClusters with k=0 will create a convex cluster for each tetrahedron or triangle
843         ///otherwise an approximation will be used (better performance)
844         int                                     generateClusters(int k,int maxiterations=8192);
845         /* Refine                                                                                                                               */ 
846         void                            refine(ImplicitFn* ifn,btScalar accurary,bool cut);
847         /* CutLink                                                                                                                              */ 
848         bool                            cutLink(int node0,int node1,btScalar position);
849         bool                            cutLink(const Node* node0,const Node* node1,btScalar position);
850
851         ///Ray casting using rayFrom and rayTo in worldspace, (not direction!)
852         bool                            rayTest(const btVector3& rayFrom,
853                 const btVector3& rayTo,
854                 sRayCast& results);
855         /* Solver presets                                                                                                               */ 
856         void                            setSolver(eSolverPresets::_ preset);
857         /* predictMotion                                                                                                                */ 
858         void                            predictMotion(btScalar dt);
859         /* solveConstraints                                                                                                             */ 
860         void                            solveConstraints();
861         /* staticSolve                                                                                                                  */ 
862         void                            staticSolve(int iterations);
863         /* solveCommonConstraints                                                                                               */ 
864         static void                     solveCommonConstraints(btSoftBody** bodies,int count,int iterations);
865         /* solveClusters                                                                                                                */ 
866         static void                     solveClusters(const btAlignedObjectArray<btSoftBody*>& bodies);
867         /* integrateMotion                                                                                                              */ 
868         void                            integrateMotion();
869         /* defaultCollisionHandlers                                                                                             */ 
870         void                            defaultCollisionHandler(btCollisionObject* pco);
871         void                            defaultCollisionHandler(btSoftBody* psb);
872
873
874
875         //
876         // Functionality to deal with new accelerated solvers.
877         //
878
879         /**
880          * Set a wind velocity for interaction with the air.
881          */
882         void setWindVelocity( const btVector3 &velocity );
883
884
885         /**
886          * Return the wind velocity for interaction with the air.
887          */
888         const btVector3& getWindVelocity();
889
890         //
891         // Set the solver that handles this soft body
892         // Should not be allowed to get out of sync with reality
893         // Currently called internally on addition to the world
894         void setSoftBodySolver( btSoftBodySolver *softBodySolver )
895         {
896                 m_softBodySolver = softBodySolver;
897         }
898
899         //
900         // Return the solver that handles this soft body
901         // 
902         btSoftBodySolver *getSoftBodySolver()
903         {
904                 return m_softBodySolver;
905         }
906
907         //
908         // Return the solver that handles this soft body
909         // 
910         btSoftBodySolver *getSoftBodySolver() const
911         {
912                 return m_softBodySolver;
913         }
914
915
916         //
917         // Cast
918         //
919
920         static const btSoftBody*        upcast(const btCollisionObject* colObj)
921         {
922                 if (colObj->getInternalType()==CO_SOFT_BODY)
923                         return (const btSoftBody*)colObj;
924                 return 0;
925         }
926         static btSoftBody*                      upcast(btCollisionObject* colObj)
927         {
928                 if (colObj->getInternalType()==CO_SOFT_BODY)
929                         return (btSoftBody*)colObj;
930                 return 0;
931         }
932
933         //
934         // ::btCollisionObject
935         //
936
937         virtual void getAabb(btVector3& aabbMin,btVector3& aabbMax) const
938         {
939                 aabbMin = m_bounds[0];
940                 aabbMax = m_bounds[1];
941         }
942         //
943         // Private
944         //
945         void                            pointersToIndices();
946         void                            indicesToPointers(const int* map=0);
947
948         int                                     rayTest(const btVector3& rayFrom,const btVector3& rayTo,
949                 btScalar& mint,eFeature::_& feature,int& index,bool bcountonly) const;
950         void                            initializeFaceTree();
951         btVector3                       evaluateCom() const;
952         bool                            checkContact(btCollisionObject* colObj,const btVector3& x,btScalar margin,btSoftBody::sCti& cti) const;
953         void                            updateNormals();
954         void                            updateBounds();
955         void                            updatePose();
956         void                            updateConstants();
957         void                            initializeClusters();
958         void                            updateClusters();
959         void                            cleanupClusters();
960         void                            prepareClusters(int iterations);
961         void                            solveClusters(btScalar sor);
962         void                            applyClusters(bool drift);
963         void                            dampClusters();
964         void                            applyForces();  
965         static void                     PSolve_Anchors(btSoftBody* psb,btScalar kst,btScalar ti);
966         static void                     PSolve_RContacts(btSoftBody* psb,btScalar kst,btScalar ti);
967         static void                     PSolve_SContacts(btSoftBody* psb,btScalar,btScalar ti);
968         static void                     PSolve_Links(btSoftBody* psb,btScalar kst,btScalar ti);
969         static void                     VSolve_Links(btSoftBody* psb,btScalar kst);
970         static psolver_t        getSolver(ePSolver::_ solver);
971         static vsolver_t        getSolver(eVSolver::_ solver);
972
973
974         virtual int     calculateSerializeBufferSize()  const;
975
976         ///fills the dataBuffer and returns the struct name (and 0 on failure)
977         virtual const char*     serialize(void* dataBuffer,  class btSerializer* serializer) const;
978
979         //virtual void serializeSingleObject(class btSerializer* serializer) const;
980
981
982 };
983
984
985
986
987 #endif //_BT_SOFT_BODY_H