| Title: | Overlay Any Number of Polygon Layers with a Triangle Mesh |
|---|---|
| Description: | Overlay polygon layers by building one constrained Delaunay triangulation of every input edge from every layer, with crossings inserted as new vertices, and recording which input features cover each triangle. The mesh and its index answer overlay questions for any number of layers at once: where features overlap, how many times, and which features are involved. Overlay pieces are dissolved from the mesh, so they form an exact partition with shared vertices, unlike pairwise polygon clipping. Input is anything the 'wk' package reads, the vertex pool comes from 'wkpool' and the triangulation from 'cdtr'. |
| Authors: | Michael Sumner [aut, cre, cph] (ORCID: <https://orcid.org/0000-0002-2471-7511>), Gabriel Becker [ctb] (Provided the package name.) |
| Maintainer: | Michael Sumner <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.4.0 |
| Built: | 2026-11-18 06:25:58 UTC |
| Source: | https://github.com/hypertidy/polymer |
A, B and C are three partially overlapping polygon layers with
different attributes: A is four squares in a 2 by 2 grid over the unit square, B is a
single triangle and C a single thin rectangle.
'sf' data frames with no coordinate reference system:
A: 4 rows, layer, a and geometry.
B: 1 row, b and geometry.
C: 1 row, c and geometry.
polymer(A, B, C)polymer(A, B, C)
Two polygon layers used to show overlay: soil is a coverage of 12
quadrilaterals (a jittered 4 by 3 grid) with a made-up soil type, and
field has two rectangular fields that cross them. The layout follows an
example from a question on the GIS Stack Exchange
(https://gis.stackexchange.com/a/230161), but both layers are generated
by data-raw/field-soil.R, with no external data.
'sf' data frames in longitude and latitude (WGS84):
soil: 12 rows, soil (character) and geometry.
field: 2 rows, field (character) and geoms.
polymer(soil, field)polymer(soil, field)
Dissolve the triangles of a polymer into polygons, one for each distinct
set of covering input features. This is the n-ary intersection of all
layers (the same partition that sf::st_intersection() computes for a
single layer), derived from the mesh rather than from pairwise overlay.
fuse(x, ...) layer_n(x, n = 2, ...)fuse(x, ...) layer_n(x, n = 2, ...)
x |
A polymer (see |
... |
Ignored. |
n |
Minimum number of covering features, for |
layer_n() keeps the pieces covered by at least n features.
Pieces are dissolved along mesh edges, so they share vertices exactly where they touch. Outer rings are counter-clockwise and holes clockwise. Every piece is a MULTIPOLYGON, with one polygon for each connected part.
A data frame with one row per piece and columns
n: the number of input features covering the piece.
origins: a list column, each element a data frame of layer and
feature (row within its layer) for the features covering the piece.
geometry: a wk::wkb() vector with the polymer's coordinate reference
system. Convert with sf::st_as_sf() if you work with 'sf'.
pool <- polymer(A, B, C) pieces <- fuse(pool) pieces[c("n", "geometry")] ## which features made the deepest piece pieces$origins[[which.max(pieces$n)]] ## pieces covered two or more times plot(pool) wk::wk_plot(layer_n(pool, 2)$geometry, add = TRUE, col = "grey") wk::wk_plot(layer_n(pool, 3)$geometry, add = TRUE, col = "dodgerblue") layer_n(pool, 3)pool <- polymer(A, B, C) pieces <- fuse(pool) pieces[c("n", "geometry")] ## which features made the deepest piece pieces$origins[[which.max(pieces$n)]] ## pieces covered two or more times plot(pool) wk::wk_plot(layer_n(pool, 2)$geometry, add = TRUE, col = "grey") wk::wk_plot(layer_n(pool, 3)$geometry, add = TRUE, col = "dodgerblue") layer_n(pool, 3)
The labelling that polymer() uses to find which input features cover
each triangle is a dependency-free, header-only C++17 file,
polymer/overlay.hpp (MIT). Another package can use it directly, for
example to label a mesh of its own from a constrained triangulation with
its edge_sources, without going through R.
In the other package's DESCRIPTION, link to polymer (and to 'cpp11' if
that is how it talks to R; the header itself needs only the C++ standard
library):
LinkingTo: cpp11, polymer
The header needs C++17, which is not the default in every R version that
polymer supports, so set it in src/Makevars (and src/Makevars.win):
CXX_STD = CXX17
Then #include <polymer/overlay.hpp>. Everything is in the
polymer::overlay namespace.
polymer::overlay::label() takes borrowed, 0-based views of
a Mesh: counter-clockwise triangles (tri, three vertex ids each)
and the constraint edges (edge, two vertex ids each);
EdgeSources: one row for each constraint edge and input segment
lying on it, with the segment's feature and whether it runs the same
way as the edge (forward), as from cdtr::cdt_triangulate(edge_sources = TRUE);
a FillRule: NonZero, EvenOdd or Positive.
It returns Labels: tri_set, the covering set of each triangle (-1
when uncovered), the sets in compressed form (set_offset,
set_feature), and inconsistent_edges, a self-check count where a
non-zero value means the noding is broken. No coordinates are used. The
header's own comments give the details.
One counter-clockwise triangle whose three edges belong to feature 0, all running the same way as the edge:
#include <cpp11.hpp>
#include <polymer/overlay.hpp>
[[cpp11::register]]
cpp11::writable::integers label_one() {
using namespace polymer::overlay;
std::vector<int32_t> tri = {0, 1, 2};
std::vector<int32_t> edge = {0, 1, 1, 2, 2, 0};
std::vector<int32_t> es_edge = {0, 1, 2};
std::vector<int32_t> es_feature = {0, 0, 0};
std::vector<int8_t> es_forward = {1, 1, 1};
Mesh m;
m.tri = tri.data(); m.n_tri = 1;
m.edge = edge.data(); m.n_edge = 3;
EdgeSources s;
s.edge = es_edge.data(); s.feature = es_feature.data();
s.forward = es_forward.data(); s.n = 3;
Labels l = label(m, s, FillRule::NonZero);
// l.tri_set is {0}: the triangle is covered by set 0, whose only
// feature is 0; l.inconsistent_edges is 0
return cpp11::writable::integers(l.tri_set.begin(), l.tri_set.end());
}
label() throws std::exception on malformed input, so catch it at the
R boundary (cpp11 does this for exceptions that escape a registered
function).
polymer(), which calls the header on the output of
cdtr::cdt_triangulate().
Draw the triangles of the mesh. With show_intersection = TRUE the
triangles covered by two or more input features are filled.
## S3 method for class 'polymer' plot(x, ..., show_intersection = FALSE)## S3 method for class 'polymer' plot(x, ..., show_intersection = FALSE)
x |
A polymer. |
... |
Arguments passed to |
show_intersection |
Logical, fill the triangles covered more than
once (default |
x, invisibly.
plot(polymer(A, B, C)) plot(polymer(A, B, C), show_intersection = TRUE, col = "firebrick")plot(polymer(A, B, C)) plot(polymer(A, B, C), show_intersection = TRUE, col = "firebrick")
Combine one or more polygon layers into a single triangle mesh, where every input edge from every layer is kept as a chain of mesh edges, and record which input features cover each triangle.
polymer( ..., rule = c("nonzero", "evenodd", "positive"), engine = "cdtr", label = c("mesh", "pip") )polymer( ..., rule = c("nonzero", "evenodd", "positive"), engine = "cdtr", label = c("mesh", "pip") )
... |
Polygon layers. Each can be anything the 'wk' package can read
(an 'sf' data frame or |
rule |
The fill rule: |
engine |
The triangulation engine. Only |
label |
How triangles are labelled: |
All the inputs' edges are triangulated together in one constrained Delaunay triangulation. Where edges from different features cross, the crossing is inserted as a new vertex, so the mesh is a partition of the plane that respects every input boundary. Vertices are shared on exact coordinate equality before triangulation.
Each triangle is then labelled with the features that cover it. The
winding number of every feature is propagated across the mesh from the
outside: stepping over a mesh edge adds or subtracts one for each input
edge lying on it, by its direction. This uses no coordinates, so a sliver
triangle cannot be mislabelled, and edges not on the walk are checked for
agreement, which detects broken noding (a warning is given). Shells are
oriented counter-clockwise and holes clockwise first, the first ring of
each polygon being its shell, so holes are subtracted. The fill rule then
decides which windings count as covered: "nonzero" (any non-zero
winding, so a duplicated part stays covered), "evenodd" (odd winding, so
a duplicated part cancels, as in polymer 0.3.0) or "positive".
Triangles covered by no feature (gaps enclosed by the inputs) are dropped.
The result is the mesh and its index, not a set of polygons. Use
fuse() or layer_n() to get polygons back.
A polymer object, a list with
mesh: a wkpool_tri (see wkpool::new_wkpool_tri()) holding the
triangles on a shared vertex pool. The vertex table has an origin
column: "input" for input vertices and "crossing" for vertices
inserted where input edges cross.
index: a data frame with one row per triangle and covering feature:
triangle (row in mesh), layer (position of the layer in ...) and
feature (row within that layer).
layers: a list with one data frame of attributes per layer (no
geometry).
crs: the coordinate reference system shared by the inputs.
set_id: the covering set of each triangle of mesh, an integer from
1 (in order of first appearance), equal for triangles covered by the same
features. NULL when label = "pip".
pool <- polymer(A, B, C) pool head(pool$index) ## the mesh is a 'wkpool' triangle pool pool$meshpool <- polymer(A, B, C) pool head(pool$index) ## the mesh is a 'wkpool' triangle pool pool$mesh
Print a short summary of a polymer mesh: the number of layers, input features, triangles, crossing vertices and the deepest overlap.
## S3 method for class 'polymer' print(x, ...)## S3 method for class 'polymer' print(x, ...)
x |
A polymer. |
... |
Ignored. |
x, invisibly.
print(polymer(A, B, C))print(polymer(A, B, C))
Give the DE-9IM relation of every pair of input features that meet, across
all layers at once. The relation is read from the mesh by
wkpool::tri_relate(), from the ids of the vertices and triangles that
the features share, so no polygon is built and no coordinates are
compared. Because every layer is in the one triangulation, features of
three or more layers are related in the same pass, which pairwise
tools (such as GEOS, two geometries at a time) cannot do on shared
vertices.
relate(x, cross_layer = TRUE)relate(x, cross_layer = TRUE)
x |
A polymer (see |
cross_layer |
If |
The relation is a nine character string, as from ST_Relate(): how the
interior, boundary and exterior of feature a meet those of feature b
("F" for not at all, or the dimension of the intersection, "0",
"1" or "2"). Named predicates are patterns on that string. For
example, two features overlap in area when the first character is "2",
and touch when it is "F" and they are listed at all.
Pairs that are not listed are disjoint. Features that are covered by no
triangle (empty features) are not listed. The answers are exact for the
mesh, which is the answer for the input polygons when each crossing is
computed exactly; crossings are computed in double precision (see
polymer()).
A data frame with one row for each pair of features that meet and
columns layer_a, feature_a, layer_b, feature_b (the row within
its layer) and relate, the DE-9IM string. Feature a comes from the
earlier layer, or the earlier row within a layer.
pool <- polymer(A, B, C) r <- relate(pool) r ## features of different layers whose interiors overlap in area r[substr(r$relate, 1, 1) == "2", ] ## neighbours within a layer too relate(pool, cross_layer = FALSE)pool <- polymer(A, B, C) r <- relate(pool) r ## features of different layers whose interiors overlap in area r[substr(r$relate, 1, 1) == "2", ] ## neighbours within a layer too relate(pool, cross_layer = FALSE)