Files
tippecanoe/unit.cpp
T
Claude 4d761d4307 Don't snap polygons a second time when removing overlaps
Removing the area that a polygon shares with an earlier polygon ran wagyu on
geometry that had already been snapped to tile coordinates, and snapping it
again could change it. In Dane County tile 8/64/93, consistent snapping bent
one block's edge into a 45-degree diagonal that left it a half-pixel
triangle, and when that block's overlap with another block was removed, the
diagonal passed through the corner of the hot pixel of the vertex beside it,
so it was snapped again and the triangle collapsed, leaving a hole between
it and its neighbor. Elsewhere in the same tile, two half-pixel overlaps
were left behind the same way.

The polygons' edges no longer cross after consistent snapping, so the
difference needs no new vertices. So compute it at 16 times the tile
resolution, where the vertices are far from each other's hot pixels, and use
the result if all of its vertices are the original ones. Only if they aren't,
fall back to snapping at tile resolution to the layer's hot pixels.

For Dane County at -D8 -d8 -pt -pn -zg, this reduces the overlapping
pixels at z8, z9, and z10 from 7, 8, and 16 to 5, 3, and 3, and removes the
hole and both overlaps in 8/64/93 at -z8.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CQ6vQUJtmGZnqz7RmVYQaJ
2026-12-01 02:13:36 +00:00

979 lines
36 KiB
C++

