Modern Apps git

← Modern-Apps.git

tilecodec: body v12 shared point runs between parts (#planet5)

Commit
01f0b706cb458d631ae8a98beaaa391882f328b3
Author
Vayun Mathur <[email protected]>
When
2026-11-14 15:11 UTC (21 days ago)
Parents
18c1914
Owner asked for shared-arc topology for adjacent polygons. Two
polygons that touch trace their common edge in opposite directions,
which a byte-level LZ (zstd) cannot match; the v12 body stores such
runs once.

- Part flag 0x02 (v12 bodies only): the part's arena data is a token
  stream -- literal points (zigzag deltas, like the plain encoding),
  or a copy of L points of a part `back` parts earlier in the same
  layer, from point `start`, forwards or backwards. The writer
  (encode_layer_shared_runs) finds runs of >= 3 points through a
  vertex-pair index (forward and reversed keys, 16 candidates per
  pair) and keeps a part's plain encoding when its tokens are not
  smaller, so v12 never grows a body.
- serialize_into_v12 = v11 (MED heightmaps) + shared runs; Body::parse
  reads v12 into the identical model, so nothing above the codec
  changes. v10/v11 readers refuse body v12 by version.
- mamaps_planet5 writes v12 bodies (--verify compares the models).

Measured, US West aggressive with superblocks: 1,498,119,711 ->
1,481,853,450 B (-1.1%; raw bodies -0.9%). Smaller than the 15-19%
of z10-13 landtype vertices on shared edges suggested: most of those
are on clip edges and straight runs zstd already compresses. Planet
projection about -0.4 GB.

Verified: cargo test -p tilecodec --features write (202 pass; new: two
squares sharing a reversed edge plus a forward run shrink under v12
and parse to the same Body as v11); mamaps_planet5 --verify on US
West (every block member identical).

Diff

library/tilecodec/src/main/rust/src/mamaps/body.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body.rs b/library/tilecodec/src/main/rust/src/mamaps/body.rsindex b30dd6a745..b98f1f9327 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body.rs@@ -77,6 +77,6 @@ pub use model::{     ROOF_ORIENT_ACROSS, ROOF_ORIENT_ALONG, ROOF_ORIENT_MAX, ROOF_PYRAMIDAL, ROOF_SHAPE_MAX,     ROOF_SKILLION, };-pub use emit::{Scratch, serialize, serialize_into, serialize_into_v10, serialize_into_v11};+pub use emit::{Scratch, serialize, serialize_into, serialize_into_v10, serialize_into_v11, serialize_into_v12}; pub(crate) use codec::parse_layer; pub(crate) use tables::align4;
library/tilecodec/src/main/rust/src/mamaps/body/codec.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs b/library/tilecodec/src/main/rust/src/mamaps/body/codec.rsindex 1c47110d51..1a68bb81b6 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs@@ -112,10 +112,12 @@ impl Body {             && version != crate::mamaps::header::FORMAT_VERSION_V9             && version != crate::mamaps::header::FORMAT_VERSION_V10             && version != crate::mamaps::header::FORMAT_VERSION_V11+            && version != crate::mamaps::header::FORMAT_VERSION_V12         {             return err(format!("unsupported .mamaps body version {version}"));         }-        let v11 = version == crate::mamaps::header::FORMAT_VERSION_V11;+        let v12 = version == crate::mamaps::header::FORMAT_VERSION_V12;+        let v11 = version == crate::mamaps::header::FORMAT_VERSION_V11 || v12;         let v10 = version == crate::mamaps::header::FORMAT_VERSION_V10 || v11;         let raw_len = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]) as usize;         if raw_len != buf.len() {@@ -188,7 +190,7 @@ impl Body {                 return err("a .mamaps layer's payload is outside the body");             }             layers.push(if v10 {-                parse_layer_v10(layer_id, feature_count, &buf[offset..end])?+                parse_layer_v10(layer_id, feature_count, &buf[offset..end], v12)?             } else {                 parse_layer(layer_id, feature_count, &buf[offset..end])?             });@@ -433,7 +435,7 @@ fn parse_layer_v8(layer_id: u8, feature_count: usize, buf: &[u8]) -> Result<Laye /// writer used without a wire bit. Dropped fields read back as their defaults /// (zero names/details/transit/lanes), and `coord_start` is reconstructed by /// the arena walk โ€” v10 parts are validated contiguous exactly as v8 requires.-pub(crate) fn parse_layer_v10(layer_id: u8, feature_count: usize, buf: &[u8]) -> Result<Layer> {+pub(crate) fn parse_layer_v10(layer_id: u8, feature_count: usize, buf: &[u8], v12: bool) -> Result<Layer> {     use super::consts::{FEATURE_RECORD_MIN_LEN, FEATURE_RECORD_ROAD_LEN, PART_ENTRY_V10_LEN};     use super::emit_extra::{RecordClass, is_mixed_layer, record_class};     let class = record_class(layer_id);@@ -552,12 +554,14 @@ pub(crate) fn parse_layer_v10(layer_id: u8, feature_count: usize, buf: &[u8]) ->         return err("a .mamaps layer's parts run past its payload");     }     let mut parts = Vec::with_capacity(parts_needed);+    let mut token_parts: Vec<bool> = Vec::with_capacity(parts_needed);     let mut coords_needed = 0usize;     for i in 0..parts_needed {         let at = parts_at + i * PART_ENTRY_V10_LEN;         let point_count = u32::from(u16::from_le_bytes([buf[at], buf[at + 1]]));         let pflags = buf[at + 2];-        if pflags & !0x01 != 0 {+        let allowed = if v12 { 0x01 | super::emit_extra::PART_FLAG_SHARED_RUNS } else { 0x01 };+        if pflags & !allowed != 0 {             return err(format!("a .mamaps part sets unknown flags {pflags:#04x}"));         }         if buf[at + 3] != 0 {@@ -571,6 +575,7 @@ pub(crate) fn parse_layer_v10(layer_id: u8, feature_count: usize, buf: &[u8]) ->         // coord_start is reconstructed: v10 parts are contiguous by         // construction (the writer validates), so the Nth part starts where         // the arena walk ends.+        token_parts.push(pflags & super::emit_extra::PART_FLAG_SHARED_RUNS != 0);         let part = Part { coord_start: coords_needed as u32, point_count, winding };         let end = (part.coord_start as usize)             .checked_add(part.point_count as usize)@@ -586,7 +591,7 @@ pub(crate) fn parse_layer_v10(layer_id: u8, feature_count: usize, buf: &[u8]) ->     // Identical arena walk to v8: varint deltas restarting at each part.     let mut coords = Vec::with_capacity(coords_needed);     let mut reader = crate::proto::Reader::new(&buf[coords_at..]);-    for part in &parts {+    for (pi, part) in parts.iter().enumerate() {         if part.coord_start as usize != coords.len() {             return err(format!(                 "a .mamaps part claims to start at point {} but the arena is {} points in",@@ -594,6 +599,10 @@ pub(crate) fn parse_layer_v10(layer_id: u8, feature_count: usize, buf: &[u8]) ->                 coords.len(),             ));         }+        if token_parts[pi] {+            decode_part_tokens(&mut reader, &parts, pi, &mut coords)?;+            continue;+        }         let (mut x, mut y) = (0i32, 0i32);         for _ in 0..part.point_count {             x += zigzag(reader.uvarint()?);@@ -613,6 +622,58 @@ pub(crate) fn parse_layer_v10(layer_id: u8, feature_count: usize, buf: &[u8]) ->     Ok(Layer { layer_id, features, parts, coords }) } +/// Decode one v12 shared-run part (see `emit_extra::encode_layer_shared_runs`) onto `coords`.+fn decode_part_tokens(+    reader: &mut crate::proto::Reader<'_>,+    parts: &[Part],+    pi: usize,+    coords: &mut Vec<(i16, i16)>,+) -> Result<()> {+    let want = parts[pi].point_count as usize;+    let start_len = coords.len();+    let (mut x, mut y) = (0i32, 0i32);+    while coords.len() - start_len < want {+        let t = reader.uvarint()?;+        let len = (t >> 1) as usize;+        if len == 0 || coords.len() - start_len + len > want {+            return err("a .mamaps shared-run token overruns its part");+        }+        if t & 1 == 0 {+            for _ in 0..len {+                x += zigzag(reader.uvarint()?);+                y += zigzag(reader.uvarint()?);+                let (Ok(xx), Ok(yy)) = (i16::try_from(x), i16::try_from(y)) else {+                    return err("a .mamaps coordinate delta walks outside the extent an i16 holds");+                };+                coords.push((xx, yy));+            }+        } else {+            let r = reader.uvarint()?;+            let back = (r >> 1) as usize;+            let reverse = r & 1 != 0;+            let start = reader.uvarint()? as usize;+            if back == 0 || back > pi {+                return err("a .mamaps shared-run copy names a part that is not earlier");+            }+            let q = &parts[pi - back];+            let qs = q.coord_start as usize;+            let qn = q.point_count as usize;+            let ok = if reverse { start < qn && start + 1 >= len } else { start + len <= qn };+            if !ok {+                return err("a .mamaps shared-run copy runs outside its source part");+            }+            for t in 0..len {+                let p = if reverse { coords[qs + start - t] } else { coords[qs + start + t] };+                coords.push(p);+            }+            let last = coords[coords.len() - 1];+            x = last.0 as i32;+            y = last.1 as i32;+        }+    }+    Ok(())+}+ fn zigzag(v: u64) -> i32 {     crate::proto::zigzag_decode(v) as i32 }
library/tilecodec/src/main/rust/src/mamaps/body/emit.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/emit.rs b/library/tilecodec/src/main/rust/src/mamaps/body/emit.rsindex b7031ce457..13e08cbb64 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/emit.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/emit.rs@@ -51,6 +51,12 @@ pub fn serialize_into_v11<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&     serialize_into_version(body, scratch, crate::mamaps::header::FORMAT_VERSION_V11) } +/// Serialise a v12 body: v11 plus shared-run parts (see+/// [`crate::mamaps::header::FORMAT_VERSION_V12`]). Lossless; same model back.+pub fn serialize_into_v12<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [u8]> {+    serialize_into_version(body, scratch, crate::mamaps::header::FORMAT_VERSION_V12)+}+ fn serialize_into_version<'s>(     body: &Body,     scratch: &'s mut Scratch,@@ -289,8 +295,9 @@ fn serialize_into_version<'s>(         out.clear();         if version == crate::mamaps::header::FORMAT_VERSION_V10             || version == crate::mamaps::header::FORMAT_VERSION_V11+            || version == crate::mamaps::header::FORMAT_VERSION_V12         {-            write_v10_layer_payload(layer, out)?;+            write_v10_layer_payload(layer, out, version == crate::mamaps::header::FORMAT_VERSION_V12)?;         } else {             write_full_layer_payload(layer, out);         }@@ -320,8 +327,10 @@ fn serialize_into_version<'s>(         body_flags |= BODY_FLAG_BUILDING_TABLE;     }     let v10 = version == crate::mamaps::header::FORMAT_VERSION_V10-        || version == crate::mamaps::header::FORMAT_VERSION_V11;-    let v11 = version == crate::mamaps::header::FORMAT_VERSION_V11;+        || version == crate::mamaps::header::FORMAT_VERSION_V11+        || version == crate::mamaps::header::FORMAT_VERSION_V12;+    let v11 = version == crate::mamaps::header::FORMAT_VERSION_V11+        || version == crate::mamaps::header::FORMAT_VERSION_V12;     if body.heightmap.is_some() {         body_flags |= BODY_FLAG_HEIGHTMAP;     }
library/tilecodec/src/main/rust/src/mamaps/body/emit_extra.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/emit_extra.rs b/library/tilecodec/src/main/rust/src/mamaps/body/emit_extra.rsindex 8690839644..3609ec9a2e 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/emit_extra.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/emit_extra.rs@@ -139,6 +139,7 @@ pub(crate) fn write_full_layer_payload(layer: &Layer, out: &mut Vec<u8>) { pub(crate) fn write_v10_layer_payload(     layer: &Layer,     out: &mut Vec<u8>,+    shared_runs: bool, ) -> crate::proto::Result<()> {     use crate::proto::err;     let class = record_class(layer.layer_id);@@ -228,7 +229,14 @@ pub(crate) fn write_v10_layer_payload(             }         }     }-    for part in &layer.parts {+    // Each part's arena bytes: plain varint deltas, or (v12) the shared-run token stream when it+    // is smaller.+    let arenas: Vec<(Vec<u8>, bool)> = if shared_runs {+        encode_layer_shared_runs(layer)+    } else {+        layer.parts.iter().map(|p| (plain_part(layer.points(p)), false)).collect()+    };+    for (part, (_, tokens)) in layer.parts.iter().zip(&arenas) {         if part.point_count > u16::MAX as u32 {             return err(format!(                 "a v10 part holds {} points, past the u16 count",@@ -236,27 +244,138 @@ pub(crate) fn write_v10_layer_payload(             ));         }         out.extend_from_slice(&(part.point_count as u16).to_le_bytes());-        // Bit 0 is the winding (outer/hole); the rest is reserved zero.-        let flags = if part.winding == super::consts::WINDING_HOLE {+        // Bit 0 is the winding (outer/hole); bit 1 (v12) a shared-run token part; the rest is+        // reserved zero.+        let mut flags = if part.winding == super::consts::WINDING_HOLE {             1u8         } else {             0u8         };+        if *tokens {+            flags |= PART_FLAG_SHARED_RUNS;+        }         out.push(flags);         out.push(0);     }     while out.len() % 4 != 0 {         out.push(0);     }-    // The arena is byte-identical to the v8 layout: same parts order, same-    // varint deltas. Only the tables around it narrow.-    for part in &layer.parts {+    // The arena: parts in table order, each its plain varint deltas (byte-identical to the v8+    // layout) or its token stream.+    for (a, _) in &arenas {+        out.extend_from_slice(a);+    }+    Ok(())+}++/// Part flag (v12 bodies): the part's arena data is a shared-run token stream.+pub(crate) const PART_FLAG_SHARED_RUNS: u8 = 0x02;+/// The shortest run worth a copy token (a token costs three varints).+const MIN_SHARED_RUN: usize = 3;+/// Candidate positions examined per vertex pair (bounds the encoder's time on dense tiles).+const MAX_CANDIDATES: usize = 16;++fn plain_part(points: &[(i16, i16)]) -> Vec<u8> {+    let mut out = Vec::with_capacity(points.len() * 3);+    let (mut px, mut py) = (0i32, 0i32);+    for &(x, y) in points {+        push_uvarint(&mut out, crate::proto::zigzag_encode(x as i64 - px as i64));+        push_uvarint(&mut out, crate::proto::zigzag_encode(y as i64 - py as i64));+        (px, py) = (x as i32, y as i32);+    }+    out+}++/// Shared-run token streams for every part of `layer` (each `(bytes, is_tokens)`; a part keeps+/// its plain encoding when the tokens would not be smaller).+///+/// Token stream of one part, until `point_count` points are produced (deltas run from the+/// previous produced point; the part starts at (0, 0) like the plain encoding):+///+/// * `uvarint(L << 1)` then `L` literal points, each `zigzag(dx), zigzag(dy)`;+/// * `uvarint(L << 1 | 1)`, `uvarint(back << 1 | reverse)`, `uvarint(start)`: copy `L` points of+///   the part `back` parts earlier in this layer, from point `start`, forwards+///   (`start, start + 1, ...`) or backwards (`start, start - 1, ...`).+///+/// Adjacent polygons trace their common edge in opposite directions, which a byte-level LZ+/// (zstd) cannot see; a reversed copy can.+pub(crate) fn encode_layer_shared_runs(layer: &Layer) -> Vec<(Vec<u8>, bool)> {+    use std::collections::HashMap;+    type Pt = (i16, i16);+    let mut pairs: HashMap<(Pt, Pt), Vec<(u32, u32)>> = HashMap::new();+    let mut out = Vec::with_capacity(layer.parts.len());+    for (pi, part) in layer.parts.iter().enumerate() {+        let c = layer.points(part);+        let plain = plain_part(c);+        let mut tok = Vec::with_capacity(plain.len());+        let mut lit: Vec<Pt> = Vec::new();         let (mut px, mut py) = (0i32, 0i32);-        for &(x, y) in layer.points(part) {-            push_uvarint(out, crate::proto::zigzag_encode(x as i64 - px as i64));-            push_uvarint(out, crate::proto::zigzag_encode(y as i64 - py as i64));-            (px, py) = (x as i32, y as i32);+        let flush = |lit: &mut Vec<Pt>, tok: &mut Vec<u8>, px: &mut i32, py: &mut i32| {+            if lit.is_empty() {+                return;+            }+            push_uvarint(tok, (lit.len() as u64) << 1);+            for &(x, y) in lit.iter() {+                push_uvarint(tok, crate::proto::zigzag_encode(x as i64 - *px as i64));+                push_uvarint(tok, crate::proto::zigzag_encode(y as i64 - *py as i64));+                (*px, *py) = (x as i32, y as i32);+            }+            lit.clear();+        };+        let mut j = 0usize;+        while j < c.len() {+            let mut best: Option<(usize, u32, u32, bool)> = None; // (len, part, start, reverse)+            if j + 1 < c.len() {+                for (key, reverse) in [((c[j], c[j + 1]), false), ((c[j + 1], c[j]), true)] {+                    let Some(cands) = pairs.get(&key) else { continue };+                    for &(qp, qi) in cands.iter().rev().take(MAX_CANDIDATES) {+                        let q = layer.points(&layer.parts[qp as usize]);+                        let (start, len) = if !reverse {+                            let mut l = 0usize;+                            while j + l < c.len() && (qi as usize) + l < q.len() && c[j + l] == q[qi as usize + l] {+                                l += 1;+                            }+                            (qi, l)+                        } else {+                            // pair (q[qi], q[qi + 1]) == (c[j + 1], c[j]): walk q down from qi + 1+                            let s = qi as usize + 1;+                            let mut l = 0usize;+                            while j + l < c.len() && l <= s && c[j + l] == q[s - l] {+                                l += 1;+                            }+                            (s as u32, l)+                        };+                        if len >= MIN_SHARED_RUN && best.is_none_or(|b| len > b.0) {+                            best = Some((len, qp, start, reverse));+                        }+                    }+                }+            }+            match best {+                Some((len, qp, start, reverse)) => {+                    flush(&mut lit, &mut tok, &mut px, &mut py);+                    push_uvarint(&mut tok, ((len as u64) << 1) | 1);+                    push_uvarint(&mut tok, (((pi as u32 - qp) as u64) << 1) | u64::from(reverse));+                    push_uvarint(&mut tok, start as u64);+                    let last = c[j + len - 1];+                    (px, py) = (last.0 as i32, last.1 as i32);+                    j += len;+                }+                None => {+                    lit.push(c[j]);+                    j += 1;+                }+            }+        }+        flush(&mut lit, &mut tok, &mut px, &mut py);+        for i in 0..c.len().saturating_sub(1) {+            pairs.entry((c[i], c[i + 1])).or_default().push((pi as u32, i as u32));+        }+        if tok.len() < plain.len() {+            out.push((tok, true));+        } else {+            out.push((plain, false));         }     }-    Ok(())+    out }
library/tilecodec/src/main/rust/src/mamaps/header.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/header.rs b/library/tilecodec/src/main/rust/src/mamaps/header.rsindex 240450d661..61650d0eaa 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header.rs@@ -25,7 +25,7 @@ mod tests; pub use consts::{     COMPRESSION_DEFLATE, COMPRESSION_NONE, COMPRESSION_ZSTD, COMPRESSION_ZSTD_DICT, FLAG_BODIES_COMPRESSED,     FLAG_LEAF_LEN_64, FLAG_LEAVES_COMPRESSED, FLAG_RINGS_VALIDATED, FLAG_RUN_LENGTH_PRESENT, FORMAT_VERSION,-    FORMAT_VERSION_HEADER_V10, FORMAT_VERSION_HEADER_V11, FORMAT_VERSION_V9, FORMAT_VERSION_V10, FORMAT_VERSION_V11, HEADER_LEN, MAGIC, FLAG_SUPERBLOCKS,+    FORMAT_VERSION_HEADER_V10, FORMAT_VERSION_HEADER_V11, FORMAT_VERSION_V9, FORMAT_VERSION_V10, FORMAT_VERSION_V11, FORMAT_VERSION_V12, HEADER_LEN, MAGIC, FLAG_SUPERBLOCKS,     MAX_ZOOM, }; pub use types::Header;
library/tilecodec/src/main/rust/src/mamaps/header/consts.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/header/consts.rs b/library/tilecodec/src/main/rust/src/mamaps/header/consts.rsindex 0a1d61fc20..f73cdcf5b5 100644--- a/library/tilecodec/src/main/rust/src/mamaps/header/consts.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/header/consts.rs@@ -97,6 +97,11 @@ pub const FORMAT_VERSION_HEADER_V11: u8 = 11; /// residuals rather than raw `u16`s. Lossless (mod 2^16 arithmetic); only the entropy of the /// heightmap section changes, which is what makes it compress. Planet5 only. pub const FORMAT_VERSION_V11: u8 = 11;+/// Planet5 (~50 GB revision) body v12: v11 plus *shared-run* parts (part flag `0x02`): a part's+/// arena data is a token stream of literal points and copies of point runs from an earlier part+/// of the same layer, forwards or backwards -- the edge two adjacent polygons share is stored+/// once. Decodes to the identical model (lossless); see `body::emit_extra::encode_part_tokens`.+pub const FORMAT_VERSION_V12: u8 = 12;  pub const HEADER_LEN: usize = 128; 
library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs b/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rsindex 5cdac96b7b..bc843c775f 100644--- a/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs@@ -495,3 +495,43 @@ fn a_superblock_archive_round_trips_through_every_reader() {     // The superblock frame is stored once (content dedup): the file holds one copy.     assert_eq!(bytes.windows(frame.len()).filter(|w| *w == &frame[..]).count(), 1); }++#[test]+fn a_v12_body_shares_runs_between_adjacent_polygons_and_round_trips() {+    use crate::mamaps::body::{serialize_into_v11, serialize_into_v12, Body, Scratch};+    // Two squares sharing an edge (traced in opposite directions), plus a third copying a+    // forward run, in the landtype layer.+    let mut body = body_for(1);+    let lid = crate::mamaps::dict::LAYER_LANDTYPE;+    let mut layer = crate::mamaps::body::Layer::new(lid);+    let rings: Vec<Vec<(i16, i16)>> = vec![+        (0..40).map(|i| (i * 10, 0)).chain((0..40).map(|i| (400, i * 10))).chain([(0, 400)]).collect(),+        (0..40).rev().map(|i| (400, i * 10)).chain([(800, 0), (800, 400)]).collect(),+        (5..30).map(|i| (i * 10, 0)).chain([(100, -50)]).collect(),+    ];+    for (k, r) in rings.iter().enumerate() {+        let start = layer.coords.len() as u32;+        layer.coords.extend_from_slice(r);+        layer.parts.push(crate::mamaps::body::Part {+            coord_start: start,+            point_count: r.len() as u32,+            winding: crate::mamaps::body::WINDING_OUTER,+        });+        layer.features.push(crate::mamaps::body::Feature {+            kind: 1 + k as u16,+            geom_type: crate::mamaps::body::GEOM_POLYGON,+            parts_offset: k as u32,+            part_count: 1,+            ..body.layers[0].features[0]+        });+    }+    body.layers.retain(|l| l.layer_id != lid);+    body.layers.push(layer);+    body.layers.sort_by_key(|l| l.layer_id);+    let (mut s11, mut s12) = (Scratch::default(), Scratch::default());+    let b11 = serialize_into_v11(&body, &mut s11).expect("v11").to_vec();+    let b12 = serialize_into_v12(&body, &mut s12).expect("v12").to_vec();+    assert_eq!(b12[3], crate::mamaps::header::FORMAT_VERSION_V12);+    assert!(b12.len() < b11.len(), "shared runs must shrink the body ({} vs {})", b12.len(), b11.len());+    assert_eq!(Body::parse(&b12).expect("parse v12"), Body::parse(&b11).expect("parse v11"));+}
scripts/maps/tile_build/src/bin/mamaps_planet5.rs
diff --git a/scripts/maps/tile_build/src/bin/mamaps_planet5.rs b/scripts/maps/tile_build/src/bin/mamaps_planet5.rsindex 3f85355f0b..783f4c8531 100644--- a/scripts/maps/tile_build/src/bin/mamaps_planet5.rs+++ b/scripts/maps/tile_build/src/bin/mamaps_planet5.rs@@ -8,7 +8,8 @@ //! writes the same tiles as: //! //! * **v11 bodies** โ€” byte-for-byte the v10 body except that the heightmap is MED-residual coded-//!   (`tilecodec::mamaps::body::serialize_into_v11`); decodes to the identical `Body`;+//!   (`tilecodec::mamaps::body::serialize_into_v11`), and since the ~50 GB revision v12: shared+//!   point runs between parts of a layer (`serialize_into_v12`); decodes to the identical `Body`; //! * **dictionary zstd** โ€” one zstd dictionary trained per zoom band (z0-9, z10-11, z12, z13, //!   z14) on a stride sample of that band's v11 bodies, every body compressed at zstd-19 against //!   its band's dictionary; the dictionaries go into the v10 header's dictionary section.@@ -34,7 +35,7 @@ use std::sync::Arc; use std::time::Instant;  use rayon::prelude::*;-use tile_build::mamaps::body::{serialize_into_v11, Body, Scratch, BODY_HEADER_LEN};+use tile_build::mamaps::body::{serialize_into_v12, Body, Scratch, BODY_HEADER_LEN}; use tile_build::mamaps::header::{Header, FLAG_RINGS_VALIDATED}; use tile_build::mamaps::index; use tile_build::mamaps::read::decompress;@@ -114,9 +115,9 @@ fn to_v11(map: &[u8], hdr: &Header, off: u64, len: u32) -> Result<(Vec<u8>, Body             .map(|l| l.features.len())             .ok_or("a body with a marking convention and no roads layer")?;         b.carriageways = vec![(roads, vec![tile_build::mamaps::body::Carriageway::default(); n])];-        serialize_into_v11(&b, &mut s).map_err(|e| e.0)?.to_vec()+        serialize_into_v12(&b, &mut s).map_err(|e| e.0)?.to_vec()     } else {-        serialize_into_v11(&body, &mut s).map_err(|e| e.0)?.to_vec()+        serialize_into_v12(&body, &mut s).map_err(|e| e.0)?.to_vec()     };     Ok((v11, body)) }