point in polygon algorithm

Point-In-Polygon Algorithm — Determining Whether A Point Is Inside A Complex Polygon

© 1998,2006,2007 Darel Rex Finley.  This complete article, unmodified, may be freely
distributed for educational purposes.

Visit the new page which adds spline curves to this
technique!  Also visit the shortest-path-through-polygon
page
!

Figure 1

Figure 1 demonstrates a typical case of a severely concave polygon with 14 sides.  The red dot is a point which
needs to be tested, to determine if it lies inside the polygon.

The solution is to compare each side of the polygon to the Y (vertical) coordinate of the test point, and compile a list
of nodes, where each node is a point where one side crosses the Y threshold of the test point. In this example,
eight sides of the polygon cross the Y threshold, while the other six sides do not.  Then, if there are an
odd number of nodes on each side of the test point, then it is inside the polygon; if there are an even
number of nodes on each side of the test point, then it is outside the polygon.  In our example, there are five
nodes to the left of the test point, and three nodes to the right.  Since five and three are odd numbers, our test
point is inside the polygon.

(Note:  This algorithm does not care whether the polygon is traced in clockwise or counterclockwise
fashion.)

Figure 2

Figure 2 shows what happens if the polygon crosses itself.  In this example, a ten-sided polygon has lines which
cross each other.  The effect is much like “exclusive or,” or XOR as it is known to assembly-language
programmers.  The portions of the polygon which overlap cancel each other out.  So, the test point is outside
the polygon, as indicated by the even number of nodes (two and two) on either side of it.

Figure 3

In Figure 3, the six-sided polygon does not overlap itself, but it does have lines that cross.  This is not a
problem; the algorithm still works fine.

Figure 4

Figure 4 demonstrates the problem that results when a vertex of the polygon falls directly on the Y threshold. 
Since sides a and b both touch the threshold, should they both generate a node?  No, because then
there would be two nodes on each side of the test point and so the test would say it was outside of the polygon, when it
clearly is not!

The solution to this situation is simple.  Points which are exactly on the Y threshold must be considered to belong
to one side of the threshold.  Let’s say we arbitrarily decide that points on the Y threshold will belong to the
“above” side of the threshold.  Then, side a generates a node, since it has one endpoint below the
threshold and its other endpoint on-or-above the threshold.  Side b does not generate a node, because both of
its endpoints are on-or-above the threshold, so it is not considered to be a threshold-crossing side.

Figure 5

Figure 5 shows the case of a polygon in which one of its sides lies entirely on the threshold.  Simply follow the
rule as described concerning Figure 4.  Side c generates a node, because it has one endpoint below the
threshold, and its other endpoint on-or-above the threshold.  Side d does not generate a node, because it has
both endpoints on-or-above the threshold.  And side e also does not generate a node, because it has both
endpoints on-or-above the threshold.

Figure 6

Figure 6 illustrates a special case brought to my attention by John David Munch of Cal Poly.  One interior angle of
the polygon just touches the Y-threshold of the test point.  This is OK.  In the upper picture, only one side
(hilited in red) generates a node to the left of the test point, and in the bottom example, three sides do.  Either
way, the number is odd, and the test point will be deemed inside the polygon.

Polygon Edge

If the test point is on the border of the polygon, this algorithm will deliver unpredictable results; i.e. the result may
be “inside” or “outside” depending on arbitrary factors such as how the polygon is oriented with
respect to the coordinate system.  (That is not generally a problem, since the edge of the polygon is infinitely
thin anyway, and points that fall right on the edge can go either way without hurting the look of the polygon.)

C Code Sample

//  Globals which should be set before calling this function:
//
//  int    polySides  =  how many corners the polygon has
//  float  polyX[]    =  horizontal coordinates of corners
//  float  polyY[]    =  vertical coordinates of corners
//  float  x, y       =  point to be tested
//
//  (Globals are used in this example for purposes of speed.  Change as
//  desired.)
//
//  The function will return YES if the point x,y is inside the polygon, or
//  NO if it is not.  If the point is exactly on the edge of the polygon,
//  then the function may return YES or NO.
//
//  Note that division by zero is avoided because the division is protected
//  by the "if" clause which surrounds it.

