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