// 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 #include #include #include #include #include #include #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; namespace { struct fedge { double x1, y1, x2, y2; // unrounded tile coordinates long long wx1, wy1, wx2, wy2; // world coordinates 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; }; 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 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); } } } // namespace drawvec thin_polygon_strips(drawvec const &geom, int z, int detail) { 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 edges; std::vector 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 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; }); std::vector 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; if (e.thin && f.thin) { 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; } if (!e.thin && close_along(e, f, ring_perimeters)) { e.thin = true; any = true; } if (!f.thin && close_along(f, e, ring_perimeters)) { f.thin = true; any = true; } } active.resize(keep); active.push_back(ei); } if (!any) { return out; } for (auto const &e : edges) { if (e.thin) { add_strip(out, e.wx1, e.wy1, e.wx2, e.wy2, shift); } } return out; } static void add_rings(mapbox::geometry::wagyu::wagyu &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 lr; for (size_t k = i; k < j; k++) { lr.push_back(mapbox::geometry::point(geom[k].x * scale, geom[k].y * scale)); } wagyu.add_ring(lr, type); } i = j - 1; } } } 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. const long long scale = 16; mapbox::geometry::multi_polygon result; mapbox::geometry::wagyu::wagyu wagyu; // 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. add_rings(wagyu, geom, mapbox::geometry::wagyu::polygon_type_subject, scale); add_rings(wagyu, strips, mapbox::geometry::wagyu::polygon_type_clip, scale); try { 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) { fprintf(stderr, "Internal error: Polygon spindle union failed: %s\n", e.what()); exit(EXIT_IMPOSSIBLE); } drawvec out; for (auto const &poly : result) { for (auto const &ring : poly) { for (size_t k = 0; k < ring.size(); k++) { 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 clean_or_clip_poly(out, 0, 0, false, true); }