bool pointInPolygon() {

int   i, j=polySides-1 ;
  bool  oddNodes=NO      ;

for (i=0; i<polySides; i++) {
    if (polyY[i]<y && polyY[j]>=y
    ||  polyY[j]<y && polyY[i]>=y) {
      if (polyX[i]+(y-polyY[i])/(polyY[j]-polyY[i])*(polyX[j]-polyX[i])<x) {
        oddNodes=!oddNodes; }}
    j=i; }

return oddNodes; }

Here’s an efficiency improvement provided by Nathan Mercer.  The blue
code eliminates calculations on sides that are entirely to the right of
the test point.  Though this might be occasionally slower for some
polygons, it is probably faster for most.

//  Globals which should be set before calling this function:
//
//  int    polySides  =  how many corners the polygon has
//  float  polyX[]    =  horizontal coordinates of corners
//  float  polyY[]    =  vertical coordinates of corners
//  float  x, y       =  point to be tested
//
//  (Globals are used in this example for purposes of speed.  Change as
//  desired.)
//
//  The function will return YES if the point x,y is inside the polygon, or
//  NO if it is not.  If the point is exactly on the edge of the polygon,
//  then the function may return YES or NO.
//
//  Note that division by zero is avoided because the division is protected
//  by the "if" clause which surrounds it.

bool pointInPolygon() {

int   i, j=polySides-1 ;
  bool  oddNodes=NO      ;

for (i=0; i<polySides; i++) {
    if ((polyY[i]< y && polyY[j]>=y
    ||   polyY[j]< y && polyY[i]>=y)
    &&  (polyX[i]<=x || polyX[j]<=x)) {
      if (polyX[i]+(y-polyY[i])/(polyY[j]-polyY[i])*(polyX[j]-polyX[i])<x) {
        oddNodes=!oddNodes; }}
    j=i; }

return oddNodes; }

Here’s another efficiency improvement provided by Lascha Lagidse.  The
inner “if” statement is eliminated and replaced with an exclusive-OR
operation.

//  Globals which should be set before calling this function:
//
//  int    polySides  =  how many corners the polygon has
//  float  polyX[]    =  horizontal coordinates of corners
//  float  polyY[]    =  vertical coordinates of corners
//  float  x, y       =  point to be tested
//
//  (Globals are used in this example for purposes of speed.  Change as
//  desired.)
//
//  The function will return YES if the point x,y is inside the polygon, or
//  NO if it is not.  If the point is exactly on the edge of the polygon,
//  then the function may return YES or NO.
//
//  Note that division by zero is avoided because the division is protected
//  by the "if" clause which surrounds it.

bool pointInPolygon() {

int   i, j=polySides-1 ;
  bool  oddNodes=NO      ;

for (i=0; i<polySides; i++) {
    if ((polyY[i]< y && polyY[j]>=y
    ||   polyY[j]< y && polyY[i]>=y)
    &&  (polyX[i]<=x || polyX[j]<=x)) {
      oddNodes^=(polyX[i]+(y-polyY[i])/(polyY[j]-polyY[i])*(polyX[j]-polyX[i])<x); }
    j=i; }

return oddNodes; }

And here’s a pre-calcuation efficiency improvement provided by Patrick
Mullen.  This is useful if you have many points that need to be tested
against the same (static) polygon:

//  Globals which should be set before calling these functions:
//
//  int    polySides  =  how many corners the polygon has
//  float  polyX[]    =  horizontal coordinates of corners
//  float  polyY[]    =  vertical coordinates of corners
//  float  x, y       =  point to be tested
//
//  The following global arrays should be allocated before calling these functions:
//
//  float  constant[] = storage for precalculated constants (same size as polyX)
//  float  multiple[] = storage for precalculated multipliers (same size as polyX)
//
//  (Globals are used in this example for purposes of speed.  Change as
//  desired.)
//
//  USAGE:
//  Call precalc_values() to initialize the constant[] and multiple[] arrays,
//  then call pointInPolygon(x, y) to determine if the point is in the polygon.
//
//  The function will return YES if the point x,y is inside the polygon, or
//  NO if it is not.  If the point is exactly on the edge of the polygon,
//  then the function may return YES or NO.
//
//  Note that division by zero is avoided because the division is protected
//  by the "if" clause which surrounds it.

void precalc_values() {

int   i, j=polySides-1 ;

for(i=0; i<polySides; i++) {
    if(polyY[j]==polyY[i]) {
      constant[i]=polyX[i];
      multiple[i]=0; }
    else {
      constant[i]=polyX[i]-(polyY[i]*polyX[j])/(polyY[j]-polyY[i])+(polyY[i]*polyX[i])/(polyY[j]-polyY[i]);
      multiple[i]=(polyX[j]-polyX[i])/(polyY[j]-polyY[i]); }
    j=i; }}

