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