fix memleak in BGE py api - action.channelNames
[blender.git] / source / blender / blenkernel / intern / softbody.c
1 /*  softbody.c      
2  * 
3  * $Id$
4  *
5  * ***** BEGIN GPL LICENSE BLOCK *****
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software Foundation,
19  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20  *
21  * The Original Code is Copyright (C) Blender Foundation
22  * All rights reserved.
23  *
24  * The Original Code is: all of this file.
25  *
26  * Contributor(s): none yet.
27  *
28  * ***** END GPL LICENSE BLOCK *****
29  */
30
31 /*
32 ******
33 variables on the UI for now
34
35         float mediafrict;  friction to env 
36         float nodemass;   softbody mass of *vertex* 
37         float grav;        softbody amount of gravitaion to apply 
38         
39         float goalspring;  softbody goal springs 
40         float goalfrict;   softbody goal springs friction 
41         float mingoal;     quick limits for goal 
42         float maxgoal;
43
44         float inspring;   softbody inner springs 
45         float infrict;     softbody inner springs friction 
46
47 *****
48 */
49
50
51 #include <math.h>
52 #include <stdlib.h>
53 #include <string.h>
54
55 #include "MEM_guardedalloc.h"
56
57 /* types */
58 #include "DNA_curve_types.h"
59 #include "DNA_object_types.h"
60 #include "DNA_object_force.h"   /* here is the softbody struct */
61 #include "DNA_particle_types.h"
62 #include "DNA_key_types.h"
63 #include "DNA_mesh_types.h"
64 #include "DNA_meshdata_types.h"
65 #include "DNA_modifier_types.h"
66 #include "DNA_lattice_types.h"
67 #include "DNA_scene_types.h"
68
69 #include "BLI_blenlib.h"
70 #include "BLI_arithb.h"
71 #include "BLI_ghash.h"
72 #include "BLI_threads.h"
73
74 #include "BKE_curve.h"
75 #include "BKE_effect.h"
76 #include "BKE_global.h"
77 #include "BKE_key.h"
78 #include "BKE_object.h"
79 #include "BKE_particle.h"
80 #include "BKE_softbody.h"
81 #include "BKE_utildefines.h"
82 #include "BKE_DerivedMesh.h"
83 #include "BKE_pointcache.h"
84 #include "BKE_modifier.h"
85 #include "BKE_deform.h"
86 #include  "BIF_editdeform.h"
87 #include  "BIF_graphics.h"
88 #include  "PIL_time.h"
89 // #include  "ONL_opennl.h" remove linking to ONL for now
90
91 /* callbacks for errors and interrupts and some goo */
92 static int (*SB_localInterruptCallBack)(void) = NULL;
93
94
95 /* ********** soft body engine ******* */
96
97
98 typedef struct BodySpring {
99         int v1, v2;
100         float len, strength, cf,load;
101         float ext_force[3]; /* edges colliding and sailing */
102         short order;
103         short flag;
104 } BodySpring;
105
106 typedef struct BodyFace {
107         int v1, v2, v3 ,v4;
108         float ext_force[3]; /* faces colliding */
109         short flag;
110 } BodyFace;
111
112
113 /*private scratch pad for caching and other data only needed when alive*/
114 typedef struct SBScratch {
115         GHash *colliderhash;
116         short needstobuildcollider;
117         short flag;
118         BodyFace *bodyface;
119         int totface;
120         float aabbmin[3],aabbmax[3];
121 }SBScratch;
122
123 typedef struct  SB_thread_context{
124         Object *ob;
125                 float forcetime;
126                 float timenow;
127                 int ifirst;
128                 int ilast;
129                 ListBase *do_effector;
130                 int do_deflector;
131                 float fieldfactor;
132                 float windfactor;
133                 int nr;
134                 int tot;
135 }SB_thread_context;
136
137 #define NLF_BUILD  1 
138 #define NLF_SOLVE  2 
139
140 #define MID_PRESERVE 1
141
142 #define SOFTGOALSNAP  0.999f 
143 /* if bp-> goal is above make it a *forced follow original* and skip all ODE stuff for this bp
144    removes *unnecessary* stiffnes from ODE system
145 */
146 #define HEUNWARNLIMIT 1 /* 500 would be fine i think for detecting severe *stiff* stuff */
147
148
149 #define BSF_INTERSECT   1 /* edge intersects collider face */
150 #define SBF_DOFUZZY     1 /* edge intersects collider face */
151
152 #define BFF_INTERSECT   1 /* collider edge   intrudes face */
153 #define BFF_CLOSEVERT   2 /* collider vertex repulses face */
154
155
156 float SoftHeunTol = 1.0f; /* humm .. this should be calculated from sb parameters and sizes */
157
158 /* local prototypes */
159 static void free_softbody_intern(SoftBody *sb);
160 /* aye this belongs to arith.c */
161 static void Vec3PlusStVec(float *v, float s, float *v1);
162
163 /*+++ frame based timing +++*/
164
165 /*physical unit of force is [kg * m / sec^2]*/
166
167 static float sb_grav_force_scale(Object *ob)
168 /* since unit of g is [m/sec^2] and F = mass * g we rescale unit mass of node to 1 gramm
169   put it to a function here, so we can add user options later without touching simulation code
170 */
171 {
172         return (0.001f);
173 }
174
175 static float sb_fric_force_scale(Object *ob)
176 /* rescaling unit of drag [1 / sec] to somehow reasonable
177   put it to a function here, so we can add user options later without touching simulation code
178 */
179 {
180         return (0.01f);
181 }
182
183 static float sb_time_scale(Object *ob)
184 /* defining the frames to *real* time relation */
185 {
186         SoftBody *sb= ob->soft; /* is supposed to be there */
187         if (sb){
188                 return(sb->physics_speed); 
189                 /*hrms .. this could be IPO as well :) 
190                  estimated range [0.001 sluggish slug - 100.0 very fast (i hope ODE solver can handle that)]
191                  1 approx = a unit 1 pendulum at g = 9.8 [earth conditions]  has period 65 frames
192          theory would give a 50 frames period .. so there must be something inaccurate .. looking for that (BM) 
193                  */
194         }
195         return (1.0f);
196         /* 
197         this would be frames/sec independant timing assuming 25 fps is default
198         but does not work very well with NLA
199                 return (25.0f/G.scene->r.frs_sec)
200         */
201 }
202 /*--- frame based timing ---*/
203
204 /*+++ collider caching and dicing +++*/
205
206 /********************
207 for each target object/face the axis aligned bounding box (AABB) is stored
208 faces paralell to global axes 
209 so only simple "value" in [min,max] ckecks are used
210 float operations still
211 */
212
213 /* just an ID here to reduce the prob for killing objects
214 ** ob->sumohandle points to we should not kill :)
215 */ 
216 const int CCD_SAVETY = 190561; 
217
218 typedef struct ccdf_minmax{
219 float minx,miny,minz,maxx,maxy,maxz;
220 }ccdf_minmax;
221
222
223
224 typedef struct ccd_Mesh {
225         int totvert, totface;
226         MVert *mvert;
227         MVert *mprevvert;
228         MFace *mface;
229         int savety;
230         ccdf_minmax *mima;
231         /* Axis Aligned Bounding Box AABB */
232         float bbmin[3];
233         float bbmax[3];
234 }ccd_Mesh;
235
236
237
238
239 static ccd_Mesh *ccd_mesh_make(Object *ob, DerivedMesh *dm)
240 {
241     ccd_Mesh *pccd_M = NULL;
242         ccdf_minmax *mima =NULL;
243         MFace *mface=NULL;
244         float v[3],hull;
245         int i;
246         
247         /* first some paranoia checks */
248         if (!dm) return NULL;
249         if (!dm->getNumVerts(dm) || !dm->getNumFaces(dm)) return NULL;
250         
251         pccd_M = MEM_mallocN(sizeof(ccd_Mesh),"ccd_Mesh");
252         pccd_M->totvert = dm->getNumVerts(dm);
253         pccd_M->totface = dm->getNumFaces(dm);
254         pccd_M->savety  = CCD_SAVETY;
255         pccd_M->bbmin[0]=pccd_M->bbmin[1]=pccd_M->bbmin[2]=1e30f;
256         pccd_M->bbmax[0]=pccd_M->bbmax[1]=pccd_M->bbmax[2]=-1e30f;
257         pccd_M->mprevvert=NULL;
258         
259         
260     /* blow it up with forcefield ranges */
261         hull = MAX2(ob->pd->pdef_sbift,ob->pd->pdef_sboft);
262         
263         /* alloc and copy verts*/
264         pccd_M->mvert = dm->dupVertArray(dm);
265     /* ah yeah, put the verices to global coords once */        
266         /* and determine the ortho BB on the fly */ 
267         for(i=0; i < pccd_M->totvert; i++){
268                 Mat4MulVecfl(ob->obmat, pccd_M->mvert[i].co);
269                 
270         /* evaluate limits */
271                 VECCOPY(v,pccd_M->mvert[i].co);
272                 pccd_M->bbmin[0] = MIN2(pccd_M->bbmin[0],v[0]-hull);
273                 pccd_M->bbmin[1] = MIN2(pccd_M->bbmin[1],v[1]-hull);
274                 pccd_M->bbmin[2] = MIN2(pccd_M->bbmin[2],v[2]-hull);
275                 
276                 pccd_M->bbmax[0] = MAX2(pccd_M->bbmax[0],v[0]+hull);
277                 pccd_M->bbmax[1] = MAX2(pccd_M->bbmax[1],v[1]+hull);
278                 pccd_M->bbmax[2] = MAX2(pccd_M->bbmax[2],v[2]+hull);
279                 
280         }
281         /* alloc and copy faces*/
282     pccd_M->mface = dm->dupFaceArray(dm);
283         
284         /* OBBs for idea1 */
285     pccd_M->mima = MEM_mallocN(sizeof(ccdf_minmax)*pccd_M->totface,"ccd_Mesh_Faces_mima");
286         mima  = pccd_M->mima;
287         mface = pccd_M->mface;
288
289
290         /* anyhoo we need to walk the list of faces and find OBB they live in */
291         for(i=0; i < pccd_M->totface; i++){
292                 mima->minx=mima->miny=mima->minz=1e30f;
293                 mima->maxx=mima->maxy=mima->maxz=-1e30f;
294                 
295         VECCOPY(v,pccd_M->mvert[mface->v1].co);
296                 mima->minx = MIN2(mima->minx,v[0]-hull);
297                 mima->miny = MIN2(mima->miny,v[1]-hull);
298                 mima->minz = MIN2(mima->minz,v[2]-hull);
299                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
300                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
301                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
302                 
303         VECCOPY(v,pccd_M->mvert[mface->v2].co);
304                 mima->minx = MIN2(mima->minx,v[0]-hull);
305                 mima->miny = MIN2(mima->miny,v[1]-hull);
306                 mima->minz = MIN2(mima->minz,v[2]-hull);
307                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
308                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
309                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
310                 
311                 VECCOPY(v,pccd_M->mvert[mface->v3].co);
312                 mima->minx = MIN2(mima->minx,v[0]-hull);
313                 mima->miny = MIN2(mima->miny,v[1]-hull);
314                 mima->minz = MIN2(mima->minz,v[2]-hull);
315                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
316                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
317                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
318         
319                 if(mface->v4){
320                         VECCOPY(v,pccd_M->mvert[mface->v4].co);
321                 mima->minx = MIN2(mima->minx,v[0]-hull);
322                 mima->miny = MIN2(mima->miny,v[1]-hull);
323                 mima->minz = MIN2(mima->minz,v[2]-hull);
324                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
325                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
326                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
327                 }
328
329                 
330         mima++;
331         mface++;
332                 
333         }
334         return pccd_M;
335 }
336 static void ccd_mesh_update(Object *ob,ccd_Mesh *pccd_M, DerivedMesh *dm)
337 {
338         ccdf_minmax *mima =NULL;
339         MFace *mface=NULL;
340         float v[3],hull;
341         int i;
342         
343         /* first some paranoia checks */
344         if (!dm) return ;
345         if (!dm->getNumVerts(dm) || !dm->getNumFaces(dm)) return ;
346
347         if ((pccd_M->totvert != dm->getNumVerts(dm)) ||
348                 (pccd_M->totface != dm->getNumFaces(dm))) return;
349
350         pccd_M->bbmin[0]=pccd_M->bbmin[1]=pccd_M->bbmin[2]=1e30f;
351         pccd_M->bbmax[0]=pccd_M->bbmax[1]=pccd_M->bbmax[2]=-1e30f;
352         
353         
354     /* blow it up with forcefield ranges */
355         hull = MAX2(ob->pd->pdef_sbift,ob->pd->pdef_sboft);
356         
357         /* rotate current to previous */
358         if(pccd_M->mprevvert) MEM_freeN(pccd_M->mprevvert);
359     pccd_M->mprevvert = pccd_M->mvert;
360         /* alloc and copy verts*/
361     pccd_M->mvert = dm->dupVertArray(dm);
362     /* ah yeah, put the verices to global coords once */        
363         /* and determine the ortho BB on the fly */ 
364         for(i=0; i < pccd_M->totvert; i++){
365                 Mat4MulVecfl(ob->obmat, pccd_M->mvert[i].co);
366                 
367         /* evaluate limits */
368                 VECCOPY(v,pccd_M->mvert[i].co);
369                 pccd_M->bbmin[0] = MIN2(pccd_M->bbmin[0],v[0]-hull);
370                 pccd_M->bbmin[1] = MIN2(pccd_M->bbmin[1],v[1]-hull);
371                 pccd_M->bbmin[2] = MIN2(pccd_M->bbmin[2],v[2]-hull);
372                 
373                 pccd_M->bbmax[0] = MAX2(pccd_M->bbmax[0],v[0]+hull);
374                 pccd_M->bbmax[1] = MAX2(pccd_M->bbmax[1],v[1]+hull);
375                 pccd_M->bbmax[2] = MAX2(pccd_M->bbmax[2],v[2]+hull);
376
377         /* evaluate limits */
378                 VECCOPY(v,pccd_M->mprevvert[i].co);
379                 pccd_M->bbmin[0] = MIN2(pccd_M->bbmin[0],v[0]-hull);
380                 pccd_M->bbmin[1] = MIN2(pccd_M->bbmin[1],v[1]-hull);
381                 pccd_M->bbmin[2] = MIN2(pccd_M->bbmin[2],v[2]-hull);
382                 
383                 pccd_M->bbmax[0] = MAX2(pccd_M->bbmax[0],v[0]+hull);
384                 pccd_M->bbmax[1] = MAX2(pccd_M->bbmax[1],v[1]+hull);
385                 pccd_M->bbmax[2] = MAX2(pccd_M->bbmax[2],v[2]+hull);
386                 
387         }
388         
389         mima  = pccd_M->mima;
390         mface = pccd_M->mface;
391
392
393         /* anyhoo we need to walk the list of faces and find OBB they live in */
394         for(i=0; i < pccd_M->totface; i++){
395                 mima->minx=mima->miny=mima->minz=1e30f;
396                 mima->maxx=mima->maxy=mima->maxz=-1e30f;
397                 
398         VECCOPY(v,pccd_M->mvert[mface->v1].co);
399                 mima->minx = MIN2(mima->minx,v[0]-hull);
400                 mima->miny = MIN2(mima->miny,v[1]-hull);
401                 mima->minz = MIN2(mima->minz,v[2]-hull);
402                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
403                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
404                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
405                 
406         VECCOPY(v,pccd_M->mvert[mface->v2].co);
407                 mima->minx = MIN2(mima->minx,v[0]-hull);
408                 mima->miny = MIN2(mima->miny,v[1]-hull);
409                 mima->minz = MIN2(mima->minz,v[2]-hull);
410                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
411                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
412                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
413                 
414                 VECCOPY(v,pccd_M->mvert[mface->v3].co);
415                 mima->minx = MIN2(mima->minx,v[0]-hull);
416                 mima->miny = MIN2(mima->miny,v[1]-hull);
417                 mima->minz = MIN2(mima->minz,v[2]-hull);
418                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
419                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
420                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
421         
422                 if(mface->v4){
423                         VECCOPY(v,pccd_M->mvert[mface->v4].co);
424                 mima->minx = MIN2(mima->minx,v[0]-hull);
425                 mima->miny = MIN2(mima->miny,v[1]-hull);
426                 mima->minz = MIN2(mima->minz,v[2]-hull);
427                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
428                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
429                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
430                 }
431
432
433         VECCOPY(v,pccd_M->mprevvert[mface->v1].co);
434                 mima->minx = MIN2(mima->minx,v[0]-hull);
435                 mima->miny = MIN2(mima->miny,v[1]-hull);
436                 mima->minz = MIN2(mima->minz,v[2]-hull);
437                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
438                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
439                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
440                 
441         VECCOPY(v,pccd_M->mprevvert[mface->v2].co);
442                 mima->minx = MIN2(mima->minx,v[0]-hull);
443                 mima->miny = MIN2(mima->miny,v[1]-hull);
444                 mima->minz = MIN2(mima->minz,v[2]-hull);
445                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
446                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
447                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
448                 
449                 VECCOPY(v,pccd_M->mprevvert[mface->v3].co);
450                 mima->minx = MIN2(mima->minx,v[0]-hull);
451                 mima->miny = MIN2(mima->miny,v[1]-hull);
452                 mima->minz = MIN2(mima->minz,v[2]-hull);
453                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
454                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
455                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
456         
457                 if(mface->v4){
458                         VECCOPY(v,pccd_M->mprevvert[mface->v4].co);
459                 mima->minx = MIN2(mima->minx,v[0]-hull);
460                 mima->miny = MIN2(mima->miny,v[1]-hull);
461                 mima->minz = MIN2(mima->minz,v[2]-hull);
462                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
463                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
464                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
465                 }
466
467                 
468         mima++;
469         mface++;
470                 
471         }
472         return ;
473 }
474
475 static void ccd_mesh_free(ccd_Mesh *ccdm)
476 {
477         if(ccdm && (ccdm->savety == CCD_SAVETY )){ /*make sure we're not nuking objects we don't know*/
478                 MEM_freeN(ccdm->mface);
479                 MEM_freeN(ccdm->mvert);
480                 if (ccdm->mprevvert) MEM_freeN(ccdm->mprevvert);
481                 MEM_freeN(ccdm->mima);
482                 MEM_freeN(ccdm);
483                 ccdm = NULL;
484         }
485 }
486
487 static void ccd_build_deflector_hache(Object *vertexowner,GHash *hash)
488 {
489         Base *base;
490         Object *ob;
491         base= G.scene->base.first;
492         base= G.scene->base.first;
493         if (!hash) return;
494         while (base) {
495                 /*Only proceed for mesh object in same layer */
496                 if(base->object->type==OB_MESH && (base->lay & vertexowner->lay)) {
497                         int particles=0;
498                         ob= base->object;
499                         if((vertexowner) && (ob == vertexowner)) {
500                                 if(vertexowner->soft->particles){
501                                         particles=1;
502                                 }
503                                 else {
504                                         /* if vertexowner is given  we don't want to check collision with owner object */ 
505                                         base = base->next;
506                                         continue;                               
507                                 }
508                         }
509
510                         /*+++ only with deflecting set */
511                         if(ob->pd && ob->pd->deflect && BLI_ghash_lookup(hash, ob) == 0) {
512                                 DerivedMesh *dm= NULL;
513
514                                 if(particles) {
515                                         dm = psys_get_modifier(ob,psys_get_current(ob))->dm;
516                                 }
517                                 else {
518                                         if(ob->softflag & OB_SB_COLLFINAL) /* so maybe someone wants overkill to collide with subsurfed */
519                                                 dm = mesh_get_derived_final(ob, CD_MASK_BAREMESH);
520                                         else
521                                                 dm = mesh_get_derived_deform(ob, CD_MASK_BAREMESH);
522                                 }
523
524                                 if(dm){
525                                         ccd_Mesh *ccdmesh = ccd_mesh_make(ob, dm);
526                                         BLI_ghash_insert(hash, ob, ccdmesh);
527
528                                         /* we did copy & modify all we need so give 'em away again */
529                                         dm->release(dm);
530                                         
531                                 }
532                         }/*--- only with deflecting set */
533
534                 }/* mesh && layer*/             
535            base = base->next;
536         } /* while (base) */
537 }
538
539 static void ccd_update_deflector_hache(Object *vertexowner,GHash *hash)
540 {
541         Base *base;
542         Object *ob;
543         base= G.scene->base.first;
544         base= G.scene->base.first;
545         if ((!hash) || (!vertexowner)) return;
546         while (base) {
547                 /*Only proceed for mesh object in same layer */
548                 if(base->object->type==OB_MESH && (base->lay & vertexowner->lay)) {
549                         ob= base->object;
550                         if(ob == vertexowner){ 
551                                 /* if vertexowner is given  we don't want to check collision with owner object */ 
552                                 base = base->next;
553                                 continue;                               
554                         }
555
556                         /*+++ only with deflecting set */
557                         if(ob->pd && ob->pd->deflect) {
558                                 DerivedMesh *dm= NULL;
559                                 
560                                 if(ob->softflag & OB_SB_COLLFINAL) { /* so maybe someone wants overkill to collide with subsurfed */
561                                         dm = mesh_get_derived_final(ob, CD_MASK_BAREMESH);
562                                 } else {
563                                         dm = mesh_get_derived_deform(ob, CD_MASK_BAREMESH);
564                                 }
565                                 if(dm){
566                                         ccd_Mesh *ccdmesh = BLI_ghash_lookup(hash,ob);
567                                         if (ccdmesh)
568                                                 ccd_mesh_update(ob,ccdmesh,dm);
569
570                                         /* we did copy & modify all we need so give 'em away again */
571                                         dm->release(dm);
572                                 }
573                         }/*--- only with deflecting set */
574
575                 }/* mesh && layer*/             
576            base = base->next;
577         } /* while (base) */
578 }
579
580
581
582
583 /*--- collider caching and dicing ---*/
584
585
586 static int count_mesh_quads(Mesh *me)
587 {
588         int a,result = 0;
589         MFace *mface= me->mface;
590         
591         if(mface) {
592                 for(a=me->totface; a>0; a--, mface++) {
593                         if(mface->v4) result++;
594                 }
595         }       
596         return result;
597 }
598
599 static void add_mesh_quad_diag_springs(Object *ob)
600 {
601         Mesh *me= ob->data;
602         MFace *mface= me->mface;
603         BodyPoint *bp;
604         BodySpring *bs, *bs_new;
605         int a ;
606         
607         if (ob->soft){
608                 int nofquads;
609                 float s_shear = ob->soft->shearstiff*ob->soft->shearstiff;
610                 
611                 nofquads = count_mesh_quads(me);
612                 if (nofquads) {
613                         /* resize spring-array to hold additional quad springs */
614                         bs_new= MEM_callocN( (ob->soft->totspring + nofquads *2 )*sizeof(BodySpring), "bodyspring");
615                         memcpy(bs_new,ob->soft->bspring,(ob->soft->totspring )*sizeof(BodySpring));
616                         
617                         if(ob->soft->bspring)
618                                 MEM_freeN(ob->soft->bspring); /* do this before reassigning the pointer  or have a 1st class memory leak */
619                         ob->soft->bspring = bs_new; 
620                         
621                         /* fill the tail */
622                         a = 0;
623                         bs = bs_new+ob->soft->totspring;
624                         bp= ob->soft->bpoint;
625                         if(mface ) {
626                                 for(a=me->totface; a>0; a--, mface++) {
627                                         if(mface->v4) {
628                                                 bs->v1= mface->v1;
629                                                 bs->v2= mface->v3;
630                                                 bs->strength= s_shear;
631                                                 bs->order   =2;
632                                                 bs++;
633                                                 bs->v1= mface->v2;
634                                                 bs->v2= mface->v4;
635                                                 bs->strength= s_shear;
636                                                 bs->order   =2;
637                                                 bs++;
638                                                 
639                                         }
640                                 }       
641                         }
642                         
643             /* now we can announce new springs */
644                         ob->soft->totspring += nofquads *2;
645                 }
646         }
647 }
648
649 static void add_2nd_order_roller(Object *ob,float stiffness,int *counter, int addsprings)
650 {
651         /*assume we have a softbody*/
652         SoftBody *sb= ob->soft; /* is supposed to be there */
653         BodyPoint *bp,*bpo;     
654         BodySpring *bs,*bs2,*bs3= NULL;
655         int a,b,c,notthis= 0,v0;
656         if (!sb->bspring){return;} /* we are 2nd order here so 1rst should have been build :) */
657         /* first run counting  second run adding */
658         *counter = 0;
659         if (addsprings) bs3 = ob->soft->bspring+ob->soft->totspring;
660         for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
661                 /*scan for neighborhood*/
662                 bpo = NULL;
663                 v0  = (sb->totpoint-a);
664                 for(b=bp->nofsprings;b>0;b--){
665                         bs = sb->bspring + bp->springs[b-1];
666                         /*nasty thing here that springs have two ends
667                         so here we have to make sure we examine the other */
668                         if (( v0 == bs->v1) ){ 
669                                 bpo =sb->bpoint+bs->v2;
670                                 notthis = bs->v2;
671                         }
672                         else {
673                         if (( v0 == bs->v2) ){
674                                 bpo =sb->bpoint+bs->v1;
675                                 notthis = bs->v1;
676                         } 
677                         else {printf("oops we should not get here -  add_2nd_order_springs");}
678                         }
679             if (bpo){/* so now we have a 2nd order humpdidump */
680                                 for(c=bpo->nofsprings;c>0;c--){
681                                         bs2 = sb->bspring + bpo->springs[c-1];
682                                         if ((bs2->v1 != notthis)  && (bs2->v1 > v0)){
683                                                 (*counter)++;/*hit */
684                                                 if (addsprings){
685                                                         bs3->v1= v0;
686                                                         bs3->v2= bs2->v1;
687                                                         bs3->strength= stiffness;
688                                                         bs3->order=2;
689                                                         bs3++;
690                                                 }
691                                         }
692                                         if ((bs2->v2 !=notthis)&&(bs2->v2 > v0)){
693                                         (*counter)++;/*hit */
694                                                 if (addsprings){
695                                                         bs3->v1= v0;
696                                                         bs3->v2= bs2->v2;
697                                                         bs3->strength= stiffness;
698                                                         bs3->order=2;
699                                                         bs3++;
700                                                 }
701
702                                         }
703                                 }
704                                 
705                         }
706                         
707                 }
708                 /*scan for neighborhood done*/
709         }
710 }
711
712
713 static void add_2nd_order_springs(Object *ob,float stiffness)
714 {
715         int counter = 0;
716         BodySpring *bs_new;
717         stiffness *=stiffness;
718         
719         add_2nd_order_roller(ob,stiffness,&counter,0); /* counting */
720         if (counter) {
721                 /* resize spring-array to hold additional springs */
722                 bs_new= MEM_callocN( (ob->soft->totspring + counter )*sizeof(BodySpring), "bodyspring");
723                 memcpy(bs_new,ob->soft->bspring,(ob->soft->totspring )*sizeof(BodySpring));
724                 
725                 if(ob->soft->bspring)
726                         MEM_freeN(ob->soft->bspring); 
727                 ob->soft->bspring = bs_new; 
728                 
729                 add_2nd_order_roller(ob,stiffness,&counter,1); /* adding */
730                 ob->soft->totspring +=counter ;
731         }
732 }
733
734 static void add_bp_springlist(BodyPoint *bp,int springID)
735 {
736         int *newlist;
737         
738         if (bp->springs == NULL) {
739                 bp->springs = MEM_callocN( sizeof(int), "bpsprings");
740                 bp->springs[0] = springID;
741                 bp->nofsprings = 1;
742         }
743         else {
744                 bp->nofsprings++;
745                 newlist = MEM_callocN(bp->nofsprings * sizeof(int), "bpsprings");
746                 memcpy(newlist,bp->springs,(bp->nofsprings-1)* sizeof(int));
747                 MEM_freeN(bp->springs);
748                 bp->springs = newlist;
749                 bp->springs[bp->nofsprings-1] = springID;
750         }
751 }
752
753 /* do this once when sb is build
754 it is O(N^2) so scanning for springs every iteration is too expensive
755 */
756 static void build_bps_springlist(Object *ob)
757 {
758         SoftBody *sb= ob->soft; /* is supposed to be there */
759         BodyPoint *bp;  
760         BodySpring *bs; 
761         int a,b;
762         
763         if (sb==NULL) return; /* paranoya check */
764         
765         for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
766                 /* throw away old list */
767                 if (bp->springs) {
768                         MEM_freeN(bp->springs);
769                         bp->springs=NULL;
770                 }
771                 /* scan for attached inner springs */   
772                 for(b=sb->totspring, bs= sb->bspring; b>0; b--, bs++) {
773                         if (( (sb->totpoint-a) == bs->v1) ){ 
774                                 add_bp_springlist(bp,sb->totspring -b);
775                         }
776                         if (( (sb->totpoint-a) == bs->v2) ){ 
777                                 add_bp_springlist(bp,sb->totspring -b);
778                         }
779                 }/*for springs*/
780         }/*for bp*/             
781 }
782
783 static void calculate_collision_balls(Object *ob)
784 {
785         SoftBody *sb= ob->soft; /* is supposed to be there */
786         BodyPoint *bp;  
787         BodySpring *bs; 
788         int a,b,akku_count;
789         float min,max,akku;
790
791         if (sb==NULL) return; /* paranoya check */
792
793         for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
794                 bp->colball=0;
795                 akku =0.0f;
796                 akku_count=0;
797                 min = 1e22f;
798                 max = -1e22f;
799                 /* first estimation based on attached */
800                 for(b=bp->nofsprings;b>0;b--){
801                         bs = sb->bspring + bp->springs[b-1];
802                         if (bs->order == 1){
803                         akku += bs->len;
804                         akku_count++,
805                         min = MIN2(bs->len,min);
806                         max = MAX2(bs->len,max);
807                         }
808                 }
809
810                 if (akku_count > 0) {
811                         if (sb->sbc_mode == SBC_MODE_MANUAL){
812                                 bp->colball=sb->colball;
813                         }
814                         if (sb->sbc_mode == SBC_MODE_AVG){
815                                 bp->colball = akku/(float)akku_count*sb->colball;
816                         }
817                         if (sb->sbc_mode == SBC_MODE_MIN){
818                                 bp->colball=min*sb->colball;
819                         }
820                         if (sb->sbc_mode == SBC_MODE_MAX){
821                                 bp->colball=max*sb->colball;
822                         }
823                         if (sb->sbc_mode == SBC_MODE_AVGMINMAX){
824                                 bp->colball = (min + max)/2.0f*sb->colball;
825                         }
826                 }
827                 else bp->colball=0;
828         }/*for bp*/             
829 }
830
831
832 /* creates new softbody if didn't exist yet, makes new points and springs arrays */
833 static void renew_softbody(Object *ob, int totpoint, int totspring)  
834 {
835         SoftBody *sb;
836         int i;
837         short softflag;
838         if(ob->soft==NULL) ob->soft= sbNew();
839         else free_softbody_intern(ob->soft);
840         sb= ob->soft;
841         softflag=ob->softflag;
842            
843         if(totpoint) {
844                 sb->totpoint= totpoint;
845                 sb->totspring= totspring;
846                 
847                 sb->bpoint= MEM_mallocN( totpoint*sizeof(BodyPoint), "bodypoint");
848                 if(totspring) 
849                         sb->bspring= MEM_mallocN( totspring*sizeof(BodySpring), "bodyspring");
850
851                         /* initialise BodyPoint array */
852                 for (i=0; i<totpoint; i++) {
853                         BodyPoint *bp = &sb->bpoint[i];
854
855                         if(softflag & OB_SB_GOAL) {
856                                 bp->goal= sb->defgoal;
857                         }
858                         else { 
859                                 bp->goal= 0.0f; 
860                                 /* so this will definily be below SOFTGOALSNAP */
861                         }
862                         
863                         bp->nofsprings= 0;
864                         bp->springs= NULL;
865                         bp->choke = 0.0f;
866                         bp->choke2 = 0.0f;
867                         bp->frozen = 1.0f;
868                         bp->colball = 0.0f;
869                         bp->flag = 0;
870
871                 }
872         }
873 }
874
875 static void free_softbody_baked(SoftBody *sb)
876 {
877         SBVertex *key;
878         int k;
879
880         for(k=0; k<sb->totkey; k++) {
881                 key= *(sb->keys + k);
882                 if(key) MEM_freeN(key);
883         }
884         if(sb->keys) MEM_freeN(sb->keys);
885         
886         sb->keys= NULL;
887         sb->totkey= 0;
888 }
889 static void free_scratch(SoftBody *sb)
890 {
891         if(sb->scratch){
892                 /* todo make sure everything is cleaned up nicly */
893                 if (sb->scratch->colliderhash){
894                         BLI_ghash_free(sb->scratch->colliderhash, NULL,
895                                         (GHashValFreeFP) ccd_mesh_free); /*this hoepfully will free all caches*/
896                         sb->scratch->colliderhash = NULL;
897                 }
898                 if (sb->scratch->bodyface){
899                         MEM_freeN(sb->scratch->bodyface);
900                 }
901                 MEM_freeN(sb->scratch);
902                 sb->scratch = NULL;
903         }
904         
905 }
906
907 /* only frees internal data */
908 static void free_softbody_intern(SoftBody *sb)
909 {
910         if(sb) {
911                 int a;
912                 BodyPoint *bp;
913                 
914                 if(sb->bpoint){
915                         for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
916                                 /* free spring list */ 
917                                 if (bp->springs != NULL) {
918                                         MEM_freeN(bp->springs);
919                                 }
920                         }
921                         MEM_freeN(sb->bpoint);
922                 }
923                 
924                 if(sb->bspring) MEM_freeN(sb->bspring);
925                 
926                 sb->totpoint= sb->totspring= 0;
927                 sb->bpoint= NULL;
928                 sb->bspring= NULL;
929
930                 free_scratch(sb);
931                 free_softbody_baked(sb);
932         }
933 }
934
935
936 /* ************ dynamics ********** */
937
938 /* the most general (micro physics correct) way to do collision 
939 ** (only needs the current particle position)  
940 **
941 ** it actually checks if the particle intrudes a short range force field generated 
942 ** by the faces of the target object and returns a force to drive the particel out
943 ** the strenght of the field grows exponetially if the particle is on the 'wrong' side of the face
944 ** 'wrong' side : projection to the face normal is negative (all referred to a vertex in the face)
945 **
946 ** flaw of this: 'fast' particles as well as 'fast' colliding faces 
947 ** give a 'tunnel' effect such that the particle passes through the force field 
948 ** without ever 'seeing' it 
949 ** this is fully compliant to heisenberg: h >= fuzzy(location) * fuzzy(time)
950 ** besides our h is way larger than in QM because forces propagate way slower here
951 ** we have to deal with fuzzy(time) in the range of 1/25 seconds (typical frame rate)
952 ** yup collision targets are not known here any better 
953 ** and 1/25 second is looong compared to real collision events
954 ** Q: why not use 'simple' collision here like bouncing back a particle 
955 **   --> reverting is velocity on the face normal
956 ** A: because our particles are not alone here 
957 **    and need to tell their neighbours exactly what happens via spring forces 
958 ** unless sbObjectStep( .. ) is called on sub frame timing level
959 ** BTW that also questions the use of a 'implicit' solvers on softbodies  
960 ** since that would only valid for 'slow' moving collision targets and dito particles
961 */
962
963 /* aye this belongs to arith.c */
964 static void Vec3PlusStVec(float *v, float s, float *v1)
965 {
966         v[0] += s*v1[0];
967         v[1] += s*v1[1];
968         v[2] += s*v1[2];
969 }
970
971 /* +++ dependancy information functions*/
972
973 static int are_there_deflectors(unsigned int layer)
974 {
975         Base *base;
976         
977         for(base = G.scene->base.first; base; base= base->next) {
978                 if( (base->lay & layer) && base->object->pd) {
979                         if(base->object->pd->deflect) 
980                                 return 1;
981                 }
982         }
983         return 0;
984 }
985
986 static int query_external_colliders(Object *me)
987 {
988         return(are_there_deflectors(me->lay));
989 }
990 /* --- dependancy information functions*/
991
992
993 /* +++ the aabb "force" section*/
994 static int sb_detect_aabb_collisionCached(      float force[3], unsigned int par_layer,struct Object *vertexowner,float time)
995 {
996         Object *ob;
997         SoftBody *sb=vertexowner->soft;
998         GHash *hash;
999         GHashIterator *ihash;
1000         float  aabbmin[3],aabbmax[3];
1001         int a, deflected=0;
1002
1003         if ((sb == NULL) || (sb->scratch ==NULL)) return 0;
1004         VECCOPY(aabbmin,sb->scratch->aabbmin);
1005         VECCOPY(aabbmax,sb->scratch->aabbmax);
1006
1007         hash  = vertexowner->soft->scratch->colliderhash;
1008         ihash = BLI_ghashIterator_new(hash);
1009     while (!BLI_ghashIterator_isDone(ihash) ) {
1010
1011                 ccd_Mesh *ccdm = BLI_ghashIterator_getValue     (ihash);
1012                 ob             = BLI_ghashIterator_getKey       (ihash);
1013                         /* only with deflecting set */
1014                         if(ob->pd && ob->pd->deflect) {
1015                                 MFace *mface= NULL;
1016                                 MVert *mvert= NULL;
1017                                 MVert *mprevvert= NULL;
1018                                 ccdf_minmax *mima= NULL;
1019                                 if(ccdm){
1020                                         mface= ccdm->mface;
1021                                         mvert= ccdm->mvert;
1022                                         mprevvert= ccdm->mprevvert;
1023                                         mima= ccdm->mima;
1024                                         a = ccdm->totface;
1025                                         
1026                                         if ((aabbmax[0] < ccdm->bbmin[0]) || 
1027                                                 (aabbmax[1] < ccdm->bbmin[1]) ||
1028                                                 (aabbmax[2] < ccdm->bbmin[2]) ||
1029                                                 (aabbmin[0] > ccdm->bbmax[0]) || 
1030                                                 (aabbmin[1] > ccdm->bbmax[1]) || 
1031                                                 (aabbmin[2] > ccdm->bbmax[2]) ) {
1032                                                 /* boxes dont intersect */ 
1033                                                 BLI_ghashIterator_step(ihash);
1034                                                 continue;                               
1035                                         }                                       
1036
1037                                         /* so now we have the 2 boxes overlapping */
1038                     /* forces actually not used */
1039                                         deflected = 2;
1040
1041                                 }
1042                                 else{
1043                                         /*aye that should be cached*/
1044                                         printf("missing cache error \n");
1045                                         BLI_ghashIterator_step(ihash);
1046                                         continue;                               
1047                                 }
1048                         } /* if(ob->pd && ob->pd->deflect) */
1049                         BLI_ghashIterator_step(ihash);
1050         } /* while () */
1051         BLI_ghashIterator_free(ihash);
1052         return deflected;       
1053 }
1054 /* --- the aabb section*/
1055
1056
1057 /* +++ the face external section*/
1058 static int sb_detect_face_pointCached(float face_v1[3],float face_v2[3],float face_v3[3],float *damp,                                           
1059                                                                    float force[3], unsigned int par_layer,struct Object *vertexowner,float time)
1060                                                                    {
1061         Object *ob;
1062         GHash *hash;
1063         GHashIterator *ihash;
1064         float nv1[3], edge1[3], edge2[3], d_nvect[3], aabbmin[3],aabbmax[3];
1065         float facedist,outerfacethickness,tune = 10.f;
1066         int a, deflected=0;
1067
1068         aabbmin[0] = MIN3(face_v1[0],face_v2[0],face_v3[0]);
1069         aabbmin[1] = MIN3(face_v1[1],face_v2[1],face_v3[1]);
1070         aabbmin[2] = MIN3(face_v1[2],face_v2[2],face_v3[2]);
1071         aabbmax[0] = MAX3(face_v1[0],face_v2[0],face_v3[0]);
1072         aabbmax[1] = MAX3(face_v1[1],face_v2[1],face_v3[1]);
1073         aabbmax[2] = MAX3(face_v1[2],face_v2[2],face_v3[2]);
1074
1075         /* calculate face normal once again SIGH */
1076         VECSUB(edge1, face_v1, face_v2);
1077         VECSUB(edge2, face_v3, face_v2);
1078         Crossf(d_nvect, edge2, edge1);
1079         Normalize(d_nvect);
1080
1081
1082         hash  = vertexowner->soft->scratch->colliderhash;
1083         ihash = BLI_ghashIterator_new(hash);
1084     while (!BLI_ghashIterator_isDone(ihash) ) {
1085
1086                 ccd_Mesh *ccdm = BLI_ghashIterator_getValue     (ihash);
1087                 ob             = BLI_ghashIterator_getKey       (ihash);
1088                         /* only with deflecting set */
1089                         if(ob->pd && ob->pd->deflect) {
1090                                 MVert *mvert= NULL;
1091                                 MVert *mprevvert= NULL;
1092                                 if(ccdm){
1093                                         mvert= ccdm->mvert;
1094                                         a    = ccdm->totvert; 
1095                                         mprevvert= ccdm->mprevvert;                             
1096                                         outerfacethickness =ob->pd->pdef_sboft;
1097                                         if ((aabbmax[0] < ccdm->bbmin[0]) || 
1098                                                 (aabbmax[1] < ccdm->bbmin[1]) ||
1099                                                 (aabbmax[2] < ccdm->bbmin[2]) ||
1100                                                 (aabbmin[0] > ccdm->bbmax[0]) || 
1101                                                 (aabbmin[1] > ccdm->bbmax[1]) || 
1102                                                 (aabbmin[2] > ccdm->bbmax[2]) ) {
1103                                                 /* boxes dont intersect */ 
1104                                                 BLI_ghashIterator_step(ihash);
1105                                                 continue;                               
1106                                         }                                       
1107
1108                                 }
1109                                 else{
1110                                         /*aye that should be cached*/
1111                                         printf("missing cache error \n");
1112                                         BLI_ghashIterator_step(ihash);
1113                                         continue;                               
1114                                 }
1115
1116
1117                                 /* use mesh*/
1118                                 if (mvert) {
1119                                         while(a){
1120                                                 VECCOPY(nv1,mvert[a-1].co);                                             
1121                                                 if(mprevvert){
1122                                                         VecMulf(nv1,time);
1123                                                         Vec3PlusStVec(nv1,(1.0f-time),mprevvert[a-1].co);
1124                                                 }
1125                                                 /* origin to face_v2*/
1126                                                 VECSUB(nv1, nv1, face_v2);
1127                                                 facedist = Inpf(nv1,d_nvect);
1128                                                 if (ABS(facedist)<outerfacethickness){
1129                                                         if (point_in_tri_prism(nv1, face_v1,face_v2,face_v3) ){
1130                                                                 float df;
1131                                                                 if (facedist > 0){
1132                                                                         df = (outerfacethickness-facedist)/outerfacethickness;
1133                                                                 }
1134                                                                 else {
1135                                                                         df = (outerfacethickness+facedist)/outerfacethickness;
1136                                                                 }
1137
1138                                                                 *damp=df*tune*ob->pd->pdef_sbdamp;
1139
1140                                                                 df = 0.01f*exp(- 100.0f*df);
1141                                                                 Vec3PlusStVec(force,-df,d_nvect);
1142                                                                 deflected = 3;
1143                                                         }
1144                                                 }
1145                                                 a--;
1146                                         }/* while(a)*/
1147                                 } /* if (mvert) */
1148                         } /* if(ob->pd && ob->pd->deflect) */
1149                         BLI_ghashIterator_step(ihash);
1150         } /* while () */
1151         BLI_ghashIterator_free(ihash);
1152         return deflected;       
1153 }
1154
1155
1156 static int sb_detect_face_collisionCached(float face_v1[3],float face_v2[3],float face_v3[3],float *damp,                                               
1157                                                                    float force[3], unsigned int par_layer,struct Object *vertexowner,float time)
1158 {
1159         Object *ob;
1160         GHash *hash;
1161         GHashIterator *ihash;
1162         float nv1[3], nv2[3], nv3[3], nv4[3], edge1[3], edge2[3], d_nvect[3], aabbmin[3],aabbmax[3];
1163         float t,tune = 10.0f;
1164         int a, deflected=0;
1165
1166         aabbmin[0] = MIN3(face_v1[0],face_v2[0],face_v3[0]);
1167         aabbmin[1] = MIN3(face_v1[1],face_v2[1],face_v3[1]);
1168         aabbmin[2] = MIN3(face_v1[2],face_v2[2],face_v3[2]);
1169         aabbmax[0] = MAX3(face_v1[0],face_v2[0],face_v3[0]);
1170         aabbmax[1] = MAX3(face_v1[1],face_v2[1],face_v3[1]);
1171         aabbmax[2] = MAX3(face_v1[2],face_v2[2],face_v3[2]);
1172
1173         hash  = vertexowner->soft->scratch->colliderhash;
1174         ihash = BLI_ghashIterator_new(hash);
1175     while (!BLI_ghashIterator_isDone(ihash) ) {
1176
1177                 ccd_Mesh *ccdm = BLI_ghashIterator_getValue     (ihash);
1178                 ob             = BLI_ghashIterator_getKey       (ihash);
1179                         /* only with deflecting set */
1180                         if(ob->pd && ob->pd->deflect) {
1181                                 MFace *mface= NULL;
1182                                 MVert *mvert= NULL;
1183                                 MVert *mprevvert= NULL;
1184                                 ccdf_minmax *mima= NULL;
1185                                 if(ccdm){
1186                                         mface= ccdm->mface;
1187                                         mvert= ccdm->mvert;
1188                                         mprevvert= ccdm->mprevvert;
1189                                         mima= ccdm->mima;
1190                                         a = ccdm->totface;
1191                                         
1192                                         if ((aabbmax[0] < ccdm->bbmin[0]) || 
1193                                                 (aabbmax[1] < ccdm->bbmin[1]) ||
1194                                                 (aabbmax[2] < ccdm->bbmin[2]) ||
1195                                                 (aabbmin[0] > ccdm->bbmax[0]) || 
1196                                                 (aabbmin[1] > ccdm->bbmax[1]) || 
1197                                                 (aabbmin[2] > ccdm->bbmax[2]) ) {
1198                                                 /* boxes dont intersect */ 
1199                                                 BLI_ghashIterator_step(ihash);
1200                                                 continue;                               
1201                                         }                                       
1202
1203                                 }
1204                                 else{
1205                                         /*aye that should be cached*/
1206                                         printf("missing cache error \n");
1207                                         BLI_ghashIterator_step(ihash);
1208                                         continue;                               
1209                                 }
1210
1211
1212                                 /* use mesh*/
1213                                 while (a--) {
1214                                         if (
1215                                                 (aabbmax[0] < mima->minx) || 
1216                                                 (aabbmin[0] > mima->maxx) || 
1217                                                 (aabbmax[1] < mima->miny) ||
1218                                                 (aabbmin[1] > mima->maxy) || 
1219                                                 (aabbmax[2] < mima->minz) ||
1220                                                 (aabbmin[2] > mima->maxz) 
1221                                                 ) {
1222                                                 mface++;
1223                                                 mima++;
1224                                                 continue;
1225                                         }
1226
1227
1228                                         if (mvert){
1229
1230                                                 VECCOPY(nv1,mvert[mface->v1].co);                                               
1231                                                 VECCOPY(nv2,mvert[mface->v2].co);
1232                                                 VECCOPY(nv3,mvert[mface->v3].co);
1233                                                 if (mface->v4){
1234                                                         VECCOPY(nv4,mvert[mface->v4].co);
1235                                                 }
1236                                                 if (mprevvert){
1237                                                         VecMulf(nv1,time);
1238                                                         Vec3PlusStVec(nv1,(1.0f-time),mprevvert[mface->v1].co);
1239                                                         
1240                                                         VecMulf(nv2,time);
1241                                                         Vec3PlusStVec(nv2,(1.0f-time),mprevvert[mface->v2].co);
1242                                                         
1243                                                         VecMulf(nv3,time);
1244                                                         Vec3PlusStVec(nv3,(1.0f-time),mprevvert[mface->v3].co);
1245                                                         
1246                                                         if (mface->v4){
1247                                                                 VecMulf(nv4,time);
1248                                                                 Vec3PlusStVec(nv4,(1.0f-time),mprevvert[mface->v4].co);
1249                                                         }
1250                                                 }       
1251                                         }
1252
1253                                         /* switch origin to be nv2*/
1254                                         VECSUB(edge1, nv1, nv2);
1255                                         VECSUB(edge2, nv3, nv2);
1256                                         Crossf(d_nvect, edge2, edge1);
1257                                         Normalize(d_nvect);
1258                                         if ( 
1259                                                 LineIntersectsTriangle(nv1, nv2, face_v1, face_v2, face_v3, &t, NULL) ||
1260                                                 LineIntersectsTriangle(nv2, nv3, face_v1, face_v2, face_v3, &t, NULL) ||
1261                                                 LineIntersectsTriangle(nv3, nv1, face_v1, face_v2, face_v3, &t, NULL) ){
1262                                                 Vec3PlusStVec(force,-0.5f,d_nvect);
1263                                                 *damp=tune*ob->pd->pdef_sbdamp;
1264                                                 deflected = 2;
1265                                         }
1266                                         if (mface->v4){ /* quad */
1267                                                 /* switch origin to be nv4 */
1268                                                 VECSUB(edge1, nv3, nv4);
1269                                                 VECSUB(edge2, nv1, nv4);                                        
1270                                                 Crossf(d_nvect, edge2, edge1);
1271                                                 Normalize(d_nvect);     
1272                                                 if ( 
1273                                                         /* LineIntersectsTriangle(nv1, nv3, face_v1, face_v2, face_v3, &t, NULL) ||
1274                                                          we did that edge allready */
1275                                                         LineIntersectsTriangle(nv3, nv4, face_v1, face_v2, face_v3, &t, NULL) ||
1276                                                         LineIntersectsTriangle(nv4, nv1, face_v1, face_v2, face_v3, &t, NULL) ){
1277                                                         Vec3PlusStVec(force,-0.5f,d_nvect);
1278                                                         *damp=tune*ob->pd->pdef_sbdamp;
1279                                                         deflected = 2;
1280                                                 }
1281                                         }
1282                                         mface++;
1283                                         mima++;                                 
1284                                 }/* while a */          
1285                         } /* if(ob->pd && ob->pd->deflect) */
1286                         BLI_ghashIterator_step(ihash);
1287         } /* while () */
1288         BLI_ghashIterator_free(ihash);
1289         return deflected;       
1290 }
1291
1292
1293
1294 static void scan_for_ext_face_forces(Object *ob,float timenow)
1295 {
1296         SoftBody *sb = ob->soft;
1297         BodyFace *bf;
1298         int a;
1299         float damp=0.0f,choke=1.0f; 
1300         float tune = -10.0f;
1301         float feedback[3];
1302         
1303         if (sb && sb->scratch->totface){
1304                 
1305                 
1306                 bf = sb->scratch->bodyface;
1307                 for(a=0; a<sb->scratch->totface; a++, bf++) {
1308                         bf->ext_force[0]=bf->ext_force[1]=bf->ext_force[2]=0.0f; 
1309 /*+++edges intruding*/
1310                         bf->flag &= ~BFF_INTERSECT;             
1311                         feedback[0]=feedback[1]=feedback[2]=0.0f;
1312                         if (sb_detect_face_collisionCached(sb->bpoint[bf->v1].pos,sb->bpoint[bf->v2].pos, sb->bpoint[bf->v3].pos, 
1313                                 &damp,  feedback, ob->lay ,ob , timenow)){
1314                                 Vec3PlusStVec(sb->bpoint[bf->v1].force,tune,feedback);
1315                                 Vec3PlusStVec(sb->bpoint[bf->v2].force,tune,feedback);
1316                                 Vec3PlusStVec(sb->bpoint[bf->v3].force,tune,feedback);
1317 //                              Vec3PlusStVec(bf->ext_force,tune,feedback);
1318                                 bf->flag |= BFF_INTERSECT;
1319                                 choke = MIN2(MAX2(damp,choke),1.0f);
1320                         }
1321
1322                         feedback[0]=feedback[1]=feedback[2]=0.0f;
1323                         if ((bf->v4) && (sb_detect_face_collisionCached(sb->bpoint[bf->v1].pos,sb->bpoint[bf->v3].pos, sb->bpoint[bf->v4].pos, 
1324                                 &damp,  feedback, ob->lay ,ob , timenow))){
1325                                 Vec3PlusStVec(sb->bpoint[bf->v1].force,tune,feedback);
1326                                 Vec3PlusStVec(sb->bpoint[bf->v3].force,tune,feedback);
1327                                 Vec3PlusStVec(sb->bpoint[bf->v4].force,tune,feedback);
1328 //                              Vec3PlusStVec(bf->ext_force,tune,feedback);
1329                                 bf->flag |= BFF_INTERSECT;
1330                                 choke = MIN2(MAX2(damp,choke),1.0f);
1331                         }
1332 /*---edges intruding*/
1333
1334 /*+++ close vertices*/
1335                         if  (( bf->flag & BFF_INTERSECT)==0){
1336                                 bf->flag &= ~BFF_CLOSEVERT;
1337                                 tune = -1.0f;
1338                                 feedback[0]=feedback[1]=feedback[2]=0.0f;
1339                                 if (sb_detect_face_pointCached(sb->bpoint[bf->v1].pos,sb->bpoint[bf->v2].pos, sb->bpoint[bf->v3].pos, 
1340                                         &damp,  feedback, ob->lay ,ob , timenow)){
1341                                 Vec3PlusStVec(sb->bpoint[bf->v1].force,tune,feedback);
1342                                 Vec3PlusStVec(sb->bpoint[bf->v2].force,tune,feedback);
1343                                 Vec3PlusStVec(sb->bpoint[bf->v3].force,tune,feedback);
1344 //                                              Vec3PlusStVec(bf->ext_force,tune,feedback);
1345                                                 bf->flag |= BFF_CLOSEVERT;
1346                                                 choke = MIN2(MAX2(damp,choke),1.0f);
1347                                 }
1348
1349                                 feedback[0]=feedback[1]=feedback[2]=0.0f;
1350                                 if ((bf->v4) && (sb_detect_face_pointCached(sb->bpoint[bf->v1].pos,sb->bpoint[bf->v3].pos, sb->bpoint[bf->v4].pos, 
1351                                         &damp,  feedback, ob->lay ,ob , timenow))){
1352                                 Vec3PlusStVec(sb->bpoint[bf->v1].force,tune,feedback);
1353                                 Vec3PlusStVec(sb->bpoint[bf->v3].force,tune,feedback);
1354                                 Vec3PlusStVec(sb->bpoint[bf->v4].force,tune,feedback);
1355 //                                              Vec3PlusStVec(bf->ext_force,tune,feedback);
1356                                                 bf->flag |= BFF_CLOSEVERT;
1357                                                 choke = MIN2(MAX2(damp,choke),1.0f);
1358                                 }
1359                         }
1360 /*--- close vertices*/
1361                 }
1362                 bf = sb->scratch->bodyface;
1363                 for(a=0; a<sb->scratch->totface; a++, bf++) {
1364                         if (( bf->flag & BFF_INTERSECT) || ( bf->flag & BFF_CLOSEVERT))
1365                         {
1366                 sb->bpoint[bf->v1].choke2=MAX2(sb->bpoint[bf->v1].choke2,choke);
1367                 sb->bpoint[bf->v2].choke2=MAX2(sb->bpoint[bf->v2].choke2,choke);
1368                 sb->bpoint[bf->v3].choke2=MAX2(sb->bpoint[bf->v3].choke2,choke);
1369                                 if (bf->v4){
1370                 sb->bpoint[bf->v2].choke2=MAX2(sb->bpoint[bf->v2].choke2,choke);
1371                                 }
1372                         }       
1373                 }
1374         }
1375 }
1376
1377 /*  --- the face external section*/
1378
1379
1380 /* +++ the spring external section*/
1381
1382 static int sb_detect_edge_collisionCached(float edge_v1[3],float edge_v2[3],float *damp,                                                
1383                                                                    float force[3], unsigned int par_layer,struct Object *vertexowner,float time)
1384 {
1385         Object *ob;
1386         GHash *hash;
1387         GHashIterator *ihash;
1388         float nv1[3], nv2[3], nv3[3], nv4[3], edge1[3], edge2[3], d_nvect[3], aabbmin[3],aabbmax[3];
1389         float t,el;
1390         int a, deflected=0;
1391
1392         aabbmin[0] = MIN2(edge_v1[0],edge_v2[0]);
1393         aabbmin[1] = MIN2(edge_v1[1],edge_v2[1]);
1394         aabbmin[2] = MIN2(edge_v1[2],edge_v2[2]);
1395         aabbmax[0] = MAX2(edge_v1[0],edge_v2[0]);
1396         aabbmax[1] = MAX2(edge_v1[1],edge_v2[1]);
1397         aabbmax[2] = MAX2(edge_v1[2],edge_v2[2]);
1398
1399         el = VecLenf(edge_v1,edge_v2);
1400
1401         hash  = vertexowner->soft->scratch->colliderhash;
1402         ihash = BLI_ghashIterator_new(hash);
1403     while (!BLI_ghashIterator_isDone(ihash) ) {
1404
1405                 ccd_Mesh *ccdm = BLI_ghashIterator_getValue     (ihash);
1406                 ob             = BLI_ghashIterator_getKey       (ihash);
1407                         /* only with deflecting set */
1408                         if(ob->pd && ob->pd->deflect) {
1409                                 MFace *mface= NULL;
1410                                 MVert *mvert= NULL;
1411                                 MVert *mprevvert= NULL;
1412                                 ccdf_minmax *mima= NULL;
1413                                 if(ccdm){
1414                                         mface= ccdm->mface;
1415                                         mvert= ccdm->mvert;
1416                                         mprevvert= ccdm->mprevvert;
1417                                         mima= ccdm->mima;
1418                                         a = ccdm->totface;
1419                                         
1420                                         if ((aabbmax[0] < ccdm->bbmin[0]) || 
1421                                                 (aabbmax[1] < ccdm->bbmin[1]) ||
1422                                                 (aabbmax[2] < ccdm->bbmin[2]) ||
1423                                                 (aabbmin[0] > ccdm->bbmax[0]) || 
1424                                                 (aabbmin[1] > ccdm->bbmax[1]) || 
1425                                                 (aabbmin[2] > ccdm->bbmax[2]) ) {
1426                                                 /* boxes dont intersect */ 
1427                                                 BLI_ghashIterator_step(ihash);
1428                                                 continue;                               
1429                                         }                                       
1430
1431                                 }
1432                                 else{
1433                                         /*aye that should be cached*/
1434                                         printf("missing cache error \n");
1435                                         BLI_ghashIterator_step(ihash);
1436                                         continue;                               
1437                                 }
1438
1439
1440                                 /* use mesh*/
1441                                 while (a--) {
1442                                         if (
1443                                                 (aabbmax[0] < mima->minx) || 
1444                                                 (aabbmin[0] > mima->maxx) || 
1445                                                 (aabbmax[1] < mima->miny) ||
1446                                                 (aabbmin[1] > mima->maxy) || 
1447                                                 (aabbmax[2] < mima->minz) ||
1448                                                 (aabbmin[2] > mima->maxz) 
1449                                                 ) {
1450                                                 mface++;
1451                                                 mima++;
1452                                                 continue;
1453                                         }
1454
1455
1456                                         if (mvert){
1457
1458                                                 VECCOPY(nv1,mvert[mface->v1].co);                                               
1459                                                 VECCOPY(nv2,mvert[mface->v2].co);
1460                                                 VECCOPY(nv3,mvert[mface->v3].co);
1461                                                 if (mface->v4){
1462                                                         VECCOPY(nv4,mvert[mface->v4].co);
1463                                                 }
1464                                                 if (mprevvert){
1465                                                         VecMulf(nv1,time);
1466                                                         Vec3PlusStVec(nv1,(1.0f-time),mprevvert[mface->v1].co);
1467                                                         
1468                                                         VecMulf(nv2,time);
1469                                                         Vec3PlusStVec(nv2,(1.0f-time),mprevvert[mface->v2].co);
1470                                                         
1471                                                         VecMulf(nv3,time);
1472                                                         Vec3PlusStVec(nv3,(1.0f-time),mprevvert[mface->v3].co);
1473                                                         
1474                                                         if (mface->v4){
1475                                                                 VecMulf(nv4,time);
1476                                                                 Vec3PlusStVec(nv4,(1.0f-time),mprevvert[mface->v4].co);
1477                                                         }
1478                                                 }       
1479                                         }
1480
1481                                         /* switch origin to be nv2*/
1482                                         VECSUB(edge1, nv1, nv2);
1483                                         VECSUB(edge2, nv3, nv2);
1484
1485                                         Crossf(d_nvect, edge2, edge1);
1486                                         Normalize(d_nvect);
1487                                         if ( LineIntersectsTriangle(edge_v1, edge_v2, nv1, nv2, nv3, &t, NULL)){
1488                                                 float v1[3],v2[3];
1489                                                 float intrusiondepth,i1,i2;
1490                                                 VECSUB(v1, edge_v1, nv2);
1491                                                 VECSUB(v2, edge_v2, nv2);
1492                                                 i1 = Inpf(v1,d_nvect);
1493                                                 i2 = Inpf(v2,d_nvect);
1494                                                 intrusiondepth = -MIN2(i1,i2)/el;
1495                                                 Vec3PlusStVec(force,intrusiondepth,d_nvect);
1496                                                 *damp=ob->pd->pdef_sbdamp;
1497                                                 deflected = 2;
1498                                         }
1499                                         if (mface->v4){ /* quad */
1500                                                 /* switch origin to be nv4 */
1501                                                 VECSUB(edge1, nv3, nv4);
1502                                                 VECSUB(edge2, nv1, nv4);
1503
1504                                                 Crossf(d_nvect, edge2, edge1);
1505                                                 Normalize(d_nvect);                                             
1506                                                 if (LineIntersectsTriangle( edge_v1, edge_v2,nv1, nv3, nv4, &t, NULL)){
1507                                                         float v1[3],v2[3];
1508                                                         float intrusiondepth,i1,i2;
1509                                                         VECSUB(v1, edge_v1, nv4);
1510                                                         VECSUB(v2, edge_v2, nv4);
1511                                                 i1 = Inpf(v1,d_nvect);
1512                                                 i2 = Inpf(v2,d_nvect);
1513                                                 intrusiondepth = -MIN2(i1,i2)/el;
1514
1515
1516                                                         Vec3PlusStVec(force,intrusiondepth,d_nvect);
1517                                                         *damp=ob->pd->pdef_sbdamp;
1518                                                         deflected = 2;
1519                                                 }
1520                                         }
1521                                         mface++;
1522                                         mima++;                                 
1523                                 }/* while a */          
1524                         } /* if(ob->pd && ob->pd->deflect) */
1525                         BLI_ghashIterator_step(ihash);
1526         } /* while () */
1527         BLI_ghashIterator_free(ihash);
1528         return deflected;       
1529 }
1530
1531
1532
1533 static void _scan_for_ext_spring_forces(Object *ob,float timenow,int ifirst,int ilast, struct ListBase *do_effector)
1534 {
1535         SoftBody *sb = ob->soft;
1536         int a;
1537         float damp; 
1538         float feedback[3];
1539
1540         if (sb && sb->totspring){
1541                 for(a=ifirst; a<ilast; a++) {
1542                         BodySpring *bs = &sb->bspring[a];
1543                         bs->ext_force[0]=bs->ext_force[1]=bs->ext_force[2]=0.0f; 
1544                         feedback[0]=feedback[1]=feedback[2]=0.0f;
1545                         bs->flag &= ~BSF_INTERSECT;
1546
1547                         if (bs->order ==1){
1548                                 /* +++ springs colliding */
1549                                 if (ob->softflag & OB_SB_EDGECOLL){
1550                                         if ( sb_detect_edge_collisionCached (sb->bpoint[bs->v1].pos , sb->bpoint[bs->v2].pos,
1551                                                 &damp,feedback,ob->lay,ob,timenow)){
1552                                                         VecAddf(bs->ext_force,bs->ext_force,feedback);
1553                                                         bs->flag |= BSF_INTERSECT;
1554                                                         //bs->cf=damp;
1555                             bs->cf=sb->choke*0.01f;
1556
1557                                         }
1558                                 }
1559                                 /* ---- springs colliding */
1560
1561                                 /* +++ springs seeing wind ... n stuff depending on their orientation*/
1562                                 /* note we don't use sb->mediafrict but use sb->aeroedge for magnitude of effect*/ 
1563                                 if(sb->aeroedge){
1564                                         float vel[3],sp[3],pr[3],force[3];
1565                                         float f,windfactor  = 0.25f;   
1566                                         /*see if we have wind*/
1567                                         if(do_effector) {
1568                                                 float speed[3]={0.0f,0.0f,0.0f};
1569                                                 float pos[3];
1570                                                 VecMidf(pos, sb->bpoint[bs->v1].pos , sb->bpoint[bs->v2].pos);
1571                                                 VecMidf(vel, sb->bpoint[bs->v1].vec , sb->bpoint[bs->v2].vec);
1572                                                 pdDoEffectors(do_effector, pos, force, speed, (float)G.scene->r.cfra, 0.0f, PE_WIND_AS_SPEED);
1573                                                 VecMulf(speed,windfactor); 
1574                                                 VecAddf(vel,vel,speed);
1575                                         }
1576                                         /* media in rest */
1577                                         else{
1578                                                 VECADD(vel, sb->bpoint[bs->v1].vec , sb->bpoint[bs->v2].vec);
1579                                         }
1580                                         f = Normalize(vel);
1581                                         f = -0.0001f*f*f*sb->aeroedge;
1582                                         /* (todo) add a nice angle dependant function done for now BUT */
1583                                         /* still there could be some nice drag/lift function, but who needs it */ 
1584
1585                                         VECSUB(sp, sb->bpoint[bs->v1].pos , sb->bpoint[bs->v2].pos);
1586                                         Projf(pr,vel,sp);
1587                                         VECSUB(vel,vel,pr);
1588                                         Normalize(vel);
1589                                         if (ob->softflag & OB_SB_AERO_ANGLE){
1590                                                 Normalize(sp);
1591                                                 Vec3PlusStVec(bs->ext_force,f*(1.0f-ABS(Inpf(vel,sp))),vel);
1592                                         }
1593                                         else{ 
1594                                                 Vec3PlusStVec(bs->ext_force,f,vel); // to keep compatible with 2.45 release files
1595                                         }
1596                                 }
1597                                 /* --- springs seeing wind */
1598                         }
1599                 }
1600         }
1601 }
1602
1603
1604 static void scan_for_ext_spring_forces(Object *ob,float timenow)
1605 {
1606   SoftBody *sb = ob->soft;
1607   ListBase *do_effector= NULL; 
1608   do_effector= pdInitEffectors(ob,NULL);
1609   if (sb){
1610   _scan_for_ext_spring_forces(ob,timenow,0,sb->totspring,do_effector);
1611   }
1612   if(do_effector)
1613   pdEndEffectors(do_effector);
1614 }
1615
1616 static void *exec_scan_for_ext_spring_forces(void *data)
1617 {
1618         SB_thread_context *pctx = (SB_thread_context*)data;
1619         _scan_for_ext_spring_forces(pctx->ob,pctx->timenow,pctx->ifirst,pctx->ilast,pctx->do_effector);
1620         return 0;
1621
1622
1623 static void sb_sfesf_threads_run(struct Object *ob, float timenow,int totsprings,int *ptr_to_break_func())
1624 {
1625         ListBase *do_effector = NULL; 
1626         ListBase threads;
1627         SB_thread_context *sb_threads;
1628         int i, totthread,left,dec;
1629         int lowsprings =100; /* wild guess .. may increase with better thread management 'above' or even be UI option sb->spawn_cf_threads_nopts */
1630
1631         do_effector= pdInitEffectors(ob,NULL);
1632
1633         /* figure the number of threads while preventing pretty pointless threading overhead */
1634         if(G.scene->r.mode & R_FIXED_THREADS)
1635                 totthread= G.scene->r.threads;
1636         else
1637                 totthread= BLI_system_thread_count();
1638         /* what if we got zillions of CPUs running but less to spread*/
1639         while ((totsprings/totthread < lowsprings) && (totthread > 1)) {
1640                 totthread--;
1641         }
1642
1643         sb_threads= MEM_callocN(sizeof(SB_thread_context)*totthread, "SBSpringsThread");
1644         memset(sb_threads, 0, sizeof(SB_thread_context)*totthread);
1645         left = totsprings;
1646         dec = totsprings/totthread +1;
1647         for(i=0; i<totthread; i++) {
1648                 sb_threads[i].ob = ob; 
1649                 sb_threads[i].forcetime = 0.0; // not used here 
1650                 sb_threads[i].timenow = timenow; 
1651                 sb_threads[i].ilast   = left; 
1652                 left = left - dec;
1653                 if (left >0){
1654                         sb_threads[i].ifirst  = left;
1655                 }
1656                 else
1657                         sb_threads[i].ifirst  = 0; 
1658         sb_threads[i].do_effector = do_effector;
1659         sb_threads[i].do_deflector = 0;// not used here
1660                 sb_threads[i].fieldfactor = 0.0f;// not used here
1661                 sb_threads[i].windfactor  = 0.0f;// not used here
1662                 sb_threads[i].nr= i;
1663                 sb_threads[i].tot= totthread;
1664         }
1665         if(totthread > 1) {
1666                 BLI_init_threads(&threads, exec_scan_for_ext_spring_forces, totthread);
1667
1668                 for(i=0; i<totthread; i++)
1669                         BLI_insert_thread(&threads, &sb_threads[i]);
1670
1671                 BLI_end_threads(&threads);
1672         }
1673         else
1674                 exec_scan_for_ext_spring_forces(&sb_threads[0]);
1675     /* clean up */
1676         MEM_freeN(sb_threads);
1677
1678           if(do_effector)
1679   pdEndEffectors(do_effector);
1680 }
1681
1682
1683 /* --- the spring external section*/
1684
1685 static int choose_winner(float*w, float* pos,float*a,float*b,float*c,float*ca,float*cb,float*cc)
1686 {
1687         float mindist,cp;
1688         int winner =1;
1689         mindist = ABS(Inpf(pos,a));
1690
1691     cp = ABS(Inpf(pos,b));
1692         if ( mindist < cp ){
1693                 mindist = cp;
1694                 winner =2;
1695         }
1696
1697         cp = ABS(Inpf(pos,c));
1698         if (mindist < cp ){
1699                 mindist = cp;
1700                 winner =3;
1701         }
1702         switch (winner){ 
1703                 case 1: VECCOPY(w,ca); break; 
1704                 case 2: VECCOPY(w,cb); break; 
1705                 case 3: VECCOPY(w,cc); 
1706         }
1707         return(winner);
1708 }
1709
1710
1711
1712 static int sb_detect_vertex_collisionCached(float opco[3], float facenormal[3], float *damp,
1713                                                                          float force[3], unsigned int par_layer,struct Object *vertexowner,
1714                                                                          float time,float vel[3], float *intrusion)
1715 {
1716         Object *ob= NULL;
1717         GHash *hash;
1718         GHashIterator *ihash;
1719         float nv1[3], nv2[3], nv3[3], nv4[3], edge1[3], edge2[3],d_nvect[3], dv1[3],ve[3],avel[3]={0.0,0.0,0.0},
1720     vv1[3], vv2[3], vv3[3], vv4[3], coledge[3], mindistedge = 1000.0f, 
1721         outerforceaccu[3],innerforceaccu[3],
1722                 facedist,n_mag,force_mag_norm,minx,miny,minz,maxx,maxy,maxz,
1723                 innerfacethickness = -0.5f, outerfacethickness = 0.2f,
1724                 ee = 5.0f, ff = 0.1f, fa=1;
1725         int a, deflected=0, cavel=0,ci=0;
1726 /* init */
1727         *intrusion = 0.0f;
1728         hash  = vertexowner->soft->scratch->colliderhash;
1729         ihash = BLI_ghashIterator_new(hash);
1730         outerforceaccu[0]=outerforceaccu[1]=outerforceaccu[2]=0.0f;
1731         innerforceaccu[0]=innerforceaccu[1]=innerforceaccu[2]=0.0f;
1732 /* go */
1733     while (!BLI_ghashIterator_isDone(ihash) ) {
1734
1735                 ccd_Mesh *ccdm = BLI_ghashIterator_getValue     (ihash);
1736                 ob             = BLI_ghashIterator_getKey       (ihash);
1737                         /* only with deflecting set */
1738                         if(ob->pd && ob->pd->deflect) {
1739                                 MFace *mface= NULL;
1740                                 MVert *mvert= NULL;
1741                                 MVert *mprevvert= NULL;
1742                                 ccdf_minmax *mima= NULL;
1743
1744                                 if(ccdm){
1745                                         mface= ccdm->mface;
1746                                         mvert= ccdm->mvert;
1747                                         mprevvert= ccdm->mprevvert;
1748                                         mima= ccdm->mima;
1749                                         a = ccdm->totface;
1750
1751                                         minx =ccdm->bbmin[0]; 
1752                                         miny =ccdm->bbmin[1]; 
1753                                         minz =ccdm->bbmin[2];
1754
1755                                         maxx =ccdm->bbmax[0]; 
1756                                         maxy =ccdm->bbmax[1]; 
1757                                         maxz =ccdm->bbmax[2]; 
1758
1759                                         if ((opco[0] < minx) || 
1760                                                 (opco[1] < miny) ||
1761                                                 (opco[2] < minz) ||
1762                                                 (opco[0] > maxx) || 
1763                                                 (opco[1] > maxy) || 
1764                                                 (opco[2] > maxz) ) {
1765                                                         /* outside the padded boundbox --> collision object is too far away */ 
1766                                                                                                 BLI_ghashIterator_step(ihash);
1767                                                         continue;                               
1768                                         }                                       
1769                                 }
1770                                 else{
1771                                         /*aye that should be cached*/
1772                                         printf("missing cache error \n");
1773                                                 BLI_ghashIterator_step(ihash);
1774                                         continue;                               
1775                                 }
1776
1777                                 /* do object level stuff */
1778                                 /* need to have user control for that since it depends on model scale */
1779                                 innerfacethickness =-ob->pd->pdef_sbift;
1780                                 outerfacethickness =ob->pd->pdef_sboft;
1781                                 fa = (ff*outerfacethickness-outerfacethickness);
1782                                 fa *= fa;
1783                                 fa = 1.0f/fa;
1784                 avel[0]=avel[1]=avel[2]=0.0f;
1785                                 /* use mesh*/
1786                                 while (a--) {
1787                                         if (
1788                                                 (opco[0] < mima->minx) || 
1789                                                 (opco[0] > mima->maxx) || 
1790                                                 (opco[1] < mima->miny) ||
1791                                                 (opco[1] > mima->maxy) || 
1792                                                 (opco[2] < mima->minz) ||
1793                                                 (opco[2] > mima->maxz) 
1794                                                 ) {
1795                                                         mface++;
1796                                                         mima++;
1797                                                         continue;
1798                                         }
1799
1800                                         if (mvert){
1801
1802                                                 VECCOPY(nv1,mvert[mface->v1].co);                                               
1803                                                 VECCOPY(nv2,mvert[mface->v2].co);
1804                                                 VECCOPY(nv3,mvert[mface->v3].co);
1805                                                 if (mface->v4){
1806                                                         VECCOPY(nv4,mvert[mface->v4].co);
1807                                                 }
1808
1809                                                 if (mprevvert){
1810                                                         /* grab the average speed of the collider vertices
1811                                                         before we spoil nvX 
1812                                                         humm could be done once a SB steps but then we' need to store that too
1813                                                         since the AABB reduced propabitlty to get here drasticallly
1814                                                         it might be a nice tradeof CPU <--> memory
1815                                                         */
1816                                                         VECSUB(vv1,nv1,mprevvert[mface->v1].co);
1817                                                         VECSUB(vv2,nv2,mprevvert[mface->v2].co);
1818                                                         VECSUB(vv3,nv3,mprevvert[mface->v3].co);
1819                                                         if (mface->v4){
1820                                                                 VECSUB(vv4,nv4,mprevvert[mface->v4].co);
1821                                                         }
1822
1823                                                         VecMulf(nv1,time);
1824                                                         Vec3PlusStVec(nv1,(1.0f-time),mprevvert[mface->v1].co);
1825
1826                                                         VecMulf(nv2,time);
1827                                                         Vec3PlusStVec(nv2,(1.0f-time),mprevvert[mface->v2].co);
1828
1829                                                         VecMulf(nv3,time);
1830                                                         Vec3PlusStVec(nv3,(1.0f-time),mprevvert[mface->v3].co);
1831
1832                                                         if (mface->v4){
1833                                                                 VecMulf(nv4,time);
1834                                                                 Vec3PlusStVec(nv4,(1.0f-time),mprevvert[mface->v4].co);
1835                                                         }
1836                                                 }       
1837                                         }
1838                                         
1839                                         /* switch origin to be nv2*/
1840                                         VECSUB(edge1, nv1, nv2);
1841                                         VECSUB(edge2, nv3, nv2);
1842                                         VECSUB(dv1,opco,nv2); /* abuse dv1 to have vertex in question at *origin* of triangle */
1843
1844                                         Crossf(d_nvect, edge2, edge1);
1845                                         n_mag = Normalize(d_nvect);
1846                                         facedist = Inpf(dv1,d_nvect);
1847                                         // so rules are
1848                                         //
1849
1850                                         if ((facedist > innerfacethickness) && (facedist < outerfacethickness)){                
1851                                                 if (point_in_tri_prism(opco, nv1, nv2, nv3) ){
1852                                                         force_mag_norm =(float)exp(-ee*facedist);
1853                                                         if (facedist > outerfacethickness*ff)
1854                                                                 force_mag_norm =(float)force_mag_norm*fa*(facedist - outerfacethickness)*(facedist - outerfacethickness);
1855                                                         *damp=ob->pd->pdef_sbdamp;
1856                                                         if (facedist > 0.0f){
1857                                                                 *damp *= (1.0f - facedist/outerfacethickness);
1858                                                                 Vec3PlusStVec(outerforceaccu,force_mag_norm,d_nvect);
1859                                                                 deflected = 3;
1860
1861                                                         }
1862                                                         else {
1863                                                                 Vec3PlusStVec(innerforceaccu,force_mag_norm,d_nvect);
1864                                                                 if (deflected < 2) deflected = 2;
1865                                                         }
1866                                                         if ((mprevvert) && (*damp > 0.0f)){
1867                                                                 choose_winner(ve,opco,nv1,nv2,nv3,vv1,vv2,vv3);
1868                                                                 VECADD(avel,avel,ve);
1869                                                                 cavel ++;
1870                                                         }
1871                                                         *intrusion += facedist;
1872                                                         ci++;
1873                                                 }
1874                                         }               
1875                                         if (mface->v4){ /* quad */
1876                                                 /* switch origin to be nv4 */
1877                                                 VECSUB(edge1, nv3, nv4);
1878                                                 VECSUB(edge2, nv1, nv4);
1879                                                 VECSUB(dv1,opco,nv4); /* abuse dv1 to have vertex in question at *origin* of triangle */
1880
1881                                                 Crossf(d_nvect, edge2, edge1);
1882                                                 n_mag = Normalize(d_nvect);
1883                                                 facedist = Inpf(dv1,d_nvect);
1884
1885                                                 if ((facedist > innerfacethickness) && (facedist < outerfacethickness)){
1886                                                         if (point_in_tri_prism(opco, nv1, nv3, nv4) ){
1887                                                                 force_mag_norm =(float)exp(-ee*facedist);
1888                                                                 if (facedist > outerfacethickness*ff)
1889                                                                         force_mag_norm =(float)force_mag_norm*fa*(facedist - outerfacethickness)*(facedist - outerfacethickness);
1890                                                                 *damp=ob->pd->pdef_sbdamp;
1891                                                         if (facedist > 0.0f){
1892                                                                 *damp *= (1.0f - facedist/outerfacethickness);
1893                                                                 Vec3PlusStVec(outerforceaccu,force_mag_norm,d_nvect);
1894                                                                 deflected = 3;
1895
1896                                                         }
1897                                                         else {
1898                                                                 Vec3PlusStVec(innerforceaccu,force_mag_norm,d_nvect);
1899                                                                 if (deflected < 2) deflected = 2;
1900                                                         }
1901
1902                                                                 if ((mprevvert) && (*damp > 0.0f)){
1903                                                                         choose_winner(ve,opco,nv1,nv3,nv4,vv1,vv3,vv4);
1904                                                                         VECADD(avel,avel,ve);
1905                                                                         cavel ++;
1906                                                                 }
1907                                                             *intrusion += facedist;
1908                                                                 ci++;
1909                                                         }
1910
1911                                                 }
1912                                                 if ((deflected < 2)&& (G.rt != 444)) // we did not hit a face until now
1913                                                 { // see if 'outer' hits an edge
1914                                                         float dist;
1915
1916                                                         PclosestVL3Dfl(ve, opco, nv1, nv2);
1917                                             VECSUB(ve,opco,ve); 
1918                                                         dist = Normalize(ve);
1919                                                         if ((dist < outerfacethickness)&&(dist < mindistedge )){
1920                                                                 VECCOPY(coledge,ve);
1921                                                                 mindistedge = dist,
1922                                                                 deflected=1;
1923                                                         }
1924
1925                                                         PclosestVL3Dfl(ve, opco, nv2, nv3);
1926                                             VECSUB(ve,opco,ve); 
1927                                                         dist = Normalize(ve);
1928                                                         if ((dist < outerfacethickness)&&(dist < mindistedge )){
1929                                                                 VECCOPY(coledge,ve);
1930                                                                 mindistedge = dist,
1931                                                                 deflected=1;
1932                                                         }
1933
1934                                                         PclosestVL3Dfl(ve, opco, nv3, nv1);
1935                                             VECSUB(ve,opco,ve); 
1936                                                         dist = Normalize(ve);
1937                                                         if ((dist < outerfacethickness)&&(dist < mindistedge )){
1938                                                                 VECCOPY(coledge,ve);
1939                                                                 mindistedge = dist,
1940                                                                 deflected=1;
1941                                                         }
1942                                                         if (mface->v4){ /* quad */
1943                                                                 PclosestVL3Dfl(ve, opco, nv3, nv4);
1944                                                                 VECSUB(ve,opco,ve); 
1945                                                                 dist = Normalize(ve);
1946                                                                 if ((dist < outerfacethickness)&&(dist < mindistedge )){
1947                                                                         VECCOPY(coledge,ve);
1948                                                                         mindistedge = dist,
1949                                                                                 deflected=1;
1950                                                                 }
1951
1952                                                                 PclosestVL3Dfl(ve, opco, nv1, nv4);
1953                                                                 VECSUB(ve,opco,ve); 
1954                                                                 dist = Normalize(ve);
1955                                                                 if ((dist < outerfacethickness)&&(dist < mindistedge )){
1956                                                                         VECCOPY(coledge,ve);
1957                                                                         mindistedge = dist,
1958                                                                                 deflected=1;
1959                                                                 }
1960                                                         
1961                                                         }
1962
1963
1964                                                 }
1965                                         }
1966                                         mface++;
1967                                         mima++;                                 
1968                                 }/* while a */          
1969                         } /* if(ob->pd && ob->pd->deflect) */
1970                         BLI_ghashIterator_step(ihash);
1971         } /* while () */
1972
1973         if (deflected == 1){ // no face but 'outer' edge cylinder sees vert
1974                 force_mag_norm =(float)exp(-ee*mindistedge);
1975                 if (mindistedge > outerfacethickness*ff)
1976                         force_mag_norm =(float)force_mag_norm*fa*(mindistedge - outerfacethickness)*(mindistedge - outerfacethickness);
1977                 Vec3PlusStVec(force,force_mag_norm,coledge);
1978                 *damp=ob->pd->pdef_sbdamp;
1979                 if (mindistedge > 0.0f){
1980                         *damp *= (1.0f - mindistedge/outerfacethickness);
1981                 }
1982
1983         }
1984         if (deflected == 2){ //  face inner detected
1985                 VECADD(force,force,innerforceaccu);
1986         }
1987         if (deflected == 3){ //  face outer detected
1988                 VECADD(force,force,outerforceaccu);
1989         }
1990
1991         BLI_ghashIterator_free(ihash);
1992         if (cavel) VecMulf(avel,1.0f/(float)cavel);
1993         VECCOPY(vel,avel);
1994         if (ci) *intrusion /= ci;
1995         if (deflected){ 
1996                 VECCOPY(facenormal,force);
1997                 Normalize(facenormal);
1998         }
1999         return deflected;       
2000 }
2001
2002
2003 /* sandbox to plug in various deflection algos */
2004 static int sb_deflect_face(Object *ob,float *actpos,float *facenormal,float *force,float *cf,float time,float *vel,float *intrusion)
2005 {
2006         float s_actpos[3];
2007         int deflected;  
2008         VECCOPY(s_actpos,actpos);
2009         deflected= sb_detect_vertex_collisionCached(s_actpos, facenormal, cf, force , ob->lay, ob,time,vel,intrusion);
2010         //deflected= sb_detect_vertex_collisionCachedEx(s_actpos, facenormal, cf, force , ob->lay, ob,time,vel,intrusion);
2011         return(deflected);
2012 }
2013
2014 /* hiding this for now .. but the jacobian may pop up on other tasks .. so i'd like to keep it
2015 static void dfdx_spring(int ia, int ic, int op, float dir[3],float L,float len,float factor)
2016
2017         float m,delta_ij;
2018         int i ,j;
2019         if (L < len){
2020                 for(i=0;i<3;i++)
2021                         for(j=0;j<3;j++){
2022                                 delta_ij = (i==j ? (1.0f): (0.0f));
2023                                 m=factor*(dir[i]*dir[j] + (1-L/len)*(delta_ij - dir[i]*dir[j]));
2024                                 nlMatrixAdd(ia+i,op+ic+j,m);
2025                         }
2026         }
2027         else{
2028                 for(i=0;i<3;i++)
2029                         for(j=0;j<3;j++){
2030                                 m=factor*dir[i]*dir[j];
2031                                 nlMatrixAdd(ia+i,op+ic+j,m);
2032                         }
2033         }
2034 }
2035
2036
2037 static void dfdx_goal(int ia, int ic, int op, float factor)
2038
2039         int i;
2040         for(i=0;i<3;i++) nlMatrixAdd(ia+i,op+ic+i,factor);
2041 }
2042
2043 static void dfdv_goal(int ia, int ic,float factor)
2044
2045         int i;
2046         for(i=0;i<3;i++) nlMatrixAdd(ia+i,ic+i,factor);
2047 }
2048 */
2049 static void sb_spring_force(Object *ob,int bpi,BodySpring *bs,float iks,float forcetime,int nl_flags)
2050 {
2051         SoftBody *sb= ob->soft; /* is supposed to be there */
2052         BodyPoint  *bp1,*bp2;
2053
2054         float dir[3],dvel[3];
2055         float distance,forcefactor,kd,absvel,projvel,kw;
2056         int ia,ic;
2057         /* prepare depending on which side of the spring we are on */
2058         if (bpi == bs->v1){
2059                 bp1 = &sb->bpoint[bs->v1];
2060                 bp2 = &sb->bpoint[bs->v2];
2061                 ia =3*bs->v1;
2062                 ic =3*bs->v2;
2063         }
2064         else if (bpi == bs->v2){
2065                 bp1 = &sb->bpoint[bs->v2];
2066                 bp2 = &sb->bpoint[bs->v1];
2067                 ia =3*bs->v2;
2068                 ic =3*bs->v1;
2069         }
2070         else{
2071                 /* TODO make this debug option */
2072                 /**/
2073                 printf("bodypoint <bpi> is not attached to spring  <*bs> --> sb_spring_force()\n");
2074                 return;
2075         }
2076
2077         /* do bp1 <--> bp2 elastic */
2078         VecSubf(dir,bp1->pos,bp2->pos);
2079         distance = Normalize(dir);
2080         if (bs->len < distance)
2081                 iks  = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
2082         else
2083                 iks  = 1.0f/(1.0f-sb->inpush)-1.0f ;/* inner spring constants function */
2084
2085         if(bs->len > 0.0f) /* check for degenerated springs */
2086                 forcefactor = iks/bs->len;
2087         else
2088                 forcefactor = iks;
2089             kw = (bp1->springweight+bp2->springweight)/2.0f;
2090                 kw = kw * kw;
2091                 kw = kw * kw;
2092         forcefactor *= bs->strength * kw; 
2093         Vec3PlusStVec(bp1->force,(bs->len - distance)*forcefactor,dir);
2094
2095         /* do bp1 <--> bp2 viscous */
2096         VecSubf(dvel,bp1->vec,bp2->vec);
2097         kd = sb->infrict * sb_fric_force_scale(ob);
2098         absvel  = Normalize(dvel);
2099         projvel = Inpf(dir,dvel);
2100         kd     *= absvel * projvel;
2101         Vec3PlusStVec(bp1->force,-kd,dir);
2102
2103         /* do jacobian stuff if needed */
2104         if(nl_flags & NLF_BUILD){
2105                 //int op =3*sb->totpoint;
2106                 //float mvel = -forcetime*kd;
2107                 //float mpos = -forcetime*forcefactor;
2108                 /* depending on my pos */ 
2109                 // dfdx_spring(ia,ia,op,dir,bs->len,distance,-mpos);
2110                 /* depending on my vel */
2111                 // dfdv_goal(ia,ia,mvel); // well that ignores geometie
2112                 if(bp2->goal < SOFTGOALSNAP){ /* ommit this bp when it snaps */
2113                         /* depending on other pos */ 
2114                         // dfdx_spring(ia,ic,op,dir,bs->len,distance,mpos);
2115                         /* depending on other vel */
2116                         // dfdv_goal(ia,ia,-mvel); // well that ignores geometie
2117                 }
2118         }
2119 }
2120
2121
2122 /* since this is definitely the most CPU consuming task here .. try to spread it */
2123 /* core function _softbody_calc_forces_slice_in_a_thread */
2124 /* result is int to be able to flag user break */
2125 static int _softbody_calc_forces_slice_in_a_thread(Object *ob, float forcetime, float timenow,int ifirst,int ilast,int *ptr_to_break_func(),ListBase *do_effector,int do_deflector,float fieldfactor, float windfactor)
2126 {
2127         float iks;
2128         int bb,do_selfcollision,do_springcollision,do_aero;
2129         int number_of_points_here = ilast - ifirst;
2130         SoftBody *sb= ob->soft; /* is supposed to be there */
2131         BodyPoint  *bp;
2132         /* intitialize */
2133         if (sb) {
2134         /* check conditions for various options */
2135     /* +++ could be done on object level to squeeze out the last bits of it */
2136         do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF));
2137         do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL);
2138         do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES));
2139     /* --- could be done on object level to squeeze out the last bits of it */
2140         }
2141         else {
2142                 printf("Error expected a SB here \n");
2143                 return (999);
2144         }
2145
2146 /* debugerin */
2147         if  (sb->totpoint < ifirst) {
2148                 printf("Aye 998");
2149                 return (998);
2150         }
2151 /* debugerin */
2152
2153
2154         bp = &sb->bpoint[ifirst]; 
2155         for(bb=number_of_points_here; bb>0; bb--, bp++) {
2156                 /* clear forces  accumulator */
2157                 bp->force[0]= bp->force[1]= bp->force[2]= 0.0;
2158                 /* naive ball self collision */
2159                 /* needs to be done if goal snaps or not */
2160                 if(do_selfcollision){
2161                                 int attached;
2162                                 BodyPoint   *obp;
2163                                 BodySpring *bs; 
2164                                 int c,b;
2165                                 float velcenter[3],dvel[3],def[3];
2166                                 float distance;
2167                                 float compare;
2168                 float bstune = sb->ballstiff;
2169
2170                                 for(c=sb->totpoint, obp= sb->bpoint; c>=ifirst+bb; c--, obp++) {
2171                                         compare = (obp->colball + bp->colball);         
2172                                         VecSubf(def, bp->pos, obp->pos);
2173                                         /* rather check the AABBoxes before ever calulating the real distance */
2174                                         /* mathematically it is completly nuts, but performace is pretty much (3) times faster */
2175                                         if ((ABS(def[0]) > compare) || (ABS(def[1]) > compare) || (ABS(def[2]) > compare)) continue;
2176                     distance = Normalize(def);
2177                                         if (distance < compare ){
2178                                                 /* exclude body points attached with a spring */
2179                                                 attached = 0;
2180                                                 for(b=obp->nofsprings;b>0;b--){
2181                                                         bs = sb->bspring + obp->springs[b-1];
2182                                                         if (( ilast-bb == bs->v2)  || ( ilast-bb == bs->v1)){
2183                                                                 attached=1;
2184                                                                 continue;}
2185                                                 }
2186                                                 if (!attached){
2187                                                         float f = bstune/(distance) + bstune/(compare*compare)*distance - 2.0f*bstune/compare ;
2188
2189                                                         VecMidf(velcenter, bp->vec, obp->vec);
2190                                                         VecSubf(dvel,velcenter,bp->vec);
2191                                                         VecMulf(dvel,bp->mass);
2192
2193                                                         Vec3PlusStVec(bp->force,f*(1.0f-sb->balldamp),def);
2194                                                         Vec3PlusStVec(bp->force,sb->balldamp,dvel);
2195
2196                                                         /* exploit force(a,b) == -force(b,a) part2/2 */
2197                                                         VecSubf(dvel,velcenter,obp->vec);
2198                                                         VecMulf(dvel,bp->mass);
2199
2200                                                         Vec3PlusStVec(obp->force,sb->balldamp,dvel);
2201                                                         Vec3PlusStVec(obp->force,-f*(1.0f-sb->balldamp),def);
2202                                                 }
2203                                         }
2204                                 }
2205                 }
2206                 /* naive ball self collision done */
2207
2208                 if(bp->goal < SOFTGOALSNAP){ /* ommit this bp when it snaps */
2209                         float auxvect[3];  
2210                         float velgoal[3];
2211
2212                         /* do goal stuff */
2213                         if(ob->softflag & OB_SB_GOAL) {
2214                                 /* true elastic goal */
2215                                 float ks,kd;
2216                                 VecSubf(auxvect,bp->pos,bp->origT);
2217                                 ks  = 1.0f/(1.0f- bp->goal*sb->goalspring)-1.0f ;
2218                                 bp->force[0]+= -ks*(auxvect[0]);
2219                                 bp->force[1]+= -ks*(auxvect[1]);
2220                                 bp->force[2]+= -ks*(auxvect[2]);
2221
2222                                 /* calulate damping forces generated by goals*/
2223                                 VecSubf(velgoal,bp->origS, bp->origE);
2224                                 kd =  sb->goalfrict * sb_fric_force_scale(ob) ;
2225                                 VecAddf(auxvect,velgoal,bp->vec);
2226                                 
2227                                 if (forcetime > 0.0 ) { /* make sure friction does not become rocket motor on time reversal */
2228                                         bp->force[0]-= kd * (auxvect[0]);
2229                                         bp->force[1]-= kd * (auxvect[1]);
2230                                         bp->force[2]-= kd * (auxvect[2]);
2231                                 }
2232                                 else {
2233                                         bp->force[0]-= kd * (velgoal[0] - bp->vec[0]);
2234                                         bp->force[1]-= kd * (velgoal[1] - bp->vec[1]);
2235                                         bp->force[2]-= kd * (velgoal[2] - bp->vec[2]);
2236                                 }
2237                         }
2238                         /* done goal stuff */
2239                         
2240                         /* gravitation */
2241                         if (sb){ 
2242                         float gravity = sb->grav * sb_grav_force_scale(ob);     
2243                         bp->force[2]-= gravity*bp->mass; /* individual mass of node here */
2244                         }
2245                         
2246                         /* particle field & vortex */
2247                         if(do_effector) {
2248                                 float kd;
2249                                 float force[3]= {0.0f, 0.0f, 0.0f};
2250                                 float speed[3]= {0.0f, 0.0f, 0.0f};
2251                                 float eval_sb_fric_force_scale = sb_fric_force_scale(ob); /* just for calling function once */
2252                                 
2253                                 pdDoEffectors(do_effector, bp->pos, force, speed, (float)G.scene->r.cfra, 0.0f, PE_WIND_AS_SPEED);
2254                                 
2255                                 /* apply forcefield*/
2256                                 VecMulf(force,fieldfactor* eval_sb_fric_force_scale); 
2257                                 VECADD(bp->force, bp->force, force);
2258                                 
2259                                 /* BP friction in moving media */       
2260                                 kd= sb->mediafrict* eval_sb_fric_force_scale;  
2261                                 bp->force[0] -= kd * (bp->vec[0] + windfactor*speed[0]/eval_sb_fric_force_scale);
2262                                 bp->force[1] -= kd * (bp->vec[1] + windfactor*speed[1]/eval_sb_fric_force_scale);
2263                                 bp->force[2] -= kd * (bp->vec[2] + windfactor*speed[2]/eval_sb_fric_force_scale);
2264                                 /* now we'll have nice centrifugal effect for vortex */
2265                                 
2266                         }
2267                         else {
2268                                 /* BP friction in media (not) moving*/
2269                                 float kd = sb->mediafrict* sb_fric_force_scale(ob);  
2270                                 /* assume it to be proportional to actual velocity */
2271                                 bp->force[0]-= bp->vec[0]*kd;
2272                                 bp->force[1]-= bp->vec[1]*kd;
2273                                 bp->force[2]-= bp->vec[2]*kd;
2274                                 /* friction in media done */
2275                         }
2276                         /* +++cached collision targets */
2277                         bp->choke = 0.0f;
2278                         bp->choke2 = 0.0f;
2279                         bp->flag &= ~SBF_DOFUZZY;
2280                         if(do_deflector) {
2281                                 float cfforce[3],defforce[3] ={0.0f,0.0f,0.0f}, vel[3] = {0.0f,0.0f,0.0f}, facenormal[3], cf = 1.0f,intrusion;
2282                                 float kd = 1.0f;
2283
2284                                 if (sb_deflect_face(ob,bp->pos,facenormal,defforce,&cf,timenow,vel,&intrusion)){
2285                                                 if (intrusion < 0.0f){
2286                                                         sb->scratch->flag |= SBF_DOFUZZY;
2287                                                         bp->flag |= SBF_DOFUZZY;
2288                                                         bp->choke = sb->choke*0.01f;
2289                                                 }
2290
2291                                                         VECSUB(cfforce,bp->vec,vel);
2292                                                         Vec3PlusStVec(bp->force,-cf*50.0f,cfforce);
2293                                         
2294                                         Vec3PlusStVec(bp->force,kd,defforce);  
2295                                 }
2296
2297                         }
2298                         /* ---cached collision targets */
2299
2300                         /* +++springs */
2301                         iks  = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
2302                         if(ob->softflag & OB_SB_EDGES) {
2303                                 if (sb->bspring){ /* spring list exists at all ? */
2304                                         int b;
2305                                         BodySpring *bs; 
2306                                         for(b=bp->nofsprings;b>0;b--){
2307                                                 bs = sb->bspring + bp->springs[b-1];
2308                                                 if (do_springcollision || do_aero){
2309                                                         VecAddf(bp->force,bp->force,bs->ext_force);
2310                                                         if (bs->flag & BSF_INTERSECT)
2311                                                                 bp->choke = bs->cf; 
2312
2313                                                 }
2314                         // sb_spring_force(Object *ob,int bpi,BodySpring *bs,float iks,float forcetime,int nl_flags)
2315                                                 sb_spring_force(ob,ilast-bb,bs,iks,forcetime,0);
2316                                         }/* loop springs */
2317                                 }/* existing spring list */ 
2318                         }/*any edges*/
2319                         /* ---springs */
2320                 }/*omit on snap */
2321         }/*loop all bp's*/
2322 return 0; /*done fine*/
2323 }
2324
2325 static void *exec_softbody_calc_forces(void *data)
2326 {
2327         SB_thread_context *pctx = (SB_thread_context*)data;
2328     _softbody_calc_forces_slice_in_a_thread(pctx->ob,pctx->forcetime,pctx->timenow,pctx->ifirst,pctx->ilast,NULL,pctx->do_effector,pctx->do_deflector,pctx->fieldfactor,pctx->windfactor);
2329         return 0;
2330
2331
2332 static void sb_cf_threads_run(struct Object *ob, float forcetime, float timenow,int totpoint,int *ptr_to_break_func(),struct ListBase *do_effector,int do_deflector,float fieldfactor, float windfactor)
2333 {
2334         ListBase threads;
2335         SB_thread_context *sb_threads;
2336         int i, totthread,left,dec;
2337         int lowpoints =100; /* wild guess .. may increase with better thread management 'above' or even be UI option sb->spawn_cf_threads_nopts */
2338
2339         /* figure the number of threads while preventing pretty pointless threading overhead */
2340         if(G.scene->r.mode & R_FIXED_THREADS)
2341                 totthread= G.scene->r.threads;
2342         else
2343                 totthread= BLI_system_thread_count();
2344         /* what if we got zillions of CPUs running but less to spread*/
2345         while ((totpoint/totthread < lowpoints) && (totthread > 1)) {
2346                 totthread--;
2347         }
2348
2349     /* printf("sb_cf_threads_run spawning %d threads \n",totthread); */
2350
2351         sb_threads= MEM_callocN(sizeof(SB_thread_context)*totthread, "SBThread");
2352         memset(sb_threads, 0, sizeof(SB_thread_context)*totthread);
2353         left = totpoint;
2354         dec = totpoint/totthread +1;
2355         for(i=0; i<totthread; i++) {
2356                 sb_threads[i].ob = ob; 
2357                 sb_threads[i].forcetime = forcetime; 
2358                 sb_threads[i].timenow = timenow; 
2359                 sb_threads[i].ilast   = left; 
2360                 left = left - dec;
2361                 if (left >0){
2362                         sb_threads[i].ifirst  = left;
2363                 }
2364                 else
2365                         sb_threads[i].ifirst  = 0; 
2366         sb_threads[i].do_effector = do_effector;
2367         sb_threads[i].do_deflector = do_deflector;
2368                 sb_threads[i].fieldfactor = fieldfactor;
2369                 sb_threads[i].windfactor  = windfactor;
2370                 sb_threads[i].nr= i;
2371                 sb_threads[i].tot= totthread;
2372         }
2373
2374
2375         if(totthread > 1) {
2376                 BLI_init_threads(&threads, exec_softbody_calc_forces, totthread);
2377
2378                 for(i=0; i<totthread; i++)
2379                         BLI_insert_thread(&threads, &sb_threads[i]);
2380
2381                 BLI_end_threads(&threads);
2382         }
2383         else
2384                 exec_softbody_calc_forces(&sb_threads[0]);
2385     /* clean up */
2386         MEM_freeN(sb_threads);
2387 }
2388
2389 static void softbody_calc_forcesEx(Object *ob, float forcetime, float timenow, int nl_flags)
2390 {
2391 /* rule we never alter free variables :bp->vec bp->pos in here ! 
2392  * this will ruin adaptive stepsize AKA heun! (BM) 
2393  */
2394         SoftBody *sb= ob->soft; /* is supposed to be there */
2395         BodyPoint *bproot;
2396         ListBase *do_effector;
2397         float iks, gravity;
2398         float fieldfactor = -1.0f, windfactor  = 0.25;   
2399         int   do_deflector,do_selfcollision,do_springcollision,do_aero;
2400         
2401         gravity = sb->grav * sb_grav_force_scale(ob);   
2402         
2403         /* check conditions for various options */
2404         do_deflector= query_external_colliders(ob);
2405         do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF));
2406         do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL);
2407         do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES));
2408         
2409         iks  = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
2410         bproot= sb->bpoint; /* need this for proper spring addressing */
2411         
2412         if (do_springcollision || do_aero)  
2413         sb_sfesf_threads_run(ob,timenow,sb->totspring,NULL);    
2414         
2415         /* after spring scan because it uses Effoctors too */
2416         do_effector= pdInitEffectors(ob,NULL);
2417
2418         if (do_deflector) {
2419                 float defforce[3];
2420                 do_deflector = sb_detect_aabb_collisionCached(defforce,ob->lay,ob,timenow);
2421         }
2422
2423         sb_cf_threads_run(ob,forcetime,timenow,sb->totpoint,NULL,do_effector,do_deflector,fieldfactor,windfactor);
2424
2425         /* finally add forces caused by face collision */
2426         if (ob->softflag & OB_SB_FACECOLL) scan_for_ext_face_forces(ob,timenow);
2427         
2428         /* finish matrix and solve */
2429         if(do_effector) pdEndEffectors(do_effector);
2430 }
2431
2432
2433
2434
2435 static void softbody_calc_forces(Object *ob, float forcetime, float timenow, int nl_flags)
2436 {
2437         /* redirection to the new threaded Version */
2438         if (!(G.rt & 0x10)){ // 16
2439                 softbody_calc_forcesEx(ob, forcetime, timenow, nl_flags);
2440                 return;
2441         }
2442         else{
2443                 /* so the following will die  */
2444                 /* |||||||||||||||||||||||||| */
2445                 /* VVVVVVVVVVVVVVVVVVVVVVVVVV */
2446                 /*backward compatibility note:
2447                 fixing bug [17428] which forces adaptive step size to tiny steps 
2448                 in some situations 
2449                 .. keeping G.rt==17 0x11 option for old files 'needing' the bug*/
2450
2451                 /* rule we never alter free variables :bp->vec bp->pos in here ! 
2452                 * this will ruin adaptive stepsize AKA heun! (BM) 
2453                 */
2454                 SoftBody *sb= ob->soft; /* is supposed to be there */
2455                 BodyPoint  *bp;
2456                 BodyPoint *bproot;
2457                 BodySpring *bs; 
2458                 ListBase *do_effector;
2459                 float iks, ks, kd, gravity;
2460                 float fieldfactor = -1.0f, windfactor  = 0.25f;   
2461                 float tune = sb->ballstiff;
2462                 int a, b,  do_deflector,do_selfcollision,do_springcollision,do_aero;
2463
2464
2465                 /* jacobian
2466                 NLboolean success;
2467
2468                 if(nl_flags){
2469                 nlBegin(NL_SYSTEM);
2470                 nlBegin(NL_MATRIX);
2471                 }
2472                 */
2473
2474
2475                 gravity = sb->grav * sb_grav_force_scale(ob);   
2476
2477                 /* check conditions for various options */
2478                 do_deflector= query_external_colliders(ob);
2479                 do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF));
2480                 do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL);
2481                 do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES));
2482
2483                 iks  = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
2484                 bproot= sb->bpoint; /* need this for proper spring addressing */
2485
2486                 if (do_springcollision || do_aero)  scan_for_ext_spring_forces(ob,timenow);
2487                 /* after spring scan because it uses Effoctors too */
2488                 do_effector= pdInitEffectors(ob,NULL);
2489
2490                 if (do_deflector) {
2491                         float defforce[3];
2492                         do_deflector = sb_detect_aabb_collisionCached(defforce,ob->lay,ob,timenow);
2493                 }
2494
2495                 for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
2496                         /* clear forces  accumulator */
2497                         bp->force[0]= bp->force[1]= bp->force[2]= 0.0;
2498                         if(nl_flags & NLF_BUILD){
2499                                 //int ia =3*(sb->totpoint-a);
2500                                 //int op =3*sb->totpoint;
2501                                 /* dF/dV = v */ 
2502                                 /* jacobioan
2503                                 nlMatrixAdd(op+ia,ia,-forcetime);
2504                                 nlMatrixAdd(op+ia+1,ia+1,-forcetime);
2505                                 nlMatrixAdd(op+ia+2,ia+2,-forcetime);
2506
2507                                 nlMatrixAdd(ia,ia,1);
2508                                 nlMatrixAdd(ia+1,ia+1,1);
2509                                 nlMatrixAdd(ia+2,ia+2,1);
2510
2511                                 nlMatrixAdd(op+ia,op+ia,1);
2512                                 nlMatrixAdd(op+ia+1,op+ia+1,1);
2513                                 nlMatrixAdd(op+ia+2,op+ia+2,1);
2514                                 */
2515
2516
2517                         }
2518
2519                         /* naive ball self collision */
2520                         /* needs to be done if goal snaps or not */
2521                         if(do_selfcollision){
2522                                 int attached;
2523                                 BodyPoint   *obp;
2524                                 int c,b;
2525                                 float velcenter[3],dvel[3],def[3];
2526                                 float distance;
2527                                 float compare;
2528
2529                                 for(c=sb->totpoint, obp= sb->bpoint; c>=a; c--, obp++) {
2530
2531                                         //if ((bp->octantflag & obp->octantflag) == 0) continue;
2532
2533                                         compare = (obp->colball + bp->colball);         
2534                                         VecSubf(def, bp->pos, obp->pos);
2535
2536                                         /* rather check the AABBoxes before ever calulating the real distance */
2537                                         /* mathematically it is completly nuts, but performace is pretty much (3) times faster */
2538                                         if ((ABS(def[0]) > compare) || (ABS(def[1]) > compare) || (ABS(def[2]) > compare)) continue;
2539
2540                                         distance = Normalize(def);
2541                                         if (distance < compare ){
2542                                                 /* exclude body points attached with a spring */
2543                                                 attached = 0;
2544                                                 for(b=obp->nofsprings;b>0;b--){
2545                                                         bs = sb->bspring + obp->springs[b-1];
2546                                                         if (( sb->totpoint-a == bs->v2)  || ( sb->totpoint-a == bs->v1)){
2547                                                                 attached=1;
2548                                                                 continue;}
2549                                                 }
2550                                                 if (!attached){
2551                                                         float f = tune/(distance) + tune/(compare*compare)*distance - 2.0f*tune/compare ;
2552
2553                                                         VecMidf(velcenter, bp->vec, obp->vec);
2554                                                         VecSubf(dvel,velcenter,bp->vec);
2555                                                         VecMulf(dvel,bp->mass);
2556
2557                                                         Vec3PlusStVec(bp->force,f*(1.0f-sb->balldamp),def);
2558                                                         Vec3PlusStVec(bp->force,sb->balldamp,dvel);
2559
2560                                                         if(nl_flags & NLF_BUILD){
2561                                                                 //int ia =3*(sb->totpoint-a);
2562                                                                 //int ic =3*(sb->totpoint-c);
2563                                                                 //int op =3*sb->totpoint;
2564                                                                 //float mvel = forcetime*sb->nodemass*sb->balldamp;
2565                                                                 //float mpos = forcetime*tune*(1.0f-sb->balldamp);
2566                                                                 /*some quick and dirty entries to the jacobian*/
2567                                                                 //dfdx_goal(ia,ia,op,mpos);
2568                                                                 //dfdv_goal(ia,ia,mvel);
2569                                                                 /* exploit force(a,b) == -force(b,a) part1/2 */
2570                                                                 //dfdx_goal(ic,ic,op,mpos);
2571                                                                 //dfdv_goal(ic,ic,mvel);
2572
2573
2574                                                                 /*TODO sit down an X-out the true jacobian entries*/
2575                                                                 /*well does not make to much sense because the eigenvalues
2576                                                                 of the jacobian go negative; and negative eigenvalues
2577                                                                 on a complex iterative system z(n+1)=A * z(n) 
2578                                                                 give imaginary roots in the charcateristic polynom
2579                                                                 --> solutions that to z(t)=u(t)* exp ( i omega t) --> oscilations we don't want here 
2580                                                                 where u(t) is a unknown amplitude function (worst case rising fast)
2581                                                                 */ 
2582                                                         }
2583
2584                                                         /* exploit force(a,b) == -force(b,a) part2/2 */
2585                                                         VecSubf(dvel,velcenter,obp->vec);
2586                                                         VecMulf(dvel,(bp->mass+obp->mass)/2.0f);
2587
2588                                                         Vec3PlusStVec(obp->force,sb->balldamp,dvel);
2589                                                         Vec3PlusStVec(obp->force,-f*(1.0f-sb->balldamp),def);
2590
2591
2592                                                 }
2593                                         }
2594                                 }
2595                         }
2596                         /* naive ball self collision done */
2597
2598                         if(bp->goal < SOFTGOALSNAP){ /* ommit this bp when it snaps */
2599                                 float auxvect[3];  
2600                                 float velgoal[3];
2601
2602                                 /* do goal stuff */
2603                                 if(ob->softflag & OB_SB_GOAL) {
2604                                         /* true elastic goal */
2605                                         VecSubf(auxvect,bp->pos,bp->origT);
2606                                         ks  = 1.0f/(1.0f- bp->goal*sb->goalspring)-1.0f ;
2607                                         bp->force[0]+= -ks*(auxvect[0]);
2608                                         bp->force[1]+= -ks*(auxvect[1]);
2609                                         bp->force[2]+= -ks*(auxvect[2]);
2610
2611                                         if(nl_flags & NLF_BUILD){
2612                                                 //int ia =3*(sb->totpoint-a);
2613                                                 //int op =3*(sb->totpoint);
2614                                                 /* depending on my pos */ 
2615                                                 //dfdx_goal(ia,ia,op,ks*forcetime);
2616                                         }
2617
2618
2619                                         /* calulate damping forces generated by goals*/
2620                                         VecSubf(velgoal,bp->origS, bp->origE);
2621                                         kd =  sb->goalfrict * sb_fric_force_scale(ob) ;
2622                                         VecAddf(auxvect,velgoal,bp->vec);
2623
2624                                         if (forcetime > 0.0 ) { /* make sure friction does not become rocket motor on time reversal */
2625                                                 bp->force[0]-= kd * (auxvect[0]);
2626                                                 bp->force[1]-= kd * (auxvect[1]);
2627                                                 bp->force[2]-= kd * (auxvect[2]);
2628                                                 if(nl_flags & NLF_BUILD){
2629                                                         //int ia =3*(sb->totpoint-a);
2630                                                         Normalize(auxvect);
2631                                                         /* depending on my vel */ 
2632                                                         //dfdv_goal(ia,ia,kd*forcetime);
2633                                                 }
2634
2635                                         }
2636                                         else {
2637                                                 bp->force[0]-= kd * (velgoal[0] - bp->vec[0]);
2638                                                 bp->force[1]-= kd * (velgoal[1] - bp->vec[1]);
2639                                                 bp->force[2]-= kd * (velgoal[2] - bp->vec[2]);
2640                                         }
2641                                 }
2642                                 /* done goal stuff */
2643
2644
2645                                 /* gravitation */
2646                                 bp->force[2]-= gravity*bp->mass; /* individual mass of node here */
2647
2648
2649                                 /* particle field & vortex */
2650                                 if(do_effector) {
2651                                         float force[3]= {0.0f, 0.0f, 0.0f};
2652                                         float speed[3]= {0.0f, 0.0f, 0.0f};
2653                                         float eval_sb_fric_force_scale = sb_fric_force_scale(ob); /* just for calling function once */
2654
2655                                         pdDoEffectors(do_effector, bp->pos, force, speed, (float)G.scene->r.cfra, 0.0f, PE_WIND_AS_SPEED);
2656
2657                                         /* apply forcefield*/
2658                                         VecMulf(force,fieldfactor* eval_sb_fric_force_scale); 
2659                                         VECADD(bp->force, bp->force, force);
2660
2661                                         /* BP friction in moving media */       
2662                                         kd= sb->mediafrict* eval_sb_fric_force_scale;  
2663                                         bp->force[0] -= kd * (bp->vec[0] + windfactor*speed[0]/eval_sb_fric_force_scale);
2664                                         bp->force[1] -= kd * (bp->vec[1] + windfactor*speed[1]/eval_sb_fric_force_scale);
2665                                         bp->force[2] -= kd * (bp->vec[2] + windfactor*speed[2]/eval_sb_fric_force_scale);
2666                                         /* now we'll have nice centrifugal effect for vortex */
2667
2668                                 }
2669                                 else {
2670                                         /* BP friction in media (not) moving*/
2671                                         kd= sb->mediafrict* sb_fric_force_scale(ob);  
2672                                         /* assume it to be proportional to actual velocity */
2673                                         bp->force[0]-= bp->vec[0]*kd;
2674                                         bp->force[1]-= bp->vec[1]*kd;
2675                                         bp->force[2]-= bp->vec[2]*kd;