add some missing NULL checks, a few parts of the code used a pointer then checked...
[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
83 #include  "PIL_time.h"
84 // #include  "ONL_opennl.h" remove linking to ONL for now
85
86 /* callbacks for errors and interrupts and some goo */
87 static int (*SB_localInterruptCallBack)(void) = NULL;
88
89
90 /* ********** soft body engine ******* */
91
92 typedef enum {SB_EDGE=1, SB_BEND=2, SB_STIFFQUAD=3, SB_HANDLE=4} type_spring;
93
94 typedef struct BodySpring {
95         int v1, v2;
96         float len, cf, load;
97         float ext_force[3]; /* edges colliding and sailing */
98         type_spring springtype;
99         short flag;
100 } BodySpring;
101
102 typedef struct BodyFace {
103         int v1, v2, v3, v4;
104         float ext_force[3]; /* faces colliding */
105         short flag;
106 } BodyFace;
107
108 typedef struct ReferenceVert {
109         float pos[3]; /* position relative to com */
110         float mass;   /* node mass */
111 } ReferenceVert;
112
113 typedef struct ReferenceState {
114         float com[3]; /* center of mass*/
115         ReferenceVert *ivert; /* list of intial values */
116 } ReferenceState;
117
118
119 /*private scratch pad for caching and other data only needed when alive*/
120 typedef struct SBScratch {
121         GHash *colliderhash;
122         short needstobuildcollider;
123         short flag;
124         BodyFace *bodyface;
125         int totface;
126         float aabbmin[3], aabbmax[3];
127         ReferenceState Ref;
128 } SBScratch;
129
130 typedef struct  SB_thread_context {
131                 Scene *scene;
132                 Object *ob;
133                 float forcetime;
134                 float timenow;
135                 int ifirst;
136                 int ilast;
137                 ListBase *do_effector;
138                 int do_deflector;
139                 float fieldfactor;
140                 float windfactor;
141                 int nr;
142                 int tot;
143 } SB_thread_context;
144
145 #define NLF_BUILD  1
146 #define NLF_SOLVE  2
147
148 #define MID_PRESERVE 1
149
150 #define SOFTGOALSNAP  0.999f
151 /* if bp-> goal is above make it a *forced follow original* and skip all ODE stuff for this bp
152  * removes *unnecessary* stiffnes from ODE system
153  */
154 #define HEUNWARNLIMIT 1 /* 500 would be fine i think for detecting severe *stiff* stuff */
155
156
157 #define BSF_INTERSECT   1 /* edge intersects collider face */
158
159 /* private definitions for bodypoint states */
160 #define SBF_DOFUZZY          1 /* Bodypoint do fuzzy */
161 #define SBF_OUTOFCOLLISION   2 /* Bodypoint does not collide  */
162
163
164 #define BFF_INTERSECT   1 /* collider edge   intrudes face */
165 #define BFF_CLOSEVERT   2 /* collider vertex repulses face */
166
167
168 static float SoftHeunTol = 1.0f; /* humm .. this should be calculated from sb parameters and sizes */
169
170 /* local prototypes */
171 static void free_softbody_intern(SoftBody *sb);
172 /* aye this belongs to arith.c */
173 static void Vec3PlusStVec(float *v, float s, float *v1);
174
175 /*+++ frame based timing +++*/
176
177 /*physical unit of force is [kg * m / sec^2]*/
178
179 static float sb_grav_force_scale(Object *UNUSED(ob))
180 /* since unit of g is [m/sec^2] and F = mass * g we rescale unit mass of node to 1 gramm
181  * put it to a function here, so we can add user options later without touching simulation code
182  */
183 {
184         return (0.001f);
185 }
186
187 static float sb_fric_force_scale(Object *UNUSED(ob))
188 /* rescaling unit of drag [1 / sec] to somehow reasonable
189  * put it to a function here, so we can add user options later without touching simulation code
190  */
191 {
192         return (0.01f);
193 }
194
195 static float sb_time_scale(Object *ob)
196 /* defining the frames to *real* time relation */
197 {
198         SoftBody *sb= ob->soft; /* is supposed to be there */
199         if (sb) {
200                 return(sb->physics_speed);
201                 /*hrms .. this could be IPO as well :)
202                  estimated range [0.001 sluggish slug - 100.0 very fast (i hope ODE solver can handle that)]
203                  1 approx = a unit 1 pendulum at g = 9.8 [earth conditions]  has period 65 frames
204                  theory would give a 50 frames period .. so there must be something inaccurate .. looking for that (BM)
205                  */
206         }
207         return (1.0f);
208         /*
209         this would be frames/sec independent timing assuming 25 fps is default
210         but does not work very well with NLA
211                 return (25.0f/scene->r.frs_sec)
212         */
213 }
214 /*--- frame based timing ---*/
215
216 /* helper functions for everything is animatable jow_go_for2_5 +++++++*/
217 /* introducing them here, because i know: steps in properties  ( at frame timing )
218  * will cause unwanted responses of the softbody system (which does inter frame calculations )
219  * so first 'cure' would be: interpolate linear in time ..
220  * Q: why do i write this?
221  * A: because it happend once, that some eger coder 'streamlined' code to fail.
222  * We DO linear interpolation for goals .. and i think we should do on animated properties as well
223  */
224
225 /* animate sb->maxgoal, sb->mingoal */
226 static float _final_goal(Object *ob, BodyPoint *bp)/*jow_go_for2_5 */
227 {
228         float f = -1999.99f;
229         if (ob) {
230                 SoftBody *sb= ob->soft; /* is supposed to be there */
231                 if (!(ob->softflag & OB_SB_GOAL)) return (0.0f);
232                 if (sb&&bp) {
233                         if (bp->goal < 0.0f) return (0.0f);
234                         f = sb->mingoal + bp->goal*ABS(sb->maxgoal - sb->mingoal);
235                         f = pow(f, 4.0f);
236                         return (f);
237                 }
238         }
239         printf("_final_goal failed! sb or bp ==NULL\n");
240         return f; /*using crude but spot able values some times helps debuggin */
241 }
242
243 static float _final_mass(Object *ob, BodyPoint *bp)
244 {
245         if (ob) {
246                 SoftBody *sb= ob->soft; /* is supposed to be there */
247                 if (sb&&bp) {
248                         return(bp->mass*sb->nodemass);
249                 }
250         }
251         printf("_final_mass failed! sb or bp ==NULL\n");
252         return 1.0f;
253 }
254 /* helper functions for everything is animateble jow_go_for2_5 ------*/
255
256 /*+++ collider caching and dicing +++*/
257
258 /********************
259 for each target object/face the axis aligned bounding box (AABB) is stored
260 faces parallel to global axes
261 so only simple "value" in [min, max] ckecks are used
262 float operations still
263 */
264
265 /* just an ID here to reduce the prob for killing objects
266 ** ob->sumohandle points to we should not kill :)
267 */
268 static const int CCD_SAVETY = 190561;
269
270 typedef struct ccdf_minmax {
271         float minx, miny, minz, maxx, maxy, maxz;
272 } ccdf_minmax;
273
274
275
276 typedef struct ccd_Mesh {
277         int totvert, totface;
278         MVert *mvert;
279         MVert *mprevvert;
280         MFace *mface;
281         int savety;
282         ccdf_minmax *mima;
283         /* Axis Aligned Bounding Box AABB */
284         float bbmin[3];
285         float bbmax[3];
286 } ccd_Mesh;
287
288
289
290
291 static ccd_Mesh *ccd_mesh_make(Object *ob)
292 {
293         CollisionModifierData *cmd;
294         ccd_Mesh *pccd_M = NULL;
295         ccdf_minmax *mima = NULL;
296         MFace *mface=NULL;
297         float v[3], hull;
298         int i;
299
300         cmd =(CollisionModifierData *)modifiers_findByType(ob, eModifierType_Collision);
301
302         /* first some paranoia checks */
303         if (!cmd) return NULL;
304         if (!cmd->numverts || !cmd->numfaces) return NULL;
305
306         pccd_M = MEM_mallocN(sizeof(ccd_Mesh), "ccd_Mesh");
307         pccd_M->totvert = cmd->numverts;
308         pccd_M->totface = cmd->numfaces;
309         pccd_M->savety  = CCD_SAVETY;
310         pccd_M->bbmin[0]=pccd_M->bbmin[1]=pccd_M->bbmin[2]=1e30f;
311         pccd_M->bbmax[0]=pccd_M->bbmax[1]=pccd_M->bbmax[2]=-1e30f;
312         pccd_M->mprevvert=NULL;
313
314
315         /* blow it up with forcefield ranges */
316         hull = MAX2(ob->pd->pdef_sbift, ob->pd->pdef_sboft);
317
318         /* alloc and copy verts*/
319         pccd_M->mvert = MEM_dupallocN(cmd->xnew);
320         /* note that xnew coords are already in global space, */
321         /* determine the ortho BB */
322         for (i=0; i < pccd_M->totvert; i++) {
323                 /* evaluate limits */
324                 copy_v3_v3(v, pccd_M->mvert[i].co);
325                 pccd_M->bbmin[0] = MIN2(pccd_M->bbmin[0], v[0]-hull);
326                 pccd_M->bbmin[1] = MIN2(pccd_M->bbmin[1], v[1]-hull);
327                 pccd_M->bbmin[2] = MIN2(pccd_M->bbmin[2], v[2]-hull);
328
329                 pccd_M->bbmax[0] = MAX2(pccd_M->bbmax[0], v[0]+hull);
330                 pccd_M->bbmax[1] = MAX2(pccd_M->bbmax[1], v[1]+hull);
331                 pccd_M->bbmax[2] = MAX2(pccd_M->bbmax[2], v[2]+hull);
332
333         }
334         /* alloc and copy faces*/
335         pccd_M->mface = MEM_dupallocN(cmd->mfaces);
336
337         /* OBBs for idea1 */
338         pccd_M->mima = MEM_mallocN(sizeof(ccdf_minmax)*pccd_M->totface, "ccd_Mesh_Faces_mima");
339         mima  = pccd_M->mima;
340         mface = pccd_M->mface;
341
342
343         /* anyhoo we need to walk the list of faces and find OBB they live in */
344         for (i=0; i < pccd_M->totface; i++) {
345                 mima->minx=mima->miny=mima->minz=1e30f;
346                 mima->maxx=mima->maxy=mima->maxz=-1e30f;
347
348                 copy_v3_v3(v, pccd_M->mvert[mface->v1].co);
349                 mima->minx = MIN2(mima->minx, v[0]-hull);
350                 mima->miny = MIN2(mima->miny, v[1]-hull);
351                 mima->minz = MIN2(mima->minz, v[2]-hull);
352                 mima->maxx = MAX2(mima->maxx, v[0]+hull);
353                 mima->maxy = MAX2(mima->maxy, v[1]+hull);
354                 mima->maxz = MAX2(mima->maxz, v[2]+hull);
355
356                 copy_v3_v3(v, pccd_M->mvert[mface->v2].co);
357                 mima->minx = MIN2(mima->minx, v[0]-hull);
358                 mima->miny = MIN2(mima->miny, v[1]-hull);
359                 mima->minz = MIN2(mima->minz, v[2]-hull);
360                 mima->maxx = MAX2(mima->maxx, v[0]+hull);
361                 mima->maxy = MAX2(mima->maxy, v[1]+hull);
362                 mima->maxz = MAX2(mima->maxz, v[2]+hull);
363
364                 copy_v3_v3(v, pccd_M->mvert[mface->v3].co);
365                 mima->minx = MIN2(mima->minx, v[0]-hull);
366                 mima->miny = MIN2(mima->miny, v[1]-hull);
367                 mima->minz = MIN2(mima->minz, v[2]-hull);
368                 mima->maxx = MAX2(mima->maxx, v[0]+hull);
369                 mima->maxy = MAX2(mima->maxy, v[1]+hull);
370                 mima->maxz = MAX2(mima->maxz, v[2]+hull);
371
372                 if (mface->v4) {
373                         copy_v3_v3(v, pccd_M->mvert[mface->v4].co);
374                 mima->minx = MIN2(mima->minx, v[0]-hull);
375                 mima->miny = MIN2(mima->miny, v[1]-hull);
376                 mima->minz = MIN2(mima->minz, v[2]-hull);
377                 mima->maxx = MAX2(mima->maxx, v[0]+hull);
378                 mima->maxy = MAX2(mima->maxy, v[1]+hull);
379                 mima->maxz = MAX2(mima->maxz, v[2]+hull);
380                 }
381
382
383         mima++;
384         mface++;
385
386         }
387         return pccd_M;
388 }
389 static void ccd_mesh_update(Object *ob, ccd_Mesh *pccd_M)
390 {
391         CollisionModifierData *cmd;
392         ccdf_minmax *mima = NULL;
393         MFace *mface=NULL;
394         float v[3], hull;
395         int i;
396
397         cmd =(CollisionModifierData *)modifiers_findByType(ob, eModifierType_Collision);
398
399         /* first some paranoia checks */
400         if (!cmd) return;
401         if (!cmd->numverts || !cmd->numfaces) return;
402
403         if ((pccd_M->totvert != cmd->numverts) ||
404             (pccd_M->totface != cmd->numfaces))
405         {
406                 return;
407         }
408
409         pccd_M->bbmin[0]=pccd_M->bbmin[1]=pccd_M->bbmin[2]=1e30f;
410         pccd_M->bbmax[0]=pccd_M->bbmax[1]=pccd_M->bbmax[2]=-1e30f;
411
412
413         /* blow it up with forcefield ranges */
414         hull = MAX2(ob->pd->pdef_sbift, ob->pd->pdef_sboft);
415
416         /* rotate current to previous */
417         if (pccd_M->mprevvert) MEM_freeN(pccd_M->mprevvert);
418         pccd_M->mprevvert = pccd_M->mvert;
419         /* alloc and copy verts*/
420         pccd_M->mvert = MEM_dupallocN(cmd->xnew);
421         /* note that xnew coords are already in global space, */
422         /* determine the ortho BB */
423         for (i=0; i < pccd_M->totvert; i++) {
424                 /* evaluate limits */
425                 copy_v3_v3(v, pccd_M->mvert[i].co);
426                 pccd_M->bbmin[0] = MIN2(pccd_M->bbmin[0], v[0]-hull);
427                 pccd_M->bbmin[1] = MIN2(pccd_M->bbmin[1], v[1]-hull);
428                 pccd_M->bbmin[2] = MIN2(pccd_M->bbmin[2], v[2]-hull);
429
430                 pccd_M->bbmax[0] = MAX2(pccd_M->bbmax[0], v[0]+hull);
431                 pccd_M->bbmax[1] = MAX2(pccd_M->bbmax[1], v[1]+hull);
432                 pccd_M->bbmax[2] = MAX2(pccd_M->bbmax[2], v[2]+hull);
433
434                 /* evaluate limits */
435                 copy_v3_v3(v, pccd_M->mprevvert[i].co);
436                 pccd_M->bbmin[0] = MIN2(pccd_M->bbmin[0], v[0]-hull);
437                 pccd_M->bbmin[1] = MIN2(pccd_M->bbmin[1], v[1]-hull);
438                 pccd_M->bbmin[2] = MIN2(pccd_M->bbmin[2], v[2]-hull);
439
440                 pccd_M->bbmax[0] = MAX2(pccd_M->bbmax[0], v[0]+hull);
441                 pccd_M->bbmax[1] = MAX2(pccd_M->bbmax[1], v[1]+hull);
442                 pccd_M->bbmax[2] = MAX2(pccd_M->bbmax[2], v[2]+hull);
443
444         }
445
446         mima  = pccd_M->mima;
447         mface = pccd_M->mface;
448
449
450         /* anyhoo we need to walk the list of faces and find OBB they live in */
451         for (i=0; i < pccd_M->totface; i++) {
452                 mima->minx=mima->miny=mima->minz=1e30f;
453                 mima->maxx=mima->maxy=mima->maxz=-1e30f;
454
455                 copy_v3_v3(v, pccd_M->mvert[mface->v1].co);
456                 mima->minx = MIN2(mima->minx, v[0]-hull);
457                 mima->miny = MIN2(mima->miny, v[1]-hull);
458                 mima->minz = MIN2(mima->minz, v[2]-hull);
459                 mima->maxx = MAX2(mima->maxx, v[0]+hull);
460                 mima->maxy = MAX2(mima->maxy, v[1]+hull);
461                 mima->maxz = MAX2(mima->maxz, v[2]+hull);
462
463                 copy_v3_v3(v, pccd_M->mvert[mface->v2].co);
464                 mima->minx = MIN2(mima->minx, v[0]-hull);
465                 mima->miny = MIN2(mima->miny, v[1]-hull);
466                 mima->minz = MIN2(mima->minz, v[2]-hull);
467                 mima->maxx = MAX2(mima->maxx, v[0]+hull);
468                 mima->maxy = MAX2(mima->maxy, v[1]+hull);
469                 mima->maxz = MAX2(mima->maxz, v[2]+hull);
470
471                 copy_v3_v3(v, pccd_M->mvert[mface->v3].co);
472                 mima->minx = MIN2(mima->minx, v[0]-hull);
473                 mima->miny = MIN2(mima->miny, v[1]-hull);
474                 mima->minz = MIN2(mima->minz, v[2]-hull);
475                 mima->maxx = MAX2(mima->maxx, v[0]+hull);
476                 mima->maxy = MAX2(mima->maxy, v[1]+hull);
477                 mima->maxz = MAX2(mima->maxz, v[2]+hull);
478
479                 if (mface->v4) {
480                         copy_v3_v3(v, pccd_M->mvert[mface->v4].co);
481                 mima->minx = MIN2(mima->minx, v[0]-hull);
482                 mima->miny = MIN2(mima->miny, v[1]-hull);
483                 mima->minz = MIN2(mima->minz, v[2]-hull);
484                 mima->maxx = MAX2(mima->maxx, v[0]+hull);
485                 mima->maxy = MAX2(mima->maxy, v[1]+hull);
486                 mima->maxz = MAX2(mima->maxz, v[2]+hull);
487                 }
488
489
490                 copy_v3_v3(v, pccd_M->mprevvert[mface->v1].co);
491                 mima->minx = MIN2(mima->minx, v[0]-hull);
492                 mima->miny = MIN2(mima->miny, v[1]-hull);
493                 mima->minz = MIN2(mima->minz, v[2]-hull);
494                 mima->maxx = MAX2(mima->maxx, v[0]+hull);
495                 mima->maxy = MAX2(mima->maxy, v[1]+hull);
496                 mima->maxz = MAX2(mima->maxz, v[2]+hull);
497
498                 copy_v3_v3(v, pccd_M->mprevvert[mface->v2].co);
499                 mima->minx = MIN2(mima->minx, v[0]-hull);
500                 mima->miny = MIN2(mima->miny, v[1]-hull);
501                 mima->minz = MIN2(mima->minz, v[2]-hull);
502                 mima->maxx = MAX2(mima->maxx, v[0]+hull);
503                 mima->maxy = MAX2(mima->maxy, v[1]+hull);
504                 mima->maxz = MAX2(mima->maxz, v[2]+hull);
505
506                 copy_v3_v3(v, pccd_M->mprevvert[mface->v3].co);
507                 mima->minx = MIN2(mima->minx, v[0]-hull);
508                 mima->miny = MIN2(mima->miny, v[1]-hull);
509                 mima->minz = MIN2(mima->minz, v[2]-hull);
510                 mima->maxx = MAX2(mima->maxx, v[0]+hull);
511                 mima->maxy = MAX2(mima->maxy, v[1]+hull);
512                 mima->maxz = MAX2(mima->maxz, v[2]+hull);
513
514                 if (mface->v4) {
515                         copy_v3_v3(v, pccd_M->mprevvert[mface->v4].co);
516                 mima->minx = MIN2(mima->minx, v[0]-hull);
517                 mima->miny = MIN2(mima->miny, v[1]-hull);
518                 mima->minz = MIN2(mima->minz, v[2]-hull);
519                 mima->maxx = MAX2(mima->maxx, v[0]+hull);
520                 mima->maxy = MAX2(mima->maxy, v[1]+hull);
521                 mima->maxz = MAX2(mima->maxz, v[2]+hull);
522                 }
523
524
525         mima++;
526         mface++;
527
528         }
529         return;
530 }
531
532 static void ccd_mesh_free(ccd_Mesh *ccdm)
533 {
534         if (ccdm && (ccdm->savety == CCD_SAVETY )) { /*make sure we're not nuking objects we don't know*/
535                 MEM_freeN(ccdm->mface);
536                 MEM_freeN(ccdm->mvert);
537                 if (ccdm->mprevvert) MEM_freeN(ccdm->mprevvert);
538                 MEM_freeN(ccdm->mima);
539                 MEM_freeN(ccdm);
540                 ccdm = NULL;
541         }
542 }
543
544 static void ccd_build_deflector_hash(Scene *scene, Object *vertexowner, GHash *hash)
545 {
546         Base *base= scene->base.first;
547         Object *ob;
548
549         if (!hash) return;
550         while (base) {
551                 /*Only proceed for mesh object in same layer */
552                 if (base->object->type==OB_MESH && (base->lay & vertexowner->lay)) {
553                         ob= base->object;
554                         if ((vertexowner) && (ob == vertexowner)) {
555                                 /* if vertexowner is given  we don't want to check collision with owner object */
556                                 base = base->next;
557                                 continue;
558                         }
559
560                         /*+++ only with deflecting set */
561                         if (ob->pd && ob->pd->deflect && BLI_ghash_lookup(hash, ob) == NULL) {
562                                 ccd_Mesh *ccdmesh = ccd_mesh_make(ob);
563                                 BLI_ghash_insert(hash, ob, ccdmesh);
564                         }/*--- only with deflecting set */
565
566                 }/* mesh && layer*/
567                 base = base->next;
568         } /* while (base) */
569 }
570
571 static void ccd_update_deflector_hash(Scene *scene, Object *vertexowner, GHash *hash)
572 {
573         Base *base= scene->base.first;
574         Object *ob;
575
576         if ((!hash) || (!vertexowner)) return;
577         while (base) {
578                 /*Only proceed for mesh object in same layer */
579                 if (base->object->type==OB_MESH && (base->lay & vertexowner->lay)) {
580                         ob= base->object;
581                         if (ob == vertexowner) {
582                                 /* if vertexowner is given  we don't want to check collision with owner object */
583                                 base = base->next;
584                                 continue;
585                         }
586
587                         /*+++ only with deflecting set */
588                         if (ob->pd && ob->pd->deflect) {
589                                 ccd_Mesh *ccdmesh = BLI_ghash_lookup(hash, ob);
590                                 if (ccdmesh)
591                                         ccd_mesh_update(ob, ccdmesh);
592                         }/*--- only with deflecting set */
593
594                 }/* mesh && layer*/
595                 base = base->next;
596         } /* while (base) */
597 }
598
599
600
601
602 /*--- collider caching and dicing ---*/
603
604
605 static int count_mesh_quads(Mesh *me)
606 {
607         int a, result = 0;
608         MFace *mface= me->mface;
609
610         if (mface) {
611                 for (a=me->totface; a>0; a--, mface++) {
612                         if (mface->v4) result++;
613                 }
614         }
615         return result;
616 }
617
618 static void add_mesh_quad_diag_springs(Object *ob)
619 {
620         Mesh *me= ob->data;
621         MFace *mface= me->mface;
622         /*BodyPoint *bp;*/ /*UNUSED*/
623         BodySpring *bs, *bs_new;
624         int a;
625
626         if (ob->soft) {
627                 int nofquads;
628                 //float s_shear = ob->soft->shearstiff*ob->soft->shearstiff;
629
630                 nofquads = count_mesh_quads(me);
631                 if (nofquads) {
632                         /* resize spring-array to hold additional quad springs */
633                         bs_new= MEM_callocN((ob->soft->totspring + nofquads *2 )*sizeof(BodySpring), "bodyspring");
634                         memcpy(bs_new, ob->soft->bspring, (ob->soft->totspring )*sizeof(BodySpring));
635
636                         if (ob->soft->bspring)
637                                 MEM_freeN(ob->soft->bspring); /* do this before reassigning the pointer  or have a 1st class memory leak */
638                         ob->soft->bspring = bs_new;
639
640                         /* fill the tail */
641                         a = 0;
642                         bs = bs_new+ob->soft->totspring;
643                         /*bp= ob->soft->bpoint; */ /*UNUSED*/
644                         if (mface ) {
645                                 for (a=me->totface; a>0; a--, mface++) {
646                                         if (mface->v4) {
647                                                 bs->v1= mface->v1;
648                                                 bs->v2= mface->v3;
649                                                 bs->springtype   = SB_STIFFQUAD;
650                                                 bs++;
651                                                 bs->v1= mface->v2;
652                                                 bs->v2= mface->v4;
653                                                 bs->springtype   = SB_STIFFQUAD;
654                                                 bs++;
655
656                                         }
657                                 }
658                         }
659
660                         /* now we can announce new springs */
661                         ob->soft->totspring += nofquads *2;
662                 }
663         }
664 }
665
666 static void add_2nd_order_roller(Object *ob, float UNUSED(stiffness), int *counter, int addsprings)
667 {
668         /*assume we have a softbody*/
669         SoftBody *sb= ob->soft; /* is supposed to be there */
670         BodyPoint *bp, *bpo;
671         BodySpring *bs, *bs2, *bs3= NULL;
672         int a, b, c, notthis= 0, v0;
673         if (!sb->bspring) {return;} /* we are 2nd order here so 1rst should have been build :) */
674         /* first run counting  second run adding */
675         *counter = 0;
676         if (addsprings) bs3 = ob->soft->bspring+ob->soft->totspring;
677         for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
678                 /*scan for neighborhood*/
679                 bpo = NULL;
680                 v0  = (sb->totpoint-a);
681                 for (b=bp->nofsprings;b>0;b--) {
682                         bs = sb->bspring + bp->springs[b-1];
683                         /*nasty thing here that springs have two ends
684                         so here we have to make sure we examine the other */
685                         if (v0 == bs->v1) {
686                                 bpo = sb->bpoint+bs->v2;
687                                 notthis = bs->v2;
688                         }
689                         else {
690                         if (v0 == bs->v2) {
691                                 bpo = sb->bpoint+bs->v1;
692                                 notthis = bs->v1;
693                         }
694                         else {printf("oops we should not get here -  add_2nd_order_springs");}
695                         }
696                         if (bpo) {/* so now we have a 2nd order humpdidump */
697                                 for (c=bpo->nofsprings;c>0;c--) {
698                                         bs2 = sb->bspring + bpo->springs[c-1];
699                                         if ((bs2->v1 != notthis) && (bs2->v1 > v0)) {
700                                                 (*counter)++;/*hit */
701                                                 if (addsprings) {
702                                                         bs3->v1= v0;
703                                                         bs3->v2= bs2->v1;
704                                                         bs3->springtype   = SB_BEND;
705                                                         bs3++;
706                                                 }
707                                         }
708                                         if ((bs2->v2 !=notthis)&&(bs2->v2 > v0)) {
709                                         (*counter)++;/*hit */
710                                                 if (addsprings) {
711                                                         bs3->v1= v0;
712                                                         bs3->v2= bs2->v2;
713                                                         bs3->springtype   = SB_BEND;
714                                                         bs3++;
715                                                 }
716
717                                         }
718                                 }
719
720                         }
721
722                 }
723                 /*scan for neighborhood done*/
724         }
725 }
726
727
728 static void add_2nd_order_springs(Object *ob, float stiffness)
729 {
730         int counter = 0;
731         BodySpring *bs_new;
732         stiffness *=stiffness;
733
734         add_2nd_order_roller(ob, stiffness, &counter, 0); /* counting */
735         if (counter) {
736                 /* resize spring-array to hold additional springs */
737                 bs_new= MEM_callocN((ob->soft->totspring + counter )*sizeof(BodySpring), "bodyspring");
738                 memcpy(bs_new, ob->soft->bspring, (ob->soft->totspring )*sizeof(BodySpring));
739
740                 if (ob->soft->bspring)
741                         MEM_freeN(ob->soft->bspring);
742                 ob->soft->bspring = bs_new;
743
744                 add_2nd_order_roller(ob, stiffness, &counter, 1); /* adding */
745                 ob->soft->totspring += counter;
746         }
747 }
748
749 static void add_bp_springlist(BodyPoint *bp, int springID)
750 {
751         int *newlist;
752
753         if (bp->springs == NULL) {
754                 bp->springs = MEM_callocN(sizeof(int), "bpsprings");
755                 bp->springs[0] = springID;
756                 bp->nofsprings = 1;
757         }
758         else {
759                 bp->nofsprings++;
760                 newlist = MEM_callocN(bp->nofsprings * sizeof(int), "bpsprings");
761                 memcpy(newlist, bp->springs, (bp->nofsprings-1)* sizeof(int));
762                 MEM_freeN(bp->springs);
763                 bp->springs = newlist;
764                 bp->springs[bp->nofsprings-1] = springID;
765         }
766 }
767
768 /* do this once when sb is build
769 it is O(N^2) so scanning for springs every iteration is too expensive
770 */
771 static void build_bps_springlist(Object *ob)
772 {
773         SoftBody *sb= ob->soft; /* is supposed to be there */
774         BodyPoint *bp;
775         BodySpring *bs;
776         int a, b;
777
778         if (sb==NULL) return; /* paranoya check */
779
780         for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
781                 /* throw away old list */
782                 if (bp->springs) {
783                         MEM_freeN(bp->springs);
784                         bp->springs=NULL;
785                 }
786                 /* scan for attached inner springs */
787                 for (b=sb->totspring, bs= sb->bspring; b>0; b--, bs++) {
788                         if (( (sb->totpoint-a) == bs->v1) ) {
789                                 add_bp_springlist(bp, sb->totspring -b);
790                         }
791                         if (( (sb->totpoint-a) == bs->v2) ) {
792                                 add_bp_springlist(bp, sb->totspring -b);
793                         }
794                 }/*for springs*/
795         }/*for bp*/
796 }
797
798 static void calculate_collision_balls(Object *ob)
799 {
800         SoftBody *sb= ob->soft; /* is supposed to be there */
801         BodyPoint *bp;
802         BodySpring *bs;
803         int a, b, akku_count;
804         float min, max, akku;
805
806         if (sb==NULL) return; /* paranoya check */
807
808         for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
809                 bp->colball=0;
810                 akku =0.0f;
811                 akku_count=0;
812                 min = 1e22f;
813                 max = -1e22f;
814                 /* first estimation based on attached */
815                 for (b=bp->nofsprings;b>0;b--) {
816                         bs = sb->bspring + bp->springs[b-1];
817                         if (bs->springtype == SB_EDGE) {
818                         akku += bs->len;
819                         akku_count++,
820                         min = MIN2(bs->len, min);
821                         max = MAX2(bs->len, max);
822                         }
823                 }
824
825                 if (akku_count > 0) {
826                         if (sb->sbc_mode == SBC_MODE_MANUAL) {
827                                 bp->colball=sb->colball;
828                         }
829                         if (sb->sbc_mode == SBC_MODE_AVG) {
830                                 bp->colball = akku/(float)akku_count*sb->colball;
831                         }
832                         if (sb->sbc_mode == SBC_MODE_MIN) {
833                                 bp->colball=min*sb->colball;
834                         }
835                         if (sb->sbc_mode == SBC_MODE_MAX) {
836                                 bp->colball=max*sb->colball;
837                         }
838                         if (sb->sbc_mode == SBC_MODE_AVGMINMAX) {
839                                 bp->colball = (min + max)/2.0f*sb->colball;
840                         }
841                 }
842                 else bp->colball=0;
843         }/*for bp*/
844 }
845
846
847 /* creates new softbody if didn't exist yet, makes new points and springs arrays */
848 static void renew_softbody(Scene *scene, Object *ob, int totpoint, int totspring)
849 {
850         SoftBody *sb;
851         int i;
852         short softflag;
853         if (ob->soft==NULL) ob->soft= sbNew(scene);
854         else free_softbody_intern(ob->soft);
855         sb= ob->soft;
856         softflag=ob->softflag;
857
858         if (totpoint) {
859                 sb->totpoint= totpoint;
860                 sb->totspring= totspring;
861
862                 sb->bpoint= MEM_mallocN(totpoint*sizeof(BodyPoint), "bodypoint");
863                 if (totspring)
864                         sb->bspring= MEM_mallocN(totspring*sizeof(BodySpring), "bodyspring");
865
866                         /* initialize BodyPoint array */
867                 for (i=0; i<totpoint; i++) {
868                         BodyPoint *bp = &sb->bpoint[i];
869
870
871                         /* hum as far as i see this is overridden by _final_goal() now jow_go_for2_5 */
872                         /* sadly breaks compatibility with older versions */
873                         /* but makes goals behave the same for meshes, lattices and curves */
874                         if (softflag & OB_SB_GOAL) {
875                                 bp->goal= sb->defgoal;
876                         }
877                         else {
878                                 bp->goal= 0.0f;
879                                 /* so this will definily be below SOFTGOALSNAP */
880                         }
881
882                         bp->nofsprings= 0;
883                         bp->springs= NULL;
884                         bp->choke = 0.0f;
885                         bp->choke2 = 0.0f;
886                         bp->frozen = 1.0f;
887                         bp->colball = 0.0f;
888                         bp->loc_flag = 0;
889                         bp->springweight = 1.0f;
890                         bp->mass = 1.0f;
891                 }
892         }
893 }
894
895 static void free_softbody_baked(SoftBody *sb)
896 {
897         SBVertex *key;
898         int k;
899
900         for (k=0; k<sb->totkey; k++) {
901                 key= *(sb->keys + k);
902                 if (key) MEM_freeN(key);
903         }
904         if (sb->keys) MEM_freeN(sb->keys);
905
906         sb->keys= NULL;
907         sb->totkey= 0;
908 }
909 static void free_scratch(SoftBody *sb)
910 {
911         if (sb->scratch) {
912                 /* todo make sure everything is cleaned up nicly */
913                 if (sb->scratch->colliderhash) {
914                         BLI_ghash_free(sb->scratch->colliderhash, NULL,
915                                         (GHashValFreeFP) ccd_mesh_free); /*this hoepfully will free all caches*/
916                         sb->scratch->colliderhash = NULL;
917                 }
918                 if (sb->scratch->bodyface) {
919                         MEM_freeN(sb->scratch->bodyface);
920                 }
921                 if (sb->scratch->Ref.ivert) {
922                         MEM_freeN(sb->scratch->Ref.ivert);
923                 }
924                 MEM_freeN(sb->scratch);
925                 sb->scratch = NULL;
926         }
927
928 }
929
930 /* only frees internal data */
931 static void free_softbody_intern(SoftBody *sb)
932 {
933         if (sb) {
934                 int a;
935                 BodyPoint *bp;
936
937                 if (sb->bpoint) {
938                         for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
939                                 /* free spring list */
940                                 if (bp->springs != NULL) {
941                                         MEM_freeN(bp->springs);
942                                 }
943                         }
944                         MEM_freeN(sb->bpoint);
945                 }
946
947                 if (sb->bspring) MEM_freeN(sb->bspring);
948
949                 sb->totpoint= sb->totspring= 0;
950                 sb->bpoint= NULL;
951                 sb->bspring= NULL;
952
953                 free_scratch(sb);
954                 free_softbody_baked(sb);
955         }
956 }
957
958
959 /* ************ dynamics ********** */
960
961 /* the most general (micro physics correct) way to do collision
962 ** (only needs the current particle position)
963 **
964 ** it actually checks if the particle intrudes a short range force field generated
965 ** by the faces of the target object and returns a force to drive the particel out
966 ** the strenght of the field grows exponetially if the particle is on the 'wrong' side of the face
967 ** 'wrong' side : projection to the face normal is negative (all referred to a vertex in the face)
968 **
969 ** flaw of this: 'fast' particles as well as 'fast' colliding faces
970 ** give a 'tunnel' effect such that the particle passes through the force field
971 ** without ever 'seeing' it
972 ** this is fully compliant to heisenberg: h >= fuzzy(location) * fuzzy(time)
973 ** besides our h is way larger than in QM because forces propagate way slower here
974 ** we have to deal with fuzzy(time) in the range of 1/25 seconds (typical frame rate)
975 ** yup collision targets are not known here any better
976 ** and 1/25 second is looong compared to real collision events
977 ** Q: why not use 'simple' collision here like bouncing back a particle
978 **   --> reverting is velocity on the face normal
979 ** A: because our particles are not alone here
980 **    and need to tell their neighbors exactly what happens via spring forces
981 ** unless sbObjectStep( .. ) is called on sub frame timing level
982 ** BTW that also questions the use of a 'implicit' solvers on softbodies
983 ** since that would only valid for 'slow' moving collision targets and dito particles
984 */
985
986 /* aye this belongs to arith.c */
987 static void Vec3PlusStVec(float *v, float s, float *v1)
988 {
989         v[0] += s*v1[0];
990         v[1] += s*v1[1];
991         v[2] += s*v1[2];
992 }
993
994 /* +++ dependency information functions*/
995
996 static int are_there_deflectors(Scene *scene, unsigned int layer)
997 {
998         Base *base;
999
1000         for (base = scene->base.first; base; base= base->next) {
1001                 if ( (base->lay & layer) && base->object->pd) {
1002                         if (base->object->pd->deflect)
1003                                 return 1;
1004                 }
1005         }
1006         return 0;
1007 }
1008
1009 static int query_external_colliders(Scene *scene, Object *me)
1010 {
1011         return(are_there_deflectors(scene, me->lay));
1012 }
1013 /* --- dependency information functions*/
1014
1015
1016 /* +++ the aabb "force" section*/
1017 static int sb_detect_aabb_collisionCached(float UNUSED(force[3]), unsigned int UNUSED(par_layer), struct Object *vertexowner, float UNUSED(time))
1018 {
1019         Object *ob;
1020         SoftBody *sb=vertexowner->soft;
1021         GHash *hash;
1022         GHashIterator *ihash;
1023         float  aabbmin[3], aabbmax[3];
1024         int deflected=0;
1025 #if 0
1026         int a;
1027 #endif
1028
1029         if ((sb == NULL) || (sb->scratch ==NULL)) return 0;
1030         copy_v3_v3(aabbmin, sb->scratch->aabbmin);
1031         copy_v3_v3(aabbmax, sb->scratch->aabbmax);
1032
1033         hash  = vertexowner->soft->scratch->colliderhash;
1034         ihash = BLI_ghashIterator_new(hash);
1035         while (!BLI_ghashIterator_isDone(ihash) ) {
1036
1037                 ccd_Mesh *ccdm = BLI_ghashIterator_getValue     (ihash);
1038                 ob             = BLI_ghashIterator_getKey       (ihash);
1039                         /* only with deflecting set */
1040                         if (ob->pd && ob->pd->deflect) {
1041 #if 0                   /* UNUSED */
1042                                 MFace *mface= NULL;
1043                                 MVert *mvert= NULL;
1044                                 MVert *mprevvert= NULL;
1045                                 ccdf_minmax *mima= NULL;
1046 #endif
1047                                 if (ccdm) {
1048 #if 0                           /* UNUSED */
1049                                         mface= ccdm->mface;
1050                                         mvert= ccdm->mvert;
1051                                         mprevvert= ccdm->mprevvert;
1052                                         mima= ccdm->mima;
1053                                         a = ccdm->totface;
1054 #endif
1055                                         if ((aabbmax[0] < ccdm->bbmin[0]) ||
1056                                             (aabbmax[1] < ccdm->bbmin[1]) ||
1057                                             (aabbmax[2] < ccdm->bbmin[2]) ||
1058                                             (aabbmin[0] > ccdm->bbmax[0]) ||
1059                                             (aabbmin[1] > ccdm->bbmax[1]) ||
1060                                             (aabbmin[2] > ccdm->bbmax[2]) )
1061                                         {
1062                                                 /* boxes don't intersect */
1063                                                 BLI_ghashIterator_step(ihash);
1064                                                 continue;
1065                                         }
1066
1067                                         /* so now we have the 2 boxes overlapping */
1068                                         /* forces actually not used */
1069                                         deflected = 2;
1070
1071                                 }
1072                                 else {
1073                                         /*aye that should be cached*/
1074                                         printf("missing cache error\n");
1075                                         BLI_ghashIterator_step(ihash);
1076                                         continue;
1077                                 }
1078                         } /* if (ob->pd && ob->pd->deflect) */
1079                         BLI_ghashIterator_step(ihash);
1080         } /* while () */
1081         BLI_ghashIterator_free(ihash);
1082         return deflected;
1083 }
1084 /* --- the aabb section*/
1085
1086
1087 /* +++ the face external section*/
1088 static int sb_detect_face_pointCached(float face_v1[3], float face_v2[3], float face_v3[3], float *damp,
1089                                       float force[3], unsigned int UNUSED(par_layer), struct Object *vertexowner, float time)
1090 {
1091         Object *ob;
1092         GHash *hash;
1093         GHashIterator *ihash;
1094         float nv1[3], edge1[3], edge2[3], d_nvect[3], aabbmin[3], aabbmax[3];
1095         float facedist, outerfacethickness, tune = 10.f;
1096         int a, deflected=0;
1097
1098         aabbmin[0] = MIN3(face_v1[0], face_v2[0], face_v3[0]);
1099         aabbmin[1] = MIN3(face_v1[1], face_v2[1], face_v3[1]);
1100         aabbmin[2] = MIN3(face_v1[2], face_v2[2], face_v3[2]);
1101         aabbmax[0] = MAX3(face_v1[0], face_v2[0], face_v3[0]);
1102         aabbmax[1] = MAX3(face_v1[1], face_v2[1], face_v3[1]);
1103         aabbmax[2] = MAX3(face_v1[2], face_v2[2], face_v3[2]);
1104
1105         /* calculate face normal once again SIGH */
1106         sub_v3_v3v3(edge1, face_v1, face_v2);
1107         sub_v3_v3v3(edge2, face_v3, face_v2);
1108         cross_v3_v3v3(d_nvect, edge2, edge1);
1109         normalize_v3(d_nvect);
1110
1111
1112         hash  = vertexowner->soft->scratch->colliderhash;
1113         ihash = BLI_ghashIterator_new(hash);
1114         while (!BLI_ghashIterator_isDone(ihash) ) {
1115
1116                 ccd_Mesh *ccdm = BLI_ghashIterator_getValue     (ihash);
1117                 ob             = BLI_ghashIterator_getKey       (ihash);
1118                         /* only with deflecting set */
1119                         if (ob->pd && ob->pd->deflect) {
1120                                 MVert *mvert= NULL;
1121                                 MVert *mprevvert= NULL;
1122                                 if (ccdm) {
1123                                         mvert= ccdm->mvert;
1124                                         a    = ccdm->totvert;
1125                                         mprevvert= ccdm->mprevvert;
1126                                         outerfacethickness = ob->pd->pdef_sboft;
1127                                         if ((aabbmax[0] < ccdm->bbmin[0]) ||
1128                                             (aabbmax[1] < ccdm->bbmin[1]) ||
1129                                             (aabbmax[2] < ccdm->bbmin[2]) ||
1130                                             (aabbmin[0] > ccdm->bbmax[0]) ||
1131                                             (aabbmin[1] > ccdm->bbmax[1]) ||
1132                                             (aabbmin[2] > ccdm->bbmax[2]) )
1133                                         {
1134                                                 /* boxes don't intersect */
1135                                                 BLI_ghashIterator_step(ihash);
1136                                                 continue;
1137                                         }
1138
1139                                 }
1140                                 else {
1141                                         /*aye that should be cached*/
1142                                         printf("missing cache error\n");
1143                                         BLI_ghashIterator_step(ihash);
1144                                         continue;
1145                                 }
1146
1147
1148                                 /* use mesh*/
1149                                 if (mvert) {
1150                                         while (a) {
1151                                                 copy_v3_v3(nv1, mvert[a-1].co);
1152                                                 if (mprevvert) {
1153                                                         mul_v3_fl(nv1, time);
1154                                                         Vec3PlusStVec(nv1, (1.0f-time), mprevvert[a-1].co);
1155                                                 }
1156                                                 /* origin to face_v2*/
1157                                                 sub_v3_v3(nv1, face_v2);
1158                                                 facedist = dot_v3v3(nv1, d_nvect);
1159                                                 if (ABS(facedist)<outerfacethickness) {
1160                                                         if (isect_point_tri_prism_v3(nv1, face_v1, face_v2, face_v3) ) {
1161                                                                 float df;
1162                                                                 if (facedist > 0) {
1163                                                                         df = (outerfacethickness-facedist)/outerfacethickness;
1164                                                                 }
1165                                                                 else {
1166                                                                         df = (outerfacethickness+facedist)/outerfacethickness;
1167                                                                 }
1168
1169                                                                 *damp=df*tune*ob->pd->pdef_sbdamp;
1170
1171                                                                 df = 0.01f*exp(- 100.0f*df);
1172                                                                 Vec3PlusStVec(force, -df, d_nvect);
1173                                                                 deflected = 3;
1174                                                         }
1175                                                 }
1176                                                 a--;
1177                                         }/* while (a)*/
1178                                 } /* if (mvert) */
1179                         } /* if (ob->pd && ob->pd->deflect) */
1180                         BLI_ghashIterator_step(ihash);
1181         } /* while () */
1182         BLI_ghashIterator_free(ihash);
1183         return deflected;
1184 }
1185
1186
1187 static int sb_detect_face_collisionCached(float face_v1[3], float face_v2[3], float face_v3[3], float *damp,
1188                                           float force[3], unsigned int UNUSED(par_layer), struct Object *vertexowner, float time)
1189 {
1190         Object *ob;
1191         GHash *hash;
1192         GHashIterator *ihash;
1193         float nv1[3], nv2[3], nv3[3], nv4[3], edge1[3], edge2[3], d_nvect[3], aabbmin[3], aabbmax[3];
1194         float t, tune = 10.0f;
1195         int a, deflected=0;
1196
1197         aabbmin[0] = MIN3(face_v1[0], face_v2[0], face_v3[0]);
1198         aabbmin[1] = MIN3(face_v1[1], face_v2[1], face_v3[1]);
1199         aabbmin[2] = MIN3(face_v1[2], face_v2[2], face_v3[2]);
1200         aabbmax[0] = MAX3(face_v1[0], face_v2[0], face_v3[0]);
1201         aabbmax[1] = MAX3(face_v1[1], face_v2[1], face_v3[1]);
1202         aabbmax[2] = MAX3(face_v1[2], face_v2[2], face_v3[2]);
1203
1204         hash  = vertexowner->soft->scratch->colliderhash;
1205         ihash = BLI_ghashIterator_new(hash);
1206         while (!BLI_ghashIterator_isDone(ihash) ) {
1207
1208                 ccd_Mesh *ccdm = BLI_ghashIterator_getValue     (ihash);
1209                 ob             = BLI_ghashIterator_getKey       (ihash);
1210                         /* only with deflecting set */
1211                         if (ob->pd && ob->pd->deflect) {
1212                                 MFace *mface= NULL;
1213                                 MVert *mvert= NULL;
1214                                 MVert *mprevvert= NULL;
1215                                 ccdf_minmax *mima= NULL;
1216                                 if (ccdm) {
1217                                         mface= ccdm->mface;
1218                                         mvert= ccdm->mvert;
1219                                         mprevvert= ccdm->mprevvert;
1220                                         mima= ccdm->mima;
1221                                         a = ccdm->totface;
1222
1223                                         if ((aabbmax[0] < ccdm->bbmin[0]) ||
1224                                             (aabbmax[1] < ccdm->bbmin[1]) ||
1225                                             (aabbmax[2] < ccdm->bbmin[2]) ||
1226                                             (aabbmin[0] > ccdm->bbmax[0]) ||
1227                                             (aabbmin[1] > ccdm->bbmax[1]) ||
1228                                             (aabbmin[2] > ccdm->bbmax[2]) )
1229                                         {
1230                                                 /* boxes don't intersect */
1231                                                 BLI_ghashIterator_step(ihash);
1232                                                 continue;
1233                                         }
1234
1235                                 }
1236                                 else {
1237                                         /*aye that should be cached*/
1238                                         printf("missing cache error\n");
1239                                         BLI_ghashIterator_step(ihash);
1240                                         continue;
1241                                 }
1242
1243
1244                                 /* use mesh*/
1245                                 while (a--) {
1246                                         if (
1247                                                 (aabbmax[0] < mima->minx) ||
1248                                                 (aabbmin[0] > mima->maxx) ||
1249                                                 (aabbmax[1] < mima->miny) ||
1250                                                 (aabbmin[1] > mima->maxy) ||
1251                                                 (aabbmax[2] < mima->minz) ||
1252                                                 (aabbmin[2] > mima->maxz)
1253                                                 ) {
1254                                                 mface++;
1255                                                 mima++;
1256                                                 continue;
1257                                         }
1258
1259
1260                                         if (mvert) {
1261
1262                                                 copy_v3_v3(nv1, mvert[mface->v1].co);
1263                                                 copy_v3_v3(nv2, mvert[mface->v2].co);
1264                                                 copy_v3_v3(nv3, mvert[mface->v3].co);
1265                                                 if (mface->v4) {
1266                                                         copy_v3_v3(nv4, mvert[mface->v4].co);
1267                                                 }
1268                                                 if (mprevvert) {
1269                                                         mul_v3_fl(nv1, time);
1270                                                         Vec3PlusStVec(nv1, (1.0f-time), mprevvert[mface->v1].co);
1271
1272                                                         mul_v3_fl(nv2, time);
1273                                                         Vec3PlusStVec(nv2, (1.0f-time), mprevvert[mface->v2].co);
1274
1275                                                         mul_v3_fl(nv3, time);
1276                                                         Vec3PlusStVec(nv3, (1.0f-time), mprevvert[mface->v3].co);
1277
1278                                                         if (mface->v4) {
1279                                                                 mul_v3_fl(nv4, time);
1280                                                                 Vec3PlusStVec(nv4, (1.0f-time), mprevvert[mface->v4].co);
1281                                                         }
1282                                                 }
1283                                         }
1284
1285                                         /* switch origin to be nv2*/
1286                                         sub_v3_v3v3(edge1, nv1, nv2);
1287                                         sub_v3_v3v3(edge2, nv3, nv2);
1288                                         cross_v3_v3v3(d_nvect, edge2, edge1);
1289                                         normalize_v3(d_nvect);
1290                                         if (
1291                                                 isect_line_tri_v3(nv1, nv2, face_v1, face_v2, face_v3, &t, NULL) ||
1292                                                 isect_line_tri_v3(nv2, nv3, face_v1, face_v2, face_v3, &t, NULL) ||
1293                                                 isect_line_tri_v3(nv3, nv1, face_v1, face_v2, face_v3, &t, NULL) ) {
1294                                                 Vec3PlusStVec(force, -0.5f, d_nvect);
1295                                                 *damp=tune*ob->pd->pdef_sbdamp;
1296                                                 deflected = 2;
1297                                         }
1298                                         if (mface->v4) { /* quad */
1299                                                 /* switch origin to be nv4 */
1300                                                 sub_v3_v3v3(edge1, nv3, nv4);
1301                                                 sub_v3_v3v3(edge2, nv1, nv4);
1302                                                 cross_v3_v3v3(d_nvect, edge2, edge1);
1303                                                 normalize_v3(d_nvect);
1304                                                 if (
1305                                                         /* isect_line_tri_v3(nv1, nv3, face_v1, face_v2, face_v3, &t, NULL) ||
1306                                                          we did that edge already */
1307                                                         isect_line_tri_v3(nv3, nv4, face_v1, face_v2, face_v3, &t, NULL) ||
1308                                                         isect_line_tri_v3(nv4, nv1, face_v1, face_v2, face_v3, &t, NULL) ) {
1309                                                         Vec3PlusStVec(force, -0.5f, d_nvect);
1310                                                         *damp=tune*ob->pd->pdef_sbdamp;
1311                                                         deflected = 2;
1312                                                 }
1313                                         }
1314                                         mface++;
1315                                         mima++;
1316                                 }/* while a */
1317                         } /* if (ob->pd && ob->pd->deflect) */
1318                         BLI_ghashIterator_step(ihash);
1319         } /* while () */
1320         BLI_ghashIterator_free(ihash);
1321         return deflected;
1322 }
1323
1324
1325
1326 static void scan_for_ext_face_forces(Object *ob, float timenow)
1327 {
1328         SoftBody *sb = ob->soft;
1329         BodyFace *bf;
1330         int a;
1331         float damp=0.0f, choke=1.0f;
1332         float tune = -10.0f;
1333         float feedback[3];
1334
1335         if (sb && sb->scratch->totface) {
1336
1337
1338                 bf = sb->scratch->bodyface;
1339                 for (a=0; a<sb->scratch->totface; a++, bf++) {
1340                         bf->ext_force[0]=bf->ext_force[1]=bf->ext_force[2]=0.0f;
1341 /*+++edges intruding*/
1342                         bf->flag &= ~BFF_INTERSECT;
1343                         feedback[0]=feedback[1]=feedback[2]=0.0f;
1344                         if (sb_detect_face_collisionCached(sb->bpoint[bf->v1].pos, sb->bpoint[bf->v2].pos, sb->bpoint[bf->v3].pos,
1345                                 &damp,  feedback, ob->lay, ob, timenow)) {
1346                                 Vec3PlusStVec(sb->bpoint[bf->v1].force, tune, feedback);
1347                                 Vec3PlusStVec(sb->bpoint[bf->v2].force, tune, feedback);
1348                                 Vec3PlusStVec(sb->bpoint[bf->v3].force, tune, feedback);
1349 //                              Vec3PlusStVec(bf->ext_force, tune, feedback);
1350                                 bf->flag |= BFF_INTERSECT;
1351                                 choke = MIN2(MAX2(damp, choke), 1.0f);
1352                         }
1353
1354                         feedback[0]=feedback[1]=feedback[2]=0.0f;
1355                         if ((bf->v4) && (sb_detect_face_collisionCached(sb->bpoint[bf->v1].pos, sb->bpoint[bf->v3].pos, sb->bpoint[bf->v4].pos,
1356                                 &damp,  feedback, ob->lay, ob, timenow))) {
1357                                 Vec3PlusStVec(sb->bpoint[bf->v1].force, tune, feedback);
1358                                 Vec3PlusStVec(sb->bpoint[bf->v3].force, tune, feedback);
1359                                 Vec3PlusStVec(sb->bpoint[bf->v4].force, tune, feedback);
1360 //                              Vec3PlusStVec(bf->ext_force, tune, feedback);
1361                                 bf->flag |= BFF_INTERSECT;
1362                                 choke = MIN2(MAX2(damp, choke), 1.0f);
1363                         }
1364 /*---edges intruding*/
1365
1366 /*+++ close vertices*/
1367                         if (( bf->flag & BFF_INTERSECT)==0) {
1368                                 bf->flag &= ~BFF_CLOSEVERT;
1369                                 tune = -1.0f;
1370                                 feedback[0]=feedback[1]=feedback[2]=0.0f;
1371                                 if (sb_detect_face_pointCached(sb->bpoint[bf->v1].pos, sb->bpoint[bf->v2].pos, sb->bpoint[bf->v3].pos,
1372                                         &damp,  feedback, ob->lay, ob, timenow)) {
1373                                 Vec3PlusStVec(sb->bpoint[bf->v1].force, tune, feedback);
1374                                 Vec3PlusStVec(sb->bpoint[bf->v2].force, tune, feedback);
1375                                 Vec3PlusStVec(sb->bpoint[bf->v3].force, tune, feedback);
1376 //                                              Vec3PlusStVec(bf->ext_force, tune, feedback);
1377                                                 bf->flag |= BFF_CLOSEVERT;
1378                                                 choke = MIN2(MAX2(damp, choke), 1.0f);
1379                                 }
1380
1381                                 feedback[0]=feedback[1]=feedback[2]=0.0f;
1382                                 if ((bf->v4) && (sb_detect_face_pointCached(sb->bpoint[bf->v1].pos, sb->bpoint[bf->v3].pos, sb->bpoint[bf->v4].pos,
1383                                         &damp,  feedback, ob->lay, ob, timenow))) {
1384                                 Vec3PlusStVec(sb->bpoint[bf->v1].force, tune, feedback);
1385                                 Vec3PlusStVec(sb->bpoint[bf->v3].force, tune, feedback);
1386                                 Vec3PlusStVec(sb->bpoint[bf->v4].force, tune, feedback);
1387 //                                              Vec3PlusStVec(bf->ext_force, tune, feedback);
1388                                                 bf->flag |= BFF_CLOSEVERT;
1389                                                 choke = MIN2(MAX2(damp, choke), 1.0f);
1390                                 }
1391                         }
1392 /*--- close vertices*/
1393                 }
1394                 bf = sb->scratch->bodyface;
1395                 for (a=0; a<sb->scratch->totface; a++, bf++) {
1396                         if (( bf->flag & BFF_INTERSECT) || ( bf->flag & BFF_CLOSEVERT)) {
1397                                 sb->bpoint[bf->v1].choke2=MAX2(sb->bpoint[bf->v1].choke2, choke);
1398                                 sb->bpoint[bf->v2].choke2=MAX2(sb->bpoint[bf->v2].choke2, choke);
1399                                 sb->bpoint[bf->v3].choke2=MAX2(sb->bpoint[bf->v3].choke2, choke);
1400                                 if (bf->v4) {
1401                                 sb->bpoint[bf->v2].choke2=MAX2(sb->bpoint[bf->v2].choke2, choke);
1402                                 }
1403                         }
1404                 }
1405         }
1406 }
1407
1408 /*  --- the face external section*/
1409
1410
1411 /* +++ the spring external section*/
1412
1413 static int sb_detect_edge_collisionCached(float edge_v1[3], float edge_v2[3], float *damp,
1414                                                                    float force[3], unsigned int UNUSED(par_layer), struct Object *vertexowner, float time)
1415 {
1416         Object *ob;
1417         GHash *hash;
1418         GHashIterator *ihash;
1419         float nv1[3], nv2[3], nv3[3], nv4[3], edge1[3], edge2[3], d_nvect[3], aabbmin[3], aabbmax[3];
1420         float t, el;
1421         int a, deflected=0;
1422
1423         aabbmin[0] = MIN2(edge_v1[0], edge_v2[0]);
1424         aabbmin[1] = MIN2(edge_v1[1], edge_v2[1]);
1425         aabbmin[2] = MIN2(edge_v1[2], edge_v2[2]);
1426         aabbmax[0] = MAX2(edge_v1[0], edge_v2[0]);
1427         aabbmax[1] = MAX2(edge_v1[1], edge_v2[1]);
1428         aabbmax[2] = MAX2(edge_v1[2], edge_v2[2]);
1429
1430         el = len_v3v3(edge_v1, edge_v2);
1431
1432         hash  = vertexowner->soft->scratch->colliderhash;
1433         ihash = BLI_ghashIterator_new(hash);
1434         while (!BLI_ghashIterator_isDone(ihash) ) {
1435
1436                 ccd_Mesh *ccdm = BLI_ghashIterator_getValue     (ihash);
1437                 ob             = BLI_ghashIterator_getKey       (ihash);
1438                         /* only with deflecting set */
1439                         if (ob->pd && ob->pd->deflect) {
1440                                 MFace *mface= NULL;
1441                                 MVert *mvert= NULL;
1442                                 MVert *mprevvert= NULL;
1443                                 ccdf_minmax *mima= NULL;
1444                                 if (ccdm) {
1445                                         mface= ccdm->mface;
1446                                         mvert= ccdm->mvert;
1447                                         mprevvert= ccdm->mprevvert;
1448                                         mima= ccdm->mima;
1449                                         a = ccdm->totface;
1450
1451                                         if ((aabbmax[0] < ccdm->bbmin[0]) ||
1452                                             (aabbmax[1] < ccdm->bbmin[1]) ||
1453                                             (aabbmax[2] < ccdm->bbmin[2]) ||
1454                                             (aabbmin[0] > ccdm->bbmax[0]) ||
1455                                             (aabbmin[1] > ccdm->bbmax[1]) ||
1456                                             (aabbmin[2] > ccdm->bbmax[2]) )
1457                                         {
1458                                                 /* boxes don't intersect */
1459                                                 BLI_ghashIterator_step(ihash);
1460                                                 continue;
1461                                         }
1462
1463                                 }
1464                                 else {
1465                                         /*aye that should be cached*/
1466                                         printf("missing cache error\n");
1467                                         BLI_ghashIterator_step(ihash);
1468                                         continue;
1469                                 }
1470
1471
1472                                 /* use mesh*/
1473                                 while (a--) {
1474                                         if (
1475                                                 (aabbmax[0] < mima->minx) ||
1476                                                 (aabbmin[0] > mima->maxx) ||
1477                                                 (aabbmax[1] < mima->miny) ||
1478                                                 (aabbmin[1] > mima->maxy) ||
1479                                                 (aabbmax[2] < mima->minz) ||
1480                                                 (aabbmin[2] > mima->maxz)
1481                                                 ) {
1482                                                 mface++;
1483                                                 mima++;
1484                                                 continue;
1485                                         }
1486
1487
1488                                         if (mvert) {
1489
1490                                                 copy_v3_v3(nv1, mvert[mface->v1].co);
1491                                                 copy_v3_v3(nv2, mvert[mface->v2].co);
1492                                                 copy_v3_v3(nv3, mvert[mface->v3].co);
1493                                                 if (mface->v4) {
1494                                                         copy_v3_v3(nv4, mvert[mface->v4].co);
1495                                                 }
1496                                                 if (mprevvert) {
1497                                                         mul_v3_fl(nv1, time);
1498                                                         Vec3PlusStVec(nv1, (1.0f-time), mprevvert[mface->v1].co);
1499
1500                                                         mul_v3_fl(nv2, time);
1501                                                         Vec3PlusStVec(nv2, (1.0f-time), mprevvert[mface->v2].co);
1502
1503                                                         mul_v3_fl(nv3, time);
1504                                                         Vec3PlusStVec(nv3, (1.0f-time), mprevvert[mface->v3].co);
1505
1506                                                         if (mface->v4) {
1507                                                                 mul_v3_fl(nv4, time);
1508                                                                 Vec3PlusStVec(nv4, (1.0f-time), mprevvert[mface->v4].co);
1509                                                         }
1510                                                 }
1511                                         }
1512
1513                                         /* switch origin to be nv2*/
1514                                         sub_v3_v3v3(edge1, nv1, nv2);
1515                                         sub_v3_v3v3(edge2, nv3, nv2);
1516
1517                                         cross_v3_v3v3(d_nvect, edge2, edge1);
1518                                         normalize_v3(d_nvect);
1519                                         if ( isect_line_tri_v3(edge_v1, edge_v2, nv1, nv2, nv3, &t, NULL)) {
1520                                                 float v1[3], v2[3];
1521                                                 float intrusiondepth, i1, i2;
1522                                                 sub_v3_v3v3(v1, edge_v1, nv2);
1523                                                 sub_v3_v3v3(v2, edge_v2, nv2);
1524                                                 i1 = dot_v3v3(v1, d_nvect);
1525                                                 i2 = dot_v3v3(v2, d_nvect);
1526                                                 intrusiondepth = -MIN2(i1, i2)/el;
1527                                                 Vec3PlusStVec(force, intrusiondepth, d_nvect);
1528                                                 *damp=ob->pd->pdef_sbdamp;
1529                                                 deflected = 2;
1530                                         }
1531                                         if (mface->v4) { /* quad */
1532                                                 /* switch origin to be nv4 */
1533                                                 sub_v3_v3v3(edge1, nv3, nv4);
1534                                                 sub_v3_v3v3(edge2, nv1, nv4);
1535
1536                                                 cross_v3_v3v3(d_nvect, edge2, edge1);
1537                                                 normalize_v3(d_nvect);
1538                                                 if (isect_line_tri_v3( edge_v1, edge_v2, nv1, nv3, nv4, &t, NULL)) {
1539                                                         float v1[3], v2[3];
1540                                                         float intrusiondepth, i1, i2;
1541                                                         sub_v3_v3v3(v1, edge_v1, nv4);
1542                                                         sub_v3_v3v3(v2, edge_v2, nv4);
1543                                                 i1 = dot_v3v3(v1, d_nvect);
1544                                                 i2 = dot_v3v3(v2, d_nvect);
1545                                                 intrusiondepth = -MIN2(i1, i2)/el;
1546
1547
1548                                                         Vec3PlusStVec(force, intrusiondepth, d_nvect);
1549                                                         *damp=ob->pd->pdef_sbdamp;
1550                                                         deflected = 2;
1551                                                 }
1552                                         }
1553                                         mface++;
1554                                         mima++;
1555                                 }/* while a */
1556                         } /* if (ob->pd && ob->pd->deflect) */
1557                         BLI_ghashIterator_step(ihash);
1558         } /* while () */
1559         BLI_ghashIterator_free(ihash);
1560         return deflected;
1561 }
1562
1563 static void _scan_for_ext_spring_forces(Scene *scene, Object *ob, float timenow, int ifirst, int ilast, struct ListBase *do_effector)
1564 {
1565         SoftBody *sb = ob->soft;
1566         int a;
1567         float damp;
1568         float feedback[3];
1569
1570         if (sb && sb->totspring) {
1571                 for (a=ifirst; a<ilast; a++) {
1572                         BodySpring *bs = &sb->bspring[a];
1573                         bs->ext_force[0]=bs->ext_force[1]=bs->ext_force[2]=0.0f;
1574                         feedback[0]=feedback[1]=feedback[2]=0.0f;
1575                         bs->flag &= ~BSF_INTERSECT;
1576
1577                         if (bs->springtype == SB_EDGE) {
1578                                 /* +++ springs colliding */
1579                                 if (ob->softflag & OB_SB_EDGECOLL) {
1580                                         if ( sb_detect_edge_collisionCached (sb->bpoint[bs->v1].pos, sb->bpoint[bs->v2].pos,
1581                                                 &damp, feedback, ob->lay, ob, timenow)) {
1582                                                         add_v3_v3(bs->ext_force, feedback);
1583                                                         bs->flag |= BSF_INTERSECT;
1584                                                         //bs->cf=damp;
1585                                                         bs->cf=sb->choke*0.01f;
1586
1587                                         }
1588                                 }
1589                                 /* ---- springs colliding */
1590
1591                                 /* +++ springs seeing wind ... n stuff depending on their orientation*/
1592                                 /* note we don't use sb->mediafrict but use sb->aeroedge for magnitude of effect*/
1593                                 if (sb->aeroedge) {
1594                                         float vel[3], sp[3], pr[3], force[3];
1595                                         float f, windfactor  = 0.25f;
1596                                         /*see if we have wind*/
1597                                         if (do_effector) {
1598                                                 EffectedPoint epoint;
1599                                                 float speed[3]={0.0f, 0.0f, 0.0f};
1600                                                 float pos[3];
1601                                                 mid_v3_v3v3(pos, sb->bpoint[bs->v1].pos, sb->bpoint[bs->v2].pos);
1602                                                 mid_v3_v3v3(vel, sb->bpoint[bs->v1].vec, sb->bpoint[bs->v2].vec);
1603                                                 pd_point_from_soft(scene, pos, vel, -1, &epoint);
1604                                                 pdDoEffectors(do_effector, NULL, sb->effector_weights, &epoint, force, speed);
1605
1606                                                 mul_v3_fl(speed, windfactor);
1607                                                 add_v3_v3(vel, speed);
1608                                         }
1609                                         /* media in rest */
1610                                         else {
1611                                                 add_v3_v3v3(vel, sb->bpoint[bs->v1].vec, sb->bpoint[bs->v2].vec);
1612                                         }
1613                                         f = normalize_v3(vel);
1614                                         f = -0.0001f*f*f*sb->aeroedge;
1615                                         /* (todo) add a nice angle dependent function done for now BUT */
1616                                         /* still there could be some nice drag/lift function, but who needs it */
1617
1618                                         sub_v3_v3v3(sp, sb->bpoint[bs->v1].pos, sb->bpoint[bs->v2].pos);
1619                                         project_v3_v3v3(pr, vel, sp);
1620                                         sub_v3_v3(vel, pr);
1621                                         normalize_v3(vel);
1622                                         if (ob->softflag & OB_SB_AERO_ANGLE) {
1623                                                 normalize_v3(sp);
1624                                                 Vec3PlusStVec(bs->ext_force, f*(1.0f-ABS(dot_v3v3(vel, sp))), vel);
1625                                         }
1626                                         else {
1627                                                 Vec3PlusStVec(bs->ext_force, f, vel); // to keep compatible with 2.45 release files
1628                                         }
1629                                 }
1630                                 /* --- springs seeing wind */
1631                         }
1632                 }
1633         }
1634 }
1635
1636
1637 static void scan_for_ext_spring_forces(Scene *scene, Object *ob, float timenow)
1638 {
1639         SoftBody *sb = ob->soft;
1640         ListBase *do_effector = NULL;
1641
1642         do_effector = pdInitEffectors(scene, ob, NULL, sb->effector_weights);
1643         _scan_for_ext_spring_forces(scene, ob, timenow, 0, sb->totspring, do_effector);
1644         pdEndEffectors(&do_effector);
1645 }
1646
1647 static void *exec_scan_for_ext_spring_forces(void *data)
1648 {
1649         SB_thread_context *pctx = (SB_thread_context*)data;
1650         _scan_for_ext_spring_forces(pctx->scene, pctx->ob, pctx->timenow, pctx->ifirst, pctx->ilast, pctx->do_effector);
1651         return NULL;
1652 }
1653
1654 static void sb_sfesf_threads_run(Scene *scene, struct Object *ob, float timenow, int totsprings, int *UNUSED(ptr_to_break_func(void)))
1655 {
1656         ListBase *do_effector = NULL;
1657         ListBase threads;
1658         SB_thread_context *sb_threads;
1659         int i, totthread, left, dec;
1660         int lowsprings =100; /* wild guess .. may increase with better thread management 'above' or even be UI option sb->spawn_cf_threads_nopts */
1661
1662         do_effector= pdInitEffectors(scene, ob, NULL, ob->soft->effector_weights);
1663
1664         /* figure the number of threads while preventing pretty pointless threading overhead */
1665         if (scene->r.mode & R_FIXED_THREADS)
1666                 totthread= scene->r.threads;
1667         else
1668                 totthread= BLI_system_thread_count();
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_isDone(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         if (scene->r.mode & R_FIXED_THREADS)
2397                 totthread= scene->r.threads;
2398         else
2399                 totthread= BLI_system_thread_count();
2400         /* what if we got zillions of CPUs running but less to spread*/
2401         while ((totpoint/totthread < lowpoints) && (totthread > 1)) {
2402                 totthread--;
2403         }
2404
2405         /* printf("sb_cf_threads_run spawning %d threads\n", totthread); */
2406
2407         sb_threads= MEM_callocN(sizeof(SB_thread_context)*totthread, "SBThread");
2408         memset(sb_threads, 0, sizeof(SB_thread_context)*totthread);
2409         left = totpoint;
2410         dec = totpoint/totthread +1;
2411         for (i=0; i<totthread; i++) {
2412                 sb_threads[i].scene = scene;
2413                 sb_threads[i].ob = ob;
2414                 sb_threads[i].forcetime = forcetime;
2415                 sb_threads[i].timenow = timenow;
2416                 sb_threads[i].ilast   = left;
2417                 left = left - dec;
2418                 if (left >0) {
2419                         sb_threads[i].ifirst  = left;
2420                 }
2421                 else
2422                         sb_threads[i].ifirst  = 0;
2423                 sb_threads[i].do_effector = do_effector;
2424                 sb_threads[i].do_deflector = do_deflector;
2425                 sb_threads[i].fieldfactor = fieldfactor;
2426                 sb_threads[i].windfactor  = windfactor;
2427                 sb_threads[i].nr= i;
2428                 sb_threads[i].tot= totthread;
2429         }
2430
2431
2432         if (totthread > 1) {
2433                 BLI_init_threads(&threads, exec_softbody_calc_forces, totthread);
2434
2435                 for (i=0; i<totthread; i++)
2436                         BLI_insert_thread(&threads, &sb_threads[i]);
2437
2438                 BLI_end_threads(&threads);
2439         }
2440         else
2441                 exec_softbody_calc_forces(&sb_threads[0]);
2442         /* clean up */
2443         MEM_freeN(sb_threads);
2444 }
2445
2446 static void softbody_calc_forcesEx(Scene *scene, Object *ob, float forcetime, float timenow, int UNUSED(nl_flags))
2447 {
2448 /* rule we never alter free variables :bp->vec bp->pos in here !
2449  * this will ruin adaptive stepsize AKA heun! (BM)
2450  */
2451         SoftBody *sb= ob->soft; /* is supposed to be there */
2452         /*BodyPoint *bproot;*/ /* UNUSED */
2453         ListBase *do_effector = NULL;
2454         /* float gravity; */ /* UNUSED */
2455         /* float iks; */
2456         float fieldfactor = -1.0f, windfactor  = 0.25;
2457         int   do_deflector /*, do_selfcollision*/, do_springcollision, do_aero;
2458
2459         /* gravity = sb->grav * sb_grav_force_scale(ob); */ /* UNUSED */
2460
2461         /* check conditions for various options */
2462         do_deflector= query_external_colliders(scene, ob);
2463         /* do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF)); */ /* UNUSED */
2464         do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL);
2465         do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES));
2466
2467         /* iks  = 1.0f/(1.0f-sb->inspring)-1.0f; */ /* inner spring constants function */ /* UNUSED */
2468         /* bproot= sb->bpoint; */ /* need this for proper spring addressing */ /* UNUSED */
2469
2470         if (do_springcollision || do_aero)
2471         sb_sfesf_threads_run(scene, ob, timenow, sb->totspring, NULL);
2472
2473         /* after spring scan because it uses Effoctors too */
2474         do_effector= pdInitEffectors(scene, ob, NULL, sb->effector_weights);
2475
2476         if (do_deflector) {
2477                 float defforce[3];
2478                 do_deflector = sb_detect_aabb_collisionCached(defforce, ob->lay, ob, timenow);
2479         }
2480
2481         sb_cf_threads_run(scene, ob, forcetime, timenow, sb->totpoint, NULL, do_effector, do_deflector, fieldfactor, windfactor);
2482
2483         /* finally add forces caused by face collision */
2484         if (ob->softflag & OB_SB_FACECOLL) scan_for_ext_face_forces(ob, timenow);
2485
2486         /* finish matrix and solve */
2487         pdEndEffectors(&do_effector);
2488 }
2489
2490
2491
2492
2493 static void softbody_calc_forces(Scene *scene, Object *ob, float forcetime, float timenow, int nl_flags)
2494 {
2495         /* redirection to the new threaded Version */
2496         if (!(G.debug_value & 0x10)) { // 16
2497                 softbody_calc_forcesEx(scene, ob, forcetime, timenow, nl_flags);
2498                 return;
2499         }
2500         else {
2501                 /* so the following will die  */
2502                 /* |||||||||||||||||||||||||| */
2503                 /* VVVVVVVVVVVVVVVVVVVVVVVVVV */
2504                 /*backward compatibility note:
2505                 fixing bug [17428] which forces adaptive step size to tiny steps
2506                 in some situations
2507                 .. keeping G.debug_value==17 0x11 option for old files 'needing' the bug*/
2508
2509                 /* rule we never alter free variables :bp->vec bp->pos in here !
2510                 * this will ruin adaptive stepsize AKA heun! (BM)
2511                 */
2512                 SoftBody *sb= ob->soft; /* is supposed to be there */
2513                 BodyPoint  *bp;
2514                 /* BodyPoint *bproot; */ /* UNUSED */
2515                 BodySpring *bs;
2516                 ListBase *do_effector = NULL;
2517                 float iks, ks, kd, gravity[3] = {0.0f, 0.0f, 0.0f};
2518                 float fieldfactor = -1.0f, windfactor  = 0.25f;
2519                 float tune = sb->ballstiff;
2520                 int a, b,  do_deflector, do_selfcollision, do_springcollision, do_aero;
2521
2522
2523                 /* jacobian
2524                 NLboolean success;
2525
2526                 if (nl_flags) {
2527                 nlBegin(NL_SYSTEM);
2528                 nlBegin(NL_MATRIX);
2529                 }
2530                 */
2531
2532
2533                 if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
2534                         copy_v3_v3(gravity, scene->physics_settings.gravity);
2535                         mul_v3_fl(gravity, sb_grav_force_scale(ob)*sb->effector_weights->global_gravity);
2536                 }
2537
2538                 /* check conditions for various options */
2539                 do_deflector= query_external_colliders(scene, ob);
2540                 do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF));
2541                 do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL);
2542                 do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES));
2543
2544                 iks  = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
2545                 /* bproot= sb->bpoint; */ /* need this for proper spring addressing */ /* UNUSED */
2546
2547                 if (do_springcollision || do_aero)  scan_for_ext_spring_forces(scene, ob, timenow);
2548                 /* after spring scan because it uses Effoctors too */
2549                 do_effector= pdInitEffectors(scene, ob, NULL, ob->soft->effector_weights);
2550
2551                 if (do_deflector) {
2552                         float defforce[3];
2553                         do_deflector = sb_detect_aabb_collisionCached(defforce, ob->lay, ob, timenow);
2554                 }
2555
2556                 for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
2557                         /* clear forces  accumulator */
2558                         bp->force[0]= bp->force[1]= bp->force[2]= 0.0;
2559                         if (nl_flags & NLF_BUILD) {
2560                                 //int ia =3*(sb->totpoint-a);
2561                                 //int op =3*sb->totpoint;
2562                                 /* dF/dV = v */
2563                                 /* jacobioan
2564                                 nlMatrixAdd(op+ia, ia, -forcetime);
2565                                 nlMatrixAdd(op+ia+1, ia+1, -forcetime);
2566                                 nlMatrixAdd(op+ia+2, ia+2, -forcetime);
2567
2568                                 nlMatrixAdd(ia, ia, 1);
2569                                 nlMatrixAdd(ia+1, ia+1, 1);
2570                                 nlMatrixAdd(ia+2, ia+2, 1);
2571
2572                                 nlMatrixAdd(op+ia, op+ia, 1);
2573                                 nlMatrixAdd(op+ia+1, op+ia+1, 1);
2574                                 nlMatrixAdd(op+ia+2, op+ia+2, 1);
2575                                 */
2576
2577
2578                         }
2579
2580                         /* naive ball self collision */
2581                         /* needs to be done if goal snaps or not */
2582                         if (do_selfcollision) {
2583                                 int attached;
2584                                 BodyPoint   *obp;
2585                                 int c, b;
2586                                 float velcenter[3], dvel[3], def[3];
2587                                 float distance;
2588                                 float compare;
2589
2590                                 for (c=sb->totpoint, obp= sb->bpoint; c>=a; c--, obp++) {
2591
2592                                         //if ((bp->octantflag & obp->octantflag) == 0) continue;
2593
2594                                         compare = (obp->colball + bp->colball);
2595                                         sub_v3_v3v3(def, bp->pos, obp->pos);
2596
2597                                         /* rather check the AABBoxes before ever calulating the real distance */
2598                                         /* mathematically it is completly nuts, but performance is pretty much (3) times faster */
2599                                         if ((ABS(def[0]) > compare) || (ABS(def[1]) > compare) || (ABS(def[2]) > compare)) continue;
2600
2601                                         distance = normalize_v3(def);
2602                                         if (distance < compare ) {
2603                                                 /* exclude body points attached with a spring */
2604                                                 attached = 0;
2605                                                 for (b=obp->nofsprings;b>0;b--) {
2606                                                         bs = sb->bspring + obp->springs[b-1];
2607                                                         if (( sb->totpoint-a == bs->v2) || ( sb->totpoint-a == bs->v1)) {
2608                                                                 attached=1;
2609                                                                 continue;}
2610                                                 }
2611                                                 if (!attached) {
2612                                                         float f = tune / (distance) + tune / (compare * compare) * distance - 2.0f * tune/compare;
2613
2614                                                         mid_v3_v3v3(velcenter, bp->vec, obp->vec);
2615                                                         sub_v3_v3v3(dvel, velcenter, bp->vec);
2616                                                         mul_v3_fl(dvel, _final_mass(ob, bp));
2617
2618                                                         Vec3PlusStVec(bp->force, f*(1.0f-sb->balldamp), def);
2619                                                         Vec3PlusStVec(bp->force, sb->balldamp, dvel);
2620
2621                                                         if (nl_flags & NLF_BUILD) {
2622                                                                 //int ia =3*(sb->totpoint-a);
2623                                                                 //int ic =3*(sb->totpoint-c);
2624                                                                 //int op =3*sb->totpoint;
2625                                                                 //float mvel = forcetime*sb->nodemass*sb->balldamp;
2626                                                                 //float mpos = forcetime*tune*(1.0f-sb->balldamp);
2627                                                                 /*some quick and dirty entries to the jacobian*/
2628                                                                 //dfdx_goal(ia, ia, op, mpos);
2629                                                                 //dfdv_goal(ia, ia, mvel);
2630                                                                 /* exploit force(a, b) == -force(b, a) part1/2 */
2631                                                                 //dfdx_goal(ic, ic, op, mpos);
2632                                                                 //dfdv_goal(ic, ic, mvel);
2633
2634
2635                                                                 /*TODO sit down an X-out the true jacobian entries*/
2636                                                                 /*well does not make to much sense because the eigenvalues
2637                                                                 of the jacobian go negative; and negative eigenvalues
2638                                                                 on a complex iterative system z(n+1)=A * z(n)
2639                                                                 give imaginary roots in the charcateristic polynom
2640                                                                 --> solutions that to z(t)=u(t)* exp ( i omega t) --> oscilations we don't want here
2641                                                                 where u(t) is a unknown amplitude function (worst case rising fast)
2642                                                                 */
2643                                                         }
2644
2645                                                         /* exploit force(a, b) == -force(b, a) part2/2 */
2646                                                         sub_v3_v3v3(dvel, velcenter, obp->vec);
2647                                                         mul_v3_fl(dvel, (_final_mass(ob, bp)+_final_mass(ob, obp))/2.0f);
2648
2649                                                         Vec3PlusStVec(obp->force, sb->balldamp, dvel);
2650                                                         Vec3PlusStVec(obp->force, -f*(1.0f-sb->balldamp), def);
2651
2652
2653                                                 }
2654                                         }
2655                                 }
2656                         }
2657                         /* naive ball self collision done */
2658
2659                         if (_final_goal(ob, bp) < SOFTGOALSNAP) { /* ommit this bp when it snaps */
2660                                 float auxvect[3];
2661                                 float velgoal[3];
2662
2663                                 /* do goal stuff */
2664                                 if (ob->softflag & OB_SB_GOAL) {
2665                                         /* true elastic goal */
2666                                         sub_v3_v3v3(auxvect, bp->pos, bp->origT);
2667                                         ks  = 1.0f / (1.0f- _final_goal(ob, bp) * sb->goalspring) - 1.0f;
2668                                         bp->force[0]+= -ks*(auxvect[0]);
2669                                         bp->force[1]+= -ks*(auxvect[1]);
2670                                         bp->force[2]+= -ks*(auxvect[2]);
2671
2672                                         if (nl_flags & NLF_BUILD) {
2673                                                 //int ia =3*(sb->totpoint-a);
2674                                                 //int op =3*(sb->totpoint);
2675                                                 /* depending on my pos */
2676                                                 //dfdx_goal(ia, ia, op, ks*forcetime);
2677                                         }
2678
2679
2680                                         /* calulate damping forces generated by goals*/
2681                                         sub_v3_v3v3(velgoal, bp->origS, bp->origE);
2682                                         kd = sb->goalfrict * sb_fric_force_scale(ob);
2683                                         add_v3_v3v3(auxvect, velgoal, bp->vec);
2684
2685                                         if (forcetime > 0.0f) { /* make sure friction does not become rocket motor on time reversal */
2686                                                 bp->force[0]-= kd * (auxvect[0]);
2687                                                 bp->force[1]-= kd * (auxvect[1]);
2688                                                 bp->force[2]-= kd * (auxvect[2]);
2689                                                 if (nl_flags & NLF_BUILD) {
2690                                                         //int ia =3*(sb->totpoint-a);
2691                                                         normalize_v3(auxvect);
2692                                                         /* depending on my vel */
2693                                                         //dfdv_goal(ia, ia, kd*forcetime);
2694                                                 }
2695
2696                                         }
2697                                         else {
2698                                                 bp->force[0]-= kd * (velgoal[0] - bp->vec[0]);
2699                                                 bp->force[1]-= kd * (velgoal[1] - bp->vec[1]);
2700                                                 bp->force[2]-= kd * (velgoal[2] - bp->vec[2]);
2701                                         }
2702                                 }
2703                                 /* done goal stuff */
2704
2705
2706                                 /* gravitation */
2707                                 madd_v3_v3fl(bp->force, gravity, _final_mass(ob, bp)); /* individual mass of node here */
2708
2709
2710                                 /* particle field & vortex */
2711                                 if (do_effector) {
2712                                         EffectedPoint epoint;
2713                                         float force[3]= {0.0f, 0.0f, 0.0f};
2714                                         float speed[3]= {0.0f, 0.0f, 0.0f};
2715                                         float eval_sb_fric_force_scale = sb_fric_force_scale(ob); /* just for calling function once */
2716                                         pd_point_from_soft(scene, bp->pos, bp->vec, sb->bpoint-bp, &epoint);
2717                                         pdDoEffectors(do_effector, NULL, sb->effector_weights, &epoint, force, speed);
2718
2719                                         /* apply forcefield*/
2720                                         mul_v3_fl(force, fieldfactor* eval_sb_fric_force_scale);
2721                                         add_v3_v3(bp->force, force);
2722
2723                                         /* BP friction in moving media */
2724                                         kd= sb->mediafrict* eval_sb_fric_force_scale;
2725                                         bp->force[0] -= kd * (bp->vec[0] + windfactor*speed[0]/eval_sb_fric_force_scale);
2726                                         bp->force[1] -= kd * (bp->vec[1] + windfactor*speed[1]/eval_sb_fric_force_scale);
2727                                         bp->force[2] -= kd * (bp->vec[2] + windfactor*speed[2]/eval_sb_fric_force_scale);
2728        &nb