How can I determine whether a 2D Point is within a Polygon?

前端 未结 30 2148
醉梦人生
醉梦人生 2020-11-21 05:06

I\'m trying to create a fast 2D point inside polygon algorithm, for use in hit-testing (e.g. Polygon.contains(p:Point)). Suggestions for effective tech

相关标签:
30条回答
  • 2020-11-21 06:06

    You can do this by checking if the area formed by connecting the desired point to the vertices of your polygon matches the area of the polygon itself.

    Or you could check if the sum of the inner angles from your point to each pair of two consecutive polygon vertices to your check point sums to 360, but I have the feeling that the first option is quicker because it doesn't involve divisions nor calculations of inverse of trigonometric functions.

    I don't know what happens if your polygon has a hole inside it but it seems to me that the main idea can be adapted to this situation

    You can as well post the question in a math community. I bet they have one million ways of doing that

    0 讨论(0)
  • Java Version:

    public class Geocode {
        private float latitude;
        private float longitude;
    
        public Geocode() {
        }
    
        public Geocode(float latitude, float longitude) {
            this.latitude = latitude;
            this.longitude = longitude;
        }
    
        public float getLatitude() {
            return latitude;
        }
    
        public void setLatitude(float latitude) {
            this.latitude = latitude;
        }
    
        public float getLongitude() {
            return longitude;
        }
    
        public void setLongitude(float longitude) {
            this.longitude = longitude;
        }
    }
    
    public class GeoPolygon {
        private ArrayList<Geocode> points;
    
        public GeoPolygon() {
            this.points = new ArrayList<Geocode>();
        }
    
        public GeoPolygon(ArrayList<Geocode> points) {
            this.points = points;
        }
    
        public GeoPolygon add(Geocode geo) {
            points.add(geo);
            return this;
        }
    
        public boolean inside(Geocode geo) {
            int i, j;
            boolean c = false;
            for (i = 0, j = points.size() - 1; i < points.size(); j = i++) {
                if (((points.get(i).getLongitude() > geo.getLongitude()) != (points.get(j).getLongitude() > geo.getLongitude())) &&
                        (geo.getLatitude() < (points.get(j).getLatitude() - points.get(i).getLatitude()) * (geo.getLongitude() - points.get(i).getLongitude()) / (points.get(j).getLongitude() - points.get(i).getLongitude()) + points.get(i).getLatitude()))
                    c = !c;
            }
            return c;
        }
    
    }
    
    0 讨论(0)
  • 2020-11-21 06:08

    Here is a JavaScript variant of the answer by M. Katz based on Nirg's approach:

    function pointIsInPoly(p, polygon) {
        var isInside = false;
        var minX = polygon[0].x, maxX = polygon[0].x;
        var minY = polygon[0].y, maxY = polygon[0].y;
        for (var n = 1; n < polygon.length; n++) {
            var q = polygon[n];
            minX = Math.min(q.x, minX);
            maxX = Math.max(q.x, maxX);
            minY = Math.min(q.y, minY);
            maxY = Math.max(q.y, maxY);
        }
    
        if (p.x < minX || p.x > maxX || p.y < minY || p.y > maxY) {
            return false;
        }
    
        var i = 0, j = polygon.length - 1;
        for (i, j; i < polygon.length; j = i++) {
            if ( (polygon[i].y > p.y) != (polygon[j].y > p.y) &&
                    p.x < (polygon[j].x - polygon[i].x) * (p.y - polygon[i].y) / (polygon[j].y - polygon[i].y) + polygon[i].x ) {
                isInside = !isInside;
            }
        }
    
        return isInside;
    }
    
    0 讨论(0)
  • 2020-11-21 06:09

    David Segond's answer is pretty much the standard general answer, and Richard T's is the most common optimization, though therre are some others. Other strong optimizations are based on less general solutions. For example if you are going to check the same polygon with lots of points, triangulating the polygon can speed things up hugely as there are a number of very fast TIN searching algorithms. Another is if the polygon and points are on a limited plane at low resolution, say a screen display, you can paint the polygon onto a memory mapped display buffer in a given colour, and check the color of a given pixel to see if it lies in the polygons.

    Like many optimizations, these are based on specific rather than general cases, and yield beneifits based on amortized time rather than single usage.

    Working in this field, i found Joeseph O'Rourkes 'Computation Geometry in C' ISBN 0-521-44034-3 to be a great help.

    0 讨论(0)
  • There is nothing more beutiful than an inductive definition of a problem. For the sake of completeness here you have a version in prolog which might also clarify the thoughs behind ray casting:

    Based on the simulation of simplicity algorithm in http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html

    Some helper predicates:

    exor(A,B):- \+A,B;A,\+B.
    in_range(Coordinate,CA,CB) :- exor((CA>Coordinate),(CB>Coordinate)).
    
    inside(false).
    inside(_,[_|[]]).
    inside(X:Y, [X1:Y1,X2:Y2|R]) :- in_range(Y,Y1,Y2), X > ( ((X2-X1)*(Y-Y1))/(Y2-Y1) +      X1),toggle_ray, inside(X:Y, [X2:Y2|R]); inside(X:Y, [X2:Y2|R]).
    
    get_line(_,_,[]).
    get_line([XA:YA,XB:YB],[X1:Y1,X2:Y2|R]):- [XA:YA,XB:YB]=[X1:Y1,X2:Y2]; get_line([XA:YA,XB:YB],[X2:Y2|R]).
    

    The equation of a line given 2 points A and B (Line(A,B)) is:

                        (YB-YA)
               Y - YA = ------- * (X - XA) 
                        (XB-YB) 
    

    It is important that the direction of rotation for the line is setted to clock-wise for boundaries and anti-clock-wise for holes. We are going to check whether the point (X,Y), i.e the tested point is at the left half-plane of our line (it is a matter of taste, it could also be the right side, but also the direction of boundaries lines has to be changed in that case), this is to project the ray from the point to the right (or left) and acknowledge the intersection with the line. We have chosen to project the ray in the horizontal direction (again it is a matter of taste, it could also be done in vertical with similar restrictions), so we have:

                   (XB-XA)
               X < ------- * (Y - YA) + XA
                   (YB-YA) 
    

    Now we need to know if the point is at the left (or right) side of the line segment only, not the entire plane, so we need to restrict the search only to this segment, but this is easy since to be inside the segment only one point in the line can be higher than Y in the vertical axis. As this is a stronger restriction it needs to be the first to check, so we take first only those lines meeting this requirement and then check its possition. By the Jordan Curve theorem any ray projected to a polygon must intersect at an even number of lines. So we are done, we will throw the ray to the right and then everytime it intersects a line, toggle its state. However in our implementation we are goint to check the lenght of the bag of solutions meeting the given restrictions and decide the innership upon it. for each line in the polygon this have to be done.

    is_left_half_plane(_,[],[],_).
    is_left_half_plane(X:Y,[XA:YA,XB:YB], [[X1:Y1,X2:Y2]|R], Test) :- [XA:YA, XB:YB] =  [X1:Y1, X2:Y2], call(Test, X , (((XB - XA) * (Y - YA)) / (YB - YA) + XA)); 
                                                            is_left_half_plane(X:Y, [XA:YA, XB:YB], R, Test).
    
    in_y_range_at_poly(Y,[XA:YA,XB:YB],Polygon) :- get_line([XA:YA,XB:YB],Polygon),  in_range(Y,YA,YB).
    all_in_range(Coordinate,Polygon,Lines) :- aggregate(bag(Line),    in_y_range_at_poly(Coordinate,Line,Polygon), Lines).
    
    traverses_ray(X:Y, Lines, Count) :- aggregate(bag(Line), is_left_half_plane(X:Y, Line, Lines, <), IntersectingLines), length(IntersectingLines, Count).
    
    % This is the entry point predicate
    inside_poly(X:Y,Polygon,Answer) :- all_in_range(Y,Polygon,Lines), traverses_ray(X:Y, Lines, Count), (1 is mod(Count,2)->Answer=inside;Answer=outside).
    
    0 讨论(0)
  • 2020-11-21 06:11

    Really like the solution posted by Nirg and edited by bobobobo. I just made it javascript friendly and a little more legible for my use:

    function insidePoly(poly, pointx, pointy) {
        var i, j;
        var inside = false;
        for (i = 0, j = poly.length - 1; i < poly.length; j = i++) {
            if(((poly[i].y > pointy) != (poly[j].y > pointy)) && (pointx < (poly[j].x-poly[i].x) * (pointy-poly[i].y) / (poly[j].y-poly[i].y) + poly[i].x) ) inside = !inside;
        }
        return inside;
    }
    
    0 讨论(0)
提交回复
热议问题