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