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