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