code cleanup: dont use function calls like dot_v3v3, pow and sqrt within macros which...
[blender.git] / source / blender / blenkernel / intern / collision.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) Blender Foundation
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/collision.c
29  *  \ingroup bke
30  */
31
32
33 #include "MEM_guardedalloc.h"
34
35 #include "BKE_cloth.h"
36
37 #include "DNA_cloth_types.h"
38 #include "DNA_group_types.h"
39 #include "DNA_mesh_types.h"
40 #include "DNA_object_types.h"
41 #include "DNA_object_force.h"
42 #include "DNA_scene_types.h"
43 #include "DNA_meshdata_types.h"
44
45 #include "BLI_utildefines.h"
46 #include "BLI_blenlib.h"
47 #include "BLI_math.h"
48 #include "BLI_edgehash.h"
49 #include "BLI_utildefines.h"
50 #include "BLI_ghash.h"
51 #include "BLI_memarena.h"
52 #include "BLI_rand.h"
53
54 #include "BKE_DerivedMesh.h"
55 #include "BKE_global.h"
56 #include "BKE_scene.h"
57 #include "BKE_mesh.h"
58 #include "BKE_object.h"
59 #include "BKE_modifier.h"
60
61 #include "BKE_DerivedMesh.h"
62 #ifdef USE_BULLET
63 #include "Bullet-C-Api.h"
64 #endif
65 #include "BLI_kdopbvh.h"
66 #include "BKE_collision.h"
67
68 #ifdef WITH_ELTOPO
69 #include "eltopo-capi.h"
70 #endif
71
72
73 /***********************************
74 Collision modifier code start
75 ***********************************/
76
77 /* step is limited from 0 (frame start position) to 1 (frame end position) */
78 void collision_move_object(CollisionModifierData *collmd, float step, float prevstep)
79 {
80         float tv[3] = {0, 0, 0};
81         unsigned int i = 0;
82
83         for ( i = 0; i < collmd->numverts; i++ ) {
84                 sub_v3_v3v3(tv, collmd->xnew[i].co, collmd->x[i].co);
85                 VECADDS(collmd->current_x[i].co, collmd->x[i].co, tv, prevstep);
86                 VECADDS(collmd->current_xnew[i].co, collmd->x[i].co, tv, step);
87                 sub_v3_v3v3(collmd->current_v[i].co, collmd->current_xnew[i].co, collmd->current_x[i].co);
88         }
89
90         bvhtree_update_from_mvert ( collmd->bvhtree, collmd->mfaces, collmd->numfaces, collmd->current_x, collmd->current_xnew, collmd->numverts, 1 );
91 }
92
93 BVHTree *bvhtree_build_from_mvert ( MFace *mfaces, unsigned int numfaces, MVert *x, unsigned int UNUSED(numverts), float epsilon )
94 {
95         BVHTree *tree;
96         float co[12];
97         unsigned int i;
98         MFace *tface = mfaces;
99
100         tree = BLI_bvhtree_new ( numfaces*2, epsilon, 4, 26 );
101
102         // fill tree
103         for ( i = 0; i < numfaces; i++, tface++ ) {
104                 copy_v3_v3 ( &co[0*3], x[tface->v1].co );
105                 copy_v3_v3 ( &co[1*3], x[tface->v2].co );
106                 copy_v3_v3 ( &co[2*3], x[tface->v3].co );
107                 if ( tface->v4 )
108                         copy_v3_v3 ( &co[3*3], x[tface->v4].co );
109
110                 BLI_bvhtree_insert ( tree, i, co, ( mfaces->v4 ? 4 : 3 ) );
111         }
112
113         // balance tree
114         BLI_bvhtree_balance ( tree );
115
116         return tree;
117 }
118
119 void bvhtree_update_from_mvert(BVHTree * bvhtree, MFace *faces, int numfaces, MVert *x, MVert *xnew, int UNUSED(numverts), int moving )
120 {
121         int i;
122         MFace *mfaces = faces;
123         float co[12], co_moving[12];
124         int ret = 0;
125
126         if ( !bvhtree )
127                 return;
128
129         if ( x ) {
130                 for ( i = 0; i < numfaces; i++, mfaces++ ) {
131                         copy_v3_v3 ( &co[0*3], x[mfaces->v1].co );
132                         copy_v3_v3 ( &co[1*3], x[mfaces->v2].co );
133                         copy_v3_v3 ( &co[2*3], x[mfaces->v3].co );
134                         if ( mfaces->v4 )
135                                 copy_v3_v3 ( &co[3*3], x[mfaces->v4].co );
136
137                         // copy new locations into array
138                         if ( moving && xnew ) {
139                                 // update moving positions
140                                 copy_v3_v3 ( &co_moving[0*3], xnew[mfaces->v1].co );
141                                 copy_v3_v3 ( &co_moving[1*3], xnew[mfaces->v2].co );
142                                 copy_v3_v3 ( &co_moving[2*3], xnew[mfaces->v3].co );
143                                 if ( mfaces->v4 )
144                                         copy_v3_v3 ( &co_moving[3*3], xnew[mfaces->v4].co );
145
146                                 ret = BLI_bvhtree_update_node ( bvhtree, i, co, co_moving, ( mfaces->v4 ? 4 : 3 ) );
147                         }
148                         else {
149                                 ret = BLI_bvhtree_update_node ( bvhtree, i, co, NULL, ( mfaces->v4 ? 4 : 3 ) );
150                         }
151
152                         // check if tree is already full
153                         if ( !ret )
154                                 break;
155                 }
156
157                 BLI_bvhtree_update_tree ( bvhtree );
158         }
159 }
160
161 /***********************************
162 Collision modifier code end
163 ***********************************/
164 #define mySWAP(a, b) do { double tmp = b ; b = a ; a = tmp ; } while (0)
165
166
167 // w3 is not perfect
168 static void collision_compute_barycentric ( float pv[3], float p1[3], float p2[3], float p3[3], float *w1, float *w2, float *w3 )
169 {
170         double  tempV1[3], tempV2[3], tempV4[3];
171         double  a, b, c, d, e, f;
172
173         VECSUB ( tempV1, p1, p3 );
174         VECSUB ( tempV2, p2, p3 );
175         VECSUB ( tempV4, pv, p3 );
176
177         a = INPR ( tempV1, tempV1 );
178         b = INPR ( tempV1, tempV2 );
179         c = INPR ( tempV2, tempV2 );
180         e = INPR ( tempV1, tempV4 );
181         f = INPR ( tempV2, tempV4 );
182
183         d = ( a * c - b * b );
184
185         if ( ABS ( d ) < (double)ALMOST_ZERO ) {
186                 *w1 = *w2 = *w3 = 1.0 / 3.0;
187                 return;
188         }
189
190         w1[0] = ( float ) ( ( e * c - b * f ) / d );
191
192         if ( w1[0] < 0 )
193                 w1[0] = 0;
194
195         w2[0] = ( float ) ( ( f - b * ( double ) w1[0] ) / c );
196
197         if ( w2[0] < 0 )
198                 w2[0] = 0;
199
200         w3[0] = 1.0f - w1[0] - w2[0];
201 }
202
203 DO_INLINE void collision_interpolateOnTriangle ( float to[3], float v1[3], float v2[3], float v3[3], double w1, double w2, double w3 )
204 {
205         zero_v3(to);
206         VECADDMUL(to, v1, w1);
207         VECADDMUL(to, v2, w2);
208         VECADDMUL(to, v3, w3);
209 }
210
211 static int cloth_collision_response_static ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end )
212 {
213         int result = 0;
214         Cloth *cloth1;
215         float w1, w2, w3, u1, u2, u3;
216         float v1[3], v2[3], relativeVelocity[3];
217         float magrelVel;
218         float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree );
219
220         cloth1 = clmd->clothObject;
221
222         for ( ; collpair != collision_end; collpair++ ) {
223                 float i1[3], i2[3], i3[3];
224
225                 zero_v3(i1);
226                 zero_v3(i2);
227                 zero_v3(i3);
228
229                 // only handle static collisions here
230                 if ( collpair->flag & COLLISION_IN_FUTURE )
231                         continue;
232
233                 // compute barycentric coordinates for both collision points
234                 collision_compute_barycentric ( collpair->pa,
235                         cloth1->verts[collpair->ap1].txold,
236                         cloth1->verts[collpair->ap2].txold,
237                         cloth1->verts[collpair->ap3].txold,
238                         &w1, &w2, &w3 );
239
240                 // was: txold
241                 collision_compute_barycentric ( collpair->pb,
242                         collmd->current_x[collpair->bp1].co,
243                         collmd->current_x[collpair->bp2].co,
244                         collmd->current_x[collpair->bp3].co,
245                         &u1, &u2, &u3 );
246
247                 // Calculate relative "velocity".
248                 collision_interpolateOnTriangle ( v1, cloth1->verts[collpair->ap1].tv, cloth1->verts[collpair->ap2].tv, cloth1->verts[collpair->ap3].tv, w1, w2, w3 );
249
250                 collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
251
252                 sub_v3_v3v3(relativeVelocity, v2, v1);
253
254                 // Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal').
255                 magrelVel = dot_v3v3(relativeVelocity, collpair->normal);
256
257                 // printf("magrelVel: %f\n", magrelVel);
258
259                 // Calculate masses of points.
260                 // TODO
261
262                 // If v_n_mag < 0 the edges are approaching each other.
263                 if ( magrelVel > ALMOST_ZERO ) {
264                         // Calculate Impulse magnitude to stop all motion in normal direction.
265                         float magtangent = 0, repulse = 0, d = 0;
266                         double impulse = 0.0;
267                         float vrel_t_pre[3];
268                         float temp[3], spf;
269
270                         // calculate tangential velocity
271                         copy_v3_v3 ( temp, collpair->normal );
272                         mul_v3_fl(temp, magrelVel);
273                         sub_v3_v3v3(vrel_t_pre, relativeVelocity, temp);
274
275                         // Decrease in magnitude of relative tangential velocity due to coulomb friction
276                         // in original formula "magrelVel" should be the "change of relative velocity in normal direction"
277                         magtangent = minf(clmd->coll_parms->friction * 0.01f * magrelVel, sqrtf(dot_v3v3(vrel_t_pre, vrel_t_pre)));
278
279                         // Apply friction impulse.
280                         if ( magtangent > ALMOST_ZERO ) {
281                                 normalize_v3(vrel_t_pre);
282
283                                 impulse = magtangent / ( 1.0f + w1*w1 + w2*w2 + w3*w3 ); // 2.0 *
284                                 VECADDMUL ( i1, vrel_t_pre, w1 * impulse );
285                                 VECADDMUL ( i2, vrel_t_pre, w2 * impulse );
286                                 VECADDMUL ( i3, vrel_t_pre, w3 * impulse );
287                         }
288
289                         // Apply velocity stopping impulse
290                         // I_c = m * v_N / 2.0
291                         // no 2.0 * magrelVel normally, but looks nicer DG
292                         impulse =  magrelVel / ( 1.0 + w1*w1 + w2*w2 + w3*w3 );
293
294                         VECADDMUL ( i1, collpair->normal, w1 * impulse );
295                         cloth1->verts[collpair->ap1].impulse_count++;
296
297                         VECADDMUL ( i2, collpair->normal, w2 * impulse );
298                         cloth1->verts[collpair->ap2].impulse_count++;
299
300                         VECADDMUL ( i3, collpair->normal, w3 * impulse );
301                         cloth1->verts[collpair->ap3].impulse_count++;
302
303                         // Apply repulse impulse if distance too short
304                         // I_r = -min(dt*kd, m(0, 1d/dt - v_n))
305                         // DG: this formula ineeds to be changed for this code since we apply impulses/repulses like this:
306                         // v += impulse; x_new = x + v; 
307                         // We don't use dt!!
308                         // DG TODO: Fix usage of dt here!
309                         spf = (float)clmd->sim_parms->stepsPerFrame / clmd->sim_parms->timescale;
310
311                         d = clmd->coll_parms->epsilon*8.0f/9.0f + epsilon2*8.0f/9.0f - collpair->distance;
312                         if ( ( magrelVel < 0.1f*d*spf ) && ( d > ALMOST_ZERO ) ) {
313                                 repulse = MIN2 ( d*1.0f/spf, 0.1f*d*spf - magrelVel );
314
315                                 // stay on the safe side and clamp repulse
316                                 if ( impulse > ALMOST_ZERO )
317                                         repulse = MIN2 ( repulse, 5.0*impulse );
318                                 repulse = MAX2 ( impulse, repulse );
319
320                                 impulse = repulse / ( 1.0f + w1*w1 + w2*w2 + w3*w3 ); // original 2.0 / 0.25
321                                 VECADDMUL ( i1, collpair->normal,  impulse );
322                                 VECADDMUL ( i2, collpair->normal,  impulse );
323                                 VECADDMUL ( i3, collpair->normal,  impulse );
324                         }
325
326                         result = 1;
327                 }
328                 else {
329                         // Apply repulse impulse if distance too short
330                         // I_r = -min(dt*kd, max(0, 1d/dt - v_n))
331                         // DG: this formula ineeds to be changed for this code since we apply impulses/repulses like this:
332                         // v += impulse; x_new = x + v; 
333                         // We don't use dt!!
334                         float spf = (float)clmd->sim_parms->stepsPerFrame / clmd->sim_parms->timescale;
335
336                         float d = clmd->coll_parms->epsilon*8.0f/9.0f + epsilon2*8.0f/9.0f - collpair->distance;
337                         if ( d > ALMOST_ZERO) {
338                                 // stay on the safe side and clamp repulse
339                                 float repulse = d*1.0f/spf;
340
341                                 float impulse = repulse / ( 3.0 * ( 1.0f + w1*w1 + w2*w2 + w3*w3 )); // original 2.0 / 0.25 
342
343                                 VECADDMUL ( i1, collpair->normal,  impulse );
344                                 VECADDMUL ( i2, collpair->normal,  impulse );
345                                 VECADDMUL ( i3, collpair->normal,  impulse );
346
347                                 cloth1->verts[collpair->ap1].impulse_count++;
348                                 cloth1->verts[collpair->ap2].impulse_count++;
349                                 cloth1->verts[collpair->ap3].impulse_count++;
350
351                                 result = 1;
352                         }
353                 }
354
355                 if (result) {
356                         int i = 0;
357
358                         for (i = 0; i < 3; i++) {
359                                 if (cloth1->verts[collpair->ap1].impulse_count > 0 && ABS(cloth1->verts[collpair->ap1].impulse[i]) < ABS(i1[i]))
360                                         cloth1->verts[collpair->ap1].impulse[i] = i1[i];
361
362                                 if (cloth1->verts[collpair->ap2].impulse_count > 0 && ABS(cloth1->verts[collpair->ap2].impulse[i]) < ABS(i2[i]))
363                                         cloth1->verts[collpair->ap2].impulse[i] = i2[i];
364
365                                 if (cloth1->verts[collpair->ap3].impulse_count > 0 && ABS(cloth1->verts[collpair->ap3].impulse[i]) < ABS(i3[i]))
366                                         cloth1->verts[collpair->ap3].impulse[i] = i3[i];
367                         }
368                 }
369         }
370         return result;
371 }
372
373 //Determines collisions on overlap, collisions are written to collpair[i] and collision+number_collision_found is returned
374 static CollPair* cloth_collision(ModifierData *md1, ModifierData *md2,
375                                  BVHTreeOverlap *overlap, CollPair *collpair, float UNUSED(dt))
376 {
377         ClothModifierData *clmd = (ClothModifierData *)md1;
378         CollisionModifierData *collmd = (CollisionModifierData *) md2;
379         /* Cloth *cloth = clmd->clothObject; */ /* UNUSED */
380         MFace *face1=NULL, *face2 = NULL;
381 #ifdef USE_BULLET
382         ClothVertex *verts1 = clmd->clothObject->verts;
383 #endif
384         double distance = 0;
385         float epsilon1 = clmd->coll_parms->epsilon;
386         float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree );
387         int i;
388
389         face1 = & ( clmd->clothObject->mfaces[overlap->indexA] );
390         face2 = & ( collmd->mfaces[overlap->indexB] );
391
392         // check all 4 possible collisions
393         for ( i = 0; i < 4; i++ ) {
394                 if ( i == 0 ) {
395                         // fill faceA
396                         collpair->ap1 = face1->v1;
397                         collpair->ap2 = face1->v2;
398                         collpair->ap3 = face1->v3;
399
400                         // fill faceB
401                         collpair->bp1 = face2->v1;
402                         collpair->bp2 = face2->v2;
403                         collpair->bp3 = face2->v3;
404                 }
405                 else if ( i == 1 ) {
406                         if ( face1->v4 ) {
407                                 // fill faceA
408                                 collpair->ap1 = face1->v1;
409                                 collpair->ap2 = face1->v3;
410                                 collpair->ap3 = face1->v4;
411
412                                 // fill faceB
413                                 collpair->bp1 = face2->v1;
414                                 collpair->bp2 = face2->v2;
415                                 collpair->bp3 = face2->v3;
416                         }
417                         else
418                                 i++;
419                 }
420                 if ( i == 2 ) {
421                         if ( face2->v4 ) {
422                                 // fill faceA
423                                 collpair->ap1 = face1->v1;
424                                 collpair->ap2 = face1->v2;
425                                 collpair->ap3 = face1->v3;
426
427                                 // fill faceB
428                                 collpair->bp1 = face2->v1;
429                                 collpair->bp2 = face2->v4;
430                                 collpair->bp3 = face2->v3;
431                         }
432                         else
433                                 break;
434                 }
435                 else if ( i == 3 ) {
436                         if ( face1->v4 && face2->v4 ) {
437                                 // fill faceA
438                                 collpair->ap1 = face1->v1;
439                                 collpair->ap2 = face1->v3;
440                                 collpair->ap3 = face1->v4;
441
442                                 // fill faceB
443                                 collpair->bp1 = face2->v1;
444                                 collpair->bp2 = face2->v3;
445                                 collpair->bp3 = face2->v4;
446                         }
447                         else
448                                 break;
449                 }
450                 
451 #ifdef USE_BULLET
452                 // calc distance + normal
453                 distance = plNearestPoints (
454                         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 );
455 #else
456                 // just be sure that we don't add anything
457                 distance = 2.0 * (double)( epsilon1 + epsilon2 + ALMOST_ZERO );
458 #endif
459
460                 if (distance <= (epsilon1 + epsilon2 + ALMOST_ZERO)) {
461                         normalize_v3_v3(collpair->normal, collpair->vector);
462
463                         collpair->distance = distance;
464                         collpair->flag = 0;
465                         collpair++;
466                 }/*
467                 else
468                 {
469                         float w1, w2, w3, u1, u2, u3;
470                         float v1[3], v2[3], relativeVelocity[3];
471
472                         // calc relative velocity
473                         
474                         // compute barycentric coordinates for both collision points
475                         collision_compute_barycentric ( collpair->pa,
476                         verts1[collpair->ap1].txold,
477                         verts1[collpair->ap2].txold,
478                         verts1[collpair->ap3].txold,
479                         &w1, &w2, &w3 );
480
481                         // was: txold
482                         collision_compute_barycentric ( collpair->pb,
483                         collmd->current_x[collpair->bp1].co,
484                         collmd->current_x[collpair->bp2].co,
485                         collmd->current_x[collpair->bp3].co,
486                         &u1, &u2, &u3 );
487
488                         // Calculate relative "velocity".
489                         collision_interpolateOnTriangle ( v1, verts1[collpair->ap1].tv, verts1[collpair->ap2].tv, verts1[collpair->ap3].tv, w1, w2, w3 );
490
491                         collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
492
493                         sub_v3_v3v3(relativeVelocity, v2, v1);
494
495                         if (sqrt(dot_v3v3(relativeVelocity, relativeVelocity)) >= distance)
496                         {
497                                 // check for collision in the future
498                                 collpair->flag |= COLLISION_IN_FUTURE;
499                                 collpair++;
500                         }
501                 }*/
502         }
503         return collpair;
504 }
505
506 static void add_collision_object(Object ***objs, unsigned int *numobj, unsigned int *maxobj, Object *ob, Object *self, int level, unsigned int modifier_type)
507 {
508         CollisionModifierData *cmd= NULL;
509
510         if (ob == self)
511                 return;
512
513         /* only get objects with collision modifier */
514         if (((modifier_type == eModifierType_Collision) && ob->pd && ob->pd->deflect) || (modifier_type != eModifierType_Collision))
515                 cmd= (CollisionModifierData *)modifiers_findByType(ob, modifier_type);
516         
517         if (cmd) {      
518                 /* extend array */
519                 if (*numobj >= *maxobj) {
520                         *maxobj *= 2;
521                         *objs= MEM_reallocN(*objs, sizeof(Object*)*(*maxobj));
522                 }
523                 
524                 (*objs)[*numobj] = ob;
525                 (*numobj)++;
526         }
527
528         /* objects in dupli groups, one level only for now */
529         if (ob->dup_group && level == 0) {
530                 GroupObject *go;
531                 Group *group= ob->dup_group;
532
533                 /* add objects */
534                 for (go= group->gobject.first; go; go= go->next)
535                         add_collision_object(objs, numobj, maxobj, go->ob, self, level+1, modifier_type);
536         }       
537 }
538
539 // return all collision objects in scene
540 // collision object will exclude self 
541 Object **get_collisionobjects(Scene *scene, Object *self, Group *group, unsigned int *numcollobj, unsigned int modifier_type)
542 {
543         Base *base;
544         Object **objs;
545         GroupObject *go;
546         unsigned int numobj= 0, maxobj= 100;
547         
548         objs= MEM_callocN(sizeof(Object *)*maxobj, "CollisionObjectsArray");
549
550         /* gather all collision objects */
551         if (group) {
552                 /* use specified group */
553                 for (go= group->gobject.first; go; go= go->next)
554                         add_collision_object(&objs, &numobj, &maxobj, go->ob, self, 0, modifier_type);
555         }
556         else {
557                 Scene *sce_iter;
558                 /* add objects in same layer in scene */
559                 for (SETLOOPER(scene, sce_iter, base)) {
560                         if (base->lay & self->lay)
561                                 add_collision_object(&objs, &numobj, &maxobj, base->object, self, 0, modifier_type);
562
563                 }
564         }
565
566         *numcollobj= numobj;
567
568         return objs;
569 }
570
571 static void add_collider_cache_object(ListBase **objs, Object *ob, Object *self, int level)
572 {
573         CollisionModifierData *cmd= NULL;
574         ColliderCache *col;
575
576         if (ob == self)
577                 return;
578
579         if (ob->pd && ob->pd->deflect)
580                 cmd =(CollisionModifierData *)modifiers_findByType(ob, eModifierType_Collision);
581         
582         if (cmd && cmd->bvhtree) {      
583                 if (*objs == NULL)
584                         *objs = MEM_callocN(sizeof(ListBase), "ColliderCache array");
585
586                 col = MEM_callocN(sizeof(ColliderCache), "ColliderCache");
587                 col->ob = ob;
588                 col->collmd = cmd;
589                 /* make sure collider is properly set up */
590                 collision_move_object(cmd, 1.0, 0.0);
591                 BLI_addtail(*objs, col);
592         }
593
594         /* objects in dupli groups, one level only for now */
595         if (ob->dup_group && level == 0) {
596                 GroupObject *go;
597                 Group *group= ob->dup_group;
598
599                 /* add objects */
600                 for (go= group->gobject.first; go; go= go->next)
601                         add_collider_cache_object(objs, go->ob, self, level+1);
602         }
603 }
604
605 ListBase *get_collider_cache(Scene *scene, Object *self, Group *group)
606 {
607         GroupObject *go;
608         ListBase *objs= NULL;
609         
610         /* add object in same layer in scene */
611         if (group) {
612                 for (go= group->gobject.first; go; go= go->next)
613                         add_collider_cache_object(&objs, go->ob, self, 0);
614         }
615         else {
616                 Scene *sce_iter;
617                 Base *base;
618
619                 /* add objects in same layer in scene */
620                 for (SETLOOPER(scene, sce_iter, base)) {
621                         if (!self || (base->lay & self->lay))
622                                 add_collider_cache_object(&objs, base->object, self, 0);
623
624                 }
625         }
626
627         return objs;
628 }
629
630 void free_collider_cache(ListBase **colliders)
631 {
632         if (*colliders) {
633                 BLI_freelistN(*colliders);
634                 MEM_freeN(*colliders);
635                 *colliders = NULL;
636         }
637 }
638
639
640 static void cloth_bvh_objcollisions_nearcheck ( ClothModifierData * clmd, CollisionModifierData *collmd,
641         CollPair **collisions, CollPair **collisions_index, int numresult, BVHTreeOverlap *overlap, double dt)
642 {
643         int i;
644         
645         *collisions = (CollPair *) MEM_mallocN(sizeof(CollPair) * numresult * 64, "collision array" ); //*4 since cloth_collision_static can return more than 1 collision
646         *collisions_index = *collisions;
647
648         for ( i = 0; i < numresult; i++ ) {
649                 *collisions_index = cloth_collision ( (ModifierData *)clmd, (ModifierData *)collmd,
650                                                       overlap+i, *collisions_index, dt );
651         }
652 }
653
654 static int cloth_bvh_objcollisions_resolve ( ClothModifierData * clmd, CollisionModifierData *collmd, CollPair *collisions, CollPair *collisions_index)
655 {
656         Cloth *cloth = clmd->clothObject;
657         int i=0, j = 0, /*numfaces = 0, */ numverts = 0;
658         ClothVertex *verts = NULL;
659         int ret = 0;
660         int result = 0;
661         
662         numverts = clmd->clothObject->numverts;
663         verts = cloth->verts;
664         
665         // process all collisions (calculate impulses, TODO: also repulses if distance too short)
666         result = 1;
667         for ( j = 0; j < 2; j++ ) { /* 5 is just a value that ensures convergence */
668                 result = 0;
669
670                 if ( collmd->bvhtree ) {
671                         result += cloth_collision_response_static ( clmd, collmd, collisions, collisions_index );
672
673                         // apply impulses in parallel
674                         if (result) {
675                                 for (i = 0; i < numverts; i++) {
676                                         // calculate "velocities" (just xnew = xold + v; no dt in v)
677                                         if (verts[i].impulse_count) {
678                                                 // VECADDMUL ( verts[i].tv, verts[i].impulse, 1.0f / verts[i].impulse_count );
679                                                 VECADD ( verts[i].tv, verts[i].tv, verts[i].impulse);
680                                                 zero_v3(verts[i].impulse);
681                                                 verts[i].impulse_count = 0;
682
683                                                 ret++;
684                                         }
685                                 }
686                         }
687                 }
688
689                 if (!result) {
690                         break;
691                 }
692         }
693         return ret;
694 }
695
696 // cloth - object collisions
697 int cloth_bvh_objcollision(Object *ob, ClothModifierData * clmd, float step, float dt )
698 {
699         Cloth *cloth= clmd->clothObject;
700         BVHTree *cloth_bvh= cloth->bvhtree;
701         unsigned int i=0, /* numfaces = 0, */ /* UNUSED */ numverts = 0, k, l, j;
702         int rounds = 0; // result counts applied collisions; ic is for debug output;
703         ClothVertex *verts = NULL;
704         int ret = 0, ret2 = 0;
705         Object **collobjs = NULL;
706         unsigned int numcollobj = 0;
707
708         if ((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_COLLOBJ) || cloth_bvh==NULL)
709                 return 0;
710         
711         verts = cloth->verts;
712         /* numfaces = cloth->numfaces; */ /* UNUSED */
713         numverts = cloth->numverts;
714
715         ////////////////////////////////////////////////////////////
716         // static collisions
717         ////////////////////////////////////////////////////////////
718
719         // update cloth bvh
720         bvhtree_update_from_cloth ( clmd, 1 ); // 0 means STATIC, 1 means MOVING (see later in this function)
721         bvhselftree_update_from_cloth ( clmd, 0 ); // 0 means STATIC, 1 means MOVING (see later in this function)
722         
723         collobjs = get_collisionobjects(clmd->scene, ob, clmd->coll_parms->group, &numcollobj, eModifierType_Collision);
724         
725         if (!collobjs)
726                 return 0;
727
728         /* move object to position (step) in time */
729         for (i = 0; i < numcollobj; i++) {
730                 Object *collob= collobjs[i];
731                 CollisionModifierData *collmd = (CollisionModifierData*)modifiers_findByType(collob, eModifierType_Collision);
732
733                 if (!collmd->bvhtree)
734                         continue;
735
736                 /* move object to position (step) in time */
737                 collision_move_object ( collmd, step + dt, step );
738         }
739
740         do
741         {
742                 CollPair **collisions, **collisions_index;
743                 
744                 ret2 = 0;
745
746                 collisions = MEM_callocN(sizeof(CollPair *) *numcollobj, "CollPair");
747                 collisions_index = MEM_callocN(sizeof(CollPair *) *numcollobj, "CollPair");
748                 
749                 // check all collision objects
750                 for (i = 0; i < numcollobj; i++) {
751                         Object *collob= collobjs[i];
752                         CollisionModifierData *collmd = (CollisionModifierData*)modifiers_findByType(collob, eModifierType_Collision);
753                         BVHTreeOverlap *overlap = NULL;
754                         unsigned int result = 0;
755                         
756                         if (!collmd->bvhtree)
757                                 continue;
758                         
759                         /* search for overlapping collision pairs */
760                         overlap = BLI_bvhtree_overlap ( cloth_bvh, collmd->bvhtree, &result );
761                                 
762                         // go to next object if no overlap is there
763                         if ( result && overlap ) {
764                                 /* check if collisions really happen (costly near check) */
765                                 cloth_bvh_objcollisions_nearcheck ( clmd, collmd, &collisions[i], 
766                                         &collisions_index[i], result, overlap, dt/(float)clmd->coll_parms->loop_count);
767                         
768                                 // resolve nearby collisions
769                                 ret += cloth_bvh_objcollisions_resolve ( clmd, collmd, collisions[i],  collisions_index[i]);
770                                 ret2 += ret;
771                         }
772
773                         if ( overlap )
774                                 MEM_freeN ( overlap );
775                 }
776                 rounds++;
777                 
778                 for (i = 0; i < numcollobj; i++) {
779                         if ( collisions[i] ) MEM_freeN ( collisions[i] );
780                 }
781                         
782                 MEM_freeN(collisions);
783                 MEM_freeN(collisions_index);
784
785                 ////////////////////////////////////////////////////////////
786                 // update positions
787                 // this is needed for bvh_calc_DOP_hull_moving() [kdop.c]
788                 ////////////////////////////////////////////////////////////
789
790                 // verts come from clmd
791                 for ( i = 0; i < numverts; i++ ) {
792                         if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ) {
793                                 if ( verts [i].flags & CLOTH_VERT_FLAG_PINNED ) {
794                                         continue;
795                                 }
796                         }
797
798                         VECADD ( verts[i].tx, verts[i].txold, verts[i].tv );
799                 }
800                 ////////////////////////////////////////////////////////////
801                 
802                 
803                 ////////////////////////////////////////////////////////////
804                 // Test on *simple* selfcollisions
805                 ////////////////////////////////////////////////////////////
806                 if ( clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF ) {
807                         for (l = 0; l < (unsigned int)clmd->coll_parms->self_loop_count; l++) {
808                                 // TODO: add coll quality rounds again
809                                 BVHTreeOverlap *overlap = NULL;
810                                 unsigned int result = 0;
811         
812                                 // collisions = 1;
813                                 verts = cloth->verts; // needed for openMP
814         
815                                 /* numfaces = cloth->numfaces; */ /* UNUSED */
816                                 numverts = cloth->numverts;
817         
818                                 verts = cloth->verts;
819         
820                                 if ( cloth->bvhselftree ) {
821                                         // search for overlapping collision pairs
822                                         overlap = BLI_bvhtree_overlap ( cloth->bvhselftree, cloth->bvhselftree, &result );
823         
824         // #pragma omp parallel for private(k, i, j) schedule(static)
825                                         for ( k = 0; k < result; k++ ) {
826                                                 float temp[3];
827                                                 float length = 0;
828                                                 float mindistance;
829         
830                                                 i = overlap[k].indexA;
831                                                 j = overlap[k].indexB;
832         
833                                                 mindistance = clmd->coll_parms->selfepsilon* ( cloth->verts[i].avg_spring_len + cloth->verts[j].avg_spring_len );
834         
835                                                 if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ) {
836                                                         if ( ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED ) &&
837                                                              ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED ) )
838                                                         {
839                                                                 continue;
840                                                         }
841                                                 }
842
843                                                 if ((cloth->verts[i].flags & CLOTH_VERT_FLAG_NOSELFCOLL) ||
844                                                     (cloth->verts[j].flags & CLOTH_VERT_FLAG_NOSELFCOLL))
845                                                 {
846                                                         continue;
847                                                 }
848         
849                                                 sub_v3_v3v3(temp, verts[i].tx, verts[j].tx);
850         
851                                                 if ( ( ABS ( temp[0] ) > mindistance ) || ( ABS ( temp[1] ) > mindistance ) || ( ABS ( temp[2] ) > mindistance ) ) continue;
852         
853                                                 // check for adjacent points (i must be smaller j)
854                                                 if ( BLI_edgehash_haskey ( cloth->edgehash, MIN2(i, j), MAX2(i, j) ) ) {
855                                                         continue;
856                                                 }
857         
858                                                 length = normalize_v3(temp );
859         
860                                                 if ( length < mindistance ) {
861                                                         float correction = mindistance - length;
862         
863                                                         if ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED ) {
864                                                                 mul_v3_fl(temp, -correction);
865                                                                 VECADD ( verts[j].tx, verts[j].tx, temp );
866                                                         }
867                                                         else if ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED ) {
868                                                                 mul_v3_fl(temp, correction);
869                                                                 VECADD ( verts[i].tx, verts[i].tx, temp );
870                                                         }
871                                                         else {
872                                                                 mul_v3_fl(temp, correction * -0.5);
873                                                                 VECADD ( verts[j].tx, verts[j].tx, temp );
874         
875                                                                 sub_v3_v3v3(verts[i].tx, verts[i].tx, temp);
876                                                         }
877                                                         ret = 1;
878                                                         ret2 += ret;
879                                                 }
880                                                 else {
881                                                         // check for approximated time collisions
882                                                 }
883                                         }
884         
885                                         if ( overlap )
886                                                 MEM_freeN ( overlap );
887         
888                                 }
889                         }
890                         ////////////////////////////////////////////////////////////
891
892                         ////////////////////////////////////////////////////////////
893                         // SELFCOLLISIONS: update velocities
894                         ////////////////////////////////////////////////////////////
895                         if ( ret2 ) {
896                                 for ( i = 0; i < cloth->numverts; i++ ) {
897                                         if ( ! ( verts [i].flags & CLOTH_VERT_FLAG_PINNED ) ) {
898                                                 sub_v3_v3v3(verts[i].tv, verts[i].tx, verts[i].txold);
899                                         }
900                                 }
901                         }
902                         ////////////////////////////////////////////////////////////
903                 }
904         }
905         while ( ret2 && ( clmd->coll_parms->loop_count>rounds ) );
906         
907         if (collobjs)
908                 MEM_freeN(collobjs);
909
910         return 1|MIN2 ( ret, 1 );
911 }