Notes on the Martinez-Rueda Polygon Clipping algorithm: Segments to Paths

Posted on 28 November, 2026

The Martinez-Rueda algorithm computes boolean operations between polygons. It works at the segment level. This article describes the graph faces computation algorithm which is used to convert those segments to paths (lists of ordered points).

This is part of a group of articles on the Martinez-Rueda Polygon algorithm. The other articles are:

Table of Contents

1 Introduction

Boolean operations spiral star
Boolean operations between a spiral and a star, computed with the Martinez-Rueda algorithm.

The Martinez-Rueda algorithm is a generic, versatile algorithm for calculating boolean operations between polygons such as intersections (also known as polygon clipping) as well as unions, differences, and XORs. This is useful for graphic art programs (e.g. Inkscape) and also geospatial/geographic information systems (GIS). It can also be used for computer games, but often simpler, faster algorithms are used there instead.

I have implemented Martinez-Rueda in my PolygonAlgorithms.jl Julia package. I recently updated this package to use graph faces computation to convert segments to paths. See Pull Request 35. This closed issue #24 Handle improper self-intersecting polygons. This is the focus of the blog post.

Fill annotations
Fill annotations in the Martinez-Rueda algorithm.

The full description of the Martinez-Rueda algorithm can be found in their paper A new algorithm for computing Boolean operations on polygons (2009). At a high level, the main idea of the Martinez-Rueda algorithm is to annotate segments with filled above and filled below during a line sweep, and then to use those annotations to select the relevant segments in the output polygon.

The algorithm outputs a collection of segments. However in most cases the input is a path - an ordered list of points - and the desired output is also a path. Therefore the challenge is to map segments to paths.

So if the output is a list of segments, which is a list of pairs of points:

\[[((1.0, 1.2), (1.4, 1.8)), ..., ((1.4, 1.8), (2.0, 3.5)), ...]\]

then we want to convert it to a list of paths, which is a list of lists of points:

\[[[(1.0, 1.2), (1.4, 1.8), (2.0, 3.5), ...],...]\]

A follow-up paper, A simple algorithm for Boolean operations on polygons (2013), describes an algorithm called computeContour. It relies on the fact that the line sweep processes events in sorted order, left to right and then bottom to top, so its output is already sorted. Each event points to the other end of its edge, and any other event at the same point sits next to it in the output, so the next edge can be found in constant time. However, the paper notes this only works when exactly two edges meet at each vertex.

My original code did not use this algorithm. Instead it used a “segment chaining” algorithm based on this blog post https://sean.fun/a/polygon-clipping-pt2/. Here is the description from the blog post:

The basic algorithm is to keep a list of open chains.

When we process a segment, search to see if it can be added to the end of any open chains.

If it can’t be added to a chain, then create a new open chain with the single segment inside of it.

If it can be added to two open chains, then combine the chains into a single open chain.

Otherwise, if it is only added to a single open chain, then we’ll need to check if adding the segment causes the chain to close. If so, close the chain and add it to the region list (and remove it from the list of open chains).

This algorithm looks simple but relies on the same assumption as computeContour: exactly two segments meet at each vertex. For improper polygons this is not true. This resulted in a common “There are still open chains at the end of processing all segments” error at the end of the algorithm that end users could not address easily.

Here are some examples where the segment chaining algorithm fails or produces inconsistent results:

improper
Improper polygons

There are workarounds to this issue, however I eventually decided to instead implement a totally new algorithm which does not have this issue at all. This is the graph faces computation algorithm.

2 Computing graph faces

My main source for this algorithm was this answer on StackOverflow.

Graph to faces

Given a directed graph of edges $(u, v)$, the task of computing the faces of the graph is known as “graph face computation”. A “face” is a region of the plane bounded by a loop of half-edges. A graph can have multiple interior faces and one exterior face per disconnected region, which covers all interior faces in that region. In total the faces have double the area of the graph. The algorithm returns all faces, and so the step afterwards is to discern which ones are relevant. See the Segments to Paths section. The algorithm is linear in the number of edges $E$: $\mathcal{O}(E)$. (This assumes the number of half-edges per node is low, so the sorting cost can be ignored.)

