Compare commits

..
Author SHA1 Message Date
Claude 9ff3f92e6e Spread shared node marking across all CPUs regardless of readers
Marking used one thread per reader, so input that was read serially,
which all goes to the first reader, was marked by a single thread.
Instead, use the readers' indexes to divide all the geometry into
ranges of about the same size at feature boundaries, and have each
thread take the next unmarked range until there are none left.

With 4 CPUs and input read by one reader, this makes marking about
3x faster.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P2nBqZisxNQfmEmon3vE9v
2026-09-23 20:02:49 +00:00
Claude 58ad6e3008 Use the faster bit interleave for encode_quadkey itself
encode_vertex() computed exactly the same thing as encode_quadkey(),
so there is no reason to have both. Give encode_quadkey() the branch-free
implementation, which also speeds up the default encode_index, and have
the shared node code call it directly. The unit test now compares it
against the old bit-at-a-time loop and checks that decode_quadkey()
reverses it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P2nBqZisxNQfmEmon3vE9v
2026-09-23 20:02:49 +00:00
Claude e1795ebe32 Make the remaining shared node lookups faster
Encode the shared nodes as quadkeys, as the comment on struct node
already said they were, with a branch-free bit interleave, so that
vertices that are near each other are near each other in the sorted list
too. Search the list with an inlined std::lower_bound instead of bsearch.

Size the Bloom filter by the number of nodes, at about 16 bits each and
at most 32MB, instead of always using 34MB, so that it can usually stay
in the cache, and set three bits for each node, chosen by a mixing hash,
within a single 64-bit word, so that each check still touches only one
cache line but has far fewer false positives than a single bit.

In the pass that marks the vertices with whether they are shared nodes,
this is about 1.7x faster with 70 thousand nodes and 1.9x faster with
3 million.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P2nBqZisxNQfmEmon3vE9v
2026-09-23 19:46:09 +00:00
Claude 175036930d Test --no-simplification-of-shared-nodes with --clip-bounding-box
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P2nBqZisxNQfmEmon3vE9v
2026-09-23 18:28:32 +00:00
Claude f03cc8ce0e Treat points created by clipping and tiny polygon placeholders as not shared
Points that clipping creates along a feature's edges, other than at the
existing vertices, and the vertices of tiny polygon placeholders, are
not vertices of the original geometry, so they are now marked as not
being shared nodes instead of being looked up in the global list of
shared nodes when they are simplified. This could only change the output
where a vertex of some other feature happens to fall exactly on one of
these new points, and in practice none of them ever turned out to be
shared nodes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P2nBqZisxNQfmEmon3vE9v
2026-09-23 18:28:04 +00:00
Claude 1dee1890e7 Mask the node state out of the operation when marking shared nodes
Geometry that was clipped to --clip-bounding-box while it was being
serialized can already have node states in its operation bytes, so the
unmasked comparison against VT_MOVETO and VT_LINETO failed to recognize
those vertices and lost track of where the following vertices began.
Also stop with an error instead of continuing if the operation is not
one that can appear in serialized geometry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P2nBqZisxNQfmEmon3vE9v
2026-09-23 18:28:04 +00:00
Claude ee5debc4f2 Don't look up shared nodes that are already necessary
Vertices that are already going to be kept, because they begin a ring
or are on the tile boundary, can't be affected by whether they are also
global shared nodes, so skip looking them up. These are most of the
vertices that clipping creates, which don't know their node state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P2nBqZisxNQfmEmon3vE9v
2026-09-23 18:09:52 +00:00
Claude d3a98170bf Look up shared nodes once per vertex instead of once per tile
With --no-simplification-of-shared-nodes, simplify_lines() used to offset
every vertex of every feature to world coordinates and check it against
the Bloom filter and the global sorted list of shared nodes, in every
tile at every zoom level.

Whether a vertex is a shared node depends only on its world coordinates,
so now it is found once, after the list of shared nodes has been made
and before the geometry is sorted, by a parallel pass over each reader's
geometry that marks each vertex in place, in the upper bits of its
serialized operation byte. Decoding puts that state into a new field of
draw (which still fits in 16 bytes), and it is carried through clipping,
the copies across the antimeridian at z0, and the geometry written for
the next zoom level. Polygon cleaning of coalesced features restores the
state of any output vertex with the same coordinates as an input vertex.

