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