I have a large array of Axis-Aligned Bounding Boxes, I'm trying to get the euclidean distance from a point to the closest one, I have tried manhattan distance but it doesn't seem to match the "brute force" result by iterating over all of them with euclidean distance. Any efficient approaches? Cheers
How to get the closest Axis-Aligned Bounding Box to a point?
924 Views Asked by Doofus At
2
There are 2 best solutions below
0
On
- Build a BVH (bounding volume hierarchy) over your input boxes.
- recursively traverse a point through this BVH: in each step
- if node is a leaf:
- compute distance of point to box in this leaf
- keep track of closest intersection found
- else
- compute distance of point to each of the children
- (optional but recommended:) sort the children by distance
- if child distance > closest already found distance: cull it;
- otherwise: recurse into that child
- if node is a leaf:
To compute (euclidean) distance between point P and box B:
- compute point
PBin box that's closest to P:PB = min(max(P,B.lower),B.upper) - return euclidean length of
PtoPB:return length(P-PB)
To build a BVH over those boxes: just one of the options: Embree does have a interface to build BVHes over boxes, and query the result.
I propose the following solution. You have the 5 rectagles as below and your point P is at (7,4)
If you build two sorted lists which are ordered by the horizontal edges and the vertical edges you will get:
Now you can do a binary search on the Horizontal list on Py = 4. This is your starting index to work outwards in both directions. The same for Px = 7.
On your Horizontal list, you find H_index = 4 (Rec1)
On your Vertical list, you find V-Index = 4 (Rec2)
No match yet, move one out of centre in all directions (this step is repeated until one match)
We have a match->Rec1 (H_index = 4, V_index = 3)
If you want to find all equals, you are not done yet.
The x-distance between Px & rec1 = 1. you will need to include all Rectangles within this limit.
this gives V_index 3 to 8. For each of them check if Py is between or equal to the y values of the line.
So Rec3 is also found as a solution
The y-distance between Py & rec1 = 0. you wll need to include all Rectangles within this limit.
this gives H_index 4 to 5. For each of them check if Px is between or equal to the x values of the line.
No Other solutions found, we are done: Rec1 & Rec3 are closest.
This solution will be fast enough for up to 100.000 Rectangles. When you talk about milj. of Rectangles, you will need to use a Segment Tree.