Vertices whose state is still unknown, because they were created by
clipping or polygon cleaning or came back from a prefilter, are still
looked up in the global list when they are simplified, so the output is
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P2nBqZisxNQfmEmon3vE9v
2026-09-23 17:39:48 +00:00
4f2621186a Convert jsonpull to C++ with shared_ptr and std::vector/std::string (#388)
* Rename to jsonpull.cpp

* Clear for merge

* Convert jsonpull to C++ with shared_ptr and std::vector/std::string

Replace the manual malloc/realloc/free memory management in jsonpull
with std::shared_ptr ownership. Each json_object now owns its children
through std::vector<json_object_ptr>; raw back-pointers to parent and
parser remain valid by structural invariant and are cleared on
json_disconnect so detached subtrees can outlive their parser.
Strings become std::string, child arrays become std::vector, and the
old union becomes a struct so non-trivial members can coexist while
preserving the existing o->value.xxx access paths.

The old jsonpull.c is replaced by jsonpull.cpp, json_stringify now
returns std::string, and all callers across tippecanoe, tile-join,
tippecanoe-decode, tippecanoe-json-tool, tippecanoe-overzoom and the
unit tests are updated to use json_object_ptr / json_pull_ptr.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Subclass json_object so primitives shrink from 168 to 24 bytes

The previous "every member in a struct" layout cost 168 bytes per
json_object, even for JSON_NULL / JSON_TRUE / JSON_FALSE nodes that
have no payload. Splitting json_object into a small base class plus
json_number / json_string / json_array / json_hash subclasses brings
each instance down to just the size of its actual contents:

  json_object (base, TRUE / FALSE / NULL)   24 bytes
  json_number                                48 bytes
  json_string                                48 bytes
  json_array  (empty)                        48 bytes
  json_hash   (empty)                        72 bytes

Other size wins along the way:

* Drop enable_shared_from_this<json_object> (its embedded weak_ptr
  was 16 bytes per node). json_pull now keeps an explicit
  container_stack and the parser no longer needs to resurrect a
  shared_ptr from a raw `parent` walk.
* Remove the unused `refcon` slot from the string variant.
* No virtual destructor: shared_ptr keeps the deleter from the
  original std::make_shared<json_xxx> call, so destroying a
  shared_ptr<json_object> still runs the right subclass dtor.

The base class exposes type-tagged accessors (o->string(),
o->number(), o->array(), o->keys(), o->values(), o->large_signed(),
o->large_unsigned()) that assert the type matches and downcast to
the appropriate subclass storage. All call sites were swept from
the old `o->value.X.Y` field paths to these accessors. A raw-pointer
overload of json_hash_get() replaces the few external uses of
shared_from_this() that survived in geojson-loop.cpp.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Store hash key/value pairs in one ordered vector

Replace the parallel std::vector<json_object_ptr> keys / values on
json_hash with a single std::vector<json_entry>, where json_entry is
a small {key, value} aggregate. This still preserves insertion order
(the property the parallel vectors were providing) but removes the
"keep two vectors in lockstep" pattern, and call sites can now use
range-for with structured bindings:

    for (auto &[k, v] : o->entries()) { ... }

Side effects:

* sizeof(json_hash) drops from 72 to 48 bytes (one fewer vector
  header), matching json_array.
* The keys() and values() accessors on json_object are replaced by a
  single entries() accessor returning std::vector<json_entry>&.
* All call sites were swept from the old paired-index pattern
  (`o->keys()[i]` / `o->values()[i]`) to entry-based access. Where the
  original pattern relied on `nprop = 0` to short-circuit iteration on
  a null or non-hash `properties`, the rewrite now guards the loop
  explicitly with `if (o->type == JSON_HASH)` so that calling
  entries() doesn't trip the asserting downcast.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Move parser-only `expect` state out of json_object

`expect` was only meaningful while the parser was building a container,
and only ever read or written from jsonpull.cpp itself; once parsing
finished it was dead weight on every JSON_ARRAY and JSON_HASH (and
present-but-unused on every primitive too). Move it into the parser's
container stack, alongside the shared_ptr to the container it pertains
to:

    struct json_pull::parse_frame {
        json_object_ptr container;
        json_type       expect;
    };
    std::vector<parse_frame> container_stack;

The base class now only carries data-model state (parent, parser, type).
No external caller depended on `expect`, so no sweep was needed outside
jsonpull.cpp.

This change does not, in itself, shrink any json_object: the 4-byte
`expect` field used to live at offset 20 inside the base, where it was
already being eaten by alignment padding for the 8-byte-aligned first
member of every subclass (std::string, std::vector, double). The win is
in the data model, not the byte count -- the 4-byte hole is still
there, but it is now available for a future subclass whose first member
is small enough to slot into it.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Discriminate json_number's three numeric slots into one union

json_number used to carry three parallel 8-byte fields (a double plus
both a 64-bit unsigned and a 64-bit signed slot for the large-integer
cases) even though at most one of the integer slots is ever the
canonical value for any given number. Collapse them into a
discriminated union:

    enum repr_t { REPR_DOUBLE, REPR_LARGE_UNSIGNED, REPR_LARGE_SIGNED };
    repr_t repr;
    union { double d; unsigned long long u; long long s; } value;

Callers keep the same read API: number() returns the appropriate
double, large_unsigned() returns the ull (or 0 if not currently stored
that way), large_signed() likewise. Writes go through new set_number /
set_large_unsigned / set_large_signed methods that keep the
discriminator and the union value in sync.

This was prompted by an observation that moving json_type to the end
of the object should shrink things via tail-padding reuse. Empirically
the type-at-end rearrangement saves nothing on its own (every
subclass payload is 8-byte aligned so it can't slot into the 4-byte
tail), but the discriminated-number redesign hits the same idea from
a different direction: adding the 4-byte `repr` to json_number makes
the class non-standard-layout, which lets the Itanium ABI pack `repr`
into the base's 4-byte tail padding at offset 20. The union value
then starts at the natural offset 24, and json_number ends at offset
32 -- a 33% reduction.

Per-node sizes:
  json_object (TRUE/FALSE/NULL)  24 bytes
  json_number                    32 bytes  (was 48)
  json_string                    48 bytes
  json_array                     48 bytes
  json_hash                      48 bytes

Numbers dominate real GeoJSON (every coordinate is one), so the net
memory win on a typical parse is substantial.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fix bugs flagged in code review of jsonpull C++ port

- jsontool.cpp `out()`: route JSON_NUMBER (and anything else non-string)
  through `json_stringify` instead of `o->string()`, which now asserts
  on a non-string type and would crash `--extract` on numeric attributes.
- geojson.{hpp,cpp} `json_end_map`: take `json_pull_ptr` by reference so
  the caller's shared_ptr is released, null-guard before touching
  `jp->source`, and clear `jp->source` after delete to avoid a dangling
  pointer.
- jsonpull/jsonpull.cpp: low-surrogate range check was comparing the
  outer-loop byte `c` instead of the parsed code unit `ch`, breaking
  surrogate-pair decoding for some \\uXXXX escapes. Pre-existing bug
  preserved across the port.
- tile-join.cpp `handle_vector_layers`: require the field value to have
  type JSON_STRING (and the key to be non-null) before calling
  `string()`; the previous truthy `type` check would assert on a
  non-string value.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Add jsonpull regression test for surrogate-pair decoding

Covers the `c` vs `ch` bug fixed in the previous commit: parsing
"\uD83D\uE000" (a valid high surrogate followed by a non-surrogate
BMP code point) used to mis-classify U+E000 as a low surrogate and
combine the two units into U+1F400 (F0 9F 90 80). The fixed code
flushes the stale high surrogate as standalone CESU-8 (ED A0 BD)
and then encodes U+E000 normally as EE 80 80. Verified the test
fails under the pre-fix logic.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Cheap perf wins in jsonpull C++ port

Profiling tl_2022_us_county.json (sample(1) on Apple Silicon) showed
~38% of parse time in allocator work and ~14% in std::string::push_back
during string-token construction. These changes target the low-hanging
fruit from that profile:

- Pre-reserve 2 slots in json_array and 4 slots in json_hash so
  coordinate `[x, y]` pairs and typical GeoJSON property maps avoid
  the 0 -> 1 -> 2 -> 4 vector-growth chain (and the shared_ptr copies
  it incurs).
- Reuse a parser-wide std::string buffer for JSON_STRING tokens
  instead of constructing a fresh local std::string per token. The
  buffer is cleared (capacity preserved) at the start of each token
  and copied into the final json_string, so once it has grown to the
  longest string seen it stops reallocating entirely.
- std::move the freshly-created container shared_ptr into the parser
  container stack in the `[` and `{` handlers, and move it out of the
  frame on the matching `]` / `}`. Each move skips one atomic
  inc/dec round-trip per container open and close.

On a tl_2022_us_county.json benchmark (4-iter user-time mean, Apple
Silicon, /usr/bin/time):
- main baseline:                              ~8.17s
- jsonpull-cpp before these changes:          ~10.90s  (+33%)
- jsonpull-cpp with these changes:            ~9.33s   (+14%)

So this commit recovers roughly half of the post-port regression.
The remaining gap is dominated by shared_ptr atomic refcount traffic
on the parse tree and per-node heap allocations, which would require
the larger unique_ptr/arena reworks to address.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Make json_free actually free the subtree

In the C++ port, json_free was just `o.reset()`, which dropped the
caller's reference but left the subtree alive: the parent's vector
slot kept it allocated, and for line-delimited streams the parser's
jp->root co-owned it until the next top-level value started parsing.
That defeated the geojson-loop pattern of calling json_free on each
feature after serializing it, which is supposed to release the
feature so it doesn't sit in memory while subsequent ones are parsed.

Restore the historical "remove this from the tree" semantics by
splicing the node out of its parent (sharing splice_from_parent with
json_disconnect) and clearing jp->root when the node is the parser's
current top-level value, then dropping the caller's reference.

Two unit tests pin this down: a pruning test parses
"[[1, 2], [3, 4], [5, 6]]" element-wise and confirms that calling
json_free on [3, 4] leaves the outer array with just [1, 2] and
[5, 6]; a top-level test uses a weak_ptr observer to confirm that
json_free on the parser's root really destroys the tree.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Migrate jsonpull to unique_ptr ownership

Replaces the shared_ptr-based json_object_ptr with a unique_ptr that
has a stateless custom deleter dispatching on json_object::type before
calling the right subclass destructor. Eliminates per-node atomic
reference-counting and the control-block allocation that shared_ptr
required for every node in the tree.

API now distinguishes owning and borrowing pointers explicitly:
- json_read / json_read_separators / json_hash_get return raw
  json_object * (borrowed from the parser-owned tree).
- json_read_tree / json_disconnect return json_object_ptr (caller
  takes ownership; back-pointers are cleared so the subtree can
  outlive the parser).
- json_free / json_context / json_stringify take raw pointers.
- The parser's container_stack holds raw pointers; jp->root keeps
  unique_ptr ownership of the most recent top-level value.

Internally, take_from_owner moves the unique_ptr out of whichever
parent vector / hash entry / parser root owned it, which both
json_free and json_disconnect rely on.

In the streaming parsers (parse_feature, parse_layers, the
geojson-loop callback), we are careful to free `j` only after we
have processed a complete Feature: json_read returns each token
as the tree is being built up, and freeing an intermediate node
would splice it out of the surrounding hash and corrupt the
in-progress feature.

Benchmark (tl_2022_us_county.json, -z0 --extend-zooms-if-still-dropping,
median of 5 runs on macOS arm64): 8.5s, vs 10.6s with shared_ptr
and 8.7s on the pre-refactor C baseline.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fix preprocessor mistakes identified by Copilot

* Make indent

* Skip non-string metadata.json entries instead of reading them as strings

dirmeta2tmp() warned about a metadata entry that was not a string/string
pair and then read it as a string anyway. Under the new type-tagged
accessors that trips the assert in json_object::string(); before them it
reinterpreted the node's storage as a char pointer, which segfaulted for
most values. Either way, tippecanoe-decode and tile-join could not read a
directory tileset whose metadata.json had a numeric minzoom or a nested
object, which is common in metadata.json files written by other tools.

Add the missing continue, and cover it in raw-tiles-test.

pmtilesmeta2tmp() handles the same case correctly but read the key with
string() before its own JSON_STRING check, so the assert would have fired
ahead of the check meant to catch a bad key. Hoist the check above the
read. The parser rejects non-string hash keys, so this is unreachable in
practice; the ordering is what makes the check meaningful.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017KNxyHKasyWrWcvre2yK4r

* Don't redefine _GNU_SOURCE in the C++ jsonpull port

The `#define _GNU_SOURCE` carried over from jsonpull.c, where it was
needed to get asprintf() declared. g++ already defines _GNU_SOURCE on the
command line for C++ translation units, so redefining it warns:

    jsonpull/jsonpull.cpp:1: warning: "_GNU_SOURCE" redefined

Guard the define rather than drop it, so platforms whose C++ driver does
not predefine it still get asprintf() declared.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017KNxyHKasyWrWcvre2yK4r

* Add a unit test for json_disconnect

json_disconnect() is documented in jsonpull.h as the supported way to
splice a subtree out of the parser's tree and take ownership of it, but
nothing calls it: read_filter() and parse_filter() used to, and now get
the same guarantee from json_read_tree() clearing back-pointers on the way
out. Cover the behavior rather than leave the primitive dead and untested.

The test pins that the subtree is removed from its parent, that the parser
keeps the rest of the tree, and that the detached subtree stays readable
after the json_pull is destroyed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017KNxyHKasyWrWcvre2yK4r

* Correct two stale comments in the jsonpull port

jsonpull.h said a json_number is 40 bytes; it is 32 (json_object is 24,
and the repr discriminator fits in the base class's tail padding, so the
8-byte union lands at offset 24).

plugin.cpp's parse_feature() said `j` is freed only just before returning
or as jp->root at end of stream, but there is a third json_free(j) at the
bottom of the loop, for a complete Feature whose geometry came out empty.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017KNxyHKasyWrWcvre2yK4r

* Add a changelog entry and bump the version for the jsonpull rewrite

The rewrite is meant to be behavior-preserving, but it carries four
user-visible bug fixes that warrant release notes: tippecanoe-json-tool
--extract on a numeric attribute, surrogate-pair decoding, tile-join
reading a non-string tilejson field type, and non-string values in a
directory tileset's metadata.json.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017KNxyHKasyWrWcvre2yK4r

* Encode U+FFFF as three bytes instead of an overlong four

The \uXXXX decoder tested `ch < 0xFFFF` before taking the three-byte UTF-8
path, so U+FFFF itself fell through to the four-byte branch and came out as
F0 8F BF BF -- an overlong, and therefore invalid, encoding of a code point
that fits in three bytes.

check_utf8() only checks that continuation bytes look like continuation
bytes, not that a sequence is the shortest form, so nothing downstream
noticed: a GeoJSON attribute containing U+FFFF put invalid UTF-8 into the
output tile, where a strict consumer would reject it.

Since `ch` is parsed from exactly four hex digits it cannot exceed 0xFFFF
on its own, so after this change the four-byte branch is reached only for a
code point assembled from a surrogate pair, which is the only way to name
one above the BMP.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017KNxyHKasyWrWcvre2yK4r

* Keep the parent links inside a detached jsonpull subtree

json_read_tree() and json_disconnect() cleared both back-pointers on every
node of the subtree they handed out. Clearing `parser` throughout is
necessary -- the json_pull can be destroyed while the subtree lives on, so
a surviving `parser` would dangle -- but clearing `parent` throughout cost
more than it bought.

`parent` is a non-owning raw pointer, so keeping it cannot form a reference
cycle or keep anything alive; there is nothing to leak. And within a
detached subtree it refers to nodes the caller now owns as a single unit,
so it stays valid for exactly as long as the subtree itself. Clearing it
only made the tree unwalkable upwards, and made json_free() and
json_disconnect() silently no-ops on interior nodes of a detached tree,
since both find a node's owner through o->parent.

So clear `parser` everywhere and clear `parent` on the detached root alone,
which is the one that pointed out of the subtree at a node the parser still
owns. Split the old clear_back_pointers() into clear_parser_pointers() plus
a detach_subtree() wrapper that adds the root's `parent`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017KNxyHKasyWrWcvre2yK4r

* Cover the U+FFFF encoding and detached-tree parent links

Each of the new assertions fails against the previous behavior, so they
pin the two fixes rather than merely passing alongside them:

  - the U+FFFF test, plus the U+FFFE boundary below it and a surrogate pair
    above it, so the three-byte and four-byte paths are both held in place
  - json_disconnect() leaving the parent links inside the subtree intact
    while clearing the root's
  - json_free() pruning an interior node of a tree whose parser is already
    gone, which only works because those links survive
  - json_free() of a hash value leaving the key paired with a JSON_NULL
    placeholder, which is the documented behavior and not a removal

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017KNxyHKasyWrWcvre2yK4r

* Address review notes in jsonpull itself

- json_stringify walked c_str(), so it truncated at an embedded NUL even
  though values are std::string now and carry one through faithfully.
  Range over the string instead; the existing control-character branch
  already escapes a NUL like any other, so the output stays valid JSON.
- Assert that the hash has an entry waiting before add_object() assigns to
  entries().back(). It always does -- JSON_VALUE is only set by a colon,
  which requires a pushed key -- but the derivation is not local.
- Drop fabricate_object(), a pass-through to make_object() with the
  arguments reordered, kept only to preserve the old C name.
- Inline the string_append / string_append_c wrappers over push_back and
  append, and note that json_print_one's JSON_HASH and JSON_ARRAY branches
  are unreachable, since json_print handles both itself.
- json_hash_get's comment said nullptr meant "the matching value is null",
  which reads as JSON null. A JSON null comes back as a JSON_NULL node;
  nullptr means the value slot is not filled in yet.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017KNxyHKasyWrWcvre2yK4r

* Tidy jsonpull call sites flagged in review

- geojson.cpp and attribute.cpp passed key_pool::pool() and
  set_attribute_accum() a c_str() from a std::string, forcing a needless
  reconstruction (and truncating at an embedded NUL). Both overloads take
  std::string, so pass it directly. The geojson.cpp one is the hottest
  loop in the program.
- Replace the hand-maintained counters beside range-for loops in
  attribute.cpp, main.cpp and tile-join.cpp with indexed loops, since the
  index is only wanted for error messages.
- parse_json_args took json_pull_ptr by value and then copied it, costing
  two refcount bumps per construction. Move it.
- Assert that the parser is still attached where geojson.cpp reads
  geometry->parser->line. Only json_read results reach it today, but
  json_read_tree and json_disconnect now clear every parser pointer, so a
  detached tree would null-deref there instead of tripping an assert.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017KNxyHKasyWrWcvre2yK4r

* Pin the array-splicing fix, and close four test gaps

The existing pruning test does not discriminate: json_read hands back each
container as it completes, so the node it frees is always the most recently
added element of its parent -- the one case the old element-count-vs-byte-
count memmove got right, because it then moved zero bytes. Widening that
test to more elements does not change this; the shape is what matters, not
the size. Verified: the eight-element streaming variant still passes
against the pre-fix code.

Add a test that builds the array first and then prunes element 0 of eight,
asserting the identity of every survivor rather than just the resulting
count. That fails against the pre-fix code deterministically, with
arr[0] == arr[1] and the last element dropped. Note the limitation on the
streaming test so the next reader does not try to strengthen it in place.

Also cover, all previously untested:

- json_free of a hash key, and of both halves of a pair, where the entry
  survives with a JSON_NULL stand-in until both are gone
- repeated json_read_tree over a line-delimited stream, which is what the
  filter loaders and -L / -E do, asserting each detached tree survives the
  next read and the parser's destruction
- json_stringify of a partially-parsed tree, the json_context error path
- json_stringify across an embedded NUL, which fails against the c_str()
  walk this branch replaces

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017KNxyHKasyWrWcvre2yK4r

* Add changelog entries for three unadvertised fixes

The array-splicing fix goes first: it is a memory-corruption fix, and it is
the strongest illustration of why the ownership model is worth having,
since it is exactly the failure the model makes unrepresentable.

Also the uninitialized read when a filter emitted "properties": null, and
the evaluator.hpp include guard that defined EVALUATOR HPP and so never
guarded anything.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017KNxyHKasyWrWcvre2yK4r

* Consolidate the jsonpull comments

Comments were 25% of the added lines, and the ownership model was spelled
out in five places. Collect it into one block at the top of jsonpull.h and
point at it from the rest, cutting the ratio to 14% and the total by about
200 lines.

Removed the duplicate explanations of the deleter dispatch, of what detach
does to the back-pointers, and of "json_read returns intermediate
containers, do not free them". Trimmed the comments that argued for a
choice rather than described the code -- the reserve(2) / reserve(4)
rationales, the string-buffer copy, the pmtiles check ordering -- to a line
each, and shortened the test preambles, keeping the parts that say why a
test is shaped the way it is.

No code changes; the test suite is unchanged in both configurations.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017KNxyHKasyWrWcvre2yK4r

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-08-13 21:27:07 -07:00
15 changed files with 2596 additions and 82 deletions
+27
View File
@@ -1,3 +1,30 @@
# 2.83.0
* Speed up `--no-simplification-of-shared-nodes` by checking each vertex
against the global list of shared nodes only once, before tiling begins,
instead of again in every tile at every zoom level. Each vertex now carries
whether it is a shared node, in the upper bits of its serialized operation
byte and in a new field of `draw`, through clipping and into the geometry
for the next zoom level. Vertices that are already being kept, because they
begin a ring or are on the tile boundary, are not looked up at all.
* Points that clipping creates along a feature's edges, and the vertices
of tiny polygon placeholders, are no longer considered to be shared nodes,
since they are not vertices of the original geometry. This could only
change the output where a vertex of some other feature happens to fall
exactly on one of these new points, and means that only
vertices that come back from a prefilter, or that are created by polygon
cleaning, still need to be looked up in the list of shared nodes during tiling.
* Make the remaining lookups of shared nodes faster: sort the list of nodes
by quadkey, as its comment always said, so that nearby vertices are near
each other in the list; search it with `std::lower_bound` instead of `bsearch`;
and size the Bloom filter in front of it by the number of nodes, with three
bits for each node within one 64-bit word, so that it usually fits in the cache.
* Spread the marking of shared nodes across all the CPUs even when all
the features were read by one reader, by dividing the geometry into
ranges at feature boundaries instead of giving each reader's geometry
to its own thread.
* Speed up `encode_quadkey` with a branch-free bit interleave.
# 2.82.0
* Fix corruption of a JSON array when a non-final element was removed from it.
+78 -31
View File
@@ -16,10 +16,29 @@
#include "projection.hpp"
#include "read_json.hpp"
static std::vector<std::pair<double, double>> clip_poly1(std::vector<std::pair<double, double>> &geom,
long long minx, long long miny, long long maxx, long long maxy,
long long ax, long long ay, long long bx, long long by, drawvec &edge_nodes,
bool prevent_simplify_shared_nodes);
// A vertex being clipped, which remembers whether it is a shared node.
struct clip_point_d {
double first;
double second;
signed char node = NODE_UNKNOWN;
clip_point_d()
: first(0), second(0) {
}
clip_point_d(double x, double y)
: first(x), second(y) {
}
clip_point_d(double x, double y, signed char n)
: first(x), second(y), node(n) {
}
};
static std::vector<clip_point_d> clip_poly1(std::vector<clip_point_d> &geom,
long long minx, long long miny, long long maxx, long long maxy,
long long ax, long long ay, long long bx, long long by, drawvec &edge_nodes,
bool prevent_simplify_shared_nodes);
drawvec simple_clip_poly(drawvec &geom, long long minx, long long miny, long long maxx, long long maxy,
long long ax, long long ay, long long bx, long long by, drawvec &edge_nodes, bool prevent_simplify_shared_nodes) {
@@ -37,11 +56,11 @@ drawvec simple_clip_poly(drawvec &geom, long long minx, long long miny, long lon
}
}
std::vector<std::pair<double, double>> tmp;
std::vector<clip_point_d> tmp;
for (size_t k = i; k < j; k++) {
double x = geom[k].x;
double y = geom[k].y;
tmp.emplace_back(x, y);
tmp.emplace_back(x, y, geom[k].node);
}
tmp = clip_poly1(tmp, minx, miny, maxx, maxy, ax, ay, bx, by, edge_nodes, prevent_simplify_shared_nodes);
if (tmp.size() > 0) {
@@ -52,9 +71,9 @@ drawvec simple_clip_poly(drawvec &geom, long long minx, long long miny, long lon
}
for (size_t k = 0; k < tmp.size(); k++) {
if (k == 0) {
out.push_back(draw(VT_MOVETO, std::round(tmp[k].first), std::round(tmp[k].second)));
out.push_back(draw(VT_MOVETO, std::round(tmp[k].first), std::round(tmp[k].second), tmp[k].node));
} else {
out.push_back(draw(VT_LINETO, std::round(tmp[k].first), std::round(tmp[k].second)));
out.push_back(draw(VT_LINETO, std::round(tmp[k].first), std::round(tmp[k].second), tmp[k].node));
}
}
@@ -126,13 +145,15 @@ drawvec clip_lines(drawvec &geom, long long minx, long long miny, long long maxx
int c = clip(&x1, &y1, &x2, &y2, minx, miny, maxx, maxy);
if (c > 1) { // clipped
out.push_back(draw(VT_MOVETO, x1, y1));
out.push_back(draw(VT_LINETO, x2, y2));
out.push_back(draw(VT_MOVETO, geom[i].x, geom[i].y));
// endpoints that weren't moved by clipping keep their node state;
// new endpoints along the segment aren't original vertices, so aren't shared nodes
out.push_back(draw(VT_MOVETO, x1, y1, (x1 == geom[i - 1].x && y1 == geom[i - 1].y) ? geom[i - 1].node : NODE_NOT_SHARED));
out.push_back(draw(VT_LINETO, x2, y2, (x2 == geom[i].x && y2 == geom[i].y) ? geom[i].node : NODE_NOT_SHARED));
out.push_back(draw(VT_MOVETO, geom[i].x, geom[i].y, geom[i].node));
} else if (c == 1) { // unchanged
out.push_back(geom[i]);
} else { // clipped away entirely
out.push_back(draw(VT_MOVETO, geom[i].x, geom[i].y));
out.push_back(draw(VT_MOVETO, geom[i].x, geom[i].y, geom[i].node));
}
} else {
out.push_back(geom[i]);
@@ -739,7 +760,7 @@ drawvec close_poly(drawvec &geom) {
return out;
}
static bool inside(std::pair<double, double> d, int edge, long long minx, long long miny, long long maxx, long long maxy) {
static bool inside(clip_point_d const &d, int edge, long long minx, long long miny, long long maxx, long long maxy) {
switch (edge) {
case 0: // top
return d.second > miny;
@@ -758,41 +779,64 @@ static bool inside(std::pair<double, double> d, int edge, long long minx, long l
exit(EXIT_FAILURE);
}
static std::pair<double, double> intersect(std::pair<double, double> a, std::pair<double, double> b, int edge, long long minx, long long miny, long long maxx, long long maxy) {
static clip_point_d intersect1(clip_point_d const &a, clip_point_d const &b, int edge, long long minx, long long miny, long long maxx, long long maxy) {
switch (edge) {
case 0: // top
return std::pair<double, double>((a.first + (double) (b.first - a.first) * (miny - a.second) / (b.second - a.second)), miny);
return clip_point_d((a.first + (double) (b.first - a.first) * (miny - a.second) / (b.second - a.second)), miny);
case 1: // right
return std::pair<double, double>(maxx, (a.second + (double) (b.second - a.second) * (maxx - a.first) / (b.first - a.first)));
return clip_point_d(maxx, (a.second + (double) (b.second - a.second) * (maxx - a.first) / (b.first - a.first)));
case 2: // bottom
return std::pair<double, double>((a.first + (double) (b.first - a.first) * (maxy - a.second) / (b.second - a.second)), maxy);
return clip_point_d((a.first + (double) (b.first - a.first) * (maxy - a.second) / (b.second - a.second)), maxy);
case 3: // left
return std::pair<double, double>(minx, (a.second + (double) (b.second - a.second) * (minx - a.first) / (b.first - a.first)));
return clip_point_d(minx, (a.second + (double) (b.second - a.second) * (minx - a.first) / (b.first - a.first)));
}
fprintf(stderr, "internal error intersecting\n");
exit(EXIT_FAILURE);
}
// If the intersection is at one of the endpoints of the segment,
// it is the same vertex, and has the same node state.
//
// Otherwise it is a new point along the segment, which is not a vertex
// of the original geometry, so it is treated as not being a shared node.
// (It could only be one if some other feature had a vertex exactly where
// this feature's edge crosses the clipping line, without this feature
// having a vertex there too.)
static clip_point_d intersect(clip_point_d const &a, clip_point_d const &b, int edge, long long minx, long long miny, long long maxx, long long maxy) {
clip_point_d p = intersect1(a, b, edge, minx, miny, maxx, maxy);
double x = std::round(p.first), y = std::round(p.second);
if (x == a.first && y == a.second) {
p.node = a.node;
} else if (x == b.first && y == b.second) {
p.node = b.node;
} else {
p.node = NODE_NOT_SHARED;
}
return p;
}
// http://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm
static std::vector<std::pair<double, double>> clip_poly1(std::vector<std::pair<double, double>> &geom,
long long minx, long long miny, long long maxx, long long maxy,
long long ax, long long ay, long long bx, long long by, drawvec &edge_nodes,
bool prevent_simplify_shared_nodes) {
std::vector<std::pair<double, double>> out = geom;
static std::vector<clip_point_d> clip_poly1(std::vector<clip_point_d> &geom,
long long minx, long long miny, long long maxx, long long maxy,
long long ax, long long ay, long long bx, long long by, drawvec &edge_nodes,
bool prevent_simplify_shared_nodes) {
std::vector<clip_point_d> out = geom;
for (int edge = 0; edge < 4; edge++) {
if (out.size() > 0) {
std::vector<std::pair<double, double>> in = out;
std::vector<clip_point_d> in = out;
out.resize(0);
std::pair<double, double> S = in[in.size() - 1];
clip_point_d S = in[in.size() - 1];
for (size_t e = 0; e < in.size(); e++) {
std::pair<double, double> E = in[e];
clip_point_d E = in[e];
if (!inside(S, edge, minx, miny, maxx, maxy)) {
// was outside the buffer
@@ -1087,11 +1131,14 @@ drawvec reduce_tiny_poly(drawvec const &geom, int z, int detail, bool *still_nee
if (area > 0 && *accum_area > pixel * pixel) {
// XXX use centroid;
out.emplace_back(VT_MOVETO, geom[i].x - pixel / 2, geom[i].y - pixel / 2);
out.emplace_back(VT_LINETO, geom[i].x - pixel / 2 + pixel, geom[i].y - pixel / 2);
out.emplace_back(VT_LINETO, geom[i].x - pixel / 2 + pixel, geom[i].y - pixel / 2 + pixel);
out.emplace_back(VT_LINETO, geom[i].x - pixel / 2, geom[i].y - pixel / 2 + pixel);
out.emplace_back(VT_LINETO, geom[i].x - pixel / 2, geom[i].y - pixel / 2);
// This placeholder is synthetic, so none of its vertices
// can be shared nodes from the original geometry.
out.emplace_back(VT_MOVETO, geom[i].x - pixel / 2, geom[i].y - pixel / 2, NODE_NOT_SHARED);
out.emplace_back(VT_LINETO, geom[i].x - pixel / 2 + pixel, geom[i].y - pixel / 2, NODE_NOT_SHARED);
out.emplace_back(VT_LINETO, geom[i].x - pixel / 2 + pixel, geom[i].y - pixel / 2 + pixel, NODE_NOT_SHARED);
out.emplace_back(VT_LINETO, geom[i].x - pixel / 2, geom[i].y - pixel / 2 + pixel, NODE_NOT_SHARED);
out.emplace_back(VT_LINETO, geom[i].x - pixel / 2, geom[i].y - pixel / 2, NODE_NOT_SHARED);
*accum_area -= pixel * pixel;
}
+105 -19
View File
@@ -7,6 +7,7 @@
#include <cstdio>
#include <unistd.h>
#include <cmath>
#include <cstring>
#include <limits.h>
#include <sqlite3.h>
#include <mapbox/geometry/point.hpp>
@@ -37,6 +38,9 @@ drawvec decode_geometry(const char **meta, int z, unsigned tx, unsigned ty, long
break;
}
d.node = (d.op >> NODE_SHIFT) & NODE_MASK;
d.op &= OP_MASK;
if (d.op == VT_MOVETO || d.op == VT_LINETO) {
long long dx, dy;
@@ -216,6 +220,81 @@ drawvec impose_tile_boundaries(const drawvec &geom, long long extent) {
return out;
}
// Where a shared node goes in the Bloom filter: three bits, all within the same
// 64-bit word, so that checking for a node only touches one cache line.
static void shared_node_bloom_bits(unsigned long long index, size_t bloom_size, size_t *word, unsigned long long *mask) {
// splitmix64 finalizer, to spread out the index, whose low bits are
// mostly zero because of the geometry scale
unsigned long long h = index;
h ^= h >> 30;
h *= 0xBF58476D1CE4E5B9ULL;
h ^= h >> 27;
h *= 0x94D049BB133111EBULL;
h ^= h >> 31;
*word = ((h >> 32) * (unsigned long long) (bloom_size / sizeof(unsigned long long))) >> 32;
*mask = (1ULL << (h & 63)) | (1ULL << ((h >> 6) & 63)) | (1ULL << ((h >> 12) & 63));
}
void add_shared_node_to_bloom(std::string &shared_nodes_bloom, unsigned long long index) {
size_t word;
unsigned long long mask, bits;
shared_node_bloom_bits(index, shared_nodes_bloom.size(), &word, &mask);
memcpy(&bits, shared_nodes_bloom.data() + word * sizeof(bits), sizeof(bits));
bits |= mask;
memcpy(&shared_nodes_bloom[0] + word * sizeof(bits), &bits, sizeof(bits));
}
// Is the vertex at world coordinates wx, wy one of the nodes in the global list of shared nodes?
bool is_shared_node(long long wx, long long wy, struct node const *shared_nodes_map, size_t nodepos, std::string const &shared_nodes_bloom) {
struct node n;
n.index = encode_quadkey((unsigned) wx, (unsigned) wy);
size_t word;
unsigned long long mask, bits;
shared_node_bloom_bits(n.index, shared_nodes_bloom.size(), &word, &mask);
memcpy(&bits, shared_nodes_bloom.data() + word * sizeof(bits), sizeof(bits));
if ((bits & mask) == mask) {
struct node const *end = shared_nodes_map + nodepos / sizeof(node);
struct node const *found = std::lower_bound(shared_nodes_map, end, n.index, [](struct node const &a, unsigned long long b) {
return a.index < b;
});
if (found != end && found->index == n.index) {
return true;
}
}
return false;
}
// Operations like polygon cleaning that construct new geometries don't know about
// the node states of the vertices. But since the node state is a function only
// of the vertex's coordinates, any vertex in the output that has the same coordinates
// as a vertex in the input must have the same node state as that vertex did.
void restore_node_states(drawvec const &from, drawvec &to) {
drawvec known;
for (auto const &d : from) {
if ((d.op == VT_MOVETO || d.op == VT_LINETO) && d.node != NODE_UNKNOWN) {
known.push_back(d);
}
}
if (known.size() == 0) {
return;
}
std::sort(known.begin(), known.end());
for (auto &d : to) {
if ((d.op == VT_MOVETO || d.op == VT_LINETO) && d.node == NODE_UNKNOWN) {
auto pt = std::lower_bound(known.begin(), known.end(), d);
if (pt != known.end() && *pt == d) {
d.node = pt->node;
}
}
}
}
drawvec simplify_lines(drawvec &geom, int z, int tx, int ty, int detail, bool mark_tile_bounds, double simplification, size_t retain, drawvec const &shared_nodes, struct node *shared_nodes_map, size_t nodepos, std::string const &shared_nodes_bloom) {
int res = 1 << (32 - detail - z);
long long area = 1LL << (32 - z);
@@ -236,33 +315,40 @@ drawvec simplify_lines(drawvec &geom, int z, int tx, int ty, int detail, bool ma
// * the drawvec, which is nodes that were introduced during clipping to the tile edge,
// and which are in local tile coordinates
// * the shared_nodes_map, which was made globally before tiling began, and which
// is in global quadkey coordinates.
// To look through the latter, we need to offset and encode the coordinates
// of the feature we are simplifying.
// is in global coordinates.
//
// The vertices from the original geometry were already checked against the
// shared_nodes_map before tiling began, and carry the result of that check
// in their node state, so it is only vertices that have been created since then,
// by clipping or polygon cleaning, that need to be looked up in it here.
// To look through it, we need to offset the coordinates to global.
//
// If the shared_nodes_map is NULL, the caller doesn't want the global
// shared nodes to be preserved, so the node states are ignored too.
auto pt = std::lower_bound(shared_nodes.begin(), shared_nodes.end(), geom[i]);
if (pt != shared_nodes.end() && *pt == geom[i]) {
geom[i].necessary = true;
}
if (nodepos > 0) {
// offset to global
draw d = geom[i];
if (z != 0) {
d.x += tx * (1LL << (32 - z));
d.y += ty * (1LL << (32 - z));
// A vertex that is already necessary, because it is the start of a ring
// or on the tile boundary, doesn't need to be looked up, since the answer
// could only make it necessary again.
if (shared_nodes_map != NULL && nodepos > 0 && !geom[i].necessary) {
if (geom[i].node == NODE_UNKNOWN) {
// offset to global
long long wx = geom[i].x;
long long wy = geom[i].y;
if (z != 0) {
wx += tx * (1LL << (32 - z));
wy += ty * (1LL << (32 - z));
}
geom[i].node = is_shared_node(wx, wy, shared_nodes_map, nodepos, shared_nodes_bloom) ? NODE_SHARED : NODE_NOT_SHARED;
}
struct node n;
n.index = encode_vertex((unsigned) d.x, (unsigned) d.y);
size_t bloom_ix = n.index % (shared_nodes_bloom.size() * 8);
unsigned char bloom_mask = 1 << (bloom_ix & 7);
bloom_ix >>= 3;
if (shared_nodes_bloom[bloom_ix] & bloom_mask) {
if (bsearch(&n, shared_nodes_map, nodepos / sizeof(node), sizeof(node), nodecmp) != NULL) {
geom[i].necessary = true;
}
if (geom[i].node == NODE_SHARED) {
geom[i].necessary = true;
}
}
}
+34 -2
View File
@@ -20,6 +20,22 @@
#define VT_LINETO 2
#define VT_CLOSEPATH 7
// Whether a vertex is one of the shared nodes that --no-simplification-of-shared-nodes
// must not simplify away. This is a function only of the vertex's world coordinates,
// so it is found once, before tiling, from the global list of shared nodes, and then
// carried along with the vertex, instead of being looked up again for each tile.
// Vertices that are created during tiling, by clipping or polygon cleaning,
// start out NODE_UNKNOWN and are looked up in the global list if they are simplified.
#define NODE_UNKNOWN 0
#define NODE_NOT_SHARED 1
#define NODE_SHARED 2
// In serialized geometry, the node state is stored in the upper bits
// of the byte that holds each vertex's operation.
#define NODE_SHIFT 4
#define NODE_MASK 3
#define OP_MASK 0x0F
// The bitfield is to make sizeof(draw) be 16 instead of 24
// at the cost, apparently, of a 0.7% increase in running time
// for packing and unpacking.
@@ -28,19 +44,30 @@ struct draw {
signed char op;
long long y : 40;
signed char necessary;
signed char node;
draw(int nop, long long nx, long long ny)
: x(nx),
op(nop),
y(ny),
necessary(0) {
necessary(0),
node(NODE_UNKNOWN) {
}
draw(int nop, long long nx, long long ny, signed char nnode)
: x(nx),
op(nop),
y(ny),
necessary(0),
node(nnode) {
}
draw()
: x(0),
op(0),
y(0),
necessary(0) {
necessary(0),
node(NODE_UNKNOWN) {
}
bool operator<(draw const &s) const {
@@ -64,6 +91,8 @@ struct draw {
}
};
static_assert(sizeof(draw) == 16, "draw should still fit in 16 bytes");
typedef std::vector<draw> drawvec;
struct serial_feature;
@@ -81,6 +110,9 @@ drawvec stairstep(drawvec &geom, int z, int detail);
bool point_within_tile(long long x, long long y, int z);
int quick_check(const long long *bbox, int z, long long buffer);
void douglas_peucker(drawvec &geom, int start, int n, double e, size_t kept, size_t retain, bool prevent_simplify_shared_nodes);
void add_shared_node_to_bloom(std::string &shared_nodes_bloom, unsigned long long index);
bool is_shared_node(long long wx, long long wy, struct node const *shared_nodes_map, size_t nodepos, std::string const &shared_nodes_bloom);
void restore_node_states(drawvec const &from, drawvec &to);
drawvec simplify_lines(drawvec &geom, int z, int tx, int ty, int detail, bool mark_tile_bounds, double simplification, size_t retain, drawvec const &shared_nodes, struct node *shared_nodes_map, size_t nodepos, std::string const &shared_nodes_bloom);
drawvec reorder_lines(const drawvec &geom);
drawvec fix_polygon(const drawvec &geom, bool use_winding, bool reverse_winding);
+186 -7
View File
@@ -1233,6 +1233,140 @@ int vertexcmp(const void *void1, const void *void2) {
return 0;
}
// A range of one reader's geometry, beginning and ending at feature boundaries
struct mark_shared_nodes_range {
int geomfd;
long long start;
long long end;
};
struct mark_shared_nodes_arg {
std::vector<mark_shared_nodes_range> const *ranges;
std::atomic<size_t> *next_range;
unsigned *initial_x;
unsigned *initial_y;
node const *shared_nodes_map;
size_t nodepos;
std::string const *shared_nodes_bloom;
};
// Go through a range of the geometry that a reader serialized, marking each vertex
// with whether it is one of the shared nodes. The features are read in
// chunks and written back in place, since marking doesn't change their size.
static void mark_shared_nodes_in_range(mark_shared_nodes_arg *a, mark_shared_nodes_range const &r, std::string &buf) {
long long pos = r.start;
while (pos < r.end) {
long long want = std::min((long long) buf.size(), r.end - pos);
if (pread(r.geomfd, &buf[0], want, pos) != want) {
fprintf(stderr, "pread(geom): %s\n", strerror(errno));
exit(EXIT_READ);
}
// Mark each feature that is entirely within this chunk
long long used = 0;
while (used < want) {
// a feature length is at most 10 bytes of varint
if (want - used < 10 && pos + want < r.end) {
break;
}
const char *cp = buf.c_str() + used;
long long len;
deserialize_long_long(&cp, &len);
long long flen = (cp - buf.c_str()) - used;
if (used + flen + len > want) {
break;
}
mark_shared_nodes(&buf[0] + used + flen, len, a->initial_x, a->initial_y, a->shared_nodes_map, a->nodepos, *a->shared_nodes_bloom);
used += flen + len;
}
if (used == 0) {
// a single feature is bigger than the buffer
buf.resize(buf.size() * 2);
continue;
}
if (pwrite(r.geomfd, buf.c_str(), used, pos) != used) {
fprintf(stderr, "pwrite(geom): %s\n", strerror(errno));
exit(EXIT_WRITE);
}
pos += used;
}
}
// Each thread takes the next range that hasn't been marked yet, until there are none left
static void *run_mark_shared_nodes(void *v) {
mark_shared_nodes_arg *a = (mark_shared_nodes_arg *) v;
std::string buf;
buf.resize(4 * 1024 * 1024);
while (true) {
size_t which = (*a->next_range)++;
if (which >= a->ranges->size()) {
break;
}
mark_shared_nodes_in_range(a, (*a->ranges)[which], buf);
}
return NULL;
}
// Divide the geometry of all the readers into ranges of about the same size,
// at feature boundaries, which are found from the readers' indexes, so that
// the marking can be spread across all the CPUs even if all the features
// were read by one reader.
static std::vector<mark_shared_nodes_range> mark_shared_nodes_ranges(std::vector<struct reader> &readers) {
long long total = 0;
for (auto &r : readers) {
total += r.geompos;
}
long long target = std::max(total / (long long) (CPUS * 8), 1024LL * 1024);
std::vector<mark_shared_nodes_range> ranges;
for (auto &r : readers) {
long long indexsize = r.indexpos;
if (indexsize == 0) {
continue;
}
struct index *indexmap = (struct index *) mmap(NULL, indexsize, PROT_READ, MAP_PRIVATE, r.indexfd, 0);
if (indexmap == MAP_FAILED) {
perror("mmap index for marking nodes");
exit(EXIT_MEMORY);
}
madvise(indexmap, indexsize, MADV_SEQUENTIAL);
size_t n = indexsize / sizeof(struct index);
long long start = indexmap[0].start;
for (size_t i = 0; i < n; i++) {
if (i + 1 == n || indexmap[i].end - start >= target) {
ranges.push_back(mark_shared_nodes_range{r.geomfd, start, indexmap[i].end});
start = indexmap[i].end;
}
}
if (indexmap[0].start != 0 || indexmap[n - 1].end != r.geompos) {
fprintf(stderr, "Internal error: index covers geometry %lld to %lld, not 0 to %lld\n", indexmap[0].start, indexmap[n - 1].end, (long long) r.geompos);
exit(EXIT_IMPOSSIBLE);
}
if (munmap(indexmap, indexsize) != 0) {
perror("munmap index for marking nodes");
exit(EXIT_MEMORY);
}
}
return ranges;
}
double round_droprate(double r) {
return std::round(r * 100000.0) / 100000.0;
}
@@ -2057,7 +2191,7 @@ std::pair<int, metadata> read_input(std::vector<source> &sources, char *fname, i
#endif
struct node n;
n.index = encode_vertex((unsigned) x, (unsigned) y);
n.index = encode_quadkey((unsigned) x, (unsigned) y);
fwrite_check((char *) &n, sizeof(struct node), 1, readers[0].nodefile, &readers[0].nodepos, "vertices");
}
@@ -2071,8 +2205,8 @@ std::pair<int, metadata> read_input(std::vector<source> &sources, char *fname, i
fprintf(stderr, "Merging nodes \r");
}
// This is sized once the number of nodes is known, below
std::string shared_nodes_bloom;
shared_nodes_bloom.resize(34567891); // circa 34MB, size nowhere near a power of 2
// Sort nodes that can't be simplified away; scan the list to remove duplicates
@@ -2139,11 +2273,6 @@ std::pair<int, metadata> read_input(std::vector<source> &sources, char *fname, i
fwrite_check((void *) &here, sizeof(here), 1, shared_nodes, &nodepos, "shared nodes");
written = here;
size_t bloom_ix = here.index % (shared_nodes_bloom.size() * 8);
unsigned char bloom_mask = 1 << (bloom_ix & 7);
bloom_ix >>= 3;
shared_nodes_bloom[bloom_ix] |= bloom_mask;
#if 0
unsigned wx, wy;
decode_quadkey(here.index, &wx, &wy);
@@ -2162,11 +2291,61 @@ std::pair<int, metadata> read_input(std::vector<source> &sources, char *fname, i
perror("mmap nodes");
exit(EXIT_MEMORY);
}
// Size the Bloom filter at about 16 bits per node, so that for a moderate
// number of nodes it can stay in the cache while it is being checked,
// but no more than 32MB.
size_t nnodes = nodepos / sizeof(node);
size_t bloom_size = std::min(nnodes * 2, (size_t) 32 * 1024 * 1024);
bloom_size = std::max((bloom_size + 7) / 8 * 8, (size_t) 64);
shared_nodes_bloom.resize(bloom_size);
for (size_t i = 0; i < nnodes; i++) {
add_shared_node_to_bloom(shared_nodes_bloom, shared_nodes_map[i].index);
}
}
fclose(node_out);
}
// Mark the vertices of each feature with whether they are shared nodes,
// so that tiling doesn't need to look them up again for every tile.
if (nodepos > 0) {
if (!quiet) {
fprintf(stderr, "Marking nodes \r");
}
std::vector<mark_shared_nodes_range> ranges = mark_shared_nodes_ranges(readers);
std::atomic<size_t> next_range(0);
std::vector<pthread_t> pthreads(CPUS);
std::vector<mark_shared_nodes_arg> args(CPUS);
for (size_t i = 0; i < CPUS; i++) {
args[i].ranges = &ranges;
args[i].next_range = &next_range;
args[i].initial_x = initial_x.data();
args[i].initial_y = initial_y.data();
args[i].shared_nodes_map = shared_nodes_map;
args[i].nodepos = nodepos;
args[i].shared_nodes_bloom = &shared_nodes_bloom;
if (thread_create(&pthreads[i], NULL, run_mark_shared_nodes, &args[i]) != 0) {
perror("pthread_create");
exit(EXIT_PTHREAD);
}
}
for (size_t i = 0; i < CPUS; i++) {
void *retval;
if (pthread_join(pthreads[i], &retval) != 0) {
perror("pthread_join mark nodes");
}
}
}
if (!quiet) {
fprintf(stderr, "Merging index \r");
}
+13 -16
View File
@@ -156,19 +156,20 @@ void decode_hilbert(unsigned long long index, unsigned *wx, unsigned *wy) {
hilbert_d2xy(1LL << 32, index, wx, wy);
}
// Spread the 32 bits of v out into the even bits of a 64-bit value
static inline unsigned long long spread_bits(unsigned int v) {
unsigned long long x = v;
x = (x | (x << 16)) & 0x0000FFFF0000FFFFULL;
x = (x | (x << 8)) & 0x00FF00FF00FF00FFULL;
x = (x | (x << 4)) & 0x0F0F0F0F0F0F0F0FULL;
x = (x | (x << 2)) & 0x3333333333333333ULL;
x = (x | (x << 1)) & 0x5555555555555555ULL;
return x;
}
// Interleave the bits of wx and wy, with each bit of wx above the same bit of wy
unsigned long long encode_quadkey(unsigned int wx, unsigned int wy) {
unsigned long long out = 0;
int i;
for (i = 0; i < 32; i++) {
unsigned long long v = ((wx >> (32 - (i + 1))) & 1) << 1;
v |= (wy >> (32 - (i + 1))) & 1;
v = v << (64 - 2 * (i + 1));
out |= v;
}
return out;
return (spread_bits(wx) << 1) | spread_bits(wy);
}
static std::atomic<unsigned char> decodex[256];
@@ -217,7 +218,3 @@ void set_projection_or_exit(const char *optarg) {
exit(EXIT_ARGS);
}
}
unsigned long long encode_vertex(unsigned int wx, unsigned int wy) {
return (((unsigned long long) wx) << 32) | wy;
}
-1
View File
@@ -26,6 +26,5 @@ void decode_quadkey(unsigned long long index, unsigned *wx, unsigned *wy);
unsigned long long encode_hilbert(unsigned int wx, unsigned int wy);
void decode_hilbert(unsigned long long index, unsigned *wx, unsigned *wy);
unsigned long long encode_vertex(unsigned int wx, unsigned int wy);
#endif
+70 -2
View File
@@ -157,7 +157,7 @@ void deserialize_byte(const char **f, signed char *n) {
static void write_geometry(drawvec const &dv, std::string &out, long long wx, long long wy) {
for (size_t i = 0; i < dv.size(); i++) {
if (dv[i].op == VT_MOVETO || dv[i].op == VT_LINETO) {
serialize_byte(out, dv[i].op);
serialize_byte(out, dv[i].op | (dv[i].node << NODE_SHIFT));
serialize_long_long(out, dv[i].x - wx);
serialize_long_long(out, dv[i].y - wy);
wx = dv[i].x;
@@ -301,6 +301,74 @@ serial_feature deserialize_feature(std::string const &geoms, unsigned z, unsigne
return sf;
}
// Before tiling, mark each vertex of a serialized feature with whether
// it is one of the global shared nodes. This is done in place, by setting
// the node state in the upper bits of the byte that holds each vertex's operation,
// so the feature's length and position don't change.
void mark_shared_nodes(char *feature, size_t len, unsigned *initial_x, unsigned *initial_y, struct node const *shared_nodes_map, size_t nodepos, std::string const &shared_nodes_bloom) {
const char *cp = feature;
signed char t;
deserialize_byte(&cp, &t);
if (t != VT_LINE && t != VT_POLYGON) {
return;
}
long long layer, seq;
deserialize_long_long(&cp, &layer);
deserialize_long_long(&cp, &seq);
if (layer & (1 << FLAG_MINZOOM)) {
int minzoom;
deserialize_int(&cp, &minzoom);
}
if (layer & (1 << FLAG_MAXZOOM)) {
int maxzoom;
deserialize_int(&cp, &maxzoom);
}
if (layer & (1 << FLAG_ID)) {
unsigned long long id;
deserialize_ulong_long(&cp, &id);
}
int segment;
deserialize_int(&cp, &segment);
// the same accumulation as in decode_geometry()
long long wx = initial_x[segment], wy = initial_y[segment];
while (cp < feature + len) {
char *opp = feature + (cp - feature);
signed char op;
deserialize_byte(&cp, &op);
if (op == VT_END) {
return;
}
// the vertex may already have a node state, from clipping to --clip-bounding-box
op &= OP_MASK;
if (op == VT_MOVETO || op == VT_LINETO) {
long long dx, dy;
deserialize_long_long(&cp, &dx);
deserialize_long_long(&cp, &dy);
wx += dx * (1 << geometry_scale);
wy += dy * (1 << geometry_scale);
signed char node = is_shared_node(wx, wy, shared_nodes_map, nodepos, shared_nodes_bloom) ? NODE_SHARED : NODE_NOT_SHARED;
*opp = op | (node << NODE_SHIFT);
} else if (op != VT_CLOSEPATH) {
fprintf(stderr, "Internal error: unexpected geometry operation %d marking shared nodes\n", op);
exit(EXIT_IMPOSSIBLE);
}
}
fprintf(stderr, "Internal error: no end of geometry marking shared nodes\n");
exit(EXIT_IMPOSSIBLE);
}
static long long scale_geometry(struct serialization_state *sst, long long *bbox, drawvec &geom) {
long long offset = 0;
long long prev = 0;
@@ -407,7 +475,7 @@ static void add_scaled_node(struct reader *r, serialization_state *sst, draw g)
long long y = SHIFT_LEFT(g.y);
struct node n;
n.index = encode_vertex((unsigned) x, (unsigned) y);
n.index = encode_quadkey((unsigned) x, (unsigned) y);
fwrite_check((char *) &n, sizeof(struct node), 1, r->nodefile, &r->nodepos, sst->fname);
}
+1
View File
@@ -321,6 +321,7 @@ struct node {
};
int nodecmp(const void *void1, const void *void2);
void mark_shared_nodes(char *feature, size_t len, unsigned *initial_x, unsigned *initial_y, struct node const *shared_nodes_map, size_t nodepos, std::string const &shared_nodes_bloom);
int serialize_feature(struct serialization_state *sst, serial_feature &sf, std::string const &layername);
void coerce_value(std::string const &key, int &vt, std::string &val, std::unordered_map<std::string, int> const *attribute_types);
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+6 -3
View File
@@ -476,7 +476,7 @@ static void rewrite(serial_feature const &osf, int z, int nextzoom, int maxzoom,
drawvec geom2;
for (auto const &g : osf.geometry) {
geom2.emplace_back(g.op, SHIFT_RIGHT(g.x + sx), SHIFT_RIGHT(g.y + sy));
geom2.emplace_back(g.op, SHIFT_RIGHT(g.x + sx), SHIFT_RIGHT(g.y + sy), g.node);
}
for (xo = bbox2[0]; xo <= bbox2[2]; xo++) {
@@ -631,7 +631,9 @@ static double simplify_feature(serial_feature *p, drawvec const &shared_nodes, n
// unioned exactly
//
// don't try to scale up because these are still world coordinates
drawvec before = geom;
coalesce_polygon(geom, false);
restore_node_states(before, geom);
}
// continues to simplify to line_detail even if we have extra detail
@@ -979,13 +981,13 @@ static bool clip_to_tile(serial_feature &sf, int z, long long buffer) {
if (sf.bbox[0] <= (1LL << 32) * buffer / 256) {
for (size_t i = 0; i < n; i++) {
sf.geometry.push_back(draw(sf.geometry[i].op, sf.geometry[i].x + (1LL << 32), sf.geometry[i].y));
sf.geometry.push_back(draw(sf.geometry[i].op, sf.geometry[i].x + (1LL << 32), sf.geometry[i].y, sf.geometry[i].node));
}
}
if (sf.bbox[2] >= (1LL << 32) - ((1LL << 32) * buffer / 256)) {
for (size_t i = 0; i < n; i++) {
sf.geometry.push_back(draw(sf.geometry[i].op, sf.geometry[i].x - (1LL << 32), sf.geometry[i].y));
sf.geometry.push_back(draw(sf.geometry[i].op, sf.geometry[i].x - (1LL << 32), sf.geometry[i].y, sf.geometry[i].node));
}
}
@@ -2295,6 +2297,7 @@ long long write_tile(decompressor *geoms, std::atomic<long long> *geompos_in, ch
// don't scale up because this is still world coordinates
coalesce_polygon(to_clean, false);
restore_node_states(features[simplified_geometry_through]->geometry, to_clean);
features[simplified_geometry_through]->geometry = std::move(to_clean);
}
}
+37
View File
@@ -129,6 +129,43 @@ TEST_CASE("Bit reversal", "bit reversal") {
REQUIRE(bit_reverse(0xF3D912481E6A2C48) == 0x1234567812489BCF);
}
// The bit-at-a-time quadkey encoding that encode_quadkey() used to use
static unsigned long long reference_quadkey(unsigned int wx, unsigned int wy) {
unsigned long long out = 0;
for (int i = 0; i < 32; i++) {
unsigned long long v = ((wx >> (32 - (i + 1))) & 1) << 1;
v |= (wy >> (32 - (i + 1))) & 1;
v = v << (64 - 2 * (i + 1));
out |= v;
}
return out;
}
TEST_CASE("Quadkey encoding", "[projection]") {
unsigned int values[] = {0, 1, 2, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, 0x12345678, 0xDEADBEEF};
for (unsigned int x : values) {
for (unsigned int y : values) {
REQUIRE(encode_quadkey(x, y) == reference_quadkey(x, y));
unsigned wx, wy;
decode_quadkey(encode_quadkey(x, y), &wx, &wy);
REQUIRE(wx == x);
REQUIRE(wy == y);
}
}
unsigned long long seed = 1;
for (size_t i = 0; i < 10000; i++) {
seed = seed * 6364136223846793005ULL + 1442695040888963407ULL;
unsigned int x = seed >> 32;
unsigned int y = seed;
REQUIRE(encode_quadkey(x, y) == reference_quadkey(x, y));
}
}
TEST_CASE("line_is_too_small") {
drawvec dv;
dv.emplace_back(VT_MOVETO, 4243099709, 2683872952);
+1 -1
View File
@@ -1,6 +1,6 @@
#ifndef VERSION_HPP
#define VERSION_HPP
#define VERSION "v2.82.0"
#define VERSION "v2.83.0"
#endif