#define CATCH_CONFIG_MAIN
#include "catch/catch.hpp"
#include "text.hpp"
#include "sort.hpp"
#include "tile-cache.hpp"
#include "mvt.hpp"
#include "projection.hpp"
#include "geometry.hpp"
#include "polygon.hpp"
#include "jsonpull/jsonpull.h"
#include <unistd.h>
#include <limits.h>
#include <tuple>
#include <algorithm>
#include <sstream>
TEST_CASE("UTF-8 enforcement", "[utf8]") {
REQUIRE(check_utf8("") == std::string(""));
REQUIRE(check_utf8("hello world") == std::string(""));
REQUIRE(check_utf8("Καλημέρα κόσμε") == std::string(""));
REQUIRE(check_utf8("こんにちは 世界") == std::string(""));
REQUIRE(check_utf8("👋🌏") == std::string(""));
REQUIRE(check_utf8("Hola m\xF3n") == std::string("\"Hola m\xF3n\" is not valid UTF-8 (0xF3 0x6E)"));
}
TEST_CASE("UTF-8 truncation", "[trunc]") {
REQUIRE(truncate16("0123456789abcdefghi", 16) == std::string("0123456789abcdef"));
REQUIRE(truncate16("0123456789éîôüéîôüç", 16) == std::string("0123456789éîôüéî"));
REQUIRE(truncate16("0123456789😀😬😁😂😃😄😅😆", 16) == std::string("0123456789😀😬😁"));
REQUIRE(truncate16("0123456789😀😬😁😂😃😄😅😆", 17) == std::string("0123456789😀😬😁"));
REQUIRE(truncate16("0123456789あいうえおかきくけこさ", 16) == std::string("0123456789あいうえおか"));
REQUIRE(truncate_string("789éîôüéîôüç", 3) == std::string("789"));
REQUIRE(truncate_string("789éîôüéîôüç", 4) == std::string("789"));
REQUIRE(truncate_string("789éîôüéîôüç", 5) == std::string("789é"));
REQUIRE(truncate_string("789éîôüéîôüç", 6) == std::string("789é"));
REQUIRE(truncate_string("789éîôüéîôüç", 7) == std::string("789éî"));
REQUIRE(truncate_string("789éîôüéîôüç", 8) == std::string("789éî"));
REQUIRE(truncate_string("0123456789😀😬😁😂😃😄😅😆", 10) == std::string("0123456789"));
REQUIRE(truncate_string("0123456789😀😬😁😂😃😄😅😆", 11) == std::string("0123456789"));
REQUIRE(truncate_string("0123456789😀😬😁😂😃😄😅😆", 12) == std::string("0123456789"));
REQUIRE(truncate_string("0123456789😀😬😁😂😃😄😅😆", 13) == std::string("0123456789"));
REQUIRE(truncate_string("0123456789😀😬😁😂😃😄😅😆", 14) == std::string("0123456789😀"));
REQUIRE(truncate_string("😀", 4) == std::string("😀"));
REQUIRE(truncate_string("😀", 3) == std::string(""));
REQUIRE(truncate_string("😀", 2) == std::string(""));
REQUIRE(truncate_string("😀", 1) == std::string(""));
REQUIRE(truncate_string("😀", 0) == std::string(""));
}
int intcmp(const void *v1, const void *v2) {
return *((int *) v1) - *((int *) v2);
}
TEST_CASE("External quicksort", "fqsort") {
std::vector<FILE *> inputs;
size_t written = 0;
for (size_t i = 0; i < 5; i++) {
std::string tmpname = "/tmp/in.XXXXXXX";
int fd = mkstemp((char *) tmpname.c_str());
unlink(tmpname.c_str());
FILE *f = fdopen(fd, "w+b");
inputs.emplace_back(f);
size_t iterations = 2000 + rand() % 200;
for (size_t j = 0; j < iterations; j++) {
int n = rand();
fwrite((void *) &n, sizeof(int), 1, f);
written++;
}
rewind(f);
}
std::string tmpname = "/tmp/out.XXXXXX";
int fd = mkstemp((char *) tmpname.c_str());
unlink(tmpname.c_str());
FILE *f = fdopen(fd, "w+b");
fqsort(inputs, sizeof(int), intcmp, f, 256, "/tmp");
rewind(f);
int prev = INT_MIN;
int here;
size_t nread = 0;
while (fread((void *) &here, sizeof(int), 1, f)) {
REQUIRE(here >= prev);
prev = here;
nread++;
}
fclose(f);
REQUIRE(nread == written);
}
mvt_tile mock_get_tile(zxy tile) {
mvt_layer l;
l.name = std::to_string(tile.z) + "/" + std::to_string(tile.x) + "/" + std::to_string(tile.y);
mvt_tile t;
t.layers.push_back(l);
return t;
}
TEST_CASE("Tile-join cache", "tile cache") {
tile_cache tc;
tc.capacity = 5;
REQUIRE(tc.get(zxy(11, 327, 791), mock_get_tile).layers[0].name == "11/327/791");
REQUIRE(tc.get(zxy(11, 5, 7), mock_get_tile).layers[0].name == "11/5/7");
REQUIRE(tc.get(zxy(11, 5, 8), mock_get_tile).layers[0].name == "11/5/8");
REQUIRE(tc.get(zxy(11, 5, 9), mock_get_tile).layers[0].name == "11/5/9");
REQUIRE(tc.get(zxy(11, 5, 10), mock_get_tile).layers[0].name == "11/5/10");
REQUIRE(tc.get(zxy(11, 327, 791), mock_get_tile).layers[0].name == "11/327/791");
REQUIRE(tc.overzoom_cache.size() == 5);
REQUIRE(tc.overzoom_cache.find(zxy(11, 327, 791)) != tc.overzoom_cache.end());
REQUIRE(tc.overzoom_cache.find(zxy(11, 5, 7)) != tc.overzoom_cache.end());
// verify that additional gets evict the least-recently-used elements
REQUIRE(tc.get(zxy(11, 5, 11), mock_get_tile).layers[0].name == "11/5/11");
REQUIRE(tc.overzoom_cache.size() == 5);
REQUIRE(tc.overzoom_cache.find(zxy(11, 5, 7)) == tc.overzoom_cache.end());
REQUIRE(tc.get(zxy(11, 5, 12), mock_get_tile).layers[0].name == "11/5/12");
REQUIRE(tc.overzoom_cache.size() == 5);
REQUIRE(tc.overzoom_cache.find(zxy(11, 5, 8)) == tc.overzoom_cache.end());
}
TEST_CASE("Bit reversal", "bit reversal") {
REQUIRE(bit_reverse(1) == 0x8000000000000000);
REQUIRE(bit_reverse(0x1234567812489BCF) == 0xF3D912481E6A2C48);
REQUIRE(bit_reverse(0xF3D912481E6A2C48) == 0x1234567812489BCF);
}
TEST_CASE("line_is_too_small") {
drawvec dv;
dv.emplace_back(VT_MOVETO, 4243099709, 2683872952);
dv.emplace_back(VT_LINETO, 4243102487, 2683873977);
dv.emplace_back(VT_MOVETO, -51867587, 2683872952);
dv.emplace_back(VT_LINETO, -51864809, 2683873977);
REQUIRE(line_is_too_small(dv, 0, 10));
}
// A high surrogate followed by a non-surrogate used to be combined into one
// code point, because the range check tested the outer-loop byte instead of
// the parsed code unit. The stale surrogate should come out as standalone
// CESU-8, then U+E000 encoded normally.
TEST_CASE("jsonpull surrogate-pair regression", "[jsonpull][surrogate]") {
json_pull_ptr jp = json_begin_string("\"\\uD83D\\uE000\"");
json_object_ptr o = json_read_tree(jp);
REQUIRE(jp->error == nullptr);
REQUIRE(o != nullptr);
REQUIRE(o->type == JSON_STRING);
const std::string expected = "\xED\xA0\xBD\xEE\x80\x80";
REQUIRE(o->string() == expected);
// Sanity check: the buggy output (a single 4-byte UTF-8 sequence for
// U+1F400) must not be what we got.
const std::string buggy = "\xF0\x9F\x90\x80";
REQUIRE(o->string() != buggy);
}
// What geojson-loop does: free each feature once serialized, so they do not
// accumulate while the rest of the document is parsed.
//
// This shape cannot catch the array-splicing bug, at any size: json_read hands
// back each container as it completes, so the node freed here is always the
// last-added element of its parent, which the old memmove got right by moving
// zero bytes. "json_free prunes a non-final element" below covers that.
TEST_CASE("json_free prunes a subtree from its parent", "[jsonpull][memory]") {
json_pull_ptr jp = json_begin_string("[[1, 2], [3, 4], [5, 6]]");
json_object *outer = nullptr;
int arrays_seen = 0;
json_object *j;
while ((j = json_read(jp)) != nullptr) {
if (j->type != JSON_ARRAY) {
continue;
}
arrays_seen++;
if (arrays_seen == 2) {
// This is [3, 4]; verify, then ask the parser to drop it.
REQUIRE(j->array().size() == 2);
REQUIRE(j->array()[0]->number() == 3);
REQUIRE(j->array()[1]->number() == 4);
json_free(j);
} else if (j->parent == nullptr) {
// The completed outer array; the parser still owns it
// via jp->root, so the borrowed pointer stays valid.
outer = j;
break;
}
}
REQUIRE(outer != nullptr);
REQUIRE(outer->type == JSON_ARRAY);
REQUIRE(outer->array().size() == 2);
// First surviving element: [1, 2].
REQUIRE(outer->array()[0]->type == JSON_ARRAY);
REQUIRE(outer->array()[0]->array().size() == 2);
REQUIRE(outer->array()[0]->array()[0]->number() == 1);
REQUIRE(outer->array()[0]->array()[1]->number() == 2);
// Second surviving element (previously third): [5, 6].
REQUIRE(outer->array()[1]->type == JSON_ARRAY);
REQUIRE(outer->array()[1]->array().size() == 2);
REQUIRE(outer->array()[1]->array()[0]->number() == 5);
REQUIRE(outer->array()[1]->array()[1]->number() == 6);
}
// A top-level value has no parent, so json_free has to drop the parser's
// reference instead. jp->root being empty afterwards is also proof the subtree
// was destroyed, since jp->root was its only owner.
TEST_CASE("json_free releases a top-level value held by the parser", "[jsonpull][memory]") {
json_pull_ptr jp = json_begin_string(R"({"a": 1, "b": [2, 3]})");
// json_read streams atoms first (1, 2, 3, [2,3], ...); the top-level
// hash is returned by the final `}` token.
json_object *top = nullptr;
json_object *j;
while ((j = json_read(jp)) != nullptr) {
if (j->parent == nullptr) {
top = j;
break;
}
}
REQUIRE(top != nullptr);
REQUIRE(top->type == JSON_HASH);
REQUIRE(jp->root.get() == top);
json_free(top);
// top is dangling now; do not dereference.
REQUIRE(jp->root == nullptr);
}
// Nothing in tippecanoe calls json_disconnect today -- the filter loaders get
// the same guarantee from json_read_tree -- so cover it here rather than leave
// a documented ownership primitive untested.
TEST_CASE("json_disconnect hands a subtree to the caller", "[jsonpull][ownership]") {
json_object_ptr taken;
json_object *outer = nullptr;
json_pull_ptr jp = json_begin_string("[[1, 2], [3, 4]]");
int arrays_seen = 0;
json_object *j;
while ((j = json_read(jp)) != nullptr) {
if (j->type != JSON_ARRAY) {
continue;
}
arrays_seen++;
if (arrays_seen == 2) {
// This is [3, 4]; take it away from the enclosing array.
taken = json_disconnect(j);
REQUIRE(taken != nullptr);
REQUIRE(taken.get() == j);
} else if (j->parent == nullptr) {
outer = j;
break;
}
}
// The outer array is left holding only the element we didn't take,
// and the parser is still the owner of it.
REQUIRE(outer != nullptr);
REQUIRE(jp->root.get() == outer);
REQUIRE(outer->array().size() == 1);
REQUIRE(outer->array()[0]->array().size() == 2);
REQUIRE(outer->array()[0]->array()[0]->number() == 1);
REQUIRE(outer->array()[0]->array()[1]->number() == 2);
// The detached subtree holds no pointers into the parser...
REQUIRE(taken->parser == nullptr);
REQUIRE(taken->array()[0]->parser == nullptr);
REQUIRE(taken->array()[1]->parser == nullptr);
// ...and its root no longer points out at the array it was spliced
// from, but the parent links *within* it are left intact so the tree
// stays navigable upwards.
REQUIRE(taken->parent == nullptr);
REQUIRE(taken->array()[0]->parent == taken.get());
REQUIRE(taken->array()[1]->parent == taken.get());
// So the subtree stays valid once the parser, and the tree the parser
// still owns, are destroyed.
jp.reset();
// outer is dangling now; do not dereference.
REQUIRE(taken->type == JSON_ARRAY);
REQUIRE(taken->array().size() == 2);
REQUIRE(taken->array()[0]->number() == 3);
REQUIRE(taken->array()[1]->number() == 4);
}
// json_free finds a node's owner through o->parent, so clearing the interior
// parent links on detach would make this a silent no-op.
TEST_CASE("json_free prunes an interior node of a detached tree", "[jsonpull][ownership]") {
json_pull_ptr jp = json_begin_string("[[1, 2], [3, 4], [5, 6]]");
json_object_ptr tree = json_read_tree(jp);
REQUIRE(tree != nullptr);
REQUIRE(tree->type == JSON_ARRAY);
REQUIRE(tree->array().size() == 3);
// Destroy the parser first, so this is unambiguously operating on a
// tree that no longer has one.
jp.reset();
REQUIRE(tree->parser == nullptr);
json_object *drop = tree->array()[1].get();
REQUIRE(drop->array()[0]->number() == 3);
REQUIRE(drop->parent == tree.get());
json_free(drop);
// drop is dangling now; do not dereference.
// Had the parent links been cleared on detach, json_free would not
// have found an owner to splice the node out of, and the array would
// still have three elements.
REQUIRE(tree->array().size() == 2);
REQUIRE(tree->array()[0]->array()[0]->number() == 1);
REQUIRE(tree->array()[1]->array()[0]->number() == 5);
}
// Not a removal: the key stays with a JSON_NULL stand-in so the surrounding
// pairs keep their alignment, and the entry goes only when both halves do.
TEST_CASE("json_free of a hash value leaves a null placeholder", "[jsonpull][ownership]") {
json_pull_ptr jp = json_begin_string(R"({"keep": 1, "drop": [2, 3]})");
json_object_ptr tree = json_read_tree(jp);
REQUIRE(tree != nullptr);
REQUIRE(tree->entries().size() == 2);
json_object *drop = json_hash_get(tree, "drop");
REQUIRE(drop != nullptr);
REQUIRE(drop->type == JSON_ARRAY);
json_free(drop);
// drop is dangling now; do not dereference.
// The key survives, now paired with a null rather than the array.
REQUIRE(tree->entries().size() == 2);
json_object *after = json_hash_get(tree, "drop");
REQUIRE(after != nullptr);
REQUIRE(after->type == JSON_NULL);
// The neighbouring pair is untouched.
REQUIRE(json_hash_get(tree, "keep") != nullptr);
REQUIRE(json_hash_get(tree, "keep")->number() == 1);
}
// The array-splicing fix. The old code passed an element count to memmove
// where a byte count was wanted, so pruning element 0 of eight left
// arr[0] == arr[1] -- one node owned twice -- and dropped the last element.
// Asserting each survivor's identity is what discriminates; checking only the
// size would not.
TEST_CASE("json_free prunes a non-final element", "[jsonpull][ownership]") {
json_pull_ptr jp = json_begin_string("[[1], [2], [3], [4], [5], [6], [7], [8]]");
json_object_ptr tree = json_read_tree(jp);
REQUIRE(tree != nullptr);
REQUIRE(tree->type == JSON_ARRAY);
REQUIRE(tree->array().size() == 8);
json_free(tree->array()[0].get());
// Every survivor keeps its identity, in order, and nothing is aliased.
REQUIRE(tree->array().size() == 7);
for (size_t i = 0; i < tree->array().size(); i++) {
json_object *e = tree->array()[i].get();
REQUIRE(e->type == JSON_ARRAY);
REQUIRE(e->array().size() == 1);
REQUIRE(e->array()[0]->number() == (double) (i + 2));
if (i + 1 < tree->array().size()) {
REQUIRE(e != tree->array()[i + 1].get());
}
}
}
// The mirror of the value case above.
TEST_CASE("json_free of a hash key, then of both halves", "[jsonpull][ownership]") {
json_pull_ptr jp = json_begin_string(R"({"a": 1, "b": 2, "c": 3})");
json_object_ptr tree = json_read_tree(jp);
REQUIRE(tree != nullptr);
REQUIRE(tree->entries().size() == 3);
// Free the key of the middle pair. The entry stays, with a null key,
// and its value is still reachable positionally.
json_free(tree->entries()[1].key.get());
REQUIRE(tree->entries().size() == 3);
REQUIRE(tree->entries()[1].key->type == JSON_NULL);
REQUIRE(tree->entries()[1].value->number() == 2);
// The neighbours are untouched, and the now-keyless pair is no longer
// findable by name.
REQUIRE(json_hash_get(tree, "b") == nullptr);
REQUIRE(json_hash_get(tree, "a")->number() == 1);
REQUIRE(json_hash_get(tree, "c")->number() == 3);
// Freeing the other half too retires the whole entry.
json_free(tree->entries()[1].value.get());
REQUIRE(tree->entries().size() == 2);
REQUIRE(json_hash_get(tree, "a")->number() == 1);
REQUIRE(json_hash_get(tree, "c")->number() == 3);
}
// What the filter loaders and -L / -E do. Each detached tree has to survive
// the next json_read_tree call and the parser's destruction.
TEST_CASE("repeated json_read_tree on a line-delimited stream", "[jsonpull][ownership]") {
json_pull_ptr jp = json_begin_string("{\"n\": 1}\n{\"n\": 2}\n{\"n\": 3}\n");
std::vector<json_object_ptr> trees;
for (int i = 0; i < 3; i++) {
json_object_ptr t = json_read_tree(jp);
REQUIRE(t != nullptr);
REQUIRE(t->type == JSON_HASH);
// Reading the next tree must not disturb the ones already taken.
REQUIRE(json_hash_get(t, "n")->number() == i + 1);
trees.push_back(std::move(t));
}
REQUIRE(json_read_tree(jp) == nullptr);
// All three outlive the parser they came from.
jp.reset();
for (int i = 0; i < 3; i++) {
REQUIRE(trees[i]->parser == nullptr);
REQUIRE(json_hash_get(trees[i], "n")->number() == i + 1);
}
}
// What json_context() prints on the error paths: a hash whose last key has no
// value yet renders that slot as "...".
TEST_CASE("json_stringify of a partially-parsed tree", "[jsonpull][stringify]") {
json_pull_ptr jp = json_begin_string("{\"a\": [1, 2], \"b\":");
// Read until the parser runs out of input mid-hash.
while (json_read(jp) != nullptr) {
;
}
REQUIRE(jp->error != nullptr);
REQUIRE(jp->root != nullptr);
std::string s = json_stringify(jp->root.get());
REQUIRE(s == "{\"a\":[1,2],\"b\":...}");
}
// Values are std::string now, so an embedded NUL is legal and stringify has to
// walk past it rather than stop the way a c_str() loop would.
TEST_CASE("json_stringify keeps text after an embedded NUL", "[jsonpull][stringify]") {
json_pull_ptr jp = json_begin_string("\"a\\u0000b\"");
json_object_ptr o = json_read_tree(jp);
REQUIRE(o != nullptr);
REQUIRE(o->type == JSON_STRING);
REQUIRE(o->string().size() == 3);
std::string s = json_stringify(o.get());
REQUIRE(s == "\"a\\u0000b\"");
}
// U+FFFF used to fall through the `< 0xFFFF` test into the four-byte branch
// and come out as the overlong F0 8F BF BF, which check_utf8 does not catch.
TEST_CASE("jsonpull encodes U+FFFF as three bytes", "[jsonpull][utf8]") {
json_pull_ptr jp = json_begin_string("\"a\\uFFFFb\"");
json_object_ptr o = json_read_tree(jp);
REQUIRE(jp->error == nullptr);
REQUIRE(o != nullptr);
REQUIRE(o->type == JSON_STRING);
REQUIRE(o->string() ==
"a\xEF\xBF\xBF"
"b");
REQUIRE(o->string() !=
"a\xF0\x8F\xBF\xBF"
"b");
// The boundary below it, and a genuine supplementary code point built
// from a surrogate pair, both keep their existing encodings.
json_pull_ptr jp2 = json_begin_string("\"\\uFFFE\"");
json_object_ptr o2 = json_read_tree(jp2);
REQUIRE(o2 != nullptr);
REQUIRE(o2->string() == "\xEF\xBF\xBE");
json_pull_ptr jp3 = json_begin_string("\"\\uD83D\\uDC00\"");
json_object_ptr o3 = json_read_tree(jp3);
REQUIRE(o3 != nullptr);
REQUIRE(o3->string() == "\xF0\x9F\x90\x80");
}
TEST_CASE("Polygon cleaning drops a hole that no ring can parent", "[wagyu]") {
// Two mutually reversed self-intersecting rings whose union leaves a hole
// that wagyu's topology correction cannot assign to any surviving parent
// ring (found by fuzzing; same failure as mapbox/tippecanoe#761). Without
// the fix in mapbox/geometry/wagyu/topology_correction.hpp, this exits
// through the "Could not properly place hole to a parent." handler in
// clean_or_clip_poly instead of returning.
static const std::vector<std::vector<std::pair<long long, long long>>> rings = {
{{0, 5}, {5, 4}, {5, 1}, {4, 4}, {4, 2}, {7, 1}, {0, 5}},
{{0, 5}, {7, 1}, {4, 2}, {4, 4}, {5, 1}, {5, 4}, {0, 0}, {0, 5}},
};
drawvec geom;
for (auto const &ring : rings) {
for (size_t i = 0; i < ring.size(); i++) {
geom.push_back(draw(i == 0 ? VT_MOVETO : VT_LINETO, ring[i].first, ring[i].second));
}
}
drawvec out = clean_or_clip_poly(geom, 0, 0, false, false);
// The regression signal is getting here at all: without the fix,
// clean_or_clip_poly exits the process from its wagyu error handler.
SUCCEED("clean_or_clip_poly returned");
// Anything that survives must be sanely wound: first ring positive.
if (out.size() > 0) {
size_t j = 1;
while (j < out.size() && out[j].op == VT_LINETO) j++;
REQUIRE(get_area(out, 0, j) > 0);
}
}
static drawvec world_ring(std::vector<std::pair<double, double>> const &pixels, int shift) {
drawvec ring;
for (size_t i = 0; i < pixels.size(); i++) {
ring.push_back(draw(i == 0 ? VT_MOVETO : VT_LINETO,
std::llround(pixels[i].first * (1LL << shift)),
std::llround(pixels[i].second * (1LL << shift))));
}
ring.push_back(draw(VT_LINETO, ring[0].x, ring[0].y));
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;
}
return ring;
}
TEST_CASE("Spindle polygons are preserved as one-pixel strips", "[spindle]") {
const int z = 0, detail = 12, shift = 32 - detail - z;
// A spindle 0.2 pixels wide and about 3200 pixels long, at an angle
double ax = 100, ay = 100, bx = 3000, by = 1500;
double len = std::hypot(bx - ax, by - ay);
double nx = -(by - ay) / len * 0.1, ny = (bx - ax) / len * 0.1;
drawvec geom = world_ring({{ax + nx, ay + ny}, {bx + nx, by + ny}, {bx - nx, by - ny}, {ax - nx, ay - ny}}, shift);
drawvec strips = thin_polygon_strips(geom, z, detail);
REQUIRE(strips.size() > 0);
drawvec scaled = geom;
to_tile_scale(scaled, z, detail);
drawvec cleaned = clean_or_clip_poly(scaled, 0, 0, false, true);
drawvec out = union_polygon_strips(cleaned, strips);
// Without the strips, the spindle collapses to (nearly) nothing.
// With them, it is a continuous line about a pixel thick.
REQUIRE(get_mp_area(cleaned) < len * 0.5);
REQUIRE(get_mp_area(out) >= len * 0.9);
REQUIRE(get_mp_area(out) <= len * 2.1);
size_t outer = 0;
for (size_t i = 0; i < out.size(); i++) {
if (out[i].op == VT_MOVETO) {
size_t j;
for (j = i + 1; j < out.size() && out[j].op == VT_LINETO; j++) {
}
if (get_area(out, i, j) > 0) {
outer++;
}
i = j - 1;
}
}
REQUIRE(outer == 1);
}
TEST_CASE("Polygons without narrow parts get no spindle strips", "[spindle]") {
const int z = 0, detail = 12, shift = 32 - detail - z;
// A big square
REQUIRE(thin_polygon_strips(world_ring({{100, 100}, {2000, 100}, {2000, 2000}, {100, 2000}}, shift), z, detail).size() == 0);
// An equilateral triangle: its corners are sharp, but not narrow
REQUIRE(thin_polygon_strips(world_ring({{100, 100}, {1100, 100}, {600, 100 + 500 * std::sqrt(3)}}, shift), z, detail).size() == 0);
// A strip 3 pixels wide is wide enough to survive rounding
REQUIRE(thin_polygon_strips(world_ring({{100, 100}, {3000, 100}, {3000, 103}, {100, 103}}, shift), z, detail).size() == 0);
// A shape that is already exact at tile resolution can't collapse
REQUIRE(thin_polygon_strips(world_ring({{100, 100}, {3000, 100}, {3000, 100.2}, {100, 100.2}}, 0), 20, detail).size() == 0);
}
TEST_CASE("Spindle strips are not added where they would overlap a neighboring feature", "[spindle]") {
const int z = 0, detail = 12, shift = 32 - detail - z;
const long long px = 1LL << shift;
// A strip 0.2 pixels wide and 3000 pixels long: a "panhandle"
// if both sides are shared, or a coastal strip if only one is
long long x1 = 100 * px, x2 = 3100 * px;
long long y1 = 1000 * px, y2 = 1000 * px + px / 5;
drawvec geom = world_ring({{100, 1000}, {3100, 1000}, {3100, 1000.2}, {100, 1000.2}}, shift);
REQUIRE(geom[2].y == y2);
auto with_shared = [&](std::vector<shared_edge> edges) {
std::sort(edges.begin(), edges.end(), [](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);
});
shared_edges_map = edges.data();
shared_edges_count = edges.size();
drawvec strips = thin_polygon_strips(geom, z, detail);
shared_edges_map = NULL;
shared_edges_count = 0;
return strips;
};
// No shared edges: both long sides get strips
drawvec none = with_shared({});
REQUIRE(none.size() == 2 * 5);
// Both long sides shared with neighbors: no strips at all
REQUIRE(with_shared({{x1, y1, x2, y1}, {x2, y1, x1, y1}, {x1, y2, x2, y2}, {x2, y2, x1, y2}}).size() == 0);
// Only the top side (y1) shared: only the strip along the shared side,
// which extends away from the neighbor, is kept
drawvec one = with_shared({{x1, y1, x2, y1}, {x2, y1, x1, y1}});
REQUIRE(one.size() == 5);
for (auto const &d : one) {
REQUIRE(d.y >= 1000);
}
}
TEST_CASE("Polygon cleaning keeps a diagonal polygon one pixel wide", "[wagyu]") {
// Two parallel 45-degree edges one pixel apart. Each edge passes exactly
// through the corner of the pixel around the other edge's endpoints.
// Wagyu used to count that as passing through the pixel, snap each edge
// to the other's endpoints, and collapse this valid polygon to nothing.
static const std::vector<std::pair<long long, long long>> ring = {
{135, 103},
{143, 95},
{143, 96},
{137, 102},
{135, 103},
};
drawvec geom;
for (size_t i = 0; i < ring.size(); i++) {
geom.push_back(draw(i == 0 ? VT_MOVETO : VT_LINETO, ring[i].first, ring[i].second));
}
REQUIRE(get_area(geom, 0, geom.size()) == 7);
drawvec out = clean_or_clip_poly(geom, 0, 0, false, false);
REQUIRE(get_mp_area(out) == 7);
}
TEST_CASE("A polygon that collapses entirely can be replaced by its outline", "[spindle]") {
const int z = 0, detail = 12, shift = 32 - detail - z;
// An L-shaped polygon 0.2 pixels wide, with arms 1000 and 500 pixels long
drawvec geom = world_ring({{100, 100}, {1100, 100}, {1100, 600}, {1099.8, 600}, {1099.8, 100.2}, {100, 100.2}}, shift);
drawvec scaled = geom;
to_tile_scale(scaled, z, detail);
REQUIRE(clean_or_clip_poly(scaled, 0, 0, false, true).size() == 0);
bool all_shared;
drawvec outline = union_polygon_strips(drawvec(), outline_strips(geom, z, detail, 1, 0, 0, &all_shared));
REQUIRE(!all_shared);
double area = get_mp_area(outline);
// About a pixel wide along both arms, rather than a square
REQUIRE(area >= 1500);
REQUIRE(area <= 2 * 1500 + 10);
long long minx = LLONG_MAX, maxx = LLONG_MIN, miny = LLONG_MAX, maxy = LLONG_MIN;
for (auto const &d : outline) {
minx = std::min(minx, (long long) d.x);
maxx = std::max(maxx, (long long) d.x);
miny = std::min(miny, (long long) d.y);
maxy = std::max(maxy, (long long) d.y);
}
REQUIRE(minx >= 99);
REQUIRE(maxx <= 1101);
REQUIRE(miny >= 99);
REQUIRE(maxy <= 601);
}
TEST_CASE("Snapping to a layer's hot pixels keeps shared borders consistent", "[wagyu]") {
// A Census block (rounded to tile coordinates) and the sliver beside it,
// which share a long diagonal border. Rounding moved one of the block's
// own vertices across that border, so cleaning the block on its own snaps
// its copy of the border through a hot pixel that the sliver doesn't have,
// leaving a gap between them.
auto ring = [](std::vector<std::pair<long long, long long>> pts) {
drawvec g;
for (size_t i = 0; i < pts.size(); i++) {
g.push_back(draw(i == 0 ? VT_MOVETO : VT_LINETO, pts[i].first, pts[i].second));
}
return g;
};
drawvec sliver = ring({{227, 197}, {228, 197}, {235, 226}, {235, 226}, {227, 197}});
drawvec block = ring({{241, 226}, {235, 226}, {228, 197}, {230, 197}, {229, 199}, {229, 202}, {231, 207}, {234, 208}, {234, 213}, {235, 218}, {238, 223}, {241, 224}, {241, 226}});
drawvec both = sliver;
both.insert(both.end(), block.begin(), block.end());
drawvec together = clean_or_clip_poly(both, 0, 0, false, false);
// Count the pixels covered by the two cleaned together that neither covers
// when cleaned separately, and the pixels that both cover
auto shards = [&](drawvec const &a, drawvec const &b, int *gaps, int *overlaps) {
auto x2 = [](drawvec g) {
for (auto &d : g) {
d.x *= 2;
d.y *= 2;
}
return g;
};
drawvec u2 = x2(together), a2 = x2(a), b2 = x2(b);
*gaps = *overlaps = 0;
for (long long y = 190; y < 230; y++) {
for (long long x = 220; x < 245; x++) {
int n = pnpoly_mp(a2, 2 * x + 1, 2 * y + 1) + pnpoly_mp(b2, 2 * x + 1, 2 * y + 1);
if (n == 0 && pnpoly_mp(u2, 2 * x + 1, 2 * y + 1)) {
(*gaps)++;
}
if (n > 1) {
(*overlaps)++;
}
}
}
};
drawvec s1 = sliver, b1 = block;
int gaps, overlaps;
shards(clean_or_clip_poly(s1, 0, 0, false, false), clean_or_clip_poly(b1, 0, 0, false, false), &gaps, &overlaps);
REQUIRE(gaps > 0);
hot_pixel_list hot = layer_hot_pixels({&sliver, &block});
bool ok1, ok2;
drawvec s2 = clean_polygon_with_hot_pixels(sliver, hot, &ok1);
drawvec b2 = clean_polygon_with_hot_pixels(block, hot, &ok2);
REQUIRE(ok1);
REQUIRE(ok2);
shards(s2, b2, &gaps, &overlaps);
REQUIRE(gaps == 0);
REQUIRE(overlaps == 0);
}
TEST_CASE("Consistent snapping doesn't make neighboring polygons' edges cross", "[wagyu]") {
// Five Census blocks around a sliver whose sides crossed each other when
// rounded to tile coordinates. With closed hot pixels, edges passing
// diagonally through pixel corners were snapped into zigzags that visited
// the same pixels in different orders, and edges of two neighboring blocks
// crossed each other. With half-open hot pixels, they only meet at vertices.
auto parse = [](const char *s) {
drawvec g;
std::istringstream in(s);
std::string tok;
while (in >> tok) {
bool m = tok[0] == 'M';
if (m) {
tok = tok.substr(1);
}
long long x, y;
sscanf(tok.c_str(), "%lld,%lld", &x, &y);
g.push_back(draw(m ? VT_MOVETO : VT_LINETO, x, y));
}
g.push_back(draw(VT_LINETO, (long long) g[0].x, (long long) g[0].y));
return g;
};
std::vector<drawvec> in = {
parse("M196,147 196,147 196,149 199,147 198,146 199,146 200,147 200,148 201,149 200,150 203,150 203,155 204,154 204,155 207,158 207,158 201,152 203,153 203,150 200,150 201,149 198,146 199,148 197,148 198,149 196,147"),
parse("M196,149 196,147 199,145 200,147 199,146 198,146 199,147 196,149"),
parse("M198,146 201,149 200,150 203,150 203,153 201,152 207,158 206,162 192,162 192,148 196,147 198,149 197,148 199,148 198,146"),
parse("M200,148 207,148 207,158 204,155 204,154 203,155 203,150 200,150 201,149 200,148"),
parse("M199,145 207,144 207,148 200,148 200,147 199,145"),
};
std::vector<drawvec const *> ptrs;
for (auto const &g : in) {
ptrs.push_back(&g);
}
hot_pixel_list hot = layer_hot_pixels(ptrs);
std::vector<drawvec> out;
for (auto const &g : in) {
bool ok;
out.push_back(clean_polygon_with_hot_pixels(g, hot, &ok));
REQUIRE(ok);
}
auto orient = [](draw const &a, draw const &b, draw const &c) {
long long v = ((long long) b.x - a.x) * ((long long) c.y - a.y) - ((long long) b.y - a.y) * ((long long) c.x - a.x);
return (v > 0) - (v < 0);
};
size_t crossings = 0;
for (size_t a = 0; a < out.size(); a++) {
for (size_t b = a + 1; b < out.size(); b++) {
for (size_t i = 0; i + 1 < out[a].size(); i++) {
if (out[a][i + 1].op != VT_LINETO) {
continue;
}
for (size_t j = 0; j + 1 < out[b].size(); j++) {
if (out[b][j + 1].op != VT_LINETO) {
continue;
}
draw const &p1 = out[a][i], &p2 = out[a][i + 1], &q1 = out[b][j], &q2 = out[b][j + 1];
if (orient(p1, p2, q1) * orient(p1, p2, q2) < 0 && orient(q1, q2, p1) * orient(q1, q2, p2) < 0) {
crossings++;
}
}
}
}
}
REQUIRE(crossings == 0);
}
TEST_CASE("Overlaps between polygons go to the earlier polygon", "[wagyu]") {
auto ring = [](std::vector<std::pair<long long, long long>> pts) {
drawvec g;
for (size_t i = 0; i < pts.size(); i++) {
g.push_back(draw(i == 0 ? VT_MOVETO : VT_LINETO, pts[i].first, pts[i].second));
}
g.push_back(draw(VT_LINETO, pts[0].first, pts[0].second));
if (get_area(g, 0, g.size()) < 0) {
std::reverse(g.begin(), g.end());
g[0].op = VT_MOVETO;
g[g.size() - 1].op = VT_LINETO;
}
return g;
};
// Two squares that overlap in a 2x10 strip, without sharing any edges
drawvec first = ring({{0, 0}, {10, 0}, {10, 10}, {0, 10}});
drawvec second = ring({{8, 0}, {20, 0}, {20, 10}, {8, 10}});
// and one that shares a border with the first in the same direction,
// so that it covers the same triangle beside it
drawvec third = ring({{0, 10}, {10, 10}, {5, 5}});
// Clean them consistently first, as tippecanoe does, which splits
// each square's edges where the other's corners touch them
hot_pixel_list hot = layer_hot_pixels({&first, &second, &third});
bool ok;
first = clean_polygon_with_hot_pixels(first, hot, &ok);
second = clean_polygon_with_hot_pixels(second, hot, &ok);
third = clean_polygon_with_hot_pixels(third, hot, &ok);
std::vector<drawvec *> geoms = {&first, &second, &third};
REQUIRE(remove_overlaps(geoms, &hot) == 2);
REQUIRE(get_mp_area(first) == 100);
REQUIRE(get_mp_area(second) == 100);
REQUIRE(get_mp_area(third) == 0);
}
TEST_CASE("Removing overlaps doesn't snap the polygons again", "[wagyu]") {
// Census blocks around a half-pixel triangle (in Dane County tile 8/64/93),
// as rounded to tile coordinates, in order of sequence number. Consistent
// snapping leaves the triangle in one of them, whose diagonal edge then
// passes through the corner of the hot pixel of the vertex beside it.
// Removing that block's overlap with another must not snap it again,
// which collapsed the triangle and left a hole.
auto parse = [](const char *s) {
drawvec g;
std::istringstream in(s);
std::string tok;
while (in >> tok) {
bool m = tok[0] == 'M';
if (m) {
tok = tok.substr(1);
}
long long x, y;
sscanf(tok.c_str(), "%lld,%lld", &x, &y);
g.push_back(draw(m ? VT_MOVETO : VT_LINETO, x, y));
}
g.push_back(draw(VT_LINETO, (long long) g[0].x, (long long) g[0].y));
return g;
};
std::vector<drawvec> in = {
parse("M65,245 65,244 66,244 66,244 66,245 65,245"),
parse("M66,244 66,244 65,244 65,244 66,244"),
parse("M67,244 67,244 67,244 67,244 67,243 67,243 67,243 67,243 67,243 67,244"),
parse("M66,244 66,244 66,244 67,245 67,244 67,245 67,245 66,245 66,245 66,245 66,244"),
parse("M66,244 66,244 66,244 66,244 67,244 67,244 67,244 67,244 66,244 66,244"),
parse("M68,242 67,243 67,243 66,243 66,242 67,242 68,242 67,243 68,243"),
parse("M65,244 65,245 65,245 65,245 65,245 65,244"),
parse("M64,244 65,245 64,245 64,244 64,244"),
parse("M65,244 65,244 65,244 64,244 64,244 65,244"),
parse("M65,244 65,244 66,244 66,244 66,244 66,244 65,244"),
parse("M66,244 67,244 67,244 67,244 67,244 67,244 66,244 66,244 66,244"),
parse("M69,240 71,238 73,237 73,241 69,240"),
parse("M66,243 66,243 66,243 66,243 66,244 66,244 65,244 65,244 66,243"),
parse("M67,244 67,243 68,243 68,243 68,243 68,244 67,244"),
parse("M67,243 67,243 67,243 68,243 68,243 65,244"),
parse("M61,244 63,239 66,235 69,234 69,236 67,236 68,241 68,242 67,242 67,241 65,242 65,243 65,243 65,244 64,244 64,243 62,244 62,244 61,244"),
parse("M65,245 65,245 65,244 65,244 65,244 65,244 65,244 65,244 65,244 65,244 65,244 65,243 65,243 65,243 65,244 65,244 65,244 65,244 65,245"),
parse("M67,244 67,244 68,244 68,244 68,244 68,244 68,244 68,244 73,245 73,245 73,249 72,249 71,249 71,249 69,249 66,247 66,247 66,247 66,245 67,245 67,245 67,245 67,244 67,244"),
parse("M64,244 64,245 64,245 64,244 64,244"),
parse("M66,244 67,244 67,245 67,244 67,245 66,244"),
parse("M69,243 68,244 68,244 68,243 68,243 68,243 68,243 69,243"),
parse("M68,241 67,236 69,236 69,240 68,241"),
parse("M73,241 73,243 73,244 68,244 68,244 68,244 69,243 68,243 67,243 68,242 68,241 69,240 73,241"),
parse("M67,243 67,244 67,244 67,243 67,243"),
parse("M65,244 65,243 66,243 66,242 66,243 65,244"),
parse("M66,242 66,242 66,242 66,242 66,243 66,242"),
parse("M63,244 64,244 64,245 63,245 63,244"),
parse("M64,245 64,244 64,245 64,245 64,245"),
parse("M65,244 65,244 65,244 65,244 65,245 65,244 65,244"),
parse("M66,244 66,243 66,243 66,243 66,243 67,242 66,242 66,243 67,243 67,243 67,243 67,244 66,244 66,244 66,244 66,244"),
parse("M67,244 67,244 66,244 66,244 67,244"),
parse("M67,245 67,244 67,245 67,245"),
parse("M73,245 68,244 68,244 73,244 73,245"),
parse("M64,244 64,244 64,244 64,244 64,244"),
parse("M65,243 65,243 65,242 67,241 67,242 66,243 66,242 66,242 66,242 66,242 66,243 65,243"),
parse("M69,236 71,238 69,240 69,236"),
parse("M64,245 64,245 64,244 64,244 64,245"),
parse("M66,244 66,244 66,244 66,244 66,244 66,245 66,245 66,245 66,245 66,245 65,245 66,245 66,244 66,244 63,244 63,244 64,244"),
parse("M65,244 65,245 64,244 64,244 63,244 63,244 63,245 63,244 63,244"),
parse("M65,245 67,243 67,243")
};
std::vector<drawvec const *> ptrs;
for (auto const &g : in) {
ptrs.push_back(&g);
}
hot_pixel_list hot = layer_hot_pixels(ptrs);
std::vector<drawvec> out;
for (auto const &g : in) {
bool ok;
out.push_back(clean_polygon_with_hot_pixels(g, hot, &ok));
}
std::vector<drawvec *> geoms;
for (auto &g : out) {
geoms.push_back(&g);
}
remove_overlaps(geoms, &hot);
// Sample the area (with coordinates doubled, so the samples are at
// quarter-pixel offsets that are never on a boundary)
for (auto &g : out) {
for (auto &d : g) {
d.x *= 4;
d.y *= 4;
}
}
size_t overlaps = 0;
for (long long y = 238 * 4 + 1; y < 245 * 4; y += 2) {
for (long long x = 62 * 4 + 1; x < 70 * 4; x += 2) {
size_t n = 0;
for (auto const &g : out) {
n += pnpoly_mp(g, x, y);
}
if (n > 1) {
overlaps++;
}
}
}
REQUIRE(overlaps == 0);
// The triangle between (67, 241), (67, 242), and (66, 242) is covered once
size_t n = 0;
for (auto const &g : out) {
n += pnpoly_mp(g, 4 * 67 - 1, 4 * 242 - 1);
}
REQUIRE(n == 1);
}