13.3 Point in Polygon 699
return PointInSubpolygon(P, C, i0, mid);
} else {
// P potentially in <V(mid), V(mid + 1), ... ,V(i1 - 1), V(i1)>
return PointInSubpolygon(P, C, mid, i1);
}
}
bool PointInPolygon(Point P, ConvexPolygon C)
{
return PointInSubpolygon(P, C, 0, 0);
}
The vertex indices are computed modulo C.N. Because of the bisection, the algo-
rithm is O(log n) for a convex polygon with n vertices.
Another Asymptotically Faster Method
The method described in this subsection also requires O(log n) time to perform the
point-in-convex-polygon query.
The polygon vertices V
i
for 0 ≤ i<nare assumed to be stored in counterclock-
wise order. Extreme vertices in the x-direction are computed. This can be done in
O(log n) time using the bisection method discussed in Section 7.7.2.The x-minimum
vertex has index i
min
, and the x-maximum vertex has index i
max
. Observe that it is not
necessary that i
min
<i
max
. As the vertices are counterclockwise traversed from V
i
min
to V
i
max
, the corresponding edges have outer normal vectors whose y-components are
negative or zero, the latter occurring at most twice if the polygon has vertical edges at
either x-extreme. The corresponding vertices and edges are referred to as the bottom
half of the polygon. Similarly, as the vertices are counterclockwise traversed from V
i
max
to V
i
min
, the corresponding edges have outer normal vectors whose y-components are
positive or zero. The corresponding vertices and edges are referred to as the top half
of the polygon.
Let P be the point to be tested for containment. The index bisection method is
used to determine which vertex V
t
in the top half of the polygon has the smallest
x-value larger or equal to the x-value of P . If the top half has vertical edges, the
extreme indices found initially can be appropriately incremented or decremented to
exclude those edges from this test without affecting the correctness of the algorithm.
Similarly, index bisection can be used to determine which vertex V
b
in the bottom
half of the polygon has the largest x-value smaller or equal to the x-value of P . Both
bisections are O(log n) in time.
The vertical line containing P intersects the two directed edges whose initial
points are V
t
and V
b
.IfP is between the two edges, then it is inside the polygon.
Otherwise it is outside the polygon. Figure 13.13 illustrates the various concepts in
this section.