This algorithm works in any closed polygon if the sides of the polygon do not intersect. Triangle, pentagon, square, even a very curved piecewise-linear rubber band that does not cross itself.
1) Define your polygon as a directed group of vectors. This implies that each side of the polygon is described by a vector that goes from the vertex a to the vertex a + 1. The vectors are so directed that the head of one touches the tail of the next until the last vector touches the tail of the first.
2) Select a point to check inside or outside the polygon.
3) For each vector Vn along the perimeter of the search vector of the polygon Dn, starting at the test point and ending at the tail of Vn. Calculate the vector Cn defined as DnXVn / DN * VN (X denotes the transverse product, * indicates the point product). Name the value Cn by the name Mn.
4) Add all Mn and call this value K.
5) If K is zero, the point is outside the polygon.
6) If K is not equal to zero, the point is inside the polygon.
Theoretically, a point lying on the edge of a polygon will produce an undefined result.
The geometric meaning of K is the full angle at which the flea sitting on our test point βsawβ ant, going along the edge of the polygon, going to the left minus the corner going to the right. In a closed loop, ant ends where it begins. Outside the polygon, regardless of location, the answer is zero.
Inside the polygon, regardless of location, the answer is "once around a point."
Mario Mar 21 '14 at 21:53 2014-03-21 21:53
source share