// 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 #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; 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 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 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 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; }); // 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 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 &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; } } } // 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. // The hot pixels from `hot` (sorted by y, then x) that are within a pixel of // the bounding box of `geom`, which are the only ones its edges could touch static std::vector> hot_pixels_near(drawvec const &geom, hot_pixel_list const &hot) { std::vector> out; if (geom.size() == 0 || hot.size() == 0) { return out; } long long minx = LLONG_MAX, miny = LLONG_MAX, maxx = LLONG_MIN, maxy = LLONG_MIN; for (auto const &d : geom) { minx = std::min(minx, (long long) d.x); miny = std::min(miny, (long long) d.y); maxx = std::max(maxx, (long long) d.x); maxy = std::max(maxy, (long long) d.y); } for (long long y = miny - 1; y <= maxy + 1; y++) { auto it = std::lower_bound(hot.begin(), hot.end(), std::make_pair(y, minx - 1)); for (; it != hot.end() && it->first == y && it->second <= maxx + 1; ++it) { out.emplace_back(it->second, it->first); } } return out; } static bool wagyu_union(drawvec const &subject, drawvec const *clip, long long scale, drawvec &out, bool require_exact, hot_pixel_list const *hot = NULL) { mapbox::geometry::multi_polygon result; try { mapbox::geometry::wagyu::wagyu 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); } if (hot != NULL && scale == 1) { drawvec both = subject; if (clip != NULL) { both.insert(both.end(), clip->begin(), clip->end()); } std::vector> near = hot_pixels_near(both, *hot); if (near.size() > 0) { wagyu.add_hot_pixels(near); } } 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, hot_pixel_list const *hot) { 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. // (Or, if there is a set of hot pixels to snap to consistently // with other features, at tile resolution with those.) drawvec out; if (hot != NULL) { if (wagyu_union(unioned, NULL, 1, out, false, hot)) { return out; } } else 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; } hot_pixel_list layer_hot_pixels(std::vector const &geoms) { hot_pixel_list out; try { mapbox::geometry::wagyu::wagyu wagyu; for (auto const *g : geoms) { add_rings(wagyu, *g, mapbox::geometry::wagyu::polygon_type_subject, 1); } for (auto const &p : wagyu.hot_pixels()) { out.emplace_back(p.y, p.x); } } catch (std::runtime_error &e) { // Without a consistent set of hot pixels, each feature is // just snapped to its own, as it would otherwise be. out.clear(); } std::sort(out.begin(), out.end()); out.erase(std::unique(out.begin(), out.end()), out.end()); return out; } drawvec clean_polygon_with_hot_pixels(drawvec const &geom, hot_pixel_list const &hot, bool *ok) { drawvec out; *ok = wagyu_union(geom, NULL, 1, out, false, &hot); return out; } namespace { struct directed_edge { long long ax, ay, bx, by; bool operator==(directed_edge const &o) const { return ax == o.ax && ay == o.ay && bx == o.bx && by == o.by; } }; struct directed_edge_hash { size_t operator()(directed_edge const &e) const { size_t h = std::hash()(e.ax); h = h * 1000003 ^ std::hash()(e.ay); h = h * 1000003 ^ std::hash()(e.bx); h = h * 1000003 ^ std::hash()(e.by); return h; } }; template void for_each_edge(drawvec const &geom, F f) { 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; } } for (size_t k = i; k + 1 < j; k++) { if (geom[k].x != geom[k + 1].x || geom[k].y != geom[k + 1].y) { f(directed_edge{geom[k].x, geom[k].y, geom[k + 1].x, geom[k + 1].y}); } } i = j - 1; } } } } // namespace // Whether the point (px, py) is strictly inside the polygon `geom` by the // nonzero winding rule, with exact integer arithmetic. A point exactly on the // polygon's boundary does not count as inside. static bool strictly_inside(drawvec const &geom, long long px, long long py) { int wn = 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; } } for (size_t k = i; k + 1 < j; k++) { long long x1 = geom[k].x, y1 = geom[k].y, x2 = geom[k + 1].x, y2 = geom[k + 1].y; long long cross = (x2 - x1) * (py - y1) - (px - x1) * (y2 - y1); if (cross == 0 && std::min(x1, x2) <= px && px <= std::max(x1, x2) && std::min(y1, y2) <= py && py <= std::max(y1, y2)) { return false; // on the boundary } if (y1 <= py) { if (y2 > py && cross > 0) { wn++; } } else { if (y2 <= py && cross < 0) { wn--; } } } i = j - 1; } } return wn != 0; } size_t remove_overlaps(std::vector const &geoms, hot_pixel_list const *hot) { // Which polygon (the earliest) each directed edge is part of. Cleaned rings // all have their polygon's interior on the same side, so two polygons that // tile exactly traverse the border they share in opposite directions, and // two polygons that share an edge in the same direction both cover the area // beside it. With consistent snapping, edges of different polygons don't // cross, so this is where overlaps between them show up. std::unordered_map owner; std::vector> overlaps(geoms.size()); for (size_t i = 0; i < geoms.size(); i++) { for_each_edge(*geoms[i], [&](directed_edge const &e) { auto found = owner.find(e); if (found == owner.end()) { owner.emplace(e, i); } else if (found->second != i) { std::vector &o = overlaps[i]; if (std::find(o.begin(), o.end(), found->second) == o.end()) { o.push_back(found->second); } } }); } // Where the polygons' boundaries don't share any edges where they overlap, // one of them has a vertex that is strictly inside the other. { const long long cell = 16; std::vector minx(geoms.size()), miny(geoms.size()), maxx(geoms.size()), maxy(geoms.size()); std::unordered_map> grid; auto key = [](long long cx, long long cy) { return (cx << 32) ^ (cy & 0xFFFFFFFF); }; for (size_t i = 0; i < geoms.size(); i++) { minx[i] = miny[i] = LLONG_MAX; maxx[i] = maxy[i] = LLONG_MIN; for (auto const &d : *geoms[i]) { minx[i] = std::min(minx[i], (long long) d.x); miny[i] = std::min(miny[i], (long long) d.y); maxx[i] = std::max(maxx[i], (long long) d.x); maxy[i] = std::max(maxy[i], (long long) d.y); } if (geoms[i]->size() == 0) { continue; } for (long long cx = std::floor(minx[i] / (double) cell); cx <= std::floor(maxx[i] / (double) cell); cx++) { for (long long cy = std::floor(miny[i] / (double) cell); cy <= std::floor(maxy[i] / (double) cell); cy++) { grid[key(cx, cy)].push_back(i); } } } for (size_t i = 0; i < geoms.size(); i++) { for (auto const &d : *geoms[i]) { auto found = grid.find(key(std::floor(d.x / (double) cell), std::floor(d.y / (double) cell))); if (found == grid.end()) { continue; } for (size_t j : found->second) { if (j == i || d.x < minx[j] || d.x > maxx[j] || d.y < miny[j] || d.y > maxy[j]) { continue; } size_t later = std::max(i, j), earlier = std::min(i, j); std::vector &o = overlaps[later]; if (std::find(o.begin(), o.end(), earlier) != o.end()) { continue; } if (strictly_inside(*geoms[j], d.x, d.y)) { o.push_back(earlier); } } } } } size_t changed = 0; for (size_t i = 0; i < geoms.size(); i++) { if (overlaps[i].size() == 0) { continue; } // The polygons have already been snapped, and their edges don't cross, // so the difference doesn't need any new vertices. Snapping them again at // tile resolution could still bend their edges (for example, a 45-degree // edge through the corner of the hot pixel of the vertex beside it) and // collapse parts of them, so do it at a higher resolution, where the // vertices are far from each other's hot pixels, and use the result if // it does only have the original vertices. Otherwise, snap at tile // resolution to the layer's hot pixels, consistently with the rest. drawvec out; bool done = false; for (long long scale : {16LL, 1LL}) { mapbox::geometry::multi_polygon result; try { mapbox::geometry::wagyu::wagyu wagyu; add_rings(wagyu, *geoms[i], mapbox::geometry::wagyu::polygon_type_subject, scale); drawvec all = *geoms[i]; for (size_t earlier : overlaps[i]) { add_rings(wagyu, *geoms[earlier], mapbox::geometry::wagyu::polygon_type_clip, scale); all.insert(all.end(), geoms[earlier]->begin(), geoms[earlier]->end()); } if (scale == 1 && hot != NULL) { std::vector> near = hot_pixels_near(all, *hot); if (near.size() > 0) { wagyu.add_hot_pixels(near); } } wagyu.execute(mapbox::geometry::wagyu::clip_type_difference, result, mapbox::geometry::wagyu::fill_type_positive, mapbox::geometry::wagyu::fill_type_positive); } catch (std::runtime_error &e) { continue; } out.clear(); bool exact = true; for (auto const &poly : result) { for (auto const &ring : poly) { for (size_t k = 0; k < ring.size(); k++) { if (ring[k].x % scale != 0 || ring[k].y % scale != 0) { exact = false; } out.emplace_back(k == 0 ? VT_MOVETO : VT_LINETO, ring[k].x / scale, ring[k].y / scale); } if (ring.size() > 0 && (ring.front().x != ring.back().x || ring.front().y != ring.back().y)) { out.emplace_back(VT_LINETO, ring.front().x / scale, ring.front().y / scale); } } } if (exact) { done = true; break; } } if (done) { *geoms[i] = std::move(out); changed++; } } return changed; }