C 多边形中的点算法

C 多边形中的点算法,c,algorithm,C,Algorithm,我看到下面的算法可以从这个角度检查一个点是否在给定的多边形中: int-pnpoly(int-nvert,float*vertx,float*verty,float-testx,float-testy) { int i,j,c=0; 对于(i=0,j=nvert-1;itesty)!=(verty[j]>testy))&& (testx”运算符更改为“>=”并更改“”,算法将精简为最必要的元素。在开发和测试之后,所有不必要的东西都被移除了。因此,你不能轻易理解它,但它确实做到了,而且表现非常好。

我看到下面的算法可以从这个角度检查一个点是否在给定的多边形中:

int-pnpoly(int-nvert,float*vertx,float*verty,float-testx,float-testy)
{
int i,j,c=0;
对于(i=0,j=nvert-1;itesty)!=(verty[j]>testy))&&
(testx<(vertx[j]-vertx[i])*(testy-verty[i])/(verty[j]-verty[i])+vertx[i]))
c=!c;
}
返回c;
}
我尝试了这个算法,它实际上工作得非常完美。但可悲的是,在花了一些时间试图了解它之后,我无法很好地理解它

如果有人能理解这个算法,请给我解释一下


谢谢。

我认为基本思想是从点开始计算向量,多边形的每边一个向量。如果向量穿过一条边,则该点位于多边形内。通过凹多边形如果它穿过奇数条边,它也在里面(免责声明:尽管不确定它是否适用于所有凹多边形)。

该算法是向右进行光线投射。循环的每次迭代,都会根据多边形的一条边检查测试点。如果点的y坐标在边的范围内,则if测试的第一行成功。第二行检查测试点是否在该行的左侧(我想-我手上没有要检查的废纸)。如果为真,则从测试点向右绘制的线穿过该边

通过反复反转
c
的值,该算法计算向右的直线穿过多边形的次数。如果它穿过奇数次,则该点位于内部;如果是偶数,则点位于外侧


我会关注a)浮点运算的准确性,b)水平边或与顶点具有相同y坐标的测试点的效果。

此方法检查从点(testx,testy)到O(0,0)的光线是否切割多边形的边


有一个众所周知的结论:如果一条光线从一个点开始,并在奇数时间内切割多边形的边,则该点将属于该多边形,否则该点将位于该多边形之外

Chowlett在各个方面、形状和形式上都是正确的。
该算法假设,如果您的点位于多边形的直线上,则该点位于外部-在某些情况下,这是错误的。将两个“>”运算符更改为“>=”并更改“”,算法将精简为最必要的元素。在开发和测试之后,所有不必要的东西都被移除了。因此,你不能轻易理解它,但它确实做到了,而且表现非常好。
我冒昧地把它翻译成了ActionScript-3:

// not optimized yet (nvert could be left out)
public static function pnpoly(nvert: int, vertx: Array, verty: Array, x: Number, y: Number): Boolean
{
    var i: int, j: int;
    var c: Boolean = false;
    for (i = 0, j = nvert - 1; i < nvert; j = i++)
    {
        if (((verty[i] > y) != (verty[j] > y)) && (x < (vertx[j] - vertx[i]) * (y - verty[i]) / (verty[j] - verty[i]) + vertx[i]))
            c = !c;
    }
    return c;
}
//尚未优化(可以忽略nvert)
公共静态函数pnpoly(nvert:int,vertx:Array,verty:Array,x:Number,y:Number):布尔
{
变量i:int,j:int;
变量c:布尔值=false;
对于(i=0,j=nvert-1;iy)!=(verty[j]>y))和&(x<(vertx[j]-vertx[i])*(y-verty[i])/(verty[j]-verty[i])+vertx[i]))
c=!c;
}
返回c;
}

这是我使用的算法,但我添加了一些预处理技巧以加快速度。我的多边形有大约1000条边,它们不会改变,但每次鼠标移动时,我都需要查看光标是否在其中

