Merge branch 'blender2.7'
[blender.git] / source / blender / blenkernel / intern / cloth.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) Blender Foundation
17  * All rights reserved.
18  */
19
20 /** \file
21  * \ingroup bke
22  */
23
24
25 #include "MEM_guardedalloc.h"
26
27 #include "DNA_cloth_types.h"
28 #include "DNA_scene_types.h"
29 #include "DNA_object_types.h"
30 #include "DNA_mesh_types.h"
31 #include "DNA_meshdata_types.h"
32
33 #include "BLI_utildefines.h"
34 #include "BLI_math.h"
35 #include "BLI_edgehash.h"
36 #include "BLI_linklist.h"
37
38 #include "DEG_depsgraph.h"
39 #include "DEG_depsgraph_query.h"
40
41 #include "BKE_bvhutils.h"
42 #include "BKE_cloth.h"
43 #include "BKE_effect.h"
44 #include "BKE_global.h"
45 #include "BKE_mesh_runtime.h"
46 #include "BKE_modifier.h"
47 #include "BKE_pointcache.h"
48
49 #include "BPH_mass_spring.h"
50
51 // #include "PIL_time.h"  /* timing for debug prints */
52
53 /* ********** cloth engine ******* */
54 /* Prototypes for internal functions.
55  */
56 static void cloth_to_object (Object *ob,  ClothModifierData *clmd, float (*vertexCos)[3]);
57 static void cloth_from_mesh ( ClothModifierData *clmd, Mesh *mesh );
58 static int cloth_from_object(Object *ob, ClothModifierData *clmd, Mesh *mesh, float framenr, int first);
59 static void cloth_update_springs( ClothModifierData *clmd );
60 static void cloth_update_verts( Object *ob, ClothModifierData *clmd, Mesh *mesh );
61 static void cloth_update_spring_lengths( ClothModifierData *clmd, Mesh *mesh );
62 static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh );
63 static void cloth_apply_vgroup ( ClothModifierData *clmd, Mesh *mesh );
64
65 typedef struct BendSpringRef {
66         int index;
67         int polys;
68         ClothSpring *spring;
69 } BendSpringRef;
70
71 /******************************************************************************
72  *
73  * External interface called by modifier.c clothModifier functions.
74  *
75  ******************************************************************************/
76 /**
77  * cloth_init - creates a new cloth simulation.
78  *
79  * 1. create object
80  * 2. fill object with standard values or with the GUI settings if given
81  */
82 void cloth_init(ClothModifierData *clmd )
83 {
84         /* Initialize our new data structure to reasonable values. */
85         clmd->sim_parms->gravity[0] = 0.0;
86         clmd->sim_parms->gravity[1] = 0.0;
87         clmd->sim_parms->gravity[2] = -9.81;
88         clmd->sim_parms->tension = 15.0;
89         clmd->sim_parms->max_tension = 15.0;
90         clmd->sim_parms->compression = 15.0;
91         clmd->sim_parms->max_compression = 15.0;
92         clmd->sim_parms->shear = 5.0;
93         clmd->sim_parms->max_shear = 5.0;
94         clmd->sim_parms->bending = 0.5;
95         clmd->sim_parms->max_bend = 0.5;
96         clmd->sim_parms->tension_damp = 5.0;
97         clmd->sim_parms->compression_damp = 5.0;
98         clmd->sim_parms->shear_damp = 5.0;
99         clmd->sim_parms->bending_damping = 0.5;
100         clmd->sim_parms->Cvi = 1.0;
101         clmd->sim_parms->mass = 0.3f;
102         clmd->sim_parms->stepsPerFrame = 5;
103         clmd->sim_parms->flags = 0;
104         clmd->sim_parms->solver_type = 0;
105         clmd->sim_parms->maxspringlen = 10;
106         clmd->sim_parms->vgroup_mass = 0;
107         clmd->sim_parms->vgroup_shrink = 0;
108         clmd->sim_parms->shrink_min = 0.0f; /* min amount the fabric will shrink by 0.0 = no shrinking, 1.0 = shrink to nothing*/
109         clmd->sim_parms->avg_spring_len = 0.0;
110         clmd->sim_parms->presets = 2; /* cotton as start setting */
111         clmd->sim_parms->timescale = 1.0f; /* speed factor, describes how fast cloth moves */
112         clmd->sim_parms->time_scale = 1.0f; /* multiplies cloth speed */
113         clmd->sim_parms->reset = 0;
114
115         clmd->coll_parms->self_friction = 5.0;
116         clmd->coll_parms->friction = 5.0;
117         clmd->coll_parms->loop_count = 2;
118         clmd->coll_parms->epsilon = 0.015f;
119         clmd->coll_parms->flags = CLOTH_COLLSETTINGS_FLAG_ENABLED;
120         clmd->coll_parms->collision_list = NULL;
121         clmd->coll_parms->selfepsilon = 0.015;
122         clmd->coll_parms->vgroup_selfcol = 0;
123
124         /* These defaults are copied from softbody.c's
125          * softbody_calc_forces() function.
126          */
127         clmd->sim_parms->eff_force_scale = 1000.0;
128         clmd->sim_parms->eff_wind_scale = 250.0;
129
130         // also from softbodies
131         clmd->sim_parms->maxgoal = 1.0f;
132         clmd->sim_parms->mingoal = 0.0f;
133         clmd->sim_parms->defgoal = 0.0f;
134         clmd->sim_parms->goalspring = 1.0f;
135         clmd->sim_parms->goalfrict = 0.0f;
136         clmd->sim_parms->velocity_smooth = 0.0f;
137
138         clmd->sim_parms->voxel_cell_size = 0.1f;
139
140         clmd->sim_parms->bending_model = CLOTH_BENDING_ANGULAR;
141
142         if (!clmd->sim_parms->effector_weights)
143                 clmd->sim_parms->effector_weights = BKE_effector_add_weights(NULL);
144
145         if (clmd->point_cache)
146                 clmd->point_cache->step = 1;
147 }
148
149 static BVHTree *bvhtree_build_from_cloth (ClothModifierData *clmd, float epsilon)
150 {
151         unsigned int i;
152         BVHTree *bvhtree;
153         Cloth *cloth;
154         ClothVertex *verts;
155         const MVertTri *vt;
156
157         if (!clmd)
158                 return NULL;
159
160         cloth = clmd->clothObject;
161
162         if (!cloth)
163                 return NULL;
164
165         verts = cloth->verts;
166         vt = cloth->tri;
167
168         /* in the moment, return zero if no faces there */
169         if (!cloth->tri_num)
170                 return NULL;
171
172         /* create quadtree with k=26 */
173         bvhtree = BLI_bvhtree_new(cloth->tri_num, epsilon, 4, 26);
174
175         /* fill tree */
176         for (i = 0; i < cloth->tri_num; i++, vt++) {
177                 float co[3][3];
178
179                 copy_v3_v3(co[0], verts[vt->tri[0]].xold);
180                 copy_v3_v3(co[1], verts[vt->tri[1]].xold);
181                 copy_v3_v3(co[2], verts[vt->tri[2]].xold);
182
183                 BLI_bvhtree_insert(bvhtree, i, co[0], 3);
184         }
185
186         /* balance tree */
187         BLI_bvhtree_balance(bvhtree);
188
189         return bvhtree;
190 }
191
192 void bvhtree_update_from_cloth(ClothModifierData *clmd, bool moving, bool self)
193 {
194         unsigned int i = 0;
195         Cloth *cloth = clmd->clothObject;
196         BVHTree *bvhtree;
197         ClothVertex *verts = cloth->verts;
198         const MVertTri *vt;
199
200         if (self) {
201                 bvhtree = cloth->bvhselftree;
202         }
203         else {
204                 bvhtree = cloth->bvhtree;
205         }
206
207         if (!bvhtree)
208                 return;
209
210         vt = cloth->tri;
211
212         /* update vertex position in bvh tree */
213         if (verts && vt) {
214                 for (i = 0; i < cloth->tri_num; i++, vt++) {
215                         float co[3][3], co_moving[3][3];
216                         bool ret;
217
218                         /* copy new locations into array */
219                         if (moving) {
220                                 copy_v3_v3(co[0], verts[vt->tri[0]].txold);
221                                 copy_v3_v3(co[1], verts[vt->tri[1]].txold);
222                                 copy_v3_v3(co[2], verts[vt->tri[2]].txold);
223
224                                 /* update moving positions */
225                                 copy_v3_v3(co_moving[0], verts[vt->tri[0]].tx);
226                                 copy_v3_v3(co_moving[1], verts[vt->tri[1]].tx);
227                                 copy_v3_v3(co_moving[2], verts[vt->tri[2]].tx);
228
229                                 ret = BLI_bvhtree_update_node(bvhtree, i, co[0], co_moving[0], 3);
230                         }
231                         else {
232                                 copy_v3_v3(co[0], verts[vt->tri[0]].tx);
233                                 copy_v3_v3(co[1], verts[vt->tri[1]].tx);
234                                 copy_v3_v3(co[2], verts[vt->tri[2]].tx);
235
236                                 ret = BLI_bvhtree_update_node(bvhtree, i, co[0], NULL, 3);
237                         }
238
239                         /* check if tree is already full */
240                         if (ret == false) {
241                                 break;
242                         }
243                 }
244
245                 BLI_bvhtree_update_tree(bvhtree);
246         }
247 }
248
249 void cloth_clear_cache(Object *ob, ClothModifierData *clmd, float framenr)
250 {
251         PTCacheID pid;
252
253         BKE_ptcache_id_from_cloth(&pid, ob, clmd);
254
255         // don't do anything as long as we're in editmode!
256         if (pid.cache->edit && ob->mode & OB_MODE_PARTICLE_EDIT)
257                 return;
258
259         BKE_ptcache_id_clear(&pid, PTCACHE_CLEAR_AFTER, framenr);
260 }
261
262 static int do_init_cloth(Object *ob, ClothModifierData *clmd, Mesh *result, int framenr)
263 {
264         PointCache *cache;
265
266         cache= clmd->point_cache;
267
268         /* initialize simulation data if it didn't exist already */
269         if (clmd->clothObject == NULL) {
270                 if (!cloth_from_object(ob, clmd, result, framenr, 1)) {
271                         BKE_ptcache_invalidate(cache);
272                         modifier_setError(&(clmd->modifier), "Can't initialize cloth");
273                         return 0;
274                 }
275
276                 if (clmd->clothObject == NULL) {
277                         BKE_ptcache_invalidate(cache);
278                         modifier_setError(&(clmd->modifier), "Null cloth object");
279                         return 0;
280                 }
281
282                 BKE_cloth_solver_set_positions(clmd);
283
284                 clmd->clothObject->last_frame= MINFRAME-1;
285                 clmd->sim_parms->dt = 1.0f / clmd->sim_parms->stepsPerFrame;
286         }
287
288         return 1;
289 }
290
291 static int do_step_cloth(Depsgraph *depsgraph, Object *ob, ClothModifierData *clmd, Mesh *result, int framenr)
292 {
293         ClothVertex *verts = NULL;
294         Cloth *cloth;
295         ListBase *effectors = NULL;
296         MVert *mvert;
297         unsigned int i = 0;
298         int ret = 0;
299
300         /* simulate 1 frame forward */
301         cloth = clmd->clothObject;
302         verts = cloth->verts;
303         mvert = result->mvert;
304
305         /* force any pinned verts to their constrained location. */
306         for (i = 0; i < clmd->clothObject->mvert_num; i++, verts++) {
307                 /* save the previous position. */
308                 copy_v3_v3(verts->xold, verts->xconst);
309                 copy_v3_v3(verts->txold, verts->x);
310
311                 /* Get the current position. */
312                 copy_v3_v3(verts->xconst, mvert[i].co);
313                 mul_m4_v3(ob->obmat, verts->xconst);
314         }
315
316         effectors = BKE_effectors_create(depsgraph, ob, NULL, clmd->sim_parms->effector_weights);
317
318         if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_DYNAMIC_BASEMESH )
319                 cloth_update_verts ( ob, clmd, result );
320
321         /* Support for dynamic vertex groups, changing from frame to frame */
322         cloth_apply_vgroup ( clmd, result );
323
324         if ((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_DYNAMIC_BASEMESH) ||
325             (clmd->sim_parms->vgroup_shrink > 0) || (clmd->sim_parms->shrink_min > 0.0f))
326         {
327                 cloth_update_spring_lengths ( clmd, result );
328         }
329
330         cloth_update_springs( clmd );
331
332         // TIMEIT_START(cloth_step)
333
334         /* call the solver. */
335         ret = BPH_cloth_solve(depsgraph, ob, framenr, clmd, effectors);
336
337         // TIMEIT_END(cloth_step)
338
339         BKE_effectors_free(effectors);
340
341         // printf ( "%f\n", ( float ) tval() );
342
343         return ret;
344 }
345
346 /************************************************
347  * clothModifier_do - main simulation function
348  ************************************************/
349 void clothModifier_do(ClothModifierData *clmd, Depsgraph *depsgraph, Scene *scene, Object *ob, Mesh *mesh, float (*vertexCos)[3])
350 {
351         PointCache *cache;
352         PTCacheID pid;
353         float timescale;
354         int framenr, startframe, endframe;
355         int cache_result;
356
357         framenr = DEG_get_ctime(depsgraph);
358         cache= clmd->point_cache;
359
360         BKE_ptcache_id_from_cloth(&pid, ob, clmd);
361         BKE_ptcache_id_time(&pid, scene, framenr, &startframe, &endframe, &timescale);
362         clmd->sim_parms->timescale= timescale * clmd->sim_parms->time_scale;
363
364         if (clmd->sim_parms->reset || (clmd->clothObject && mesh->totvert != clmd->clothObject->mvert_num)) {
365                 clmd->sim_parms->reset = 0;
366                 cache->flag |= PTCACHE_OUTDATED;
367                 BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
368                 BKE_ptcache_validate(cache, 0);
369                 cache->last_exact= 0;
370                 cache->flag &= ~PTCACHE_REDO_NEEDED;
371         }
372
373         /* simulation is only active during a specific period */
374         if (framenr < startframe) {
375                 BKE_ptcache_invalidate(cache);
376                 return;
377         }
378         else if (framenr > endframe) {
379                 framenr= endframe;
380         }
381
382         /* initialize simulation data if it didn't exist already */
383         if (!do_init_cloth(ob, clmd, mesh, framenr))
384                 return;
385
386         if (framenr == startframe) {
387                 BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
388                 do_init_cloth(ob, clmd, mesh, framenr);
389                 BKE_ptcache_validate(cache, framenr);
390                 cache->flag &= ~PTCACHE_REDO_NEEDED;
391                 clmd->clothObject->last_frame= framenr;
392                 return;
393         }
394
395         /* try to read from cache */
396         bool can_simulate = (framenr == clmd->clothObject->last_frame+1) && !(cache->flag & PTCACHE_BAKED);
397
398         cache_result = BKE_ptcache_read(&pid, (float)framenr+scene->r.subframe, can_simulate);
399
400         if (cache_result == PTCACHE_READ_EXACT || cache_result == PTCACHE_READ_INTERPOLATED ||
401             (!can_simulate && cache_result == PTCACHE_READ_OLD))
402         {
403                 BKE_cloth_solver_set_positions(clmd);
404                 cloth_to_object (ob, clmd, vertexCos);
405
406                 BKE_ptcache_validate(cache, framenr);
407
408                 if (cache_result == PTCACHE_READ_INTERPOLATED && cache->flag & PTCACHE_REDO_NEEDED)
409                         BKE_ptcache_write(&pid, framenr);
410
411                 clmd->clothObject->last_frame= framenr;
412
413                 return;
414         }
415         else if (cache_result==PTCACHE_READ_OLD) {
416                 BKE_cloth_solver_set_positions(clmd);
417         }
418         else if ( /*ob->id.lib ||*/ (cache->flag & PTCACHE_BAKED)) { /* 2.4x disabled lib, but this can be used in some cases, testing further - campbell */
419                 /* if baked and nothing in cache, do nothing */
420                 BKE_ptcache_invalidate(cache);
421                 return;
422         }
423
424         /* if on second frame, write cache for first frame */
425         if (cache->simframe == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact==0))
426                 BKE_ptcache_write(&pid, startframe);
427
428         clmd->sim_parms->timescale *= framenr - cache->simframe;
429
430         /* do simulation */
431         BKE_ptcache_validate(cache, framenr);
432
433         if (!do_step_cloth(depsgraph, ob, clmd, mesh, framenr)) {
434                 BKE_ptcache_invalidate(cache);
435         }
436         else
437                 BKE_ptcache_write(&pid, framenr);
438
439         cloth_to_object (ob, clmd, vertexCos);
440         clmd->clothObject->last_frame= framenr;
441 }
442
443 /* frees all */
444 void cloth_free_modifier(ClothModifierData *clmd )
445 {
446         Cloth   *cloth = NULL;
447
448         if ( !clmd )
449                 return;
450
451         cloth = clmd->clothObject;
452
453
454         if ( cloth ) {
455                 BPH_cloth_solver_free(clmd);
456
457                 // Free the verts.
458                 if ( cloth->verts != NULL )
459                         MEM_freeN ( cloth->verts );
460
461                 cloth->verts = NULL;
462                 cloth->mvert_num = 0;
463
464                 // Free the springs.
465                 if ( cloth->springs != NULL ) {
466                         LinkNode *search = cloth->springs;
467                         while (search) {
468                                 ClothSpring *spring = search->link;
469
470                                 MEM_SAFE_FREE(spring->pa);
471                                 MEM_SAFE_FREE(spring->pb);
472
473                                 MEM_freeN ( spring );
474                                 search = search->next;
475                         }
476                         BLI_linklist_free(cloth->springs, NULL);
477
478                         cloth->springs = NULL;
479                 }
480
481                 cloth->springs = NULL;
482                 cloth->numsprings = 0;
483
484                 // free BVH collision tree
485                 if ( cloth->bvhtree )
486                         BLI_bvhtree_free ( cloth->bvhtree );
487
488                 if ( cloth->bvhselftree )
489                         BLI_bvhtree_free ( cloth->bvhselftree );
490
491                 // we save our faces for collision objects
492                 if (cloth->tri)
493                         MEM_freeN(cloth->tri);
494
495                 if (cloth->edgeset)
496                         BLI_edgeset_free(cloth->edgeset);
497
498 #if 0
499                 if (clmd->clothObject->facemarks) {
500                         MEM_freeN(clmd->clothObject->facemarks);
501                 }
502 #endif
503                 MEM_freeN ( cloth );
504                 clmd->clothObject = NULL;
505         }
506 }
507
508 /* frees all */
509 void cloth_free_modifier_extern(ClothModifierData *clmd )
510 {
511         Cloth   *cloth = NULL;
512         if (G.debug & G_DEBUG_SIMDATA) {
513                 printf("cloth_free_modifier_extern\n");
514         }
515
516         if ( !clmd )
517                 return;
518
519         cloth = clmd->clothObject;
520
521         if ( cloth ) {
522                 if (G.debug & G_DEBUG_SIMDATA) {
523                         printf("cloth_free_modifier_extern in\n");
524                 }
525
526                 BPH_cloth_solver_free(clmd);
527
528                 // Free the verts.
529                 if ( cloth->verts != NULL )
530                         MEM_freeN ( cloth->verts );
531
532                 cloth->verts = NULL;
533                 cloth->mvert_num = 0;
534
535                 // Free the springs.
536                 if ( cloth->springs != NULL ) {
537                         LinkNode *search = cloth->springs;
538                         while (search) {
539                                 ClothSpring *spring = search->link;
540
541                                 MEM_SAFE_FREE(spring->pa);
542                                 MEM_SAFE_FREE(spring->pb);
543
544                                 MEM_freeN ( spring );
545                                 search = search->next;
546                         }
547                         BLI_linklist_free(cloth->springs, NULL);
548
549                         cloth->springs = NULL;
550                 }
551
552                 cloth->springs = NULL;
553                 cloth->numsprings = 0;
554
555                 // free BVH collision tree
556                 if ( cloth->bvhtree )
557                         BLI_bvhtree_free ( cloth->bvhtree );
558
559                 if ( cloth->bvhselftree )
560                         BLI_bvhtree_free ( cloth->bvhselftree );
561
562                 // we save our faces for collision objects
563                 if (cloth->tri)
564                         MEM_freeN(cloth->tri);
565
566                 if (cloth->edgeset)
567                         BLI_edgeset_free(cloth->edgeset);
568
569
570 #if 0
571                 if (clmd->clothObject->facemarks) {
572                         MEM_freeN(clmd->clothObject->facemarks);
573                 }
574 #endif
575                 MEM_freeN ( cloth );
576                 clmd->clothObject = NULL;
577         }
578 }
579
580 /******************************************************************************
581  *
582  * Internal functions.
583  *
584  ******************************************************************************/
585
586 /**
587  * Copies the deformed vertices to the object.
588  */
589 static void cloth_to_object (Object *ob,  ClothModifierData *clmd, float (*vertexCos)[3])
590 {
591         unsigned int i = 0;
592         Cloth *cloth = clmd->clothObject;
593
594         if (clmd->clothObject) {
595                 /* inverse matrix is not uptodate... */
596                 invert_m4_m4(ob->imat, ob->obmat);
597
598                 for (i = 0; i < cloth->mvert_num; i++) {
599                         copy_v3_v3 (vertexCos[i], cloth->verts[i].x);
600                         mul_m4_v3(ob->imat, vertexCos[i]);      /* cloth is in global coords */
601                 }
602         }
603 }
604
605
606 int cloth_uses_vgroup(ClothModifierData *clmd)
607 {
608         return (((clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF) && (clmd->coll_parms->vgroup_selfcol > 0)) ||
609                 (clmd->sim_parms->vgroup_struct > 0) ||
610                 (clmd->sim_parms->vgroup_bend > 0) ||
611                 (clmd->sim_parms->vgroup_shrink > 0) ||
612                 (clmd->sim_parms->vgroup_mass > 0));
613 }
614
615 /**
616  * Applies a vertex group as specified by type.
617  */
618 static void cloth_apply_vgroup ( ClothModifierData *clmd, Mesh *mesh )
619 {
620         /* Can be optimized to do all groups in one loop. */
621         int i = 0;
622         int j = 0;
623         MDeformVert *dvert = NULL;
624         Cloth *clothObj = NULL;
625         int mvert_num;
626         /* float goalfac = 0; */ /* UNUSED */
627         ClothVertex *verts = NULL;
628
629         if (!clmd || !mesh) return;
630
631         clothObj = clmd->clothObject;
632
633         mvert_num = mesh->totvert;
634
635         verts = clothObj->verts;
636
637         if (cloth_uses_vgroup(clmd)) {
638                 for (i = 0; i < mvert_num; i++, verts++) {
639
640                         /* Reset Goal values to standard */
641                         if (clmd->sim_parms->vgroup_mass > 0)
642                                 verts->goal= clmd->sim_parms->defgoal;
643                         else
644                                 verts->goal= 0.0f;
645
646                         /* Compute base cloth shrink weight */
647                         verts->shrink_factor = 0.0f;
648
649                         /* Reset vertex flags */
650                         verts->flags &= ~CLOTH_VERT_FLAG_PINNED;
651                         verts->flags &= ~CLOTH_VERT_FLAG_NOSELFCOLL;
652
653                         dvert = CustomData_get(&mesh->vdata, i, CD_MDEFORMVERT);
654                         if ( dvert ) {
655                                 for ( j = 0; j < dvert->totweight; j++ ) {
656                                         if (dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_mass - 1)) {
657                                                 verts->goal = dvert->dw [j].weight;
658
659                                                 /* goalfac= 1.0f; */ /* UNUSED */
660
661                                                 // Kicking goal factor to simplify things...who uses that anyway?
662                                                 // ABS ( clmd->sim_parms->maxgoal - clmd->sim_parms->mingoal );
663
664                                                 verts->goal  = pow4f(verts->goal);
665                                                 if ( verts->goal >= SOFTGOALSNAP )
666                                                         verts->flags |= CLOTH_VERT_FLAG_PINNED;
667                                         }
668
669                                         if (dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_struct - 1)) {
670                                                 verts->struct_stiff = dvert->dw[j].weight;
671                                         }
672
673                                         if (dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_shear - 1)) {
674                                                 verts->shear_stiff = dvert->dw[j].weight;
675                                         }
676
677                                         if (dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_bend - 1)) {
678                                                 verts->bend_stiff = dvert->dw[j].weight;
679                                         }
680
681                                         if (clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF ) {
682                                                 if ( dvert->dw[j].def_nr == (clmd->coll_parms->vgroup_selfcol-1)) {
683                                                         if (dvert->dw [j].weight > 0.0f) {
684                                                                 verts->flags |= CLOTH_VERT_FLAG_NOSELFCOLL;
685                                                         }
686                                                 }
687                                         }
688                                         if (clmd->sim_parms->vgroup_shrink > 0) {
689                                                 if (dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_shrink - 1)) {
690                                                         /* Used for linear interpolation between min and max shrink factor based on weight. */
691                                                         verts->shrink_factor = dvert->dw[j].weight;
692                                                 }
693                                         }
694                                 }
695                         }
696                 }
697         }
698 }
699
700 static float cloth_shrink_factor(ClothModifierData *clmd, ClothVertex *verts, int i1, int i2)
701 {
702         /* Linear interpolation between min and max shrink factor based on weight. */
703         float base = 1.0f - clmd->sim_parms->shrink_min;
704         float delta = clmd->sim_parms->shrink_min - clmd->sim_parms->shrink_max;
705
706         float k1 = base + delta * verts[i1].shrink_factor;
707         float k2 = base + delta * verts[i2].shrink_factor;
708
709         /* Use geometrical mean to average two factors since it behaves better
710            for diagonals when a rectangle transforms into a trapezoid. */
711         return sqrtf(k1 * k2);
712 }
713
714 static int cloth_from_object(Object *ob, ClothModifierData *clmd, Mesh *mesh, float UNUSED(framenr), int first)
715 {
716         int i = 0;
717         MVert *mvert = NULL;
718         ClothVertex *verts = NULL;
719         float (*shapekey_rest)[3] = NULL;
720         float tnull[3] = {0, 0, 0};
721
722         // If we have a clothObject, free it.
723         if ( clmd->clothObject != NULL ) {
724                 cloth_free_modifier ( clmd );
725                 if (G.debug & G_DEBUG_SIMDATA) {
726                         printf("cloth_free_modifier cloth_from_object\n");
727                 }
728         }
729
730         // Allocate a new cloth object.
731         clmd->clothObject = MEM_callocN ( sizeof ( Cloth ), "cloth" );
732         if ( clmd->clothObject ) {
733                 clmd->clothObject->old_solver_type = 255;
734                 clmd->clothObject->edgeset = NULL;
735         }
736         else if (!clmd->clothObject) {
737                 modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject");
738                 return 0;
739         }
740
741         // mesh input objects need Mesh
742         if ( !mesh )
743                 return 0;
744
745         cloth_from_mesh ( clmd, mesh );
746
747         // create springs
748         clmd->clothObject->springs = NULL;
749         clmd->clothObject->numsprings = -1;
750
751         if ( clmd->sim_parms->shapekey_rest && !(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_DYNAMIC_BASEMESH ) )
752                 shapekey_rest = CustomData_get_layer(&mesh->vdata, CD_CLOTH_ORCO);
753
754         mvert = mesh->mvert;
755
756         verts = clmd->clothObject->verts;
757
758         // set initial values
759         for ( i = 0; i < mesh->totvert; i++, verts++ ) {
760                 if (first) {
761                         copy_v3_v3(verts->x, mvert[i].co);
762
763                         mul_m4_v3(ob->obmat, verts->x);
764
765                         if ( shapekey_rest ) {
766                                 copy_v3_v3(verts->xrest, shapekey_rest[i]);
767                                 mul_m4_v3(ob->obmat, verts->xrest);
768                         }
769                         else
770                                 copy_v3_v3(verts->xrest, verts->x);
771                 }
772
773                 /* no GUI interface yet */
774                 verts->mass = clmd->sim_parms->mass;
775                 verts->impulse_count = 0;
776
777                 if (clmd->sim_parms->vgroup_mass > 0)
778                         verts->goal= clmd->sim_parms->defgoal;
779                 else
780                         verts->goal= 0.0f;
781
782                 verts->shrink_factor = 0.0f;
783
784                 verts->flags = 0;
785                 copy_v3_v3 ( verts->xold, verts->x );
786                 copy_v3_v3 ( verts->xconst, verts->x );
787                 copy_v3_v3 ( verts->txold, verts->x );
788                 copy_v3_v3 ( verts->tx, verts->x );
789                 mul_v3_fl(verts->v, 0.0f);
790
791                 verts->impulse_count = 0;
792                 copy_v3_v3 ( verts->impulse, tnull );
793         }
794
795         // apply / set vertex groups
796         // has to be happen before springs are build!
797         cloth_apply_vgroup (clmd, mesh);
798
799         if ( !cloth_build_springs ( clmd, mesh ) ) {
800                 cloth_free_modifier ( clmd );
801                 modifier_setError(&(clmd->modifier), "Cannot build springs");
802                 return 0;
803         }
804
805         // init our solver
806         BPH_cloth_solver_init(ob, clmd);
807
808         if (!first)
809                 BKE_cloth_solver_set_positions(clmd);
810
811         clmd->clothObject->bvhtree = bvhtree_build_from_cloth (clmd, clmd->coll_parms->epsilon);
812         clmd->clothObject->bvhselftree = bvhtree_build_from_cloth(clmd, clmd->coll_parms->selfepsilon);
813
814         return 1;
815 }
816
817 static void cloth_from_mesh ( ClothModifierData *clmd, Mesh *mesh )
818 {
819         const MLoop *mloop = mesh->mloop;
820         const MLoopTri *looptri = BKE_mesh_runtime_looptri_ensure(mesh);
821         const unsigned int mvert_num = mesh->totvert;
822         const unsigned int looptri_num = mesh->runtime.looptris.len;
823
824         /* Allocate our vertices. */
825         clmd->clothObject->mvert_num = mvert_num;
826         clmd->clothObject->verts = MEM_callocN(sizeof(ClothVertex) * clmd->clothObject->mvert_num, "clothVertex");
827         if (clmd->clothObject->verts == NULL) {
828                 cloth_free_modifier(clmd);
829                 modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject->verts");
830                 printf("cloth_free_modifier clmd->clothObject->verts\n");
831                 return;
832         }
833
834         /* save face information */
835         clmd->clothObject->tri_num = looptri_num;
836         clmd->clothObject->tri = MEM_mallocN(sizeof(MVertTri) * looptri_num, "clothLoopTris");
837         if (clmd->clothObject->tri == NULL) {
838                 cloth_free_modifier(clmd);
839                 modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject->looptri");
840                 printf("cloth_free_modifier clmd->clothObject->looptri\n");
841                 return;
842         }
843         BKE_mesh_runtime_verttri_from_looptri(clmd->clothObject->tri, mloop, looptri, looptri_num);
844
845         /* Free the springs since they can't be correct if the vertices
846          * changed.
847          */
848         if ( clmd->clothObject->springs != NULL )
849                 MEM_freeN ( clmd->clothObject->springs );
850
851 }
852
853 /***************************************************************************************
854  * SPRING NETWORK GPU_BATCH_BUILDING IMPLEMENTATION BEGIN
855  ***************************************************************************************/
856
857 BLI_INLINE void spring_verts_ordered_set(ClothSpring *spring, int v0, int v1)
858 {
859         if (v0 < v1) {
860                 spring->ij = v0;
861                 spring->kl = v1;
862         }
863         else {
864                 spring->ij = v1;
865                 spring->kl = v0;
866         }
867 }
868
869 static void cloth_free_edgelist(LinkNodePair *edgelist, unsigned int mvert_num)
870 {
871         if (edgelist) {
872                 unsigned int i;
873                 for (i = 0; i < mvert_num; i++) {
874                         BLI_linklist_free(edgelist[i].list, NULL);
875                 }
876
877                 MEM_freeN(edgelist);
878         }
879 }
880
881 static void cloth_free_errorsprings(Cloth *cloth, LinkNodePair *edgelist, BendSpringRef *spring_ref)
882 {
883         if ( cloth->springs != NULL ) {
884                 LinkNode *search = cloth->springs;
885                 while (search) {
886                         ClothSpring *spring = search->link;
887
888                         MEM_SAFE_FREE(spring->pa);
889                         MEM_SAFE_FREE(spring->pb);
890
891                         MEM_freeN ( spring );
892                         search = search->next;
893                 }
894                 BLI_linklist_free(cloth->springs, NULL);
895
896                 cloth->springs = NULL;
897         }
898
899         cloth_free_edgelist(edgelist, cloth->mvert_num);
900
901         MEM_SAFE_FREE(spring_ref);
902
903         if (cloth->edgeset) {
904                 BLI_edgeset_free(cloth->edgeset);
905                 cloth->edgeset = NULL;
906         }
907 }
908
909 BLI_INLINE void cloth_bend_poly_dir(ClothVertex *verts, int i, int j, int *inds, int len, float r_dir[3])
910 {
911         float cent[3] = {0};
912         float fact = 1.0f / len;
913
914         for (int x = 0; x < len; x++) {
915                 madd_v3_v3fl(cent, verts[inds[x]].xrest, fact);
916         }
917
918         normal_tri_v3(r_dir, verts[i].xrest, verts[j].xrest, cent);
919 }
920
921 static float cloth_spring_angle(ClothVertex *verts, int i, int j, int *i_a, int *i_b, int len_a, int len_b)
922 {
923         float dir_a[3], dir_b[3];
924         float tmp[3], vec_e[3];
925         float sin, cos;
926
927         /* Poly vectors. */
928         cloth_bend_poly_dir(verts, j, i, i_a, len_a, dir_a);
929         cloth_bend_poly_dir(verts, i, j, i_b, len_b, dir_b);
930
931         /* Edge vector. */
932         sub_v3_v3v3(vec_e, verts[i].xrest, verts[j].xrest);
933         normalize_v3(vec_e);
934
935         /* Compute angle. */
936         cos = dot_v3v3(dir_a, dir_b);
937
938         cross_v3_v3v3(tmp, dir_a, dir_b);
939         sin = dot_v3v3(tmp, vec_e);
940
941         return atan2f(sin, cos);
942 }
943
944 static void cloth_hair_update_bending_targets(ClothModifierData *clmd)
945 {
946         Cloth *cloth = clmd->clothObject;
947         LinkNode *search = NULL;
948         float hair_frame[3][3], dir_old[3], dir_new[3];
949         int prev_mn; /* to find hair chains */
950
951         if (!clmd->hairdata)
952                 return;
953
954         /* XXX Note: we need to propagate frames from the root up,
955          * but structural hair springs are stored in reverse order.
956          * The bending springs however are then inserted in the same
957          * order as vertices again ...
958          * This messy situation can be resolved when solver data is
959          * generated directly from a dedicated hair system.
960          */
961
962         prev_mn = -1;
963         for (search = cloth->springs; search; search = search->next) {
964                 ClothSpring *spring = search->link;
965                 ClothHairData *hair_ij, *hair_kl;
966                 bool is_root = spring->kl != prev_mn;
967
968                 if (spring->type != CLOTH_SPRING_TYPE_BENDING_HAIR) {
969                         continue;
970                 }
971
972                 hair_ij = &clmd->hairdata[spring->ij];
973                 hair_kl = &clmd->hairdata[spring->kl];
974                 if (is_root) {
975                         /* initial hair frame from root orientation */
976                         copy_m3_m3(hair_frame, hair_ij->rot);
977                         /* surface normal is the initial direction,
978                          * parallel transport then keeps it aligned to the hair direction
979                          */
980                         copy_v3_v3(dir_new, hair_frame[2]);
981                 }
982
983                 copy_v3_v3(dir_old, dir_new);
984                 sub_v3_v3v3(dir_new, cloth->verts[spring->mn].x, cloth->verts[spring->kl].x);
985                 normalize_v3(dir_new);
986
987                 /* get local targets for kl/mn vertices by putting rest targets into the current frame,
988                  * then multiply with the rest length to get the actual goals
989                  */
990
991                 mul_v3_m3v3(spring->target, hair_frame, hair_kl->rest_target);
992                 mul_v3_fl(spring->target, spring->restlen);
993
994                 /* move frame to next hair segment */
995                 cloth_parallel_transport_hair_frame(hair_frame, dir_old, dir_new);
996
997                 prev_mn = spring->mn;
998         }
999 }
1000
1001 static void cloth_hair_update_bending_rest_targets(ClothModifierData *clmd)
1002 {
1003         Cloth *cloth = clmd->clothObject;
1004         LinkNode *search = NULL;
1005         float hair_frame[3][3], dir_old[3], dir_new[3];
1006         int prev_mn; /* to find hair roots */
1007
1008         if (!clmd->hairdata)
1009                 return;
1010
1011         /* XXX Note: we need to propagate frames from the root up,
1012          * but structural hair springs are stored in reverse order.
1013          * The bending springs however are then inserted in the same
1014          * order as vertices again ...
1015          * This messy situation can be resolved when solver data is
1016          * generated directly from a dedicated hair system.
1017          */
1018
1019         prev_mn = -1;
1020         for (search = cloth->springs; search; search = search->next) {
1021                 ClothSpring *spring = search->link;
1022                 ClothHairData *hair_ij, *hair_kl;
1023                 bool is_root = spring->kl != prev_mn;
1024
1025                 if (spring->type != CLOTH_SPRING_TYPE_BENDING_HAIR) {
1026                         continue;
1027                 }
1028
1029                 hair_ij = &clmd->hairdata[spring->ij];
1030                 hair_kl = &clmd->hairdata[spring->kl];
1031                 if (is_root) {
1032                         /* initial hair frame from root orientation */
1033                         copy_m3_m3(hair_frame, hair_ij->rot);
1034                         /* surface normal is the initial direction,
1035                          * parallel transport then keeps it aligned to the hair direction
1036                          */
1037                         copy_v3_v3(dir_new, hair_frame[2]);
1038                 }
1039
1040                 copy_v3_v3(dir_old, dir_new);
1041                 sub_v3_v3v3(dir_new, cloth->verts[spring->mn].xrest, cloth->verts[spring->kl].xrest);
1042                 normalize_v3(dir_new);
1043
1044                 /* dir expressed in the hair frame defines the rest target direction */
1045                 copy_v3_v3(hair_kl->rest_target, dir_new);
1046                 mul_transposed_m3_v3(hair_frame, hair_kl->rest_target);
1047
1048                 /* move frame to next hair segment */
1049                 cloth_parallel_transport_hair_frame(hair_frame, dir_old, dir_new);
1050
1051                 prev_mn = spring->mn;
1052         }
1053 }
1054
1055 /* update stiffness if vertex group values are changing from frame to frame */
1056 static void cloth_update_springs( ClothModifierData *clmd )
1057 {
1058         Cloth *cloth = clmd->clothObject;
1059         LinkNode *search = NULL;
1060
1061         search = cloth->springs;
1062         while (search) {
1063                 ClothSpring *spring = search->link;
1064
1065                 spring->lin_stiffness = 0.0f;
1066
1067                 if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1068                         if (spring->type & CLOTH_SPRING_TYPE_BENDING) {
1069                                 spring->ang_stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1070                         }
1071                 }
1072
1073                 if (spring->type & CLOTH_SPRING_TYPE_STRUCTURAL) {
1074                         spring->lin_stiffness = (cloth->verts[spring->kl].struct_stiff + cloth->verts[spring->ij].struct_stiff) / 2.0f;
1075                 }
1076                 else if (spring->type & CLOTH_SPRING_TYPE_SHEAR) {
1077                         spring->lin_stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0f;
1078                 }
1079                 else if (spring->type == CLOTH_SPRING_TYPE_BENDING) {
1080                         spring->lin_stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1081                 }
1082                 else if (spring->type == CLOTH_SPRING_TYPE_BENDING_HAIR) {
1083                         ClothVertex *v1 = &cloth->verts[spring->ij];
1084                         ClothVertex *v2 = &cloth->verts[spring->kl];
1085                         if (clmd->hairdata) {
1086                                 /* copy extra hair data to generic cloth vertices */
1087                                 v1->bend_stiff = clmd->hairdata[spring->ij].bending_stiffness;
1088                                 v2->bend_stiff = clmd->hairdata[spring->kl].bending_stiffness;
1089                         }
1090                         spring->lin_stiffness = (v1->bend_stiff + v2->bend_stiff) / 2.0f;
1091                 }
1092                 else if (spring->type == CLOTH_SPRING_TYPE_GOAL) {
1093                         /* Warning: Appending NEW goal springs does not work because implicit solver would need reset! */
1094
1095                         /* Activate / Deactivate existing springs */
1096                         if ((!(cloth->verts[spring->ij].flags & CLOTH_VERT_FLAG_PINNED)) &&
1097                             (cloth->verts[spring->ij].goal > ALMOST_ZERO))
1098                         {
1099                                 spring->flags &= ~CLOTH_SPRING_FLAG_DEACTIVATE;
1100                         }
1101                         else {
1102                                 spring->flags |= CLOTH_SPRING_FLAG_DEACTIVATE;
1103                         }
1104                 }
1105
1106                 search = search->next;
1107         }
1108
1109         cloth_hair_update_bending_targets(clmd);
1110 }
1111
1112 /* Update rest verts, for dynamically deformable cloth */
1113 static void cloth_update_verts( Object *ob, ClothModifierData *clmd, Mesh *mesh )
1114 {
1115         unsigned int i = 0;
1116         MVert *mvert = mesh->mvert;
1117         ClothVertex *verts = clmd->clothObject->verts;
1118
1119         /* vertex count is already ensured to match */
1120         for ( i = 0; i < mesh->totvert; i++, verts++ ) {
1121                 copy_v3_v3(verts->xrest, mvert[i].co);
1122                 mul_m4_v3(ob->obmat, verts->xrest);
1123         }
1124 }
1125
1126 /* Update spring rest length, for dynamically deformable cloth */
1127 static void cloth_update_spring_lengths( ClothModifierData *clmd, Mesh *mesh )
1128 {
1129         Cloth *cloth = clmd->clothObject;
1130         LinkNode *search = cloth->springs;
1131         unsigned int struct_springs = 0;
1132         unsigned int i = 0;
1133         unsigned int mvert_num = (unsigned int)mesh->totvert;
1134         float shrink_factor;
1135
1136         clmd->sim_parms->avg_spring_len = 0.0f;
1137
1138         for (i = 0; i < mvert_num; i++) {
1139                 cloth->verts[i].avg_spring_len = 0.0f;
1140         }
1141
1142         while (search) {
1143                 ClothSpring *spring = search->link;
1144
1145                 if (spring->type != CLOTH_SPRING_TYPE_SEWING) {
1146                         if (spring->type & (CLOTH_SPRING_TYPE_STRUCTURAL | CLOTH_SPRING_TYPE_SHEAR | CLOTH_SPRING_TYPE_BENDING)) {
1147                                 shrink_factor = cloth_shrink_factor(clmd, cloth->verts, spring->ij, spring->kl);
1148                         }
1149                         else {
1150                                 shrink_factor = 1.0f;
1151                         }
1152
1153                         spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest) * shrink_factor;
1154
1155                         if (spring->type & CLOTH_SPRING_TYPE_BENDING) {
1156                                 spring->restang = cloth_spring_angle(cloth->verts, spring->ij, spring->kl,
1157                                                                      spring->pa, spring->pb, spring->la, spring->lb);
1158                         }
1159                 }
1160
1161                 if (spring->type & CLOTH_SPRING_TYPE_STRUCTURAL) {
1162                         clmd->sim_parms->avg_spring_len += spring->restlen;
1163                         cloth->verts[spring->ij].avg_spring_len += spring->restlen;
1164                         cloth->verts[spring->kl].avg_spring_len += spring->restlen;
1165                         struct_springs++;
1166                 }
1167
1168                 search = search->next;
1169         }
1170
1171         if (struct_springs > 0) {
1172                 clmd->sim_parms->avg_spring_len /= struct_springs;
1173         }
1174
1175         for (i = 0; i < mvert_num; i++) {
1176                 if (cloth->verts[i].spring_count > 0) {
1177                         cloth->verts[i].avg_spring_len = cloth->verts[i].avg_spring_len * 0.49f / ((float)cloth->verts[i].spring_count);
1178                 }
1179         }
1180 }
1181
1182 BLI_INLINE void cross_identity_v3(float r[3][3], const float v[3])
1183 {
1184         zero_m3(r);
1185         r[0][1] = v[2];
1186         r[0][2] = -v[1];
1187         r[1][0] = -v[2];
1188         r[1][2] = v[0];
1189         r[2][0] = v[1];
1190         r[2][1] = -v[0];
1191 }
1192
1193 BLI_INLINE void madd_m3_m3fl(float r[3][3], float m[3][3], float f)
1194 {
1195         r[0][0] += m[0][0] * f;
1196         r[0][1] += m[0][1] * f;
1197         r[0][2] += m[0][2] * f;
1198         r[1][0] += m[1][0] * f;
1199         r[1][1] += m[1][1] * f;
1200         r[1][2] += m[1][2] * f;
1201         r[2][0] += m[2][0] * f;
1202         r[2][1] += m[2][1] * f;
1203         r[2][2] += m[2][2] * f;
1204 }
1205
1206 void cloth_parallel_transport_hair_frame(float mat[3][3], const float dir_old[3], const float dir_new[3])
1207 {
1208         float rot[3][3];
1209
1210         /* rotation between segments */
1211         rotation_between_vecs_to_mat3(rot, dir_old, dir_new);
1212
1213         /* rotate the frame */
1214         mul_m3_m3m3(mat, rot, mat);
1215 }
1216
1217 /* Add a shear and a bend spring between two verts within a poly. */
1218 static bool cloth_add_shear_bend_spring(ClothModifierData *clmd, LinkNodePair *edgelist,
1219                                         const MLoop *mloop, const MPoly *mpoly, int i, int j, int k)
1220 {
1221         Cloth *cloth = clmd->clothObject;
1222         ClothSpring *spring;
1223         const MLoop *tmp_loop;
1224         float shrink_factor;
1225         int x, y;
1226
1227         /* Combined shear/bend properties. */
1228         spring = (ClothSpring *)MEM_callocN(sizeof(ClothSpring), "cloth spring");
1229
1230         if (!spring) {
1231                 return false;
1232         }
1233
1234         spring_verts_ordered_set(spring,
1235                                  mloop[mpoly[i].loopstart + j].v,
1236                                  mloop[mpoly[i].loopstart + k].v);
1237
1238         shrink_factor = cloth_shrink_factor(clmd, cloth->verts, spring->ij, spring->kl);
1239         spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest) * shrink_factor;
1240         spring->type |= CLOTH_SPRING_TYPE_SHEAR;
1241         spring->lin_stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0f;
1242
1243         if (edgelist) {
1244                 BLI_linklist_append(&edgelist[spring->ij], spring);
1245                 BLI_linklist_append(&edgelist[spring->kl], spring);
1246         }
1247
1248         /* Bending specific properties. */
1249         if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1250                 spring->type |= CLOTH_SPRING_TYPE_BENDING;
1251
1252                 spring->la = k - j + 1;
1253                 spring->lb = mpoly[i].totloop - k + j + 1;
1254
1255                 spring->pa = MEM_mallocN(sizeof(*spring->pa) * spring->la, "spring poly");
1256                 if (!spring->pa) {
1257                         return false;
1258                 }
1259
1260                 spring->pb = MEM_mallocN(sizeof(*spring->pb) * spring->lb, "spring poly");
1261                 if (!spring->pb) {
1262                         return false;
1263                 }
1264
1265                 tmp_loop = mloop + mpoly[i].loopstart;
1266
1267                 for (x = 0; x < spring->la; x++) {
1268                         spring->pa[x] = tmp_loop[j + x].v;
1269                 }
1270
1271                 for (x = 0; x <= j; x++) {
1272                         spring->pb[x] = tmp_loop[x].v;
1273                 }
1274
1275                 for (y = k; y < mpoly[i].totloop; x++, y++) {
1276                         spring->pb[x] = tmp_loop[y].v;
1277                 }
1278
1279                 spring->mn = -1;
1280
1281                 spring->restang = cloth_spring_angle(cloth->verts, spring->ij, spring->kl,
1282                                                      spring->pa, spring->pb, spring->la, spring->lb);
1283
1284                 spring->ang_stiffness = (cloth->verts[spring->ij].bend_stiff + cloth->verts[spring->kl].bend_stiff) / 2.0f;
1285         }
1286
1287         BLI_linklist_prepend(&cloth->springs, spring);
1288
1289         return true;
1290 }
1291
1292 BLI_INLINE bool cloth_bend_set_poly_vert_array(int **poly, int len, const MLoop *mloop)
1293 {
1294         int *p = MEM_mallocN(sizeof(int) * len, "spring poly");
1295
1296         if (!p) {
1297                 return false;
1298         }
1299
1300         for (int i = 0; i < len; i++, mloop++) {
1301                 p[i] = mloop->v;
1302         }
1303
1304         *poly = p;
1305
1306         return true;
1307 }
1308
1309 static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh )
1310 {
1311         Cloth *cloth = clmd->clothObject;
1312         ClothSpring *spring = NULL, *tspring = NULL, *tspring2 = NULL;
1313         unsigned int struct_springs = 0, shear_springs=0, bend_springs = 0, struct_springs_real = 0;
1314         unsigned int mvert_num = (unsigned int)mesh->totvert;
1315         unsigned int numedges = (unsigned int)mesh->totedge;
1316         unsigned int numpolys = (unsigned int)mesh->totpoly;
1317         float shrink_factor;
1318         const MEdge *medge = mesh->medge;
1319         const MPoly *mpoly = mesh->mpoly;
1320         const MLoop *mloop = mesh->mloop;
1321         int index2 = 0; // our second vertex index
1322         LinkNodePair *edgelist = NULL;
1323         EdgeSet *edgeset = NULL;
1324         LinkNode *search = NULL, *search2 = NULL;
1325         BendSpringRef *spring_ref = NULL;
1326
1327         // error handling
1328         if ( numedges==0 )
1329                 return 0;
1330
1331         /* NOTE: handling ownership of springs and edgeset is quite sloppy
1332          * currently they are never initialized but assert just to be sure */
1333         BLI_assert(cloth->springs == NULL);
1334         BLI_assert(cloth->edgeset == NULL);
1335
1336         cloth->springs = NULL;
1337         cloth->edgeset = NULL;
1338
1339         if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1340                 spring_ref = MEM_callocN(sizeof(*spring_ref) * numedges, "temp bend spring reference");
1341
1342                 if (!spring_ref) {
1343                         return 0;
1344                 }
1345         }
1346         else {
1347                 edgelist = MEM_callocN(sizeof(*edgelist) * mvert_num, "cloth_edgelist_alloc" );
1348
1349                 if (!edgelist) {
1350                         return 0;
1351                 }
1352         }
1353
1354         clmd->sim_parms->avg_spring_len = 0.0f;
1355         for (int i = 0; i < mvert_num; i++) {
1356                 cloth->verts[i].avg_spring_len = 0.0f;
1357         }
1358
1359         /* Structural springs. */
1360         for (int i = 0; i < numedges; i++) {
1361                 spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1362
1363                 if ( spring ) {
1364                         spring_verts_ordered_set(spring, medge[i].v1, medge[i].v2);
1365                         if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SEW && medge[i].flag & ME_LOOSEEDGE) {
1366                                 // handle sewing (loose edges will be pulled together)
1367                                 spring->restlen = 0.0f;
1368                                 spring->lin_stiffness = 1.0f;
1369                                 spring->type = CLOTH_SPRING_TYPE_SEWING;
1370                         }
1371                         else {
1372                                 shrink_factor = cloth_shrink_factor(clmd, cloth->verts, spring->ij, spring->kl);
1373                                 spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest) * shrink_factor;
1374                                 spring->lin_stiffness = (cloth->verts[spring->kl].struct_stiff + cloth->verts[spring->ij].struct_stiff) / 2.0f;
1375                                 spring->type = CLOTH_SPRING_TYPE_STRUCTURAL;
1376
1377                                 clmd->sim_parms->avg_spring_len += spring->restlen;
1378                                 cloth->verts[spring->ij].avg_spring_len += spring->restlen;
1379                                 cloth->verts[spring->kl].avg_spring_len += spring->restlen;
1380                                 cloth->verts[spring->ij].spring_count++;
1381                                 cloth->verts[spring->kl].spring_count++;
1382                                 struct_springs_real++;
1383                         }
1384
1385                         spring->flags = 0;
1386                         struct_springs++;
1387
1388                         BLI_linklist_prepend ( &cloth->springs, spring );
1389
1390                         if (spring_ref) {
1391                                 spring_ref[i].spring = spring;
1392                         }
1393                 }
1394                 else {
1395                         cloth_free_errorsprings(cloth, edgelist, spring_ref);
1396                         return 0;
1397                 }
1398         }
1399
1400         if (struct_springs_real > 0)
1401                 clmd->sim_parms->avg_spring_len /= struct_springs_real;
1402
1403         for (int i = 0; i < mvert_num; i++) {
1404                 if (cloth->verts[i].spring_count > 0)
1405                         cloth->verts[i].avg_spring_len = cloth->verts[i].avg_spring_len * 0.49f / ((float)cloth->verts[i].spring_count);
1406         }
1407
1408         edgeset = BLI_edgeset_new_ex(__func__, numedges);
1409         cloth->edgeset = edgeset;
1410
1411         if (numpolys) {
1412                 for (int i = 0; i < numpolys; i++) {
1413                         /* Shear springs. */
1414                         /* Triangle faces already have shear springs due to structural geometry. */
1415                         if (mpoly[i].totloop > 3) {
1416                                 for (int j = 1; j < mpoly[i].totloop - 1; j++) {
1417                                         if (j > 1) {
1418                                                 if (cloth_add_shear_bend_spring(clmd, edgelist, mloop, mpoly, i, 0, j)) {
1419                                                         shear_springs++;
1420
1421                                                         if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1422                                                                 bend_springs++;
1423                                                         }
1424                                                 }
1425                                                 else {
1426                                                         cloth_free_errorsprings(cloth, edgelist, spring_ref);
1427                                                         return 0;
1428                                                 }
1429                                         }
1430
1431                                         for (int k = j + 2; k < mpoly[i].totloop; k++) {
1432                                                 if (cloth_add_shear_bend_spring(clmd, edgelist, mloop, mpoly, i, j, k)) {
1433                                                         shear_springs++;
1434
1435                                                         if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1436                                                                 bend_springs++;
1437                                                         }
1438                                                 }
1439                                                 else {
1440                                                         cloth_free_errorsprings(cloth, edgelist, spring_ref);
1441                                                         return 0;
1442                                                 }
1443                                         }
1444                                 }
1445                         }
1446
1447                         /* Angular bending springs along struct springs. */
1448                         if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1449                                 const MLoop *ml = mloop + mpoly[i].loopstart;
1450
1451                                 for (int j = 0; j < mpoly[i].totloop; j++, ml++) {
1452                                         BendSpringRef *curr_ref = &spring_ref[ml->e];
1453                                         curr_ref->polys++;
1454
1455                                         /* First poly found for this edge, store poly index. */
1456                                         if (curr_ref->polys == 1) {
1457                                                 curr_ref->index = i;
1458                                         }
1459                                         /* Second poly found for this edge, add bending data. */
1460                                         else if (curr_ref->polys == 2) {
1461                                                 spring = curr_ref->spring;
1462
1463                                                 spring->type |= CLOTH_SPRING_TYPE_BENDING;
1464
1465                                                 spring->la = mpoly[curr_ref->index].totloop;
1466                                                 spring->lb = mpoly[i].totloop;
1467
1468                                                 if (!cloth_bend_set_poly_vert_array(&spring->pa, spring->la, &mloop[mpoly[curr_ref->index].loopstart]) ||
1469                                                     !cloth_bend_set_poly_vert_array(&spring->pb, spring->lb, &mloop[mpoly[i].loopstart]))
1470                                                 {
1471                                                         cloth_free_errorsprings(cloth, edgelist, spring_ref);
1472                                                         return 0;
1473                                                 }
1474
1475                                                 spring->mn = ml->e;
1476
1477                                                 spring->restang = cloth_spring_angle(cloth->verts, spring->ij, spring->kl,
1478                                                                                      spring->pa, spring->pb, spring->la, spring->lb);
1479
1480                                                 spring->ang_stiffness = (cloth->verts[spring->ij].bend_stiff + cloth->verts[spring->kl].bend_stiff) / 2.0f;
1481
1482                                                 bend_springs++;
1483                                         }
1484                                         /* Third poly found for this edge, remove bending data. */
1485                                         else if (curr_ref->polys == 3) {
1486                                                 spring = curr_ref->spring;
1487
1488                                                 spring->type &= ~CLOTH_SPRING_TYPE_BENDING;
1489                                                 MEM_freeN(spring->pa);
1490                                                 MEM_freeN(spring->pb);
1491                                                 spring->pa = NULL;
1492                                                 spring->pb = NULL;
1493
1494                                                 bend_springs--;
1495                                         }
1496                                 }
1497                         }
1498                 }
1499
1500                 /* Linear bending springs. */
1501                 if (clmd->sim_parms->bending_model == CLOTH_BENDING_LINEAR) {
1502                         search2 = cloth->springs;
1503
1504                         for (int i = struct_springs; i < struct_springs+shear_springs; i++) {
1505                                 if (!search2) {
1506                                         break;
1507                                 }
1508
1509                                 tspring2 = search2->link;
1510                                 search = edgelist[tspring2->kl].list;
1511
1512                                 while (search) {
1513                                         tspring = search->link;
1514                                         index2 = ((tspring->ij == tspring2->kl) ? (tspring->kl) : (tspring->ij));
1515
1516                                         /* Check for existing spring. */
1517                                         /* Check also if startpoint is equal to endpoint. */
1518                                         if ((index2 != tspring2->ij) &&
1519                                                 !BLI_edgeset_haskey(edgeset, tspring2->ij, index2))
1520                                         {
1521                                                 spring = (ClothSpring *)MEM_callocN(sizeof(ClothSpring), "cloth spring");
1522
1523                                                 if (!spring) {
1524                                                         cloth_free_errorsprings(cloth, edgelist, spring_ref);
1525                                                         return 0;
1526                                                 }
1527
1528                                                 spring_verts_ordered_set(spring, tspring2->ij, index2);
1529                                                 shrink_factor = cloth_shrink_factor(clmd, cloth->verts, spring->ij, spring->kl);
1530                                                 spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest) * shrink_factor;
1531                                                 spring->type = CLOTH_SPRING_TYPE_BENDING;
1532                                                 spring->lin_stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1533                                                 BLI_edgeset_insert(edgeset, spring->ij, spring->kl);
1534                                                 bend_springs++;
1535
1536                                                 BLI_linklist_prepend(&cloth->springs, spring);
1537                                         }
1538
1539                                         search = search->next;
1540                                 }
1541
1542                                 search2 = search2->next;
1543                         }
1544                 }
1545         }
1546         else if (struct_springs > 2) {
1547                 if (G.debug_value != 1112) {
1548                         search = cloth->springs;
1549                         search2 = search->next;
1550                         while (search && search2) {
1551                                 tspring = search->link;
1552                                 tspring2 = search2->link;
1553
1554                                 if (tspring->ij == tspring2->kl) {
1555                                         spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1556
1557                                         if (!spring) {
1558                                                 cloth_free_errorsprings(cloth, edgelist, spring_ref);
1559                                                 return 0;
1560                                         }
1561
1562                                         spring->ij = tspring2->ij;
1563                                         spring->kl = tspring->ij;
1564                                         spring->mn = tspring->kl;
1565                                         spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest);
1566                                         spring->type = CLOTH_SPRING_TYPE_BENDING_HAIR;
1567                                         spring->lin_stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1568                                         bend_springs++;
1569
1570                                         BLI_linklist_prepend ( &cloth->springs, spring );
1571                                 }
1572
1573                                 search = search->next;
1574                                 search2 = search2->next;
1575                         }
1576                 }
1577                 else {
1578                         /* bending springs for hair strands
1579                          * The current algorithm only goes through the edges in order of the mesh edges list
1580                          * and makes springs between the outer vert of edges sharing a vertice. This works just
1581                          * fine for hair, but not for user generated string meshes. This could/should be later
1582                          * extended to work with non-ordered edges so that it can be used for general "rope
1583                          * dynamics" without the need for the vertices or edges to be ordered through the length
1584                          * of the strands. -jahka */
1585                         search = cloth->springs;
1586                         search2 = search->next;
1587                         while (search && search2) {
1588                                 tspring = search->link;
1589                                 tspring2 = search2->link;
1590
1591                                 if (tspring->ij == tspring2->kl) {
1592                                         spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1593
1594                                         if (!spring) {
1595                                                 cloth_free_errorsprings(cloth, edgelist, spring_ref);
1596                                                 return 0;
1597                                         }
1598
1599                                         spring->ij = tspring2->ij;
1600                                         spring->kl = tspring->kl;
1601                                         spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest);
1602                                         spring->type = CLOTH_SPRING_TYPE_BENDING;
1603                                         spring->lin_stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1604                                         bend_springs++;
1605
1606                                         BLI_linklist_prepend ( &cloth->springs, spring );
1607                                 }
1608
1609                                 search = search->next;
1610                                 search2 = search2->next;
1611                         }
1612                 }
1613
1614                 cloth_hair_update_bending_rest_targets(clmd);
1615         }
1616
1617         /* note: the edges may already exist so run reinsert */
1618
1619         /* insert other near springs in edgeset AFTER bending springs are calculated (for selfcolls) */
1620         for (int i = 0; i < numedges; i++) { /* struct springs */
1621                 BLI_edgeset_add(edgeset, medge[i].v1, medge[i].v2);
1622         }
1623
1624         for (int i = 0; i < numpolys; i++) { /* edge springs */
1625                 if (mpoly[i].totloop == 4) {
1626                         BLI_edgeset_add(edgeset, mloop[mpoly[i].loopstart + 0].v, mloop[mpoly[i].loopstart + 2].v);
1627                         BLI_edgeset_add(edgeset, mloop[mpoly[i].loopstart + 1].v, mloop[mpoly[i].loopstart + 3].v);
1628                 }
1629         }
1630
1631         MEM_SAFE_FREE(spring_ref);
1632
1633         cloth->numsprings = struct_springs + shear_springs + bend_springs;
1634
1635         cloth_free_edgelist(edgelist, mvert_num);
1636
1637 #if 0
1638         if (G.debug_value > 0)
1639                 printf("avg_len: %f\n", clmd->sim_parms->avg_spring_len);
1640 #endif
1641
1642         return 1;
1643
1644 } /* cloth_build_springs */
1645 /***************************************************************************************
1646  * SPRING NETWORK GPU_BATCH_BUILDING IMPLEMENTATION END
1647  ***************************************************************************************/