Modern Apps git

← Modern-Apps.git

maps: planet-size prototype knobs in mamaps_build (#planet5)

Commit
86a4c352436d7e8dd86c31fadf009ce2d6d61598
Author
Vayun Mathur <[email protected]>
When
2026-11-13 23:22 UTC (22 days ago)
Parents
95a59d5
Planet-size study (exp/planet-size): the planet .mamaps is 81.3 GB and
the owner wants options toward ~50 GB. These are the build-side knobs
the US West experiments use. Every default reproduces today's archive
byte for byte (verified: a US West build with the new binary and no
flags has the same sha256 as one from origin/main, e708b548...), and a
non-default value is folded into the build id seed.

New mamaps_build flags (tiler::SizeOpts):
- --body-zstd LEVEL: zstd tile bodies (header compression 2). The
  shipped reader already decodes these with ruzstd (f8d24686d, before
  v2.6.11b and planet4), so this is not a format change. A thread-local
  zstd-rs encoder per worker (compress_body_zstd_level) avoids a
  per-tile encoder allocation, the same trap compress_body_with fixed
  for DEFLATE. Writer Options gains `zstd` to stamp the header byte.
- --dem-max-error M: error-bounded adaptive heightmaps. Each tile keeps
  the coarsest aligned sub-grid (dim 2/3/5/9) whose bilinear
  reconstruction stays within M/2 of the full dataset grid, then
  quantises elevations to a floor(M)-metre step, so max error <= M by
  construction. Replaces the relief-gated 5x5 coarsening, whose own
  error reaches 32 m. Dim is per tile on the wire already.
- --dem-px K: zoom-adaptive bound, K x the tile's ground resolution
  (m per 256-px pixel at its latitude), floored at --dem-max-error.
- --simplify-scale S: multiplies every below-z14 tolerance.
- --z14-tolerance T: DP floor at z14 for landtype, boundaries,
  buildings and washable roads; crisp roads keep full detail.
- --coord-quant: snap tile coordinates to a 2-unit grid at z13 and a
  4-unit grid at z<=12 (points and junction untouched), dropping
  collapsed parts with the same floors simplify::filter uses; stage C
  re-normalises rings afterwards.

Every build now prints per-zoom DEM error/size stats (DEMSTAT) against
the full dataset grid; the error over the grid nodes is the exact max
over the continuous bilinear surface because the coarse nodes are a
subset of the fine ones.

Verified: cargo test -p tilecodec --features write (191 pass),
cargo test -p mamaps_build (293 pass, incl. a new adaptive-grid
error-bound test); US West builds for each knob (see the planet-size
report).

Diff

library/tilecodec/src/main/rust/src/mamaps/write.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write.rs b/library/tilecodec/src/main/rust/src/mamaps/write.rsindex f8ede99efa..1ac36f145b 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write.rs@@ -60,7 +60,7 @@ mod tests;  pub use codec::{compress_body, compress_body_with, hash64}; #[cfg(feature = "write")]-pub use codec::compress_body_zstd;+pub use codec::{compress_body_zstd, compress_body_zstd_level}; pub use options::Options; pub use writer::{content_build_id, StreamWriter}; pub(crate) use writer::Pending;
library/tilecodec/src/main/rust/src/mamaps/write/codec.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write/codec.rs b/library/tilecodec/src/main/rust/src/mamaps/write/codec.rsindex 5d931d2365..f0ad7e6b23 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/codec.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/codec.rs@@ -60,6 +60,34 @@ pub fn compress_body_zstd(encoded: &[u8]) -> Vec<u8> {     out } +/// [`compress_body_zstd`] at a chosen level, reusing one encoder per thread.+///+/// Planet-size prototype (`mamaps_build --body-zstd LEVEL`). A fresh `zstd_rs::Compressor` per+/// body would allocate its match tables per tile on every core — the same trap+/// [`compress_body_with`] documents for DEFLATE — so each worker keeps one per level. Output is+/// a pure function of input + level (the encoder is reset per frame), so dedup and the content+/// build id behave exactly as with DEFLATE.+#[cfg(feature = "write")]+pub fn compress_body_zstd_level(encoded: &[u8], level: i32) -> Vec<u8> {+    use std::cell::RefCell;+    thread_local! {+        static ENC: RefCell<Option<(i32, zstd_rs::Compressor)>> = const { RefCell::new(None) };+    }+    let header_len = body::BODY_HEADER_LEN;+    let mut out = Vec::with_capacity(encoded.len());+    out.extend_from_slice(&encoded[..header_len]);+    ENC.with(|cell| {+        let mut slot = cell.borrow_mut();+        if slot.as_ref().map(|(l, _)| *l) != Some(level) {+            let cfg = zstd_rs::CompressionConfig { level, ..zstd_rs::CompressionConfig::DEFAULT };+            *slot = Some((level, zstd_rs::Compressor::new(cfg).expect("valid zstd level")));+        }+        let (_, enc) = slot.as_mut().expect("encoder");+        enc.compress(&encoded[header_len..], None, &mut out).expect("zstd encode of an in-memory body");+    });+    out+}+ /// FNV-1a. Only ever a bucket key — every hit is confirmed by comparing bytes — so it needs to be /// fast and well spread, not collision-proof. ///
library/tilecodec/src/main/rust/src/mamaps/write/options.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write/options.rs b/library/tilecodec/src/main/rust/src/mamaps/write/options.rsindex fd0c1009f5..7d4d5b4c7d 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/options.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/options.rs@@ -19,6 +19,9 @@ pub struct Options {     /// tiles and seed give an identical id on any machine; any changed tile byte changes it.     pub build_id_from_content: bool,     pub compress: bool,+    /// Bodies are zstd frames (header `compression` 2) rather than DEFLATE. Only meaningful with+    /// `compress`; the generator compresses (see `compress_body_zstd_level`) and appends stored.+    pub zstd: bool,     /// Store each leaf as one raw-DEFLATE frame rather than raw fixed-stride entries.     ///     /// The root stays raw either way — same 32-byte stride, same opening-prefix budget — and@@ -61,6 +64,7 @@ impl Default for Options {             build_id: 0,             build_id_from_content: false,             compress: true,+            zstd: false,             compress_leaves: true,             rings_validated: false,             leaf_entry_capacity: DEFAULT_LEAF_CAPACITY,
library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs b/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rsindex ba0faa4eba..1a0e0764ba 100644--- a/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/write/writer_extra.rs@@ -139,7 +139,13 @@ impl StreamWriter {          let header = Header {             flags,-            compression: if self.options.compress { COMPRESSION_DEFLATE } else { COMPRESSION_NONE },+            compression: if !self.options.compress {+                COMPRESSION_NONE+            } else if self.options.zstd {+                crate::mamaps::header::COMPRESSION_ZSTD+            } else {+                COMPRESSION_DEFLATE+            },             layer_count: dict::LAYERS.len() as u8,             min_zoom: self.options.min_zoom,             max_zoom: self.options.max_zoom,
scripts/maps/mamaps_build/src/dem.rs
diff --git a/scripts/maps/mamaps_build/src/dem.rs b/scripts/maps/mamaps_build/src/dem.rsindex 8d03aed112..11680bc2e9 100644--- a/scripts/maps/mamaps_build/src/dem.rs+++ b/scripts/maps/mamaps_build/src/dem.rs@@ -79,6 +79,149 @@ fn coarsen(samples: &[u16], dim: usize) -> Vec<u16> {     out } +/// The grid a tile carries, from its full-resolution `dim x dim` samples.+///+/// Default: today's relief gate (flat tiles coarsen to `FLAT_DIM`). Under+/// `--dem-max-error M` (planet-size prototype): the coarsest aligned sub-grid whose bilinear+/// reconstruction stays within `M/2` of the full grid, then elevations quantised to a+/// `floor(M)`-metre step (rounding error <= M/2), so the total error is <= M metres by+/// construction — flat ground collapses to 2x2, mountains keep 9x9. Either way the emitted+/// grid's error against the full grid is recorded in [`DEM_STATS`].+fn finish_grid(z: u8, y: u64, samples: &[u16], dim: u16) -> Heightmap {+    let o = crate::tiler::size_opts();+    let tol = if o.dem_px > 0.0 {+        let lat = tile_y_to_lat(y as f64 + 0.5, z);+        let m_per_px = 156_543.033_92 * lat.to_radians().cos() / (1u64 << z) as f64;+        (o.dem_px * m_per_px).max(o.dem_max_error_m.max(1.0))+    } else {+        o.dem_max_error_m+    };+    let full = Heightmap { dim, samples: samples.to_vec() };+    let out = if tol > 0.0 {+        adapt_grid(&full, tol)+    } else if relief(samples) <= FLAT_RELIEF_M && dim >= FLAT_DIM {+        Heightmap { dim: FLAT_DIM, samples: coarsen(samples, dim as usize) }+    } else {+        full.clone()+    };+    DEM_STATS.record(z, &full, &out);+    out+}++fn bilinear_at(g: &[u16], dg: usize, fr: f64, fc: f64) -> f64 {+    let gr = fr * (dg - 1) as f64;+    let gc = fc * (dg - 1) as f64;+    let r0 = (gr.floor() as usize).min(dg - 1);+    let c0 = (gc.floor() as usize).min(dg - 1);+    let r1 = (r0 + 1).min(dg - 1);+    let c1 = (c0 + 1).min(dg - 1);+    let (fy, fx) = (gr - r0 as f64, gc - c0 as f64);+    let at = |r: usize, c: usize| g[r * dg + c] as f64;+    let top = at(r0, c0) * (1.0 - fx) + at(r0, c1) * fx;+    let bot = at(r1, c0) * (1.0 - fx) + at(r1, c1) * fx;+    top * (1.0 - fy) + bot * fy+}++/// Max abs and sum of squared error of `new` against `full`, at every full-grid node. Both are+/// bilinear surfaces and the coarse nodes are a subset of the fine ones, so the difference is+/// bilinear inside every fine cell: the max over the nodes is the max over the whole surface.+fn grid_error(full: &Heightmap, new: &Heightmap) -> (f64, f64) {+    let d = full.dim as usize;+    let dn = new.dim as usize;+    let (mut mx, mut ss) = (0.0f64, 0.0f64);+    for r in 0..d {+        for c in 0..d {+            let e = (bilinear_at(&new.samples, dn, r as f64 / (d - 1) as f64, c as f64 / (d - 1) as f64)+                - full.samples[r * d + c] as f64)+                .abs();+            mx = mx.max(e);+            ss += e * e;+        }+    }+    (mx, ss)+}++fn adapt_grid(full: &Heightmap, tol: f64) -> Heightmap {+    let d = full.dim as usize;+    let mut pick = full.clone();+    for dn in (2..=d).filter(|dn| (d - 1) % (dn - 1) == 0) {+        let mut sub = Vec::with_capacity(dn * dn);+        for r in 0..dn {+            for c in 0..dn {+                sub.push(full.samples[(r * (d - 1) / (dn - 1)) * d + c * (d - 1) / (dn - 1)]);+            }+        }+        let cand = Heightmap { dim: dn as u16, samples: sub };+        if grid_error(full, &cand).0 <= tol / 2.0 + 1e-9 {+            pick = cand;+            break;+        }+    }+    let q = tol.floor().max(1.0) as i32;+    if q > 1 {+        for v in &mut pick.samples {+            let m = *v as i32 - SEA_LEVEL as i32;+            let r = ((m as f64 / q as f64).round() as i32) * q;+            *v = (r + SEA_LEVEL as i32).clamp(0, u16::MAX as i32) as u16;+        }+        // Quantising can make a coastal grid all-sea-level; keep it (the caller already decided+        // the tile has relief) — the renderer's land mask handles the shore.+    }+    pick+}++/// Per-zoom DEM error/size accounting, printed at the end of the build.+pub struct DemStats {+    max_bits: [std::sync::atomic::AtomicU64; 15],+    ss_micro: [std::sync::atomic::AtomicU64; 15],+    nodes: [std::sync::atomic::AtomicU64; 15],+    grids: [std::sync::atomic::AtomicU64; 15],+    cells: [std::sync::atomic::AtomicU64; 15],+}++#[allow(clippy::declare_interior_mutable_const)]+const ZERO: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+pub static DEM_STATS: DemStats =+    DemStats { max_bits: [ZERO; 15], ss_micro: [ZERO; 15], nodes: [ZERO; 15], grids: [ZERO; 15], cells: [ZERO; 15] };++impl DemStats {+    fn record(&self, z: u8, full: &Heightmap, out: &Heightmap) {+        use std::sync::atomic::Ordering::Relaxed;+        let z = (z as usize).min(14);+        let (mx, ss) = grid_error(full, out);+        // Non-negative f64s order like their bit patterns.+        self.max_bits[z].fetch_max(mx.to_bits(), Relaxed);+        self.ss_micro[z].fetch_add((ss * 1e6).round() as u64, Relaxed);+        self.nodes[z].fetch_add((full.dim as u64).pow(2), Relaxed);+        self.grids[z].fetch_add(1, Relaxed);+        self.cells[z].fetch_add((out.dim as u64).pow(2), Relaxed);+    }++    pub fn report(&self) {+        use std::sync::atomic::Ordering::Relaxed;+        println!("DEM grids (error vs the full {}-sample dataset grid, metres):", "dim^2");+        let (mut gmx, mut gss, mut gn) = (0.0f64, 0.0f64, 0u64);+        for z in 0..15 {+            let g = self.grids[z].load(Relaxed);+            if g == 0 {+                continue;+            }+            let mx = f64::from_bits(self.max_bits[z].load(Relaxed));+            let ss = self.ss_micro[z].load(Relaxed) as f64 / 1e6;+            let n = self.nodes[z].load(Relaxed);+            gmx = gmx.max(mx);+            gss += ss;+            gn += n;+            println!(+                "  DEMSTAT z{z:<2} grids {g:>10} avg_cells {:>6.1} max_err {mx:>7.2} rms_err {:>7.3}",+                self.cells[z].load(Relaxed) as f64 / g as f64,+                (ss / n.max(1) as f64).sqrt()+            );+        }+        println!("  DEMSTAT all max_err {gmx:.2} rms_err {:.3}", (gss / gn.max(1) as f64).sqrt());+    }+}+ /// A loaded `.mdem` dataset: one `u16` grid per output tile, keyed by pmtiles tile id at the /// dataset's own zoom. pub struct Dem {@@ -235,10 +378,7 @@ impl Dem {             }             // A flat tile's grid is mostly repetition: coarsen it. Steep             // tiles keep the full grid.-            if relief(samples) <= FLAT_RELIEF_M && self.dim >= FLAT_DIM {-                return Some(Heightmap { dim: FLAT_DIM, samples: coarsen(samples, self.dim as usize) });-            }-            return Some(Heightmap { dim: self.dim, samples: samples.to_vec() });+            return Some(finish_grid(z, y, samples, self.dim));         }         self.resample(z, x, y)     }@@ -274,10 +414,7 @@ impl Dem {         }         // Same flat-tile coarsening as the verbatim path: the resampled grid         // is full resolution, so relief is measured on it directly.-        if relief(&samples) <= FLAT_RELIEF_M && self.dim >= FLAT_DIM {-            return Some(Heightmap { dim: FLAT_DIM, samples: coarsen(&samples, dim) });-        }-        Some(Heightmap { dim: self.dim, samples })+        Some(finish_grid(z, y, &samples, self.dim))     }      /// Build a dataset directly from grids, for tests that inject a synthetic DEM into the tiler@@ -346,6 +483,26 @@ fn tile_y_to_lat(y: f64, z: u8) -> f64 { mod tests {     use super::*; +    /// `--dem-max-error`: a plane collapses to 2x2 (bilinear reproduces it exactly), a spike keeps+    /// the full grid, and every emitted grid stays within the bound against the full grid.+    #[test]+    fn adaptive_grids_respect_their_error_bound() {+        let full = |f: &dyn Fn(usize, usize) -> i32| Heightmap {+            dim: 9,+            samples: (0..81).map(|i| (f(i / 9, i % 9) + SEA_LEVEL as i32) as u16).collect(),+        };+        let plane = full(&|r, c| 100 + 3 * r as i32 + 2 * c as i32);+        assert_eq!(adapt_grid(&plane, 1.0).dim, 2, "a plane is exactly bilinear");+        let spike = full(&|r, c| if r == 4 && c == 4 { 500 } else { 100 });+        assert_eq!(adapt_grid(&spike, 2.0).dim, 9, "a spike keeps full resolution");+        for tol in [1.0, 2.0, 5.0, 10.0] {+            for g in [&plane, &spike, &full(&|r, c| ((r * 37 + c * 11) % 23) as i32 * 7)] {+                let out = adapt_grid(g, tol);+                assert!(grid_error(g, &out).0 <= tol + 1e-9, "tol {tol}: {}", grid_error(g, &out).0);+            }+        }+    }+     /// The sorted-column grids answer exactly what the old `HashMap` built by inserting in file     /// order answered -- for ascending files, unsorted ones, and ones repeating an id (last wins).     #[test]
scripts/maps/mamaps_build/src/main.rs
diff --git a/scripts/maps/mamaps_build/src/main.rs b/scripts/maps/mamaps_build/src/main.rsindex b500be2ce9..a4bcbefc38 100644--- a/scripts/maps/mamaps_build/src/main.rs+++ b/scripts/maps/mamaps_build/src/main.rs@@ -129,6 +129,7 @@ fn main() -> ExitCode {     let mut build_poi_to: Option<PathBuf> = None;     let mut graph_ready_file: Option<PathBuf> = None;     let mut v8_bodies = false;+    let mut size = tiler::SizeOpts::DEFAULT;      let mut i = 1;     while i < args.len() {@@ -182,6 +183,31 @@ fn main() -> ExitCode {                 v8_bodies = true;                 Ok(1)             }+            // Planet-size prototype knobs (see `tiler::SizeOpts`); defaults = today's bytes.+            "--body-zstd" => value("--body-zstd").and_then(|v| {+                size.zstd_level = v.parse().map_err(|_| format!("--body-zstd: bad level '{v}'"))?;+                Ok(2)+            }),+            "--dem-max-error" => value("--dem-max-error").and_then(|v| {+                size.dem_max_error_m = v.parse().map_err(|_| format!("--dem-max-error: bad '{v}'"))?;+                Ok(2)+            }),+            "--dem-px" => value("--dem-px").and_then(|v| {+                size.dem_px = v.parse().map_err(|_| format!("--dem-px: bad '{v}'"))?;+                Ok(2)+            }),+            "--simplify-scale" => value("--simplify-scale").and_then(|v| {+                size.simplify_scale = v.parse().map_err(|_| format!("--simplify-scale: bad '{v}'"))?;+                Ok(2)+            }),+            "--z14-tolerance" => value("--z14-tolerance").and_then(|v| {+                size.z14_tolerance = v.parse().map_err(|_| format!("--z14-tolerance: bad '{v}'"))?;+                Ok(2)+            }),+            "--coord-quant" => {+                size.coord_quant = true;+                Ok(1)+            }             "-h" | "--help" => {                 usage();                 return ExitCode::SUCCESS;@@ -218,6 +244,13 @@ fn main() -> ExitCode {         },     }; +    if tiler::SIZE_OPTS.set(size).is_err() {+        eprintln!("mamaps_build: size options set twice");+        return ExitCode::from(2);+    }+    if !size.is_default() {+        println!("size options: {}", size.tag());+    }     let settings = RunSettings {         coastline,         transit_routes,
scripts/maps/mamaps_build/src/main_part1.rs
diff --git a/scripts/maps/mamaps_build/src/main_part1.rs b/scripts/maps/mamaps_build/src/main_part1.rsindex ed17c22023..107903b93d 100644--- a/scripts/maps/mamaps_build/src/main_part1.rs+++ b/scripts/maps/mamaps_build/src/main_part1.rs@@ -316,6 +316,7 @@ fn run(         .map_err(|e| format!("cannot stat {}: {e}", out.display()))?;     // The header's id: the seed above folded with the archive's tile digest by the writer.     let header_id = read_header_build_id(out)?;+    crate::dem::DEM_STATS.report();     println!(         "\nwrote {} ({archive_len} bytes, build_id {header_id:#018x}, seed {build_id:#018x})",         out.display(),@@ -447,5 +448,10 @@ pub(crate) fn derive_build_id(     // input has not moved.     h.eat_u64(tilecodec::mamaps::dict::KINDS.len() as u64);     h.eat(if v8_bodies { b"bodies/v8" } else { b"bodies/v10" });+    // Planet-size knobs: only hashed when set, so a default build keeps its id.+    let size = tiler::size_opts();+    if !size.is_default() {+        h.eat(size.tag().as_bytes());+    }     h.finish() }
scripts/maps/mamaps_build/src/main_part2.rs
diff --git a/scripts/maps/mamaps_build/src/main_part2.rs b/scripts/maps/mamaps_build/src/main_part2.rsindex a1476a5ce9..f1c6828fff 100644--- a/scripts/maps/mamaps_build/src/main_part2.rs+++ b/scripts/maps/mamaps_build/src/main_part2.rs@@ -74,6 +74,8 @@ fn usage() {         \x20                   [--region california|world]\n\         \x20                   [--build-graph-to DIR] [--build-poi-to DIR]\n\         \x20                   [--graph-ready-file PATH] [--v8-bodies]\n\+        \x20                   [--body-zstd LEVEL] [--dem-max-error M] [--dem-px K]\n\+        \x20                   [--simplify-scale S] [--z14-tolerance T] [--coord-quant]\n\         \n\         \x20All six flags are required. Every build carries all 9 layers at\n\         \x20z0-14 as FORMAT_VERSION 8. --region filters roads/pois/buildings\n\
scripts/maps/mamaps_build/src/tiler.rs
diff --git a/scripts/maps/mamaps_build/src/tiler.rs b/scripts/maps/mamaps_build/src/tiler.rsindex f1fb4b23ee..b764cf9e90 100644--- a/scripts/maps/mamaps_build/src/tiler.rs+++ b/scripts/maps/mamaps_build/src/tiler.rs@@ -329,6 +329,70 @@ pub struct ZoomStats {     pub append_ms: u64, } +/// Planet-size prototype knobs (exp/planet-size). Every field's default reproduces today's+/// archive byte for byte; a non-default value is folded into the build id (see+/// `derive_build_id`). Set once by `main` before tiling, read everywhere after.+#[derive(Debug, Clone, Copy, PartialEq)]+pub struct SizeOpts {+    /// `--body-zstd LEVEL`: zstd bodies (header compression 2, which the shipping reader already+    /// decodes with `ruzstd`) instead of DEFLATE-9. 0 = DEFLATE (today).+    pub zstd_level: i32,+    /// `--dem-max-error M`: error-bounded adaptive heightmap grids (coarsest aligned sub-grid ++    /// elevation step whose reconstruction stays within M metres of the full grid). 0 = today's+    /// relief-gated 5x5 coarsening.+    pub dem_max_error_m: f64,+    /// `--dem-px K`: zoom-adaptive DEM bound — the error allowed on a tile is K times its ground+    /// resolution (metres per 256-px-tile pixel at the tile's latitude), floored at+    /// `dem_max_error_m` (or 1 m). 0 = off.+    pub dem_px: f64,+    /// `--simplify-scale S`: multiply every below-max-zoom simplification tolerance. 1 = today.+    pub simplify_scale: f64,+    /// `--z14-tolerance T`: extent-unit DP floor at z14 for landtype, boundaries, buildings and+    /// washable roads (crisp roads keep full detail). 0 = today's floors.+    pub z14_tolerance: f64,+    /// `--coord-quant`: snap tile coordinates below z14 to a zoom-scaled grid (2 units at z13,+    /// 4 at z<=12; points and the junction layer untouched). false = today.+    pub coord_quant: bool,+}++impl SizeOpts {+    pub const DEFAULT: SizeOpts = SizeOpts {+        zstd_level: 0,+        dem_max_error_m: 0.0,+        dem_px: 0.0,+        simplify_scale: 1.0,+        z14_tolerance: 0.0,+        coord_quant: false,+    };+    pub fn is_default(&self) -> bool {+        *self == SizeOpts::DEFAULT+    }+    /// Stable text for the build id (only hashed when non-default).+    pub fn tag(&self) -> String {+        format!(+            "size/zstd={};dem={};dempx={};simp={};z14={};q={}",+            self.zstd_level, self.dem_max_error_m, self.dem_px, self.simplify_scale, self.z14_tolerance, self.coord_quant+        )+    }+    /// The coordinate grid step for zoom `z` under `--coord-quant` (1 = untouched).+    pub fn quant_step(&self, z: u8, layer: u8) -> i32 {+        if !self.coord_quant || layer == tilecodec::mamaps::dict::LAYER_JUNCTION {+            return 1;+        }+        match z {+            0..=12 => 4,+            13 => 2,+            _ => 1,+        }+    }+}++pub static SIZE_OPTS: std::sync::OnceLock<SizeOpts> = std::sync::OnceLock::new();++pub fn size_opts() -> SizeOpts {+    *SIZE_OPTS.get().unwrap_or(&SizeOpts::DEFAULT)+}+ /// `--v8-bodies`: encode dense v8 bodies (set once by `main` before tiling). pub static V8_BODIES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); 
scripts/maps/mamaps_build/src/tiler_part1.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part1.rs b/scripts/maps/mamaps_build/src/tiler_part1.rsindex 94226e18a7..97907bc033 100644--- a/scripts/maps/mamaps_build/src/tiler_part1.rs+++ b/scripts/maps/mamaps_build/src/tiler_part1.rs@@ -70,6 +70,8 @@ fn writer_for(store: &Store, settings: &Settings) -> Result<StreamWriter> {         // The body scratch holds already-DEFLATEd bodies (~53 GB on a planet): keep btrfs         // `compress-force` from zstd'ing them again at writeback.         spill_file_hook: Some(osm_ingest::mem::mark_scratch_uncompressed),+        // `--body-zstd`: the header says zstd; the encode worker compresses with it.+        zstd: size_opts().zstd_level > 0,         ..Options::default()     }) }@@ -110,7 +112,8 @@ fn tile_zooms(     for z in 0..=crate::DEFAULT_MAX_ZOOM {         let mut stats = ZoomStats { zoom: z, ..ZoomStats::default() };         let tolerance =-            simplify::tolerance_for(z, crate::DEFAULT_MAX_ZOOM, DEFAULT_SIMPLIFICATION);+            simplify::tolerance_for(z, crate::DEFAULT_MAX_ZOOM, DEFAULT_SIMPLIFICATION)+                * size_opts().simplify_scale;         let buffer = geom::buffer_for(EXTENT);          // Per zoom, so peak scratch is the largest single zoom rather than the sum, and so a build
scripts/maps/mamaps_build/src/tiler_part2.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part2.rs b/scripts/maps/mamaps_build/src/tiler_part2.rsindex a336aa747c..1cc1ad52d6 100644--- a/scripts/maps/mamaps_build/src/tiler_part2.rs+++ b/scripts/maps/mamaps_build/src/tiler_part2.rs@@ -371,6 +371,11 @@ fn tile_chunk(                 return;             }             let local = geom::to_tile(clipped, tx, ty, EXTENT);+            let q = size_opts().quant_step(z, feature.class.layer);+            let local = if q > 1 { snap_grid(local, q) } else { local };+            if is_empty_int(&local) {+                return;+            }             let layer = tiles                 .entry((tile_id(z, tx, ty), feature.class.layer))                 .or_insert_with(|| ChunkEntry::new(feature.class.layer));@@ -456,14 +461,27 @@ fn tolerance_for_layer(layer: u8, z: u8, tolerance: f64) -> f64 { fn tolerance_for_feature(feature: &crate::extract::Feature, z: u8, tolerance: f64) -> f64 {     use tilecodec::mamaps::dict;     let base = tolerance_for_layer(feature.class.layer, z, tolerance);-    if z == crate::DEFAULT_MAX_ZOOM+    let base = if z == crate::DEFAULT_MAX_ZOOM         && feature.class.layer == dict::LAYER_ROADS         && !needs_crisp(feature)     {         base.max(ROAD_DETAIL_FLOOR)     } else {         base+    };+    // `--z14-tolerance`: a z14 floor for the washable layers (crisp roads keep full detail).+    let floor = size_opts().z14_tolerance;+    if floor > 0.0 && z == crate::DEFAULT_MAX_ZOOM {+        let l = feature.class.layer;+        let washable = l == dict::LAYER_LANDTYPE+            || l == dict::LAYER_BOUNDARIES+            || l == dict::LAYER_BUILDINGS+            || (l == dict::LAYER_ROADS && !needs_crisp(feature));+        if washable {+            return base.max(floor);+        }     }+    base }  /// Snap a building geometry's near-axis-aligned edges to exactly axis-aligned.@@ -545,3 +563,58 @@ fn snap_building_ring(ring: &[SigPt]) -> Vec<SigPt> {     out } ++/// `--coord-quant`: snap tile-local coordinates to a `q`-unit grid, dropping consecutive+/// duplicates. Max displacement per vertex is `q/2` per axis (`q/sqrt(2)` units). A line that+/// collapses below 2 vertices or a ring below 4 is dropped (a ring that was the exterior takes+/// its polygon with it) — the same floors `simplify::filter` applies. Points are untouched.+/// Rings are re-normalised by stage C afterwards, so `rings_validated` stays true.+fn snap_grid(g: tile_build::geom::IntGeometry, q: i32) -> tile_build::geom::IntGeometry {+    use tile_build::geom::IntGeometry;+    let s = |v: i32| (v + q / 2).div_euclid(q) * q;+    let snap = |pts: &[(i32, i32)]| -> Vec<(i32, i32)> {+        let mut out: Vec<(i32, i32)> = Vec::with_capacity(pts.len());+        for &(x, y) in pts {+            let p = (s(x), s(y));+            if out.last() != Some(&p) {+                out.push(p);+            }+        }+        out+    };+    match g {+        IntGeometry::Points(p) => IntGeometry::Points(p),+        IntGeometry::Lines(lines) => {+            IntGeometry::Lines(lines.iter().map(|l| snap(l)).filter(|l| l.len() >= 2).collect())+        }+        IntGeometry::Polygons(polys) => IntGeometry::Polygons(+            polys+                .iter()+                .filter_map(|rings| {+                    let mut out = Vec::with_capacity(rings.len());+                    for (i, r) in rings.iter().enumerate() {+                        let sr = snap(r);+                        // Distinct corners: a closed ring repeats its first vertex.+                        let closed = sr.len() > 1 && sr.first() == sr.last();+                        let distinct = sr.len() - usize::from(closed);+                        if distinct >= 3 {+                            out.push(sr);+                        } else if i == 0 {+                            return None;+                        }+                    }+                    (!out.is_empty()).then_some(out)+                })+                .collect(),+        ),+    }+}++fn is_empty_int(g: &tile_build::geom::IntGeometry) -> bool {+    use tile_build::geom::IntGeometry;+    match g {+        IntGeometry::Points(p) => p.is_empty(),+        IntGeometry::Lines(l) => l.is_empty(),+        IntGeometry::Polygons(p) => p.is_empty(),+    }+}
scripts/maps/mamaps_build/src/tiler_part5.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part5.rs b/scripts/maps/mamaps_build/src/tiler_part5.rsindex 2b8f13b848..2397f5fc0d 100644--- a/scripts/maps/mamaps_build/src/tiler_part5.rs+++ b/scripts/maps/mamaps_build/src/tiler_part5.rs@@ -307,7 +307,12 @@ fn encode_tile(         tilecodec::mamaps::body::serialize_into_v10(&body, scratch)     }?;     let raw_len = encoded_body.len();-    let stored = tilecodec::mamaps::write::compress_body_with(deflate, encoded_body);+    let level = crate::tiler::size_opts().zstd_level;+    let stored = if level > 0 {+        tilecodec::mamaps::write::compress_body_zstd_level(encoded_body, level)+    } else {+        tilecodec::mamaps::write::compress_body_with(deflate, encoded_body)+    };     // Compute the dedup key here, in the parallel worker, rather than on the serial append thread.     // It is a pure function of the stored bytes, so the key — and every dedup decision the writer     // makes from it — is unchanged; it just no longer walks the whole body downstream of this phase.