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