bool pointInPolygon() {

int   i, j=polySides-1 ;
  bool  oddNodes=NO      ;

for (i=0; i<polySides; i++) {
    if ((polyY[i]< y && polyY[j]>=y
    ||   polyY[j]< y && polyY[i]>=y)) {
      oddNodes^=(y*multiple[i]+constant[i]<x); }
    j=i; }

return oddNodes; }

Integer Issue

What if you’re trying to make a polygon like the blue one below (Figure
7), but it comes out all horizontal and vertical lines, like the red
one?  That indicates that you have defined some of your variables as
integers instead of floating-point.  Check your code carefully to ensure
that your test point and all the corners of your polygon are defined
as, and passed as, floating-point numbers.

   Figure 7

Send me an e-mail!

  Does the brace style in the above code sample freak
you out?  Click here to see it explained in a new
window.
Quicksort  | 
Point in polygon  | 
Mouseover menus  | 
Gyroscope  | 
Osmosis  | 
Polarizer experiment  | 
Gravity table equilibrium  | 
Calculus without calculus  |
Overlapping maze
时间: 2024-10-05 19:11:25

point in polygon algorithm的相关文章

ACdream 1429 Rectangular Polygon

Rectangular Polygon Time Limit: 1000MS   Memory Limit: 256000KB   64bit IO Format: %lld & %llu Description A rectangular polygon is a polygon whose edges are all parallel to the coordinate axes. The polygon must have a single, non-intersecting bounda

Scrambled Polygon(差集排序)

Scrambled Polygon Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 7799   Accepted: 3707 Description A closed polygon is a figure bounded by a finite number of line segments. The intersections of the bounding line segments are called the

polygon

polygon Time Limit: 1000 MS Memory Limit: 32768 K Total Submit: 38(28 users) Total Accepted: 29(27 users) Rating: Special Judge: No Description We have a special polygon that all points have the same distance to original point.As you know we can get 

hunnu11562:The Triangle Division of the Convex Polygon(第n个卡特兰数取模)

Problem description   A convex polygon with n edges can be divided into several triangles by some non-intersect diagonals. We denote d(n) is the number of the different ways to divide the convex polygon. For example,when n is 6,there are 14 different

[算法]Comparison of the different algorithms for Polygon Boolean operations

Comparison of the different algorithms for  Polygon Boolean operations. Michael Leonov 1998 http://www.angusj.com/delphi/clipper.php#screenshots http://www.complex-a5.ru/polyboolean/comp.html http://www.angusj.com/delphi/clipper.php#screenshots Intro

【ASC 23】G. ACdream 1429 Rectangular Polygon --DP

题意:有很多棍子,从棍子中选出两个棍子集合,使他们的和相等,求能取得的最多棍子数. 解法:容易看出有一个多阶段决策的过程,对于每个棍子,我们有 可以不选,或是选在第一个集合,或是选在第二个集合 这三种决策.因为两个集合最后的和要相等,那么令一个集合为正,另一个为负,那么最后和为0,我们用偏移0的量来作为状态之一. dp[i][j]表示前 i 个 偏移量为 j 的最大棍子数,因为每根棍最长为200,所以偏移量最多为+-20000,所以在+-20000之间枚举,最多100*40000 代码: #in

Uva 11971 Polygon 想法

多边形的组成条件是最长边不能占边长总和的一半,将木棒想象成圆多砍一刀,然后是简单概率. Polygon Time Limit: 1000MS   Memory Limit: Unknown   64bit IO Format: %lld & %llu Submit Status Description U   - Polygon Time Limit: 1 sec Memory Limit: 32 MB John has been given a segment of lenght N, how

POJ2007 Scrambled Polygon

PS: 此题可以用凸包做,也可以用极角排序,关键是理解排序原理,题目说不会出现三点共线的情况.(Window 64bit %I64d, Linux %lld) #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <cmath> using namespace std; struc

[算法]A General Polygon Clipping Library

A General Polygon Clipping Library Version 2.32    http://www.cs.man.ac.uk/~toby/alan/software/gpc.html Alan Murta Advanced Interfaces Group Department of Computer Science University of Manchester Manchester M13 9PL, UK Abstract: This document descri