Graph faces computation has the following advantages over segment chaining:

  1. It handles improper polygons.
  2. It returns consistent polygon directions, returning all exteriors as counter-clockwise polygons and all interior polygons as clockwise.
  3. The result is independent of the starting points in the algorithm.
  4. The user can easily choose between two modes, what I call SPLIT_FACES and MERGE_FACES. See later in Segments to Paths.

The first step of the algorithm is to convert the segments to a directed graph of $\text{nodes} \rightarrow \text{half-edges}$. “Directed” means that the half-edge $(u, v)$ from $u$ to $v$ is different to the half-edge $(v, u)$ from $v$ to $u$. The algorithm requires that the half-edges are sorted clockwise around each node, so that is done here as well.

Directed graphs from segments
inputs: segments
MAP graph $\leftarrow$ {}
for segment $\in$ segments
$\quad$ segment $\leftarrow$ snap_to_grid(segment)
$\quad$ graph[segment$_1$].add(segment)
$\quad$ graph[segment$_2$].add(reverse(segment))
for node $\in$ graph
$\quad$ graph[node] $\leftarrow$ sort_clockwise(graph[node])
return graph

The simplest implementation of snap_to_grid is to round the points to a given decimal place e.g. to 6 decimal places. My code uses a slightly more complex version that additionally checks if any rounded points already exist in half the spacing, e.g. $0.5 \times 10^{-6}$, and snaps to that point instead. This is to prevent aggressive rounding if there are trailing numeric errors, e.g. it snaps 0.007812500005 to 0.007812 instead of rounding to 0.007813. The sort_clockwise function compares angles calculated using atan.

The main insight of the algorithm is the incredibly simple observation that for the edge $(X, Y)$, if $Z$ is the next neighbor clockwise around the node $X$, then the half-edge $(Z, X)$ comes before $(X, Y)$. Put another way, if we know the half-edges around the node $X$ are $[(X, Y),(X, Z),…]$ in that order, then we know that $(Z, X)$ connects to $(X, Y)$. Therefore we can map every edge to the edge that comes after it, and then we can follow this map to walk all edges in the graph. This will return all exterior faces as counter-clockwise and all interior faces as clockwise.

Nodes around X

First, loop over all nodes and map all connections:

Map Connections
inputs: graph
MAP connections $\leftarrow$ {}
for node $\in$ graph
$\quad$ half_edges $\leftarrow$ graph[node]
$\quad$ for $i$ $\in$ 1 to length(half_edges)
$\quad\quad$ connections[(half_edges$_{i+1,2}$, node)] $\leftarrow$ half_edges$_i$
return connections

Then walk the connections:

Walk Connections
inputs: connections
LIST chains $\leftarrow$ []
SET visited $\leftarrow$ {}
for start $\in$ connections
$\quad$ if start $\notin$ visited
$\quad\quad$ visited $\leftarrow$ visited $\cup$ {start}
$\quad\quad$ chain $\leftarrow$ [start]
$\quad\quad$ next_edge $\leftarrow$ connections[start]
$\quad\quad$ while next_edge $\neq$ start
$\quad\quad\quad$ if next_edge $\in$ visited
$\quad\quad\quad\quad$ ERROR CYCLE
$\quad\quad\quad$ visited $\leftarrow$ visited $\cup$ {next_edge}
$\quad\quad\quad$ chain.add(next_edge)
$\quad\quad\quad$ next_edge $\leftarrow$ connections[next_edge]
$\quad\quad$ chains.add(chain)
return chains

This will return all interior faces and one exterior face for each disconnected polygon. The faces have double the area of the graph, so we need to determine how to halve this.

We want to return two separate sets:

  • The exterior faces as polygons.
  • Any interior faces that are holes.

My code also returns a third set, zero-area polygons, also known as lines.

As a first pass, exteriors are counter-clockwise and interiors are clockwise. So we can separate exterior and interior faces by checking if they are counter-clockwise or not. This is equivalent to checking if the area of the face is positive. This can be calculated with the shoe-lace formula:

