svn merge ^/trunk/blender -r40644:40720
[blender.git] / source / blender / blenkernel / intern / implicit.c
1 /*
2  * $Id$
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) Blender Foundation
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /** \file blender/blenkernel/intern/implicit.c
31  *  \ingroup bke
32  */
33
34
35 #include "MEM_guardedalloc.h"
36
37 #include "DNA_scene_types.h"
38 #include "DNA_object_types.h"
39 #include "DNA_object_force.h"
40 #include "DNA_meshdata_types.h"
41
42 #include "BLI_threads.h"
43 #include "BLI_math.h"
44 #include "BLI_linklist.h"
45 #include "BLI_utildefines.h"
46
47 #include "BKE_cloth.h"
48 #include "BKE_collision.h"
49 #include "BKE_effect.h"
50 #include "BKE_global.h"
51
52
53 #define CLOTH_OPENMP_LIMIT 512
54
55 #ifdef _WIN32
56 #include <windows.h>
57 static LARGE_INTEGER _itstart, _itend;
58 static LARGE_INTEGER ifreq;
59 static void itstart(void)
60 {
61         static int first = 1;
62         if(first) {
63                 QueryPerformanceFrequency(&ifreq);
64                 first = 0;
65         }
66         QueryPerformanceCounter(&_itstart);
67 }
68 static void itend(void)
69 {
70         QueryPerformanceCounter(&_itend);
71 }
72 double itval(void)
73 {
74         return ((double)_itend.QuadPart -
75                         (double)_itstart.QuadPart)/((double)ifreq.QuadPart);
76 }
77 #else
78 #include <sys/time.h>
79 // intrinsics need better compile flag checking
80 // #include <xmmintrin.h>
81 // #include <pmmintrin.h>
82 // #include <pthread.h>
83
84                          static struct timeval _itstart, _itend;
85          static struct timezone itz;
86          void itstart(void)
87 {
88         gettimeofday(&_itstart, &itz);
89 }
90 static void itend(void)
91 {
92         gettimeofday(&_itend,&itz);
93 }
94 double itval(void)
95 {
96         double t1, t2;
97         t1 =  (double)_itstart.tv_sec + (double)_itstart.tv_usec/(1000*1000);
98         t2 =  (double)_itend.tv_sec + (double)_itend.tv_usec/(1000*1000);
99         return t2-t1;
100 }
101 #endif
102
103 static float I[3][3] = {{1,0,0},{0,1,0},{0,0,1}};
104 static float ZERO[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}};
105
106 /*
107 #define C99
108 #ifdef C99
109 #defineDO_INLINE inline 
110 #else 
111 #defineDO_INLINE static 
112 #endif
113 */
114 struct Cloth;
115
116 //////////////////////////////////////////
117 /* fast vector / matrix library, enhancements are welcome :) -dg */
118 /////////////////////////////////////////
119
120 /* DEFINITIONS */
121 typedef float lfVector[3];
122 typedef struct fmatrix3x3 {
123         float m[3][3]; /* 3x3 matrix */
124         unsigned int c,r; /* column and row number */
125         int pinned; /* is this vertex allowed to move? */
126         float n1,n2,n3; /* three normal vectors for collision constrains */
127         unsigned int vcount; /* vertex count */
128         unsigned int scount; /* spring count */ 
129 } fmatrix3x3;
130
131 ///////////////////////////
132 // float[3] vector
133 ///////////////////////////
134 /* simple vector code */
135 /* STATUS: verified */
136 DO_INLINE void mul_fvector_S(float to[3], float from[3], float scalar)
137 {
138         to[0] = from[0] * scalar;
139         to[1] = from[1] * scalar;
140         to[2] = from[2] * scalar;
141 }
142 /* simple cross product */
143 /* STATUS: verified */
144 DO_INLINE void cross_fvector(float to[3], float vectorA[3], float vectorB[3])
145 {
146         to[0] = vectorA[1] * vectorB[2] - vectorA[2] * vectorB[1];
147         to[1] = vectorA[2] * vectorB[0] - vectorA[0] * vectorB[2];
148         to[2] = vectorA[0] * vectorB[1] - vectorA[1] * vectorB[0];
149 }
150 /* simple v^T * v product ("outer product") */
151 /* STATUS: HAS TO BE verified (*should* work) */
152 DO_INLINE void mul_fvectorT_fvector(float to[3][3], float vectorA[3], float vectorB[3])
153 {
154         mul_fvector_S(to[0], vectorB, vectorA[0]);
155         mul_fvector_S(to[1], vectorB, vectorA[1]);
156         mul_fvector_S(to[2], vectorB, vectorA[2]);
157 }
158 /* simple v^T * v product with scalar ("outer product") */
159 /* STATUS: HAS TO BE verified (*should* work) */
160 DO_INLINE void mul_fvectorT_fvectorS(float to[3][3], float vectorA[3], float vectorB[3], float aS)
161 {       
162         mul_fvectorT_fvector(to, vectorA, vectorB);
163         
164         mul_fvector_S(to[0], to[0], aS);
165         mul_fvector_S(to[1], to[1], aS);
166         mul_fvector_S(to[2], to[2], aS);
167 }
168
169
170 /* printf vector[3] on console: for debug output */
171 static void print_fvector(float m3[3])
172 {
173         printf("%f\n%f\n%f\n\n",m3[0],m3[1],m3[2]);
174 }
175
176 ///////////////////////////
177 // long float vector float (*)[3]
178 ///////////////////////////
179 /* print long vector on console: for debug output */
180 DO_INLINE void print_lfvector(float (*fLongVector)[3], unsigned int verts)
181 {
182         unsigned int i = 0;
183         for(i = 0; i < verts; i++)
184         {
185                 print_fvector(fLongVector[i]);
186         }
187 }
188 /* create long vector */
189 DO_INLINE lfVector *create_lfvector(unsigned int verts)
190 {
191         // TODO: check if memory allocation was successfull */
192         return  (lfVector *)MEM_callocN (verts * sizeof(lfVector), "cloth_implicit_alloc_vector");
193         // return (lfVector *)cloth_aligned_malloc(&MEMORY_BASE, verts * sizeof(lfVector));
194 }
195 /* delete long vector */
196 DO_INLINE void del_lfvector(float (*fLongVector)[3])
197 {
198         if (fLongVector != NULL)
199         {
200                 MEM_freeN (fLongVector);
201                 // cloth_aligned_free(&MEMORY_BASE, fLongVector);
202         }
203 }
204 /* copy long vector */
205 DO_INLINE void cp_lfvector(float (*to)[3], float (*from)[3], unsigned int verts)
206 {
207         memcpy(to, from, verts * sizeof(lfVector));
208 }
209 /* init long vector with float[3] */
210 DO_INLINE void init_lfvector(float (*fLongVector)[3], float vector[3], unsigned int verts)
211 {
212         unsigned int i = 0;
213         for(i = 0; i < verts; i++)
214         {
215                 VECCOPY(fLongVector[i], vector);
216         }
217 }
218 /* zero long vector with float[3] */
219 DO_INLINE void zero_lfvector(float (*to)[3], unsigned int verts)
220 {
221         memset(to, 0.0f, verts * sizeof(lfVector));
222 }
223 /* multiply long vector with scalar*/
224 DO_INLINE void mul_lfvectorS(float (*to)[3], float (*fLongVector)[3], float scalar, unsigned int verts)
225 {
226         unsigned int i = 0;
227
228         for(i = 0; i < verts; i++)
229         {
230                 mul_fvector_S(to[i], fLongVector[i], scalar);
231         }
232 }
233 /* multiply long vector with scalar*/
234 /* A -= B * float */
235 DO_INLINE void submul_lfvectorS(float (*to)[3], float (*fLongVector)[3], float scalar, unsigned int verts)
236 {
237         unsigned int i = 0;
238         for(i = 0; i < verts; i++)
239         {
240                 VECSUBMUL(to[i], fLongVector[i], scalar);
241         }
242 }
243 /* dot product for big vector */
244 DO_INLINE float dot_lfvector(float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts)
245 {
246         long i = 0;
247         float temp = 0.0;
248 // XXX brecht, disabled this for now (first schedule line was already disabled),
249 // due to non-commutative nature of floating point ops this makes the sim give
250 // different results each time you run it!
251 // schedule(guided, 2)
252 //#pragma omp parallel for reduction(+: temp) if(verts > CLOTH_OPENMP_LIMIT)
253         for(i = 0; i < (long)verts; i++)
254         {
255                 temp += INPR(fLongVectorA[i], fLongVectorB[i]);
256         }
257         return temp;
258 }
259 /* A = B + C  --> for big vector */
260 DO_INLINE void add_lfvector_lfvector(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts)
261 {
262         unsigned int i = 0;
263
264         for(i = 0; i < verts; i++)
265         {
266                 VECADD(to[i], fLongVectorA[i], fLongVectorB[i]);
267         }
268
269 }
270 /* A = B + C * float --> for big vector */
271 DO_INLINE void add_lfvector_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], float bS, unsigned int verts)
272 {
273         unsigned int i = 0;
274
275         for(i = 0; i < verts; i++)
276         {
277                 VECADDS(to[i], fLongVectorA[i], fLongVectorB[i], bS);
278
279         }
280 }
281 /* A = B * float + C * float --> for big vector */
282 DO_INLINE void add_lfvectorS_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float aS, float (*fLongVectorB)[3], float bS, unsigned int verts)
283 {
284         unsigned int i = 0;
285
286         for(i = 0; i < verts; i++)
287         {
288                 VECADDSS(to[i], fLongVectorA[i], aS, fLongVectorB[i], bS);
289         }
290 }
291 /* A = B - C * float --> for big vector */
292 DO_INLINE void sub_lfvector_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], float bS, unsigned int verts)
293 {
294         unsigned int i = 0;
295         for(i = 0; i < verts; i++)
296         {
297                 VECSUBS(to[i], fLongVectorA[i], fLongVectorB[i], bS);
298         }
299
300 }
301 /* A = B - C --> for big vector */
302 DO_INLINE void sub_lfvector_lfvector(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts)
303 {
304         unsigned int i = 0;
305
306         for(i = 0; i < verts; i++)
307         {
308                 VECSUB(to[i], fLongVectorA[i], fLongVectorB[i]);
309         }
310
311 }
312 ///////////////////////////
313 // 3x3 matrix
314 ///////////////////////////
315 #if 0
316 /* printf 3x3 matrix on console: for debug output */
317 static void print_fmatrix(float m3[3][3])
318 {
319         printf("%f\t%f\t%f\n",m3[0][0],m3[0][1],m3[0][2]);
320         printf("%f\t%f\t%f\n",m3[1][0],m3[1][1],m3[1][2]);
321         printf("%f\t%f\t%f\n\n",m3[2][0],m3[2][1],m3[2][2]);
322 }
323 #endif
324
325 /* copy 3x3 matrix */
326 DO_INLINE void cp_fmatrix(float to[3][3], float from[3][3])
327 {
328         // memcpy(to, from, sizeof (float) * 9);
329         VECCOPY(to[0], from[0]);
330         VECCOPY(to[1], from[1]);
331         VECCOPY(to[2], from[2]);
332 }
333
334 /* copy 3x3 matrix */
335 DO_INLINE void initdiag_fmatrixS(float to[3][3], float aS)
336 {
337         cp_fmatrix(to, ZERO);
338         
339         to[0][0] = aS;
340         to[1][1] = aS;
341         to[2][2] = aS;
342 }
343
344 /* calculate determinant of 3x3 matrix */
345 DO_INLINE float det_fmatrix(float m[3][3])
346 {
347         return  m[0][0]*m[1][1]*m[2][2] + m[1][0]*m[2][1]*m[0][2] + m[0][1]*m[1][2]*m[2][0] 
348                         -m[0][0]*m[1][2]*m[2][1] - m[0][1]*m[1][0]*m[2][2] - m[2][0]*m[1][1]*m[0][2];
349 }
350
351 DO_INLINE void inverse_fmatrix(float to[3][3], float from[3][3])
352 {
353         unsigned int i, j;
354         float d;
355
356         if((d=det_fmatrix(from))==0)
357         {
358                 printf("can't build inverse");
359                 exit(0);
360         }
361         for(i=0;i<3;i++) 
362         {
363                 for(j=0;j<3;j++) 
364                 {
365                         int i1=(i+1)%3;
366                         int i2=(i+2)%3;
367                         int j1=(j+1)%3;
368                         int j2=(j+2)%3;
369                         // reverse indexs i&j to take transpose
370                         to[j][i] = (from[i1][j1]*from[i2][j2]-from[i1][j2]*from[i2][j1])/d;
371                         /*
372                         if(i==j)
373                         to[i][j] = 1.0f / from[i][j];
374                         else
375                         to[i][j] = 0;
376                         */
377                 }
378         }
379
380 }
381
382 /* 3x3 matrix multiplied by a scalar */
383 /* STATUS: verified */
384 DO_INLINE void mul_fmatrix_S(float matrix[3][3], float scalar)
385 {
386         mul_fvector_S(matrix[0], matrix[0],scalar);
387         mul_fvector_S(matrix[1], matrix[1],scalar);
388         mul_fvector_S(matrix[2], matrix[2],scalar);
389 }
390
391 /* a vector multiplied by a 3x3 matrix */
392 /* STATUS: verified */
393 DO_INLINE void mul_fvector_fmatrix(float *to, float *from, float matrix[3][3])
394 {
395         to[0] = matrix[0][0]*from[0] + matrix[1][0]*from[1] + matrix[2][0]*from[2];
396         to[1] = matrix[0][1]*from[0] + matrix[1][1]*from[1] + matrix[2][1]*from[2];
397         to[2] = matrix[0][2]*from[0] + matrix[1][2]*from[1] + matrix[2][2]*from[2];
398 }
399
400 /* 3x3 matrix multiplied by a vector */
401 /* STATUS: verified */
402 DO_INLINE void mul_fmatrix_fvector(float *to, float matrix[3][3], float *from)
403 {
404         to[0] = INPR(matrix[0],from);
405         to[1] = INPR(matrix[1],from);
406         to[2] = INPR(matrix[2],from);
407 }
408 /* 3x3 matrix multiplied by a 3x3 matrix */
409 /* STATUS: verified */
410 DO_INLINE void mul_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
411 {
412         mul_fvector_fmatrix(to[0], matrixA[0],matrixB);
413         mul_fvector_fmatrix(to[1], matrixA[1],matrixB);
414         mul_fvector_fmatrix(to[2], matrixA[2],matrixB);
415 }
416 /* 3x3 matrix addition with 3x3 matrix */
417 DO_INLINE void add_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
418 {
419         VECADD(to[0], matrixA[0], matrixB[0]);
420         VECADD(to[1], matrixA[1], matrixB[1]);
421         VECADD(to[2], matrixA[2], matrixB[2]);
422 }
423 /* 3x3 matrix add-addition with 3x3 matrix */
424 DO_INLINE void addadd_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
425 {
426         VECADDADD(to[0], matrixA[0], matrixB[0]);
427         VECADDADD(to[1], matrixA[1], matrixB[1]);
428         VECADDADD(to[2], matrixA[2], matrixB[2]);
429 }
430 /* 3x3 matrix sub-addition with 3x3 matrix */
431 DO_INLINE void addsub_fmatrixS_fmatrixS(float to[3][3], float matrixA[3][3], float aS, float matrixB[3][3], float bS)
432 {
433         VECADDSUBSS(to[0], matrixA[0], aS, matrixB[0], bS);
434         VECADDSUBSS(to[1], matrixA[1], aS, matrixB[1], bS);
435         VECADDSUBSS(to[2], matrixA[2], aS, matrixB[2], bS);
436 }
437 /* A -= B + C (3x3 matrix sub-addition with 3x3 matrix) */
438 DO_INLINE void subadd_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
439 {
440         VECSUBADD(to[0], matrixA[0], matrixB[0]);
441         VECSUBADD(to[1], matrixA[1], matrixB[1]);
442         VECSUBADD(to[2], matrixA[2], matrixB[2]);
443 }
444 /* A -= B*x + C*y (3x3 matrix sub-addition with 3x3 matrix) */
445 DO_INLINE void subadd_fmatrixS_fmatrixS(float to[3][3], float matrixA[3][3], float aS, float matrixB[3][3], float bS)
446 {
447         VECSUBADDSS(to[0], matrixA[0], aS, matrixB[0], bS);
448         VECSUBADDSS(to[1], matrixA[1], aS, matrixB[1], bS);
449         VECSUBADDSS(to[2], matrixA[2], aS, matrixB[2], bS);
450 }
451 /* A = B - C (3x3 matrix subtraction with 3x3 matrix) */
452 DO_INLINE void sub_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
453 {
454         VECSUB(to[0], matrixA[0], matrixB[0]);
455         VECSUB(to[1], matrixA[1], matrixB[1]);
456         VECSUB(to[2], matrixA[2], matrixB[2]);
457 }
458 /* A += B - C (3x3 matrix add-subtraction with 3x3 matrix) */
459 DO_INLINE void addsub_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
460 {
461         VECADDSUB(to[0], matrixA[0], matrixB[0]);
462         VECADDSUB(to[1], matrixA[1], matrixB[1]);
463         VECADDSUB(to[2], matrixA[2], matrixB[2]);
464 }
465 /////////////////////////////////////////////////////////////////
466 // special functions
467 /////////////////////////////////////////////////////////////////
468 /* a vector multiplied and added to/by a 3x3 matrix */
469 DO_INLINE void muladd_fvector_fmatrix(float to[3], float from[3], float matrix[3][3])
470 {
471         to[0] += matrix[0][0]*from[0] + matrix[1][0]*from[1] + matrix[2][0]*from[2];
472         to[1] += matrix[0][1]*from[0] + matrix[1][1]*from[1] + matrix[2][1]*from[2];
473         to[2] += matrix[0][2]*from[0] + matrix[1][2]*from[1] + matrix[2][2]*from[2];
474 }
475 /* 3x3 matrix multiplied and added  to/by a 3x3 matrix  and added to another 3x3 matrix */
476 DO_INLINE void muladd_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
477 {
478         muladd_fvector_fmatrix(to[0], matrixA[0],matrixB);
479         muladd_fvector_fmatrix(to[1], matrixA[1],matrixB);
480         muladd_fvector_fmatrix(to[2], matrixA[2],matrixB);
481 }
482 /* a vector multiplied and sub'd to/by a 3x3 matrix */
483 DO_INLINE void mulsub_fvector_fmatrix(float to[3], float from[3], float matrix[3][3])
484 {
485         to[0] -= matrix[0][0]*from[0] + matrix[1][0]*from[1] + matrix[2][0]*from[2];
486         to[1] -= matrix[0][1]*from[0] + matrix[1][1]*from[1] + matrix[2][1]*from[2];
487         to[2] -= matrix[0][2]*from[0] + matrix[1][2]*from[1] + matrix[2][2]*from[2];
488 }
489 /* 3x3 matrix multiplied and sub'd  to/by a 3x3 matrix  and added to another 3x3 matrix */
490 DO_INLINE void mulsub_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
491 {
492         mulsub_fvector_fmatrix(to[0], matrixA[0],matrixB);
493         mulsub_fvector_fmatrix(to[1], matrixA[1],matrixB);
494         mulsub_fvector_fmatrix(to[2], matrixA[2],matrixB);
495 }
496 /* 3x3 matrix multiplied+added by a vector */
497 /* STATUS: verified */
498 DO_INLINE void muladd_fmatrix_fvector(float to[3], float matrix[3][3], float from[3])
499 {
500         to[0] += INPR(matrix[0],from);
501         to[1] += INPR(matrix[1],from);
502         to[2] += INPR(matrix[2],from);  
503 }
504 /* 3x3 matrix multiplied+sub'ed by a vector */
505 DO_INLINE void mulsub_fmatrix_fvector(float to[3], float matrix[3][3], float from[3])
506 {
507         to[0] -= INPR(matrix[0],from);
508         to[1] -= INPR(matrix[1],from);
509         to[2] -= INPR(matrix[2],from);
510 }
511 /////////////////////////////////////////////////////////////////
512
513 ///////////////////////////
514 // SPARSE SYMMETRIC big matrix with 3x3 matrix entries
515 ///////////////////////////
516 /* printf a big matrix on console: for debug output */
517 #if 0
518 static void print_bfmatrix(fmatrix3x3 *m3)
519 {
520         unsigned int i = 0;
521
522         for(i = 0; i < m3[0].vcount + m3[0].scount; i++)
523         {
524                 print_fmatrix(m3[i].m);
525         }
526 }
527 #endif
528
529 /* create big matrix */
530 DO_INLINE fmatrix3x3 *create_bfmatrix(unsigned int verts, unsigned int springs)
531 {
532         // TODO: check if memory allocation was successfull */
533         fmatrix3x3 *temp = (fmatrix3x3 *)MEM_callocN (sizeof (fmatrix3x3) * (verts + springs), "cloth_implicit_alloc_matrix");
534         temp[0].vcount = verts;
535         temp[0].scount = springs;
536         return temp;
537 }
538 /* delete big matrix */
539 DO_INLINE void del_bfmatrix(fmatrix3x3 *matrix)
540 {
541         if (matrix != NULL)
542         {
543                 MEM_freeN (matrix);
544         }
545 }
546
547 /* copy big matrix */
548 DO_INLINE void cp_bfmatrix(fmatrix3x3 *to, fmatrix3x3 *from)
549 {       
550         // TODO bounds checking 
551         memcpy(to, from, sizeof(fmatrix3x3) * (from[0].vcount+from[0].scount) );
552 }
553
554 /* init big matrix */
555 // slow in parallel
556 DO_INLINE void init_bfmatrix(fmatrix3x3 *matrix, float m3[3][3])
557 {
558         unsigned int i;
559
560         for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
561         {               
562                 cp_fmatrix(matrix[i].m, m3); 
563         }
564 }
565
566 /* init the diagonal of big matrix */
567 // slow in parallel
568 DO_INLINE void initdiag_bfmatrix(fmatrix3x3 *matrix, float m3[3][3])
569 {
570         unsigned int i,j;
571         float tmatrix[3][3] = {{0,0,0},{0,0,0},{0,0,0}};
572
573         for(i = 0; i < matrix[0].vcount; i++)
574         {               
575                 cp_fmatrix(matrix[i].m, m3); 
576         }
577         for(j = matrix[0].vcount; j < matrix[0].vcount+matrix[0].scount; j++)
578         {
579                 cp_fmatrix(matrix[j].m, tmatrix); 
580         }
581 }
582
583 /* multiply big matrix with scalar*/
584 DO_INLINE void mul_bfmatrix_S(fmatrix3x3 *matrix, float scalar)
585 {
586         unsigned int i = 0;
587         for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
588         {
589                 mul_fmatrix_S(matrix[i].m, scalar);
590         }
591 }
592
593 /* SPARSE SYMMETRIC multiply big matrix with long vector*/
594 /* STATUS: verified */
595 DO_INLINE void mul_bfmatrix_lfvector( float (*to)[3], fmatrix3x3 *from, lfVector *fLongVector)
596 {
597         unsigned int i = 0;
598         unsigned int vcount = from[0].vcount;
599         lfVector *temp = create_lfvector(vcount);
600         
601         zero_lfvector(to, vcount);
602
603 #pragma omp parallel sections private(i) if(vcount > CLOTH_OPENMP_LIMIT)
604         {
605 #pragma omp section
606                 {
607                         for(i = from[0].vcount; i < from[0].vcount+from[0].scount; i++)
608                         {
609                                 muladd_fmatrix_fvector(to[from[i].c], from[i].m, fLongVector[from[i].r]);
610                         }
611                 }       
612 #pragma omp section
613                 {
614                         for(i = 0; i < from[0].vcount+from[0].scount; i++)
615                         {
616                                 muladd_fmatrix_fvector(temp[from[i].r], from[i].m, fLongVector[from[i].c]);
617                         }
618                 }
619         }
620         add_lfvector_lfvector(to, to, temp, from[0].vcount);
621         
622         del_lfvector(temp);
623         
624         
625 }
626
627 /* SPARSE SYMMETRIC multiply big matrix with long vector (for diagonal preconditioner) */
628 /* STATUS: verified */
629 DO_INLINE void mul_prevfmatrix_lfvector( float (*to)[3], fmatrix3x3 *from, lfVector *fLongVector)
630 {
631         unsigned int i = 0;
632         
633         for(i = 0; i < from[0].vcount; i++)
634         {
635                 mul_fmatrix_fvector(to[from[i].r], from[i].m, fLongVector[from[i].c]);
636         }
637 }
638
639 /* SPARSE SYMMETRIC add big matrix with big matrix: A = B + C*/
640 DO_INLINE void add_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from,  fmatrix3x3 *matrix)
641 {
642         unsigned int i = 0;
643
644         /* process diagonal elements */
645         for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
646         {
647                 add_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);   
648         }
649
650 }
651 /* SPARSE SYMMETRIC add big matrix with big matrix: A += B + C */
652 DO_INLINE void addadd_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from,  fmatrix3x3 *matrix)
653 {
654         unsigned int i = 0;
655
656         /* process diagonal elements */
657         for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
658         {
659                 addadd_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);        
660         }
661
662 }
663 /* SPARSE SYMMETRIC subadd big matrix with big matrix: A -= B + C */
664 DO_INLINE void subadd_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from,  fmatrix3x3 *matrix)
665 {
666         unsigned int i = 0;
667
668         /* process diagonal elements */
669         for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
670         {
671                 subadd_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);        
672         }
673
674 }
675 /*  A = B - C (SPARSE SYMMETRIC sub big matrix with big matrix) */
676 DO_INLINE void sub_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from,  fmatrix3x3 *matrix)
677 {
678         unsigned int i = 0;
679
680         /* process diagonal elements */
681         for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
682         {
683                 sub_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);   
684         }
685
686 }
687 /* SPARSE SYMMETRIC sub big matrix with big matrix S (special constraint matrix with limited entries) */
688 DO_INLINE void sub_bfmatrix_Smatrix( fmatrix3x3 *to, fmatrix3x3 *from,  fmatrix3x3 *matrix)
689 {
690         unsigned int i = 0;
691
692         /* process diagonal elements */
693         for(i = 0; i < matrix[0].vcount; i++)
694         {
695                 sub_fmatrix_fmatrix(to[matrix[i].c].m, from[matrix[i].c].m, matrix[i].m);       
696         }
697
698 }
699 /* A += B - C (SPARSE SYMMETRIC addsub big matrix with big matrix) */
700 DO_INLINE void addsub_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from,  fmatrix3x3 *matrix)
701 {
702         unsigned int i = 0;
703
704         /* process diagonal elements */
705         for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
706         {
707                 addsub_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);        
708         }
709
710 }
711 /* SPARSE SYMMETRIC sub big matrix with big matrix*/
712 /* A -= B * float + C * float --> for big matrix */
713 /* VERIFIED */
714 DO_INLINE void subadd_bfmatrixS_bfmatrixS( fmatrix3x3 *to, fmatrix3x3 *from, float aS,  fmatrix3x3 *matrix, float bS)
715 {
716         unsigned int i = 0;
717
718         /* process diagonal elements */
719         for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
720         {
721                 subadd_fmatrixS_fmatrixS(to[i].m, from[i].m, aS, matrix[i].m, bS);      
722         }
723
724 }
725
726 ///////////////////////////////////////////////////////////////////
727 // simulator start
728 ///////////////////////////////////////////////////////////////////
729 typedef struct Implicit_Data 
730 {
731         lfVector *X, *V, *Xnew, *Vnew, *olddV, *F, *B, *dV, *z;
732         fmatrix3x3 *A, *dFdV, *dFdX, *S, *P, *Pinv, *bigI, *M; 
733 } Implicit_Data;
734
735 int implicit_init (Object *UNUSED(ob), ClothModifierData *clmd)
736 {
737         unsigned int i = 0;
738         unsigned int pinned = 0;
739         Cloth *cloth = NULL;
740         ClothVertex *verts = NULL;
741         ClothSpring *spring = NULL;
742         Implicit_Data *id = NULL;
743         LinkNode *search = NULL;
744         
745         if(G.rt > 0)
746                 printf("implicit_init\n");
747
748         // init memory guard
749         // MEMORY_BASE.first = MEMORY_BASE.last = NULL;
750
751         cloth = (Cloth *)clmd->clothObject;
752         verts = cloth->verts;
753
754         // create implicit base
755         id = (Implicit_Data *)MEM_callocN (sizeof(Implicit_Data), "implicit vecmat");
756         cloth->implicit = id;
757
758         /* process diagonal elements */         
759         id->A = create_bfmatrix(cloth->numverts, cloth->numsprings);
760         id->dFdV = create_bfmatrix(cloth->numverts, cloth->numsprings);
761         id->dFdX = create_bfmatrix(cloth->numverts, cloth->numsprings);
762         id->S = create_bfmatrix(cloth->numverts, 0);
763         id->Pinv = create_bfmatrix(cloth->numverts, cloth->numsprings);
764         id->P = create_bfmatrix(cloth->numverts, cloth->numsprings);
765         id->bigI = create_bfmatrix(cloth->numverts, cloth->numsprings); // TODO 0 springs
766         id->M = create_bfmatrix(cloth->numverts, cloth->numsprings);
767         id->X = create_lfvector(cloth->numverts);
768         id->Xnew = create_lfvector(cloth->numverts);
769         id->V = create_lfvector(cloth->numverts);
770         id->Vnew = create_lfvector(cloth->numverts);
771         id->olddV = create_lfvector(cloth->numverts);
772         zero_lfvector(id->olddV, cloth->numverts);
773         id->F = create_lfvector(cloth->numverts);
774         id->B = create_lfvector(cloth->numverts);
775         id->dV = create_lfvector(cloth->numverts);
776         id->z = create_lfvector(cloth->numverts);
777         
778         for(i=0;i<cloth->numverts;i++) 
779         {
780                 id->A[i].r = id->A[i].c = id->dFdV[i].r = id->dFdV[i].c = id->dFdX[i].r = id->dFdX[i].c = id->P[i].c = id->P[i].r = id->Pinv[i].c = id->Pinv[i].r = id->bigI[i].c = id->bigI[i].r = id->M[i].r = id->M[i].c = i;
781
782                 if(verts [i].flags & CLOTH_VERT_FLAG_PINNED)
783                 {
784                         id->S[pinned].pinned = 1;
785                         id->S[pinned].c = id->S[pinned].r = i;
786                         pinned++;
787                 }
788                 
789                 initdiag_fmatrixS(id->M[i].m, verts[i].mass);
790         }
791
792         // S is special and needs specific vcount and scount
793         id->S[0].vcount = pinned; id->S[0].scount = 0;
794
795         // init springs 
796         search = cloth->springs;
797         for(i=0;i<cloth->numsprings;i++) 
798         {
799                 spring = search->link;
800                 
801                 // dFdV_start[i].r = big_I[i].r = big_zero[i].r = 
802                 id->A[i+cloth->numverts].r = id->dFdV[i+cloth->numverts].r = id->dFdX[i+cloth->numverts].r = 
803                                 id->P[i+cloth->numverts].r = id->Pinv[i+cloth->numverts].r = id->bigI[i+cloth->numverts].r = id->M[i+cloth->numverts].r = spring->ij;
804
805                 // dFdV_start[i].c = big_I[i].c = big_zero[i].c = 
806                 id->A[i+cloth->numverts].c = id->dFdV[i+cloth->numverts].c = id->dFdX[i+cloth->numverts].c = 
807                                 id->P[i+cloth->numverts].c = id->Pinv[i+cloth->numverts].c = id->bigI[i+cloth->numverts].c = id->M[i+cloth->numverts].c = spring->kl;
808
809                 spring->matrix_index = i + cloth->numverts;
810                 
811                 search = search->next;
812         }
813         
814         initdiag_bfmatrix(id->bigI, I);
815
816         for(i = 0; i < cloth->numverts; i++)
817         {               
818                 VECCOPY(id->X[i], verts[i].x);
819         }
820
821         return 1;
822 }
823 int     implicit_free (ClothModifierData *clmd)
824 {
825         Implicit_Data *id;
826         Cloth *cloth;
827         cloth = (Cloth *)clmd->clothObject;
828
829         if(cloth)
830         {
831                 id = cloth->implicit;
832
833                 if(id)
834                 {
835                         del_bfmatrix(id->A);
836                         del_bfmatrix(id->dFdV);
837                         del_bfmatrix(id->dFdX);
838                         del_bfmatrix(id->S);
839                         del_bfmatrix(id->P);
840                         del_bfmatrix(id->Pinv);
841                         del_bfmatrix(id->bigI);
842                         del_bfmatrix(id->M);
843
844                         del_lfvector(id->X);
845                         del_lfvector(id->Xnew);
846                         del_lfvector(id->V);
847                         del_lfvector(id->Vnew);
848                         del_lfvector(id->olddV);
849                         del_lfvector(id->F);
850                         del_lfvector(id->B);
851                         del_lfvector(id->dV);
852                         del_lfvector(id->z);
853
854                         MEM_freeN(id);
855                 }
856         }
857
858         return 1;
859 }
860
861 DO_INLINE float fb(float length, float L)
862 {
863         float x = length/L;
864         return (-11.541f*pow(x,4)+34.193f*pow(x,3)-39.083f*pow(x,2)+23.116f*x-9.713f);
865 }
866
867 DO_INLINE float fbderiv(float length, float L)
868 {
869         float x = length/L;
870
871         return (-46.164f*pow(x,3)+102.579f*pow(x,2)-78.166f*x+23.116f);
872 }
873
874 DO_INLINE float fbstar(float length, float L, float kb, float cb)
875 {
876         float tempfb = kb * fb(length, L);
877
878         float fbstar = cb * (length - L);
879         
880         if(tempfb < fbstar)
881                 return fbstar;
882         else
883                 return tempfb;          
884 }
885
886 // function to calculae bending spring force (taken from Choi & Co)
887 DO_INLINE float fbstar_jacobi(float length, float L, float kb, float cb)
888 {
889         float tempfb = kb * fb(length, L);
890         float fbstar = cb * (length - L);
891
892         if(tempfb < fbstar)
893         {               
894                 return cb;
895         }
896         else
897         {
898                 return kb * fbderiv(length, L); 
899         }       
900 }
901
902 DO_INLINE void filter(lfVector *V, fmatrix3x3 *S)
903 {
904         unsigned int i=0;
905
906         for(i=0;i<S[0].vcount;i++)
907         {
908                 mul_fvector_fmatrix(V[S[i].r], V[S[i].r], S[i].m);
909         }
910 }
911
912 static int  cg_filtered(lfVector *ldV, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S)
913 {
914         // Solves for unknown X in equation AX=B
915         unsigned int conjgrad_loopcount=0, conjgrad_looplimit=100;
916         float conjgrad_epsilon=0.0001f /* , conjgrad_lasterror=0 */ /* UNUSED */;
917         lfVector *q, *d, *tmp, *r; 
918         float s, starget, a, s_prev;
919         unsigned int numverts = lA[0].vcount;
920         q = create_lfvector(numverts);
921         d = create_lfvector(numverts);
922         tmp = create_lfvector(numverts);
923         r = create_lfvector(numverts);
924
925         // zero_lfvector(ldV, CLOTHPARTICLES);
926         filter(ldV, S);
927
928         add_lfvector_lfvector(ldV, ldV, z, numverts);
929
930         // r = B - Mul(tmp,A,X);    // just use B if X known to be zero
931         cp_lfvector(r, lB, numverts);
932         mul_bfmatrix_lfvector(tmp, lA, ldV);
933         sub_lfvector_lfvector(r, r, tmp, numverts);
934
935         filter(r,S);
936
937         cp_lfvector(d, r, numverts);
938
939         s = dot_lfvector(r, r, numverts);
940         starget = s * sqrt(conjgrad_epsilon);
941
942         while(s>starget && conjgrad_loopcount < conjgrad_looplimit)
943         {       
944                 // Mul(q,A,d); // q = A*d;
945                 mul_bfmatrix_lfvector(q, lA, d);
946
947                 filter(q,S);
948
949                 a = s/dot_lfvector(d, q, numverts);
950
951                 // X = X + d*a;
952                 add_lfvector_lfvectorS(ldV, ldV, d, a, numverts);
953
954                 // r = r - q*a;
955                 sub_lfvector_lfvectorS(r, r, q, a, numverts);
956
957                 s_prev = s;
958                 s = dot_lfvector(r, r, numverts);
959
960                 //d = r+d*(s/s_prev);
961                 add_lfvector_lfvectorS(d, r, d, (s/s_prev), numverts);
962
963                 filter(d,S);
964
965                 conjgrad_loopcount++;
966         }
967         /* conjgrad_lasterror = s; */ /* UNUSED */
968
969         del_lfvector(q);
970         del_lfvector(d);
971         del_lfvector(tmp);
972         del_lfvector(r);
973         // printf("W/O conjgrad_loopcount: %d\n", conjgrad_loopcount);
974
975         return conjgrad_loopcount<conjgrad_looplimit;  // true means we reached desired accuracy in given time - ie stable
976 }
977
978 // block diagonalizer
979 DO_INLINE void BuildPPinv(fmatrix3x3 *lA, fmatrix3x3 *P, fmatrix3x3 *Pinv)
980 {
981         unsigned int i = 0;
982         
983         // Take only the diagonal blocks of A
984 // #pragma omp parallel for private(i) if(lA[0].vcount > CLOTH_OPENMP_LIMIT)
985         for(i = 0; i<lA[0].vcount; i++)
986         {
987                 // block diagonalizer
988                 cp_fmatrix(P[i].m, lA[i].m);
989                 inverse_fmatrix(Pinv[i].m, P[i].m);
990                 
991         }
992 }
993 #if 0
994 /*
995 // version 1.3
996 static int cg_filtered_pre(lfVector *dv, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S, fmatrix3x3 *P, fmatrix3x3 *Pinv)
997 {
998         unsigned int numverts = lA[0].vcount, iterations = 0, conjgrad_looplimit=100;
999         float delta0 = 0, deltaNew = 0, deltaOld = 0, alpha = 0;
1000         float conjgrad_epsilon=0.0001; // 0.2 is dt for steps=5
1001         lfVector *r = create_lfvector(numverts);
1002         lfVector *p = create_lfvector(numverts);
1003         lfVector *s = create_lfvector(numverts);
1004         lfVector *h = create_lfvector(numverts);
1005         
1006         BuildPPinv(lA, P, Pinv);
1007         
1008         filter(dv, S);
1009         add_lfvector_lfvector(dv, dv, z, numverts);
1010         
1011         mul_bfmatrix_lfvector(r, lA, dv);
1012         sub_lfvector_lfvector(r, lB, r, numverts);
1013         filter(r, S);
1014         
1015         mul_prevfmatrix_lfvector(p, Pinv, r);
1016         filter(p, S);
1017         
1018         deltaNew = dot_lfvector(r, p, numverts);
1019         
1020         delta0 = deltaNew * sqrt(conjgrad_epsilon);
1021         
1022         // itstart();
1023         
1024         while ((deltaNew > delta0) && (iterations < conjgrad_looplimit))
1025         {
1026                 iterations++;
1027                 
1028                 mul_bfmatrix_lfvector(s, lA, p);
1029                 filter(s, S);
1030                 
1031                 alpha = deltaNew / dot_lfvector(p, s, numverts);
1032                 
1033                 add_lfvector_lfvectorS(dv, dv, p, alpha, numverts);
1034                 
1035                 add_lfvector_lfvectorS(r, r, s, -alpha, numverts);
1036                 
1037                 mul_prevfmatrix_lfvector(h, Pinv, r);
1038                 filter(h, S);
1039                 
1040                 deltaOld = deltaNew;
1041                 
1042                 deltaNew = dot_lfvector(r, h, numverts);
1043                 
1044                 add_lfvector_lfvectorS(p, h, p, deltaNew / deltaOld, numverts);
1045                 
1046                 filter(p, S);
1047                 
1048         }
1049         
1050         // itend();
1051         // printf("cg_filtered_pre time: %f\n", (float)itval());
1052         
1053         del_lfvector(h);
1054         del_lfvector(s);
1055         del_lfvector(p);
1056         del_lfvector(r);
1057         
1058         printf("iterations: %d\n", iterations);
1059         
1060         return iterations<conjgrad_looplimit;
1061 }
1062 */
1063 // version 1.4
1064 static int cg_filtered_pre(lfVector *dv, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S, fmatrix3x3 *P, fmatrix3x3 *Pinv, fmatrix3x3 *bigI)
1065 {
1066         unsigned int numverts = lA[0].vcount, iterations = 0, conjgrad_looplimit=100;
1067         float delta0 = 0, deltaNew = 0, deltaOld = 0, alpha = 0, tol = 0;
1068         lfVector *r = create_lfvector(numverts);
1069         lfVector *p = create_lfvector(numverts);
1070         lfVector *s = create_lfvector(numverts);
1071         lfVector *h = create_lfvector(numverts);
1072         lfVector *bhat = create_lfvector(numverts);
1073         lfVector *btemp = create_lfvector(numverts);
1074         
1075         BuildPPinv(lA, P, Pinv);
1076         
1077         initdiag_bfmatrix(bigI, I);
1078         sub_bfmatrix_Smatrix(bigI, bigI, S);
1079         
1080         // x = Sx_0+(I-S)z
1081         filter(dv, S);
1082         add_lfvector_lfvector(dv, dv, z, numverts);
1083         
1084         // b_hat = S(b-A(I-S)z)
1085         mul_bfmatrix_lfvector(r, lA, z);
1086         mul_bfmatrix_lfvector(bhat, bigI, r);
1087         sub_lfvector_lfvector(bhat, lB, bhat, numverts);
1088         
1089         // r = S(b-Ax)
1090         mul_bfmatrix_lfvector(r, lA, dv);
1091         sub_lfvector_lfvector(r, lB, r, numverts);
1092         filter(r, S);
1093         
1094         // p = SP^-1r
1095         mul_prevfmatrix_lfvector(p, Pinv, r);
1096         filter(p, S);
1097         
1098         // delta0 = bhat^TP^-1bhat
1099         mul_prevfmatrix_lfvector(btemp, Pinv, bhat);
1100         delta0 = dot_lfvector(bhat, btemp, numverts);
1101         
1102         // deltaNew = r^TP
1103         deltaNew = dot_lfvector(r, p, numverts);
1104         
1105         /*
1106         filter(dv, S);
1107         add_lfvector_lfvector(dv, dv, z, numverts);
1108         
1109         mul_bfmatrix_lfvector(r, lA, dv);
1110         sub_lfvector_lfvector(r, lB, r, numverts);
1111         filter(r, S);
1112         
1113         mul_prevfmatrix_lfvector(p, Pinv, r);
1114         filter(p, S);
1115         
1116         deltaNew = dot_lfvector(r, p, numverts);
1117         
1118         delta0 = deltaNew * sqrt(conjgrad_epsilon);
1119         */
1120         
1121         // itstart();
1122         
1123         tol = (0.01*0.2);
1124         
1125         while ((deltaNew > delta0*tol*tol) && (iterations < conjgrad_looplimit))
1126         {
1127                 iterations++;
1128                 
1129                 mul_bfmatrix_lfvector(s, lA, p);
1130                 filter(s, S);
1131                 
1132                 alpha = deltaNew / dot_lfvector(p, s, numverts);
1133                 
1134                 add_lfvector_lfvectorS(dv, dv, p, alpha, numverts);
1135                 
1136                 add_lfvector_lfvectorS(r, r, s, -alpha, numverts);
1137                 
1138                 mul_prevfmatrix_lfvector(h, Pinv, r);
1139                 filter(h, S);
1140                 
1141                 deltaOld = deltaNew;
1142                 
1143                 deltaNew = dot_lfvector(r, h, numverts);
1144                 
1145                 add_lfvector_lfvectorS(p, h, p, deltaNew / deltaOld, numverts);
1146                 
1147                 filter(p, S);
1148                 
1149         }
1150         
1151         // itend();
1152         // printf("cg_filtered_pre time: %f\n", (float)itval());
1153         
1154         del_lfvector(btemp);
1155         del_lfvector(bhat);
1156         del_lfvector(h);
1157         del_lfvector(s);
1158         del_lfvector(p);
1159         del_lfvector(r);
1160         
1161         // printf("iterations: %d\n", iterations);
1162         
1163         return iterations<conjgrad_looplimit;
1164 }
1165 #endif
1166
1167 // outer product is NOT cross product!!!
1168 DO_INLINE void dfdx_spring_type1(float to[3][3], float extent[3], float length, float L, float dot, float k)
1169 {
1170         // dir is unit length direction, rest is spring's restlength, k is spring constant.
1171         // return  (outerprod(dir,dir)*k + (I - outerprod(dir,dir))*(k - ((k*L)/length)));
1172         float temp[3][3];
1173         float temp1 = k*(1.0 - (L/length));     
1174         
1175         mul_fvectorT_fvectorS(temp, extent, extent, 1.0 / dot);
1176         sub_fmatrix_fmatrix(to, I, temp);
1177         mul_fmatrix_S(to, temp1);
1178         
1179         mul_fvectorT_fvectorS(temp, extent, extent, k/ dot);
1180         add_fmatrix_fmatrix(to, to, temp);
1181         
1182         /*
1183         mul_fvectorT_fvector(temp, dir, dir);
1184         sub_fmatrix_fmatrix(to, I, temp);
1185         mul_fmatrix_S(to, k* (1.0f-(L/length)));
1186         mul_fmatrix_S(temp, k);
1187         add_fmatrix_fmatrix(to, temp, to);
1188         */
1189 }
1190
1191 DO_INLINE void dfdx_spring_type2(float to[3][3], float dir[3], float length, float L, float k, float cb)
1192 {
1193         // return  outerprod(dir,dir)*fbstar_jacobi(length, L, k, cb);
1194         mul_fvectorT_fvectorS(to, dir, dir, fbstar_jacobi(length, L, k, cb));
1195 }
1196
1197 DO_INLINE void dfdv_damp(float to[3][3], float dir[3], float damping)
1198 {
1199         // derivative of force wrt velocity.  
1200         mul_fvectorT_fvectorS(to, dir, dir, damping);
1201         
1202 }
1203
1204 DO_INLINE void dfdx_spring(float to[3][3],  float dir[3],float length,float L,float k)
1205 {
1206         // dir is unit length direction, rest is spring's restlength, k is spring constant.
1207         //return  ( (I-outerprod(dir,dir))*Min(1.0f,rest/length) - I) * -k;
1208         mul_fvectorT_fvector(to, dir, dir);
1209         sub_fmatrix_fmatrix(to, I, to);
1210
1211         mul_fmatrix_S(to, (L/length)); 
1212         sub_fmatrix_fmatrix(to, to, I);
1213         mul_fmatrix_S(to, -k);
1214 }
1215
1216 // unused atm
1217 DO_INLINE void dfdx_damp(float to[3][3],  float dir[3],float length,const float vel[3],float rest,float damping)
1218 {
1219         // inner spring damping   vel is the relative velocity  of the endpoints.  
1220         //      return (I-outerprod(dir,dir)) * (-damping * -(dot(dir,vel)/Max(length,rest)));
1221         mul_fvectorT_fvector(to, dir, dir);
1222         sub_fmatrix_fmatrix(to, I, to);
1223         mul_fmatrix_S(to,  (-damping * -(INPR(dir,vel)/MAX2(length,rest)))); 
1224
1225 }
1226
1227 DO_INLINE void cloth_calc_spring_force(ClothModifierData *clmd, ClothSpring *s, lfVector *UNUSED(lF), lfVector *X, lfVector *V, fmatrix3x3 *UNUSED(dFdV), fmatrix3x3 *UNUSED(dFdX), float time)
1228 {
1229         Cloth *cloth = clmd->clothObject;
1230         ClothVertex *verts = cloth->verts;
1231         float extent[3];
1232         float length = 0, dot = 0;
1233         float dir[3] = {0,0,0};
1234         float vel[3];
1235         float k = 0.0f;
1236         float L = s->restlen;
1237         float cb; /* = clmd->sim_parms->structural; */ /*UNUSED*/
1238
1239         float nullf[3] = {0,0,0};
1240         float stretch_force[3] = {0,0,0};
1241         float bending_force[3] = {0,0,0};
1242         float damping_force[3] = {0,0,0};
1243         float nulldfdx[3][3]={ {0,0,0}, {0,0,0}, {0,0,0}};
1244         
1245         float scaling = 0.0;
1246
1247         int no_compress = clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_NO_SPRING_COMPRESS;
1248         
1249         VECCOPY(s->f, nullf);
1250         cp_fmatrix(s->dfdx, nulldfdx);
1251         cp_fmatrix(s->dfdv, nulldfdx);
1252
1253         // calculate elonglation
1254         VECSUB(extent, X[s->kl], X[s->ij]);
1255         VECSUB(vel, V[s->kl], V[s->ij]);
1256         dot = INPR(extent, extent);
1257         length = sqrt(dot);
1258         
1259         s->flags &= ~CLOTH_SPRING_FLAG_NEEDED;
1260         
1261         if(length > ALMOST_ZERO)
1262         {
1263                 /*
1264                 if(length>L)
1265                 {
1266                 if((clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED) 
1267                 && ((((length-L)*100.0f/L) > clmd->sim_parms->maxspringlen))) // cut spring!
1268                 {
1269                 s->flags |= CSPRING_FLAG_DEACTIVATE;
1270                 return;
1271         }
1272         } 
1273                 */
1274                 mul_fvector_S(dir, extent, 1.0f/length);
1275         }
1276         else    
1277         {
1278                 mul_fvector_S(dir, extent, 0.0f);
1279         }
1280         
1281         // calculate force of structural + shear springs
1282         if((s->type & CLOTH_SPRING_TYPE_STRUCTURAL) || (s->type & CLOTH_SPRING_TYPE_SHEAR))
1283         {
1284                 if(length > L || no_compress)
1285                 {
1286                         s->flags |= CLOTH_SPRING_FLAG_NEEDED;
1287                         
1288                         k = clmd->sim_parms->structural;
1289                                 
1290                         scaling = k + s->stiffness * ABS(clmd->sim_parms->max_struct-k);
1291                         
1292                         k = scaling / (clmd->sim_parms->avg_spring_len + FLT_EPSILON);
1293                         
1294                         // TODO: verify, half verified (couldn't see error)
1295                         mul_fvector_S(stretch_force, dir, k*(length-L)); 
1296
1297                         VECADD(s->f, s->f, stretch_force);
1298
1299                         // Ascher & Boxman, p.21: Damping only during elonglation
1300                         // something wrong with it...
1301                         mul_fvector_S(damping_force, dir, clmd->sim_parms->Cdis * INPR(vel,dir));
1302                         VECADD(s->f, s->f, damping_force);
1303                         
1304                         /* VERIFIED */
1305                         dfdx_spring(s->dfdx, dir, length, L, k);
1306                         
1307                         /* VERIFIED */
1308                         dfdv_damp(s->dfdv, dir, clmd->sim_parms->Cdis);
1309                         
1310                 }
1311         }
1312         else if(s->type & CLOTH_SPRING_TYPE_GOAL)
1313         {
1314                 float tvect[3];
1315                 
1316                 s->flags |= CLOTH_SPRING_FLAG_NEEDED;
1317                 
1318                 // current_position = xold + t * (newposition - xold)
1319                 VECSUB(tvect, verts[s->ij].xconst, verts[s->ij].xold);
1320                 mul_fvector_S(tvect, tvect, time);
1321                 VECADD(tvect, tvect, verts[s->ij].xold);
1322
1323                 VECSUB(extent, X[s->ij], tvect);
1324                 
1325                 // SEE MSG BELOW (these are UNUSED)
1326                 // dot = INPR(extent, extent);
1327                 // length = sqrt(dot);
1328                 
1329                 k = clmd->sim_parms->goalspring;
1330                 
1331                 scaling = k + s->stiffness * ABS(clmd->sim_parms->max_struct-k);
1332                         
1333                 k = verts [s->ij].goal * scaling / (clmd->sim_parms->avg_spring_len + FLT_EPSILON);
1334                 
1335                 VECADDS(s->f, s->f, extent, -k);
1336                 
1337                 mul_fvector_S(damping_force, dir, clmd->sim_parms->goalfrict * 0.01 * INPR(vel,dir));
1338                 VECADD(s->f, s->f, damping_force);
1339                 
1340                 // HERE IS THE PROBLEM!!!!
1341                 // dfdx_spring(s->dfdx, dir, length, 0.0, k);
1342                 // dfdv_damp(s->dfdv, dir, MIN2(1.0, (clmd->sim_parms->goalfrict/100.0)));
1343         }
1344         else // calculate force of bending springs
1345         {
1346                 if(length < L)
1347                 {
1348                         s->flags |= CLOTH_SPRING_FLAG_NEEDED;
1349                         
1350                         k = clmd->sim_parms->bending;   
1351                         
1352                         scaling = k + s->stiffness * ABS(clmd->sim_parms->max_bend-k);                  
1353                         cb = k = scaling / (20.0*(clmd->sim_parms->avg_spring_len + FLT_EPSILON));
1354
1355                         mul_fvector_S(bending_force, dir, fbstar(length, L, k, cb));
1356                         VECADD(s->f, s->f, bending_force);
1357
1358                         dfdx_spring_type2(s->dfdx, dir, length,L, k, cb);
1359                 }
1360         }
1361 }
1362
1363 DO_INLINE void cloth_apply_spring_force(ClothModifierData *UNUSED(clmd), ClothSpring *s, lfVector *lF, lfVector *UNUSED(X), lfVector *UNUSED(V), fmatrix3x3 *dFdV, fmatrix3x3 *dFdX)
1364 {
1365         if(s->flags & CLOTH_SPRING_FLAG_NEEDED)
1366         {
1367                 if(!(s->type & CLOTH_SPRING_TYPE_BENDING))
1368                 {
1369                         sub_fmatrix_fmatrix(dFdV[s->ij].m, dFdV[s->ij].m, s->dfdv);
1370                         sub_fmatrix_fmatrix(dFdV[s->kl].m, dFdV[s->kl].m, s->dfdv);
1371                         add_fmatrix_fmatrix(dFdV[s->matrix_index].m, dFdV[s->matrix_index].m, s->dfdv); 
1372                 }
1373
1374                 VECADD(lF[s->ij], lF[s->ij], s->f);
1375                 
1376                 if(!(s->type & CLOTH_SPRING_TYPE_GOAL))
1377                         VECSUB(lF[s->kl], lF[s->kl], s->f);
1378                 
1379                 sub_fmatrix_fmatrix(dFdX[s->kl].m, dFdX[s->kl].m, s->dfdx);
1380                 sub_fmatrix_fmatrix(dFdX[s->ij].m, dFdX[s->ij].m, s->dfdx);
1381                 add_fmatrix_fmatrix(dFdX[s->matrix_index].m, dFdX[s->matrix_index].m, s->dfdx);
1382         }       
1383 }
1384
1385
1386 static void CalcFloat( float *v1, float *v2, float *v3, float *n)
1387 {
1388         float n1[3],n2[3];
1389
1390         n1[0]= v1[0]-v2[0];
1391         n2[0]= v2[0]-v3[0];
1392         n1[1]= v1[1]-v2[1];
1393         n2[1]= v2[1]-v3[1];
1394         n1[2]= v1[2]-v2[2];
1395         n2[2]= v2[2]-v3[2];
1396         n[0]= n1[1]*n2[2]-n1[2]*n2[1];
1397         n[1]= n1[2]*n2[0]-n1[0]*n2[2];
1398         n[2]= n1[0]*n2[1]-n1[1]*n2[0];
1399 }
1400
1401 static void CalcFloat4( float *v1, float *v2, float *v3, float *v4, float *n)
1402 {
1403         /* real cross! */
1404         float n1[3],n2[3];
1405
1406         n1[0]= v1[0]-v3[0];
1407         n1[1]= v1[1]-v3[1];
1408         n1[2]= v1[2]-v3[2];
1409
1410         n2[0]= v2[0]-v4[0];
1411         n2[1]= v2[1]-v4[1];
1412         n2[2]= v2[2]-v4[2];
1413
1414         n[0]= n1[1]*n2[2]-n1[2]*n2[1];
1415         n[1]= n1[2]*n2[0]-n1[0]*n2[2];
1416         n[2]= n1[0]*n2[1]-n1[1]*n2[0];
1417 }
1418
1419 static float calculateVertexWindForce(float wind[3], float vertexnormal[3])  
1420 {
1421         return (INPR(wind, vertexnormal));
1422 }
1423
1424 typedef struct HairGridVert {
1425         float velocity[3];
1426         float density;
1427 } HairGridVert;
1428 #define HAIR_GRID_INDEX(vec, min, max, axis) (int)( (vec[axis] - min[axis]) / (max[axis] - min[axis]) * 9.99f );
1429 /* Smoothing of hair velocities:
1430  * adapted from
1431                 Volumetric Methods for Simulation and Rendering of Hair
1432                 by Lena Petrovic, Mark Henne and John Anderson
1433  *              Pixar Technical Memo #06-08, Pixar Animation Studios
1434  */
1435 static void hair_velocity_smoothing(ClothModifierData *clmd, lfVector *lF, lfVector *lX, lfVector *lV, unsigned int numverts)
1436 {
1437         /* TODO: This is an initial implementation and should be made much better in due time.
1438          * What should at least be implemented is a grid size parameter and a smoothing kernel
1439          * for bigger grids.
1440          */
1441
1442         /* 10x10x10 grid gives nice initial results */
1443         HairGridVert grid[10][10][10];
1444         HairGridVert colg[10][10][10];
1445         ListBase *colliders = get_collider_cache(clmd->scene, NULL, NULL);
1446         ColliderCache *col = NULL;
1447         float gmin[3], gmax[3], density;
1448         /* 2.0f is an experimental value that seems to give good results */
1449         float smoothfac = 2.0f * clmd->sim_parms->velocity_smooth;
1450         float collfac = 2.0f * clmd->sim_parms->collider_friction;
1451         unsigned int    v = 0;
1452         unsigned int    i = 0;
1453         int                             j = 0;
1454         int                             k = 0;
1455
1456         INIT_MINMAX(gmin, gmax);
1457
1458         for(i = 0; i < numverts; i++)
1459                 DO_MINMAX(lX[i], gmin, gmax);
1460
1461         /* initialize grid */
1462         for(i = 0; i < 10; i++) {
1463                 for(j = 0; j < 10; j++) {
1464                         for(k = 0; k < 10; k++) {
1465                                 grid[i][j][k].velocity[0] = 0.0f;
1466                                 grid[i][j][k].velocity[1] = 0.0f;
1467                                 grid[i][j][k].velocity[2] = 0.0f;
1468                                 grid[i][j][k].density = 0.0f;
1469
1470                                 colg[i][j][k].velocity[0] = 0.0f;
1471                                 colg[i][j][k].velocity[1] = 0.0f;
1472                                 colg[i][j][k].velocity[2] = 0.0f;
1473                                 colg[i][j][k].density = 0.0f;
1474                         }
1475                 }
1476         }
1477
1478         /* gather velocities & density */
1479         if(smoothfac > 0.0f) for(v = 0; v < numverts; v++) {
1480                 i = HAIR_GRID_INDEX(lX[v], gmin, gmax, 0);
1481                 j = HAIR_GRID_INDEX(lX[v], gmin, gmax, 1);
1482                 k = HAIR_GRID_INDEX(lX[v], gmin, gmax, 2);
1483                 if (i < 0 || j < 0 || k < 0 || i > 10 || j >= 10 || k >= 10)
1484                         continue;
1485
1486                 grid[i][j][k].velocity[0] += lV[v][0];
1487                 grid[i][j][k].velocity[1] += lV[v][1];
1488                 grid[i][j][k].velocity[2] += lV[v][2];
1489                 grid[i][j][k].density += 1.0f;
1490         }
1491
1492         /* gather colliders */
1493         if(colliders && collfac > 0.0f) for(col = colliders->first; col; col = col->next)
1494         {
1495                 MVert *loc0 = col->collmd->x;
1496                 MVert *loc1 = col->collmd->xnew;
1497                 float vel[3];
1498
1499                 for(v=0; v<col->collmd->numverts; v++, loc0++, loc1++) {
1500                         i = HAIR_GRID_INDEX(loc1->co, gmin, gmax, 0);
1501
1502                         if(i>=0 && i<10) {
1503                                 j = HAIR_GRID_INDEX(loc1->co, gmin, gmax, 1);
1504
1505                                 if(j>=0 && j<10) {
1506                                         k = HAIR_GRID_INDEX(loc1->co, gmin, gmax, 2);
1507
1508                                         if(k>=0 && k<10) {
1509                                                 VECSUB(vel, loc1->co, loc0->co);
1510
1511                                                 colg[i][j][k].velocity[0] += vel[0];
1512                                                 colg[i][j][k].velocity[1] += vel[1];
1513                                                 colg[i][j][k].velocity[2] += vel[2];
1514                                                 colg[i][j][k].density += 1.0;
1515                                         }
1516                                 }
1517                         }
1518                 }
1519         }
1520         
1521
1522         /* divide velocity with density */
1523         for(i = 0; i < 10; i++) {
1524                 for(j = 0; j < 10; j++) {
1525                         for(k = 0; k < 10; k++) {
1526                                 density = grid[i][j][k].density;
1527                                 if(density > 0.0f) {
1528                                         grid[i][j][k].velocity[0] /= density;
1529                                         grid[i][j][k].velocity[1] /= density;
1530                                         grid[i][j][k].velocity[2] /= density;
1531                                 }
1532
1533                                 density = colg[i][j][k].density;
1534                                 if(density > 0.0f) {
1535                                         colg[i][j][k].velocity[0] /= density;
1536                                         colg[i][j][k].velocity[1] /= density;
1537                                         colg[i][j][k].velocity[2] /= density;
1538                                 }
1539                         }
1540                 }
1541         }
1542
1543         /* calculate forces */
1544         for(v = 0; v < numverts; v++) {
1545                 i = HAIR_GRID_INDEX(lX[v], gmin, gmax, 0);
1546                 j = HAIR_GRID_INDEX(lX[v], gmin, gmax, 1);
1547                 k = HAIR_GRID_INDEX(lX[v], gmin, gmax, 2);
1548                 if (i < 0 || j < 0 || k < 0 || i > 10 || j >= 10 || k >= 10)
1549                         continue;
1550
1551                 lF[v][0] += smoothfac * (grid[i][j][k].velocity[0] - lV[v][0]);
1552                 lF[v][1] += smoothfac * (grid[i][j][k].velocity[1] - lV[v][1]);
1553                 lF[v][2] += smoothfac * (grid[i][j][k].velocity[2] - lV[v][2]);
1554
1555                 if(colg[i][j][k].density > 0.0f) {
1556                         lF[v][0] += collfac * (colg[i][j][k].velocity[0] - lV[v][0]);
1557                         lF[v][1] += collfac * (colg[i][j][k].velocity[1] - lV[v][1]);
1558                         lF[v][2] += collfac * (colg[i][j][k].velocity[2] - lV[v][2]);
1559                 }
1560         }
1561
1562         free_collider_cache(&colliders);
1563 }
1564
1565 static void cloth_calc_force(ClothModifierData *clmd, float UNUSED(frame), lfVector *lF, lfVector *lX, lfVector *lV, fmatrix3x3 *dFdV, fmatrix3x3 *dFdX, ListBase *effectors, float time, fmatrix3x3 *M)
1566 {
1567         /* Collect forces and derivatives:  F,dFdX,dFdV */
1568         Cloth           *cloth          = clmd->clothObject;
1569         unsigned int i  = 0;
1570         float           spring_air      = clmd->sim_parms->Cvi * 0.01f; /* viscosity of air scaled in percent */
1571         float           gravity[3] = {0.0f, 0.0f, 0.0f};
1572         float           tm2[3][3]       = {{0}};
1573         MFace           *mfaces         = cloth->mfaces;
1574         unsigned int numverts = cloth->numverts;
1575         LinkNode *search;
1576         lfVector *winvec;
1577         EffectedPoint epoint;
1578
1579         tm2[0][0]= tm2[1][1]= tm2[2][2]= -spring_air;
1580         
1581         /* global acceleration (gravitation) */
1582         if(clmd->scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
1583                 VECCOPY(gravity, clmd->scene->physics_settings.gravity);
1584                 mul_fvector_S(gravity, gravity, 0.001f * clmd->sim_parms->effector_weights->global_gravity); /* scale gravity force */
1585         }
1586
1587         /* set dFdX jacobi matrix to zero */
1588         init_bfmatrix(dFdX, ZERO);
1589         /* set dFdX jacobi matrix diagonal entries to -spring_air */ 
1590         initdiag_bfmatrix(dFdV, tm2);
1591
1592         init_lfvector(lF, gravity, numverts);
1593         
1594         if(clmd->sim_parms->velocity_smooth > 0.0f || clmd->sim_parms->collider_friction > 0.0f)
1595                 hair_velocity_smoothing(clmd, lF, lX, lV, numverts);
1596
1597         /* multiply lF with mass matrix
1598         // force = mass * acceleration (in this case: gravity)
1599         */
1600         for(i = 0; i < numverts; i++)
1601         {
1602                 float temp[3];
1603                 VECCOPY(temp, lF[i]);
1604                 mul_fmatrix_fvector(lF[i], M[i].m, temp);
1605         }
1606
1607         submul_lfvectorS(lF, lV, spring_air, numverts);
1608         
1609         /* handle external forces like wind */
1610         if(effectors)
1611         {       
1612                 // 0 = force, 1 = normalized force
1613                 winvec = create_lfvector(cloth->numverts);
1614                 
1615                 if(!winvec)
1616                         printf("winvec: out of memory in implicit.c\n");
1617                 
1618                 // precalculate wind forces
1619                 for(i = 0; i < cloth->numverts; i++)
1620                 {       
1621                         pd_point_from_loc(clmd->scene, (float*)lX[i], (float*)lV[i], i, &epoint);
1622                         pdDoEffectors(effectors, NULL, clmd->sim_parms->effector_weights, &epoint, winvec[i], NULL);
1623                 }
1624                 
1625                 for(i = 0; i < cloth->numfaces; i++)
1626                 {
1627                         float trinormal[3]={0,0,0}; // normalized triangle normal
1628                         float triunnormal[3]={0,0,0}; // not-normalized-triangle normal
1629                         float tmp[3]={0,0,0};
1630                         float factor = (mfaces[i].v4) ? 0.25 : 1.0 / 3.0;
1631                         factor *= 0.02;
1632                         
1633                         // calculate face normal
1634                         if(mfaces[i].v4)
1635                                 CalcFloat4(lX[mfaces[i].v1],lX[mfaces[i].v2],lX[mfaces[i].v3],lX[mfaces[i].v4],triunnormal);
1636                         else
1637                                 CalcFloat(lX[mfaces[i].v1],lX[mfaces[i].v2],lX[mfaces[i].v3],triunnormal);
1638
1639                         normalize_v3_v3(trinormal, triunnormal);
1640                         
1641                         // add wind from v1
1642                         VECCOPY(tmp, trinormal);
1643                         mul_v3_fl(tmp, calculateVertexWindForce(winvec[mfaces[i].v1], triunnormal));
1644                         VECADDS(lF[mfaces[i].v1], lF[mfaces[i].v1], tmp, factor);
1645                         
1646                         // add wind from v2
1647                         VECCOPY(tmp, trinormal);
1648                         mul_v3_fl(tmp, calculateVertexWindForce(winvec[mfaces[i].v2], triunnormal));
1649                         VECADDS(lF[mfaces[i].v2], lF[mfaces[i].v2], tmp, factor);
1650                         
1651                         // add wind from v3
1652                         VECCOPY(tmp, trinormal);
1653                         mul_v3_fl(tmp, calculateVertexWindForce(winvec[mfaces[i].v3], triunnormal));
1654                         VECADDS(lF[mfaces[i].v3], lF[mfaces[i].v3], tmp, factor);
1655                         
1656                         // add wind from v4
1657                         if(mfaces[i].v4)
1658                         {
1659                                 VECCOPY(tmp, trinormal);
1660                                 mul_v3_fl(tmp, calculateVertexWindForce(winvec[mfaces[i].v4], triunnormal));
1661                                 VECADDS(lF[mfaces[i].v4], lF[mfaces[i].v4], tmp, factor);
1662                         }
1663                 }
1664
1665                 /* Hair has only edges */
1666                 if(cloth->numfaces == 0) {
1667                         ClothSpring *spring;
1668                         float edgevec[3]={0,0,0}; //edge vector
1669                         float edgeunnormal[3]={0,0,0}; // not-normalized-edge normal
1670                         float tmp[3]={0,0,0};
1671                         float factor = 0.01;
1672
1673                         search = cloth->springs;
1674                         while(search) {
1675                                 spring = search->link;
1676                                 
1677                                 if(spring->type == CLOTH_SPRING_TYPE_STRUCTURAL) {
1678                                         VECSUB(edgevec, (float*)lX[spring->ij], (float*)lX[spring->kl]);
1679
1680                                         project_v3_v3v3(tmp, winvec[spring->ij], edgevec);
1681                                         VECSUB(edgeunnormal, winvec[spring->ij], tmp);
1682                                         /* hair doesn't stretch too much so we can use restlen pretty safely */
1683                                         VECADDS(lF[spring->ij], lF[spring->ij], edgeunnormal, spring->restlen * factor);
1684
1685                                         project_v3_v3v3(tmp, winvec[spring->kl], edgevec);
1686                                         VECSUB(edgeunnormal, winvec[spring->kl], tmp);
1687                                         VECADDS(lF[spring->kl], lF[spring->kl], edgeunnormal, spring->restlen * factor);
1688                                 }
1689
1690                                 search = search->next;
1691                         }
1692                 }
1693
1694                 del_lfvector(winvec);
1695         }
1696                 
1697         // calculate spring forces
1698         search = cloth->springs;
1699         while(search)
1700         {
1701                 // only handle active springs
1702                 // if(((clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED) && !(springs[i].flags & CSPRING_FLAG_DEACTIVATE))|| !(clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED)){}
1703                 cloth_calc_spring_force(clmd, search->link, lF, lX, lV, dFdV, dFdX, time);
1704
1705                 search = search->next;
1706         }
1707         
1708         // apply spring forces
1709         search = cloth->springs;
1710         while(search)
1711         {
1712                 // only handle active springs
1713                 // if(((clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED) && !(springs[i].flags & CSPRING_FLAG_DEACTIVATE))|| !(clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED))  
1714                 cloth_apply_spring_force(clmd, search->link, lF, lX, lV, dFdV, dFdX);
1715                 search = search->next;
1716         }
1717         // printf("\n");
1718 }
1719
1720 static void simulate_implicit_euler(lfVector *Vnew, lfVector *UNUSED(lX), lfVector *lV, lfVector *lF, fmatrix3x3 *dFdV, fmatrix3x3 *dFdX, float dt, fmatrix3x3 *A, lfVector *B, lfVector *dV, fmatrix3x3 *S, lfVector *z, lfVector *olddV, fmatrix3x3 *UNUSED(P), fmatrix3x3 *UNUSED(Pinv), fmatrix3x3 *M, fmatrix3x3 *UNUSED(bigI))
1721 {
1722         unsigned int numverts = dFdV[0].vcount;
1723
1724         lfVector *dFdXmV = create_lfvector(numverts);
1725         zero_lfvector(dV, numverts);
1726         
1727         cp_bfmatrix(A, M);
1728         
1729         subadd_bfmatrixS_bfmatrixS(A, dFdV, dt, dFdX, (dt*dt));
1730
1731         mul_bfmatrix_lfvector(dFdXmV, dFdX, lV);
1732
1733         add_lfvectorS_lfvectorS(B, lF, dt, dFdXmV, (dt*dt), numverts);
1734         
1735         itstart();
1736         
1737         cg_filtered(dV, A, B, z, S); /* conjugate gradient algorithm to solve Ax=b */
1738         // cg_filtered_pre(dV, A, B, z, S, P, Pinv, bigI);
1739         
1740         itend();
1741         // printf("cg_filtered calc time: %f\n", (float)itval());
1742         
1743         cp_lfvector(olddV, dV, numverts);
1744
1745         // advance velocities
1746         add_lfvector_lfvector(Vnew, lV, dV, numverts);
1747         
1748
1749         del_lfvector(dFdXmV);
1750 }
1751
1752 /*computes where the cloth would be if it were subject to perfectly stiff edges
1753   (edge distance constraints) in a lagrangian solver.  then add forces to help
1754   guide the implicit solver to that state.  this function is called after
1755   collisions*/
1756 int cloth_calc_helper_forces(Object *UNUSED(ob), ClothModifierData * clmd, float (*initial_cos)[3], float UNUSED(step), float dt)
1757 {
1758         Cloth *cloth= clmd->clothObject;
1759         float (*cos)[3] = MEM_callocN(sizeof(float)*3*cloth->numverts, "cos cloth_calc_helper_forces");
1760         float *masses = MEM_callocN(sizeof(float)*cloth->numverts, "cos cloth_calc_helper_forces");
1761         LinkNode *node;
1762         ClothSpring *spring;
1763         ClothVertex *cv;
1764         int i, steps;
1765         
1766         cv = cloth->verts;
1767         for (i=0; i<cloth->numverts; i++, cv++) {
1768                 copy_v3_v3(cos[i], cv->tx);
1769                 
1770                 if (cv->goal == 1.0f || len_v3v3(initial_cos[i], cv->tx) != 0.0) {
1771                         masses[i] = 1e+10;      
1772                 } else {
1773                         masses[i] = cv->mass;
1774                 }
1775         }
1776         
1777         steps = 55;
1778         for (i=0; i<steps; i++) {
1779                 for (node=cloth->springs; node; node=node->next) {
1780                         /* ClothVertex *cv1, *cv2; */ /* UNUSED */
1781                         int v1, v2;
1782                         float len, c, l, vec[3];
1783                         
1784                         spring = node->link;
1785                         if (spring->type != CLOTH_SPRING_TYPE_STRUCTURAL && spring->type != CLOTH_SPRING_TYPE_SHEAR) 
1786                                 continue;
1787                         
1788                         v1 = spring->ij; v2 = spring->kl;
1789                         /* cv1 = cloth->verts + v1; */ /* UNUSED */
1790                         /* cv2 = cloth->verts + v2; */ /* UNUSED */
1791                         len = len_v3v3(cos[v1], cos[v2]);
1792                         
1793                         sub_v3_v3v3(vec, cos[v1], cos[v2]);
1794                         normalize_v3(vec);
1795                         
1796                         c = (len - spring->restlen);
1797                         if (c == 0.0)
1798                                 continue;
1799                         
1800                         l = c / ((1.0/masses[v1]) + (1.0/masses[v2]));
1801                         
1802                         mul_v3_fl(vec, -(1.0/masses[v1])*l);
1803                         add_v3_v3(cos[v1], vec);
1804         
1805                         sub_v3_v3v3(vec, cos[v2], cos[v1]);
1806                         normalize_v3(vec);
1807                         
1808                         mul_v3_fl(vec, -(1.0/masses[v2])*l);
1809                         add_v3_v3(cos[v2], vec);
1810                 }
1811         }
1812         
1813         cv = cloth->verts;
1814         for (i=0; i<cloth->numverts; i++, cv++) {
1815                 float vec[3];
1816                 
1817                 /*compute forces*/
1818                 sub_v3_v3v3(vec, cos[i], cv->tx);
1819                 mul_v3_fl(vec, cv->mass*dt*20.0);
1820                 add_v3_v3(cv->tv, vec);
1821                 //copy_v3_v3(cv->tx, cos[i]);
1822         }
1823         
1824         MEM_freeN(cos);
1825         MEM_freeN(masses);
1826         
1827         return 1;
1828 }
1829 int implicit_solver (Object *ob, float frame, ClothModifierData *clmd, ListBase *effectors)
1830 {
1831         unsigned int i=0;
1832         float step=0.0f, tf=clmd->sim_parms->timescale;
1833         Cloth *cloth = clmd->clothObject;
1834         ClothVertex *verts = cloth->verts, *cv;
1835         unsigned int numverts = cloth->numverts;
1836         float dt = clmd->sim_parms->timescale / clmd->sim_parms->stepsPerFrame;
1837         float spf = (float)clmd->sim_parms->stepsPerFrame / clmd->sim_parms->timescale;
1838         float (*initial_cos)[3] = MEM_callocN(sizeof(float)*3*cloth->numverts, "initial_cos implicit.c");
1839         Implicit_Data *id = cloth->implicit;
1840         int do_extra_solve;
1841
1842         if(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL) /* do goal stuff */
1843         {
1844                 for(i = 0; i < numverts; i++)
1845                 {                       
1846                         // update velocities with constrained velocities from pinned verts
1847                         if(verts [i].flags & CLOTH_VERT_FLAG_PINNED)
1848                         {                       
1849                                 VECSUB(id->V[i], verts[i].xconst, verts[i].xold);
1850                                 // mul_v3_fl(id->V[i], clmd->sim_parms->stepsPerFrame);
1851                         }
1852                 }       
1853         }
1854         
1855         while(step < tf)
1856         {       
1857                 // calculate forces
1858                 cloth_calc_force(clmd, frame, id->F, id->X, id->V, id->dFdV, id->dFdX, effectors, step, id->M);
1859                 
1860                 // calculate new velocity
1861                 simulate_implicit_euler(id->Vnew, id->X, id->V, id->F, id->dFdV, id->dFdX, dt, id->A, id->B, id->dV, id->S, id->z, id->olddV, id->P, id->Pinv, id->M, id->bigI);
1862                 
1863                 // advance positions
1864                 add_lfvector_lfvectorS(id->Xnew, id->X, id->Vnew, dt, numverts);
1865                 
1866                 /* move pinned verts to correct position */
1867                 for(i = 0; i < numverts; i++)
1868                 {       
1869                         if(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL) 
1870                         {                       
1871                                 if(verts [i].flags & CLOTH_VERT_FLAG_PINNED)
1872                                 {                       
1873                                         float tvect[3] = {.0,.0,.0};
1874                                         VECSUB(tvect, verts[i].xconst, verts[i].xold);
1875                                         mul_fvector_S(tvect, tvect, step+dt);
1876                                         VECADD(tvect, tvect, verts[i].xold);
1877                                         VECCOPY(id->Xnew[i], tvect);
1878                                 }       
1879                         }
1880                         
1881                         VECCOPY(verts[i].txold, id->X[i]);
1882                 }
1883
1884                 if(clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_ENABLED && clmd->clothObject->bvhtree)
1885                 {
1886                         // collisions 
1887                         // itstart();
1888                         
1889                         // update verts to current positions
1890                         for(i = 0; i < numverts; i++)
1891                         {
1892                                 VECCOPY(verts[i].tx, id->Xnew[i]);
1893
1894                                 VECSUB(verts[i].tv, verts[i].tx, verts[i].txold);
1895                                 VECCOPY(verts[i].v, verts[i].tv);
1896                         }
1897
1898                         for (i=0, cv=cloth->verts; i<cloth->numverts; i++, cv++) {
1899                                 copy_v3_v3(initial_cos[i], cv->tx);
1900                         }
1901                         
1902                         // call collision function
1903                         // TODO: check if "step" or "step+dt" is correct - dg
1904                         do_extra_solve = cloth_bvh_objcollision(ob, clmd, step/clmd->sim_parms->timescale, dt/clmd->sim_parms->timescale);
1905                                                 
1906                         // copy corrected positions back to simulation
1907                         for(i = 0; i < numverts; i++)
1908                         {               
1909                                 // correct velocity again, just to be sure we had to change it due to adaptive collisions
1910                                 VECSUB(verts[i].tv, verts[i].tx, id->X[i]);
1911                         }
1912
1913                         //if (do_extra_solve)
1914                         //      cloth_calc_helper_forces(ob, clmd, initial_cos, step/clmd->sim_parms->timescale, dt/clmd->sim_parms->timescale);
1915                         
1916                         for(i = 0; i < numverts; i++)
1917                         {               
1918
1919                                 if(do_extra_solve)
1920                                 {
1921                                         
1922                                         if((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL) && (verts [i].flags & CLOTH_VERT_FLAG_PINNED))
1923                                                 continue;
1924
1925                                         VECCOPY(id->Xnew[i], verts[i].tx);
1926                                         VECCOPY(id->Vnew[i], verts[i].tv);
1927                                         mul_v3_fl(id->Vnew[i], spf);
1928                                 }
1929                         }
1930                         
1931                         // X = Xnew;
1932                         cp_lfvector(id->X, id->Xnew, numverts);
1933
1934                         // if there were collisions, advance the velocity from v_n+1/2 to v_n+1
1935                         
1936                         if(do_extra_solve)
1937                         {
1938                                 // V = Vnew;
1939                                 cp_lfvector(id->V, id->Vnew, numverts);
1940
1941                                 // calculate 
1942                                 cloth_calc_force(clmd, frame, id->F, id->X, id->V, id->dFdV, id->dFdX, effectors, step+dt, id->M);      
1943                                 
1944                                 simulate_implicit_euler(id->Vnew, id->X, id->V, id->F, id->dFdV, id->dFdX, dt / 2.0f, id->A, id->B, id->dV, id->S, id->z, id->olddV, id->P, id->Pinv, id->M, id->bigI);
1945                         }
1946                 }
1947                 else
1948                 {
1949                         // X = Xnew;
1950                         cp_lfvector(id->X, id->Xnew, numverts);
1951                 }
1952                 
1953                 // itend();
1954                 // printf("collision time: %f\n", (float)itval());
1955                 
1956                 // V = Vnew;
1957                 cp_lfvector(id->V, id->Vnew, numverts);
1958                 
1959                 step += dt;
1960         }
1961
1962         for(i = 0; i < numverts; i++)
1963         {                               
1964                 if((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL) && (verts [i].flags & CLOTH_VERT_FLAG_PINNED))
1965                 {
1966                         VECCOPY(verts[i].txold, verts[i].xconst); // TODO: test --> should be .x 
1967                         VECCOPY(verts[i].x, verts[i].xconst);
1968                         VECCOPY(verts[i].v, id->V[i]);
1969                 }
1970                 else
1971                 {
1972                         VECCOPY(verts[i].txold, id->X[i]);
1973                         VECCOPY(verts[i].x, id->X[i]);
1974                         VECCOPY(verts[i].v, id->V[i]);
1975                 }
1976         }
1977         
1978         MEM_freeN(initial_cos);
1979         
1980         return 1;
1981 }
1982
1983 void implicit_set_positions (ClothModifierData *clmd)
1984 {
1985         Cloth *cloth = clmd->clothObject;
1986         ClothVertex *verts = cloth->verts;
1987         unsigned int numverts = cloth->numverts, i;
1988         Implicit_Data *id = cloth->implicit;
1989         
1990         for(i = 0; i < numverts; i++)
1991         {                               
1992                 VECCOPY(id->X[i], verts[i].x);
1993                 VECCOPY(id->V[i], verts[i].v);
1994         }
1995         if(G.rt > 0)
1996                 printf("implicit_set_positions\n");     
1997 }
1998