Search code examples
c++intersectionclipperlib

How do I determine if two polygons intersect using Clipper?


I am using Clipper and want to determine if two (multi-)polygons intersect.

My expectation was that the library would have a nice, abstract way of asking this question, but it does not seem to.

I thought that the Area() method might be useful, but it only works on Path and the Execute() method returns Paths.

I've built the following M(almost)WE demonstrating the issue:

#include <iostream>
#include "clipper.hpp"
using namespace ClipperLib;

Paths MakeBox(int xmin, int xmax, int ymin, int ymax){
  Paths temp(1);
  temp[0] << IntPoint(xmin,ymin) << IntPoint(xmax,ymin) << IntPoint(xmax,ymax) << IntPoint(xmin,ymax);
  return temp;
}

bool Intersects(const Paths &subj, const Paths &clip){
  ClipperLib::Clipper c;

  c.AddPaths(subj, ClipperLib::ptSubject, true);
  c.AddPaths(clip, ClipperLib::ptClip,    true);

  ClipperLib::Paths solution;
  c.Execute(ClipperLib::ctIntersection, solution, ClipperLib::pftNonZero, ClipperLib::pftNonZero);

  return Area(solution);
}

int main(){
  Paths subj  = MakeBox(0,10,0,10);
  Paths clip1 = MakeBox(1,2,1,2);
  Paths clip2 = MakeBox(15,20,15,20);

  Intersects(subj,clip1);
  Intersects(subj,clip2);
}

Solution

  • It seems as though the simplest way of doing this is to count the number of paths in the Paths object returned by the Execute() method. Paths is a simple vector, so, if it has size()==0, there is not intersection.

    #include <iostream>
    #include "clipper.hpp"
    using namespace ClipperLib;
    
    Paths MakeBox(int xmin, int xmax, int ymin, int ymax){
      Paths temp(1);
      temp[0] << IntPoint(xmin,ymin) << IntPoint(xmax,ymin) << IntPoint(xmax,ymax) << IntPoint(xmin,ymax);
      return temp;
    }
    
    bool Intersects(const Paths &subj, const Paths &clip){
      ClipperLib::Clipper c;
    
      c.AddPaths(subj, ClipperLib::ptSubject, true);
      c.AddPaths(clip, ClipperLib::ptClip,    true);
    
      ClipperLib::Paths solution;
      c.Execute(ClipperLib::ctIntersection, solution, ClipperLib::pftNonZero, ClipperLib::pftNonZero);
    
      return solution.size()!=0;
    }
    
    int main(){
      Paths subj  = MakeBox(0,10,0,10);
      Paths clip1 = MakeBox(1,2,1,2);
      Paths clip2 = MakeBox(15,20,15,20);
    
      Intersects(subj,clip1);
      Intersects(subj,clip2);
    }