2ea54ac1f032cec9e94504e372291b419b9df134
[blender-staging.git] / source / blender / blenkernel / intern / collision.c
1 /*  collision.c
2 *
3 *
4 * ***** BEGIN GPL LICENSE BLOCK *****
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 *
20 * The Original Code is Copyright (C) Blender Foundation
21 * All rights reserved.
22 *
23 * 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 "BKE_cloth.h"
33
34 #include "DNA_cloth_types.h"
35 #include "DNA_group_types.h"
36 #include "DNA_mesh_types.h"
37 #include "DNA_object_types.h"
38 #include "DNA_object_force.h"
39 #include "DNA_scene_types.h"
40
41 #include "BKE_DerivedMesh.h"
42 #include "BKE_global.h"
43 #include "BKE_mesh.h"
44 #include "BKE_object.h"
45 #include "BKE_modifier.h"
46 #include "BKE_utildefines.h"
47 #include "BKE_DerivedMesh.h"
48 #ifdef USE_BULLET
49 #include "Bullet-C-Api.h"
50 #endif
51 #include "BLI_kdopbvh.h"
52 #include "BKE_collision.h"
53
54
55 /***********************************
56 Collision modifier code start
57 ***********************************/
58
59 /* step is limited from 0 (frame start position) to 1 (frame end position) */
60 void collision_move_object ( CollisionModifierData *collmd, float step, float prevstep )
61 {
62         float tv[3] = {0,0,0};
63         unsigned int i = 0;
64
65         for ( i = 0; i < collmd->numverts; i++ )
66         {
67                 VECSUB ( tv, collmd->xnew[i].co, collmd->x[i].co );
68                 VECADDS ( collmd->current_x[i].co, collmd->x[i].co, tv, prevstep );
69                 VECADDS ( collmd->current_xnew[i].co, collmd->x[i].co, tv, step );
70                 VECSUB ( collmd->current_v[i].co, collmd->current_xnew[i].co, collmd->current_x[i].co );
71         }
72         bvhtree_update_from_mvert ( collmd->bvhtree, collmd->mfaces, collmd->numfaces, collmd->current_x, collmd->current_xnew, collmd->numverts, 1 );
73 }
74
75 BVHTree *bvhtree_build_from_mvert ( MFace *mfaces, unsigned int numfaces, MVert *x, unsigned int numverts, float epsilon )
76 {
77         BVHTree *tree;
78         float co[12];
79         int i;
80         MFace *tface = mfaces;
81
82         tree = BLI_bvhtree_new ( numfaces*2, epsilon, 4, 26 );
83
84         // fill tree
85         for ( i = 0; i < numfaces; i++, tface++ )
86         {
87                 VECCOPY ( &co[0*3], x[tface->v1].co );
88                 VECCOPY ( &co[1*3], x[tface->v2].co );
89                 VECCOPY ( &co[2*3], x[tface->v3].co );
90                 if ( tface->v4 )
91                         VECCOPY ( &co[3*3], x[tface->v4].co );
92
93                 BLI_bvhtree_insert ( tree, i, co, ( mfaces->v4 ? 4 : 3 ) );
94         }
95
96         // balance tree
97         BLI_bvhtree_balance ( tree );
98
99         return tree;
100 }
101
102 void bvhtree_update_from_mvert ( BVHTree * bvhtree, MFace *faces, int numfaces, MVert *x, MVert *xnew, int numverts, int moving )
103 {
104         int i;
105         MFace *mfaces = faces;
106         float co[12], co_moving[12];
107         int ret = 0;
108
109         if ( !bvhtree )
110                 return;
111
112         if ( x )
113         {
114                 for ( i = 0; i < numfaces; i++, mfaces++ )
115                 {
116                         VECCOPY ( &co[0*3], x[mfaces->v1].co );
117                         VECCOPY ( &co[1*3], x[mfaces->v2].co );
118                         VECCOPY ( &co[2*3], x[mfaces->v3].co );
119                         if ( mfaces->v4 )
120                                 VECCOPY ( &co[3*3], x[mfaces->v4].co );
121
122                         // copy new locations into array
123                         if ( moving && xnew )
124                         {
125                                 // update moving positions
126                                 VECCOPY ( &co_moving[0*3], xnew[mfaces->v1].co );
127                                 VECCOPY ( &co_moving[1*3], xnew[mfaces->v2].co );
128                                 VECCOPY ( &co_moving[2*3], xnew[mfaces->v3].co );
129                                 if ( mfaces->v4 )
130                                         VECCOPY ( &co_moving[3*3], xnew[mfaces->v4].co );
131
132                                 ret = BLI_bvhtree_update_node ( bvhtree, i, co, co_moving, ( mfaces->v4 ? 4 : 3 ) );
133                         }
134                         else
135                         {
136                                 ret = BLI_bvhtree_update_node ( bvhtree, i, co, NULL, ( mfaces->v4 ? 4 : 3 ) );
137                         }
138
139                         // check if tree is already full
140                         if ( !ret )
141                                 break;
142                 }
143
144                 BLI_bvhtree_update_tree ( bvhtree );
145         }
146 }
147
148 /***********************************
149 Collision modifier code end
150 ***********************************/
151
152 /**
153 * gsl_poly_solve_cubic -
154 *
155 * copied from SOLVE_CUBIC.C --> GSL
156 */
157
158 #define mySWAP(a,b) do { double tmp = b ; b = a ; a = tmp ; } while(0)
159
160 int 
161 gsl_poly_solve_cubic (double a, double b, double c, 
162                                           double *x0, double *x1, double *x2)
163 {
164         double q = (a * a - 3 * b);
165         double r = (2 * a * a * a - 9 * a * b + 27 * c);
166
167         double Q = q / 9;
168         double R = r / 54;
169
170         double Q3 = Q * Q * Q;
171         double R2 = R * R;
172
173         double CR2 = 729 * r * r;
174         double CQ3 = 2916 * q * q * q;
175
176         if (R == 0 && Q == 0)
177         {
178                 *x0 = - a / 3 ;
179                 *x1 = - a / 3 ;
180                 *x2 = - a / 3 ;
181                 return 3 ;
182         }
183         else if (CR2 == CQ3) 
184         {
185                 /* this test is actually R2 == Q3, written in a form suitable
186                 for exact computation with integers */
187
188                 /* Due to finite precision some double roots may be missed, and
189                 considered to be a pair of complex roots z = x +/- epsilon i
190                 close to the real axis. */
191
192                 double sqrtQ = sqrt (Q);
193
194                 if (R > 0)
195                 {
196                         *x0 = -2 * sqrtQ  - a / 3;
197                         *x1 = sqrtQ - a / 3;
198                         *x2 = sqrtQ - a / 3;
199                 }
200                 else
201                 {
202                         *x0 = - sqrtQ  - a / 3;
203                         *x1 = - sqrtQ - a / 3;
204                         *x2 = 2 * sqrtQ - a / 3;
205                 }
206                 return 3 ;
207         }
208         else if (CR2 < CQ3) /* equivalent to R2 < Q3 */
209         {
210                 double sqrtQ = sqrt (Q);
211                 double sqrtQ3 = sqrtQ * sqrtQ * sqrtQ;
212                 double theta = acos (R / sqrtQ3);
213                 double norm = -2 * sqrtQ;
214                 *x0 = norm * cos (theta / 3) - a / 3;
215                 *x1 = norm * cos ((theta + 2.0 * M_PI) / 3) - a / 3;
216                 *x2 = norm * cos ((theta - 2.0 * M_PI) / 3) - a / 3;
217
218                 /* Sort *x0, *x1, *x2 into increasing order */
219
220                 if (*x0 > *x1)
221                         mySWAP(*x0, *x1) ;
222
223                 if (*x1 > *x2)
224                 {
225                         mySWAP(*x1, *x2) ;
226
227                         if (*x0 > *x1)
228                                 mySWAP(*x0, *x1) ;
229                 }
230
231                 return 3;
232         }
233         else
234         {
235                 double sgnR = (R >= 0 ? 1 : -1);
236                 double A = -sgnR * pow (fabs (R) + sqrt (R2 - Q3), 1.0/3.0);
237                 double B = Q / A ;
238                 *x0 = A + B - a / 3;
239                 return 1;
240         }
241 }
242
243
244
245 /**
246 * gsl_poly_solve_quadratic
247 *
248 * copied from GSL
249 */
250 int 
251 gsl_poly_solve_quadratic (double a, double b, double c, 
252                                                   double *x0, double *x1)
253 {
254         double disc = b * b - 4 * a * c;
255
256         if (a == 0) /* Handle linear case */
257         {
258                 if (b == 0)
259                 {
260                         return 0;
261                 }
262                 else
263                 {
264                         *x0 = -c / b;
265                         return 1;
266                 };
267         }
268
269         if (disc > 0)
270         {
271                 if (b == 0)
272                 {
273                         double r = fabs (0.5 * sqrt (disc) / a);
274                         *x0 = -r;
275                         *x1 =  r;
276                 }
277                 else
278                 {
279                         double sgnb = (b > 0 ? 1 : -1);
280                         double temp = -0.5 * (b + sgnb * sqrt (disc));
281                         double r1 = temp / a ;
282                         double r2 = c / temp ;
283
284                         if (r1 < r2) 
285                         {
286                                 *x0 = r1 ;
287                                 *x1 = r2 ;
288                         } 
289                         else 
290                         {
291                                 *x0 = r2 ;
292                                 *x1 = r1 ;
293                         }
294                 }
295                 return 2;
296         }
297         else if (disc == 0) 
298         {
299                 *x0 = -0.5 * b / a ;
300                 *x1 = -0.5 * b / a ;
301                 return 2 ;
302         }
303         else
304         {
305                 return 0;
306         }
307 }
308
309
310
311
312 /*
313 * See Bridson et al. "Robust Treatment of Collision, Contact and Friction for Cloth Animation"
314 *     page 4, left column
315 */
316 static int cloth_get_collision_time ( double a[3], double b[3], double c[3], double d[3], double e[3], double f[3], double solution[3] )
317 {
318         int num_sols = 0;
319
320         // x^0 - checked 
321         double g =      a[0] * c[1] * e[2] - a[0] * c[2] * e[1] +
322                 a[1] * c[2] * e[0] - a[1] * c[0] * e[2] + 
323                 a[2] * c[0] * e[1] - a[2] * c[1] * e[0];
324
325         // x^1
326         double h = -b[2] * c[1] * e[0] + b[1] * c[2] * e[0] - a[2] * d[1] * e[0] +
327                 a[1] * d[2] * e[0] + b[2] * c[0] * e[1] - b[0] * c[2] * e[1] +
328                 a[2] * d[0] * e[1] - a[0] * d[2] * e[1] - b[1] * c[0] * e[2] +
329                 b[0] * c[1] * e[2] - a[1] * d[0] * e[2] + a[0] * d[1] * e[2] -
330                 a[2] * c[1] * f[0] + a[1] * c[2] * f[0] + a[2] * c[0] * f[1] -
331                 a[0] * c[2] * f[1] - a[1] * c[0] * f[2] + a[0] * c[1] * f[2];
332
333         // x^2
334         double i = -b[2] * d[1] * e[0] + b[1] * d[2] * e[0] +
335                 b[2] * d[0] * e[1] - b[0] * d[2] * e[1] -
336                 b[1] * d[0] * e[2] + b[0] * d[1] * e[2] -
337                 b[2] * c[1] * f[0] + b[1] * c[2] * f[0] -
338                 a[2] * d[1] * f[0] + a[1] * d[2] * f[0] +
339                 b[2] * c[0] * f[1] - b[0] * c[2] * f[1] + 
340                 a[2] * d[0] * f[1] - a[0] * d[2] * f[1] -
341                 b[1] * c[0] * f[2] + b[0] * c[1] * f[2] -
342                 a[1] * d[0] * f[2] + a[0] * d[1] * f[2];
343
344         // x^3 - checked
345         double j = -b[2] * d[1] * f[0] + b[1] * d[2] * f[0] +
346                 b[2] * d[0] * f[1] - b[0] * d[2] * f[1] -
347                 b[1] * d[0] * f[2] + b[0] * d[1] * f[2];
348
349         /*
350         printf("r1: %lf\n", a[0] * c[1] * e[2] - a[0] * c[2] * e[1]);
351         printf("r2: %lf\n", a[1] * c[2] * e[0] - a[1] * c[0] * e[2]);
352         printf("r3: %lf\n", a[2] * c[0] * e[1] - a[2] * c[1] * e[0]);
353
354         printf("x1 x: %f, y: %f, z: %f\n", a[0], a[1], a[2]);
355         printf("x2 x: %f, y: %f, z: %f\n", c[0], c[1], c[2]);
356         printf("x3 x: %f, y: %f, z: %f\n", e[0], e[1], e[2]);
357
358         printf("v1 x: %f, y: %f, z: %f\n", b[0], b[1], b[2]);
359         printf("v2 x: %f, y: %f, z: %f\n", d[0], d[1], d[2]);
360         printf("v3 x: %f, y: %f, z: %f\n", f[0], f[1], f[2]);
361
362         printf("t^3: %lf, t^2: %lf, t^1: %lf, t^0: %lf\n", j, i, h, g);
363         
364 */
365         // Solve cubic equation to determine times t1, t2, t3, when the collision will occur.
366         if ( ABS ( j ) > DBL_EPSILON )
367         {
368                 i /= j;
369                 h /= j;
370                 g /= j;
371                 num_sols = gsl_poly_solve_cubic ( i, h, g, &solution[0], &solution[1], &solution[2] );
372         }
373         else
374         {
375                 num_sols = gsl_poly_solve_quadratic ( i, h, g, &solution[0], &solution[1] );
376                 solution[2] = -1.0;
377         }
378
379         // printf("num_sols: %d, sol1: %lf, sol2: %lf, sol3: %lf\n", num_sols, solution[0],  solution[1],  solution[2]);
380
381         // Discard negative solutions
382         if ( ( num_sols >= 1 ) && ( solution[0] < DBL_EPSILON ) )
383         {
384                 --num_sols;
385                 solution[0] = solution[num_sols];
386         }
387         if ( ( num_sols >= 2 ) && ( solution[1] < DBL_EPSILON ) )
388         {
389                 --num_sols;
390                 solution[1] = solution[num_sols];
391         }
392         if ( ( num_sols == 3 ) && ( solution[2] < DBL_EPSILON ) )
393         {
394                 --num_sols;
395         }
396
397         // Sort
398         if ( num_sols == 2 )
399         {
400                 if ( solution[0] > solution[1] )
401                 {
402                         double tmp = solution[0];
403                         solution[0] = solution[1];
404                         solution[1] = tmp;
405                 }
406         }
407         else if ( num_sols == 3 )
408         {
409
410                 // Bubblesort
411                 if ( solution[0] > solution[1] )
412                 {
413                         double tmp = solution[0]; solution[0] = solution[1]; solution[1] = tmp;
414                 }
415                 if ( solution[1] > solution[2] )
416                 {
417                         double tmp = solution[1]; solution[1] = solution[2]; solution[2] = tmp;
418                 }
419                 if ( solution[0] > solution[1] )
420                 {
421                         double tmp = solution[0]; solution[0] = solution[1]; solution[1] = tmp;
422                 }
423         }
424
425         return num_sols;
426 }
427
428
429 // w3 is not perfect
430 static void collision_compute_barycentric ( float pv[3], float p1[3], float p2[3], float p3[3], float *w1, float *w2, float *w3 )
431 {
432         double  tempV1[3], tempV2[3], tempV4[3];
433         double  a,b,c,d,e,f;
434
435         VECSUB ( tempV1, p1, p3 );
436         VECSUB ( tempV2, p2, p3 );
437         VECSUB ( tempV4, pv, p3 );
438
439         a = INPR ( tempV1, tempV1 );
440         b = INPR ( tempV1, tempV2 );
441         c = INPR ( tempV2, tempV2 );
442         e = INPR ( tempV1, tempV4 );
443         f = INPR ( tempV2, tempV4 );
444
445         d = ( a * c - b * b );
446
447         if ( ABS ( d ) < ALMOST_ZERO )
448         {
449                 *w1 = *w2 = *w3 = 1.0 / 3.0;
450                 return;
451         }
452
453         w1[0] = ( float ) ( ( e * c - b * f ) / d );
454
455         if ( w1[0] < 0 )
456                 w1[0] = 0;
457
458         w2[0] = ( float ) ( ( f - b * ( double ) w1[0] ) / c );
459
460         if ( w2[0] < 0 )
461                 w2[0] = 0;
462
463         w3[0] = 1.0f - w1[0] - w2[0];
464 }
465
466 DO_INLINE void collision_interpolateOnTriangle ( float to[3], float v1[3], float v2[3], float v3[3], double w1, double w2, double w3 )
467 {
468         to[0] = to[1] = to[2] = 0;
469         VECADDMUL ( to, v1, w1 );
470         VECADDMUL ( to, v2, w2 );
471         VECADDMUL ( to, v3, w3 );
472 }
473
474
475 int cloth_collision_response_static ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end )
476 {
477         int result = 0;
478         Cloth *cloth1;
479         float w1, w2, w3, u1, u2, u3;
480         float v1[3], v2[3], relativeVelocity[3];
481         float magrelVel;
482         float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree );
483
484         cloth1 = clmd->clothObject;
485
486         for ( ; collpair != collision_end; collpair++ )
487         {
488                 // only handle static collisions here
489                 if ( collpair->flag & COLLISION_IN_FUTURE )
490                         continue;
491
492                 // compute barycentric coordinates for both collision points
493                 collision_compute_barycentric ( collpair->pa,
494                         cloth1->verts[collpair->ap1].txold,
495                         cloth1->verts[collpair->ap2].txold,
496                         cloth1->verts[collpair->ap3].txold,
497                         &w1, &w2, &w3 );
498
499                 // was: txold
500                 collision_compute_barycentric ( collpair->pb,
501                         collmd->current_x[collpair->bp1].co,
502                         collmd->current_x[collpair->bp2].co,
503                         collmd->current_x[collpair->bp3].co,
504                         &u1, &u2, &u3 );
505
506                 // Calculate relative "velocity".
507                 collision_interpolateOnTriangle ( v1, cloth1->verts[collpair->ap1].tv, cloth1->verts[collpair->ap2].tv, cloth1->verts[collpair->ap3].tv, w1, w2, w3 );
508
509                 collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
510
511                 VECSUB ( relativeVelocity, v2, v1 );
512
513                 // Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal').
514                 magrelVel = INPR ( relativeVelocity, collpair->normal );
515
516                 // printf("magrelVel: %f\n", magrelVel);
517
518                 // Calculate masses of points.
519                 // TODO
520
521                 // If v_n_mag < 0 the edges are approaching each other.
522                 if ( magrelVel > ALMOST_ZERO )
523                 {
524                         // Calculate Impulse magnitude to stop all motion in normal direction.
525                         float magtangent = 0, repulse = 0, d = 0;
526                         double impulse = 0.0;
527                         float vrel_t_pre[3];
528                         float temp[3];
529
530                         // calculate tangential velocity
531                         VECCOPY ( temp, collpair->normal );
532                         mul_v3_fl( temp, magrelVel );
533                         VECSUB ( vrel_t_pre, relativeVelocity, temp );
534
535                         // Decrease in magnitude of relative tangential velocity due to coulomb friction
536                         // in original formula "magrelVel" should be the "change of relative velocity in normal direction"
537                         magtangent = MIN2 ( clmd->coll_parms->friction * 0.01 * magrelVel,sqrt ( INPR ( vrel_t_pre,vrel_t_pre ) ) );
538
539                         // Apply friction impulse.
540                         if ( magtangent > ALMOST_ZERO )
541                         {
542                                 normalize_v3( vrel_t_pre );
543
544                                 impulse = magtangent / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); // 2.0 * 
545                                 VECADDMUL ( cloth1->verts[collpair->ap1].impulse, vrel_t_pre, w1 * impulse );
546                                 VECADDMUL ( cloth1->verts[collpair->ap2].impulse, vrel_t_pre, w2 * impulse );
547                                 VECADDMUL ( cloth1->verts[collpair->ap3].impulse, vrel_t_pre, w3 * impulse );
548                         }
549
550                         // Apply velocity stopping impulse
551                         // I_c = m * v_N / 2.0
552                         // no 2.0 * magrelVel normally, but looks nicer DG
553                         impulse =  magrelVel / ( 1.0 + w1*w1 + w2*w2 + w3*w3 );
554
555                         VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal, w1 * impulse );
556                         cloth1->verts[collpair->ap1].impulse_count++;
557
558                         VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal, w2 * impulse );
559                         cloth1->verts[collpair->ap2].impulse_count++;
560
561                         VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal, w3 * impulse );
562                         cloth1->verts[collpair->ap3].impulse_count++;
563
564                         // Apply repulse impulse if distance too short
565                         // I_r = -min(dt*kd, m(0,1d/dt - v_n))
566                         d = clmd->coll_parms->epsilon*8.0/9.0 + epsilon2*8.0/9.0 - collpair->distance;
567                         if ( ( magrelVel < 0.1*d*clmd->sim_parms->stepsPerFrame ) && ( d > ALMOST_ZERO ) )
568                         {
569                                 repulse = MIN2 ( d*1.0/clmd->sim_parms->stepsPerFrame, 0.1*d*clmd->sim_parms->stepsPerFrame - magrelVel );
570
571                                 // stay on the safe side and clamp repulse
572                                 if ( impulse > ALMOST_ZERO )
573                                         repulse = MIN2 ( repulse, 5.0*impulse );
574                                 repulse = MAX2 ( impulse, repulse );
575
576                                 impulse = repulse / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); // original 2.0 / 0.25
577                                 VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal,  impulse );
578                                 VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal,  impulse );
579                                 VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal,  impulse );
580                         }
581
582                         result = 1;
583                 }
584         }
585         return result;
586 }
587
588 //Determines collisions on overlap, collisions are writen to collpair[i] and collision+number_collision_found is returned
589 CollPair* cloth_collision ( ModifierData *md1, ModifierData *md2, BVHTreeOverlap *overlap, CollPair *collpair )
590 {
591         ClothModifierData *clmd = ( ClothModifierData * ) md1;
592         CollisionModifierData *collmd = ( CollisionModifierData * ) md2;
593         MFace *face1=NULL, *face2 = NULL;
594 #ifdef USE_BULLET
595         ClothVertex *verts1 = clmd->clothObject->verts;
596 #endif
597         double distance = 0;
598         float epsilon1 = clmd->coll_parms->epsilon;
599         float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree );
600         int i;
601
602         face1 = & ( clmd->clothObject->mfaces[overlap->indexA] );
603         face2 = & ( collmd->mfaces[overlap->indexB] );
604
605         // check all 4 possible collisions
606         for ( i = 0; i < 4; i++ )
607         {
608                 if ( i == 0 )
609                 {
610                         // fill faceA
611                         collpair->ap1 = face1->v1;
612                         collpair->ap2 = face1->v2;
613                         collpair->ap3 = face1->v3;
614
615                         // fill faceB
616                         collpair->bp1 = face2->v1;
617                         collpair->bp2 = face2->v2;
618                         collpair->bp3 = face2->v3;
619                 }
620                 else if ( i == 1 )
621                 {
622                         if ( face1->v4 )
623                         {
624                                 // fill faceA
625                                 collpair->ap1 = face1->v1;
626                                 collpair->ap2 = face1->v4;
627                                 collpair->ap3 = face1->v3;
628
629                                 // fill faceB
630                                 collpair->bp1 = face2->v1;
631                                 collpair->bp2 = face2->v2;
632                                 collpair->bp3 = face2->v3;
633                         }
634                         else
635                                 i++;
636                 }
637                 if ( i == 2 )
638                 {
639                         if ( face2->v4 )
640                         {
641                                 // fill faceA
642                                 collpair->ap1 = face1->v1;
643                                 collpair->ap2 = face1->v2;
644                                 collpair->ap3 = face1->v3;
645
646                                 // fill faceB
647                                 collpair->bp1 = face2->v1;
648                                 collpair->bp2 = face2->v4;
649                                 collpair->bp3 = face2->v3;
650                         }
651                         else
652                                 break;
653                 }
654                 else if ( i == 3 )
655                 {
656                         if ( face1->v4 && face2->v4 )
657                         {
658                                 // fill faceA
659                                 collpair->ap1 = face1->v1;
660                                 collpair->ap2 = face1->v4;
661                                 collpair->ap3 = face1->v3;
662
663                                 // fill faceB
664                                 collpair->bp1 = face2->v1;
665                                 collpair->bp2 = face2->v4;
666                                 collpair->bp3 = face2->v3;
667                         }
668                         else
669                                 break;
670                 }
671
672 #ifdef USE_BULLET
673                 // calc distance + normal
674                 distance = plNearestPoints (
675                         verts1[collpair->ap1].txold, verts1[collpair->ap2].txold, verts1[collpair->ap3].txold, collmd->current_x[collpair->bp1].co, collmd->current_x[collpair->bp2].co, collmd->current_x[collpair->bp3].co, collpair->pa,collpair->pb,collpair->vector );
676 #else
677                 // just be sure that we don't add anything
678                 distance = 2.0 * ( epsilon1 + epsilon2 + ALMOST_ZERO );
679 #endif
680
681                 if ( distance <= ( epsilon1 + epsilon2 + ALMOST_ZERO ) )
682                 {
683                         VECCOPY ( collpair->normal, collpair->vector );
684                         normalize_v3( collpair->normal );
685
686                         collpair->distance = distance;
687                         collpair->flag = 0;
688                         collpair++;
689                 }/*
690                 else
691                 {
692                         float w1, w2, w3, u1, u2, u3;
693                         float v1[3], v2[3], relativeVelocity[3];
694
695                         // calc relative velocity
696                         
697                         // compute barycentric coordinates for both collision points
698                         collision_compute_barycentric ( collpair->pa,
699                         verts1[collpair->ap1].txold,
700                         verts1[collpair->ap2].txold,
701                         verts1[collpair->ap3].txold,
702                         &w1, &w2, &w3 );
703
704                         // was: txold
705                         collision_compute_barycentric ( collpair->pb,
706                         collmd->current_x[collpair->bp1].co,
707                         collmd->current_x[collpair->bp2].co,
708                         collmd->current_x[collpair->bp3].co,
709                         &u1, &u2, &u3 );
710
711                         // Calculate relative "velocity".
712                         collision_interpolateOnTriangle ( v1, verts1[collpair->ap1].tv, verts1[collpair->ap2].tv, verts1[collpair->ap3].tv, w1, w2, w3 );
713
714                         collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
715
716                         VECSUB ( relativeVelocity, v2, v1 );
717
718                         if(sqrt(INPR(relativeVelocity, relativeVelocity)) >= distance)
719                         {
720                                 // check for collision in the future
721                                 collpair->flag |= COLLISION_IN_FUTURE;
722                                 collpair++;
723                         }
724                 }*/
725         }
726         return collpair;
727 }
728
729 #if 0
730 static int cloth_collision_response_moving( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end )
731 {
732         int result = 0;
733         Cloth *cloth1;
734         float w1, w2, w3, u1, u2, u3;
735         float v1[3], v2[3], relativeVelocity[3];
736         float magrelVel;
737
738         cloth1 = clmd->clothObject;
739
740         for ( ; collpair != collision_end; collpair++ )
741         {
742                 // compute barycentric coordinates for both collision points
743                 collision_compute_barycentric ( collpair->pa,
744                         cloth1->verts[collpair->ap1].txold,
745                         cloth1->verts[collpair->ap2].txold,
746                         cloth1->verts[collpair->ap3].txold,
747                         &w1, &w2, &w3 );
748
749                 // was: txold
750                 collision_compute_barycentric ( collpair->pb,
751                         collmd->current_x[collpair->bp1].co,
752                         collmd->current_x[collpair->bp2].co,
753                         collmd->current_x[collpair->bp3].co,
754                         &u1, &u2, &u3 );
755
756                 // Calculate relative "velocity".
757                 collision_interpolateOnTriangle ( v1, cloth1->verts[collpair->ap1].tv, cloth1->verts[collpair->ap2].tv, cloth1->verts[collpair->ap3].tv, w1, w2, w3 );
758
759                 collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
760
761                 VECSUB ( relativeVelocity, v2, v1 );
762
763                 // Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal').
764                 magrelVel = INPR ( relativeVelocity, collpair->normal );
765
766                 // printf("magrelVel: %f\n", magrelVel);
767
768                 // Calculate masses of points.
769                 // TODO
770
771                 // If v_n_mag < 0 the edges are approaching each other.
772                 if ( magrelVel > ALMOST_ZERO )
773                 {
774                         // Calculate Impulse magnitude to stop all motion in normal direction.
775                         float magtangent = 0;
776                         double impulse = 0.0;
777                         float vrel_t_pre[3];
778                         float temp[3];
779
780                         // calculate tangential velocity
781                         VECCOPY ( temp, collpair->normal );
782                         mul_v3_fl( temp, magrelVel );
783                         VECSUB ( vrel_t_pre, relativeVelocity, temp );
784
785                         // Decrease in magnitude of relative tangential velocity due to coulomb friction
786                         // in original formula "magrelVel" should be the "change of relative velocity in normal direction"
787                         magtangent = MIN2 ( clmd->coll_parms->friction * 0.01 * magrelVel,sqrt ( INPR ( vrel_t_pre,vrel_t_pre ) ) );
788
789                         // Apply friction impulse.
790                         if ( magtangent > ALMOST_ZERO )
791                         {
792                                 normalize_v3( vrel_t_pre );
793
794                                 impulse = 2.0 * magtangent / ( 1.0 + w1*w1 + w2*w2 + w3*w3 );
795                                 VECADDMUL ( cloth1->verts[collpair->ap1].impulse, vrel_t_pre, w1 * impulse );
796                                 VECADDMUL ( cloth1->verts[collpair->ap2].impulse, vrel_t_pre, w2 * impulse );
797                                 VECADDMUL ( cloth1->verts[collpair->ap3].impulse, vrel_t_pre, w3 * impulse );
798                         }
799
800                         // Apply velocity stopping impulse
801                         // I_c = m * v_N / 2.0
802                         // no 2.0 * magrelVel normally, but looks nicer DG
803                         impulse =  magrelVel / ( 1.0 + w1*w1 + w2*w2 + w3*w3 );
804
805                         VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal, w1 * impulse );
806                         cloth1->verts[collpair->ap1].impulse_count++;
807
808                         VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal, w2 * impulse );
809                         cloth1->verts[collpair->ap2].impulse_count++;
810
811                         VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal, w3 * impulse );
812                         cloth1->verts[collpair->ap3].impulse_count++;
813
814                         // Apply repulse impulse if distance too short
815                         // I_r = -min(dt*kd, m(0,1d/dt - v_n))
816                         /*
817                         d = clmd->coll_parms->epsilon*8.0/9.0 + epsilon2*8.0/9.0 - collpair->distance;
818                         if ( ( magrelVel < 0.1*d*clmd->sim_parms->stepsPerFrame ) && ( d > ALMOST_ZERO ) )
819                         {
820                         repulse = MIN2 ( d*1.0/clmd->sim_parms->stepsPerFrame, 0.1*d*clmd->sim_parms->stepsPerFrame - magrelVel );
821
822                         // stay on the safe side and clamp repulse
823                         if ( impulse > ALMOST_ZERO )
824                         repulse = MIN2 ( repulse, 5.0*impulse );
825                         repulse = MAX2 ( impulse, repulse );
826
827                         impulse = repulse / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); // original 2.0 / 0.25
828                         VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal,  impulse );
829                         VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal,  impulse );
830                         VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal,  impulse );
831                         }
832                         */
833                         result = 1;
834                 }
835         }
836         return result;
837 }
838 #endif
839
840 static float projectPointOntoLine(float *p, float *a, float *b) 
841 {
842    float ba[3], pa[3];
843    VECSUB(ba, b, a);
844    VECSUB(pa, p, a);
845    return INPR(pa, ba) / INPR(ba, ba);
846 }
847
848 static void calculateEENormal(float *np1, float *np2, float *np3, float *np4,float *out_normal) 
849 {
850         float line1[3], line2[3];
851         float length;
852
853         VECSUB(line1, np2, np1);
854         VECSUB(line2, np3, np1);
855
856         // printf("l1: %f, l1: %f, l2: %f, l2: %f\n", line1[0], line1[1], line2[0], line2[1]);
857
858         cross_v3_v3v3(out_normal, line1, line2);
859
860         
861
862         length = normalize_v3(out_normal);
863         if (length <= FLT_EPSILON)
864         { // lines are collinear
865                 VECSUB(out_normal, np2, np1);
866                 normalize_v3(out_normal);
867         }
868 }
869
870 static void findClosestPointsEE(float *x1, float *x2, float *x3, float *x4, float *w1, float *w2)
871 {
872         float temp[3], temp2[3];
873         
874         double a, b, c, e, f; 
875
876         VECSUB(temp, x2, x1);
877         a = INPR(temp, temp);
878
879         VECSUB(temp2, x4, x3);
880         b = -INPR(temp, temp2);
881
882         c = INPR(temp2, temp2);
883
884         VECSUB(temp2, x3, x1);
885         e = INPR(temp, temp2);
886
887         VECSUB(temp, x4, x3);
888         f = -INPR(temp, temp2);
889
890         *w1 = (e * c - b * f) / (a * c - b * b);
891         *w2 = (f - b * *w1) / c;
892
893 }
894
895 // calculates the distance of 2 edges
896 static float edgedge_distance(float np11[3], float np12[3], float np21[3], float np22[3], float *out_a1, float *out_a2, float *out_normal)
897 {
898         float line1[3], line2[3], cross[3];
899         float length;
900         float temp[3], temp2[3];
901         float dist_a1, dist_a2;
902         
903         VECSUB(line1, np12, np11);
904         VECSUB(line2, np22, np21);
905
906         cross_v3_v3v3(cross, line1, line2);
907         length = INPR(cross, cross);
908
909         if (length < FLT_EPSILON) 
910         {
911                 *out_a2 = projectPointOntoLine(np11, np21, np22);
912                 if ((*out_a2 >= -FLT_EPSILON) && (*out_a2 <= 1.0 + FLT_EPSILON)) 
913                 {
914                         *out_a1 = 0;
915                         calculateEENormal(np11, np12, np21, np22, out_normal);
916                         VECSUB(temp, np22, np21);
917                         mul_v3_fl(temp, *out_a2);
918                         VECADD(temp2, temp, np21);
919                         VECADD(temp2, temp2, np11);
920                         return INPR(temp2, temp2);
921                 }
922
923                 CLAMP(*out_a2, 0.0, 1.0);
924                 if (*out_a2 > .5) 
925                 { // == 1.0
926                         *out_a1 = projectPointOntoLine(np22, np11, np12);
927                         if ((*out_a1 >= -FLT_EPSILON) && (*out_a1 <= 1.0 + FLT_EPSILON)) 
928                         {
929                                 calculateEENormal(np11, np12, np21, np22, out_normal);
930
931                                 // return (np22 - (np11 + (np12 - np11) * out_a1)).lengthSquared();
932                                 VECSUB(temp, np12, np11);
933                                 mul_v3_fl(temp, *out_a1);
934                                 VECADD(temp2, temp, np11);
935                                 VECSUB(temp2, np22, temp2);
936                                 return INPR(temp2, temp2);
937                         }
938                 } 
939                 else 
940                 { // == 0.0
941                         *out_a1 = projectPointOntoLine(np21, np11, np12);
942                         if ((*out_a1 >= -FLT_EPSILON) && (*out_a1 <= 1.0 + FLT_EPSILON)) 
943                         {
944                                 calculateEENormal(np11, np11, np21, np22, out_normal);
945
946                                 // return (np21 - (np11 + (np12 - np11) * out_a1)).lengthSquared();
947                                 VECSUB(temp, np12, np11);
948                                 mul_v3_fl(temp, *out_a1);
949                                 VECADD(temp2, temp, np11);
950                                 VECSUB(temp2, np21, temp2);
951                                 return INPR(temp2, temp2);
952                         }
953                 }
954
955                 CLAMP(*out_a1, 0.0, 1.0);
956                 calculateEENormal(np11, np12, np21, np22, out_normal);
957                 if(*out_a1 > .5)
958                 {
959                         if(*out_a2 > .5)
960                         {
961                                 VECSUB(temp, np12, np22);
962                         }
963                         else
964                         {
965                                 VECSUB(temp, np12, np21);
966                         }
967                 }
968                 else
969                 {
970                         if(*out_a2 > .5)
971                         {
972                                 VECSUB(temp, np11, np22);
973                         }
974                         else
975                         {
976                                 VECSUB(temp, np11, np21);
977                         }
978                 }
979
980                 return INPR(temp, temp);
981         }
982         else
983         {
984                 
985                 // If the lines aren't parallel (but coplanar) they have to intersect
986
987                 findClosestPointsEE(np11, np12, np21, np22, out_a1, out_a2);
988
989                 // If both points are on the finite edges, we're done.
990                 if (*out_a1 >= 0.0 && *out_a1 <= 1.0 && *out_a2 >= 0.0 && *out_a2 <= 1.0) 
991                 {
992                         float p1[3], p2[3];
993                         
994                         // p1= np11 + (np12 - np11) * out_a1;
995                         VECSUB(temp, np12, np11);
996                         mul_v3_fl(temp, *out_a1);
997                         VECADD(p1, np11, temp);
998                         
999                         // p2 = np21 + (np22 - np21) * out_a2;
1000                         VECSUB(temp, np22, np21);
1001                         mul_v3_fl(temp, *out_a2);
1002                         VECADD(p2, np21, temp);
1003
1004                         calculateEENormal(np11, np12, np21, np22, out_normal);
1005                         VECSUB(temp, p1, p2);
1006                         return INPR(temp, temp);
1007                 }
1008
1009                 
1010                 /*
1011                 * Clamp both points to the finite edges.
1012                 * The one that moves most during clamping is one part of the solution.
1013                 */
1014                 dist_a1 = *out_a1;
1015                 CLAMP(dist_a1, 0.0, 1.0);
1016                 dist_a2 = *out_a2;
1017                 CLAMP(dist_a2, 0.0, 1.0);
1018
1019                 // Now project the "most clamped" point on the other line.
1020                 if (dist_a1 > dist_a2) 
1021                 { 
1022                         /* keep out_a1 */
1023                         float p1[3];
1024
1025                         // p1 = np11 + (np12 - np11) * out_a1;
1026                         VECSUB(temp, np12, np11);
1027                         mul_v3_fl(temp, *out_a1);
1028                         VECADD(p1, np11, temp);
1029
1030                         *out_a2 = projectPointOntoLine(p1, np21, np22);
1031                         CLAMP(*out_a2, 0.0, 1.0);
1032
1033                         calculateEENormal(np11, np12, np21, np22, out_normal);
1034
1035                         // return (p1 - (np21 + (np22 - np21) * out_a2)).lengthSquared();
1036                         VECSUB(temp, np22, np21);
1037                         mul_v3_fl(temp, *out_a2);
1038                         VECADD(temp, temp, np21);
1039                         VECSUB(temp, p1, temp);
1040                         return INPR(temp, temp);
1041                 } 
1042                 else 
1043                 {       
1044                         /* keep out_a2 */
1045                         float p2[3];
1046                         
1047                         // p2 = np21 + (np22 - np21) * out_a2;
1048                         VECSUB(temp, np22, np21);
1049                         mul_v3_fl(temp, *out_a2);
1050                         VECADD(p2, np21, temp);
1051
1052                         *out_a1 = projectPointOntoLine(p2, np11, np12);
1053                         CLAMP(*out_a1, 0.0, 1.0);
1054
1055                         calculateEENormal(np11, np12, np21, np22, out_normal);
1056                         
1057                         // return ((np11 + (np12 - np11) * out_a1) - p2).lengthSquared();
1058                         VECSUB(temp, np12, np11);
1059                         mul_v3_fl(temp, *out_a1);
1060                         VECADD(temp, temp, np11);
1061                         VECSUB(temp, temp, p2);
1062                         return INPR(temp, temp);
1063                 }
1064         }
1065         
1066         printf("Error in edgedge_distance: end of function\n");
1067         return 0;
1068 }
1069
1070 #if 0
1071 static int cloth_collision_moving_edges ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair )
1072 {
1073         EdgeCollPair edgecollpair;
1074         Cloth *cloth1=NULL;
1075         ClothVertex *verts1=NULL;
1076         unsigned int i = 0, k = 0;
1077         int numsolutions = 0;
1078         double x1[3], v1[3], x2[3], v2[3], x3[3], v3[3];
1079         double solution[3], solution2[3];
1080         MVert *verts2 = collmd->current_x; // old x
1081         MVert *velocity2 = collmd->current_v; // velocity
1082         float distance = 0;
1083         float triA[3][3], triB[3][3];
1084         int result = 0;
1085
1086         cloth1 = clmd->clothObject;
1087         verts1 = cloth1->verts;
1088
1089         for(i = 0; i < 9; i++)
1090         {
1091                 // 9 edge - edge possibilities
1092
1093                 if(i == 0) // cloth edge: 1-2; coll edge: 1-2
1094                 {
1095                         edgecollpair.p11 = collpair->ap1;
1096                         edgecollpair.p12 = collpair->ap2;
1097
1098                         edgecollpair.p21 = collpair->bp1;
1099                         edgecollpair.p22 = collpair->bp2;
1100                 }
1101                 else if(i == 1) // cloth edge: 1-2; coll edge: 2-3
1102                 {
1103                         edgecollpair.p11 = collpair->ap1;
1104                         edgecollpair.p12 = collpair->ap2;
1105
1106                         edgecollpair.p21 = collpair->bp2;
1107                         edgecollpair.p22 = collpair->bp3;
1108                 }
1109                 else if(i == 2) // cloth edge: 1-2; coll edge: 1-3
1110                 {
1111                         edgecollpair.p11 = collpair->ap1;
1112                         edgecollpair.p12 = collpair->ap2;
1113
1114                         edgecollpair.p21 = collpair->bp1;
1115                         edgecollpair.p22 = collpair->bp3;
1116                 }
1117                 else if(i == 3) // cloth edge: 2-3; coll edge: 1-2
1118                 {
1119                         edgecollpair.p11 = collpair->ap2;
1120                         edgecollpair.p12 = collpair->ap3;
1121
1122                         edgecollpair.p21 = collpair->bp1;
1123                         edgecollpair.p22 = collpair->bp2;
1124                 }
1125                 else if(i == 4) // cloth edge: 2-3; coll edge: 2-3
1126                 {
1127                         edgecollpair.p11 = collpair->ap2;
1128                         edgecollpair.p12 = collpair->ap3;
1129
1130                         edgecollpair.p21 = collpair->bp2;
1131                         edgecollpair.p22 = collpair->bp3;
1132                 }
1133                 else if(i == 5) // cloth edge: 2-3; coll edge: 1-3
1134                 {
1135                         edgecollpair.p11 = collpair->ap2;
1136                         edgecollpair.p12 = collpair->ap3;
1137
1138                         edgecollpair.p21 = collpair->bp1;
1139                         edgecollpair.p22 = collpair->bp3;
1140                 }
1141                 else if(i ==6) // cloth edge: 1-3; coll edge: 1-2
1142                 {
1143                         edgecollpair.p11 = collpair->ap1;
1144                         edgecollpair.p12 = collpair->ap3;
1145
1146                         edgecollpair.p21 = collpair->bp1;
1147                         edgecollpair.p22 = collpair->bp2;
1148                 }
1149                 else if(i ==7) // cloth edge: 1-3; coll edge: 2-3
1150                 {
1151                         edgecollpair.p11 = collpair->ap1;
1152                         edgecollpair.p12 = collpair->ap3;
1153
1154                         edgecollpair.p21 = collpair->bp2;
1155                         edgecollpair.p22 = collpair->bp3;
1156                 }
1157                 else if(i == 8) // cloth edge: 1-3; coll edge: 1-3
1158                 {
1159                         edgecollpair.p11 = collpair->ap1;
1160                         edgecollpair.p12 = collpair->ap3;
1161
1162                         edgecollpair.p21 = collpair->bp1;
1163                         edgecollpair.p22 = collpair->bp3;
1164                 }
1165                 /*
1166                 if((edgecollpair.p11 == 3) && (edgecollpair.p12 == 16))
1167                         printf("Ahier!\n");
1168                 if((edgecollpair.p11 == 16) && (edgecollpair.p12 == 3))
1169                         printf("Ahier!\n");
1170                 */
1171
1172                 // if ( !cloth_are_edges_adjacent ( clmd, collmd, &edgecollpair ) )
1173                 {
1174                         // always put coll points in p21/p22
1175                         VECSUB ( x1, verts1[edgecollpair.p12].txold, verts1[edgecollpair.p11].txold );
1176                         VECSUB ( v1, verts1[edgecollpair.p12].tv, verts1[edgecollpair.p11].tv );
1177
1178                         VECSUB ( x2, verts2[edgecollpair.p21].co, verts1[edgecollpair.p11].txold );
1179                         VECSUB ( v2, velocity2[edgecollpair.p21].co, verts1[edgecollpair.p11].tv );
1180
1181                         VECSUB ( x3, verts2[edgecollpair.p22].co, verts1[edgecollpair.p11].txold );
1182                         VECSUB ( v3, velocity2[edgecollpair.p22].co, verts1[edgecollpair.p11].tv );
1183
1184                         numsolutions = cloth_get_collision_time ( x1, v1, x2, v2, x3, v3, solution );
1185
1186                         if((edgecollpair.p11 == 3 && edgecollpair.p12==16)|| (edgecollpair.p11==16 && edgecollpair.p12==3))
1187                         {
1188                                 if(edgecollpair.p21==6 || edgecollpair.p22 == 6)
1189                                 {
1190                                         printf("dist: %f, sol[k]: %lf, sol2[k]: %lf\n", distance, solution[k], solution2[k]);
1191                                         printf("a1: %f, a2: %f, b1: %f, b2: %f\n", x1[0], x2[0], x3[0], v1[0]);
1192                                         printf("b21: %d, b22: %d\n", edgecollpair.p21, edgecollpair.p22);
1193                                 }
1194                         }
1195
1196                         for ( k = 0; k < numsolutions; k++ )
1197                         {
1198                                 // printf("sol %d: %lf\n", k, solution[k]);
1199                                 if ( ( solution[k] >= ALMOST_ZERO ) && ( solution[k] <= 1.0 ) && ( solution[k] >  ALMOST_ZERO))
1200                                 {
1201                                         float a,b;
1202                                         float out_normal[3];
1203                                         float distance;
1204                                         float impulse = 0;
1205                                         float I_mag;
1206
1207                                         // move verts
1208                                         VECADDS(triA[0], verts1[edgecollpair.p11].txold, verts1[edgecollpair.p11].tv, solution[k]);
1209                                         VECADDS(triA[1], verts1[edgecollpair.p12].txold, verts1[edgecollpair.p12].tv, solution[k]);
1210
1211                                         VECADDS(triB[0], collmd->current_x[edgecollpair.p21].co, collmd->current_v[edgecollpair.p21].co, solution[k]);
1212                                         VECADDS(triB[1], collmd->current_x[edgecollpair.p22].co, collmd->current_v[edgecollpair.p22].co, solution[k]);
1213
1214                                         // TODO: check for collisions
1215                                         distance = edgedge_distance(triA[0], triA[1], triB[0], triB[1], &a, &b, out_normal);
1216                                         
1217                                         if ((distance <= clmd->coll_parms->epsilon + BLI_bvhtree_getepsilon ( collmd->bvhtree ) + ALMOST_ZERO) && (INPR(out_normal, out_normal) > 0))
1218                                         {
1219                                                 float vrel_1_to_2[3], temp[3], temp2[3], out_normalVelocity;
1220                                                 float desiredVn;
1221
1222                                                 VECCOPY(vrel_1_to_2, verts1[edgecollpair.p11].tv);
1223                                                 mul_v3_fl(vrel_1_to_2, 1.0 - a);
1224                                                 VECCOPY(temp, verts1[edgecollpair.p12].tv);
1225                                                 mul_v3_fl(temp, a);
1226
1227                                                 VECADD(vrel_1_to_2, vrel_1_to_2, temp);
1228
1229                                                 VECCOPY(temp, verts1[edgecollpair.p21].tv);
1230                                                 mul_v3_fl(temp, 1.0 - b);
1231                                                 VECCOPY(temp2, verts1[edgecollpair.p22].tv);
1232                                                 mul_v3_fl(temp2, b);
1233                                                 VECADD(temp, temp, temp2);
1234
1235                                                 VECSUB(vrel_1_to_2, vrel_1_to_2, temp);
1236
1237                                                 out_normalVelocity = INPR(vrel_1_to_2, out_normal);
1238 /*
1239                                                 // this correction results in wrong normals sometimes?
1240                                                 if(out_normalVelocity < 0.0)
1241                                                 {
1242                                                         out_normalVelocity*= -1.0;
1243                                                         negate_v3(out_normal);
1244                                                 }
1245 */
1246                                                 /* Inelastic repulsion impulse. */
1247
1248                                                 // Calculate which normal velocity we need. 
1249                                                 desiredVn = (out_normalVelocity * (float)solution[k] - (.1 * (clmd->coll_parms->epsilon + BLI_bvhtree_getepsilon ( collmd->bvhtree )) - sqrt(distance)) - ALMOST_ZERO);
1250
1251                                                 // Now calculate what impulse we need to reach that velocity. 
1252                                                 I_mag = (out_normalVelocity - desiredVn) / 2.0; // / (1/m1 + 1/m2);
1253
1254                                                 // Finally apply that impulse. 
1255                                                 impulse = (2.0 * -I_mag) / (a*a + (1.0-a)*(1.0-a) + b*b + (1.0-b)*(1.0-b));
1256
1257                                                 VECADDMUL ( verts1[edgecollpair.p11].impulse, out_normal, (1.0-a) * impulse );
1258                                                 verts1[edgecollpair.p11].impulse_count++;
1259
1260                                                 VECADDMUL ( verts1[edgecollpair.p12].impulse, out_normal, a * impulse );
1261                                                 verts1[edgecollpair.p12].impulse_count++;
1262
1263                                                 // return true;
1264                                                 result = 1;
1265                                                 break;
1266                                         }
1267                                         else
1268                                         {
1269                                                 // missing from collision.hpp
1270                                         }
1271                                         // mintime = MIN2(mintime, (float)solution[k]);
1272
1273                                         break;
1274                                 }
1275                         }
1276                 }
1277         }
1278         return result;
1279 }
1280
1281 static int cloth_collision_moving ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end )
1282 {
1283         Cloth *cloth1;
1284         cloth1 = clmd->clothObject;
1285
1286         for ( ; collpair != collision_end; collpair++ )
1287         {
1288                 // only handle moving collisions here
1289                 if (!( collpair->flag & COLLISION_IN_FUTURE ))
1290                         continue;
1291
1292                 cloth_collision_moving_edges ( clmd, collmd, collpair);
1293                 // cloth_collision_moving_tris ( clmd, collmd, collpair);
1294         }
1295
1296         return 1;
1297 }
1298 #endif
1299
1300
1301 // return all collision objects in scene
1302 // collision object will exclude self 
1303 Object **get_collisionobjects(Scene *scene, Object *self, int *numcollobj)
1304 {
1305         Base *base=NULL;
1306         Object **objs = NULL;
1307         Object *coll_ob = NULL;
1308         CollisionModifierData *collmd = NULL;
1309         int numobj = 0, maxobj = 100;
1310         
1311         objs = MEM_callocN(sizeof(Object *)*maxobj, "CollisionObjectsArray");
1312         // check all collision objects
1313         for ( base = scene->base.first; base; base = base->next )
1314         {
1315                 /*Only proceed for mesh object in same layer */
1316                 if(!(base->object->type==OB_MESH && (base->lay & self->lay))) 
1317                         continue;
1318                 
1319                 coll_ob = base->object;
1320                 
1321                 if(coll_ob == self)
1322                                 continue;
1323                 
1324                 if(coll_ob->pd && coll_ob->pd->deflect)
1325                 {
1326                         collmd = ( CollisionModifierData * ) modifiers_findByType ( coll_ob, eModifierType_Collision );
1327                 }
1328                 else
1329                         collmd = NULL;
1330                 
1331                 if ( collmd )
1332                 {       
1333                         if(numobj >= maxobj)
1334                         {
1335                                 // realloc
1336                                 int oldmax = maxobj;
1337                                 Object **tmp;
1338                                 maxobj *= 2;
1339                                 tmp = MEM_callocN(sizeof(Object *)*maxobj, "CollisionObjectsArray");
1340                                 memcpy(tmp, objs, sizeof(Object *)*oldmax);
1341                                 MEM_freeN(objs);
1342                                 objs = tmp;
1343                                 
1344                         }
1345                         
1346                         objs[numobj] = coll_ob;
1347                         numobj++;
1348                 }
1349                 else
1350                 {
1351                         if ( coll_ob->dup_group )
1352                         {
1353                                 GroupObject *go;
1354                                 Group *group = coll_ob->dup_group;
1355
1356                                 for ( go= group->gobject.first; go; go= go->next )
1357                                 {
1358                                         coll_ob = go->ob;
1359                                         collmd = NULL;
1360                                         
1361                                         if(coll_ob == self)
1362                                                 continue;
1363                                         
1364                                         if(coll_ob->pd && coll_ob->pd->deflect)
1365                                         {
1366                                                 collmd = ( CollisionModifierData * ) modifiers_findByType ( coll_ob, eModifierType_Collision );
1367                                         }
1368                                         else
1369                                                 collmd = NULL;
1370
1371                                         if ( !collmd )
1372                                                 continue;
1373                                         
1374                                         if( !collmd->bvhtree)
1375                                                 continue;
1376
1377                                         if(numobj >= maxobj)
1378                                         {
1379                                                 // realloc
1380                                                 int oldmax = maxobj;
1381                                                 Object **tmp;
1382                                                 maxobj *= 2;
1383                                                 tmp = MEM_callocN(sizeof(Object *)*maxobj, "CollisionObjectsArray");
1384                                                 memcpy(tmp, objs, sizeof(Object *)*oldmax);
1385                                                 MEM_freeN(objs);
1386                                                 objs = tmp;
1387                                         }
1388                                         
1389                                         objs[numobj] = coll_ob;
1390                                         numobj++;
1391                                 }
1392                         }
1393                 }       
1394         }
1395         *numcollobj = numobj;
1396         return objs;
1397 }
1398
1399 ListBase *get_collider_cache(Scene *scene, Object *self)
1400 {
1401         Base *base=NULL;
1402         ListBase *objs = NULL;
1403         Object *coll_ob = NULL;
1404         CollisionModifierData *collmd = NULL;
1405         ColliderCache *col;
1406         
1407         // check all collision objects
1408         for ( base = scene->base.first; base; base = base->next )
1409         {
1410                 /*Only proceed for mesh object in same layer */
1411                 if(base->object->type!=OB_MESH)
1412                         continue;
1413
1414                 if(self && (base->lay & self->lay)==0) 
1415                         continue;
1416
1417                 
1418                 coll_ob = base->object;
1419                 
1420                 if(coll_ob == self)
1421                                 continue;
1422                 
1423                 if(coll_ob->pd && coll_ob->pd->deflect)
1424                 {
1425                         collmd = ( CollisionModifierData * ) modifiers_findByType ( coll_ob, eModifierType_Collision );
1426                 }
1427                 else
1428                         collmd = NULL;
1429                 
1430                 if ( collmd )
1431                 {       
1432                         if(objs == NULL)
1433                                 objs = MEM_callocN(sizeof(ListBase), "ColliderCache array");
1434
1435                         col = MEM_callocN(sizeof(ColliderCache), "ColliderCache");
1436                         col->ob = coll_ob;
1437                         col->collmd = collmd;
1438                         /* make sure collider is properly set up */
1439                         collision_move_object(collmd, 1.0, 0.0);
1440                         BLI_addtail(objs, col);
1441                 }
1442                 else if ( coll_ob->dup_group )
1443                         {
1444                                 GroupObject *go;
1445                                 Group *group = coll_ob->dup_group;
1446
1447                                 for ( go= group->gobject.first; go; go= go->next )
1448                                 {
1449                                         coll_ob = go->ob;
1450                                         collmd = NULL;
1451                                         
1452                                         if(coll_ob == self)
1453                                                 continue;
1454                                         
1455                                         if(coll_ob->pd && coll_ob->pd->deflect)
1456                                         {
1457                                                 collmd = ( CollisionModifierData * ) modifiers_findByType ( coll_ob, eModifierType_Collision );
1458                                         }
1459                                         else
1460                                                 collmd = NULL;
1461
1462                                         if ( !collmd )
1463                                                 continue;
1464                                         
1465                                         if( !collmd->bvhtree)
1466                                                 continue;
1467
1468                                         if(objs == NULL)
1469                                                 objs = MEM_callocN(sizeof(ListBase), "ColliderCache array");
1470
1471                                         col = MEM_callocN(sizeof(ColliderCache), "ColliderCache");
1472                                         col->ob = coll_ob;
1473                                         col->collmd = collmd;
1474                                         /* make sure collider is properly set up */
1475                                         collision_move_object(collmd, 1.0, 0.0);
1476                                         BLI_addtail(objs, col);
1477                                 }
1478                         }
1479         }
1480         return objs;
1481 }
1482 void free_collider_cache(ListBase **colliders)
1483 {
1484         if(*colliders) {
1485                 BLI_freelistN(*colliders);
1486                 MEM_freeN(*colliders);
1487                 *colliders = NULL;
1488         }
1489 }
1490 static void cloth_bvh_objcollisions_nearcheck ( ClothModifierData * clmd, CollisionModifierData *collmd, CollPair **collisions, CollPair **collisions_index, int numresult, BVHTreeOverlap *overlap)
1491 {
1492         int i;
1493         
1494         *collisions = ( CollPair* ) MEM_mallocN ( sizeof ( CollPair ) * numresult * 4, "collision array" ); //*4 since cloth_collision_static can return more than 1 collision
1495         *collisions_index = *collisions;
1496
1497         for ( i = 0; i < numresult; i++ )
1498         {
1499                 *collisions_index = cloth_collision ( ( ModifierData * ) clmd, ( ModifierData * ) collmd, overlap+i, *collisions_index );
1500         }
1501 }
1502
1503 static int cloth_bvh_objcollisions_resolve ( ClothModifierData * clmd, CollisionModifierData *collmd, CollPair *collisions, CollPair *collisions_index)
1504 {
1505         Cloth *cloth = clmd->clothObject;
1506         int i=0, j = 0, numfaces = 0, numverts = 0;
1507         ClothVertex *verts = NULL;
1508         int ret = 0;
1509         int result = 0;
1510         float tnull[3] = {0,0,0};
1511         
1512         numfaces = clmd->clothObject->numfaces;
1513         numverts = clmd->clothObject->numverts;
1514  
1515         verts = cloth->verts;
1516         
1517         // process all collisions (calculate impulses, TODO: also repulses if distance too short)
1518         result = 1;
1519         for ( j = 0; j < 5; j++ ) // 5 is just a value that ensures convergence
1520         {
1521                 result = 0;
1522
1523                 if ( collmd->bvhtree )
1524                 {
1525                         result += cloth_collision_response_static ( clmd, collmd, collisions, collisions_index );
1526
1527                         // apply impulses in parallel
1528                         if ( result )
1529                         {
1530                                 for ( i = 0; i < numverts; i++ )
1531                                 {
1532                                         // calculate "velocities" (just xnew = xold + v; no dt in v)
1533                                         if ( verts[i].impulse_count )
1534                                         {
1535                                                 VECADDMUL ( verts[i].tv, verts[i].impulse, 1.0f / verts[i].impulse_count );
1536                                                 VECCOPY ( verts[i].impulse, tnull );
1537                                                 verts[i].impulse_count = 0;
1538
1539                                                 ret++;
1540                                         }
1541                                 }
1542                         }
1543                 }
1544         }
1545         return ret;
1546 }
1547
1548 // cloth - object collisions
1549 int cloth_bvh_objcollision (Object *ob, ClothModifierData * clmd, float step, float dt )
1550 {
1551         Cloth *cloth=NULL;
1552         BVHTree *cloth_bvh=NULL;
1553         int i=0, numfaces = 0, numverts = 0, k, l, j;
1554         int rounds = 0; // result counts applied collisions; ic is for debug output;
1555         ClothVertex *verts = NULL;
1556         int ret = 0, ret2 = 0;
1557         Object **collobjs = NULL;
1558         int numcollobj = 0;
1559
1560         if ( ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_COLLOBJ ) || ! ( ( ( Cloth * ) clmd->clothObject )->bvhtree ) )
1561         {
1562                 return 0;
1563         }
1564
1565         cloth = clmd->clothObject;
1566         verts = cloth->verts;
1567         cloth_bvh = ( BVHTree * ) cloth->bvhtree;
1568         numfaces = clmd->clothObject->numfaces;
1569         numverts = clmd->clothObject->numverts;
1570
1571         ////////////////////////////////////////////////////////////
1572         // static collisions
1573         ////////////////////////////////////////////////////////////
1574
1575         // update cloth bvh
1576         bvhtree_update_from_cloth ( clmd, 1 ); // 0 means STATIC, 1 means MOVING (see later in this function)
1577         bvhselftree_update_from_cloth ( clmd, 0 ); // 0 means STATIC, 1 means MOVING (see later in this function)
1578         
1579         collobjs = get_collisionobjects(clmd->scene, ob, &numcollobj);
1580         
1581         if(!collobjs)
1582                 return 0;
1583
1584         do
1585         {
1586                 CollPair **collisions, **collisions_index;
1587                 
1588                 ret2 = 0;
1589
1590                 collisions = MEM_callocN(sizeof(CollPair *) *numcollobj , "CollPair");
1591                 collisions_index = MEM_callocN(sizeof(CollPair *) *numcollobj , "CollPair");
1592                 
1593                 // check all collision objects
1594                 for(i = 0; i < numcollobj; i++)
1595                 {
1596                         Object *collob= collobjs[i];
1597                         CollisionModifierData *collmd = (CollisionModifierData*)modifiers_findByType(collob, eModifierType_Collision);
1598                         BVHTreeOverlap *overlap = NULL;
1599                         int result = 0;
1600                         
1601                         if(!collmd->bvhtree)
1602                                 continue;
1603                         
1604                         /* move object to position (step) in time */
1605                         collision_move_object ( collmd, step + dt, step );
1606                         
1607                         /* search for overlapping collision pairs */
1608                         overlap = BLI_bvhtree_overlap ( cloth_bvh, collmd->bvhtree, &result );
1609                                 
1610                         // go to next object if no overlap is there
1611                         if(!result || !overlap)
1612                         {
1613                                 if ( overlap )
1614                                         MEM_freeN ( overlap );
1615                                 continue;
1616                         }
1617                         
1618                         /* check if collisions really happen (costly near check) */
1619                         cloth_bvh_objcollisions_nearcheck ( clmd, collmd, &collisions[i], &collisions_index[i], result, overlap);
1620                         
1621                         // resolve nearby collisions
1622                         ret += cloth_bvh_objcollisions_resolve ( clmd, collmd, collisions[i],  collisions_index[i]);
1623                         ret2 += ret;
1624                         
1625                         if ( overlap )
1626                                 MEM_freeN ( overlap );
1627                 }
1628                 rounds++;
1629                 
1630                 for(i = 0; i < numcollobj; i++)
1631                 {
1632                         if ( collisions[i] ) MEM_freeN ( collisions[i] );
1633                 }
1634                         
1635                 MEM_freeN(collisions);
1636                 MEM_freeN(collisions_index);
1637
1638                 ////////////////////////////////////////////////////////////
1639                 // update positions
1640                 // this is needed for bvh_calc_DOP_hull_moving() [kdop.c]
1641                 ////////////////////////////////////////////////////////////
1642
1643                 // verts come from clmd
1644                 for ( i = 0; i < numverts; i++ )
1645                 {
1646                         if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
1647                         {
1648                                 if ( verts [i].flags & CLOTH_VERT_FLAG_PINNED )
1649                                 {
1650                                         continue;
1651                                 }
1652                         }
1653
1654                         VECADD ( verts[i].tx, verts[i].txold, verts[i].tv );
1655                 }
1656                 ////////////////////////////////////////////////////////////
1657                 
1658                 
1659                 ////////////////////////////////////////////////////////////
1660                 // Test on *simple* selfcollisions
1661                 ////////////////////////////////////////////////////////////
1662                 if ( clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF )
1663                 {
1664                         for(l = 0; l < clmd->coll_parms->self_loop_count; l++)
1665                         {
1666                                 // TODO: add coll quality rounds again
1667                                 BVHTreeOverlap *overlap = NULL;
1668                                 int result = 0;
1669         
1670                                 // collisions = 1;
1671                                 verts = cloth->verts; // needed for openMP
1672         
1673                                 numfaces = clmd->clothObject->numfaces;
1674                                 numverts = clmd->clothObject->numverts;
1675         
1676                                 verts = cloth->verts;
1677         
1678                                 if ( cloth->bvhselftree )
1679                                 {
1680                                         // search for overlapping collision pairs 
1681                                         overlap = BLI_bvhtree_overlap ( cloth->bvhselftree, cloth->bvhselftree, &result );
1682         
1683         // #pragma omp parallel for private(k, i, j) schedule(static)
1684                                         for ( k = 0; k < result; k++ )
1685                                         {
1686                                                 float temp[3];
1687                                                 float length = 0;
1688                                                 float mindistance;
1689         
1690                                                 i = overlap[k].indexA;
1691                                                 j = overlap[k].indexB;
1692         
1693                                                 mindistance = clmd->coll_parms->selfepsilon* ( cloth->verts[i].avg_spring_len + cloth->verts[j].avg_spring_len );
1694         
1695                                                 if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
1696                                                 {
1697                                                         if ( ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED )
1698                                                                                 && ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED ) )
1699                                                         {
1700                                                                 continue;
1701                                                         }
1702                                                 }
1703         
1704                                                 VECSUB ( temp, verts[i].tx, verts[j].tx );
1705         
1706                                                 if ( ( ABS ( temp[0] ) > mindistance ) || ( ABS ( temp[1] ) > mindistance ) || ( ABS ( temp[2] ) > mindistance ) ) continue;
1707         
1708                                                 // check for adjacent points (i must be smaller j)
1709                                                 if ( BLI_edgehash_haskey ( cloth->edgehash, MIN2(i, j), MAX2(i, j) ) )
1710                                                 {
1711                                                         continue;
1712                                                 }
1713         
1714                                                 length = normalize_v3( temp );
1715         
1716                                                 if ( length < mindistance )
1717                                                 {
1718                                                         float correction = mindistance - length;
1719         
1720                                                         if ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED )
1721                                                         {
1722                                                                 mul_v3_fl( temp, -correction );
1723                                                                 VECADD ( verts[j].tx, verts[j].tx, temp );
1724                                                         }
1725                                                         else if ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED )
1726                                                         {
1727                                                                 mul_v3_fl( temp, correction );
1728                                                                 VECADD ( verts[i].tx, verts[i].tx, temp );
1729                                                         }
1730                                                         else
1731                                                         {
1732                                                                 mul_v3_fl( temp, -correction*0.5 );
1733                                                                 VECADD ( verts[j].tx, verts[j].tx, temp );
1734         
1735                                                                 VECSUB ( verts[i].tx, verts[i].tx, temp );
1736                                                         }
1737                                                         ret = 1;
1738                                                         ret2 += ret;
1739                                                 }
1740                                                 else
1741                                                 {
1742                                                         // check for approximated time collisions
1743                                                 }
1744                                         }
1745         
1746                                         if ( overlap )
1747                                                 MEM_freeN ( overlap );
1748         
1749                                 }
1750                         }
1751                         ////////////////////////////////////////////////////////////
1752
1753                         ////////////////////////////////////////////////////////////
1754                         // SELFCOLLISIONS: update velocities
1755                         ////////////////////////////////////////////////////////////
1756                         if ( ret2 )
1757                         {
1758                                 for ( i = 0; i < cloth->numverts; i++ )
1759                                 {
1760                                         if ( ! ( verts [i].flags & CLOTH_VERT_FLAG_PINNED ) )
1761                                         {
1762                                                 VECSUB ( verts[i].tv, verts[i].tx, verts[i].txold );
1763                                         }
1764                                 }
1765                         }
1766                         ////////////////////////////////////////////////////////////
1767                 }
1768         }
1769         while ( ret2 && ( clmd->coll_parms->loop_count>rounds ) );
1770         
1771         if(collobjs)
1772                 MEM_freeN(collobjs);
1773
1774         return MIN2 ( ret, 1 );
1775 }