ed22ad27811bca68b350ad3222e4d1f9190124fe
[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
165 // w3 is not perfect
166 static void collision_compute_barycentric ( float pv[3], float p1[3], float p2[3], float p3[3], float *w1, float *w2, float *w3 )
167 {
168         double  tempV1[3], tempV2[3], tempV4[3];
169         double  a, b, c, d, e, f;
170
171         VECSUB ( tempV1, p1, p3 );
172         VECSUB ( tempV2, p2, p3 );
173         VECSUB ( tempV4, pv, p3 );
174
175         a = INPR ( tempV1, tempV1 );
176         b = INPR ( tempV1, tempV2 );
177         c = INPR ( tempV2, tempV2 );
178         e = INPR ( tempV1, tempV4 );
179         f = INPR ( tempV2, tempV4 );
180
181         d = ( a * c - b * b );
182
183         if ( ABS ( d ) < (double)ALMOST_ZERO ) {
184                 *w1 = *w2 = *w3 = 1.0 / 3.0;
185                 return;
186         }
187
188         w1[0] = ( float ) ( ( e * c - b * f ) / d );
189
190         if ( w1[0] < 0 )
191                 w1[0] = 0;
192
193         w2[0] = ( float ) ( ( f - b * ( double ) w1[0] ) / c );
194
195         if ( w2[0] < 0 )
196                 w2[0] = 0;
197
198         w3[0] = 1.0f - w1[0] - w2[0];
199 }
200
201 DO_INLINE void collision_interpolateOnTriangle ( float to[3], float v1[3], float v2[3], float v3[3], double w1, double w2, double w3 )
202 {
203         zero_v3(to);
204         VECADDMUL(to, v1, w1);
205         VECADDMUL(to, v2, w2);
206         VECADDMUL(to, v3, w3);
207 }
208
209 static int cloth_collision_response_static ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end )
210 {
211         int result = 0;
212         Cloth *cloth1;
213         float w1, w2, w3, u1, u2, u3;
214         float v1[3], v2[3], relativeVelocity[3];
215         float magrelVel;
216         float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree );
217
218         cloth1 = clmd->clothObject;
219
220         for ( ; collpair != collision_end; collpair++ ) {
221                 float i1[3], i2[3], i3[3];
222
223                 zero_v3(i1);
224                 zero_v3(i2);
225                 zero_v3(i3);
226
227                 /* only handle static collisions here */
228                 if ( collpair->flag & COLLISION_IN_FUTURE )
229                         continue;
230
231                 /* compute barycentric coordinates for both collision points */
232                 collision_compute_barycentric ( collpair->pa,
233                         cloth1->verts[collpair->ap1].txold,
234                         cloth1->verts[collpair->ap2].txold,
235                         cloth1->verts[collpair->ap3].txold,
236                         &w1, &w2, &w3 );
237
238                 /* was: txold */
239                 collision_compute_barycentric ( collpair->pb,
240                         collmd->current_x[collpair->bp1].co,
241                         collmd->current_x[collpair->bp2].co,
242                         collmd->current_x[collpair->bp3].co,
243                         &u1, &u2, &u3 );
244
245                 /* Calculate relative "velocity". */
246                 collision_interpolateOnTriangle ( v1, cloth1->verts[collpair->ap1].tv, cloth1->verts[collpair->ap2].tv, cloth1->verts[collpair->ap3].tv, w1, w2, w3 );
247
248                 collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
249
250                 sub_v3_v3v3(relativeVelocity, v2, v1);
251
252                 /* Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal'). */
253                 magrelVel = dot_v3v3(relativeVelocity, collpair->normal);
254
255                 /* printf("magrelVel: %f\n", magrelVel); */
256
257                 /* Calculate masses of points.
258                  * TODO */
259
260                 /* If v_n_mag < 0 the edges are approaching each other. */
261                 if ( magrelVel > ALMOST_ZERO ) {
262                         /* Calculate Impulse magnitude to stop all motion in normal direction. */
263                         float magtangent = 0, repulse = 0, d = 0;
264                         double impulse = 0.0;
265                         float vrel_t_pre[3];
266                         float temp[3], spf;
267
268                         /* calculate tangential velocity */
269                         copy_v3_v3 ( temp, collpair->normal );
270                         mul_v3_fl(temp, magrelVel);
271                         sub_v3_v3v3(vrel_t_pre, relativeVelocity, temp);
272
273                         /* Decrease in magnitude of relative tangential velocity due to coulomb friction
274                          * in original formula "magrelVel" should be the "change of relative velocity in normal direction" */
275                         magtangent = minf(clmd->coll_parms->friction * 0.01f * magrelVel, sqrtf(dot_v3v3(vrel_t_pre, vrel_t_pre)));
276
277                         /* Apply friction impulse. */
278                         if ( magtangent > ALMOST_ZERO ) {
279                                 normalize_v3(vrel_t_pre);
280
281                                 impulse = magtangent / ( 1.0f + w1*w1 + w2*w2 + w3*w3 ); /* 2.0 * */
282                                 VECADDMUL ( i1, vrel_t_pre, w1 * impulse );
283                                 VECADDMUL ( i2, vrel_t_pre, w2 * impulse );
284                                 VECADDMUL ( i3, vrel_t_pre, w3 * impulse );
285                         }
286
287                         /* Apply velocity stopping impulse
288                          * I_c = m * v_N / 2.0
289                          * no 2.0 * magrelVel normally, but looks nicer DG */
290                         impulse =  magrelVel / ( 1.0 + w1*w1 + w2*w2 + w3*w3 );
291
292                         VECADDMUL ( i1, collpair->normal, w1 * impulse );
293                         cloth1->verts[collpair->ap1].impulse_count++;
294
295                         VECADDMUL ( i2, collpair->normal, w2 * impulse );
296                         cloth1->verts[collpair->ap2].impulse_count++;
297
298                         VECADDMUL ( i3, collpair->normal, w3 * impulse );
299                         cloth1->verts[collpair->ap3].impulse_count++;
300
301                         /* Apply repulse impulse if distance too short
302                          * I_r = -min(dt*kd, m(0, 1d/dt - v_n))
303                          * DG: this formula ineeds to be changed for this code since we apply impulses/repulses like this:
304                          * v += impulse; x_new = x + v;
305                          * We don't use dt!!
306                          * DG TODO: Fix usage of dt here! */
307                         spf = (float)clmd->sim_parms->stepsPerFrame / clmd->sim_parms->timescale;
308
309                         d = clmd->coll_parms->epsilon*8.0f/9.0f + epsilon2*8.0f/9.0f - collpair->distance;
310                         if ( ( magrelVel < 0.1f*d*spf ) && ( d > ALMOST_ZERO ) ) {
311                                 repulse = MIN2 ( d*1.0f/spf, 0.1f*d*spf - magrelVel );
312
313                                 /* stay on the safe side and clamp repulse */
314                                 if ( impulse > ALMOST_ZERO )
315                                         repulse = MIN2 ( repulse, 5.0*impulse );
316                                 repulse = MAX2 ( impulse, repulse );
317
318                                 impulse = repulse / ( 1.0f + w1*w1 + w2*w2 + w3*w3 ); /* original 2.0 / 0.25 */
319                                 VECADDMUL ( i1, collpair->normal,  impulse );
320                                 VECADDMUL ( i2, collpair->normal,  impulse );
321                                 VECADDMUL ( i3, collpair->normal,  impulse );
322                         }
323
324                         result = 1;
325                 }
326                 else {
327                         /* Apply repulse impulse if distance too short
328                          * I_r = -min(dt*kd, max(0, 1d/dt - v_n))
329                          * DG: this formula ineeds to be changed for this code since we apply impulses/repulses like this:
330                          * v += impulse; x_new = x + v;
331                          * We don't use dt!! */
332                         float spf = (float)clmd->sim_parms->stepsPerFrame / clmd->sim_parms->timescale;
333
334                         float d = clmd->coll_parms->epsilon*8.0f/9.0f + epsilon2*8.0f/9.0f - collpair->distance;
335                         if ( d > ALMOST_ZERO) {
336                                 /* stay on the safe side and clamp repulse */
337                                 float repulse = d*1.0f/spf;
338
339                                 float impulse = repulse / ( 3.0 * ( 1.0f + w1*w1 + w2*w2 + w3*w3 )); /* original 2.0 / 0.25 */
340
341                                 VECADDMUL ( i1, collpair->normal,  impulse );
342                                 VECADDMUL ( i2, collpair->normal,  impulse );
343                                 VECADDMUL ( i3, collpair->normal,  impulse );
344
345                                 cloth1->verts[collpair->ap1].impulse_count++;
346                                 cloth1->verts[collpair->ap2].impulse_count++;
347                                 cloth1->verts[collpair->ap3].impulse_count++;
348
349                                 result = 1;
350                         }
351                 }
352
353                 if (result) {
354                         int i = 0;
355
356                         for (i = 0; i < 3; i++) {
357                                 if (cloth1->verts[collpair->ap1].impulse_count > 0 && ABS(cloth1->verts[collpair->ap1].impulse[i]) < ABS(i1[i]))
358                                         cloth1->verts[collpair->ap1].impulse[i] = i1[i];
359
360                                 if (cloth1->verts[collpair->ap2].impulse_count > 0 && ABS(cloth1->verts[collpair->ap2].impulse[i]) < ABS(i2[i]))
361                                         cloth1->verts[collpair->ap2].impulse[i] = i2[i];
362
363                                 if (cloth1->verts[collpair->ap3].impulse_count > 0 && ABS(cloth1->verts[collpair->ap3].impulse[i]) < ABS(i3[i]))
364                                         cloth1->verts[collpair->ap3].impulse[i] = i3[i];
365                         }
366                 }
367         }
368         return result;
369 }
370
371 //Determines collisions on overlap, collisions are written to collpair[i] and collision+number_collision_found is returned
372 static CollPair* cloth_collision(ModifierData *md1, ModifierData *md2,
373                                  BVHTreeOverlap *overlap, CollPair *collpair, float UNUSED(dt))
374 {
375         ClothModifierData *clmd = (ClothModifierData *)md1;
376         CollisionModifierData *collmd = (CollisionModifierData *) md2;
377         /* Cloth *cloth = clmd->clothObject; */ /* UNUSED */
378         MFace *face1=NULL, *face2 = NULL;
379 #ifdef USE_BULLET
380         ClothVertex *verts1 = clmd->clothObject->verts;
381 #endif
382         double distance = 0;
383         float epsilon1 = clmd->coll_parms->epsilon;
384         float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree );
385         int i;
386
387         face1 = & ( clmd->clothObject->mfaces[overlap->indexA] );
388         face2 = & ( collmd->mfaces[overlap->indexB] );
389
390         // check all 4 possible collisions
391         for ( i = 0; i < 4; i++ ) {
392                 if ( i == 0 ) {
393                         // fill faceA
394                         collpair->ap1 = face1->v1;
395                         collpair->ap2 = face1->v2;
396                         collpair->ap3 = face1->v3;
397
398                         // fill faceB
399                         collpair->bp1 = face2->v1;
400                         collpair->bp2 = face2->v2;
401                         collpair->bp3 = face2->v3;
402                 }
403                 else if ( i == 1 ) {
404                         if ( face1->v4 ) {
405                                 // fill faceA
406                                 collpair->ap1 = face1->v1;
407                                 collpair->ap2 = face1->v3;
408                                 collpair->ap3 = face1->v4;
409
410                                 // fill faceB
411                                 collpair->bp1 = face2->v1;
412                                 collpair->bp2 = face2->v2;
413                                 collpair->bp3 = face2->v3;
414                         }
415                         else {
416                                 i++;
417                         }
418                 }
419                 if ( i == 2 ) {
420                         if ( face2->v4 ) {
421                                 // fill faceA
422                                 collpair->ap1 = face1->v1;
423                                 collpair->ap2 = face1->v2;
424                                 collpair->ap3 = face1->v3;
425
426                                 // fill faceB
427                                 collpair->bp1 = face2->v1;
428                                 collpair->bp2 = face2->v4;
429                                 collpair->bp3 = face2->v3;
430                         }
431                         else {
432                                 break;
433                         }
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                 
452 #ifdef USE_BULLET
453                 // calc distance + normal
454                 distance = plNearestPoints (
455                         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 );
456 #else
457                 // just be sure that we don't add anything
458                 distance = 2.0 * (double)( epsilon1 + epsilon2 + ALMOST_ZERO );
459 #endif
460
461                 // distance -1 means no collision result
462                 if (distance != -1.0f && (distance <= (epsilon1 + epsilon2 + ALMOST_ZERO))) {
463                         normalize_v3_v3(collpair->normal, collpair->vector);
464
465                         collpair->distance = distance;
466                         collpair->flag = 0;
467                         collpair++;
468                 }/*
469                 else {
470                         float w1, w2, w3, u1, u2, u3;
471                         float v1[3], v2[3], relativeVelocity[3];
472
473                         // calc relative velocity
474                         
475                         // compute barycentric coordinates for both collision points
476                         collision_compute_barycentric ( collpair->pa,
477                         verts1[collpair->ap1].txold,
478                         verts1[collpair->ap2].txold,
479                         verts1[collpair->ap3].txold,
480                         &w1, &w2, &w3 );
481
482                         // was: txold
483                         collision_compute_barycentric ( collpair->pb,
484                         collmd->current_x[collpair->bp1].co,
485                         collmd->current_x[collpair->bp2].co,
486                         collmd->current_x[collpair->bp3].co,
487                         &u1, &u2, &u3 );
488
489                         // Calculate relative "velocity".
490                         collision_interpolateOnTriangle ( v1, verts1[collpair->ap1].tv, verts1[collpair->ap2].tv, verts1[collpair->ap3].tv, w1, w2, w3 );
491
492                         collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
493
494                         sub_v3_v3v3(relativeVelocity, v2, v1);
495
496                         if (sqrt(dot_v3v3(relativeVelocity, relativeVelocity)) >= distance)
497                         {
498                                 // check for collision in the future
499                                 collpair->flag |= COLLISION_IN_FUTURE;
500                                 collpair++;
501                         }
502                 }*/
503         }
504         return collpair;
505 }
506
507 static void add_collision_object(Object ***objs, unsigned int *numobj, unsigned int *maxobj, Object *ob, Object *self, int level, unsigned int modifier_type)
508 {
509         CollisionModifierData *cmd= NULL;
510
511         if (ob == self)
512                 return;
513
514         /* only get objects with collision modifier */
515         if (((modifier_type == eModifierType_Collision) && ob->pd && ob->pd->deflect) || (modifier_type != eModifierType_Collision))
516                 cmd= (CollisionModifierData *)modifiers_findByType(ob, modifier_type);
517         
518         if (cmd) {
519                 /* extend array */
520                 if (*numobj >= *maxobj) {
521                         *maxobj *= 2;
522                         *objs= MEM_reallocN(*objs, sizeof(Object*)*(*maxobj));
523                 }
524                 
525                 (*objs)[*numobj] = ob;
526                 (*numobj)++;
527         }
528
529         /* objects in dupli groups, one level only for now */
530         if (ob->dup_group && level == 0) {
531                 GroupObject *go;
532                 Group *group= ob->dup_group;
533
534                 /* add objects */
535                 for (go= group->gobject.first; go; go= go->next)
536                         add_collision_object(objs, numobj, maxobj, go->ob, self, level+1, modifier_type);
537         }
538 }
539
540 // return all collision objects in scene
541 // collision object will exclude self 
542 Object **get_collisionobjects(Scene *scene, Object *self, Group *group, unsigned int *numcollobj, unsigned int modifier_type)
543 {
544         Base *base;
545         Object **objs;
546         GroupObject *go;
547         unsigned int numobj= 0, maxobj= 100;
548         
549         objs= MEM_callocN(sizeof(Object *)*maxobj, "CollisionObjectsArray");
550
551         /* gather all collision objects */
552         if (group) {
553                 /* use specified group */
554                 for (go= group->gobject.first; go; go= go->next)
555                         add_collision_object(&objs, &numobj, &maxobj, go->ob, self, 0, modifier_type);
556         }
557         else {
558                 Scene *sce_iter;
559                 /* add objects in same layer in scene */
560                 for (SETLOOPER(scene, sce_iter, base)) {
561                         if (base->lay & self->lay)
562                                 add_collision_object(&objs, &numobj, &maxobj, base->object, self, 0, modifier_type);
563
564                 }
565         }
566
567         *numcollobj= numobj;
568
569         return objs;
570 }
571
572 static void add_collider_cache_object(ListBase **objs, Object *ob, Object *self, int level)
573 {
574         CollisionModifierData *cmd= NULL;
575         ColliderCache *col;
576
577         if (ob == self)
578                 return;
579
580         if (ob->pd && ob->pd->deflect)
581                 cmd =(CollisionModifierData *)modifiers_findByType(ob, eModifierType_Collision);
582         
583         if (cmd && cmd->bvhtree) {
584                 if (*objs == NULL)
585                         *objs = MEM_callocN(sizeof(ListBase), "ColliderCache array");
586
587                 col = MEM_callocN(sizeof(ColliderCache), "ColliderCache");
588                 col->ob = ob;
589                 col->collmd = cmd;
590                 /* make sure collider is properly set up */
591                 collision_move_object(cmd, 1.0, 0.0);
592                 BLI_addtail(*objs, col);
593         }
594
595         /* objects in dupli groups, one level only for now */
596         if (ob->dup_group && level == 0) {
597                 GroupObject *go;
598                 Group *group= ob->dup_group;
599
600                 /* add objects */
601                 for (go= group->gobject.first; go; go= go->next)
602                         add_collider_cache_object(objs, go->ob, self, level+1);
603         }
604 }
605
606 ListBase *get_collider_cache(Scene *scene, Object *self, Group *group)
607 {
608         GroupObject *go;
609         ListBase *objs= NULL;
610         
611         /* add object in same layer in scene */
612         if (group) {
613                 for (go= group->gobject.first; go; go= go->next)
614                         add_collider_cache_object(&objs, go->ob, self, 0);
615         }
616         else {
617                 Scene *sce_iter;
618                 Base *base;
619
620                 /* add objects in same layer in scene */
621                 for (SETLOOPER(scene, sce_iter, base)) {
622                         if (!self || (base->lay & self->lay))
623                                 add_collider_cache_object(&objs, base->object, self, 0);
624
625                 }
626         }
627
628         return objs;
629 }
630
631 void free_collider_cache(ListBase **colliders)
632 {
633         if (*colliders) {
634                 BLI_freelistN(*colliders);
635                 MEM_freeN(*colliders);
636                 *colliders = NULL;
637         }
638 }
639
640
641 static void cloth_bvh_objcollisions_nearcheck ( ClothModifierData * clmd, CollisionModifierData *collmd,
642         CollPair **collisions, CollPair **collisions_index, int numresult, BVHTreeOverlap *overlap, double dt)
643 {
644         int i;
645         
646         *collisions = (CollPair *) MEM_mallocN(sizeof(CollPair) * numresult * 64, "collision array" ); //*4 since cloth_collision_static can return more than 1 collision
647         *collisions_index = *collisions;
648
649         for ( i = 0; i < numresult; i++ ) {
650                 *collisions_index = cloth_collision ( (ModifierData *)clmd, (ModifierData *)collmd,
651                                                       overlap+i, *collisions_index, dt );
652         }
653 }
654
655 static int cloth_bvh_objcollisions_resolve ( ClothModifierData * clmd, CollisionModifierData *collmd, CollPair *collisions, CollPair *collisions_index)
656 {
657         Cloth *cloth = clmd->clothObject;
658         int i=0, j = 0, /*numfaces = 0, */ numverts = 0;
659         ClothVertex *verts = NULL;
660         int ret = 0;
661         int result = 0;
662         
663         numverts = clmd->clothObject->numverts;
664         verts = cloth->verts;
665         
666         // process all collisions (calculate impulses, TODO: also repulses if distance too short)
667         result = 1;
668         for ( j = 0; j < 2; j++ ) { /* 5 is just a value that ensures convergence */
669                 result = 0;
670
671                 if ( collmd->bvhtree ) {
672                         result += cloth_collision_response_static ( clmd, collmd, collisions, collisions_index );
673
674                         // apply impulses in parallel
675                         if (result) {
676                                 for (i = 0; i < numverts; i++) {
677                                         // calculate "velocities" (just xnew = xold + v; no dt in v)
678                                         if (verts[i].impulse_count) {
679                                                 // VECADDMUL ( verts[i].tv, verts[i].impulse, 1.0f / verts[i].impulse_count );
680                                                 VECADD ( verts[i].tv, verts[i].tv, verts[i].impulse);
681                                                 zero_v3(verts[i].impulse);
682                                                 verts[i].impulse_count = 0;
683
684                                                 ret++;
685                                         }
686                                 }
687                         }
688                 }
689
690                 if (!result) {
691                         break;
692                 }
693         }
694         return ret;
695 }
696
697 // cloth - object collisions
698 int cloth_bvh_objcollision(Object *ob, ClothModifierData * clmd, float step, float dt )
699 {
700         Cloth *cloth= clmd->clothObject;
701         BVHTree *cloth_bvh= cloth->bvhtree;
702         unsigned int i=0, /* numfaces = 0, */ /* UNUSED */ numverts = 0, k, l, j;
703         int rounds = 0; // result counts applied collisions; ic is for debug output;
704         ClothVertex *verts = NULL;
705         int ret = 0, ret2 = 0;
706         Object **collobjs = NULL;
707         unsigned int numcollobj = 0;
708
709         if ((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_COLLOBJ) || cloth_bvh==NULL)
710                 return 0;
711         
712         verts = cloth->verts;
713         /* numfaces = cloth->numfaces; */ /* UNUSED */
714         numverts = cloth->numverts;
715
716         ////////////////////////////////////////////////////////////
717         // static collisions
718         ////////////////////////////////////////////////////////////
719
720         // update cloth bvh
721         bvhtree_update_from_cloth ( clmd, 1 ); // 0 means STATIC, 1 means MOVING (see later in this function)
722         bvhselftree_update_from_cloth ( clmd, 0 ); // 0 means STATIC, 1 means MOVING (see later in this function)
723         
724         collobjs = get_collisionobjects(clmd->scene, ob, clmd->coll_parms->group, &numcollobj, eModifierType_Collision);
725         
726         if (!collobjs)
727                 return 0;
728
729         /* move object to position (step) in time */
730         for (i = 0; i < numcollobj; i++) {
731                 Object *collob= collobjs[i];
732                 CollisionModifierData *collmd = (CollisionModifierData*)modifiers_findByType(collob, eModifierType_Collision);
733
734                 if (!collmd->bvhtree)
735                         continue;
736
737                 /* move object to position (step) in time */
738                 collision_move_object ( collmd, step + dt, step );
739         }
740
741         do {
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 }