sim: Remove "continue physics" code
[blender.git] / source / blender / blenkernel / intern / cloth.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  * Contributor(s): Daniel Genrich
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/cloth.c
27  *  \ingroup bke
28  */
29
30
31 #include "MEM_guardedalloc.h"
32
33 #include "DNA_cloth_types.h"
34 #include "DNA_scene_types.h"
35 #include "DNA_object_types.h"
36 #include "DNA_meshdata_types.h"
37
38 #include "BLI_utildefines.h"
39 #include "BLI_math.h"
40 #include "BLI_edgehash.h"
41 #include "BLI_utildefines.h"
42 #include "BLI_linklist.h"
43
44 #include "BKE_cdderivedmesh.h"
45 #include "BKE_cloth.h"
46 #include "BKE_effect.h"
47 #include "BKE_global.h"
48 #include "BKE_modifier.h"
49 #include "BKE_pointcache.h"
50
51 // #include "PIL_time.h"  /* timing for debug prints */
52
53 /* Our available solvers. */
54 // 255 is the magic reserved number, so NEVER try to put 255 solvers in here!
55 // 254 = MAX!
56 static CM_SOLVER_DEF    solvers [] =
57 {
58         { "Implicit", CM_IMPLICIT, implicit_init, implicit_solver, implicit_free },
59                 // { "Implicit C++", CM_IMPLICITCPP, implicitcpp_init, implicitcpp_solver, implicitcpp_free },
60 };
61
62 /* ********** cloth engine ******* */
63 /* Prototypes for internal functions.
64  */
65 static void cloth_to_object (Object *ob,  ClothModifierData *clmd, float (*vertexCos)[3]);
66 static void cloth_from_mesh ( ClothModifierData *clmd, DerivedMesh *dm );
67 static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *dm, float framenr, int first);
68 static void cloth_update_springs( ClothModifierData *clmd );
69 static int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm );
70 static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm );
71
72
73 /******************************************************************************
74  *
75  * External interface called by modifier.c clothModifier functions.
76  *
77  ******************************************************************************/
78 /**
79  * cloth_init - creates a new cloth simulation.
80  *
81  * 1. create object
82  * 2. fill object with standard values or with the GUI settings if given
83  */
84 void cloth_init(ClothModifierData *clmd )
85 {       
86         /* Initialize our new data structure to reasonable values. */
87         clmd->sim_parms->gravity[0] = 0.0;
88         clmd->sim_parms->gravity[1] = 0.0;
89         clmd->sim_parms->gravity[2] = -9.81;
90         clmd->sim_parms->structural = 15.0;
91         clmd->sim_parms->shear = 15.0;
92         clmd->sim_parms->bending = 0.5;
93         clmd->sim_parms->Cdis = 5.0; 
94         clmd->sim_parms->Cvi = 1.0;
95         clmd->sim_parms->mass = 0.3f;
96         clmd->sim_parms->stepsPerFrame = 5;
97         clmd->sim_parms->flags = 0;
98         clmd->sim_parms->solver_type = 0;
99         clmd->sim_parms->preroll = 0;
100         clmd->sim_parms->maxspringlen = 10;
101         clmd->sim_parms->vgroup_mass = 0;
102         clmd->sim_parms->avg_spring_len = 0.0;
103         clmd->sim_parms->presets = 2; /* cotton as start setting */
104         clmd->sim_parms->timescale = 1.0f; /* speed factor, describes how fast cloth moves */
105         clmd->sim_parms->reset = 0;
106         clmd->sim_parms->vel_damping = 1.0f; /* 1.0 = no damping, 0.0 = fully dampened */
107         
108         clmd->coll_parms->self_friction = 5.0;
109         clmd->coll_parms->friction = 5.0;
110         clmd->coll_parms->loop_count = 2;
111         clmd->coll_parms->epsilon = 0.015f;
112         clmd->coll_parms->flags = CLOTH_COLLSETTINGS_FLAG_ENABLED;
113         clmd->coll_parms->collision_list = NULL;
114         clmd->coll_parms->self_loop_count = 1.0;
115         clmd->coll_parms->selfepsilon = 0.75;
116         clmd->coll_parms->vgroup_selfcol = 0;
117
118         /* These defaults are copied from softbody.c's
119          * softbody_calc_forces() function.
120          */
121         clmd->sim_parms->eff_force_scale = 1000.0;
122         clmd->sim_parms->eff_wind_scale = 250.0;
123
124         // also from softbodies
125         clmd->sim_parms->maxgoal = 1.0f;
126         clmd->sim_parms->mingoal = 0.0f;
127         clmd->sim_parms->defgoal = 0.0f;
128         clmd->sim_parms->goalspring = 1.0f;
129         clmd->sim_parms->goalfrict = 0.0f;
130         clmd->sim_parms->velocity_smooth = 0.0f;
131
132         if (!clmd->sim_parms->effector_weights)
133                 clmd->sim_parms->effector_weights = BKE_add_effector_weights(NULL);
134
135         if (clmd->point_cache)
136                 clmd->point_cache->step = 1;
137 }
138
139 static BVHTree *bvhselftree_build_from_cloth (ClothModifierData *clmd, float epsilon)
140 {
141         unsigned int i;
142         BVHTree *bvhtree;
143         Cloth *cloth;
144         ClothVertex *verts;
145         float co[12];
146
147         if (!clmd)
148                 return NULL;
149
150         cloth = clmd->clothObject;
151
152         if (!cloth)
153                 return NULL;
154         
155         verts = cloth->verts;
156         
157         // in the moment, return zero if no faces there
158         if (!cloth->numverts)
159                 return NULL;
160         
161         // create quadtree with k=26
162         bvhtree = BLI_bvhtree_new(cloth->numverts, epsilon, 4, 6);
163         
164         // fill tree
165         for (i = 0; i < cloth->numverts; i++, verts++) {
166                 copy_v3_v3(&co[0*3], verts->xold);
167                 
168                 BLI_bvhtree_insert(bvhtree, i, co, 1);
169         }
170         
171         // balance tree
172         BLI_bvhtree_balance(bvhtree);
173         
174         return bvhtree;
175 }
176
177 static BVHTree *bvhtree_build_from_cloth (ClothModifierData *clmd, float epsilon)
178 {
179         unsigned int i;
180         BVHTree *bvhtree;
181         Cloth *cloth;
182         ClothVertex *verts;
183         MFace *mfaces;
184         float co[12];
185
186         if (!clmd)
187                 return NULL;
188
189         cloth = clmd->clothObject;
190
191         if (!cloth)
192                 return NULL;
193         
194         verts = cloth->verts;
195         mfaces = cloth->mfaces;
196         
197         /* in the moment, return zero if no faces there */
198         if (!cloth->numfaces)
199                 return NULL;
200
201         /* create quadtree with k=26 */
202         bvhtree = BLI_bvhtree_new(cloth->numfaces, epsilon, 4, 26);
203
204         /* fill tree */
205         for (i = 0; i < cloth->numfaces; i++, mfaces++) {
206                 copy_v3_v3(&co[0*3], verts[mfaces->v1].xold);
207                 copy_v3_v3(&co[1*3], verts[mfaces->v2].xold);
208                 copy_v3_v3(&co[2*3], verts[mfaces->v3].xold);
209
210                 if (mfaces->v4)
211                         copy_v3_v3(&co[3*3], verts[mfaces->v4].xold);
212
213                 BLI_bvhtree_insert(bvhtree, i, co, (mfaces->v4 ? 4 : 3));
214         }
215
216         /* balance tree */
217         BLI_bvhtree_balance(bvhtree);
218         
219         return bvhtree;
220 }
221
222 void bvhtree_update_from_cloth(ClothModifierData *clmd, int moving)
223 {       
224         unsigned int i = 0;
225         Cloth *cloth = clmd->clothObject;
226         BVHTree *bvhtree = cloth->bvhtree;
227         ClothVertex *verts = cloth->verts;
228         MFace *mfaces;
229         float co[12], co_moving[12];
230         int ret = 0;
231         
232         if (!bvhtree)
233                 return;
234         
235         mfaces = cloth->mfaces;
236         
237         // update vertex position in bvh tree
238         if (verts && mfaces) {
239                 for (i = 0; i < cloth->numfaces; i++, mfaces++) {
240                         copy_v3_v3(&co[0*3], verts[mfaces->v1].txold);
241                         copy_v3_v3(&co[1*3], verts[mfaces->v2].txold);
242                         copy_v3_v3(&co[2*3], verts[mfaces->v3].txold);
243                         
244                         if (mfaces->v4)
245                                 copy_v3_v3(&co[3*3], verts[mfaces->v4].txold);
246                 
247                         // copy new locations into array
248                         if (moving) {
249                                 // update moving positions
250                                 copy_v3_v3(&co_moving[0*3], verts[mfaces->v1].tx);
251                                 copy_v3_v3(&co_moving[1*3], verts[mfaces->v2].tx);
252                                 copy_v3_v3(&co_moving[2*3], verts[mfaces->v3].tx);
253                                 
254                                 if (mfaces->v4)
255                                         copy_v3_v3(&co_moving[3*3], verts[mfaces->v4].tx);
256                                 
257                                 ret = BLI_bvhtree_update_node(bvhtree, i, co, co_moving, (mfaces->v4 ? 4 : 3));
258                         }
259                         else {
260                                 ret = BLI_bvhtree_update_node(bvhtree, i, co, NULL, (mfaces->v4 ? 4 : 3));
261                         }
262                         
263                         // check if tree is already full
264                         if (!ret)
265                                 break;
266                 }
267                 
268                 BLI_bvhtree_update_tree(bvhtree);
269         }
270 }
271
272 void bvhselftree_update_from_cloth(ClothModifierData *clmd, int moving)
273 {       
274         unsigned int i = 0;
275         Cloth *cloth = clmd->clothObject;
276         BVHTree *bvhtree = cloth->bvhselftree;
277         ClothVertex *verts = cloth->verts;
278         MFace *mfaces;
279         float co[12], co_moving[12];
280         int ret = 0;
281         
282         if (!bvhtree)
283                 return;
284         
285         mfaces = cloth->mfaces;
286
287         // update vertex position in bvh tree
288         if (verts && mfaces) {
289                 for (i = 0; i < cloth->numverts; i++, verts++) {
290                         copy_v3_v3(&co[0*3], verts->txold);
291
292                         // copy new locations into array
293                         if (moving) {
294                                 // update moving positions
295                                 copy_v3_v3(&co_moving[0*3], verts->tx);
296
297                                 ret = BLI_bvhtree_update_node(bvhtree, i, co, co_moving, 1);
298                         }
299                         else {
300                                 ret = BLI_bvhtree_update_node(bvhtree, i, co, NULL, 1);
301                         }
302
303                         // check if tree is already full
304                         if (!ret)
305                                 break;
306                 }
307                 
308                 BLI_bvhtree_update_tree(bvhtree);
309         }
310 }
311
312 void cloth_clear_cache(Object *ob, ClothModifierData *clmd, float framenr)
313 {
314         PTCacheID pid;
315         
316         BKE_ptcache_id_from_cloth(&pid, ob, clmd);
317
318         // don't do anything as long as we're in editmode!
319         if (pid.cache->edit && ob->mode & OB_MODE_PARTICLE_EDIT)
320                 return;
321         
322         BKE_ptcache_id_clear(&pid, PTCACHE_CLEAR_AFTER, framenr);
323 }
324
325 static int do_init_cloth(Object *ob, ClothModifierData *clmd, DerivedMesh *result, int framenr)
326 {
327         PointCache *cache;
328
329         cache= clmd->point_cache;
330
331         /* initialize simulation data if it didn't exist already */
332         if (clmd->clothObject == NULL) {
333                 if (!cloth_from_object(ob, clmd, result, framenr, 1)) {
334                         BKE_ptcache_invalidate(cache);
335                         return 0;
336                 }
337         
338                 if (clmd->clothObject == NULL) {
339                         BKE_ptcache_invalidate(cache);
340                         return 0;
341                 }
342         
343                 implicit_set_positions(clmd);
344
345                 clmd->clothObject->last_frame= MINFRAME-1;
346         }
347
348         return 1;
349 }
350
351 static int do_step_cloth(Object *ob, ClothModifierData *clmd, DerivedMesh *result, int framenr)
352 {
353         ClothVertex *verts = NULL;
354         Cloth *cloth;
355         ListBase *effectors = NULL;
356         MVert *mvert;
357         unsigned int i = 0;
358         int ret = 0;
359
360         /* simulate 1 frame forward */
361         cloth = clmd->clothObject;
362         verts = cloth->verts;
363         mvert = result->getVertArray(result);
364
365         /* force any pinned verts to their constrained location. */
366         for (i = 0; i < clmd->clothObject->numverts; i++, verts++) {
367                 /* save the previous position. */
368                 copy_v3_v3(verts->xold, verts->xconst);
369                 copy_v3_v3(verts->txold, verts->x);
370
371                 /* Get the current position. */
372                 copy_v3_v3(verts->xconst, mvert[i].co);
373                 mul_m4_v3(ob->obmat, verts->xconst);
374         }
375
376         effectors = pdInitEffectors(clmd->scene, ob, NULL, clmd->sim_parms->effector_weights);
377
378         /* Support for dynamic vertex groups, changing from frame to frame */
379         cloth_apply_vgroup ( clmd, result );
380         cloth_update_springs( clmd );
381         
382         // TIMEIT_START(cloth_step)
383
384         /* call the solver. */
385         if (solvers [clmd->sim_parms->solver_type].solver)
386                 ret = solvers[clmd->sim_parms->solver_type].solver(ob, framenr, clmd, effectors);
387
388         // TIMEIT_END(cloth_step)
389
390         pdEndEffectors(&effectors);
391
392         // printf ( "%f\n", ( float ) tval() );
393         
394         return ret;
395 }
396
397 #if 0
398 static DerivedMesh *cloth_to_triangles(DerivedMesh *dm)
399 {
400         DerivedMesh *result = NULL;
401         unsigned int i = 0, j = 0;
402         unsigned int quads = 0, numfaces = dm->getNumTessFaces(dm);
403         MFace *mface = dm->getTessFaceArray(dm);
404         MFace *mface2 = NULL;
405
406         /* calc faces */
407         for (i = 0; i < numfaces; i++) {
408                 if (mface[i].v4) {
409                         quads++;
410                 }
411         }
412                 
413         result = CDDM_from_template(dm, dm->getNumVerts(dm), 0, numfaces + quads, 0, 0);
414
415         DM_copy_vert_data(dm, result, 0, 0, dm->getNumVerts(dm));
416         DM_copy_tessface_data(dm, result, 0, 0, numfaces);
417
418         DM_ensure_tessface(result);
419         mface2 = result->getTessFaceArray(result);
420
421         for (i = 0, j = numfaces; i < numfaces; i++) {
422                 // DG TODO: is this necessary?
423                 mface2[i].v1 = mface[i].v1;
424                 mface2[i].v2 = mface[i].v2;
425                 mface2[i].v3 = mface[i].v3;
426
427                 mface2[i].v4 = 0;
428                 //test_index_face(&mface2[i], &result->faceData, i, 3);
429
430                 if (mface[i].v4) {
431                         DM_copy_tessface_data(dm, result, i, j, 1);
432
433                         mface2[j].v1 = mface[i].v1;
434                         mface2[j].v2 = mface[i].v3;
435                         mface2[j].v3 = mface[i].v4;
436                         mface2[j].v4 = 0;
437                         //test_index_face(&mface2[j], &result->faceData, j, 3);
438
439                         j++;
440                 }
441         }
442
443         CDDM_calc_edges_tessface(result);
444         CDDM_tessfaces_to_faces(result); /* builds ngon faces from tess (mface) faces */
445
446         return result;
447 }
448 #endif
449
450 /************************************************
451  * clothModifier_do - main simulation function
452  ************************************************/
453 void clothModifier_do(ClothModifierData *clmd, Scene *scene, Object *ob, DerivedMesh *dm, float (*vertexCos)[3])
454 {
455         PointCache *cache;
456         PTCacheID pid;
457         float timescale;
458         int framenr, startframe, endframe;
459         int cache_result;
460
461         clmd->scene= scene;     /* nice to pass on later :) */
462         framenr= (int)scene->r.cfra;
463         cache= clmd->point_cache;
464
465         BKE_ptcache_id_from_cloth(&pid, ob, clmd);
466         BKE_ptcache_id_time(&pid, scene, framenr, &startframe, &endframe, &timescale);
467         clmd->sim_parms->timescale= timescale;
468
469         if (clmd->sim_parms->reset ||
470             (framenr == (startframe - clmd->sim_parms->preroll) && clmd->sim_parms->preroll != 0) ||
471             (clmd->clothObject && dm->getNumVerts(dm) != clmd->clothObject->numverts))
472         {
473                 clmd->sim_parms->reset = 0;
474                 cache->flag |= PTCACHE_OUTDATED;
475                 BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
476                 BKE_ptcache_validate(cache, 0);
477                 cache->last_exact= 0;
478                 cache->flag &= ~PTCACHE_REDO_NEEDED;
479                 return;
480         }
481         
482         // unused in the moment, calculated separately in implicit.c
483         clmd->sim_parms->dt = clmd->sim_parms->timescale / clmd->sim_parms->stepsPerFrame;
484
485         /* handle continuous simulation with the play button */
486         if ((clmd->sim_parms->preroll > 0) && (framenr > startframe - clmd->sim_parms->preroll) && (framenr < startframe)) {
487                 BKE_ptcache_invalidate(cache);
488
489                 /* do simulation */
490                 if (!do_init_cloth(ob, clmd, dm, framenr))
491                         return;
492
493                 do_step_cloth(ob, clmd, dm, framenr);
494                 cloth_to_object(ob, clmd, vertexCos);
495
496                 clmd->clothObject->last_frame= framenr;
497
498                 return;
499         }
500
501         /* simulation is only active during a specific period */
502         if (framenr < startframe) {
503                 BKE_ptcache_invalidate(cache);
504                 return;
505         }
506         else if (framenr > endframe) {
507                 framenr= endframe;
508         }
509
510         /* initialize simulation data if it didn't exist already */
511         if (!do_init_cloth(ob, clmd, dm, framenr))
512                 return;
513
514         if ((framenr == startframe) && (clmd->sim_parms->preroll == 0)) {
515                 BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
516                 do_init_cloth(ob, clmd, dm, framenr);
517                 BKE_ptcache_validate(cache, framenr);
518                 cache->flag &= ~PTCACHE_REDO_NEEDED;
519                 clmd->clothObject->last_frame= framenr;
520                 return;
521         }
522
523         /* try to read from cache */
524         cache_result = BKE_ptcache_read(&pid, (float)framenr+scene->r.subframe);
525
526         if (cache_result == PTCACHE_READ_EXACT || cache_result == PTCACHE_READ_INTERPOLATED) {
527                 implicit_set_positions(clmd);
528                 cloth_to_object (ob, clmd, vertexCos);
529
530                 BKE_ptcache_validate(cache, framenr);
531
532                 if (cache_result == PTCACHE_READ_INTERPOLATED && cache->flag & PTCACHE_REDO_NEEDED)
533                         BKE_ptcache_write(&pid, framenr);
534
535                 clmd->clothObject->last_frame= framenr;
536
537                 return;
538         }
539         else if (cache_result==PTCACHE_READ_OLD) {
540                 implicit_set_positions(clmd);
541         }
542         else if ( /*ob->id.lib ||*/ (cache->flag & PTCACHE_BAKED)) { /* 2.4x disabled lib, but this can be used in some cases, testing further - campbell */
543                 /* if baked and nothing in cache, do nothing */
544                 BKE_ptcache_invalidate(cache);
545                 return;
546         }
547
548         if (framenr!=clmd->clothObject->last_frame+1)
549                 return;
550
551         /* if on second frame, write cache for first frame */
552         if (cache->simframe == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact==0))
553                 BKE_ptcache_write(&pid, startframe);
554
555         clmd->sim_parms->timescale *= framenr - cache->simframe;
556
557         /* do simulation */
558         BKE_ptcache_validate(cache, framenr);
559
560         if (!do_step_cloth(ob, clmd, dm, framenr)) {
561                 BKE_ptcache_invalidate(cache);
562         }
563         else
564                 BKE_ptcache_write(&pid, framenr);
565
566         cloth_to_object (ob, clmd, vertexCos);
567         clmd->clothObject->last_frame= framenr;
568 }
569
570 /* frees all */
571 void cloth_free_modifier(ClothModifierData *clmd )
572 {
573         Cloth   *cloth = NULL;
574         
575         if ( !clmd )
576                 return;
577
578         cloth = clmd->clothObject;
579
580         
581         if ( cloth ) {
582                 // If our solver provides a free function, call it
583                 if ( solvers [clmd->sim_parms->solver_type].free ) {
584                         solvers [clmd->sim_parms->solver_type].free ( clmd );
585                 }
586
587                 // Free the verts.
588                 if ( cloth->verts != NULL )
589                         MEM_freeN ( cloth->verts );
590
591                 cloth->verts = NULL;
592                 cloth->numverts = 0;
593
594                 // Free the springs.
595                 if ( cloth->springs != NULL ) {
596                         LinkNode *search = cloth->springs;
597                         while (search) {
598                                 ClothSpring *spring = search->link;
599                                                 
600                                 MEM_freeN ( spring );
601                                 search = search->next;
602                         }
603                         BLI_linklist_free(cloth->springs, NULL);
604                 
605                         cloth->springs = NULL;
606                 }
607
608                 cloth->springs = NULL;
609                 cloth->numsprings = 0;
610
611                 // free BVH collision tree
612                 if ( cloth->bvhtree )
613                         BLI_bvhtree_free ( cloth->bvhtree );
614                 
615                 if ( cloth->bvhselftree )
616                         BLI_bvhtree_free ( cloth->bvhselftree );
617
618                 // we save our faces for collision objects
619                 if ( cloth->mfaces )
620                         MEM_freeN ( cloth->mfaces );
621                 
622                 if (cloth->edgehash)
623                         BLI_edgehash_free ( cloth->edgehash, NULL );
624                 
625                 
626                 /*
627                 if (clmd->clothObject->facemarks)
628                 MEM_freeN(clmd->clothObject->facemarks);
629                 */
630                 MEM_freeN ( cloth );
631                 clmd->clothObject = NULL;
632         }
633 }
634
635 /* frees all */
636 void cloth_free_modifier_extern(ClothModifierData *clmd )
637 {
638         Cloth   *cloth = NULL;
639         if (G.debug_value > 0)
640                 printf("cloth_free_modifier_extern\n");
641         
642         if ( !clmd )
643                 return;
644
645         cloth = clmd->clothObject;
646         
647         if ( cloth ) {
648                 if (G.debug_value > 0)
649                         printf("cloth_free_modifier_extern in\n");
650
651                 // If our solver provides a free function, call it
652                 if ( solvers [clmd->sim_parms->solver_type].free ) {
653                         solvers [clmd->sim_parms->solver_type].free ( clmd );
654                 }
655
656                 // Free the verts.
657                 if ( cloth->verts != NULL )
658                         MEM_freeN ( cloth->verts );
659
660                 cloth->verts = NULL;
661                 cloth->numverts = 0;
662
663                 // Free the springs.
664                 if ( cloth->springs != NULL ) {
665                         LinkNode *search = cloth->springs;
666                         while (search) {
667                                 ClothSpring *spring = search->link;
668
669                                 MEM_freeN ( spring );
670                                 search = search->next;
671                         }
672                         BLI_linklist_free(cloth->springs, NULL);
673
674                         cloth->springs = NULL;
675                 }
676
677                 cloth->springs = NULL;
678                 cloth->numsprings = 0;
679
680                 // free BVH collision tree
681                 if ( cloth->bvhtree )
682                         BLI_bvhtree_free ( cloth->bvhtree );
683                 
684                 if ( cloth->bvhselftree )
685                         BLI_bvhtree_free ( cloth->bvhselftree );
686
687                 // we save our faces for collision objects
688                 if ( cloth->mfaces )
689                         MEM_freeN ( cloth->mfaces );
690
691                 if (cloth->edgehash)
692                         BLI_edgehash_free ( cloth->edgehash, NULL );
693
694
695                 /*
696                 if (clmd->clothObject->facemarks)
697                 MEM_freeN(clmd->clothObject->facemarks);
698                 */
699                 MEM_freeN ( cloth );
700                 clmd->clothObject = NULL;
701         }
702 }
703
704 /******************************************************************************
705  *
706  * Internal functions.
707  *
708  ******************************************************************************/
709
710 /**
711  * cloth_to_object - copies the deformed vertices to the object.
712  *
713  **/
714 static void cloth_to_object (Object *ob,  ClothModifierData *clmd, float (*vertexCos)[3])
715 {
716         unsigned int    i = 0;
717         Cloth *cloth = clmd->clothObject;
718
719         if (clmd->clothObject) {
720                 /* inverse matrix is not uptodate... */
721                 invert_m4_m4(ob->imat, ob->obmat);
722
723                 for (i = 0; i < cloth->numverts; i++) {
724                         copy_v3_v3 (vertexCos[i], cloth->verts[i].x);
725                         mul_m4_v3(ob->imat, vertexCos[i]);      /* cloth is in global coords */
726                 }
727         }
728 }
729
730
731 int cloth_uses_vgroup(ClothModifierData *clmd)
732 {
733         return (((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING ) || 
734                 (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ) ||
735                 (clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF)) && 
736                 ((clmd->sim_parms->vgroup_mass>0) || 
737                 (clmd->sim_parms->vgroup_struct>0)||
738                 (clmd->sim_parms->vgroup_bend>0)  ||
739                 (clmd->coll_parms->vgroup_selfcol>0)));
740 }
741
742 /**
743  * cloth_apply_vgroup - applies a vertex group as specified by type
744  *
745  **/
746 /* can be optimized to do all groups in one loop */
747 static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm )
748 {
749         int i = 0;
750         int j = 0;
751         MDeformVert *dvert = NULL;
752         Cloth *clothObj = NULL;
753         int numverts;
754         /* float goalfac = 0; */ /* UNUSED */
755         ClothVertex *verts = NULL;
756
757         if (!clmd || !dm) return;
758
759         clothObj = clmd->clothObject;
760
761         numverts = dm->getNumVerts (dm);
762
763         verts = clothObj->verts;
764         
765         if (cloth_uses_vgroup(clmd)) {
766                 for ( i = 0; i < numverts; i++, verts++ ) {
767
768                         /* Reset Goal values to standard */
769                         if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
770                                 verts->goal= clmd->sim_parms->defgoal;
771                         else
772                                 verts->goal= 0.0f;
773
774                         /* Reset vertex flags */
775                         verts->flags &= ~CLOTH_VERT_FLAG_PINNED;
776                         verts->flags &= ~CLOTH_VERT_FLAG_NOSELFCOLL;
777
778                         dvert = dm->getVertData ( dm, i, CD_MDEFORMVERT );
779                         if ( dvert ) {
780                                 for ( j = 0; j < dvert->totweight; j++ ) {
781                                         if (( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_mass-1)) && (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )) {
782                                                 verts->goal = dvert->dw [j].weight;
783
784                                                 /* goalfac= 1.0f; */ /* UNUSED */
785                                                 
786                                                 /*
787                                                 // Kicking goal factor to simplify things...who uses that anyway?
788                                                 // ABS ( clmd->sim_parms->maxgoal - clmd->sim_parms->mingoal );
789                                                 */
790                                                 
791                                                 verts->goal  = powf(verts->goal, 4.0f);
792                                                 if ( verts->goal >= SOFTGOALSNAP )
793                                                          verts->flags |= CLOTH_VERT_FLAG_PINNED;
794                                         }
795                                         
796                                         if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING ) {
797                                                 if ( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_struct-1)) {
798                                                         verts->struct_stiff = dvert->dw [j].weight;
799                                                         verts->shear_stiff = dvert->dw [j].weight;
800                                                 }
801                                                 
802                                                 if ( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_bend-1)) {
803                                                         verts->bend_stiff = dvert->dw [j].weight;
804                                                 }
805                                         }
806
807                                         if (clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF ) {
808                                                 if ( dvert->dw[j].def_nr == (clmd->coll_parms->vgroup_selfcol-1)) {
809                                                         if (dvert->dw [j].weight > 0.0f) {
810                                                                 verts->flags |= CLOTH_VERT_FLAG_NOSELFCOLL;
811                                                         }
812                                                 }
813                                         }
814                                 }
815                         }
816                 }
817         }
818 }
819
820 static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *dm, float UNUSED(framenr), int first)
821 {
822         int i = 0;
823         MVert *mvert = NULL;
824         ClothVertex *verts = NULL;
825         float (*shapekey_rest)[3] = NULL;
826         float tnull[3] = {0, 0, 0};
827         Cloth *cloth = NULL;
828         float maxdist = 0;
829
830         // If we have a clothObject, free it. 
831         if ( clmd->clothObject != NULL ) {
832                 cloth_free_modifier ( clmd );
833                 if (G.debug_value > 0)
834                         printf("cloth_free_modifier cloth_from_object\n");
835         }
836
837         // Allocate a new cloth object.
838         clmd->clothObject = MEM_callocN ( sizeof ( Cloth ), "cloth" );
839         if ( clmd->clothObject ) {
840                 clmd->clothObject->old_solver_type = 255;
841                 // clmd->clothObject->old_collision_type = 255;
842                 cloth = clmd->clothObject;
843                 clmd->clothObject->edgehash = NULL;
844         }
845         else if (!clmd->clothObject) {
846                 modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject");
847                 return 0;
848         }
849
850         // mesh input objects need DerivedMesh
851         if ( !dm )
852                 return 0;
853
854         cloth_from_mesh ( clmd, dm );
855
856         // create springs
857         clmd->clothObject->springs = NULL;
858         clmd->clothObject->numsprings = -1;
859
860         if ( clmd->sim_parms->shapekey_rest )
861                 shapekey_rest = dm->getVertDataArray ( dm, CD_CLOTH_ORCO );
862
863         mvert = dm->getVertArray (dm);
864
865         verts = clmd->clothObject->verts;
866
867         // set initial values
868         for ( i = 0; i < dm->getNumVerts(dm); i++, verts++ ) {
869                 if (first) {
870                         copy_v3_v3(verts->x, mvert[i].co);
871
872                         mul_m4_v3(ob->obmat, verts->x);
873
874                         if ( shapekey_rest ) {
875                                 verts->xrest= shapekey_rest[i];
876                                 mul_m4_v3(ob->obmat, verts->xrest);
877                         }
878                         else
879                                 verts->xrest = verts->x;
880                 }
881                 
882                 /* no GUI interface yet */
883                 verts->mass = clmd->sim_parms->mass; 
884                 verts->impulse_count = 0;
885
886                 if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
887                         verts->goal= clmd->sim_parms->defgoal;
888                 else
889                         verts->goal= 0.0f;
890
891                 verts->flags = 0;
892                 copy_v3_v3 ( verts->xold, verts->x );
893                 copy_v3_v3 ( verts->xconst, verts->x );
894                 copy_v3_v3 ( verts->txold, verts->x );
895                 copy_v3_v3 ( verts->tx, verts->x );
896                 mul_v3_fl(verts->v, 0.0f);
897
898                 verts->impulse_count = 0;
899                 copy_v3_v3 ( verts->impulse, tnull );
900         }
901         
902         // apply / set vertex groups
903         // has to be happen before springs are build!
904         cloth_apply_vgroup (clmd, dm);
905
906         if ( !cloth_build_springs ( clmd, dm ) ) {
907                 cloth_free_modifier ( clmd );
908                 modifier_setError(&(clmd->modifier), "Cannot build springs");
909                 printf("cloth_free_modifier cloth_build_springs\n");
910                 return 0;
911         }
912         
913         for ( i = 0; i < dm->getNumVerts(dm); i++) {
914                 if ((!(cloth->verts[i].flags & CLOTH_VERT_FLAG_PINNED)) && (cloth->verts[i].goal > ALMOST_ZERO)) {
915                         cloth_add_spring (clmd, i, i, 0.0, CLOTH_SPRING_TYPE_GOAL);
916                 }
917         }
918         
919         // init our solver
920         if ( solvers [clmd->sim_parms->solver_type].init ) {
921                 solvers [clmd->sim_parms->solver_type].init ( ob, clmd );
922         }
923         
924         if (!first)
925                 implicit_set_positions(clmd);
926
927         clmd->clothObject->bvhtree = bvhtree_build_from_cloth ( clmd, MAX2(clmd->coll_parms->epsilon, clmd->coll_parms->distance_repel) );
928         
929         for (i = 0; i < dm->getNumVerts(dm); i++) {
930                 maxdist = MAX2(maxdist, clmd->coll_parms->selfepsilon* ( cloth->verts[i].avg_spring_len*2.0f));
931         }
932         
933         clmd->clothObject->bvhselftree = bvhselftree_build_from_cloth ( clmd, maxdist );
934
935         return 1;
936 }
937
938 static void cloth_from_mesh ( ClothModifierData *clmd, DerivedMesh *dm )
939 {
940         unsigned int numverts = dm->getNumVerts (dm);
941         unsigned int numfaces = dm->getNumTessFaces (dm);
942         MFace *mface = dm->getTessFaceArray(dm);
943         unsigned int i = 0;
944
945         /* Allocate our vertices. */
946         clmd->clothObject->numverts = numverts;
947         clmd->clothObject->verts = MEM_callocN ( sizeof ( ClothVertex ) * clmd->clothObject->numverts, "clothVertex" );
948         if ( clmd->clothObject->verts == NULL ) {
949                 cloth_free_modifier ( clmd );
950                 modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject->verts");
951                 printf("cloth_free_modifier clmd->clothObject->verts\n");
952                 return;
953         }
954
955         // save face information
956         clmd->clothObject->numfaces = numfaces;
957         clmd->clothObject->mfaces = MEM_callocN ( sizeof ( MFace ) * clmd->clothObject->numfaces, "clothMFaces" );
958         if ( clmd->clothObject->mfaces == NULL ) {
959                 cloth_free_modifier ( clmd );
960                 modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject->mfaces");
961                 printf("cloth_free_modifier clmd->clothObject->mfaces\n");
962                 return;
963         }
964         for ( i = 0; i < numfaces; i++ )
965                 memcpy ( &clmd->clothObject->mfaces[i], &mface[i], sizeof ( MFace ) );
966
967         /* Free the springs since they can't be correct if the vertices
968          * changed.
969          */
970         if ( clmd->clothObject->springs != NULL )
971                 MEM_freeN ( clmd->clothObject->springs );
972
973 }
974
975 /***************************************************************************************
976  * SPRING NETWORK BUILDING IMPLEMENTATION BEGIN
977  ***************************************************************************************/
978
979 // be careful: implicit solver has to be resettet when using this one!
980 // --> only for implicit handling of this spring!
981 int cloth_add_spring(ClothModifierData *clmd, unsigned int indexA, unsigned int indexB, float restlength, int spring_type)
982 {
983         Cloth *cloth = clmd->clothObject;
984         ClothSpring *spring = NULL;
985         
986         if (cloth) {
987                 // TODO: look if this spring is already there
988                 
989                 spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
990                 
991                 if (!spring)
992                         return 0;
993                 
994                 spring->ij = indexA;
995                 spring->kl = indexB;
996                 spring->restlen =  restlength;
997                 spring->type = spring_type;
998                 spring->flags = 0;
999                 spring->stiffness = 0;
1000                 
1001                 cloth->numsprings++;
1002         
1003                 BLI_linklist_prepend ( &cloth->springs, spring );
1004                 
1005                 return 1;
1006         }
1007         return 0;
1008 }
1009
1010 static void cloth_free_errorsprings(Cloth *cloth, EdgeHash *UNUSED(edgehash), LinkNode **edgelist)
1011 {
1012         unsigned int i = 0;
1013         
1014         if ( cloth->springs != NULL ) {
1015                 LinkNode *search = cloth->springs;
1016                 while (search) {
1017                         ClothSpring *spring = search->link;
1018                                                 
1019                         MEM_freeN ( spring );
1020                         search = search->next;
1021                 }
1022                 BLI_linklist_free(cloth->springs, NULL);
1023                 
1024                 cloth->springs = NULL;
1025         }
1026         
1027         if (edgelist) {
1028                 for ( i = 0; i < cloth->numverts; i++ ) {
1029                         BLI_linklist_free ( edgelist[i], NULL );
1030                 }
1031
1032                 MEM_freeN ( edgelist );
1033         }
1034         
1035         if (cloth->edgehash)
1036                 BLI_edgehash_free ( cloth->edgehash, NULL );
1037 }
1038
1039 /* update stiffness if vertex group values are changing from frame to frame */
1040 static void cloth_update_springs( ClothModifierData *clmd )
1041 {
1042         Cloth *cloth = clmd->clothObject;
1043         LinkNode *search = NULL;
1044
1045         search = cloth->springs;
1046         while (search) {
1047                 ClothSpring *spring = search->link;
1048
1049                 spring->stiffness = 0.0f;
1050
1051                 if (spring->type == CLOTH_SPRING_TYPE_STRUCTURAL) {
1052                         spring->stiffness = (cloth->verts[spring->kl].struct_stiff + cloth->verts[spring->ij].struct_stiff) / 2.0f;
1053                 }
1054                 else if (spring->type == CLOTH_SPRING_TYPE_SHEAR) {
1055                         spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0f;
1056                 }
1057                 else if (spring->type == CLOTH_SPRING_TYPE_BENDING) {
1058                         spring->stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1059                 }
1060                 else if (spring->type == CLOTH_SPRING_TYPE_GOAL) {
1061                         /* Warning: Appending NEW goal springs does not work because implicit solver would need reset! */
1062
1063                         /* Activate / Deactivate existing springs */
1064                         if ((!(cloth->verts[spring->ij].flags & CLOTH_VERT_FLAG_PINNED)) &&
1065                             (cloth->verts[spring->ij].goal > ALMOST_ZERO))
1066                         {
1067                                 spring->flags &= ~CLOTH_SPRING_FLAG_DEACTIVATE;
1068                         }
1069                         else {
1070                                 spring->flags |= CLOTH_SPRING_FLAG_DEACTIVATE;
1071                         }
1072                 }
1073                 
1074                 search = search->next;
1075         }
1076
1077
1078 }
1079
1080 static int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm )
1081 {
1082         Cloth *cloth = clmd->clothObject;
1083         ClothSpring *spring = NULL, *tspring = NULL, *tspring2 = NULL;
1084         unsigned int struct_springs = 0, shear_springs=0, bend_springs = 0;
1085         unsigned int i = 0;
1086         unsigned int numverts = (unsigned int)dm->getNumVerts (dm);
1087         unsigned int numedges = (unsigned int)dm->getNumEdges (dm);
1088         unsigned int numfaces = (unsigned int)dm->getNumTessFaces (dm);
1089         MEdge *medge = dm->getEdgeArray (dm);
1090         MFace *mface = dm->getTessFaceArray (dm);
1091         int index2 = 0; // our second vertex index
1092         LinkNode **edgelist = NULL;
1093         EdgeHash *edgehash = NULL;
1094         LinkNode *search = NULL, *search2 = NULL;
1095         
1096         // error handling
1097         if ( numedges==0 )
1098                 return 0;
1099
1100         cloth->springs = NULL;
1101
1102         edgelist = MEM_callocN ( sizeof (LinkNode *) * numverts, "cloth_edgelist_alloc" );
1103         
1104         if (!edgelist)
1105                 return 0;
1106         
1107         for ( i = 0; i < numverts; i++ ) {
1108                 edgelist[i] = NULL;
1109         }
1110
1111         if ( cloth->springs )
1112                 MEM_freeN ( cloth->springs );
1113
1114         // create spring network hash
1115         edgehash = BLI_edgehash_new();
1116
1117         // structural springs
1118         for ( i = 0; i < numedges; i++ ) {
1119                 spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1120
1121                 if ( spring ) {
1122                         spring->ij = MIN2(medge[i].v1, medge[i].v2);
1123                         spring->kl = MAX2(medge[i].v2, medge[i].v1);
1124                         spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest);
1125                         clmd->sim_parms->avg_spring_len += spring->restlen;
1126                         cloth->verts[spring->ij].avg_spring_len += spring->restlen;
1127                         cloth->verts[spring->kl].avg_spring_len += spring->restlen;
1128                         cloth->verts[spring->ij].spring_count++;
1129                         cloth->verts[spring->kl].spring_count++;
1130                         spring->type = CLOTH_SPRING_TYPE_STRUCTURAL;
1131                         spring->flags = 0;
1132                         spring->stiffness = (cloth->verts[spring->kl].struct_stiff + cloth->verts[spring->ij].struct_stiff) / 2.0f;
1133                         struct_springs++;
1134                         
1135                         BLI_linklist_prepend ( &cloth->springs, spring );
1136                 }
1137                 else {
1138                         cloth_free_errorsprings(cloth, edgehash, edgelist);
1139                         return 0;
1140                 }
1141         }
1142         
1143         if (struct_springs > 0)
1144                 clmd->sim_parms->avg_spring_len /= struct_springs;
1145         
1146         for (i = 0; i < numverts; i++) {
1147                 cloth->verts[i].avg_spring_len = cloth->verts[i].avg_spring_len * 0.49f / ((float)cloth->verts[i].spring_count);
1148         }
1149
1150         // shear springs
1151         for ( i = 0; i < numfaces; i++ ) {
1152                 // triangle faces already have shear springs due to structural geometry
1153                 if ( !mface[i].v4 )
1154                         continue;
1155
1156                 spring = (ClothSpring *)MEM_callocN(sizeof(ClothSpring), "cloth spring");
1157                 
1158                 if (!spring) {
1159                         cloth_free_errorsprings(cloth, edgehash, edgelist);
1160                         return 0;
1161                 }
1162
1163                 spring->ij = MIN2(mface[i].v1, mface[i].v3);
1164                 spring->kl = MAX2(mface[i].v3, mface[i].v1);
1165                 spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest);
1166                 spring->type = CLOTH_SPRING_TYPE_SHEAR;
1167                 spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0f;
1168
1169                 BLI_linklist_append ( &edgelist[spring->ij], spring );
1170                 BLI_linklist_append ( &edgelist[spring->kl], spring );
1171                 shear_springs++;
1172
1173                 BLI_linklist_prepend ( &cloth->springs, spring );
1174
1175                 
1176                 // if ( mface[i].v4 ) --> Quad face
1177                 spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1178                 
1179                 if (!spring) {
1180                         cloth_free_errorsprings(cloth, edgehash, edgelist);
1181                         return 0;
1182                 }
1183
1184                 spring->ij = MIN2(mface[i].v2, mface[i].v4);
1185                 spring->kl = MAX2(mface[i].v4, mface[i].v2);
1186                 spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest);
1187                 spring->type = CLOTH_SPRING_TYPE_SHEAR;
1188                 spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0f;
1189
1190                 BLI_linklist_append ( &edgelist[spring->ij], spring );
1191                 BLI_linklist_append ( &edgelist[spring->kl], spring );
1192                 shear_springs++;
1193
1194                 BLI_linklist_prepend ( &cloth->springs, spring );
1195         }
1196
1197         if (numfaces) {
1198                 // bending springs
1199                 search2 = cloth->springs;
1200                 for ( i = struct_springs; i < struct_springs+shear_springs; i++ ) {
1201                         if ( !search2 )
1202                                 break;
1203
1204                         tspring2 = search2->link;
1205                         search = edgelist[tspring2->kl];
1206                         while ( search ) {
1207                                 tspring = search->link;
1208                                 index2 = ( ( tspring->ij==tspring2->kl ) ? ( tspring->kl ) : ( tspring->ij ) );
1209
1210                                 // check for existing spring
1211                                 // check also if startpoint is equal to endpoint
1212                                 if (!BLI_edgehash_haskey(edgehash, MIN2(tspring2->ij, index2), MAX2(tspring2->ij, index2)) &&
1213                                     (index2 != tspring2->ij))
1214                                 {
1215                                         spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1216
1217                                         if (!spring) {
1218                                                 cloth_free_errorsprings(cloth, edgehash, edgelist);
1219                                                 return 0;
1220                                         }
1221
1222                                         spring->ij = MIN2(tspring2->ij, index2);
1223                                         spring->kl = MAX2(tspring2->ij, index2);
1224                                         spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest);
1225                                         spring->type = CLOTH_SPRING_TYPE_BENDING;
1226                                         spring->stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1227                                         BLI_edgehash_insert(edgehash, spring->ij, spring->kl, NULL);
1228                                         bend_springs++;
1229
1230                                         BLI_linklist_prepend ( &cloth->springs, spring );
1231                                 }
1232                                 search = search->next;
1233                         }
1234                         search2 = search2->next;
1235                 }
1236         }
1237         else if (struct_springs > 2) {
1238                 /* bending springs for hair strands */
1239                 /* The current algorightm only goes through the edges in order of the mesh edges list   */
1240                 /* and makes springs between the outer vert of edges sharing a vertice. This works just */
1241                 /* fine for hair, but not for user generated string meshes. This could/should be later  */
1242                 /* extended to work with non-ordered edges so that it can be used for general "rope             */
1243                 /* dynamics" without the need for the vertices or edges to be ordered through the length*/
1244                 /* of the strands. -jahka */
1245                 search = cloth->springs;
1246                 search2 = search->next;
1247                 while (search && search2) {
1248                         tspring = search->link;
1249                         tspring2 = search2->link;
1250
1251                         if (tspring->ij == tspring2->kl) {
1252                                 spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1253                                 
1254                                 if (!spring) {
1255                                         cloth_free_errorsprings(cloth, edgehash, edgelist);
1256                                         return 0;
1257                                 }
1258
1259                                 spring->ij = tspring2->ij;
1260                                 spring->kl = tspring->kl;
1261                                 spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest);
1262                                 spring->type = CLOTH_SPRING_TYPE_BENDING;
1263                                 spring->stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1264                                 bend_springs++;
1265
1266                                 BLI_linklist_prepend ( &cloth->springs, spring );
1267                         }
1268                         
1269                         search = search->next;
1270                         search2 = search2->next;
1271                 }
1272         }
1273         
1274         /* insert other near springs in edgehash AFTER bending springs are calculated (for selfcolls) */
1275         for (i = 0; i < numedges; i++) { /* struct springs */
1276                 BLI_edgehash_insert(edgehash, MIN2(medge[i].v1, medge[i].v2), MAX2(medge[i].v2, medge[i].v1), NULL);
1277         }
1278
1279         for (i = 0; i < numfaces; i++) { /* edge springs */
1280                 if (mface[i].v4) {
1281                         BLI_edgehash_insert(edgehash, MIN2(mface[i].v1, mface[i].v3), MAX2(mface[i].v3, mface[i].v1), NULL);
1282                         
1283                         BLI_edgehash_insert(edgehash, MIN2(mface[i].v2, mface[i].v4), MAX2(mface[i].v2, mface[i].v4), NULL);
1284                 }
1285         }
1286         
1287         
1288         cloth->numsprings = struct_springs + shear_springs + bend_springs;
1289         
1290         if ( edgelist ) {
1291                 for ( i = 0; i < numverts; i++ ) {
1292                         BLI_linklist_free ( edgelist[i], NULL );
1293                 }
1294         
1295                 MEM_freeN ( edgelist );
1296         }
1297         
1298         cloth->edgehash = edgehash;
1299         
1300         if (G.debug_value > 0)
1301                 printf("avg_len: %f\n", clmd->sim_parms->avg_spring_len);
1302
1303         return 1;
1304
1305 } /* cloth_build_springs */
1306 /***************************************************************************************
1307  * SPRING NETWORK BUILDING IMPLEMENTATION END
1308  ***************************************************************************************/
1309