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