\[\begin{align} \frac{1}{2} \sum_{i=1}^n (x_{i}y_{i+1} - y_ix_{i+1}) > 0 \end{align}\]

However we need further information to determine if a face is a hole or not.

3 Is hole?

The most important insight is that the directed graph has no information on fill. You cannot tell whether a face is a hole or not from the graph.

holes

To explain this further, see the above figure and note that multiple interpretations are perfectly valid of the same graph: either the shape is empty, or the centre is a hole, or the shape is filled.

Instead we need to save the fill annotations per segment and carry them through. This is why the Walk Connections in the above section carries through the edges and does not convert them to points. In particular, it has chain.add(next_edge) and not chain.add(next_point).

Then use the following definition to determine if a face is a hole:

A face is a hole if its inner region is not filled.

normal
Vectors and their normals around a counter-clockwise polygon

For a single vector $(\Delta x, \Delta y)$:

  • If the face is counter-clockwise, the inner region is on the left, and the normal $(-\Delta y, \Delta x)$ points into it. If $\Delta x$ is positive, the normal points upwards and so check if it is filled above, else check if it is filled below.
  • If the face is clockwise, the inner region is on the right, and the normal $(\Delta y, -\Delta x)$ points into it. If $-\Delta x$ is positive, the normal points upwards and so check if it is filled above, else check if it is filled below.

Here is the same algorithm in pseudo-code:

Is hole?
inputs: face
edge $\leftarrow$ sample(face)
$\Delta x$ $\leftarrow$ edge$_{2, 1}$ - edge$_{1, 1}$
if is_counter_clockwise(face)
$\quad$ filled_inner $\leftarrow$ filled_above if $\Delta x > 0$ else filled_below
else
$\quad$ filled_inner $\leftarrow$ filled_below if $\Delta x > 0$ else filled_above
return not filled_inner

To make this algorithm more robust, my code skips vertical edges ($\Delta x = 0$) and does majority voting with all other edges. That is, a face is a hole if a majority of its edges return true with the above algorithm.

4 Segments to Paths

With the Is hole? algorithm we can formulate a simple rule to halve the faces:

  • Polygons are all exterior faces that are not holes.
  • Their holes are all interior faces that are holes.

I call this rule MERGE_FACES because it tends to return fewer, larger polygons with explicit holes.

An alternative rule is SPLIT_FACES. This rule tends to return more, smaller polygons that sometimes have explicit holes and sometimes implied holes:

  • Polygons are all interior faces that are not holes that are on the exterior, each reversed so that they are counter-clockwise according to the convention.
  • Their holes are all interior faces that are holes that are not on the exterior.

After the Martinez-Rueda line sweep, it is guaranteed that interiors that are on the exterior will share one or more points (all intersection points will be present), so this requires only checking the set of points of the exterior.

This rule is recursive: adding a face to the exterior means that all interiors that have been rejected need to be checked again, because they might be on the new face. In general this won’t require more than two to five passes. However it is possible to construct a union of polygons which requires arbitrarily many passes. See the figure below.

Expanding frontier
A sequence of polygons where the frontier expands 3×.

Here is a comparison between these modes:

Face selection
Face selection modes for segments to paths.

A final, optional step is to match holes to polygons. This step can be costly. It requires checking if a single point of a hole is in a given polygon (including on the boundary of the polygon). For consistency, my code checks the smallest to the largest polygon, so that a hole is always part of the smallest suitable polygon. For a loop over all polygons and holes, this is $\mathcal{O}(phn)$ in the worst case for $p$ parent polygons, $h$ holes, and $n$ points on average per parent polygon.

5 Conclusion

Graph face computation is a more theoretical but more elegant solution to the segment to paths problem. Unlike segment chaining, it can handle improper polygons, it returns polygons in a consistent way and as a bonus, the end user can choose between two modes: MERGE_FACES or SPLIT_FACES. It was well worth the effort to change over to this algorithm.