Search code examples
c++boostgeometrynumerical-methodsboost-geometry

Using boost geometry to check if two lines have an intersection


Is it possible to use boost::geometry to check whether two line segments (each given by two points in 2D) intersect each other? If this is possible, does boost::geometry allow to check also for special cases such as that only one point is (numerically) on the other line, or that both lines are equal?


Solution

  • If you are talking specifically about Boost.Geometry API to it is, of course, possible.

    Your code should look roughly like this

    #include <boost/geometry/geometries/segment.hpp> 
    #include <boost/geometry/algorithms/intersection.hpp>
    
    typedef boost::geometry::model::segment<Point> Segment;
    Segment AB( Point(x1,y1), Point(x2,y2) );
    Segment CD; //similar code
    
    bool result = boost::geometry::intersects(AB, CD);
    

    If you need intersection points:

    std::vector<Point> output; 
    boost::geometry::intersection(AB, CD, output);
    

    Now output will have 0, 1 or 2 points, depending on locations.

    Of course, your Point type should be "compliant" with Boost.Geometry concepts. The following code will make QPointF compliant:

    #include <boost/geometry/geometries/register/point.hpp>
    BOOST_GEOMETRY_REGISTER_POINT_2D_GET_SET(QPointF, qreal, cs::cartesian, x, y, setX, setY);