I am trying to code the Ray casting algorithm (http://en.wikipedia.org/wiki/Point_in_polygon) in a manner that will be effective when:
- the algorithm will be called many times with the same polygon but a different point
- the polygon has a large number of vertices
The polygon is simple but not necessarily convex.
I will use a horizontal ray from the point (xp,yp) going right: xr = xp + a, a>=0, yr = yp.
Instead of having to loop trough all edges of the polygon and check if the point is within the y range of the edge I want to use some Binary Space Partitioning tree techique(http://en.wikipedia.org/wiki/Binary_space_partitioning) to quickly finds such edges.
I imagine a binary tree of boxes:
struct Box {
float min, max;
Box *leftChild; // [min,mid]
Box *rightChild; // [mid,max]
std::vector<int> edgeIndices; // edges that are completely within the box
};
- All edges are placed in the root box which has min = min y(polygon) and max = max y(polygon). This becomes the current box.
- The current box (min,max) is split into to: left: (min,mid) and right: (mid,max). Edges that are completely within either left or right are moved into that child box.
Step 2 is repeated for left and right child until each box contains less than a predefined number of edges or the depth of that child exceeds a predefined max depth.
Now in order to find which edges intersect a value yp: start at root box and traverse downward adding together all edges along the path.
How do I find the optimal mid values? I want the tree to be as flat and balanced as possible. That is the number of edges should be approximately the same in the left and the right child.
I could e.g. sort the edges on min y or max y and use the average y of the median edge as split point (mid).