基本上,我将边界矩形的高度拆分为等长的间隔,并为每个间隔编译位于/与之相交的边列表

当我需要查找一个点时,我可以在O(1)时间内计算它所在的间隔,然后我只需要测试间隔列表中的边


我使用了256个间隔,这将需要测试的边的数量减少到2-10条,而不是1000条。

只要多边形的边不相交,该算法适用于任何闭合多边形。三角形、五边形、正方形,甚至是一条不交叉的非常弯曲的分段线性橡皮筋

1) 将多边形定义为一组有向向量。这意味着多边形的每一侧都由一个从顶点a到顶点a+1的向量来描述。向量的方向是这样的:一个向量的头部接触下一个向量的尾部,直到最后一个向量接触第一个向量的尾部

2) 在多边形内部或外部选择要测试的点

3) 对于沿多边形周长的每个矢量Vn,找到从测试点开始到Vn尾部结束的矢量Dn。计算定义为DnXVn/DN*VN的向量Cn(X表示叉积;*表示点积)。将Cn的大小称为Mn

4) 添加所有Mn,并将此数量称为K

5) 如果K为零,则该点位于多边形外部

6) 如果K不是零,则该点位于多边形内部

理论上,位于多边形边缘的点将产生未定义的结果

K的几何意义是坐在我们测试点上的跳蚤“看见”在多边形边缘行走的蚂蚁向左行走的总角度减去向右行走的角度。在一个闭合回路中,蚂蚁从它开始的地方结束。 在多边形之外,无论位置如何,答案都是零。
在多边形内部,无论位置如何,答案都是“围绕点一次”



这可能是在实际代码中解释光线跟踪算法的详细信息。它可能不会被优化,但必须始终在完全掌握系统之后进行优化

    //method to check if a Coordinate is located in a polygon
