点の内部判定(ポリゴン)

アルゴリズム

ある2次元上の点がポリゴンの内部にあるかどうかを判定するアルゴリズム。

  1. 判定したい点から出ている X軸に水平な半直線をとる。
  2. その半直線とポリゴンの各線分との交点の個数を数える。
  3. その交点の数が偶数なら外部の点、奇数なら内部の点である。
[ポリゴンと点]

サンプルプログラム

#define  MAX 256

typedef struct {
		double x, y;
	} Point;

typedef struct {
		int n;
		Point p[MAX];
	} Polygon;

int isCross(double y, Point p1, Point p2, Point *cp)
{
	if(p1.y > p2.y)
	{
		Point p;
		p = p1;
		p1 = p2;
		p2 = p;
	}
	cp->x = (p1.x * (p2.y - y) + p2.x * (y - p1.y)) / (p2.y - p1.y);
	cp->y = y;
	if(p1.y <= y && y < p2.y)
		return 1;
	else
		return 0;
}

int inPoly(Point p, Polygon poly)
{
	int i, j;
	int count = 0;
	Point cp;

	for(i = 0; i < poly.n; i++)
	{
		j = ( i + 1 ) % poly.n;
		if(isCross(p.y, poly.p[i], poly.p[j], &cp))
		{
			if(cp.x > p.x )
				count++;
		}
	}
	return count % 2;
}

int main()
{
	Polygon poly = {3, {{0.0, 0.0}, {0.0, 1.0}, {1.0, 0.0}}};
	Point p1 = {0.5, 0.0};
	Point p2 = {-0.2, 0.5};
	Point p3 = {0.2, 0.2};

	printf("%d\n", inPoly(p1, poly));
	printf("%d\n", inPoly(p2, poly));
	printf("%d\n", inPoly(p3, poly));

	return 0;
}

home | index
Mail