Search code examples
c++cgal

Is there a CGAL function for finding all intersecting points between a 2D line (Line_2) and a set of 2D polygons with holes (Polygon_with_holes_2)?


I have a line from 0, 0 to 1024, 0. Many polygons with holes lie between the two ends of the lines. I would like to know if there is any CGAL function that can tell me all the points of intersection between the line segment and all the polygons with holes.

Alternatively, a function for intersection between a line and a single polygon with holes would also suffice for the moment. This function would have to tell me all the points at which the line intersects with the polygon with holes.


Solution

  • The answer is no. Intersection functions for polygons work with two polygons only, and the meaning of the intersection is a piece of plane, consisting of points, lying inside both polygons. If you want to find intersection points for a segment and the polygon boundary - you need to extract all the boundary edges one by one and compute all the intersections one by one. The example is below:

    #include <iostream>
    #include <vector>
    
    #include <CGAL/Exact_predicates_exact_constructions_kernel.h>
    #include <CGAL/Polygon_2.h>
    
    using Kernel = CGAL::Exact_predicates_exact_constructions_kernel;
    using Polygon = CGAL::Polygon_2<Kernel>;
    using Point = Polygon::Point_2;
    using Segment = Polygon::Segment_2;
    
    int main()
    {
      // ------ define segment
      const Segment s{{-1000, 0}, {1000, 0}};
      // ------ define polygon
      const std::vector<Point> pts{{3, 3}, {-3, 3}, {-3, -3}, {3, -3}};
      const Polygon p(pts.cbegin(), pts.cend());
      // ------ find all intersections of the segment with polygon edges
      for (auto eit = p.edges_begin(); eit != p.edges_end(); ++eit)
      {
        const auto res = CGAL::intersection(s, *eit);
        if (res)
        {
          const auto pt = boost::get<Point>(&*res);
          std::cout << *pt << std::endl;
        }
      }
    }
    

    If you work with polygons with holes, then this process should be repeated for all the holes. The example above is a simplification of the intersections processing - more complete examples can be found here.