public boolean checkIsInPolygon(ArrayList<Coordinate> poly){
    //this method uses the ray tracing algorithm to determine if the point is in the polygon
    int nPoints=poly.size();
    int j=-999;
    int i=-999;
    boolean locatedInPolygon=false;
    for(i=0;i<(nPoints);i++){
        //repeat loop for all sets of points
        if(i==(nPoints-1)){
            //if i is the last vertex, let j be the first vertex
            j= 0;
        }else{
            //for all-else, let j=(i+1)th vertex
            j=i+1;
        }

        float vertY_i= (float)poly.get(i).getY();
        float vertX_i= (float)poly.get(i).getX();
        float vertY_j= (float)poly.get(j).getY();
        float vertX_j= (float)poly.get(j).getX();
        float testX  = (float)this.getX();
        float testY  = (float)this.getY();

        // following statement checks if testPoint.Y is below Y-coord of i-th vertex
        boolean belowLowY=vertY_i>testY;
        // following statement checks if testPoint.Y is below Y-coord of i+1-th vertex
        boolean belowHighY=vertY_j>testY;

        /* following statement is true if testPoint.Y satisfies either (only one is possible) 
        -->(i).Y < testPoint.Y < (i+1).Y        OR  
        -->(i).Y > testPoint.Y > (i+1).Y

        (Note)
        Both of the conditions indicate that a point is located within the edges of the Y-th coordinate
        of the (i)-th and the (i+1)- th vertices of the polygon. If neither of the above
        conditions is satisfied, then it is assured that a semi-infinite horizontal line draw 
        to the right from the testpoint will NOT cross the line that connects vertices i and i+1 
        of the polygon
        */
        boolean withinYsEdges= belowLowY != belowHighY;

        if( withinYsEdges){
            // this is the slope of the line that connects vertices i and i+1 of the polygon
            float slopeOfLine   = ( vertX_j-vertX_i )/ (vertY_j-vertY_i) ;

            // this looks up the x-coord of a point lying on the above line, given its y-coord
            float pointOnLine   = ( slopeOfLine* (testY - vertY_i) )+vertX_i;

            //checks to see if x-coord of testPoint is smaller than the point on the line with the same y-coord
            boolean isLeftToLine= testX < pointOnLine;

            if(isLeftToLine){
                //this statement changes true to false (and vice-versa)
                locatedInPolygon= !locatedInPolygon;
            }//end if (isLeftToLine)
        }//end if (withinYsEdges
    }

    return locatedInPolygon;
}
//检查坐标是否位于多边形中的方法
公共布尔校验隐多边形(ArrayList多边形){
//此方法使用光线跟踪算法确定点是否位于多边形中
int nPoints=poly.size();
int j=-999;
int i=-999;
布尔locatedInPolygon=false;
对于(i=0;itestY;
//跟随
    //method to check if a Coordinate is located in a polygon
public boolean checkIsInPolygon(ArrayList<Coordinate> poly){
    //this method uses the ray tracing algorithm to determine if the point is in the polygon
    int nPoints=poly.size();
    int j=-999;
    int i=-999;
    boolean locatedInPolygon=false;
    for(i=0;i<(nPoints);i++){
        //repeat loop for all sets of points
        if(i==(nPoints-1)){
            //if i is the last vertex, let j be the first vertex
            j= 0;
        }else{
            //for all-else, let j=(i+1)th vertex
            j=i+1;
        }

        float vertY_i= (float)poly.get(i).getY();
        float vertX_i= (float)poly.get(i).getX();
        float vertY_j= (float)poly.get(j).getY();
        float vertX_j= (float)poly.get(j).getX();
        float testX  = (float)this.getX();
        float testY  = (float)this.getY();

        // following statement checks if testPoint.Y is below Y-coord of i-th vertex
        boolean belowLowY=vertY_i>testY;
        // following statement checks if testPoint.Y is below Y-coord of i+1-th vertex
        boolean belowHighY=vertY_j>testY;

        /* following statement is true if testPoint.Y satisfies either (only one is possible) 
        -->(i).Y < testPoint.Y < (i+1).Y        OR  
        -->(i).Y > testPoint.Y > (i+1).Y

        (Note)
        Both of the conditions indicate that a point is located within the edges of the Y-th coordinate
        of the (i)-th and the (i+1)- th vertices of the polygon. If neither of the above
        conditions is satisfied, then it is assured that a semi-infinite horizontal line draw 
        to the right from the testpoint will NOT cross the line that connects vertices i and i+1 
        of the polygon
        */
        boolean withinYsEdges= belowLowY != belowHighY;

        if( withinYsEdges){
            // this is the slope of the line that connects vertices i and i+1 of the polygon
            float slopeOfLine   = ( vertX_j-vertX_i )/ (vertY_j-vertY_i) ;

            // this looks up the x-coord of a point lying on the above line, given its y-coord
            float pointOnLine   = ( slopeOfLine* (testY - vertY_i) )+vertX_i;

            //checks to see if x-coord of testPoint is smaller than the point on the line with the same y-coord
            boolean isLeftToLine= testX < pointOnLine;

            if(isLeftToLine){
                //this statement changes true to false (and vice-versa)
                locatedInPolygon= !locatedInPolygon;
            }//end if (isLeftToLine)
        }//end if (withinYsEdges
    }

    return locatedInPolygon;
}
bool point_in_polygon_check_edge(const vec<double, 2>& v, vec<double, 2> polygon[], int point_count, double edge_error = 1.192092896e-07f)
{
    const static int x = 0;
    const static int y = 1;
    int i, j;
    bool r = false;
    for (i = 0, j = point_count - 1; i < point_count; j = i++)
    {
        const vec<double, 2>& pi = polygon[i);
        const vec<double, 2>& pj = polygon[j];
        if (fabs(pi[y] - pj[y]) <= edge_error && fabs(pj[y] - v[y]) <= edge_error && (pi[x] >= v[x]) != (pj[x] >= v[x]))
        {
            return true;
        }

        if ((pi[y] > v[y]) != (pj[y] > v[y]))
        {
            double c = (pj[x] - pi[x]) * (v[y] - pi[y]) / (pj[y] - pi[y]) + pi[x];
            if (fabs(v[x] - c) <= edge_error)
            {
                return true;
            }
            if (v[x] < c)
            {
                r = !r;
            }
        }
    }
    return r;
}
<?php
class Point2D {

    public $x;
    public $y;

    function __construct($x, $y) {
        $this->x = $x;
        $this->y = $y;
    }

    function x() {
        return $this->x;
    }

    function y() {
        return $this->y;
    }

}

class Point {

    protected $vertices;

    function __construct($vertices) {

        $this->vertices = $vertices;
    }

    //Determines if the specified point is within the polygon. 
    function pointInPolygon($point) {
        /* @var $point Point2D */
    $poly_vertices = $this->vertices;
    $num_of_vertices = count($poly_vertices);

    $edge_error = 1.192092896e-07;
    $r = false;

    for ($i = 0, $j = $num_of_vertices - 1; $i < $num_of_vertices; $j = $i++) {
        /* @var $current_vertex_i Point2D */
        /* @var $current_vertex_j Point2D */
        $current_vertex_i = $poly_vertices[$i];
        $current_vertex_j = $poly_vertices[$j];

        if (abs($current_vertex_i->y - $current_vertex_j->y) <= $edge_error && abs($current_vertex_j->y - $point->y) <= $edge_error && ($current_vertex_i->x >= $point->x) != ($current_vertex_j->x >= $point->x)) {
            return true;
        }

        if ($current_vertex_i->y > $point->y != $current_vertex_j->y > $point->y) {
            $c = ($current_vertex_j->x - $current_vertex_i->x) * ($point->y - $current_vertex_i->y) / ($current_vertex_j->y - $current_vertex_i->y) + $current_vertex_i->x;

            if (abs($point->x - $c) <= $edge_error) {
                return true;
            }

            if ($point->x < $c) {
                $r = !$r;
            }
        }
    }

    return $r;
}
        <?php
        $vertices = array();

        array_push($vertices, new Point2D(120, 40));
        array_push($vertices, new Point2D(260, 40));
        array_push($vertices, new Point2D(45, 170));
        array_push($vertices, new Point2D(335, 170));
        array_push($vertices, new Point2D(120, 300));
        array_push($vertices, new Point2D(260, 300));


        $Point = new Point($vertices);
        $point_to_find = new Point2D(190, 170);
        $isPointInPolygon = $Point->pointInPolygon($point_to_find);
        echo $isPointInPolygon;
        var_dump($isPointInPolygon);
// This uses the ray-casting algorithm to decide whether the point is inside
// the given polygon. See https://en.wikipedia.org/wiki/Point_in_polygon#Ray_casting_algorithm
bool pnpoly(const Eigen::MatrixX2d &poly, float x, float y)
{
    // If we never cross any lines we're inside.
    bool inside = false;

    // Loop through all the edges.
    for (int i = 0; i < poly.rows(); ++i)
    {
        // i is the index of the first vertex, j is the next one.
        // The original code uses a too-clever trick for this.
        int j = (i + 1) % poly.rows();

        // The vertices of the edge we are checking.
        double xp0 = poly(i, 0);
        double yp0 = poly(i, 1);
        double xp1 = poly(j, 0);
        double yp1 = poly(j, 1);

        // Check whether the edge intersects a line from (-inf,y) to (x,y).

        // First check if the line crosses the horizontal line at y in either direction.
        if ((yp0 <= y) && (yp1 > y) || (yp1 <= y) && (yp0 > y))
        {
            // If so, get the point where it crosses that line. This is a simple solution
            // to a linear equation. Note that we can't get a division by zero here -
            // if yp1 == yp0 then the above if be false.
            double cross = (xp1 - xp0) * (y - yp0) / (yp1 - yp0) + xp0;

            // Finally check if it crosses to the left of our test point. You could equally
            // do right and it should give the same result.
            if (cross < x)
                inside = !inside;
        }
    }
    return inside;
}