Bugfix [#27157] keyframing a constrained bone does not work as before
[blender.git] / source / blender / blenlib / intern / BLI_kdopbvh.c
1 /*
2  *
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  *
19  * The Original Code is Copyright (C) 2006 by NaN Holding BV.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): Daniel Genrich, Andre Pinto
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /** \file blender/blenlib/intern/BLI_kdopbvh.c
30  *  \ingroup bli
31  */
32
33
34 #include <assert.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_utildefines.h"
39
40
41
42 #include "BLI_kdopbvh.h"
43 #include "BLI_math.h"
44
45 #ifdef _OPENMP
46 #include <omp.h>
47 #endif
48
49
50
51 #define MAX_TREETYPE 32
52 #define DEFAULT_FIND_NEAREST_HEAP_SIZE 1024
53
54 typedef struct BVHNode
55 {
56         struct BVHNode **children;
57         struct BVHNode *parent; // some user defined traversed need that
58         struct BVHNode *skip[2];
59         float *bv;              // Bounding volume of all nodes, max 13 axis
60         int index;              // face, edge, vertex index
61         char totnode;   // how many nodes are used, used for speedup
62         char main_axis; // Axis used to split this node
63 } BVHNode;
64
65 struct BVHTree
66 {
67         BVHNode **nodes;
68         BVHNode *nodearray; /* pre-alloc branch nodes */
69         BVHNode **nodechild;    // pre-alloc childs for nodes
70         float   *nodebv;                // pre-alloc bounding-volumes for nodes
71         float   epsilon; /* epslion is used for inflation of the k-dop     */
72         int     totleaf; // leafs
73         int     totbranch;
74         char    tree_type; // type of tree (4 => quadtree)
75         char    axis; // kdop type (6 => OBB, 7 => AABB, ...)
76         char    start_axis, stop_axis; // KDOP_AXES array indices according to axis
77 };
78
79 typedef struct BVHOverlapData 
80 {  
81         BVHTree *tree1, *tree2; 
82         BVHTreeOverlap *overlap; 
83         int i, max_overlap; /* i is number of overlaps */
84         int start_axis, stop_axis;
85 } BVHOverlapData;
86
87 typedef struct BVHNearestData
88 {
89         BVHTree *tree;
90         const float     *co;
91         BVHTree_NearestPointCallback callback;
92         void    *userdata;
93         float proj[13];                 //coordinates projection over axis
94         BVHTreeNearest nearest;
95
96 } BVHNearestData;
97
98 typedef struct BVHRayCastData
99 {
100         BVHTree *tree;
101
102         BVHTree_RayCastCallback callback;
103         void    *userdata;
104
105
106         BVHTreeRay    ray;
107         float ray_dot_axis[13];
108         float idot_axis[13];
109         int index[6];
110
111         BVHTreeRayHit hit;
112 } BVHRayCastData;
113 ////////////////////////////////////////m
114
115
116 ////////////////////////////////////////////////////////////////////////
117 // Bounding Volume Hierarchy Definition
118 // 
119 // Notes: From OBB until 26-DOP --> all bounding volumes possible, just choose type below
120 // Notes: You have to choose the type at compile time ITM
121 // Notes: You can choose the tree type --> binary, quad, octree, choose below
122 ////////////////////////////////////////////////////////////////////////
123
124 static float KDOP_AXES[13][3] =
125 { {1.0, 0, 0}, {0, 1.0, 0}, {0, 0, 1.0}, {1.0, 1.0, 1.0}, {1.0, -1.0, 1.0}, {1.0, 1.0, -1.0},
126 {1.0, -1.0, -1.0}, {1.0, 1.0, 0}, {1.0, 0, 1.0}, {0, 1.0, 1.0}, {1.0, -1.0, 0}, {1.0, 0, -1.0},
127 {0, 1.0, -1.0}
128 };
129
130 /*
131  * Generic push and pop heap
132  */
133 #define PUSH_HEAP_BODY(HEAP_TYPE,PRIORITY,heap,heap_size)       \
134 {                                                                                                       \
135         HEAP_TYPE element = heap[heap_size-1];                  \
136         int child = heap_size-1;                                                \
137         while(child != 0)                                                               \
138         {                                                                                               \
139                 int parent = (child-1) / 2;                                     \
140                 if(PRIORITY(element, heap[parent]))                     \
141                 {                                                                                       \
142                         heap[child] = heap[parent];                             \
143                         child = parent;                                                 \
144                 }                                                                                       \
145                 else break;                                                                     \
146         }                                                                                               \
147         heap[child] = element;                                                  \
148 }
149
150 #define POP_HEAP_BODY(HEAP_TYPE, PRIORITY,heap,heap_size)       \
151 {                                                                                                       \
152         HEAP_TYPE element = heap[heap_size-1];                  \
153         int parent = 0;                                                                 \
154         while(parent < (heap_size-1)/2 )                                \
155         {                                                                                               \
156                 int child2 = (parent+1)*2;                                      \
157                 if(PRIORITY(heap[child2-1], heap[child2]))      \
158                         --child2;                                                               \
159                                                                                                         \
160                 if(PRIORITY(element, heap[child2]))                     \
161                         break;                                                                  \
162                                                                                                         \
163                 heap[parent] = heap[child2];                            \
164                 parent = child2;                                                        \
165         }                                                                                               \
166         heap[parent] = element;                                                 \
167 }
168
169 #if 0
170 static int ADJUST_MEMORY(void *local_memblock, void **memblock, int new_size, int *max_size, int size_per_item)
171 {
172         int   new_max_size = *max_size * 2;
173         void *new_memblock = NULL;
174
175         if(new_size <= *max_size)
176                 return TRUE;
177
178         if(*memblock == local_memblock)
179         {
180                 new_memblock = malloc( size_per_item * new_max_size );
181                 memcpy( new_memblock, *memblock, size_per_item * *max_size );
182         }
183         else
184                 new_memblock = realloc(*memblock, size_per_item * new_max_size );
185
186         if(new_memblock)
187         {
188                 *memblock = new_memblock;
189                 *max_size = new_max_size;
190                 return TRUE;
191         }
192         else
193                 return FALSE;
194 }
195 #endif
196
197 //////////////////////////////////////////////////////////////////////////////////////////////////////
198 // Introsort 
199 // with permission deriven from the following Java code:
200 // http://ralphunden.net/content/tutorials/a-guide-to-introsort/
201 // and he derived it from the SUN STL 
202 //////////////////////////////////////////////////////////////////////////////////////////////////////
203 //static int size_threshold = 16;
204 /*
205 * Common methods for all algorithms
206 */
207 /*static int floor_lg(int a)
208 {
209         return (int)(floor(log(a)/log(2)));
210 }*/
211
212 /*
213 * Insertion sort algorithm
214 */
215 static void bvh_insertionsort(BVHNode **a, int lo, int hi, int axis)
216 {
217         int i,j;
218         BVHNode *t;
219         for (i=lo; i < hi; i++)
220         {
221                 j=i;
222                 t = a[i];
223                 while((j!=lo) && (t->bv[axis] < (a[j-1])->bv[axis]))
224                 {
225                         a[j] = a[j-1];
226                         j--;
227                 }
228                 a[j] = t;
229         }
230 }
231
232 static int bvh_partition(BVHNode **a, int lo, int hi, BVHNode * x, int axis)
233 {
234         int i=lo, j=hi;
235         while (1)
236         {
237                 while ((a[i])->bv[axis] < x->bv[axis]) i++;
238                 j--;
239                 while (x->bv[axis] < (a[j])->bv[axis]) j--;
240                 if(!(i < j))
241                         return i;
242                 SWAP( BVHNode* , a[i], a[j]);
243                 i++;
244         }
245 }
246
247 /*
248 * Heapsort algorithm
249 */
250 #if 0
251 static void bvh_downheap(BVHNode **a, int i, int n, int lo, int axis)
252 {
253         BVHNode * d = a[lo+i-1];
254         int child;
255         while (i<=n/2)
256         {
257                 child = 2*i;
258                 if ((child < n) && ((a[lo+child-1])->bv[axis] < (a[lo+child])->bv[axis]))
259                 {
260                         child++;
261                 }
262                 if (!(d->bv[axis] < (a[lo+child-1])->bv[axis])) break;
263                 a[lo+i-1] = a[lo+child-1];
264                 i = child;
265         }
266         a[lo+i-1] = d;
267 }
268
269 static void bvh_heapsort(BVHNode **a, int lo, int hi, int axis)
270 {
271         int n = hi-lo, i;
272         for (i=n/2; i>=1; i=i-1)
273         {
274                 bvh_downheap(a, i,n,lo, axis);
275         }
276         for (i=n; i>1; i=i-1)
277         {
278                 SWAP(BVHNode*, a[lo],a[lo+i-1]);
279                 bvh_downheap(a, 1,i-1,lo, axis);
280         }
281 }
282 #endif
283
284 static BVHNode *bvh_medianof3(BVHNode **a, int lo, int mid, int hi, int axis) // returns Sortable
285 {
286         if ((a[mid])->bv[axis] < (a[lo])->bv[axis])
287         {
288                 if ((a[hi])->bv[axis] < (a[mid])->bv[axis])
289                         return a[mid];
290                 else
291                 {
292                         if ((a[hi])->bv[axis] < (a[lo])->bv[axis])
293                                 return a[hi];
294                         else
295                                 return a[lo];
296                 }
297         }
298         else
299         {
300                 if ((a[hi])->bv[axis] < (a[mid])->bv[axis])
301                 {
302                         if ((a[hi])->bv[axis] < (a[lo])->bv[axis])
303                                 return a[lo];
304                         else
305                                 return a[hi];
306                 }
307                 else
308                         return a[mid];
309         }
310 }
311
312 #if 0
313 /*
314 * Quicksort algorithm modified for Introsort
315 */
316 static void bvh_introsort_loop (BVHNode **a, int lo, int hi, int depth_limit, int axis)
317 {
318         int p;
319
320         while (hi-lo > size_threshold)
321         {
322                 if (depth_limit == 0)
323                 {
324                         bvh_heapsort(a, lo, hi, axis);
325                         return;
326                 }
327                 depth_limit=depth_limit-1;
328                 p=bvh_partition(a, lo, hi, bvh_medianof3(a, lo, lo+((hi-lo)/2)+1, hi-1, axis), axis);
329                 bvh_introsort_loop(a, p, hi, depth_limit, axis);
330                 hi=p;
331         }
332 }
333
334 static void sort(BVHNode **a0, int begin, int end, int axis)
335 {
336         if (begin < end)
337         {
338                 BVHNode **a=a0;
339                 bvh_introsort_loop(a, begin, end, 2*floor_lg(end-begin), axis);
340                 bvh_insertionsort(a, begin, end, axis);
341         }
342 }
343
344 static void sort_along_axis(BVHTree *tree, int start, int end, int axis)
345 {
346         sort(tree->nodes, start, end, axis);
347 }
348 #endif
349
350 //after a call to this function you can expect one of:
351 //      every node to left of a[n] are smaller or equal to it
352 //      every node to the right of a[n] are greater or equal to it
353 static int partition_nth_element(BVHNode **a, int _begin, int _end, int n, int axis){
354         int begin = _begin, end = _end, cut;
355         while(end-begin > 3)
356         {
357                 cut = bvh_partition(a, begin, end, bvh_medianof3(a, begin, (begin+end)/2, end-1, axis), axis );
358                 if(cut <= n)
359                         begin = cut;
360                 else
361                         end = cut;
362         }
363         bvh_insertionsort(a, begin, end, axis);
364
365         return n;
366 }
367
368 //////////////////////////////////////////////////////////////////////////////////////////////////////
369 static void build_skip_links(BVHTree *tree, BVHNode *node, BVHNode *left, BVHNode *right)
370 {
371         int i;
372         
373         node->skip[0] = left;
374         node->skip[1] = right;
375         
376         for (i = 0; i < node->totnode; i++)
377         {
378                 if(i+1 < node->totnode)
379                         build_skip_links(tree, node->children[i], left, node->children[i+1] );
380                 else
381                         build_skip_links(tree, node->children[i], left, right );
382
383                 left = node->children[i];
384         }
385 }
386
387 /*
388  * BVHTree bounding volumes functions
389  */
390 static void create_kdop_hull(BVHTree *tree, BVHNode *node, float *co, int numpoints, int moving)
391 {
392         float newminmax;
393         float *bv = node->bv;
394         int i, k;
395         
396         // don't init boudings for the moving case
397         if(!moving)
398         {
399                 for (i = tree->start_axis; i < tree->stop_axis; i++)
400                 {
401                         bv[2*i] = FLT_MAX;
402                         bv[2*i + 1] = -FLT_MAX;
403                 }
404         }
405         
406         for(k = 0; k < numpoints; k++)
407         {
408                 // for all Axes.
409                 for (i = tree->start_axis; i < tree->stop_axis; i++)
410                 {
411                         newminmax = INPR(&co[k * 3], KDOP_AXES[i]);
412                         if (newminmax < bv[2 * i])
413                                 bv[2 * i] = newminmax;
414                         if (newminmax > bv[(2 * i) + 1])
415                                 bv[(2 * i) + 1] = newminmax;
416                 }
417         }
418 }
419
420 // depends on the fact that the BVH's for each face is already build
421 static void refit_kdop_hull(BVHTree *tree, BVHNode *node, int start, int end)
422 {
423         float newmin,newmax;
424         int i, j;
425         float *bv = node->bv;
426
427         
428         for (i = tree->start_axis; i < tree->stop_axis; i++)
429         {
430                 bv[2*i] = FLT_MAX;
431                 bv[2*i + 1] = -FLT_MAX;
432         }
433
434         for (j = start; j < end; j++)
435         {
436 // for all Axes.
437                 for (i = tree->start_axis; i < tree->stop_axis; i++)
438                 {
439                         newmin = tree->nodes[j]->bv[(2 * i)];   
440                         if ((newmin < bv[(2 * i)]))
441                                 bv[(2 * i)] = newmin;
442  
443                         newmax = tree->nodes[j]->bv[(2 * i) + 1];
444                         if ((newmax > bv[(2 * i) + 1]))
445                                 bv[(2 * i) + 1] = newmax;
446                 }
447         }
448
449 }
450
451 // only supports x,y,z axis in the moment
452 // but we should use a plain and simple function here for speed sake
453 static char get_largest_axis(float *bv)
454 {
455         float middle_point[3];
456
457         middle_point[0] = (bv[1]) - (bv[0]); // x axis
458         middle_point[1] = (bv[3]) - (bv[2]); // y axis
459         middle_point[2] = (bv[5]) - (bv[4]); // z axis
460         if (middle_point[0] > middle_point[1]) 
461         {
462                 if (middle_point[0] > middle_point[2])
463                         return 1; // max x axis
464                 else
465                         return 5; // max z axis
466         }
467         else 
468         {
469                 if (middle_point[1] > middle_point[2])
470                         return 3; // max y axis
471                 else
472                         return 5; // max z axis
473         }
474 }
475
476 // bottom-up update of bvh node BV
477 // join the children on the parent BV
478 static void node_join(BVHTree *tree, BVHNode *node)
479 {
480         int i, j;
481         
482         for (i = tree->start_axis; i < tree->stop_axis; i++)
483         {
484                 node->bv[2*i] = FLT_MAX;
485                 node->bv[2*i + 1] = -FLT_MAX;
486         }
487         
488         for (i = 0; i < tree->tree_type; i++)
489         {
490                 if (node->children[i]) 
491                 {
492                         for (j = tree->start_axis; j < tree->stop_axis; j++)
493                         {
494                                 // update minimum 
495                                 if (node->children[i]->bv[(2 * j)] < node->bv[(2 * j)]) 
496                                         node->bv[(2 * j)] = node->children[i]->bv[(2 * j)];
497                                 
498                                 // update maximum 
499                                 if (node->children[i]->bv[(2 * j) + 1] > node->bv[(2 * j) + 1])
500                                         node->bv[(2 * j) + 1] = node->children[i]->bv[(2 * j) + 1];
501                         }
502                 }
503                 else
504                         break;
505         }
506 }
507
508 /*
509  * Debug and information functions
510  */
511 #if 0
512 static void bvhtree_print_tree(BVHTree *tree, BVHNode *node, int depth)
513 {
514         int i;
515         for(i=0; i<depth; i++) printf(" ");
516         printf(" - %d (%ld): ", node->index, node - tree->nodearray);
517         for(i=2*tree->start_axis; i<2*tree->stop_axis; i++)
518                 printf("%.3f ", node->bv[i]);
519         printf("\n");
520
521         for(i=0; i<tree->tree_type; i++)
522                 if(node->children[i])
523                         bvhtree_print_tree(tree, node->children[i], depth+1);
524 }
525
526 static void bvhtree_info(BVHTree *tree)
527 {
528         printf("BVHTree info\n");
529         printf("tree_type = %d, axis = %d, epsilon = %f\n", tree->tree_type, tree->axis, tree->epsilon);
530         printf("nodes = %d, branches = %d, leafs = %d\n", tree->totbranch + tree->totleaf,  tree->totbranch, tree->totleaf);
531         printf("Memory per node = %ldbytes\n", sizeof(BVHNode) + sizeof(BVHNode*)*tree->tree_type + sizeof(float)*tree->axis);
532         printf("BV memory = %dbytes\n", MEM_allocN_len(tree->nodebv));
533
534         printf("Total memory = %ldbytes\n", sizeof(BVHTree)
535                 + MEM_allocN_len(tree->nodes)
536                 + MEM_allocN_len(tree->nodearray)
537                 + MEM_allocN_len(tree->nodechild)
538                 + MEM_allocN_len(tree->nodebv)
539                 );
540
541 //      bvhtree_print_tree(tree, tree->nodes[tree->totleaf], 0);
542 }
543 #endif
544
545 #if 0
546
547
548 static void verify_tree(BVHTree *tree)
549 {
550         int i, j, check = 0;
551         
552         // check the pointer list
553         for(i = 0; i < tree->totleaf; i++)
554         {
555                 if(tree->nodes[i]->parent == NULL)
556                         printf("Leaf has no parent: %d\n", i);
557                 else
558                 {
559                         for(j = 0; j < tree->tree_type; j++)
560                         {
561                                 if(tree->nodes[i]->parent->children[j] == tree->nodes[i])
562                                         check = 1;
563                         }
564                         if(!check)
565                         {
566                                 printf("Parent child relationship doesn't match: %d\n", i);
567                         }
568                         check = 0;
569                 }
570         }
571         
572         // check the leaf list
573         for(i = 0; i < tree->totleaf; i++)
574         {
575                 if(tree->nodearray[i].parent == NULL)
576                         printf("Leaf has no parent: %d\n", i);
577                 else
578                 {
579                         for(j = 0; j < tree->tree_type; j++)
580                         {
581                                 if(tree->nodearray[i].parent->children[j] == &tree->nodearray[i])
582                                         check = 1;
583                         }
584                         if(!check)
585                         {
586                                 printf("Parent child relationship doesn't match: %d\n", i);
587                         }
588                         check = 0;
589                 }
590         }
591         
592         printf("branches: %d, leafs: %d, total: %d\n", tree->totbranch, tree->totleaf, tree->totbranch + tree->totleaf);
593 }
594 #endif
595
596 //Helper data and structures to build a min-leaf generalized implicit tree
597 //This code can be easily reduced (basicly this is only method to calculate pow(k, n) in O(1).. and stuff like that)
598 typedef struct BVHBuildHelper
599 {
600         int tree_type;                          //
601         int totleafs;                           //
602
603         int leafs_per_child  [32];      //Min number of leafs that are archievable from a node at depth N
604         int branches_on_level[32];      //Number of nodes at depth N (tree_type^N)
605
606         int remain_leafs;                       //Number of leafs that are placed on the level that is not 100% filled
607
608 } BVHBuildHelper;
609
610 static void build_implicit_tree_helper(BVHTree *tree, BVHBuildHelper *data)
611 {
612         int depth = 0;
613         int remain;
614         int nnodes;
615
616         data->totleafs = tree->totleaf;
617         data->tree_type= tree->tree_type;
618
619         //Calculate the smallest tree_type^n such that tree_type^n >= num_leafs
620         for(
621                 data->leafs_per_child[0] = 1;
622                 data->leafs_per_child[0] <  data->totleafs;
623                 data->leafs_per_child[0] *= data->tree_type
624         );
625
626         data->branches_on_level[0] = 1;
627
628         //We could stop the loop first (but I am lazy to find out when)
629         for(depth = 1; depth < 32; depth++)
630         {
631                 data->branches_on_level[depth] = data->branches_on_level[depth-1] * data->tree_type;
632                 data->leafs_per_child  [depth] = data->leafs_per_child  [depth-1] / data->tree_type;
633         }
634
635         remain = data->totleafs - data->leafs_per_child[1];
636         nnodes = (remain + data->tree_type - 2) / (data->tree_type - 1);
637         data->remain_leafs = remain + nnodes;
638 }
639
640 // return the min index of all the leafs archivable with the given branch
641 static int implicit_leafs_index(BVHBuildHelper *data, int depth, int child_index)
642 {
643         int min_leaf_index = child_index * data->leafs_per_child[depth-1];
644         if(min_leaf_index <= data->remain_leafs)
645                 return min_leaf_index;
646         else if(data->leafs_per_child[depth])
647                 return data->totleafs - (data->branches_on_level[depth-1] - child_index) * data->leafs_per_child[depth];
648         else
649                 return data->remain_leafs;
650 }
651
652 /**
653  * Generalized implicit tree build
654  *
655  * An implicit tree is a tree where its structure is implied, thus there is no need to store child pointers or indexs.
656  * Its possible to find the position of the child or the parent with simple maths (multiplication and adittion). This type
657  * of tree is for example used on heaps.. where node N has its childs at indexs N*2 and N*2+1.
658  *
659  * Altought in this case the tree type is general.. and not know until runtime.
660  * tree_type stands for the maximum number of childs that a tree node can have.
661  * All tree types >= 2 are supported.
662  *
663  * Advantages of the used trees include:
664  *  - No need to store child/parent relations (they are implicit);
665  *  - Any node child always has an index greater than the parent;
666  *  - Brother nodes are sequencial in memory;
667  *
668  *
669  * Some math relations derived for general implicit trees:
670  *
671  *   K = tree_type, ( 2 <= K )
672  *   ROOT = 1
673  *   N child of node A = A * K + (2 - K) + N, (0 <= N < K)
674  *
675  * Util methods:
676  *   TODO...
677  *    (looping elements, knowing if its a leaf or not.. etc...)
678  */
679
680 // This functions returns the number of branches needed to have the requested number of leafs.
681 static int implicit_needed_branches(int tree_type, int leafs)
682 {
683         return MAX2(1, (leafs + tree_type - 3) / (tree_type-1) );
684 }
685
686 /*
687  * This function handles the problem of "sorting" the leafs (along the split_axis).
688  *
689  * It arranges the elements in the given partitions such that:
690  *  - any element in partition N is less or equal to any element in partition N+1.
691  *  - if all elements are diferent all partition will get the same subset of elements
692  *    as if the array was sorted.
693  *
694  * partition P is described as the elements in the range ( nth[P] , nth[P+1] ]
695  *
696  * TODO: This can be optimized a bit by doing a specialized nth_element instead of K nth_elements
697  */
698 static void split_leafs(BVHNode **leafs_array, int *nth, int partitions, int split_axis)
699 {
700         int i;
701         for(i=0; i < partitions-1; i++)
702         {
703                 if(nth[i] >= nth[partitions])
704                         break;
705
706                 partition_nth_element(leafs_array, nth[i], nth[partitions], nth[i+1], split_axis);
707         }
708 }
709
710 /*
711  * This functions builds an optimal implicit tree from the given leafs.
712  * Where optimal stands for:
713  *  - The resulting tree will have the smallest number of branches;
714  *  - At most only one branch will have NULL childs;
715  *  - All leafs will be stored at level N or N+1.
716  *
717  * This function creates an implicit tree on branches_array, the leafs are given on the leafs_array.
718  *
719  * The tree is built per depth levels. First branchs at depth 1.. then branches at depth 2.. etc..
720  * The reason is that we can build level N+1 from level N witouth any data dependencies.. thus it allows
721  * to use multithread building.
722  *
723  * To archieve this is necessary to find how much leafs are accessible from a certain branch, BVHBuildHelper
724  * implicit_needed_branches and implicit_leafs_index are auxiliar functions to solve that "optimal-split".
725  */
726 static void non_recursive_bvh_div_nodes(BVHTree *tree, BVHNode *branches_array, BVHNode **leafs_array, int num_leafs)
727 {
728         int i;
729
730         const int tree_type   = tree->tree_type;
731         const int tree_offset = 2 - tree->tree_type; //this value is 0 (on binary trees) and negative on the others
732         const int num_branches= implicit_needed_branches(tree_type, num_leafs);
733
734         BVHBuildHelper data;
735         int depth;
736         
737         // set parent from root node to NULL
738         BVHNode *tmp = branches_array+0;
739         tmp->parent = NULL;
740
741         //Most of bvhtree code relies on 1-leaf trees having at least one branch
742         //We handle that special case here
743         if(num_leafs == 1)
744         {
745                 BVHNode *root = branches_array+0;
746                 refit_kdop_hull(tree, root, 0, num_leafs);
747                 root->main_axis = get_largest_axis(root->bv) / 2;
748                 root->totnode = 1;
749                 root->children[0] = leafs_array[0];
750                 root->children[0]->parent = root;
751                 return;
752         }
753
754         branches_array--;       //Implicit trees use 1-based indexs
755         
756         build_implicit_tree_helper(tree, &data);
757
758         //Loop tree levels (log N) loops
759         for(i=1, depth = 1; i <= num_branches; i = i*tree_type + tree_offset, depth++)
760         {
761                 const int first_of_next_level = i*tree_type + tree_offset;
762                 const int  end_j = MIN2(first_of_next_level, num_branches + 1); //index of last branch on this level
763                 int j;
764
765                 //Loop all branches on this level
766 #pragma omp parallel for private(j) schedule(static)
767                 for(j = i; j < end_j; j++)
768                 {
769                         int k;
770                         const int parent_level_index= j-i;
771                         BVHNode* parent = branches_array + j;
772                         int nth_positions[ MAX_TREETYPE + 1];
773                         char split_axis;
774
775                         int parent_leafs_begin = implicit_leafs_index(&data, depth, parent_level_index);
776                         int parent_leafs_end   = implicit_leafs_index(&data, depth, parent_level_index+1);
777
778                         //This calculates the bounding box of this branch
779                         //and chooses the largest axis as the axis to divide leafs
780                         refit_kdop_hull(tree, parent, parent_leafs_begin, parent_leafs_end);
781                         split_axis = get_largest_axis(parent->bv);
782
783                         //Save split axis (this can be used on raytracing to speedup the query time)
784                         parent->main_axis = split_axis / 2;
785
786                         //Split the childs along the split_axis, note: its not needed to sort the whole leafs array
787                         //Only to assure that the elements are partioned on a way that each child takes the elements
788                         //it would take in case the whole array was sorted.
789                         //Split_leafs takes care of that "sort" problem.
790                         nth_positions[        0] = parent_leafs_begin;
791                         nth_positions[tree_type] = parent_leafs_end;
792                         for(k = 1; k < tree_type; k++)
793                         {
794                                 int child_index = j * tree_type + tree_offset + k;
795                                 int child_level_index = child_index - first_of_next_level; //child level index
796                                 nth_positions[k] = implicit_leafs_index(&data, depth+1, child_level_index);
797                         }
798
799                         split_leafs(leafs_array, nth_positions, tree_type, split_axis);
800
801
802                         //Setup children and totnode counters
803                         //Not really needed but currently most of BVH code relies on having an explicit children structure
804                         for(k = 0; k < tree_type; k++)
805                         {
806                                 int child_index = j * tree_type + tree_offset + k;
807                                 int child_level_index = child_index - first_of_next_level; //child level index
808
809                                 int child_leafs_begin = implicit_leafs_index(&data, depth+1, child_level_index);
810                                 int child_leafs_end   = implicit_leafs_index(&data, depth+1, child_level_index+1);
811
812                                 if(child_leafs_end - child_leafs_begin > 1)
813                                 {
814                                         parent->children[k] = branches_array + child_index;
815                                         parent->children[k]->parent = parent;
816                                 }
817                                 else if(child_leafs_end - child_leafs_begin == 1)
818                                 {
819                                         parent->children[k] = leafs_array[ child_leafs_begin ];
820                                         parent->children[k]->parent = parent;
821                                 }
822                                 else
823                                         break;
824
825                                 parent->totnode = k+1;
826                         }
827                 }
828         }
829 }
830
831
832 /*
833  * BLI_bvhtree api
834  */
835 BVHTree *BLI_bvhtree_new(int maxsize, float epsilon, char tree_type, char axis)
836 {
837         BVHTree *tree;
838         int numnodes, i;
839         
840         // theres not support for trees below binary-trees :P
841         if(tree_type < 2)
842                 return NULL;
843         
844         if(tree_type > MAX_TREETYPE)
845                 return NULL;
846
847         tree = (BVHTree *)MEM_callocN(sizeof(BVHTree), "BVHTree");
848
849         //tree epsilon must be >= FLT_EPSILON
850         //so that tangent rays can still hit a bounding volume..
851         //this bug would show up when casting a ray aligned with a kdop-axis and with an edge of 2 faces
852         epsilon = MAX2(FLT_EPSILON, epsilon);
853         
854         if(tree)
855         {
856                 tree->epsilon = epsilon;
857                 tree->tree_type = tree_type; 
858                 tree->axis = axis;
859                 
860                 if(axis == 26)
861                 {
862                         tree->start_axis = 0;
863                         tree->stop_axis = 13;
864                 }
865                 else if(axis == 18)
866                 {
867                         tree->start_axis = 7;
868                         tree->stop_axis = 13;
869                 }
870                 else if(axis == 14)
871                 {
872                         tree->start_axis = 0;
873                         tree->stop_axis = 7;
874                 }
875                 else if(axis == 8) // AABB
876                 {
877                         tree->start_axis = 0;
878                         tree->stop_axis = 4;
879                 }
880                 else if(axis == 6) // OBB
881                 {
882                         tree->start_axis = 0;
883                         tree->stop_axis = 3;
884                 }
885                 else
886                 {
887                         MEM_freeN(tree);
888                         return NULL;
889                 }
890
891
892                 //Allocate arrays
893                 numnodes = maxsize + implicit_needed_branches(tree_type, maxsize) + tree_type;
894
895                 tree->nodes = (BVHNode **)MEM_callocN(sizeof(BVHNode *)*numnodes, "BVHNodes");
896                 
897                 if(!tree->nodes)
898                 {
899                         MEM_freeN(tree);
900                         return NULL;
901                 }
902                 
903                 tree->nodebv = (float*)MEM_callocN(sizeof(float)* axis * numnodes, "BVHNodeBV");
904                 if(!tree->nodebv)
905                 {
906                         MEM_freeN(tree->nodes);
907                         MEM_freeN(tree);
908                 }
909
910                 tree->nodechild = (BVHNode**)MEM_callocN(sizeof(BVHNode*) * tree_type * numnodes, "BVHNodeBV");
911                 if(!tree->nodechild)
912                 {
913                         MEM_freeN(tree->nodebv);
914                         MEM_freeN(tree->nodes);
915                         MEM_freeN(tree);
916                 }
917
918                 tree->nodearray = (BVHNode *)MEM_callocN(sizeof(BVHNode)* numnodes, "BVHNodeArray");
919                 
920                 if(!tree->nodearray)
921                 {
922                         MEM_freeN(tree->nodechild);
923                         MEM_freeN(tree->nodebv);
924                         MEM_freeN(tree->nodes);
925                         MEM_freeN(tree);
926                         return NULL;
927                 }
928
929                 //link the dynamic bv and child links
930                 for(i=0; i< numnodes; i++)
931                 {
932                         tree->nodearray[i].bv = tree->nodebv + i * axis;
933                         tree->nodearray[i].children = tree->nodechild + i * tree_type;
934                 }
935                 
936         }
937
938         return tree;
939 }
940
941 void BLI_bvhtree_free(BVHTree *tree)
942 {       
943         if(tree)
944         {
945                 MEM_freeN(tree->nodes);
946                 MEM_freeN(tree->nodearray);
947                 MEM_freeN(tree->nodebv);
948                 MEM_freeN(tree->nodechild);
949                 MEM_freeN(tree);
950         }
951 }
952
953 void BLI_bvhtree_balance(BVHTree *tree)
954 {
955         int i;
956
957         BVHNode*  branches_array = tree->nodearray + tree->totleaf;
958         BVHNode** leafs_array    = tree->nodes;
959
960         //This function should only be called once (some big bug goes here if its being called more than once per tree)
961         assert(tree->totbranch == 0);
962
963         //Build the implicit tree
964         non_recursive_bvh_div_nodes(tree, branches_array, leafs_array, tree->totleaf);
965
966         //current code expects the branches to be linked to the nodes array
967         //we perform that linkage here
968         tree->totbranch = implicit_needed_branches(tree->tree_type, tree->totleaf);
969         for(i = 0; i < tree->totbranch; i++)
970                 tree->nodes[tree->totleaf + i] = branches_array + i;
971
972         build_skip_links(tree, tree->nodes[tree->totleaf], NULL, NULL);
973         //bvhtree_info(tree);
974 }
975
976 int BLI_bvhtree_insert(BVHTree *tree, int index, float *co, int numpoints)
977 {
978         int i;
979         BVHNode *node = NULL;
980         
981         // insert should only possible as long as tree->totbranch is 0
982         if(tree->totbranch > 0)
983                 return 0;
984         
985         if(tree->totleaf+1 >= MEM_allocN_len(tree->nodes)/sizeof(*(tree->nodes)))
986                 return 0;
987         
988         // TODO check if have enough nodes in array
989         
990         node = tree->nodes[tree->totleaf] = &(tree->nodearray[tree->totleaf]);
991         tree->totleaf++;
992         
993         create_kdop_hull(tree, node, co, numpoints, 0);
994         node->index= index;
995         
996         // inflate the bv with some epsilon
997         for (i = tree->start_axis; i < tree->stop_axis; i++)
998         {
999                 node->bv[(2 * i)] -= tree->epsilon; // minimum 
1000                 node->bv[(2 * i) + 1] += tree->epsilon; // maximum 
1001         }
1002
1003         return 1;
1004 }
1005
1006
1007 // call before BLI_bvhtree_update_tree()
1008 int BLI_bvhtree_update_node(BVHTree *tree, int index, float *co, float *co_moving, int numpoints)
1009 {
1010         int i;
1011         BVHNode *node= NULL;
1012         
1013         // check if index exists
1014         if(index > tree->totleaf)
1015                 return 0;
1016         
1017         node = tree->nodearray + index;
1018         
1019         create_kdop_hull(tree, node, co, numpoints, 0);
1020         
1021         if(co_moving)
1022                 create_kdop_hull(tree, node, co_moving, numpoints, 1);
1023         
1024         // inflate the bv with some epsilon
1025         for (i = tree->start_axis; i < tree->stop_axis; i++)
1026         {
1027                 node->bv[(2 * i)] -= tree->epsilon; // minimum 
1028                 node->bv[(2 * i) + 1] += tree->epsilon; // maximum 
1029         }
1030
1031         return 1;
1032 }
1033
1034 // call BLI_bvhtree_update_node() first for every node/point/triangle
1035 void BLI_bvhtree_update_tree(BVHTree *tree)
1036 {
1037         //Update bottom=>top
1038         //TRICKY: the way we build the tree all the childs have an index greater than the parent
1039         //This allows us todo a bottom up update by starting on the biger numbered branch
1040
1041         BVHNode** root  = tree->nodes + tree->totleaf;
1042         BVHNode** index = tree->nodes + tree->totleaf + tree->totbranch-1;
1043
1044         for (; index >= root; index--)
1045                 node_join(tree, *index);
1046 }
1047
1048 float BLI_bvhtree_getepsilon(BVHTree *tree)
1049 {
1050         return tree->epsilon;
1051 }
1052
1053
1054 /*
1055  * BLI_bvhtree_overlap
1056  */
1057 // overlap - is it possbile for 2 bv's to collide ?
1058 static int tree_overlap(BVHNode *node1, BVHNode *node2, int start_axis, int stop_axis)
1059 {
1060         float *bv1 = node1->bv;
1061         float *bv2 = node2->bv;
1062
1063         float *bv1_end = bv1 + (stop_axis<<1);
1064                 
1065         bv1 += start_axis<<1;
1066         bv2 += start_axis<<1;
1067         
1068         // test all axis if min + max overlap
1069         for (; bv1 != bv1_end; bv1+=2, bv2+=2)
1070         {
1071                 if ((*(bv1) > *(bv2 + 1)) || (*(bv2) > *(bv1 + 1))) 
1072                         return 0;
1073         }
1074         
1075         return 1;
1076 }
1077
1078 static void traverse(BVHOverlapData *data, BVHNode *node1, BVHNode *node2)
1079 {
1080         int j;
1081         
1082         if(tree_overlap(node1, node2, data->start_axis, data->stop_axis))
1083         {
1084                 // check if node1 is a leaf
1085                 if(!node1->totnode)
1086                 {
1087                         // check if node2 is a leaf
1088                         if(!node2->totnode)
1089                         {
1090                                 
1091                                 if(node1 == node2)
1092                                 {
1093                                         return;
1094                                 }
1095                                         
1096                                 if(data->i >= data->max_overlap)
1097                                 {       
1098                                         // try to make alloc'ed memory bigger
1099                                         data->overlap = realloc(data->overlap, sizeof(BVHTreeOverlap)*data->max_overlap*2);
1100                                         
1101                                         if(!data->overlap)
1102                                         {
1103                                                 printf("Out of Memory in traverse\n");
1104                                                 return;
1105                                         }
1106                                         data->max_overlap *= 2;
1107                                 }
1108                                 
1109                                 // both leafs, insert overlap!
1110                                 data->overlap[data->i].indexA = node1->index;
1111                                 data->overlap[data->i].indexB = node2->index;
1112
1113                                 data->i++;
1114                         }
1115                         else
1116                         {
1117                                 for(j = 0; j < data->tree2->tree_type; j++)
1118                                 {
1119                                         if(node2->children[j])
1120                                                 traverse(data, node1, node2->children[j]);
1121                                 }
1122                         }
1123                 }
1124                 else
1125                 {
1126                         
1127                         for(j = 0; j < data->tree2->tree_type; j++)
1128                         {
1129                                 if(node1->children[j])
1130                                         traverse(data, node1->children[j], node2);
1131                         }
1132                 }
1133         }
1134         return;
1135 }
1136
1137 BVHTreeOverlap *BLI_bvhtree_overlap(BVHTree *tree1, BVHTree *tree2, unsigned int *result)
1138 {
1139         int j;
1140         unsigned int total = 0;
1141         BVHTreeOverlap *overlap = NULL, *to = NULL;
1142         BVHOverlapData **data;
1143         
1144         // check for compatibility of both trees (can't compare 14-DOP with 18-DOP)
1145         if((tree1->axis != tree2->axis) && (tree1->axis == 14 || tree2->axis == 14) && (tree1->axis == 18 || tree2->axis == 18))
1146                 return NULL;
1147         
1148         // fast check root nodes for collision before doing big splitting + traversal
1149         if(!tree_overlap(tree1->nodes[tree1->totleaf], tree2->nodes[tree2->totleaf], MIN2(tree1->start_axis, tree2->start_axis), MIN2(tree1->stop_axis, tree2->stop_axis)))
1150                 return NULL;
1151
1152         data = MEM_callocN(sizeof(BVHOverlapData *)* tree1->tree_type, "BVHOverlapData_star");
1153         
1154         for(j = 0; j < tree1->tree_type; j++)
1155         {
1156                 data[j] = (BVHOverlapData *)MEM_callocN(sizeof(BVHOverlapData), "BVHOverlapData");
1157                 
1158                 // init BVHOverlapData
1159                 data[j]->overlap = (BVHTreeOverlap *)malloc(sizeof(BVHTreeOverlap)*MAX2(tree1->totleaf, tree2->totleaf));
1160                 data[j]->tree1 = tree1;
1161                 data[j]->tree2 = tree2;
1162                 data[j]->max_overlap = MAX2(tree1->totleaf, tree2->totleaf);
1163                 data[j]->i = 0;
1164                 data[j]->start_axis = MIN2(tree1->start_axis, tree2->start_axis);
1165                 data[j]->stop_axis  = MIN2(tree1->stop_axis,  tree2->stop_axis );
1166         }
1167
1168 #pragma omp parallel for private(j) schedule(static)
1169         for(j = 0; j < MIN2(tree1->tree_type, tree1->nodes[tree1->totleaf]->totnode); j++)
1170         {
1171                 traverse(data[j], tree1->nodes[tree1->totleaf]->children[j], tree2->nodes[tree2->totleaf]);
1172         }
1173         
1174         for(j = 0; j < tree1->tree_type; j++)
1175                 total += data[j]->i;
1176         
1177         to = overlap = (BVHTreeOverlap *)MEM_callocN(sizeof(BVHTreeOverlap)*total, "BVHTreeOverlap");
1178         
1179         for(j = 0; j < tree1->tree_type; j++)
1180         {
1181                 memcpy(to, data[j]->overlap, data[j]->i*sizeof(BVHTreeOverlap));
1182                 to+=data[j]->i;
1183         }
1184         
1185         for(j = 0; j < tree1->tree_type; j++)
1186         {
1187                 free(data[j]->overlap);
1188                 MEM_freeN(data[j]);
1189         }
1190         MEM_freeN(data);
1191         
1192         (*result) = total;
1193         return overlap;
1194 }
1195
1196
1197 /*
1198  * Nearest neighbour - BLI_bvhtree_find_nearest
1199  */
1200 static float squared_dist(const float *a, const float *b)
1201 {
1202         float tmp[3];
1203         VECSUB(tmp, a, b);
1204         return INPR(tmp, tmp);
1205 }
1206
1207 //Determines the nearest point of the given node BV. Returns the squared distance to that point.
1208 static float calc_nearest_point(const float *proj, BVHNode *node, float *nearest)
1209 {
1210         int i;
1211         const float *bv = node->bv;
1212
1213         //nearest on AABB hull
1214         for(i=0; i != 3; i++, bv += 2)
1215         {
1216                 if(bv[0] > proj[i])
1217                         nearest[i] = bv[0];
1218                 else if(bv[1] < proj[i])
1219                         nearest[i] = bv[1];
1220                 else
1221                         nearest[i] = proj[i]; 
1222         }
1223
1224 /*
1225         //nearest on a general hull
1226         VECCOPY(nearest, data->co);
1227         for(i = data->tree->start_axis; i != data->tree->stop_axis; i++, bv+=2)
1228         {
1229                 float proj = INPR( nearest, KDOP_AXES[i]);
1230                 float dl = bv[0] - proj;
1231                 float du = bv[1] - proj;
1232
1233                 if(dl > 0)
1234                 {
1235                         VECADDFAC(nearest, nearest, KDOP_AXES[i], dl);
1236                 }
1237                 else if(du < 0)
1238                 {
1239                         VECADDFAC(nearest, nearest, KDOP_AXES[i], du);
1240                 }
1241         }
1242 */
1243         return squared_dist(proj, nearest);
1244 }
1245
1246
1247 typedef struct NodeDistance
1248 {
1249         BVHNode *node;
1250         float dist;
1251
1252 } NodeDistance;
1253
1254 #define NodeDistance_priority(a,b)      ( (a).dist < (b).dist )
1255
1256 // TODO: use a priority queue to reduce the number of nodes looked on
1257 static void dfs_find_nearest_dfs(BVHNearestData *data, BVHNode *node)
1258 {
1259         if(node->totnode == 0)
1260         {
1261                 if(data->callback)
1262                         data->callback(data->userdata , node->index, data->co, &data->nearest);
1263                 else
1264                 {
1265                         data->nearest.index     = node->index;
1266                         data->nearest.dist      = calc_nearest_point(data->proj, node, data->nearest.co);
1267                 }
1268         }
1269         else
1270         {
1271                 //Better heuristic to pick the closest node to dive on
1272                 int i;
1273                 float nearest[3];
1274
1275                 if(data->proj[ node->main_axis ] <= node->children[0]->bv[node->main_axis*2+1])
1276                 {
1277
1278                         for(i=0; i != node->totnode; i++)
1279                         {
1280                                 if( calc_nearest_point(data->proj, node->children[i], nearest) >= data->nearest.dist) continue;
1281                                 dfs_find_nearest_dfs(data, node->children[i]);
1282                         }
1283                 }
1284                 else
1285                 {
1286                         for(i=node->totnode-1; i >= 0 ; i--)
1287                         {
1288                                 if( calc_nearest_point(data->proj, node->children[i], nearest) >= data->nearest.dist) continue;
1289                                 dfs_find_nearest_dfs(data, node->children[i]);
1290                         }
1291                 }
1292         }
1293 }
1294
1295 static void dfs_find_nearest_begin(BVHNearestData *data, BVHNode *node)
1296 {
1297         float nearest[3], sdist;
1298         sdist = calc_nearest_point(data->proj, node, nearest);
1299         if(sdist >= data->nearest.dist) return;
1300         dfs_find_nearest_dfs(data, node);
1301 }
1302
1303
1304 #if 0
1305 static void NodeDistance_push_heap(NodeDistance *heap, int heap_size)
1306 PUSH_HEAP_BODY(NodeDistance, NodeDistance_priority, heap, heap_size)
1307
1308 static void NodeDistance_pop_heap(NodeDistance *heap, int heap_size)
1309 POP_HEAP_BODY(NodeDistance, NodeDistance_priority, heap, heap_size)
1310
1311 //NN function that uses an heap.. this functions leads to an optimal number of min-distance
1312 //but for normal tri-faces and BV 6-dop.. a simple dfs with local heuristics (as implemented
1313 //in source/blender/blenkernel/intern/shrinkwrap.c) works faster.
1314 //
1315 //It may make sense to use this function if the callback queries are very slow.. or if its impossible
1316 //to get a nice heuristic
1317 //
1318 //this function uses "malloc/free" instead of the MEM_* because it intends to be openmp safe
1319 static void bfs_find_nearest(BVHNearestData *data, BVHNode *node)
1320 {
1321         int i;
1322         NodeDistance default_heap[DEFAULT_FIND_NEAREST_HEAP_SIZE];
1323         NodeDistance *heap=default_heap, current;
1324         int heap_size = 0, max_heap_size = sizeof(default_heap)/sizeof(default_heap[0]);
1325         float nearest[3];
1326
1327         int callbacks = 0, push_heaps = 0;
1328
1329         if(node->totnode == 0)
1330         {
1331                 dfs_find_nearest_dfs(data, node);
1332                 return;
1333         }
1334
1335         current.node = node;
1336         current.dist = calc_nearest_point(data->proj, node, nearest);
1337
1338         while(current.dist < data->nearest.dist)
1339         {
1340 //              printf("%f : %f\n", current.dist, data->nearest.dist);
1341                 for(i=0; i< current.node->totnode; i++)
1342                 {
1343                         BVHNode *child = current.node->children[i];
1344                         if(child->totnode == 0)
1345                         {
1346                                 callbacks++;
1347                                 dfs_find_nearest_dfs(data, child);
1348                         }
1349                         else
1350                         {
1351                                 //adjust heap size
1352                                 if(heap_size >= max_heap_size
1353                                 && ADJUST_MEMORY(default_heap, (void**)&heap, heap_size+1, &max_heap_size, sizeof(heap[0])) == FALSE)
1354                                 {
1355                                         printf("WARNING: bvh_find_nearest got out of memory\n");
1356
1357                                         if(heap != default_heap)
1358                                                 free(heap);
1359
1360                                         return;
1361                                 }
1362
1363                                 heap[heap_size].node = current.node->children[i];
1364                                 heap[heap_size].dist = calc_nearest_point(data->proj, current.node->children[i], nearest);
1365
1366                                 if(heap[heap_size].dist >= data->nearest.dist) continue;
1367                                 heap_size++;
1368
1369                                 NodeDistance_push_heap(heap, heap_size);
1370         //                      PUSH_HEAP_BODY(NodeDistance, NodeDistance_priority, heap, heap_size);
1371                                 push_heaps++;
1372                         }
1373                 }
1374                 
1375                 if(heap_size == 0) break;
1376
1377                 current = heap[0];
1378                 NodeDistance_pop_heap(heap, heap_size);
1379 //              POP_HEAP_BODY(NodeDistance, NodeDistance_priority, heap, heap_size);
1380                 heap_size--;
1381         }
1382
1383 //      printf("hsize=%d, callbacks=%d, pushs=%d\n", heap_size, callbacks, push_heaps);
1384
1385         if(heap != default_heap)
1386                 free(heap);
1387 }
1388 #endif
1389
1390
1391 int BLI_bvhtree_find_nearest(BVHTree *tree, const float *co, BVHTreeNearest *nearest, BVHTree_NearestPointCallback callback, void *userdata)
1392 {
1393         int i;
1394
1395         BVHNearestData data;
1396         BVHNode* root = tree->nodes[tree->totleaf];
1397
1398         //init data to search
1399         data.tree = tree;
1400         data.co = co;
1401
1402         data.callback = callback;
1403         data.userdata = userdata;
1404
1405         for(i = data.tree->start_axis; i != data.tree->stop_axis; i++)
1406         {
1407                 data.proj[i] = INPR(data.co, KDOP_AXES[i]);
1408         }
1409
1410         if(nearest)
1411         {
1412                 memcpy( &data.nearest , nearest, sizeof(*nearest) );
1413         }
1414         else
1415         {
1416                 data.nearest.index = -1;
1417                 data.nearest.dist = FLT_MAX;
1418         }
1419
1420         //dfs search
1421         if(root)
1422                 dfs_find_nearest_begin(&data, root);
1423
1424         //copy back results
1425         if(nearest)
1426         {
1427                 memcpy(nearest, &data.nearest, sizeof(*nearest));
1428         }
1429
1430         return data.nearest.index;
1431 }
1432
1433
1434 /*
1435  * Raycast - BLI_bvhtree_ray_cast
1436  *
1437  * raycast is done by performing a DFS on the BVHTree and saving the closest hit
1438  */
1439
1440
1441 //Determines the distance that the ray must travel to hit the bounding volume of the given node
1442 static float ray_nearest_hit(BVHRayCastData *data, float *bv)
1443 {
1444         int i;
1445
1446         float low = 0, upper = data->hit.dist;
1447
1448         for(i=0; i != 3; i++, bv += 2)
1449         {
1450                 if(data->ray_dot_axis[i] == 0.0f)
1451                 {
1452                         //axis aligned ray
1453                         if(data->ray.origin[i] < bv[0] - data->ray.radius
1454                         || data->ray.origin[i] > bv[1] + data->ray.radius)
1455                                 return FLT_MAX;
1456                 }
1457                 else
1458                 {
1459                         float ll = (bv[0] - data->ray.radius - data->ray.origin[i]) / data->ray_dot_axis[i];
1460                         float lu = (bv[1] + data->ray.radius - data->ray.origin[i]) / data->ray_dot_axis[i];
1461
1462                         if(data->ray_dot_axis[i] > 0.0f)
1463                         {
1464                                 if(ll > low)   low = ll;
1465                                 if(lu < upper) upper = lu;
1466                         }
1467                         else
1468                         {
1469                                 if(lu > low)   low = lu;
1470                                 if(ll < upper) upper = ll;
1471                         }
1472         
1473                         if(low > upper) return FLT_MAX;
1474                 }
1475         }
1476         return low;
1477 }
1478
1479 //Determines the distance that the ray must travel to hit the bounding volume of the given node
1480 //Based on Tactical Optimization of Ray/Box Intersection, by Graham Fyffe
1481 //[http://tog.acm.org/resources/RTNews/html/rtnv21n1.html#art9]
1482 //
1483 //TODO this doens't has data->ray.radius in consideration
1484 static float fast_ray_nearest_hit(const BVHRayCastData *data, const BVHNode *node)
1485 {
1486         const float *bv = node->bv;
1487         float dist;
1488         
1489         float t1x = (bv[data->index[0]] - data->ray.origin[0]) * data->idot_axis[0];
1490         float t2x = (bv[data->index[1]] - data->ray.origin[0]) * data->idot_axis[0];
1491         float t1y = (bv[data->index[2]] - data->ray.origin[1]) * data->idot_axis[1];
1492         float t2y = (bv[data->index[3]] - data->ray.origin[1]) * data->idot_axis[1];
1493         float t1z = (bv[data->index[4]] - data->ray.origin[2]) * data->idot_axis[2];
1494         float t2z = (bv[data->index[5]] - data->ray.origin[2]) * data->idot_axis[2];
1495
1496         if(t1x > t2y || t2x < t1y || t1x > t2z || t2x < t1z || t1y > t2z || t2y < t1z) return FLT_MAX;
1497         if(t2x < 0.0 || t2y < 0.0 || t2z < 0.0) return FLT_MAX;
1498         if(t1x > data->hit.dist || t1y > data->hit.dist || t1z > data->hit.dist) return FLT_MAX;
1499
1500         dist = t1x;
1501         if (t1y > dist) dist = t1y;
1502         if (t1z > dist) dist = t1z;
1503         return dist;
1504 }
1505
1506 static void dfs_raycast(BVHRayCastData *data, BVHNode *node)
1507 {
1508         int i;
1509
1510         //ray-bv is really fast.. and simple tests revealed its worth to test it
1511         //before calling the ray-primitive functions
1512         /* XXX: temporary solution for particles untill fast_ray_nearest_hit supports ray.radius */
1513         float dist = (data->ray.radius > 0.0f) ? ray_nearest_hit(data, node->bv) : fast_ray_nearest_hit(data, node);
1514         if(dist >= data->hit.dist) return;
1515
1516         if(node->totnode == 0)
1517         {
1518                 if(data->callback)
1519                         data->callback(data->userdata, node->index, &data->ray, &data->hit);
1520                 else
1521                 {
1522                         data->hit.index = node->index;
1523                         data->hit.dist  = dist;
1524                         VECADDFAC(data->hit.co, data->ray.origin, data->ray.direction, dist);
1525                 }
1526         }
1527         else
1528         {
1529                 //pick loop direction to dive into the tree (based on ray direction and split axis)
1530                 if(data->ray_dot_axis[ (int)node->main_axis ] > 0.0f)
1531                 {
1532                         for(i=0; i != node->totnode; i++)
1533                         {
1534                                 dfs_raycast(data, node->children[i]);
1535                         }
1536                 }
1537                 else
1538                 {
1539                         for(i=node->totnode-1; i >= 0; i--)
1540                         {
1541                                 dfs_raycast(data, node->children[i]);
1542                         }
1543                 }
1544         }
1545 }
1546
1547 #if 0
1548 static void iterative_raycast(BVHRayCastData *data, BVHNode *node)
1549 {
1550         while(node)
1551         {
1552                 float dist = fast_ray_nearest_hit(data, node);
1553                 if(dist >= data->hit.dist)
1554                 {
1555                         node = node->skip[1];
1556                         continue;
1557                 }
1558
1559                 if(node->totnode == 0)
1560                 {
1561                         if(data->callback)
1562                                 data->callback(data->userdata, node->index, &data->ray, &data->hit);
1563                         else
1564                         {
1565                                 data->hit.index = node->index;
1566                                 data->hit.dist  = dist;
1567                                 VECADDFAC(data->hit.co, data->ray.origin, data->ray.direction, dist);
1568                         }
1569                         
1570                         node = node->skip[1];
1571                 }
1572                 else
1573                 {
1574                         node = node->children[0];
1575                 }       
1576         }
1577 }
1578 #endif
1579
1580 int BLI_bvhtree_ray_cast(BVHTree *tree, const float *co, const float *dir, float radius, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata)
1581 {
1582         int i;
1583         BVHRayCastData data;
1584         BVHNode * root = tree->nodes[tree->totleaf];
1585
1586         data.tree = tree;
1587
1588         data.callback = callback;
1589         data.userdata = userdata;
1590
1591         VECCOPY(data.ray.origin,    co);
1592         VECCOPY(data.ray.direction, dir);
1593         data.ray.radius = radius;
1594
1595         normalize_v3(data.ray.direction);
1596
1597         for(i=0; i<3; i++)
1598         {
1599                 data.ray_dot_axis[i] = INPR( data.ray.direction, KDOP_AXES[i]);
1600                 data.idot_axis[i] = 1.0f / data.ray_dot_axis[i];
1601
1602                 if(fabs(data.ray_dot_axis[i]) < FLT_EPSILON)
1603                 {
1604                         data.ray_dot_axis[i] = 0.0;
1605                 }
1606                 data.index[2*i] = data.idot_axis[i] < 0.0 ? 1 : 0;
1607                 data.index[2*i+1] = 1 - data.index[2*i];
1608                 data.index[2*i]   += 2*i;
1609                 data.index[2*i+1] += 2*i;
1610         }
1611
1612
1613         if(hit)
1614                 memcpy( &data.hit, hit, sizeof(*hit) );
1615         else
1616         {
1617                 data.hit.index = -1;
1618                 data.hit.dist = FLT_MAX;
1619         }
1620
1621         if(root)
1622         {
1623                 dfs_raycast(&data, root);
1624 //              iterative_raycast(&data, root);
1625          }
1626
1627
1628         if(hit)
1629                 memcpy( hit, &data.hit, sizeof(*hit) );
1630
1631         return data.hit.index;
1632 }
1633
1634 float BLI_bvhtree_bb_raycast(float *bv, float *light_start, float *light_end, float *pos)
1635 {
1636         BVHRayCastData data;
1637         float dist = 0.0;
1638
1639         data.hit.dist = FLT_MAX;
1640         
1641         // get light direction
1642         data.ray.direction[0] = light_end[0] - light_start[0];
1643         data.ray.direction[1] = light_end[1] - light_start[1];
1644         data.ray.direction[2] = light_end[2] - light_start[2];
1645         
1646         data.ray.radius = 0.0;
1647         
1648         data.ray.origin[0] = light_start[0];
1649         data.ray.origin[1] = light_start[1];
1650         data.ray.origin[2] = light_start[2];
1651         
1652         normalize_v3(data.ray.direction);
1653         VECCOPY(data.ray_dot_axis, data.ray.direction);
1654         
1655         dist = ray_nearest_hit(&data, bv);
1656         
1657         if(dist > 0.0)
1658         {
1659                 VECADDFAC(pos, light_start, data.ray.direction, dist);
1660         }
1661         return dist;
1662         
1663 }
1664
1665 /*
1666  * Range Query - as request by broken :P
1667  *
1668  * Allocs and fills an array with the indexs of node that are on the given spherical range (center, radius) 
1669  * Returns the size of the array.
1670  */
1671 typedef struct RangeQueryData
1672 {
1673         BVHTree *tree;
1674         const float *center;
1675         float radius;                   //squared radius
1676
1677         int hits;
1678
1679         BVHTree_RangeQuery callback;
1680         void *userdata;
1681
1682
1683 } RangeQueryData;
1684
1685
1686 static void dfs_range_query(RangeQueryData *data, BVHNode *node)
1687 {
1688         if(node->totnode == 0)
1689         {
1690 #if 0   /*UNUSED*/
1691                 //Calculate the node min-coords (if the node was a point then this is the point coordinates)
1692                 float co[3];
1693                 co[0] = node->bv[0];
1694                 co[1] = node->bv[2];
1695                 co[2] = node->bv[4];
1696 #endif
1697         }
1698         else
1699         {
1700                 int i;
1701                 for(i=0; i != node->totnode; i++)
1702                 {
1703                         float nearest[3];
1704                         float dist = calc_nearest_point(data->center, node->children[i], nearest);
1705                         if(dist < data->radius)
1706                         {
1707                                 //Its a leaf.. call the callback
1708                                 if(node->children[i]->totnode == 0)
1709                                 {
1710                                         data->hits++;
1711                                         data->callback( data->userdata, node->children[i]->index, dist );
1712                                 }
1713                                 else
1714                                         dfs_range_query( data, node->children[i] );
1715                         }
1716                 }
1717         }
1718 }
1719
1720 int BLI_bvhtree_range_query(BVHTree *tree, const float *co, float radius, BVHTree_RangeQuery callback, void *userdata)
1721 {
1722         BVHNode * root = tree->nodes[tree->totleaf];
1723
1724         RangeQueryData data;
1725         data.tree = tree;
1726         data.center = co;
1727         data.radius = radius*radius;
1728         data.hits = 0;
1729
1730         data.callback = callback;
1731         data.userdata = userdata;
1732
1733         if(root != NULL)
1734         {
1735                 float nearest[3];
1736                 float dist = calc_nearest_point(data.center, root, nearest);
1737                 if(dist < data.radius)
1738                 {
1739                         //Its a leaf.. call the callback
1740                         if(root->totnode == 0)
1741                         {
1742                                 data.hits++;
1743                                 data.callback( data.userdata, root->index, dist );
1744                         }
1745                         else
1746                                 dfs_range_query( &data, root );
1747                 }
1748         }
1749
1750         return data.hits;
1751 }