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