makes bullet independant from gameengine for cmake, introduces esc-key during sim...
[blender.git] / source / blender / blenkernel / intern / cloth.c
1 /*  cloth.c
2 *
3 *
4 * ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version. The Blender
10 * Foundation also sells licenses for use in proprietary software under
11 * the Blender License.  See http://www.blender.org/BL/ for information
12 * about this.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software Foundation,
21 * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22 *
23 * The Original Code is Copyright (C) Blender Foundation
24 * All rights reserved.
25 *
26 * The Original Code is: all of this file.
27 *
28 * Contributor(s): none yet.
29 *
30 * ***** END GPL/BL DUAL LICENSE BLOCK *****
31 */
32
33
34 #include <math.h>
35 #include <stdlib.h>
36 #include <string.h>
37
38 #include "MEM_guardedalloc.h"
39
40 /* types */
41 #include "DNA_curve_types.h"
42 #include "DNA_object_types.h"
43 #include "DNA_object_force.h"
44 #include "DNA_cloth_types.h"
45 #include "DNA_key_types.h"
46 #include "DNA_mesh_types.h"
47 #include "DNA_meshdata_types.h"
48 #include "DNA_lattice_types.h"
49 #include "DNA_scene_types.h"
50 #include "DNA_modifier_types.h"
51
52 #include "BLI_blenlib.h"
53 #include "BLI_arithb.h"
54 #include "BLI_edgehash.h"
55 #include "BLI_linklist.h"
56
57 #include "BKE_curve.h"
58 #include "BKE_deform.h"
59 #include "BKE_DerivedMesh.h"
60 #include "BKE_cdderivedmesh.h"
61 #include "BKE_displist.h"
62 #include "BKE_effect.h"
63 #include "BKE_global.h"
64 #include "BKE_key.h"
65 #include "BKE_mesh.h"
66 #include "BKE_object.h"
67 #include "BKE_cloth.h"
68 #include "BKE_modifier.h"
69 #include "BKE_utildefines.h"
70 #include "BKE_DerivedMesh.h"
71 #include "BIF_editdeform.h"
72 #include "BIF_editkey.h"
73 #include "DNA_screen_types.h"
74 #include "BSE_headerbuttons.h"
75 #include "BIF_screen.h"
76 #include "BIF_space.h"
77 #include "mydevice.h"
78
79 #include "BKE_pointcache.h"
80
81 #ifdef _WIN32
82 void tstart ( void )
83 {}
84 void tend ( void )
85 {
86 }
87 double tval()
88 {
89         return 0;
90 }
91 #else
92 #include <sys/time.h>
93                          static struct timeval _tstart, _tend;
94          static struct timezone tz;
95          void tstart ( void )
96 {
97         gettimeofday ( &_tstart, &tz );
98 }
99 void tend ( void )
100 {
101         gettimeofday ( &_tend,&tz );
102 }
103 double tval()
104 {
105         double t1, t2;
106         t1 = ( double ) _tstart.tv_sec + ( double ) _tstart.tv_usec/ ( 1000*1000 );
107         t2 = ( double ) _tend.tv_sec + ( double ) _tend.tv_usec/ ( 1000*1000 );
108         return t2-t1;
109 }
110 #endif
111
112 /* Our available solvers. */
113 // 255 is the magic reserved number, so NEVER try to put 255 solvers in here!
114 // 254 = MAX!
115 static CM_SOLVER_DEF    solvers [] =
116 {
117         { "Implicit", CM_IMPLICIT, implicit_init, implicit_solver, implicit_free },
118         // { "Implicit C++", CM_IMPLICITCPP, implicitcpp_init, implicitcpp_solver, implicitcpp_free },
119 };
120
121 /* ********** cloth engine ******* */
122 /* Prototypes for internal functions.
123 */
124 static void cloth_to_object (Object *ob,  ClothModifierData *clmd, DerivedMesh *dm);
125 static void cloth_from_mesh ( Object *ob, ClothModifierData *clmd, DerivedMesh *dm );
126 static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *dm, float framenr);
127 int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm );
128 static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm );
129
130
131 /******************************************************************************
132 *
133 * External interface called by modifier.c clothModifier functions.
134 *
135 ******************************************************************************/
136 /**
137  * cloth_init -  creates a new cloth simulation.
138  *
139  * 1. create object
140  * 2. fill object with standard values or with the GUI settings if given
141  */
142 void cloth_init ( ClothModifierData *clmd )
143 {       
144         /* Initialize our new data structure to reasonable values. */
145         clmd->sim_parms->gravity [0] = 0.0;
146         clmd->sim_parms->gravity [1] = 0.0;
147         clmd->sim_parms->gravity [2] = -9.81;
148         clmd->sim_parms->structural = 30.0;
149         clmd->sim_parms->shear = 30.0;
150         clmd->sim_parms->bending = 1.0;
151         clmd->sim_parms->Cdis = 5.0;
152         clmd->sim_parms->Cvi = 1.0;
153         clmd->sim_parms->mass = 1.0f;
154         clmd->sim_parms->stepsPerFrame = 5;
155         clmd->sim_parms->sim_time = 1.0;
156         clmd->sim_parms->flags = 0;
157         clmd->sim_parms->solver_type = 0;
158         clmd->sim_parms->preroll = 0;
159         clmd->sim_parms->maxspringlen = 10;
160         clmd->sim_parms->firstframe = 1;
161         clmd->sim_parms->lastframe = 250;
162         clmd->sim_parms->vgroup_mass = 0;
163         clmd->sim_parms->lastcachedframe = 0;
164         clmd->sim_parms->editedframe = 0;
165         clmd->sim_parms->autoprotect = 25;
166         clmd->sim_parms->firstcachedframe = -1.0;
167         
168         clmd->coll_parms->self_friction = 5.0;
169         clmd->coll_parms->friction = 10.0;
170         clmd->coll_parms->loop_count = 3;
171         clmd->coll_parms->epsilon = 0.015f;
172         clmd->coll_parms->flags = CLOTH_COLLSETTINGS_FLAG_ENABLED;
173
174         /* These defaults are copied from softbody.c's
175         * softbody_calc_forces() function.
176         */
177         clmd->sim_parms->eff_force_scale = 1000.0;
178         clmd->sim_parms->eff_wind_scale = 250.0;
179
180         // also from softbodies
181         clmd->sim_parms->maxgoal = 1.0f;
182         clmd->sim_parms->mingoal = 0.0f;
183         clmd->sim_parms->defgoal = 0.0f;
184         clmd->sim_parms->goalspring = 100.0f;
185         clmd->sim_parms->goalfrict = 0.0f;
186 }
187
188
189 BVH *bvh_build_from_cloth (ClothModifierData *clmd, float epsilon)
190 {
191         unsigned int i = 0;
192         BVH     *bvh=NULL;
193         Cloth *cloth = clmd->clothObject;
194         ClothVertex *verts = NULL;
195
196         if(!clmd)
197                 return NULL;
198
199         cloth = clmd->clothObject;
200
201         if(!cloth)
202                 return NULL;
203         
204         verts = cloth->verts;
205         
206         bvh = MEM_callocN(sizeof(BVH), "BVH");
207         if (bvh == NULL) 
208         {
209                 printf("bvh: Out of memory.\n");
210                 return NULL;
211         }
212         
213         // springs = cloth->springs;
214         // numsprings = cloth->numsprings;
215         
216         bvh->flags = 0;
217         bvh->leaf_tree = NULL;
218         bvh->leaf_root = NULL;
219         bvh->tree = NULL;
220
221         bvh->epsilon = epsilon;
222         bvh->numfaces = cloth->numfaces;
223         bvh->mfaces = cloth->mfaces;
224
225         bvh->numverts = cloth->numverts;
226         
227         bvh->current_x = MEM_callocN ( sizeof ( MVert ) * bvh->numverts, "bvh->current_x" );
228         bvh->current_xold = MEM_callocN ( sizeof ( MVert ) * bvh->numverts, "bvh->current_xold" );
229         
230         for(i = 0; i < bvh->numverts; i++)
231         {
232                 VECCOPY(bvh->current_x[i].co, verts[i].tx);
233                 VECCOPY(bvh->current_xold[i].co, verts[i].txold);
234         }
235         
236         bvh_build (bvh);
237         
238         return bvh;
239 }
240
241 void bvh_update_from_cloth(ClothModifierData *clmd, int moving)
242 {
243         unsigned int i = 0;
244         Cloth *cloth = clmd->clothObject;
245         BVH *bvh = cloth->tree;
246         ClothVertex *verts = cloth->verts;
247         
248         if(!bvh)
249                 return;
250         
251         if(cloth->numverts!=bvh->numverts)
252                 return;
253         
254         if(cloth->verts)
255         {
256                 for(i = 0; i < bvh->numverts; i++)
257                 {
258                         VECCOPY(bvh->current_x[i].co, verts[i].tx);
259                         VECCOPY(bvh->current_xold[i].co, verts[i].txold);
260                 }
261         }
262         
263         bvh_update(bvh, moving);
264 }
265
266 // unused in the moment, cloth needs quads from mesh
267 DerivedMesh *CDDM_convert_to_triangle ( DerivedMesh *dm )
268 {
269         DerivedMesh *result = NULL;
270         int i;
271         int numverts = dm->getNumVerts ( dm );
272         int numedges = dm->getNumEdges ( dm );
273         int numfaces = dm->getNumFaces ( dm );
274
275         MVert *mvert = CDDM_get_verts ( dm );
276         MEdge *medge = CDDM_get_edges ( dm );
277         MFace *mface = CDDM_get_faces ( dm );
278
279         MVert *mvert2;
280         MFace *mface2;
281         unsigned int numtris=0;
282         unsigned int numquads=0;
283         int a = 0;
284         int random = 0;
285         int firsttime = 0;
286         float vec1[3], vec2[3], vec3[3], vec4[3], vec5[3];
287         float mag1=0, mag2=0;
288
289         for ( i = 0; i < numfaces; i++ )
290         {
291                 if ( mface[i].v4 )
292                         numquads++;
293                 else
294                         numtris++;
295         }
296
297         result = CDDM_from_template ( dm, numverts, 0, numtris + 2*numquads );
298
299         if ( !result )
300                 return NULL;
301
302         // do verts
303         mvert2 = CDDM_get_verts ( result );
304         for ( a=0; a<numverts; a++ )
305         {
306                 MVert *inMV;
307                 MVert *mv = &mvert2[a];
308
309                 inMV = &mvert[a];
310
311                 DM_copy_vert_data ( dm, result, a, a, 1 );
312                 *mv = *inMV;
313         }
314
315
316         // do faces
317         mface2 = CDDM_get_faces ( result );
318         for ( a=0, i=0; a<numfaces; a++ )
319         {
320                 MFace *mf = &mface2[i];
321                 MFace *inMF;
322                 inMF = &mface[a];
323
324                 /*
325                 DM_copy_face_data(dm, result, a, i, 1);
326
327                 *mf = *inMF;
328                 */
329
330                 if ( mface[a].v4 && random==1 )
331                 {
332                         mf->v1 = mface[a].v2;
333                         mf->v2 = mface[a].v3;
334                         mf->v3 = mface[a].v4;
335                 }
336                 else
337                 {
338                         mf->v1 = mface[a].v1;
339                         mf->v2 = mface[a].v2;
340                         mf->v3 = mface[a].v3;
341                 }
342
343                 mf->v4 = 0;
344                 mf->flag |= ME_SMOOTH;
345
346                 test_index_face ( mf, NULL, 0, 3 );
347
348                 if ( mface[a].v4 )
349                 {
350                         MFace *mf2;
351
352                         i++;
353
354                         mf2 = &mface2[i];
355                         /*
356                         DM_copy_face_data(dm, result, a, i, 1);
357
358                         *mf2 = *inMF;
359                         */
360
361                         if ( random==1 )
362                         {
363                                 mf2->v1 = mface[a].v1;
364                                 mf2->v2 = mface[a].v2;
365                                 mf2->v3 = mface[a].v4;
366                         }
367                         else
368                         {
369                                 mf2->v1 = mface[a].v4;
370                                 mf2->v2 = mface[a].v1;
371                                 mf2->v3 = mface[a].v3;
372                         }
373                         mf2->v4 = 0;
374                         mf2->flag |= ME_SMOOTH;
375
376                         test_index_face ( mf2, NULL, 0, 3 );
377                 }
378
379                 i++;
380         }
381
382         CDDM_calc_edges ( result );
383         CDDM_calc_normals ( result );
384
385         return result;
386
387 }
388
389
390 DerivedMesh *CDDM_create_tearing ( ClothModifierData *clmd, DerivedMesh *dm )
391 {
392         DerivedMesh *result = NULL;
393         unsigned int i = 0, a = 0, j=0;
394         int numverts = dm->getNumVerts ( dm );
395         int numedges = dm->getNumEdges ( dm );
396         int numfaces = dm->getNumFaces ( dm );
397
398         MVert *mvert = CDDM_get_verts ( dm );
399         MEdge *medge = CDDM_get_edges ( dm );
400         MFace *mface = CDDM_get_faces ( dm );
401
402         MVert *mvert2;
403         MFace *mface2;
404         unsigned int numtris=0;
405         unsigned int numquads=0;
406         EdgeHash *edgehash = NULL;
407         Cloth *cloth = clmd->clothObject;
408         ClothSpring *springs = cloth->springs;
409         unsigned int numsprings = cloth->numsprings;
410
411         // create spring tearing hash
412         edgehash = BLI_edgehash_new();
413
414         for ( i = 0; i < numsprings; i++ )
415         {
416                 if ( ( springs[i].flags & CLOTH_SPRING_FLAG_DEACTIVATE )
417                                      && ( !BLI_edgehash_haskey ( edgehash, springs[i].ij, springs[i].kl ) ) )
418                 {
419                         BLI_edgehash_insert ( edgehash, springs[i].ij, springs[i].kl, NULL );
420                         BLI_edgehash_insert ( edgehash, springs[i].kl, springs[i].ij, NULL );
421                         j++;
422                 }
423         }
424
425         // printf("found %d tears\n", j);
426
427         result = CDDM_from_template ( dm, numverts, 0, numfaces );
428
429         if ( !result )
430                 return NULL;
431
432         // do verts
433         mvert2 = CDDM_get_verts ( result );
434         for ( a=0; a<numverts; a++ )
435         {
436                 MVert *inMV;
437                 MVert *mv = &mvert2[a];
438
439                 inMV = &mvert[a];
440
441                 DM_copy_vert_data ( dm, result, a, a, 1 );
442                 *mv = *inMV;
443         }
444
445
446         // do faces
447         mface2 = CDDM_get_faces ( result );
448         for ( a=0, i=0; a<numfaces; a++ )
449         {
450                 MFace *mf = &mface2[i];
451                 MFace *inMF;
452                 inMF = &mface[a];
453
454                 /*
455                 DM_copy_face_data(dm, result, a, i, 1);
456
457                 *mf = *inMF;
458                 */
459
460                 if ( ( !BLI_edgehash_haskey ( edgehash, mface[a].v1, mface[a].v2 ) )
461                                       && ( !BLI_edgehash_haskey ( edgehash, mface[a].v2, mface[a].v3 ) )
462                                       && ( !BLI_edgehash_haskey ( edgehash, mface[a].v3, mface[a].v4 ) )
463                                       && ( !BLI_edgehash_haskey ( edgehash, mface[a].v4, mface[a].v1 ) ) )
464                 {
465                         mf->v1 = mface[a].v1;
466                         mf->v2 = mface[a].v2;
467                         mf->v3 = mface[a].v3;
468                         mf->v4 = mface[a].v4;
469
470                         test_index_face ( mf, NULL, 0, 4 );
471
472                         i++;
473                 }
474         }
475
476         CDDM_lower_num_faces ( result, i );
477         CDDM_calc_edges ( result );
478         CDDM_calc_normals ( result );
479
480         BLI_edgehash_free ( edgehash, NULL );
481
482         return result;
483 }
484
485 int modifiers_indexInObject(Object *ob, ModifierData *md_seek);
486
487 int cloth_read_cache(Object *ob, ClothModifierData *clmd, float framenr)
488 {
489         FILE *fp = NULL;
490         int stack_index = -1;
491         unsigned int a, ret = 1;
492         Cloth *cloth = clmd->clothObject;
493         
494         if(!cloth)
495                 return 0;
496         
497         stack_index = modifiers_indexInObject(ob, (ModifierData *)clmd);
498         
499         fp = BKE_ptcache_id_fopen((ID *)ob, 'r', framenr, stack_index);
500         if(!fp)
501                 ret = 0;
502         else {
503                 for(a = 0; a < cloth->numverts; a++)
504                 {
505                         if(fread(&cloth->verts[a].x, sizeof(float), 3, fp) != 3) 
506                         {
507                                 ret = 0;
508                                 break;
509                         }
510                         if(fread(&cloth->verts[a].xconst, sizeof(float), 3, fp) != 3) 
511                         {
512                                 ret = 0;
513                                 break;
514                         }
515                         if(fread(&cloth->verts[a].v, sizeof(float), 3, fp) != 3) 
516                         {
517                                 ret = 0;
518                                 break;
519                         }
520                 }
521                 
522                 fclose(fp);
523                 
524                 if(clmd->sim_parms->lastcachedframe < framenr)
525                 {
526                         if(G.rt > 0)
527                                 printf("cloth_read_cache problem: lnex - f#: %f, lastCF: %d\n", framenr, clmd->sim_parms->lastcachedframe);
528                 }
529         }
530         
531         if(G.rt > 0)
532                 printf("cloth_read_cache: %f\n", framenr);
533         
534         return ret;
535 }
536
537 void cloth_clear_cache(Object *ob, ClothModifierData *clmd, float framenr)
538 {
539         int stack_index = -1;
540         
541         // don't do anything as long as we're in editmode!
542         if(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_EDITMODE)
543         {
544                 /* delete cache free request */
545                 clmd->sim_parms->flags &= ~CLOTH_SIMSETTINGS_FLAG_CCACHE_FFREE;
546                 
547                 return;
548         }
549         
550         /* clear cache if specific frame cleaning requested or cache is not protected */
551         if((!(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_CCACHE_PROTECT)) || (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_CCACHE_FFREE))
552         {
553                 stack_index = modifiers_indexInObject(ob, (ModifierData *)clmd);
554                 
555                 BKE_ptcache_id_clear((ID *)ob, PTCACHE_CLEAR_AFTER, framenr, stack_index);
556                 
557                 /* update last cached frame # */
558                 clmd->sim_parms->lastcachedframe = framenr;
559                 
560                 /* update first cached frame # */
561                 if((framenr < clmd->sim_parms->firstcachedframe) && (clmd->sim_parms->firstcachedframe >=0.0))
562                         clmd->sim_parms->firstcachedframe = -1.0;
563                 
564                 if(G.rt > 0)
565                         printf("cloth_clear_cache: %f\n", framenr);
566         }
567         
568         /* delete cache free request */
569         clmd->sim_parms->flags &= ~CLOTH_SIMSETTINGS_FLAG_CCACHE_FFREE;
570         
571         
572 }
573 void cloth_write_cache(Object *ob, ClothModifierData *clmd, float framenr)
574 {
575         FILE *fp = NULL;
576         int stack_index = -1;
577         unsigned int a;
578         Cloth *cloth = clmd->clothObject;
579         
580         if(G.rt > 0)
581                 printf("cloth_write_cache: %f\n", framenr);
582         
583         if(!cloth)
584         {
585                 if(G.rt > 0)
586                         printf("cloth_write_cache: no cloth\n");
587                 return;
588         }
589         
590         stack_index = modifiers_indexInObject(ob, (ModifierData *)clmd);
591         
592         fp = BKE_ptcache_id_fopen((ID *)ob, 'w', framenr, stack_index);
593         if(!fp)
594         {
595                 if(G.rt > 0)
596                         printf("cloth_write_cache: no fp\n");
597                 return;
598         }
599         
600         for(a = 0; a < cloth->numverts; a++)
601         {
602                 fwrite(&cloth->verts[a].x, sizeof(float),3,fp);
603                 fwrite(&cloth->verts[a].xconst, sizeof(float),3,fp);
604                 fwrite(&cloth->verts[a].v, sizeof(float),3,fp);
605         }
606         
607         /* update last cached frame # */
608         clmd->sim_parms->lastcachedframe = MAX2(clmd->sim_parms->lastcachedframe, framenr);
609         
610         /* update first cached frame # */
611         if((clmd->sim_parms->firstcachedframe < 0.0) || ((framenr < clmd->sim_parms->firstcachedframe) && (clmd->sim_parms->firstcachedframe > 0.0)))
612                 clmd->sim_parms->firstcachedframe = framenr;
613         
614         if(G.rt > 0)
615                 printf("lcf: %d, framenr: %f\n", clmd->sim_parms->lastcachedframe, framenr);
616
617         fclose(fp);
618 }
619
620
621
622 /************************************************
623  * clothModifier_do - main simulation function
624 ************************************************/
625 DerivedMesh *clothModifier_do(ClothModifierData *clmd,Object *ob, DerivedMesh *dm, int useRenderParams, int isFinalCalc)
626
627 {
628         unsigned int i;
629         Cloth *cloth = clmd->clothObject;
630         float framenr = G.scene->r.cfra;
631         float current_time = bsystem_time ( ob, ( float ) G.scene->r.cfra, 0.0 );
632         ListBase *effectors = NULL;
633         ClothVertex *verts = NULL;
634         float deltaTime = current_time - clmd->sim_parms->sim_time;
635         unsigned int numverts = -1;
636         unsigned int numedges = -1;
637         unsigned int numfaces = -1;
638         MVert *mvert = NULL;
639         MEdge *medge = NULL;
640         MFace *mface = NULL;
641         DerivedMesh *result = NULL;
642         int ret = 0;
643         
644         if(G.rt > 0)
645                 printf("clothModifier_do start\n");
646         
647         /* we're getting called two times during file load,
648         resulting in a not valid G.relbase on the first time (cache makes problems)
649         --> just return back */
650         if((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_LOADED)&& (!G.relbase_valid))
651         {
652                 clmd->sim_parms->flags &= ~CLOTH_SIMSETTINGS_FLAG_LOADED;
653                 return dm;
654         }
655         
656         result = CDDM_copy(dm);
657         
658         if(!result)
659         {
660                 return dm;
661         }
662         
663         numverts = result->getNumVerts(result);
664         numedges = result->getNumEdges(result);
665         numfaces = result->getNumFaces(result);
666         mvert = dm->getVertArray(result);
667         medge = dm->getEdgeArray(result);
668         mface = dm->getFaceArray(result);
669         
670         /* check if cache is active / if file is already saved */
671         /*
672         if ((!G.relbase_valid) && ( deltaTime != 1.0f ))
673         {
674         clmd->sim_parms->flags |= CLOTH_SIMSETTINGS_FLAG_RESET;
675 }
676         */
677         
678         if(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_RESET)
679         {       
680                 cloth_free_modifier (ob, clmd);
681                 if(G.rt > 0)
682                         printf("clothModifier_do CLOTH_SIMSETTINGS_FLAG_RESET\n");
683         }
684         
685         // unused in the moment, calculated seperately in implicit.c
686         clmd->sim_parms->dt = 1.0f / clmd->sim_parms->stepsPerFrame;
687         
688         if ( ( clmd->clothObject == NULL ) || (clmd->clothObject && (numverts != clmd->clothObject->numverts )) )
689         {
690                 /* only force free the cache if we have a different number of verts */
691                 if(clmd->clothObject && (numverts != clmd->clothObject->numverts ))
692                 {
693                         clmd->sim_parms->flags |= CLOTH_SIMSETTINGS_FLAG_CCACHE_FFREE;
694                         cloth_free_modifier ( ob, clmd );
695                 }
696                 
697                 cloth_clear_cache(ob, clmd, 0);
698                                 
699                 if ( !cloth_from_object ( ob, clmd, result, framenr ) )
700                         return result;
701         
702                 if ( clmd->clothObject == NULL )
703                         return result;
704         
705                 cloth = clmd->clothObject;
706                 
707                 if(!cloth_read_cache(ob, clmd, framenr))
708                 {
709                         /* save first frame in case we have a reseted object 
710                         and we move one frame forward.
711                         In that case we would only start with the SECOND frame
712                         if we don't save the current state before 
713                         TODO PROBLEM: IMHO we can't track external movement from the
714                         first frame in this case! */
715                         /*
716                         if ( deltaTime == 1.0f )
717                         cloth_write_cache(ob, clmd, framenr-1.0);
718                         */
719                         if(G.rt > 0)
720                                 printf("cloth_from_object NO cloth_read_cache cloth_write_cache\n");
721                 }
722                 else
723                 {
724                         if(G.rt > 0)
725                                 printf("cloth_from_object cloth_read_cache\n");
726                         
727                         implicit_set_positions(clmd);
728                 }
729                 
730                 clmd->sim_parms->sim_time = current_time;
731         }
732         
733         // only be active during a specific period:
734         // that's "first frame" and "last frame" on GUI
735         
736         // TODO: enable later again after refactoring
737         if ( current_time < clmd->sim_parms->firstframe )
738         {
739                 return result;
740         }
741         else if ( current_time > clmd->sim_parms->lastframe )
742         {
743                 int stack_index = modifiers_indexInObject(ob, (ModifierData *)clmd);
744                         
745                 if(BKE_ptcache_id_exist((ID *)ob, clmd->sim_parms->lastcachedframe, stack_index))
746                 {
747                         if(cloth_read_cache(ob, clmd, clmd->sim_parms->lastcachedframe))
748                         {
749                                 implicit_set_positions(clmd);
750                                 
751                                 // Copy the result back to the object.
752                                 cloth_to_object (ob, clmd, result);
753                         }
754                 }
755                 return result;
756         }
757         
758         /* nice moving one frame forward */
759         if ( deltaTime == 1.0f )
760         {
761                 clmd->sim_parms->sim_time = current_time;
762                 
763                 if(G.rt > 0)
764                         printf("clothModifier_do deltaTime=1\n");
765                 
766                 if(!cloth_read_cache(ob, clmd, framenr))
767                 {
768                         verts = cloth->verts;
769
770                         // Force any pinned verts to their constrained location.
771                         for ( i = 0; i < clmd->clothObject->numverts; i++, verts++ )
772                         {
773                                 // Save the previous position.
774                                 VECCOPY ( verts->xold, verts->xconst );
775                                 VECCOPY ( verts->txold, verts->x );
776
777                                 // Get the current position.
778                                 VECCOPY ( verts->xconst, mvert[i].co );
779                                 Mat4MulVecfl ( ob->obmat, verts->xconst );
780                         }
781                         
782                         tstart();
783
784                         // Call the solver.
785                         if ( solvers [clmd->sim_parms->solver_type].solver )
786                         {
787                                 ret = solvers [clmd->sim_parms->solver_type].solver ( ob, framenr, clmd, effectors );
788                         }
789
790                         tend();
791                         // printf ( "Cloth simulation time: %f\n", ( float ) tval() );
792                         
793                         if(ret)
794                                 cloth_write_cache(ob, clmd, framenr);
795                         else
796                                 clmd->sim_parms->sim_time--;
797                         
798                         // check for autoprotection
799                         if(framenr >= clmd->sim_parms->autoprotect)
800                         {
801                                 if(G.rt > 0)
802                                         printf("fr#: %f, auto: %d\n", framenr, clmd->sim_parms->autoprotect);
803                                 clmd->sim_parms->flags |= CLOTH_SIMSETTINGS_FLAG_CCACHE_PROTECT;
804                         }
805                         if(G.rt > 0)
806                                 printf("clothModifier_do deltaTime=1 cachewrite\n");
807                 }
808                 else
809                 {
810                         if(G.rt > 0)
811                                 printf("clothModifier_do deltaTime=1 cacheread\n");
812                         implicit_set_positions(clmd);
813                 }
814                 
815                 // Copy the result back to the object.
816                 cloth_to_object (ob, clmd, result);
817         }
818         else if(deltaTime == 0.0f) 
819         {       
820                 if(G.rt > 0)
821                         printf("clothModifier_do deltaTime!=1 clmd->clothObject != NULL\n");
822                 if(cloth_read_cache(ob, clmd, framenr))
823                 {
824                         cloth_to_object (ob, clmd, result);
825                         implicit_set_positions(clmd);
826                 }
827                 else /* same cache parts are missing */
828                 {
829                         /*
830                         clmd->sim_parms->flags |= CLOTH_SIMSETTINGS_FLAG_RESET;
831                         */
832                         clmd->sim_parms->flags |= CLOTH_SIMSETTINGS_FLAG_CCACHE_FFREE;
833                         cloth_clear_cache(ob, clmd, 0);
834                         
835                         cloth_write_cache(ob, clmd, framenr);
836                 }
837         }
838         else
839         {       
840                 if(G.rt > 0)
841                         printf("clothModifier_do deltaTime!=1 clmd->clothObject != NULL\n");
842                 if(cloth_read_cache(ob, clmd, framenr))
843                 {
844                         cloth_to_object (ob, clmd, result);
845                         implicit_set_positions(clmd);
846                         clmd->sim_parms->sim_time = current_time;
847                 }
848                 else
849                 {
850                         /* jump to a non-existing frame makes sim reset */
851                         clmd->sim_parms->flags |= CLOTH_SIMSETTINGS_FLAG_RESET;
852                 }
853         }
854         
855         return result;
856 }
857
858 /* frees all */
859 void cloth_free_modifier ( Object *ob, ClothModifierData *clmd )
860 {
861         Cloth   *cloth = NULL;
862         
863         if ( !clmd )
864                 return;
865
866         cloth = clmd->clothObject;
867
868         
869         if ( cloth )
870         {       
871                 // If our solver provides a free function, call it
872                 if ( solvers [clmd->sim_parms->solver_type].free )
873                 {
874                         solvers [clmd->sim_parms->solver_type].free ( clmd );
875                 }
876
877                 // Free the verts.
878                 if ( cloth->verts != NULL )
879                         MEM_freeN ( cloth->verts );
880
881                 cloth->verts = NULL;
882                 cloth->numverts = 0;
883
884                 // Free the springs.
885                 if ( cloth->springs != NULL )
886                 {
887                         LinkNode *search = cloth->springs;
888                         while(search)
889                         {
890                                 ClothSpring *spring = search->link;
891                                                 
892                                 MEM_freeN ( spring );
893                                 search = search->next;
894                         }
895                         BLI_linklist_free(cloth->springs, NULL);
896                 
897                         cloth->springs = NULL;
898                 }
899
900                 cloth->springs = NULL;
901                 cloth->numsprings = 0;
902
903                 // free BVH collision tree
904                 if ( cloth->tree )
905                         bvh_free ( ( BVH * ) cloth->tree );
906
907                 // we save our faces for collision objects
908                 if ( cloth->mfaces )
909                         MEM_freeN ( cloth->mfaces );
910                 /*
911                 if(clmd->clothObject->facemarks)
912                 MEM_freeN(clmd->clothObject->facemarks);
913                 */
914                 MEM_freeN ( cloth );
915                 clmd->clothObject = NULL;
916         }
917         clmd->sim_parms->flags &= ~CLOTH_SIMSETTINGS_FLAG_RESET;
918 }
919
920 /* frees all */
921 void cloth_free_modifier_extern ( ClothModifierData *clmd )
922 {
923         Cloth   *cloth = NULL;
924         if(G.rt > 0)
925                 printf("cloth_free_modifier_extern\n");
926         
927         if ( !clmd )
928                 return;
929
930         cloth = clmd->clothObject;
931         
932         if ( cloth )
933         {       
934                 if(G.rt > 0)
935                         printf("cloth_free_modifier_extern in\n");
936                 
937                 // If our solver provides a free function, call it
938                 if ( solvers [clmd->sim_parms->solver_type].free )
939                 {
940                         solvers [clmd->sim_parms->solver_type].free ( clmd );
941                 }
942
943                 // Free the verts.
944                 if ( cloth->verts != NULL )
945                         MEM_freeN ( cloth->verts );
946
947                 cloth->verts = NULL;
948                 cloth->numverts = 0;
949
950                 // Free the springs.
951                 if ( cloth->springs != NULL )
952                 {
953                         LinkNode *search = cloth->springs;
954                         while(search)
955                         {
956                                 ClothSpring *spring = search->link;
957                                                 
958                                 MEM_freeN ( spring );
959                                 search = search->next;
960                         }
961                         BLI_linklist_free(cloth->springs, NULL);
962                 
963                         cloth->springs = NULL;
964                 }
965
966                 cloth->springs = NULL;
967                 cloth->numsprings = 0;
968
969                 // free BVH collision tree
970                 if ( cloth->tree )
971                         bvh_free ( ( BVH * ) cloth->tree );
972
973                 // we save our faces for collision objects
974                 if ( cloth->mfaces )
975                         MEM_freeN ( cloth->mfaces );
976                 /*
977                 if(clmd->clothObject->facemarks)
978                 MEM_freeN(clmd->clothObject->facemarks);
979                 */
980                 MEM_freeN ( cloth );
981                 clmd->clothObject = NULL;
982         }
983 }
984
985 /******************************************************************************
986 *
987 * Internal functions.
988 *
989 ******************************************************************************/
990
991 /**
992  * cloth_to_object - copies the deformed vertices to the object.
993  *
994  **/
995 static void cloth_to_object (Object *ob,  ClothModifierData *clmd, DerivedMesh *dm)
996 {
997         unsigned int    i = 0;
998         MVert *mvert = NULL;
999         unsigned int numverts;
1000         Cloth *cloth = clmd->clothObject;
1001
1002         if (clmd->clothObject) {
1003                 /* inverse matrix is not uptodate... */
1004                 Mat4Invert (ob->imat, ob->obmat);
1005
1006                 mvert = CDDM_get_verts(dm);
1007                 numverts = dm->getNumVerts(dm);
1008
1009                 for (i = 0; i < numverts; i++)
1010                 {
1011                         VECCOPY (mvert[i].co, cloth->verts[i].x);
1012                         Mat4MulVecfl (ob->imat, mvert[i].co);   /* cloth is in global coords */
1013                 }
1014         }
1015 }
1016
1017
1018 /**
1019  * cloth_apply_vgroup - applies a vertex group as specified by type
1020  *
1021  **/
1022 /* can be optimized to do all groups in one loop */
1023 static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm )
1024 {
1025         unsigned int i = 0;
1026         unsigned int j = 0;
1027         MDeformVert *dvert = NULL;
1028         Cloth *clothObj = NULL;
1029         unsigned int numverts = dm->getNumVerts ( dm );
1030         float goalfac = 0;
1031         ClothVertex *verts = NULL;
1032         // clmd->sim_parms->vgroup_mass
1033
1034         clothObj = clmd->clothObject;
1035
1036         if ( !dm )
1037                 return;
1038         
1039         numverts = dm->getNumVerts ( dm );
1040
1041         verts = clothObj->verts;
1042         
1043         if (((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING ) || 
1044                      (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )) && 
1045                      ((clmd->sim_parms->vgroup_mass>0) || 
1046                      (clmd->sim_parms->vgroup_struct>0)||
1047                      (clmd->sim_parms->vgroup_bend>0)))
1048         {
1049                 for ( i = 0; i < numverts; i++, verts++ )
1050                 {
1051                         dvert = dm->getVertData ( dm, i, CD_MDEFORMVERT );
1052                         if ( dvert )
1053                         {
1054                                 for ( j = 0; j < dvert->totweight; j++ )
1055                                 {
1056                                         if (( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_mass-1)) && (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ))
1057                                         {
1058                                                 verts->goal = dvert->dw [j].weight;
1059                                                 goalfac= 1.0f;
1060                                                 
1061                                                 /*
1062                                                 // Kicking goal factor to simplify things...who uses that anyway?
1063                                                 // ABS ( clmd->sim_parms->maxgoal - clmd->sim_parms->mingoal );
1064                                                 */
1065                                                 
1066                                                 verts->goal  = ( float ) pow ( verts->goal , 4.0f );
1067                                                 if ( verts->goal >=SOFTGOALSNAP )
1068                                                         verts->flags |= CLOTH_VERT_FLAG_PINNED;
1069                                         }
1070                                         
1071                                         if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING )
1072                                         {
1073                                                 if( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_struct-1))
1074                                                 {
1075                                                         verts->struct_stiff = dvert->dw [j].weight;
1076                                                         verts->shear_stiff = dvert->dw [j].weight;
1077                                                 }
1078                                                 
1079                                                 if( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_bend-1))
1080                                                 {
1081                                                         verts->bend_stiff = dvert->dw [j].weight;
1082                                                 }
1083                                         }
1084                                 }
1085                         }
1086                 }
1087         }
1088 }
1089
1090 /*
1091 helper function to get proper spring length
1092 when object is rescaled
1093 */
1094 float cloth_globallen ( float *v1,float *v2,Object *ob )
1095 {
1096         float p1[3],p2[3];
1097         VECCOPY ( p1,v1 );
1098         Mat4MulVecfl ( ob->obmat, p1 );
1099         VECCOPY ( p2,v2 );
1100         Mat4MulVecfl ( ob->obmat, p2 );
1101         return VecLenf ( p1,p2 );
1102 }
1103
1104 static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *dm, float framenr)
1105 {
1106         unsigned int i = 0;
1107         MVert *mvert = NULL;
1108         ClothVertex *verts = NULL;
1109         float tnull[3] = {0,0,0};
1110         int cache_there = 0;
1111
1112         // If we have a clothObject, free it. 
1113         if ( clmd->clothObject != NULL )
1114         {
1115                 cloth_free_modifier ( ob, clmd );
1116                 if(G.rt > 0)
1117                         printf("cloth_free_modifier cloth_from_object\n");
1118         }
1119
1120         // Allocate a new cloth object.
1121         clmd->clothObject = MEM_callocN ( sizeof ( Cloth ), "cloth" );
1122         if ( clmd->clothObject )
1123         {
1124                 clmd->clothObject->old_solver_type = 255;
1125                 // clmd->clothObject->old_collision_type = 255;
1126         }
1127         else if ( !clmd->clothObject )
1128         {
1129                 modifier_setError ( & ( clmd->modifier ), "Out of memory on allocating clmd->clothObject." );
1130                 return 0;
1131         }
1132
1133         // mesh input objects need DerivedMesh
1134         if ( !dm )
1135                 return 0;
1136
1137         cloth_from_mesh ( ob, clmd, dm );
1138
1139         if((clmd->sim_parms->firstcachedframe < 0.0) || ((clmd->sim_parms->firstcachedframe >= 0.0) && (!cloth_read_cache(ob, clmd, clmd->sim_parms->firstcachedframe))))
1140         {
1141                 // no cache there
1142                 cache_there = 0;
1143                 if(G.rt > 0)
1144                         printf("cache_there = 0\n");
1145         }
1146         else
1147         {
1148                 // we have a cache
1149                 cache_there = 1;
1150                 if(G.rt > 0)
1151                         printf("cache_there = 1, fcf: %d\n", clmd->sim_parms->firstcachedframe);
1152         }
1153         
1154         // create springs 
1155         clmd->clothObject->springs = NULL;
1156         clmd->clothObject->numsprings = -1;
1157         
1158         mvert = dm->getVertArray ( dm );
1159         verts = clmd->clothObject->verts;
1160
1161         // set initial values
1162         for ( i = 0; i < dm->getNumVerts(dm); i++, verts++ )
1163         {
1164                 if(!cache_there)
1165                 {
1166                         VECCOPY ( verts->x, mvert[i].co );
1167                         Mat4MulVecfl ( ob->obmat, verts->x );
1168                 }
1169                 
1170                 verts->mass = clmd->sim_parms->mass;
1171
1172                 if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
1173                         verts->goal= clmd->sim_parms->defgoal;
1174                 else
1175                         verts->goal= 0.0f;
1176
1177                 verts->flags = 0;
1178                 VECCOPY ( verts->xold, verts->x );
1179                 VECCOPY ( verts->xconst, verts->x );
1180                 VECCOPY ( verts->txold, verts->x );
1181                 VecMulf ( verts->v, 0.0f );
1182
1183                 verts->impulse_count = 0;
1184                 VECCOPY ( verts->impulse, tnull );
1185         }
1186         
1187         // apply / set vertex groups
1188         // has to be happen before springs are build!
1189         cloth_apply_vgroup (clmd, dm);
1190         
1191         if ( !cloth_build_springs ( clmd, dm ) )
1192         {
1193                 cloth_free_modifier ( ob, clmd );
1194                 modifier_setError ( & ( clmd->modifier ), "Can't build springs." );
1195                 printf("cloth_free_modifier cloth_build_springs\n");
1196                 return 0;
1197         }
1198         
1199         // init our solver
1200         if ( solvers [clmd->sim_parms->solver_type].init )
1201                 solvers [clmd->sim_parms->solver_type].init ( ob, clmd );
1202
1203         clmd->clothObject->tree = bvh_build_from_cloth ( clmd, clmd->coll_parms->epsilon );
1204         
1205         return 1;
1206 }
1207
1208
1209 static void cloth_from_mesh ( Object *ob, ClothModifierData *clmd, DerivedMesh *dm )
1210 {
1211         unsigned int numverts = dm->getNumVerts ( dm );
1212         unsigned int numfaces = dm->getNumFaces ( dm );
1213         MFace *mface = CDDM_get_faces(dm);
1214         unsigned int i = 0;
1215
1216         /* Allocate our vertices.
1217         */
1218         clmd->clothObject->numverts = numverts;
1219         clmd->clothObject->verts = MEM_callocN ( sizeof ( ClothVertex ) * clmd->clothObject->numverts, "clothVertex" );
1220         if ( clmd->clothObject->verts == NULL )
1221         {
1222                 cloth_free_modifier ( ob, clmd );
1223                 modifier_setError ( & ( clmd->modifier ), "Out of memory on allocating clmd->clothObject->verts." );
1224                 printf("cloth_free_modifier clmd->clothObject->verts\n");
1225                 return;
1226         }
1227
1228         // save face information
1229         clmd->clothObject->numfaces = numfaces;
1230         clmd->clothObject->mfaces = MEM_callocN ( sizeof ( MFace ) * clmd->clothObject->numfaces, "clothMFaces" );
1231         if ( clmd->clothObject->mfaces == NULL )
1232         {
1233                 cloth_free_modifier ( ob, clmd );
1234                 modifier_setError ( & ( clmd->modifier ), "Out of memory on allocating clmd->clothObject->mfaces." );
1235                 printf("cloth_free_modifier clmd->clothObject->mfaces\n");
1236                 return;
1237         }
1238         for ( i = 0; i < numfaces; i++ )
1239                 memcpy ( &clmd->clothObject->mfaces[i], &mface[i], sizeof ( MFace ) );
1240
1241         /* Free the springs since they can't be correct if the vertices
1242         * changed.
1243         */
1244         if ( clmd->clothObject->springs != NULL )
1245                 MEM_freeN ( clmd->clothObject->springs );
1246
1247 }
1248
1249 /***************************************************************************************
1250 * SPRING NETWORK BUILDING IMPLEMENTATION BEGIN
1251 ***************************************************************************************/
1252
1253 // be carefull: implicit solver has to be resettet when using this one!
1254 // --> only for implicit handling of this spring!
1255 int cloth_add_spring ( ClothModifierData *clmd, unsigned int indexA, unsigned int indexB, float restlength, int spring_type)
1256 {
1257         Cloth *cloth = clmd->clothObject;
1258         ClothSpring *spring = NULL;
1259         
1260         if(cloth)
1261         {
1262                 // TODO: look if this spring is already there
1263                 
1264                 spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1265                 
1266                 spring->ij = indexA;
1267                 spring->kl = indexB;
1268                 spring->restlen =  restlength;
1269                 spring->type = spring_type;
1270                 spring->flags = 0;
1271                 
1272                 cloth->numsprings++;
1273         
1274                 BLI_linklist_append ( &cloth->springs, spring );
1275                 
1276                 return 1;
1277         }
1278         return 0;
1279 }
1280
1281 int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm )
1282 {
1283         Cloth *cloth = clmd->clothObject;
1284         ClothSpring *spring = NULL, *tspring = NULL, *tspring2 = NULL;
1285         unsigned int struct_springs = 0, shear_springs=0, bend_springs = 0;
1286         unsigned int i = 0;
1287         unsigned int numverts = dm->getNumVerts ( dm );
1288         unsigned int numedges = dm->getNumEdges ( dm );
1289         unsigned int numfaces = dm->getNumFaces ( dm );
1290         MEdge *medge = CDDM_get_edges ( dm );
1291         MFace *mface = CDDM_get_faces ( dm );
1292         unsigned int index2 = 0; // our second vertex index
1293         LinkNode **edgelist = NULL;
1294         EdgeHash *edgehash = NULL;
1295         LinkNode *search = NULL, *search2 = NULL;
1296         float temp[3];
1297         LinkNode *node = NULL, *node2 = NULL;
1298         
1299         // error handling
1300         if ( numedges==0 )
1301                 return 0;
1302
1303         cloth->springs = NULL;
1304
1305         edgelist = MEM_callocN ( sizeof ( LinkNode * ) * numverts, "cloth_edgelist_alloc" );
1306         for ( i = 0; i < numverts; i++ )
1307         {
1308                 edgelist[i] = NULL;
1309         }
1310
1311         if ( cloth->springs )
1312                 MEM_freeN ( cloth->springs );
1313
1314         // create spring network hash
1315         edgehash = BLI_edgehash_new();
1316
1317         // structural springs
1318         for ( i = 0; i < numedges; i++ )
1319         {
1320                 spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1321
1322                 if ( spring )
1323                 {
1324                         spring->ij = medge[i].v1;
1325                         spring->kl = medge[i].v2;
1326                         VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
1327                         spring->restlen =  sqrt ( INPR ( temp, temp ) );
1328                         /*
1329                         if(spring->restlen > 1.0)
1330                         {
1331                         printf("i: %d, L: %f\n", i, spring->restlen);
1332                         printf("%d, x: %f, y: %f, z: %f\n", cloth->verts[spring->ij].x[0], cloth->verts[spring->ij].x[1], spring->ij, cloth->verts[spring->ij].x[2]);
1333                         printf("%d, x: %f, y: %f, z: %f\n\n",spring->kl, cloth->verts[spring->kl].x[0], cloth->verts[spring->kl].x[1], cloth->verts[spring->kl].x[2]);
1334                 }
1335                         */
1336                         clmd->coll_parms->avg_spring_len += spring->restlen;
1337                         spring->type = CLOTH_SPRING_TYPE_STRUCTURAL;
1338                         spring->flags = 0;
1339                         spring->stiffness = (cloth->verts[spring->kl].struct_stiff + cloth->verts[spring->ij].struct_stiff) / 2.0;
1340                         struct_springs++;
1341                         
1342                         if(!i)
1343                                 node2 = BLI_linklist_append_fast ( &cloth->springs, spring );
1344                         else
1345                                 node2 = BLI_linklist_append_fast ( &node->next, spring );
1346                         node = node2;
1347                 }
1348         }
1349         
1350         clmd->coll_parms->avg_spring_len /= struct_springs;
1351         
1352         // shear springs
1353         for ( i = 0; i < numfaces; i++ )
1354         {
1355                 spring = ( ClothSpring *) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1356
1357                 spring->ij = mface[i].v1;
1358                 spring->kl = mface[i].v3;
1359                 VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
1360                 spring->restlen =  sqrt ( INPR ( temp, temp ) );
1361                 spring->type = CLOTH_SPRING_TYPE_SHEAR;
1362                 spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0;
1363
1364                 BLI_linklist_append ( &edgelist[spring->ij], spring );
1365                 BLI_linklist_append ( &edgelist[spring->kl], spring );
1366                 shear_springs++;
1367
1368                 node2 = BLI_linklist_append_fast ( &node->next, spring );
1369                 node = node2;
1370
1371                 if ( mface[i].v4 )
1372                 {
1373                         spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1374
1375                         spring->ij = mface[i].v2;
1376                         spring->kl = mface[i].v4;
1377                         VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
1378                         spring->restlen =  sqrt ( INPR ( temp, temp ) );
1379                         spring->type = CLOTH_SPRING_TYPE_SHEAR;
1380                         spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0;
1381
1382                         BLI_linklist_append ( &edgelist[spring->ij], spring );
1383                         BLI_linklist_append ( &edgelist[spring->kl], spring );
1384                         shear_springs++;
1385
1386                         node2 = BLI_linklist_append_fast ( &node->next, spring );
1387                         node = node2;
1388                 }
1389         }
1390         
1391         // bending springs
1392         search2 = cloth->springs;
1393         for ( i = struct_springs; i < struct_springs+shear_springs; i++ )
1394         {
1395                 if ( !search2 )
1396                         break;
1397
1398                 tspring2 = search2->link;
1399                 search = edgelist[tspring2->kl];
1400                 while ( search )
1401                 {
1402                         tspring = search->link;
1403                         index2 = ( ( tspring->ij==tspring2->kl ) ? ( tspring->kl ) : ( tspring->ij ) );
1404                         
1405                         // check for existing spring
1406                         // check also if startpoint is equal to endpoint
1407                         if ( !BLI_edgehash_haskey ( edgehash, index2, tspring2->ij )
1408                                                    && !BLI_edgehash_haskey ( edgehash, tspring2->ij, index2 )
1409                                                    && ( index2!=tspring2->ij ) )
1410                         {
1411                                 spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1412
1413                                 spring->ij = tspring2->ij;
1414                                 spring->kl = index2;
1415                                 VECSUB ( temp, cloth->verts[index2].x, cloth->verts[tspring2->ij].x );
1416                                 spring->restlen =  sqrt ( INPR ( temp, temp ) );
1417                                 spring->type = CLOTH_SPRING_TYPE_BENDING;
1418                                 spring->stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0;
1419                                 BLI_edgehash_insert ( edgehash, spring->ij, index2, NULL );
1420                                 bend_springs++;
1421
1422                                 node2 = BLI_linklist_append_fast ( &node->next, spring );
1423                                 node = node2;
1424                         }
1425                         search = search->next;
1426                 }
1427                 search2 = search2->next;
1428         }
1429         
1430         cloth->numsprings = struct_springs + shear_springs + bend_springs;
1431         
1432         for ( i = 0; i < numverts; i++ )
1433         {
1434                 BLI_linklist_free ( edgelist[i],NULL );
1435         }
1436         if ( edgelist )
1437                 MEM_freeN ( edgelist );
1438         
1439         BLI_edgehash_free ( edgehash, NULL );
1440
1441         return 1;
1442
1443 } /* cloth_build_springs */
1444 /***************************************************************************************
1445 * SPRING NETWORK BUILDING IMPLEMENTATION END
1446 ***************************************************************************************/
1447