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