Files
tippecanoe/polygon.cpp
T
Claude 4f64526ab4 With -pn, let neighbors close over polygons that collapse entirely
A polygon that collapses away entirely is replaced by its outline, but with
--no-simplification-of-shared-nodes that outline overlaps the neighboring
features along every shared border, and those features already cover the
space. So leave the shared borders out of the outline, as the spindle strips
already do, and if every border is shared, leave the polygon out entirely
instead of falling back to a rectangle.

For Dane County Census blocks at -D8 -d8 -pt -pn, this reduces the
overlapping pixels in tile 12/1031/1503 from 141 to 11 and in 11/515/751
from 915 to 38, and the number of revived rectangles at z8 from 6307 to
1414, at the cost of a few more one-pixel gaps (7 to 10 and 14 to 23) where
a block of less than a pixel is left out and its neighbors' borders don't
round to the same line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQ6vQUJtmGZnqz7RmVYQaJ
2026-11-30 23:03:40 +00:00

601 lines
20 KiB
C++

// Preservation of "spindle" polygons: polygons, or parts of polygons, that are
// narrower than one tile pixel, like a 1-meter buffer around a long linestring.
//
// When such a polygon is scaled down to tile coordinates, the two sides of the
// spindle round to the same or adjacent pixel rows more or less at random, so after
// polygon cleaning the feature usually collapses away to nothing in most places
// while surviving as disconnected fragments wherever the rounding happens to keep
// the two sides apart.
//
// The approach here is to look at the feature in unrounded tile coordinates,
// before it is rounded, to find the edges of each ring that have another,
// oppositely-directed edge less than a pixel away, which is also not just the
// other side of a corner. Those are the edges that are at risk of collapsing.
// For each of them, we construct a "strip" polygon one pixel wide, one side
// of which is the edge as it will be rounded, and the other side of which is
// offset by one pixel toward the inside of the polygon. The strips are then
// unioned with the normally-cleaned polygon, so the narrow parts of the feature
// come out as a continuous line of polygon one (or sometimes two) pixels thick
// instead of disappearing.
//
// Where the polygon is already at least a pixel thick, the strips lie entirely
// within it and do not change the result, so they cost only some time in the
// union, and only for features that have narrow parts.
#include <cmath>
#include <climits>
#include <algorithm>
#include <vector>
#include <tuple>
#include <mapbox/geometry/point.hpp>
#include <mapbox/geometry/multi_polygon.hpp>
#include <mapbox/geometry/wagyu/wagyu.hpp>
#include "geometry.hpp"
#include "errors.hpp"
#include "polygon.hpp"
// Boundaries closer together than this (in tile pixels) may collapse
// when they are rounded to integer tile coordinates, since rounding can
// move each vertex by up to half a pixel in each dimension
static const double THIN_DISTANCE = M_SQRT2;
// Nearby boundaries are only considered to enclose a narrow part of the polygon
// if they are at least this far apart (in tile pixels) along the ring, so that
// ordinary corners do not count.
static const double MIN_ALONG_RING = 4 * THIN_DISTANCE;
// Spacing, in tile pixels, of the points along an edge that are checked
// for being close to a nearby edge
static const double SAMPLE_SPACING = 1.0;
shared_edge *shared_edges_map = NULL;
size_t shared_edges_count = 0;
namespace {
struct fedge {
double x1, y1, x2, y2; // unrounded tile coordinates
long long wx1, wy1, wx2, wy2; // world coordinates, relative to the tile origin
size_t ring; // which ring the edge is part of
double arc; // distance along the ring to the start of the edge
double len; // length of the edge
double minx, miny, maxx, maxy;
bool thin = false; // within THIN_DISTANCE of some other edge
bool crosses_shared = false; // and that other edge is shared with another feature
int shared = -1; // is this edge shared with another feature? -1 if not yet known
};
double point_segment_distance_sq(double px, double py, fedge const &e, double &t) {
double dx = e.x2 - e.x1;
double dy = e.y2 - e.y1;
double len_sq = dx * dx + dy * dy;
t = 0;
if (len_sq > 0) {
t = ((px - e.x1) * dx + (py - e.y1) * dy) / len_sq;
t = std::max(0.0, std::min(1.0, t));
}
double cx = e.x1 + t * dx - px;
double cy = e.y1 + t * dy - py;
return cx * cx + cy * cy;
}
double cross(double ox, double oy, double ax, double ay, double bx, double by) {
return (ax - ox) * (by - oy) - (ay - oy) * (bx - ox);
}
double segment_distance_sq(fedge const &a, fedge const &b) {
double c1 = cross(a.x1, a.y1, a.x2, a.y2, b.x1, b.y1);
double c2 = cross(a.x1, a.y1, a.x2, a.y2, b.x2, b.y2);
double c3 = cross(b.x1, b.y1, b.x2, b.y2, a.x1, a.y1);
double c4 = cross(b.x1, b.y1, b.x2, b.y2, a.x2, a.y2);
if (((c1 > 0 && c2 < 0) || (c1 < 0 && c2 > 0)) &&
((c3 > 0 && c4 < 0) || (c3 < 0 && c4 > 0))) {
return 0; // they cross
}
double t;
double d = point_segment_distance_sq(a.x1, a.y1, b, t);
d = std::min(d, point_segment_distance_sq(a.x2, a.y2, b, t));
d = std::min(d, point_segment_distance_sq(b.x1, b.y1, a, t));
d = std::min(d, point_segment_distance_sq(b.x2, b.y2, a, t));
return d;
}
// Is some part of edge `e` within THIN_DISTANCE of edge `f`
// at a place that is not just the other side of a corner?
bool close_along(fedge const &e, fedge const &f, std::vector<double> const &ring_perimeters) {
// Only look at the part of `e` that is within reach of `f`'s bounding box
double t0 = 0, t1 = 1;
double dx = e.x2 - e.x1;
double dy = e.y2 - e.y1;
auto restrict = [&](double p, double dp, double lo, double hi) {
if (dp == 0) {
if (p < lo || p > hi) {
t0 = 1;
t1 = 0;
}
} else {
double a = (lo - p) / dp;
double b = (hi - p) / dp;
if (a > b) {
std::swap(a, b);
}
t0 = std::max(t0, a);
t1 = std::min(t1, b);
}
};
restrict(e.x1, dx, f.minx - THIN_DISTANCE, f.maxx + THIN_DISTANCE);
restrict(e.y1, dy, f.miny - THIN_DISTANCE, f.maxy + THIN_DISTANCE);
if (t0 > t1) {
return false;
}
double span = (t1 - t0) * e.len;
size_t samples = std::ceil(span / SAMPLE_SPACING) + 1;
const double thin_sq = THIN_DISTANCE * THIN_DISTANCE;
for (size_t s = 0; s < samples; s++) {
double t = samples == 1 ? (t0 + t1) / 2 : t0 + (t1 - t0) * s / (samples - 1);
double px = e.x1 + dx * t;
double py = e.y1 + dy * t;
double u;
if (point_segment_distance_sq(px, py, f, u) < thin_sq) {
if (e.ring != f.ring) {
return true;
}
// The other boundary is nearby in space. But is it also far away
// along the ring? If not, it is just the other side of a corner,
// not the other side of a narrow part of the polygon.
double here = e.arc + e.len * t;
double there = f.arc + f.len * u;
double along = std::fabs(here - there);
along = std::min(along, ring_perimeters[e.ring] - along);
if (along >= MIN_ALONG_RING) {
return true;
}
}
}
return false;
}
// Make a strip polygon one pixel wide along the edge from (x1,y1) to (x2,y2),
// in world coordinates. One side of the strip is the edge as it will be rounded
// to tile coordinates, so where the polygon is already at least a pixel thick
// the strip lies entirely within it and adds nothing. The other side is offset
// by one pixel (along whichever axis is closer to perpendicular to the edge)
// toward the side of the edge where the polygon is, which is always the left
// for correctly-wound rings.
void add_strip(drawvec &out, long long x1, long long y1, long long x2, long long y2, int shift) {
long long ax = std::llround((double) x1 / (1LL << shift));
long long ay = std::llround((double) y1 / (1LL << shift));
long long bx = std::llround((double) x2 / (1LL << shift));
long long by = std::llround((double) y2 / (1LL << shift));
long long dx = bx - ax;
long long dy = by - ay;
if (dx == 0 && dy == 0) {
return;
}
long long ox, oy;
if (std::llabs(dx) >= std::llabs(dy)) {
ox = 0;
oy = dx > 0 ? 1 : -1;
} else {
ox = dy > 0 ? -1 : 1;
oy = 0;
}
drawvec ring;
ring.emplace_back(VT_MOVETO, ax, ay);
ring.emplace_back(VT_LINETO, bx, by);
ring.emplace_back(VT_LINETO, bx + ox, by + oy);
ring.emplace_back(VT_LINETO, ax + ox, ay + oy);
ring.emplace_back(VT_LINETO, ax, ay);
// orient it as an outer ring
if (get_area(ring, 0, ring.size()) < 0) {
std::reverse(ring.begin(), ring.end());
ring[0].op = VT_MOVETO;
ring[ring.size() - 1].op = VT_LINETO;
}
for (auto const &d : ring) {
out.push_back(d);
}
}
// Is there an edge shared with another feature that starts at (ax, ay)
// and runs in the direction of (bx, by)? After simplification, the other end
// of the shared edge may no longer be in the geometry, but it must lie within
// the simplification tolerance of this edge.
bool shared_toward(long long ax, long long ay, long long bx, long long by, double tolerance) {
if (shared_edges_count == 0) {
return false;
}
auto first = std::lower_bound(shared_edges_map, shared_edges_map + shared_edges_count, std::make_pair(ay, ax),
[](shared_edge const &se, std::pair<long long, long long> const &p) {
return se.ay < p.first || (se.ay == p.first && se.ax < p.second);
});
double dx = bx - ax;
double dy = by - ay;
double len = std::hypot(dx, dy);
if (len == 0) {
return false;
}
for (auto it = first; it != shared_edges_map + shared_edges_count && it->ay == ay && it->ax == ax; ++it) {
double qx = it->bx - ax;
double qy = it->by - ay;
// how far along this edge, and how far off to the side of it, is the other end?
double along = (qx * dx + qy * dy) / len;
double off = std::fabs(qx * dy - qy * dx) / len;
if (along > 0 && off <= tolerance) {
return true;
}
}
return false;
}
// Is this edge (or what is left of it after simplification) shared with another feature?
bool is_shared(fedge &e, double tolerance, long long ox, long long oy) {
if (shared_edges_count == 0) {
return false;
}
if (e.shared < 0) {
e.shared = shared_toward(e.wx1 + ox, e.wy1 + oy, e.wx2 + ox, e.wy2 + oy, tolerance) ||
shared_toward(e.wx2 + ox, e.wy2 + oy, e.wx1 + ox, e.wy1 + oy, tolerance);
}
return e.shared;
}
} // namespace
drawvec thin_polygon_strips(drawvec const &geom, int z, int detail, double simplification, long long ox, long long oy) {
drawvec out;
int shift = 32 - detail - z;
if (shift <= 0) {
// tile coordinates are at least as precise as world coordinates,
// so scaling cannot make anything collapse
return out;
}
double scale = 1LL << shift;
// Decompose the rings into edges, in unrounded tile coordinates
std::vector<fedge> edges;
std::vector<double> ring_perimeters;
for (size_t i = 0; i < geom.size(); i++) {
if (geom[i].op == VT_MOVETO) {
size_t j;
for (j = i + 1; j < geom.size(); j++) {
if (geom[j].op != VT_LINETO) {
break;
}
}
if (j - i >= 3) {
double arc = 0;
for (size_t k = i; k < j; k++) {
size_t n = (k + 1 < j) ? k + 1 : i; // close the ring if it isn't already
if (geom[k].x != geom[n].x || geom[k].y != geom[n].y) {
fedge ed;
ed.x1 = geom[k].x / scale;
ed.y1 = geom[k].y / scale;
ed.x2 = geom[n].x / scale;
ed.y2 = geom[n].y / scale;
ed.wx1 = geom[k].x;
ed.wy1 = geom[k].y;
ed.wx2 = geom[n].x;
ed.wy2 = geom[n].y;
ed.ring = ring_perimeters.size();
ed.arc = arc;
ed.len = std::hypot(ed.x2 - ed.x1, ed.y2 - ed.y1);
ed.minx = std::min(ed.x1, ed.x2);
ed.miny = std::min(ed.y1, ed.y2);
ed.maxx = std::max(ed.x1, ed.x2);
ed.maxy = std::max(ed.y1, ed.y2);
edges.push_back(ed);
arc += ed.len;
}
}
ring_perimeters.push_back(arc);
}
i = j - 1;
}
}
if (edges.size() < 2) {
return out;
}
// Sweep down through the edges in order of their tops to find pairs
// of edges whose bounding boxes come within THIN_DISTANCE of each other.
std::vector<size_t> order(edges.size());
for (size_t i = 0; i < order.size(); i++) {
order[i] = i;
}
std::sort(order.begin(), order.end(), [&](size_t a, size_t b) {
return edges[a].miny < edges[b].miny;
});
// How far a simplified shared border may have strayed from the original shared edges
const double tolerance = (1 + std::max(simplification, 0.0)) * scale;
std::vector<size_t> active;
const double thin_sq = THIN_DISTANCE * THIN_DISTANCE;
bool any = false;
for (size_t oi = 0; oi < order.size(); oi++) {
size_t ei = order[oi];
fedge &e = edges[ei];
size_t keep = 0;
for (size_t ai = 0; ai < active.size(); ai++) {
size_t fi = active[ai];
fedge &f = edges[fi];
if (f.maxy + THIN_DISTANCE < e.miny) {
continue; // f is entirely above anything that remains; retire it
}
active[keep++] = fi;
// Once both edges are known to be thin (and, if there are shared
// edges, to need no strip anyway), there is nothing more to learn.
if (e.thin && f.thin && (shared_edges_count == 0 || (e.crosses_shared && f.crosses_shared))) {
continue;
}
if (f.maxx + THIN_DISTANCE < e.minx || e.maxx + THIN_DISTANCE < f.minx) {
continue;
}
// Only boundaries that run in opposite directions enclose a
// narrow stretch of polygon (or of hole) between them.
// Boundaries running in the same direction are just
// consecutive edges, or nearby parallel features.
double edx = e.x2 - e.x1, edy = e.y2 - e.y1;
double fdx = f.x2 - f.x1, fdy = f.y2 - f.y1;
if (edx * fdx + edy * fdy >= 0) {
continue;
}
// Clipping to the tile boundary (Sutherland-Hodgman) leaves
// zero-width bridges that run out along the clip line and back.
// Those are not real parts of the polygon, so don't revive them.
if ((e.y1 == e.y2 && f.y1 == f.y2 && e.y1 == f.y1) ||
(e.x1 == e.x2 && f.x1 == f.x2 && e.x1 == f.x1)) {
continue;
}
if (segment_distance_sq(e, f) >= thin_sq) {
continue;
}
// A strip along `e` would extend past `f`, so if `f` is an edge
// shared with another feature, the strip would overlap that feature.
if ((!e.thin || (shared_edges_count > 0 && !e.crosses_shared)) && close_along(e, f, ring_perimeters)) {
e.thin = true;
any = true;
if (is_shared(f, tolerance, ox, oy)) {
e.crosses_shared = true;
}
}
if ((!f.thin || (shared_edges_count > 0 && !f.crosses_shared)) && close_along(f, e, ring_perimeters)) {
f.thin = true;
any = true;
if (is_shared(e, tolerance, ox, oy)) {
f.crosses_shared = true;
}
}
}
active.resize(keep);
active.push_back(ei);
}
if (!any) {
return out;
}
// A narrow part whose far side is an edge shared with another feature,
// like a panhandle between two neighboring political units, is left to
// collapse, so that the features still tile exactly instead of overlapping.
for (auto const &e : edges) {
if (e.thin && !e.crosses_shared) {
add_strip(out, e.wx1, e.wy1, e.wx2, e.wy2, shift);
}
}
return out;
}
drawvec outline_strips(drawvec const &geom, int z, int detail, double simplification, long long ox, long long oy, bool *all_shared) {
drawvec out;
*all_shared = false;
int shift = 32 - detail - z;
if (shift <= 0) {
return out;
}
// How far a simplified shared border may have strayed from the original shared edges
const double tolerance = (1 + std::max(simplification, 0.0)) * (1LL << shift);
size_t edges = 0, shared = 0;
for (size_t i = 0; i < geom.size(); i++) {
if (geom[i].op == VT_MOVETO) {
size_t j;
for (j = i + 1; j < geom.size(); j++) {
if (geom[j].op != VT_LINETO) {
break;
}
}
if (j - i >= 3) {
for (size_t k = i; k < j; k++) {
size_t n = (k + 1 < j) ? k + 1 : i; // close the ring if it isn't already
if (geom[k].x == geom[n].x && geom[k].y == geom[n].y) {
continue;
}
edges++;
// Along a border shared with another feature, that feature
// already covers the space, so leave it to close over it.
if (shared_edges_count > 0 &&
(shared_toward(geom[k].x + ox, geom[k].y + oy, geom[n].x + ox, geom[n].y + oy, tolerance) ||
shared_toward(geom[n].x + ox, geom[n].y + oy, geom[k].x + ox, geom[k].y + oy, tolerance))) {
shared++;
continue;
}
add_strip(out, geom[k].x, geom[k].y, geom[n].x, geom[n].y, shift);
}
}
i = j - 1;
}
}
*all_shared = edges > 0 && shared == edges;
return out;
}
double unshared_perimeter(drawvec const &geom, size_t i, size_t j, long long ox, long long oy) {
double perimeter = 0;
for (size_t k = i; k + 1 < j; k++) {
long long ax = geom[k].x + ox, ay = geom[k].y + oy;
long long bx = geom[k + 1].x + ox, by = geom[k + 1].y + oy;
if (shared_edges_count > 0) {
auto first = std::lower_bound(shared_edges_map, shared_edges_map + shared_edges_count, shared_edge{ax, ay, bx, by},
[](shared_edge const &a, shared_edge const &b) {
return std::make_tuple(a.ay, a.ax, a.by, a.bx) < std::make_tuple(b.ay, b.ax, b.by, b.bx);
});
if (first != shared_edges_map + shared_edges_count &&
first->ax == ax && first->ay == ay && first->bx == bx && first->by == by) {
continue;
}
}
perimeter += std::hypot((double) bx - ax, (double) by - ay);
}
return perimeter;
}
static void add_rings(mapbox::geometry::wagyu::wagyu<long long> &wagyu, drawvec const &geom, mapbox::geometry::wagyu::polygon_type type, long long scale) {
for (size_t i = 0; i < geom.size(); i++) {
if (geom[i].op == VT_MOVETO) {
size_t j;
for (j = i + 1; j < geom.size(); j++) {
if (geom[j].op != VT_LINETO) {
break;
}
}
if (j >= i + 4) {
mapbox::geometry::linear_ring<long long> lr;
for (size_t k = i; k < j; k++) {
lr.push_back(mapbox::geometry::point<long long>(geom[k].x * scale, geom[k].y * scale));
}
wagyu.add_ring(lr, type);
}
i = j - 1;
}
}
}
// Run wagyu on `subject` (positive fill) and optionally `clip` (non-zero fill),
// at `scale` times tile resolution, and round the result back to tile resolution.
// Returns false, rather than exiting, if wagyu fails, since the callers have
// a valid polygon to fall back on.
static bool wagyu_union(drawvec const &subject, drawvec const *clip, long long scale, drawvec &out, bool require_exact) {
mapbox::geometry::multi_polygon<long long> result;
try {
mapbox::geometry::wagyu::wagyu<long long> wagyu;
add_rings(wagyu, subject, mapbox::geometry::wagyu::polygon_type_subject, scale);
if (clip != NULL) {
add_rings(wagyu, *clip, mapbox::geometry::wagyu::polygon_type_clip, scale);
}
wagyu.execute(mapbox::geometry::wagyu::clip_type_union, result, mapbox::geometry::wagyu::fill_type_positive, mapbox::geometry::wagyu::fill_type_non_zero);
} catch (std::runtime_error &e) {
return false;
}
out.clear();
for (auto const &poly : result) {
for (auto const &ring : poly) {
for (size_t k = 0; k < ring.size(); k++) {
if (require_exact && (ring[k].x % scale != 0 || ring[k].y % scale != 0)) {
return false;
}
out.emplace_back(k == 0 ? VT_MOVETO : VT_LINETO, std::llround(ring[k].x / (double) scale), std::llround(ring[k].y / (double) scale));
}
if (ring.size() > 0 && (ring.front().x != ring.back().x || ring.front().y != ring.back().y)) {
out.emplace_back(VT_LINETO, std::llround(ring.front().x / (double) scale), std::llround(ring.front().y / (double) scale));
}
}
}
return true;
}
drawvec union_polygon_strips(drawvec const &geom, drawvec const &strips) {
if (strips.size() == 0) {
return geom;
}
// The strips from the two sides of a spindle are nearly coincident,
// and cross each other at very shallow angles. If the union were done
// at tile resolution, rounding the intersections to integer coordinates
// would make the strips collapse in places, which is the very problem
// they are trying to solve. So do the union at a higher resolution,
// and then clean the result again at tile resolution.
//
// The cleaned polygon uses the positive fill rule as usual, but the strips
// use non-zero so that overlapping strips can never cancel each other out.
//
// Wagyu can fail on some of these unions ("Trying to find intersection
// of lines that do not intersect"), depending on platform floating point
// details like fused multiply-add. The strips are only an improvement on
// an already-valid polygon, so if it fails, try again at tile resolution,
// and if that fails too, give up on the strips for this feature.
drawvec unioned;
if (!wagyu_union(geom, &strips, 16, unioned, false)) {
if (!wagyu_union(geom, &strips, 1, unioned, false)) {
return geom;
}
return unioned;
}
// Clean the rounded union at tile resolution, the same way
// clean_or_clip_poly() would, but without exiting on failure.
drawvec out;
if (wagyu_union(unioned, NULL, 16, out, true)) {
return out;
}
if (wagyu_union(unioned, NULL, 1, out, false)) {
return out;
}
if (wagyu_union(geom, &strips, 1, out, false)) {
return out;
}
return geom;
}