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