[math] A simple algorithm for polygon intersection

I'm looking for a very simple algorithm for computing the polygon intersection/clipping. That is, given polygons P, Q, I wish to find polygon T which is contained in P and in Q, and I wish T to be maximal among all possible polygons.

I don't mind the run time (I have a few very small polygons), I can also afford getting an approximation of the polygons' intersection (that is, a polygon with less points, but which is still contained in the polygons' intersection).

But it is really important for me that the algorithm will be simple (cheaper testing) and preferably short (less code).

edit: please note, I wish to obtain a polygon which represent the intersection. I don't need only a boolean answer to the question of whether the two polygons intersect.

This question is related to math geometry 2d polygon

The answer is


I have no very simple solution, but here are the main steps for the real algorithm:

  1. Do a custom double linked list for the polygon vertices and edges. Using std::list won't do because you must swap next and previous pointers/offsets yourself for a special operation on the nodes. This is the only way to have simple code, and this will give good performance.
  2. Find the intersection points by comparing each pair of edges. Note that comparing each pair of edge will give O(N²) time, but improving the algorithm to O(N·logN) will be easy afterwards. For some pair of edges (say a?b and c?d), the intersection point is found by using the parameter (from 0 to 1) on edge a?b, which is given by t?=d0/(d0-d1), where d0 is (c-a)×(b-a) and d1 is (d-a)×(b-a). × is the 2D cross product such as p×q=p?·q?-p?·q?. After having found t?, finding the intersection point is using it as a linear interpolation parameter on segment a?b: P=a+t?(b-a)
  3. Split each edge adding vertices (and nodes in your linked list) where the segments intersect.
  4. Then you must cross the nodes at the intersection points. This is the operation for which you needed to do a custom double linked list. You must swap some pair of next pointers (and update the previous pointers accordingly).

Then you have the raw result of the polygon intersection resolving algorithm. Normally, you will want to select some region according to the winding number of each region. Search for polygon winding number for an explanation on this.

If you want to make a O(N·logN) algorithm out of this O(N²) one, you must do exactly the same thing except that you do it inside of a line sweep algorithm. Look for Bentley Ottman algorithm. The inner algorithm will be the same, with the only difference that you will have a reduced number of edges to compare, inside of the loop.


If you do not care about predictable run time you could try by first splitting your polygons into unions of convex polygons and then pairwise computing the intersection between the sub-polygons.

This would give you a collection of convex polygons such that their union is exactly the intersection of your starting polygons.


This can be a huge approximation depending on your polygons, but here's one :

  • Compute the center of mass for each polygon.
  • Compute the min or max or average distance from each point of the polygon to the center of mass.
  • If C1C2 (where C1/2 is the center of the first/second polygon) >= D1 + D2 (where D1/2 is the distance you computed for first/second polygon) then the two polygons "intersect".

Though, this should be very efficient as any transformation to the polygon applies in the very same way to the center of mass and the center-node distances can be computed only once.


If you use C++, and don't want to create the algorithm yourself, you can use Boost.Geometry. It uses an adapted version of the Weiler-Atherton algorithm mentioned above.


The way I worked about the same problem

  1. breaking the polygon into line segments
  2. find intersecting line using IntervalTrees or LineSweepAlgo
  3. finding a closed path using GrahamScanAlgo to find a closed path with adjacent vertices
  4. Cross Reference 3. with DinicAlgo to Dissolve them

note: my scenario was different given the polygons had a common vertice. But Hope this can help


Here's a simple-and-stupid approach: on input, discretize your polygons into a bitmap. To intersect, AND the bitmaps together. To produce output polygons, trace out the jaggy borders of the bitmap and smooth the jaggies using a polygon-approximation algorithm. (I don't remember if that link gives the most suitable algorithms, it's just the first Google hit. You might check out one of the tools out there to convert bitmap images to vector representations. Maybe you could call on them without reimplementing the algorithm?)

The most complex part would be tracing out the borders, I think.

Back in the early 90s I faced something like this problem at work, by the way. I muffed it: I came up with a (completely different) algorithm that would work on real-number coordinates, but seemed to run into a completely unfixable plethora of degenerate cases in the face of the realities of floating-point (and noisy input). Perhaps with the help of the internet I'd have done better!


You have not given us your representation of a polygon. So I am choosing (more like suggesting) one for you :)

Represent each polygon as one big convex polygon, and a list of smaller convex polygons which need to be 'subtracted' from that big convex polygon.

Now given two polygons in that representation, you can compute the intersection as:

Compute intersection of the big convex polygons to form the big polygon of the intersection. Then 'subtract' the intersections of all the smaller ones of both to get a list of subracted polygons.

You get a new polygon following the same representation.

Since convex polygon intersection is easy, this intersection finding should be easy too.

This seems like it should work, but I haven't given it more deeper thought as regards to correctness/time/space complexity.


You could use a Polygon Clipping algorithm to find the intersection between two polygons. However these tend to be complicated algorithms when all of the edge cases are taken into account.

One implementation of polygon clipping that you can use your favorite search engine to look for is Weiler-Atherton. wikipedia article on Weiler-Atherton

Alan Murta has a complete implementation of a polygon clipper GPC.

Edit:

Another approach is to first divide each polygon into a set of triangles, which are easier to deal with. The Two-Ears Theorem by Gary H. Meisters does the trick. This page at McGill does a good job of explaining triangle subdivision.


Examples related to math

How to do perspective fixing? How to pad a string with leading zeros in Python 3 How can I use "e" (Euler's number) and power operation in python 2.7 numpy max vs amax vs maximum Efficiently getting all divisors of a given number Using atan2 to find angle between two vectors How to calculate percentage when old value is ZERO Finding square root without using sqrt function? Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt? How do I get the total number of unique pairs of a set in the database?

Examples related to geometry

Circle button css Using atan2 to find angle between two vectors How do I compute the intersection point of two lines? Creating a triangle with for loops Plotting a 3d cube, a sphere and a vector in Matplotlib How to find the Center Coordinate of Rectangle? Evenly distributing n points on a sphere How do CSS triangles work? How to draw circle in html page? Generate a random point within a circle (uniformly)

Examples related to 2d

Declare an empty two-dimensional array in Javascript? Most efficient way to find mode in numpy array 2D cross-platform game engine for Android and iOS? A simple algorithm for polygon intersection Difference between SurfaceView and View? Drawing Isometric game worlds Calculating a 2D Vector's Cross Product

Examples related to polygon

How do CSS triangles work? Polygon Drawing and Getting Coordinates with Google Map API v3 A simple algorithm for polygon intersection How to determine if a list of polygon points are in clockwise order? How can I determine whether a 2D Point is within a Polygon?