scripts: drop the finished planet-size experiment tooling
- Commit
82f6d3eca0396d4ad8281a1fba3d7f0bb093edbc- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 16:09 UTC (4 days ago)
- Parents
002e323
size_lab (3 example files) and mamaps_sizes came from the planet-size study; planet5 has published and planet_build.sh invokes only mamaps_pack/mamaps_dump/mamaps_planet5/ transit_planet5. Independent re-verification found no living doc or tool referencing them, and the ruzstd/png dev-deps served only the deleted code. 3,393 counted lines (3,401 deletions incl. Cargo.toml cleanup and the two Cargo.lock entries). Verified: cargo check -p tile_build --offline --all-targets green; surviving bins untouched.
Diff
scripts/maps/tile_build/Cargo.toml
diff --git a/scripts/maps/tile_build/Cargo.toml b/scripts/maps/tile_build/Cargo.tomlindex c221f8848c..87429739e5 100644--- a/scripts/maps/tile_build/Cargo.toml+++ b/scripts/maps/tile_build/Cargo.toml@@ -67,11 +67,3 @@ zstd-rs.workspace = true zstd.workspace = true [profile.release] opt-level = 3--# Size-lab experiment (examples/size_lab.rs) only: the C zstd reference-# encoder + dictionary trainer, and the two pure-Rust codecs the shipping-# path uses (zstd-rs encode, ruzstd decode), measured side by side. Never-# linked into the shipping binaries.-[dev-dependencies]-ruzstd.workspace = true-png.workspace = true
scripts/maps/tile_build/examples/size_lab/main.rs
diff --git a/scripts/maps/tile_build/examples/size_lab/main.rs b/scripts/maps/tile_build/examples/size_lab/main.rsdeleted file mode 100644index 5fcd2353aa..0000000000--- a/scripts/maps/tile_build/examples/size_lab/main.rs+++ /dev/null@@ -1,1015 +0,0 @@-//! `size_lab` — measured size experiments on a real `.mamaps` (planet-size study).-//!-//! Usage:-//! size_lab bodies IN.mamaps [PER_ZOOM] [OUT_DIR]-//! size_lab sidecars IN.mamaps [WINDOWS] [OUT_DIR]-//!-//! `bodies`: stratified sample of unique tile bodies per zoom (stride over the-//! deduplicated data section), every body re-encoded under each codec and each-//! data transform; per-zoom totals are scaled with a ratio estimator against-//! the zoom's exact stored total, so the planet projection is-//! `sum_z exact_stored_z * (variant_sample_z / stored_sample_z)`.-//! Dictionaries are trained on a disjoint sample (offset by half a stride).-//!-//! `sidecars`: per sidecar section, WINDOWS evenly spaced 1 MiB windows, each-//! cut into independent 64 KiB blocks (what a random-access mmap reader would-//! inflate), compressed with zstd 19 (C reference and the pure-Rust zstd-rs-//! the build would ship). ZBLK sections are decoded and recompressed.-//!-//! Experiment tooling only (examples/, dev-dependencies): nothing here is in a-//! shipping binary.-use std::collections::BTreeMap;-use std::fs::File;-use std::io::Write as _;-use std::sync::Mutex;-use std::time::Instant;--use rayon::prelude::*;-use tile_build::mamaps::body::{Body, Heightmap, Layer, Part, Scratch, GEOM_POINT, GEOM_POLYGON};-use tile_build::mamaps::dict::Dictionary;-use tile_build::mamaps::{header, index};-use tilecodec::pmtiles::tile_zxy;--const H: usize = tile_build::mamaps::body::BODY_HEADER_LEN;--#[derive(Clone, Copy)]-struct Ent {- z: u8,- off: u64,- len: u32,-}--fn zstd_c(data: &[u8], level: i32) -> usize {- zstd::bulk::compress(data, level).expect("zstd").len()-}--fn zstd_c_dict(c: &mut zstd::bulk::Compressor<'_>, data: &[u8]) -> Vec<u8> {- c.compress(data).expect("zstd dict")-}--fn zstd_rs(data: &[u8], level: i32) -> Vec<u8> {- let cfg = zstd_rs::CompressionConfig { level, ..zstd_rs::CompressionConfig::DEFAULT };- let mut enc = zstd_rs::Compressor::new(cfg).expect("cfg");- let mut out = Vec::new();- enc.compress(data, None, &mut out).expect("zstd-rs");- out-}--fn zstd_rs_dict(data: &[u8], level: i32, d: &zstd_rs::EncoderDictionary) -> Vec<u8> {- let cfg = zstd_rs::CompressionConfig { level, ..zstd_rs::CompressionConfig::DEFAULT };- let mut enc = zstd_rs::Compressor::new(cfg).expect("cfg");- let mut out = Vec::new();- enc.compress(data, Some(d), &mut out).expect("zstd-rs dict");- out-}--fn deflate9(data: &[u8]) -> usize {- miniz_oxide::deflate::compress_to_vec(data, 9).len()-}--fn band(z: u8) -> usize {- match z {- 0..=9 => 0,- 10..=11 => 1,- 12 => 2,- 13 => 3,- _ => 4,- }-}-const BANDS: [&str; 5] = ["z0-9", "z10-11", "z12", "z13", "z14"];--// ---------------------------------------------------------------- transforms--fn ser(body: &Body) -> Vec<u8> {- let mut s = Scratch::default();- match tile_build::mamaps::body::serialize_into_v10(body, &mut s) {- Ok(b) => b.to_vec(),- Err(e) if e.0.contains("marking convention") => {- // A transform dropped every feature with a non-default carriageway:- // the sparse table is then empty and the convention must go too.- let mut b = body.clone();- b.convention = None;- b.carriageways.clear();- let mut s = Scratch::default();- tile_build::mamaps::body::serialize_into_v10(&b, &mut s).expect("serialize").to_vec()- }- Err(e) => panic!("serialize: {e:?}"),- }-}--/// Rebuild a layer keeping only features `keep` says yes to, with per-part-/// coordinate rewriting through `edit` (None = drop the part).-fn rebuild_layer(- layer: &Layer,- mut keep: impl FnMut(usize) -> bool,- mut edit: impl FnMut(u8, &[(i16, i16)], u16) -> Option<Vec<(i16, i16)>>,-) -> (Layer, Vec<usize>) {- let mut nl = Layer::new(layer.layer_id);- let mut kept = Vec::new();- for (i, f) in layer.features.iter().enumerate() {- if !keep(i) {- continue;- }- let start = nl.parts.len() as u32;- let from = f.parts_offset as usize;- let mut np = 0u32;- for p in &layer.parts[from..from + f.part_count as usize] {- let pts = layer.points(p);- let Some(out) = edit(f.geom_type, pts, p.winding) else { continue };- nl.parts.push(Part { coord_start: nl.coords.len() as u32, point_count: out.len() as u32, winding: p.winding });- nl.coords.extend_from_slice(&out);- np += 1;- }- if np == 0 {- nl.parts.truncate(start as usize);- continue;- }- let mut nf = *f;- nf.parts_offset = start;- nf.part_count = np;- nl.features.push(nf);- kept.push(i);- }- (nl, kept)-}--/// Filter every dense-parallel side table of `layer_id` down to `kept`.-fn filter_tables(body: &mut Body, layer_id: u8, kept: &[usize]) {- fn f<T: Clone>(v: &mut Vec<(u8, Vec<T>)>, id: u8, kept: &[usize]) {- for (lid, t) in v.iter_mut() {- if *lid == id {- *t = kept.iter().map(|&i| t[i].clone()).collect();- }- }- v.retain(|(_, t)| !t.is_empty());- }- f(&mut body.ids, layer_id, kept);- f(&mut body.turn_lanes, layer_id, kept);- f(&mut body.buildings, layer_id, kept);- f(&mut body.carriageways, layer_id, kept);- f(&mut body.region_links, layer_id, kept);- if body.carriageways.is_empty() {- body.convention = None;- }-}--fn apply_layer(- body: &Body,- layer_id: u8,- keep: impl FnMut(&Layer, usize) -> bool,- edit: impl FnMut(u8, &[(i16, i16)], u16) -> Option<Vec<(i16, i16)>>,-) -> Body {- let mut b = body.clone();- let Some(pos) = b.layers.iter().position(|l| l.layer_id == layer_id) else { return b };- let layer = b.layers[pos].clone();- let mut keep = keep;- let (nl, kept) = rebuild_layer(&layer, |i| keep(&layer, i), edit);- if nl.features.is_empty() {- b.layers.remove(pos);- } else {- b.layers[pos] = nl;- }- filter_tables(&mut b, layer_id, &kept);- // Names no longer referenced are kept (the name table is per tile); a- // real build would drop them, so this slightly understates savings.- b-}--fn ring_area2(pts: &[(i16, i16)]) -> i64 {- let mut a = 0i64;- for i in 0..pts.len() {- let (x0, y0) = pts[i];- let (x1, y1) = pts[(i + 1) % pts.len()];- a += x0 as i64 * y1 as i64 - x1 as i64 * y0 as i64;- }- a.abs()-}--fn line_len(pts: &[(i16, i16)]) -> f64 {- pts.windows(2)- .map(|w| (((w[1].0 - w[0].0) as f64).powi(2) + ((w[1].1 - w[0].1) as f64).powi(2)).sqrt())- .sum()-}--fn dp(pts: &[(i16, i16)], tol: f64, keep: &mut [bool], a: usize, b: usize) {- if b <= a + 1 {- return;- }- let (ax, ay) = (pts[a].0 as f64, pts[a].1 as f64);- let (bx, by) = (pts[b].0 as f64, pts[b].1 as f64);- let (dx, dy) = (bx - ax, by - ay);- let l2 = dx * dx + dy * dy;- let mut best = 0.0;- let mut bi = a;- for (i, p) in pts.iter().enumerate().take(b).skip(a + 1) {- let (px, py) = (p.0 as f64, p.1 as f64);- let d = if l2 == 0.0 {- ((px - ax).powi(2) + (py - ay).powi(2)).sqrt()- } else {- ((dy * px - dx * py + bx * ay - by * ax).abs()) / l2.sqrt()- };- if d > best {- best = d;- bi = i;- }- }- if best > tol {- keep[bi] = true;- dp(pts, tol, keep, a, bi);- dp(pts, tol, keep, bi, b);- }-}--fn simplify(geom: u8, pts: &[(i16, i16)], tol: f64) -> Vec<(i16, i16)> {- if geom == GEOM_POINT || pts.len() < 4 {- return pts.to_vec();- }- let n = pts.len();- let mut keep = vec![false; n];- keep[0] = true;- keep[n - 1] = true;- if geom == GEOM_POLYGON {- // Closed ring: anchor at first point and the farthest point from it.- let far = (1..n)- .max_by_key(|&i| {- let dx = (pts[i].0 - pts[0].0) as i64;- let dy = (pts[i].1 - pts[0].1) as i64;- dx * dx + dy * dy- })- .unwrap_or(n - 1);- keep[far] = true;- dp(pts, tol, &mut keep, 0, far);- dp(pts, tol, &mut keep, far, n - 1);- } else {- dp(pts, tol, &mut keep, 0, n - 1);- }- let out: Vec<_> = pts.iter().zip(&keep).filter(|(_, k)| **k).map(|(p, _)| *p).collect();- let min = if geom == GEOM_POLYGON { 4 } else { 2 };- if out.len() < min { pts.to_vec() } else { out }-}--fn snap(geom: u8, pts: &[(i16, i16)], q: i16) -> Vec<(i16, i16)> {- if geom == GEOM_POINT {- return pts.to_vec();- }- let s = |v: i16| -> i16 {- let r = ((v as i32 + (q as i32) / 2).div_euclid(q as i32)) * q as i32;- r.clamp(i16::MIN as i32, i16::MAX as i32) as i16- };- let mut out: Vec<(i16, i16)> = Vec::with_capacity(pts.len());- for &(x, y) in pts {- let p = (s(x), s(y));- if out.last() != Some(&p) {- out.push(p);- }- }- let min = if geom == GEOM_POLYGON { 4 } else { 2 };- if out.len() < min { pts.to_vec() } else { out }-}--fn hm_quant(hm: &Heightmap, step: i32) -> Heightmap {- Heightmap {- dim: hm.dim,- samples: hm- .samples- .iter()- .map(|&s| {- let m = s as i32 - 32768;- let q = ((m as f64 / step as f64).round() as i32) * step;- (q + 32768).clamp(0, 65535) as u16- })- .collect(),- }-}--/// Subsample a dim-N grid to ceil(N/2)+? keeping corners (N odd -> (N+1)/2).-fn hm_half(hm: &Heightmap) -> Heightmap {- let d = hm.dim as usize;- if d < 3 {- return hm.clone();- }- let idx: Vec<usize> = if d % 2 == 1 { (0..d).step_by(2).collect() } else {- let mut v: Vec<usize> = (0..d).step_by(2).collect();- if *v.last().unwrap() != d - 1 { v.push(d - 1); }- v- };- let mut samples = Vec::with_capacity(idx.len() * idx.len());- for &r in &idx {- for &c in &idx {- samples.push(hm.samples[r * d + c]);- }- }- Heightmap { dim: idx.len() as u16, samples }-}--/// Format-change simulation: 2D predictive (left, or up for column 0) zigzag-/// residuals stored in the same u16 slots, so only entropy changes.-fn hm_delta(hm: &Heightmap) -> Heightmap {- let d = hm.dim as usize;- let mut out = vec![0u16; hm.samples.len()];- for r in 0..d {- for c in 0..d {- let v = hm.samples[r * d + c] as i32;- let pred = if c > 0 {- let l = hm.samples[r * d + c - 1] as i32;- if r > 0 {- let u = hm.samples[(r - 1) * d + c] as i32;- let ul = hm.samples[(r - 1) * d + c - 1] as i32;- (l + u - ul).clamp(l.min(u), l.max(u)) // MED/LOCO-I predictor- } else {- l- }- } else if r > 0 {- hm.samples[(r - 1) * d] as i32- } else {- 32768- };- let e = v - pred;- out[r * d + c] = ((e << 1) ^ (e >> 31)) as u16;- }- }- Heightmap { dim: hm.dim, samples: out }-}--/// Bilinear reconstruction of grid `g` (dim `dg`) at fractional position (fr, fc) in [0,1].-fn bilin(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, sum sq, n) error of `new` against `orig`, evaluated at every original sample.-/// Both surfaces are bilinear and the coarse grid's nodes are a subset of the fine grid's,-/// so the difference is bilinear inside each fine cell: the max over these nodes IS the max-/// over the whole continuous surface.-fn hm_err(orig: &Heightmap, new: &Heightmap) -> (f64, f64, u64) {- let d = orig.dim as usize;- let dn = new.dim as usize;- let mut mx = 0.0f64;- let mut ss = 0.0f64;- for r in 0..d {- for c in 0..d {- let fr = r as f64 / (d - 1) as f64;- let fc = c as f64 / (d - 1) as f64;- let e = (bilin(&new.samples, dn, fr, fc) - orig.samples[r * d + c] as f64).abs();- mx = mx.max(e);- ss += e * e;- }- }- (mx, ss, (d * d) as u64)-}--fn subsample(hm: &Heightmap, dn: usize) -> Heightmap {- let d = hm.dim as usize;- let mut s = Vec::with_capacity(dn * dn);- for r in 0..dn {- for c in 0..dn {- s.push(hm.samples[(r * (d - 1) / (dn - 1)) * d + c * (d - 1) / (dn - 1)]);- }- }- Heightmap { dim: dn as u16, samples: s }-}--/// Error-bounded adaptive grid: the coarsest aligned sub-grid (dim-1 divisible by dn-1) whose-/// bilinear reconstruction stays within tol/2 of the full grid, then elevation quantised to a-/// step of floor(tol) metres (rounding error <= tol/2). Total max error <= tol by construction.-/// No format change: dim is per tile on the wire already.-fn hm_adapt(hm: &Heightmap, tol: f64) -> Heightmap {- let d = hm.dim as usize;- let mut cands: Vec<usize> = (2..=d).filter(|dn| (d - 1) % (dn - 1) == 0).collect();- cands.sort();- let mut pick = hm.clone();- for dn in cands {- let sub = subsample(hm, dn);- if hm_err(hm, &sub).0 <= tol / 2.0 + 1e-9 {- pick = sub;- break;- }- }- let q = tol.floor().max(1.0) as i32;- if q > 1 { hm_quant(&pick, q) } else { pick }-}--struct Ids {- landtype: u8,- roads: u8,- buildings: u8,- junction: u8,-}--/// Named transforms; each returns the transformed body (or None = unchanged).-fn transforms() -> Vec<&'static str> {- vec![- "identity_v10",- "hm_drop",- "hm_q2m",- "hm_q4m",- "hm_half_dim",- "hm_delta*",- "hm_adapt1m",- "hm_adapt2m",- "hm_adapt5m",- "hm_adapt2m_delta*",- "hm_delta_q2m*",- "coord_q2_le13",- "coord_q4_le12_q2_13",- "landtype_simp2_le13",- "landtype_simp4_le13",- "landtype_dropsmall_le13",- "roads_simp2_le13",- "junction_drop",- "buildings_drop_attrs",- "ids_drop",- "names_drop",- "combo_A",- "combo_B*",- ]-}--fn apply(name: &str, body: &Body, z: u8, ids: &Ids) -> Body {- let mut b = body.clone();- match name {- "identity_v10" => {}- "hm_drop" => b.heightmap = None,- "hm_q2m" => b.heightmap = b.heightmap.as_ref().map(|h| hm_quant(h, 2)),- "hm_q4m" => b.heightmap = b.heightmap.as_ref().map(|h| hm_quant(h, 4)),- "hm_half_dim" => b.heightmap = b.heightmap.as_ref().map(hm_half),- "hm_delta*" => b.heightmap = b.heightmap.as_ref().map(hm_delta),- "hm_adapt1m" => b.heightmap = b.heightmap.as_ref().map(|h| hm_adapt(h, 1.0)),- "hm_adapt2m" => b.heightmap = b.heightmap.as_ref().map(|h| hm_adapt(h, 2.0)),- "hm_adapt5m" => b.heightmap = b.heightmap.as_ref().map(|h| hm_adapt(h, 5.0)),- "hm_adapt2m_delta*" => b.heightmap = b.heightmap.as_ref().map(|h| hm_delta(&hm_adapt(h, 2.0))),- "hm_delta_q2m*" => b.heightmap = b.heightmap.as_ref().map(|h| hm_delta(&hm_quant(h, 2))),- "coord_q2_le13" | "coord_q4_le12_q2_13" => {- if z <= 13 {- let q = if name == "coord_q4_le12_q2_13" && z <= 12 { 4 } else { 2 };- for l in b.layers.clone() {- b = apply_layer(&b, l.layer_id, |_, _| true, |g, p, _| Some(snap(g, p, q)));- }- }- }- "landtype_simp2_le13" | "landtype_simp4_le13" => {- if z <= 13 {- let tol = if name.contains("simp4") { 4.0 } else { 2.0 };- b = apply_layer(&b, ids.landtype, |_, _| true, |g, p, _| Some(simplify(g, p, tol)));- }- }- "roads_simp2_le13" => {- if z <= 13 {- b = apply_layer(&b, ids.roads, |_, _| true, |g, p, _| Some(simplify(g, p, 2.0)));- }- }- "landtype_dropsmall_le13" => {- if z <= 13 {- // < 2x2 px of a 512 px tile (8 units/px): polygons under 256 units^2,- // lines under 16 units. Holes under the same area are dropped too.- b = apply_layer(- &b,- ids.landtype,- |l, i| {- let f = &l.features[i];- let from = f.parts_offset as usize;- let parts = &l.parts[from..from + f.part_count as usize];- if f.geom_type == GEOM_POLYGON {- let outer: i64 = parts.iter().filter(|p| !p.is_hole()).map(|p| ring_area2(l.points(p))).sum();- outer / 2 >= 256- } else if f.geom_type == GEOM_POINT {- true- } else {- parts.iter().map(|p| line_len(l.points(p))).sum::<f64>() >= 16.0- }- },- |g, p, w| {- if g == GEOM_POLYGON && w == tile_build::mamaps::body::WINDING_HOLE && ring_area2(p) / 2 < 256 {- None- } else {- Some(p.to_vec())- }- },- );- }- }- "junction_drop" => {- b = apply_layer(&b, ids.junction, |_, _| false, |_, p, _| Some(p.to_vec()));- }- "buildings_drop_attrs" => b.buildings.clear(),- "ids_drop" => b.ids.clear(),- "names_drop" => {- b.names.clear();- for l in &mut b.layers {- for f in &mut l.features {- f.name_idx = tile_build::mamaps::body::NAME_NONE;- }- }- }- "combo_A" => {- // No format change: hm 2 m quant + half dim at z<=12, coord q2 at z<=13,- // landtype simp2 + drop-small at z<=13.- b.heightmap = b.heightmap.as_ref().map(|h| {- let q = hm_quant(h, 2);- if z <= 12 { hm_half(&q) } else { q }- });- if z <= 13 {- b = apply(- "landtype_dropsmall_le13",- &apply("landtype_simp2_le13", &b, z, ids),- z,- ids,- );- b = apply("coord_q2_le13", &b, z, ids);- }- }- "combo_B*" => {- b = apply("combo_A", &b, z, ids);- b.heightmap = b.heightmap.as_ref().map(hm_delta);- }- _ => unreachable!("{name}"),- }- let _ = ids.buildings;- b-}--// ---------------------------------------------------------------- bodies--struct Arch {- map: memmap2::Mmap,- hdr: header::Header,- dict: Dictionary,- /// Planet5 archives' trained dictionaries.- zd: Option<tile_build::mamaps::zdict::ZDicts>,-}--fn open(path: &str) -> Arch {- let f = File::open(path).expect("open");- let map = unsafe { memmap2::Mmap::map(&f).expect("mmap") };- let hdr = header::Header::parse(&map[..tilecodec::stream::OPEN_PREFIX_BYTES as usize]).expect("header");- let dict = Dictionary::parse(&map[hdr.dict_offset as usize..hdr.dict_offset as usize + hdr.dict_len as usize]).expect("dict");- let zd = tile_build::mamaps::read::zdicts_in(&hdr, &map).expect("dictionaries");- Arch { map, hdr, dict, zd }-}--fn entries(a: &Arch) -> Vec<Ent> {- let hdr = &a.hdr;- let root = index::parse_root(&a.map[hdr.root_offset as usize..(hdr.root_offset + hdr.root_len as u64) as usize]).expect("root");- let per: Vec<Vec<Ent>> = root- .par_iter()- .map(|re| {- let raw_len = re.leaf_entry_count as usize * index::LEAF_ENTRY_LEN;- let at = (hdr.leaf_offset + re.leaf_offset) as usize;- let raw = if re.stored_len == 0 {- a.map[at..at + raw_len].to_vec()- } else {- index::decompress_leaf(&a.map[at..at + re.stored_len as usize], raw_len).expect("leaf")- };- index::parse_leaf(&raw)- .expect("leaf")- .iter()- .map(|e| {- let (z, _, _) = tile_zxy(re.base_tile_id + e.tile_id_lo as u64);- Ent { z, off: hdr.data_offset + re.base_data_offset + e.offset_delta as u64, len: e.length }- })- .collect()- })- .collect();- let mut all: Vec<Ent> = per.into_iter().flatten().collect();- all.sort_by_key(|e| (e.off, e.z));- all.dedup_by_key(|e| e.off);- all-}--#[derive(Default, Clone)]-struct Acc {- n: u64,- stored: u64,- raw: u64,- v: BTreeMap<String, u64>,- t_inflate_ns: u64,- t_zstd_ns: u64,- t_zstd_dict_ns: u64,- t_parse_ns: u64,- hm_dims: BTreeMap<u16, u64>,- identical_v10: u64,- hm_err: BTreeMap<String, (f64, f64, u64)>,-}--impl Acc {- fn add(&mut self, k: &str, n: usize) {- *self.v.entry(k.to_string()).or_default() += n as u64;- }- fn merge(&mut self, o: &Acc) {- self.n += o.n;- self.stored += o.stored;- self.raw += o.raw;- for (k, v) in &o.v {- *self.v.entry(k.clone()).or_default() += v;- }- self.t_inflate_ns += o.t_inflate_ns;- self.t_zstd_ns += o.t_zstd_ns;- self.t_zstd_dict_ns += o.t_zstd_dict_ns;- self.t_parse_ns += o.t_parse_ns;- for (k, v) in &o.hm_dims {- *self.hm_dims.entry(*k).or_default() += v;- }- self.identical_v10 += o.identical_v10;- for (k, v) in &o.hm_err {- let e = self.hm_err.entry(k.clone()).or_insert((0.0, 0.0, 0));- e.0 = e.0.max(v.0);- e.1 += v.1;- e.2 += v.2;- }- }-}--fn raw_of(a: &Arch, e: &Ent) -> Vec<u8> {- let stored = &a.map[e.off as usize..e.off as usize + e.len as usize];- tile_build::mamaps::read::decompress_with(a.hdr.compression, stored, a.zd.as_ref()).expect("inflate")-}--fn cmd_bodies(path: &str, per_zoom: usize, out_dir: &str) {- let a = open(path);- let t0 = Instant::now();- let ents = entries(&a);- eprintln!("unique bodies {} in {:.1}s", ents.len(), t0.elapsed().as_secs_f64());- let lid = |n: &str| a.dict.layers.iter().position(|l| l == n).expect(n) as u8;- let ids = Ids { landtype: lid("landtype"), roads: lid("roads"), buildings: lid("buildings"), junction: lid("junction") };-- // Exact per-zoom totals and the stratified samples.- let mut by_z: BTreeMap<u8, Vec<Ent>> = BTreeMap::new();- for e in &ents {- by_z.entry(e.z).or_default().push(*e);- }- let mut exact: BTreeMap<u8, (u64, u64)> = BTreeMap::new();- let mut sample: Vec<Ent> = Vec::new();- let mut train: Vec<Vec<Vec<u8>>> = vec![Vec::new(); 5];- for (z, v) in &by_z {- exact.insert(*z, (v.len() as u64, v.iter().map(|e| e.len as u64).sum()));- let step = (v.len() / per_zoom.max(1)).max(1);- let mut i = 0;- while i < v.len() {- sample.push(v[i]);- // Disjoint training sample: half a stride later (only when the- // stride leaves room; tiny zooms train on what there is).- if step >= 2 && i + step / 2 < v.len() {- train[band(*z)].push(v[i + step / 2].off.to_le_bytes().to_vec());- }- i += step;- }- }- eprintln!("sample {} bodies; training dictionaries...", sample.len());- // Training bodies: raw payload past the 16-byte header (what is compressed).- let off_to_ent: std::collections::HashMap<u64, Ent> = ents.iter().map(|e| (e.off, *e)).collect();- let dicts: Vec<Vec<u8>> = train- .par_iter()- .enumerate()- .map(|(bi, offs)| {- let mut samples: Vec<Vec<u8>> = offs- .iter()- .map(|o| {- let e = off_to_ent[&u64::from_le_bytes(o[..8].try_into().unwrap())];- raw_of(&a, &e)[H..].to_vec()- })- .collect();- // zdict wants < 4 GB total and a bounded count; cap at 200k samples.- samples.truncate(200_000);- let d = zstd::dict::from_samples(&samples, 112 * 1024).unwrap_or_default();- eprintln!(" dict {}: {} samples -> {} B", BANDS[bi], samples.len(), d.len());- d- })- .collect();- for (i, d) in dicts.iter().enumerate() {- std::fs::write(format!("{out_dir}/dict_{}.zdict", BANDS[i]), d).expect("write dict");- }- let rs_dicts: Vec<Option<zstd_rs::EncoderDictionary>> = dicts- .iter()- .map(|d| {- if d.is_empty() {- return None;- }- let dd = zstd_rs::Dictionary::new(d, zstd_rs::DictionaryFormat::Zstd).ok()?;- zstd_rs::EncoderDictionary::new(&dd, 19).ok()- })- .collect();-- let tnames = transforms();- let acc: Mutex<BTreeMap<u8, Acc>> = Mutex::new(BTreeMap::new());- let done = std::sync::atomic::AtomicUsize::new(0);- sample.par_chunks(64).for_each(|chunk| {- let mut local: BTreeMap<u8, Acc> = BTreeMap::new();- let mut cdicts: Vec<Option<zstd::bulk::Compressor>> = dicts- .iter()- .map(|d| if d.is_empty() { None } else { zstd::bulk::Compressor::with_dictionary(19, d).ok() })- .collect();- for e in chunk {- // Copied first so the timing below measures decode, not a page fault on the mmap.- let stored = a.map[e.off as usize..e.off as usize + e.len as usize].to_vec();- let ti = Instant::now();- let raw = tile_build::mamaps::read::decompress_with(a.hdr.compression, &stored, a.zd.as_ref()).expect("inflate");- let t_inf = ti.elapsed().as_nanos() as u64;- let tp = Instant::now();- let body = Body::parse(&raw).expect("parse");- let t_parse = tp.elapsed().as_nanos() as u64;- let payload = &raw[H..];- let acc = local.entry(e.z).or_default();- acc.n += 1;- acc.stored += e.len as u64;- acc.raw += raw.len() as u64;- acc.t_inflate_ns += t_inf;- acc.t_parse_ns += t_parse;- if let Some(h) = &body.heightmap {- *acc.hm_dims.entry(h.dim).or_default() += 1;- }- acc.add("codec:deflate9", H + deflate9(payload));- acc.add("codec:zstdC_19", H + zstd_c(payload, 19));- let rs19 = zstd_rs(payload, 19);- acc.add("codec:zstdRS_19", H + rs19.len());- // Decode timing of the shipping decoder (ruzstd) on the zstd-rs frame.- let td = Instant::now();- let mut out = vec![0u8; payload.len()];- let mut dec = ruzstd::decoding::FrameDecoder::new();- let n = dec.decode_all(&rs19, &mut out).expect("ruzstd");- acc.t_zstd_ns += td.elapsed().as_nanos() as u64;- assert_eq!(&out[..n], payload, "ruzstd round trip");- let bi = band(e.z);- if let Some(c) = cdicts[bi].as_mut() {- let fr = zstd_c_dict(c, payload);- acc.add("codec:zstdC_19_dict", H + fr.len());- } else {- acc.add("codec:zstdC_19_dict", H + zstd_c(payload, 19));- }- if let Some(d) = rs_dicts[bi].as_ref() {- let fr = zstd_rs_dict(payload, 19, d);- acc.add("codec:zstdRS_19_dict", H + fr.len());- if let Ok(rd) = ruzstd::decoding::Dictionary::decode_dict(&dicts[bi]) {- let td = Instant::now();- let mut dec = ruzstd::decoding::FrameDecoder::new();- dec.add_dict(rd).expect("add dict");- let mut out = vec![0u8; payload.len()];- let n = dec.decode_all(&fr, &mut out).expect("ruzstd dict");- acc.t_zstd_dict_ns += td.elapsed().as_nanos() as u64;- assert_eq!(&out[..n], payload, "ruzstd dict round trip");- }- } else {- acc.add("codec:zstdRS_19_dict", H + rs19.len());- }- for t in &tnames {- let nb = apply(t, &body, e.z, &ids);- if t.starts_with("hm_") && !t.contains("delta") {- if let (Some(o), Some(n)) = (&body.heightmap, &nb.heightmap) {- let (m, ss, c) = hm_err(o, n);- let ent = acc.hm_err.entry(t.to_string()).or_insert((0.0, 0.0, 0));- ent.0 = ent.0.max(m);- ent.1 += ss;- ent.2 += c;- }- }- let r = ser(&nb);- if *t == "identity_v10" && r == raw {- acc.identical_v10 += 1;- }- acc.add(&format!("xf:{t}:raw"), r.len());- acc.add(&format!("xf:{t}:zstdC19"), H + zstd_c(&r[H..], 19));- if let Some(c) = cdicts[bi].as_mut() {- acc.add(&format!("xf:{t}:zstdC19dict"), H + zstd_c_dict(c, &r[H..]).len());- }- }- }- let mut g = acc.lock().unwrap();- for (z, l) in local {- g.entry(z).or_default().merge(&l);- }- let d = done.fetch_add(chunk.len(), std::sync::atomic::Ordering::Relaxed) + chunk.len();- if d % 20_000 < 64 {- eprintln!(" {d}/{} ({:.0}s)", sample.len(), t0.elapsed().as_secs_f64());- }- });- let acc = acc.into_inner().unwrap();-- // Report: per-variant planet projection (ratio estimator per zoom).- let mut out = String::new();- let total_exact: u64 = exact.values().map(|v| v.1).sum();- out += &format!("archive {path}\nunique bodies {} exact stored {:.3} GB\n\n", ents.len(), total_exact as f64 / 1e9);- out += "zoom bodies sampled exact_GB ratio_raw/stored identical_v10 hm_dims\n";- for (z, a) in &acc {- let (c, s) = exact[z];- out += &format!(- "z{:<3} {:>9} {:>7} {:>8.3} {:>8.3} {:>8}/{:<8} {:?}\n",- z, c, a.n, s as f64 / 1e9, a.raw as f64 / a.stored as f64, a.identical_v10, a.n, a.hm_dims- );- }- let keys: Vec<String> = acc.values().flat_map(|a| a.v.keys().cloned()).collect::<std::collections::BTreeSet<_>>().into_iter().collect();- out += "\nvariant planet_GB delta_GB per-band GB (z0-9 z10-11 z12 z13 z14)\n";- let mut tsv = String::from("variant\tplanet_gb\tdelta_gb\tz0_9\tz10_11\tz12\tz13\tz14\n");- for k in &keys {- let mut total = 0.0;- let mut per_band = [0.0f64; 5];- for (z, a) in &acc {- let (_, s) = exact[z];- let v = *a.v.get(k).unwrap_or(&0) as f64;- let est = s as f64 * v / a.stored as f64;- total += est;- per_band[band(*z)] += est;- }- let delta = total - total_exact as f64;- out += &format!(- "{:<40} {:>10.3} {:>10.3} {}\n",- k,- total / 1e9,- delta / 1e9,- per_band.iter().map(|g| format!("{:.2}", g / 1e9)).collect::<Vec<_>>().join(" ")- );- tsv += &format!(- "{k}\t{:.4}\t{:.4}\t{}\n",- total / 1e9,- delta / 1e9,- per_band.iter().map(|g| format!("{:.4}", g / 1e9)).collect::<Vec<_>>().join("\t")- );- }- // Decode timing (host, per body, single thread inside a rayon worker).- out += "\nhost decode time per body (us): inflate(DEFLATE, current) | ruzstd(zstd-rs 19) | ruzstd+dict | Body::parse\n";- for (z, a) in &acc {- let n = a.n.max(1) as f64;- out += &format!(- "z{:<3} {:>8.1} {:>8.1} {:>8.1} {:>8.1} (avg raw {:.0} B)\n",- z,- a.t_inflate_ns as f64 / n / 1e3,- a.t_zstd_ns as f64 / n / 1e3,- a.t_zstd_dict_ns as f64 / n / 1e3,- a.t_parse_ns as f64 / n / 1e3,- a.raw as f64 / n- );- }- let mut all = Acc::default();- for a in acc.values() {- all.merge(a);- }- let n = all.n as f64;- out += &format!(- "all {:>8.1} {:>8.1} {:>8.1} {:>8.1}\n",- all.t_inflate_ns as f64 / n / 1e3,- all.t_zstd_ns as f64 / n / 1e3,- all.t_zstd_dict_ns as f64 / n / 1e3,- all.t_parse_ns as f64 / n / 1e3- );- out += "\nDEM error vs current archive grid (metres; max over the continuous bilinear surface):\n";- for (k, (m, ss, n)) in &all.hm_err {- out += &format!(" {:<14} max {:>6.2} rms {:>6.3}\n", k, m, (ss / (*n).max(1) as f64).sqrt());- }- out += &format!("total {:.0}s\n", t0.elapsed().as_secs_f64());- print!("{out}");- std::fs::write(format!("{out_dir}/bodies.txt"), &out).unwrap();- std::fs::write(format!("{out_dir}/bodies.tsv"), &tsv).unwrap();-}--// ---------------------------------------------------------------- sidecars--fn kind_name(k: u8) -> &'static str {- match k {- 1 => "graph_meta",- 2 => "graph_nodes",- 3 => "graph_edges",- 4 => "graph_intermediate",- 5 => "graph_names",- 6 => "graph_lanes",- 7 => "graph_elevation",- 8 => "poi_index",- 9 => "poi_names",- 10 => "poi_attrs",- 11 => "poi_spatial",- 12 => "poi_words",- 13 => "transit",- 14 => "graph_overlay",- 15 => "poi_region",- 16 => "poi_admin",- _ => "?",- }-}--fn cmd_sidecars(path: &str, windows: usize, out_dir: &str) {- let a = open(path);- let view = tilecodec::mamaps::archive::ArchiveView::parse(&a.map, &a.hdr).expect("view");- let mut out = String::from("section bytes_GB zblk sampled_MB zstdC19_64K zstdRS19_64K zstdC19_1M xz9e_1M(ref) est_GB(C19_64K)\n");- let mut tsv = String::from("section\tbytes\tzblk\tratio_c19_64k\tratio_rs19_64k\tratio_c19_1m\test_gb_c19_64k\n");- for e in &view.entries {- let sec = &a.map[e.offset as usize..(e.offset + e.len) as usize];- let is_zblk = sec.len() > 4 && &sec[..4] == b"ZBLK";- if is_zblk {- // Decode the ZBLK and recompress its blocks at higher levels.- let b = tilecodec::blocked::Blocked::parse(sec).expect("zblk");- let nb = b.block_count();- let step = (nb / windows.max(1)).max(1);- let idxs: Vec<usize> = (0..nb).step_by(step).collect();- let r: Vec<(u64, u64, u64, u64, u64)> = idxs- .par_iter()- .map(|&i| {- let raw = b.block(i).expect("block");- let stored = b.block_offset(i + 1).unwrap() - b.block_offset(i).unwrap();- (raw.len() as u64, stored, zstd_c(&raw, 19) as u64, zstd_c(&raw, 22) as u64, zstd_rs(&raw, 19).len() as u64)- })- .collect();- let (raw, st, c19, c22, rs19) = r.iter().fold((0, 0, 0, 0, 0), |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2, a.3 + b.3, a.4 + b.4));- let unpacked = b.unpacked_len();- out += &format!(- "{:<22} {:>8.3} ZBLK unpacked {:.3} GB, sample {} blocks: current {:.3}x C19 {:.3}x C22 {:.3}x RS19 {:.3}x -> est C19 {:.3} GB\n",- kind_name(e.kind),- e.len as f64 / 1e9,- unpacked as f64 / 1e9,- idxs.len(),- raw as f64 / st as f64,- raw as f64 / c19 as f64,- raw as f64 / c22 as f64,- raw as f64 / rs19 as f64,- e.len as f64 * c19 as f64 / st as f64 / 1e9- );- tsv += &format!("{}\t{}\t1\t{:.4}\t{:.4}\t\t{:.4}\n", kind_name(e.kind), e.len, raw as f64 / c19 as f64, raw as f64 / rs19 as f64, e.len as f64 * c19 as f64 / st as f64 / 1e9);- continue;- }- let win = 1usize << 20;- let blk = 64usize << 10;- let n = windows.min((sec.len() / win).max(1));- let starts: Vec<usize> = if sec.len() <= win * windows {- (0..sec.len()).step_by(win).collect()- } else {- (0..n).map(|i| (sec.len() - win) / n.max(1) * i).collect()- };- let r: Vec<(u64, u64, u64, u64)> = starts- .par_iter()- .map(|&s| {- let w = &sec[s..(s + win).min(sec.len())];- let mut c19 = 0u64;- let mut rs19 = 0u64;- for b in w.chunks(blk) {- c19 += zstd_c(b, 19) as u64;- rs19 += zstd_rs(b, 19).len() as u64;- }- (w.len() as u64, c19, rs19, zstd_c(w, 19) as u64)- })- .collect();- let (raw, c19, rs19, c1m) = r.iter().fold((0, 0, 0, 0), |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2, a.3 + b.3));- out += &format!(- "{:<22} {:>8.3} raw {:>9.1} {:>9.3}x {:>9.3}x {:>9.3}x {:>12} {:>8.3}\n",- kind_name(e.kind),- e.len as f64 / 1e9,- raw as f64 / 1e6,- raw as f64 / c19 as f64,- raw as f64 / rs19 as f64,- raw as f64 / c1m as f64,- "-",- e.len as f64 * c19 as f64 / raw as f64 / 1e9- );- tsv += &format!(- "{}\t{}\t0\t{:.4}\t{:.4}\t{:.4}\t{:.4}\n",- kind_name(e.kind),- e.len,- raw as f64 / c19 as f64,- raw as f64 / rs19 as f64,- raw as f64 / c1m as f64,- e.len as f64 * c19 as f64 / raw as f64 / 1e9- );- }- print!("{out}");- std::fs::write(format!("{out_dir}/sidecars.txt"), &out).unwrap();- std::fs::write(format!("{out_dir}/sidecars.tsv"), &tsv).unwrap();- let _ = std::io::stdout().flush();-}--include!("more.rs");-include!("p50.rs");--fn main() {- let args: Vec<String> = std::env::args().collect();- let mode = args.get(1).map(String::as_str).unwrap_or("");- if mode == "render" {- return cmd_render(&args);- }- if mode == "cmp" {- // size_lab cmp BASE CAND PER_ZOOM OUT_DIR- std::fs::create_dir_all(&args[5]).unwrap();- return cmd_cmp(&args[2], &args[3], args[4].parse().unwrap(), &args[5]);- }- let path = args.get(2).expect("usage: size_lab bodies|sidecars IN.mamaps [N] [OUT_DIR]");- let out_dir = args.get(4).cloned().unwrap_or_else(|| ".".into());- std::fs::create_dir_all(&out_dir).unwrap();- match mode {- "bodies" => cmd_bodies(path, args.get(3).and_then(|s| s.parse().ok()).unwrap_or(2000), &out_dir),- "sidecars" => cmd_sidecars(path, args.get(3).and_then(|s| s.parse().ok()).unwrap_or(64), &out_dir),- "transit" => cmd_transit(path, &out_dir),- "zblk" => cmd_zblk(path),- "zooms" => cmd_zooms(path),- "p50-layers" => cmd_p50_layers(path, args[3].parse().unwrap()),- "p50-pyramid" => cmd_p50_pyramid(path, args[3].parse().unwrap()),- "p50-buildings" => cmd_p50_buildings(path, args[3].parse().unwrap()),- "p50-super" => cmd_p50_super(path, args[3].parse().unwrap(), args[4].parse().unwrap()),- "p50-arcs" => cmd_p50_arcs(path, args[3].parse().unwrap()),- "recompress" => cmd_recompress(path, args.get(3).map(String::as_str).unwrap_or(".")),- "dem-pyramid" => cmd_dem_pyramid(path, args[3].parse().unwrap(), &out_dir),- _ => eprintln!("usage: size_lab bodies|sidecars IN.mamaps [N] [OUT_DIR]"),- }-}
scripts/maps/tile_build/examples/size_lab/more.rs
diff --git a/scripts/maps/tile_build/examples/size_lab/more.rs b/scripts/maps/tile_build/examples/size_lab/more.rsdeleted file mode 100644index eb6cc2561c..0000000000--- a/scripts/maps/tile_build/examples/size_lab/more.rs+++ /dev/null@@ -1,1097 +0,0 @@-// Included into size_lab.rs: recompress / cmp / render / dem-pyramid modes.--/// A 2D point in tile-local coordinates.-type Pt2 = (f64, f64);-/// A line segment between two [`Pt2`]s.-type Seg = (Pt2, Pt2);-/// Per-`(zoom, layer)` deviation accumulators.-type DevMap = BTreeMap<(u8, u8), DevAcc>;-/// DEM deviation stats: `(mean, max, count, raw, stored)`.-type DemStats = (f64, f64, u64, u64, u64);-/// Per-zoom [`DemStats`].-type DemMap = BTreeMap<u8, DemStats>;-/// One dem-pyramid row: `(tile id, heightmap, ancestor, saved bytes)`.-type DemRow = (u64, Option<Heightmap>, Option<(u8, u64, u64)>, i64);--/// Every leaf entry with its first tile id, sorted by tile id (not deduplicated).-struct TileIndex {- ents: Vec<(u64, u32, u64, u32)>, // (tile_id, run_length, abs offset, len)-}--impl TileIndex {- fn build(a: &Arch) -> TileIndex {- let hdr = &a.hdr;- let root = index::parse_root(&a.map[hdr.root_offset as usize..(hdr.root_offset + hdr.root_len as u64) as usize]).expect("root");- let per: Vec<Vec<(u64, u32, u64, u32)>> = root- .par_iter()- .map(|re| {- let raw_len = re.leaf_entry_count as usize * index::LEAF_ENTRY_LEN;- let at = (hdr.leaf_offset + re.leaf_offset) as usize;- let raw = if re.stored_len == 0 {- a.map[at..at + raw_len].to_vec()- } else {- index::decompress_leaf(&a.map[at..at + re.stored_len as usize], raw_len).expect("leaf")- };- index::parse_leaf(&raw)- .expect("leaf")- .iter()- .map(|e| (re.base_tile_id + e.tile_id_lo as u64, e.run_length, hdr.data_offset + re.base_data_offset + e.offset_delta as u64, e.length))- .collect()- })- .collect();- let mut ents: Vec<_> = per.into_iter().flatten().collect();- ents.sort_by_key(|e| e.0);- TileIndex { ents }- }- fn find(&self, id: u64) -> Option<(u64, u32)> {- let i = self.ents.partition_point(|e| e.0 <= id);- if i == 0 {- return None;- }- let e = self.ents[i - 1];- (id < e.0 + e.1 as u64).then_some((e.2, e.3))- }-}--fn body_at(a: &Arch, id: u64, off: u64, len: u32) -> Body {- let stored = &a.map[off as usize..off as usize + len as usize];- let raw = tile_build::mamaps::read::decompress_with(a.hdr.compression, stored, a.zd.as_ref()).expect("inflate");- // header v11: a superblock frame holds this tile's body among its neighbours'- let raw = tile_build::mamaps::superblock::resolve(raw, id).expect("superblock member");- Body::parse(&raw).expect("parse")-}--// ------------------------------------------------------------ recompress (exact, whole archive)--fn cmd_recompress(path: &str, out_dir: &str) {- let a = open(path);- let t0 = Instant::now();- let ents = entries(&a);- let total_now: u64 = ents.iter().map(|e| e.len as u64).sum();- // Dictionaries per zoom band from a 1-in-N sample (<= 20k bodies per band).- let mut by_band: Vec<Vec<Ent>> = vec![Vec::new(); 5];- for e in &ents {- by_band[band(e.z)].push(*e);- }- let dicts: Vec<Vec<u8>> = by_band- .par_iter()- .map(|v| {- if v.len() < 64 {- return Vec::new();- }- let step = (v.len() / 20_000).max(1);- let samples: Vec<Vec<u8>> = v.iter().step_by(step).map(|e| raw_of(&a, e)[H..].to_vec()).collect();- zstd::dict::from_samples(&samples, 112 * 1024).unwrap_or_default()- })- .collect();- let dict_bytes: usize = dicts.iter().map(|d| d.len()).sum();- let rs_dicts: Vec<Option<zstd_rs::EncoderDictionary>> = dicts- .iter()- .map(|d| {- if d.is_empty() {- return None;- }- let dd = zstd_rs::Dictionary::new(d, zstd_rs::DictionaryFormat::Zstd).ok()?;- zstd_rs::EncoderDictionary::new(&dd, 19).ok()- })- .collect();- #[derive(Default, Clone, Copy)]- struct S {- n: u64,- now: u64,- raw: u64,- rs19: u64,- rs19d: u64,- c19: u64,- c22: u64,- t_now: u64,- t_zstd: u64,- }- let acc: Mutex<[S; 15]> = Mutex::new([S::default(); 15]);- ents.par_chunks(256).for_each(|chunk| {- let mut loc = [S::default(); 15];- let mut dec = ruzstd::decoding::FrameDecoder::new();- for e in chunk {- let stored = a.map[e.off as usize..e.off as usize + e.len as usize].to_vec();- let t = Instant::now();- let raw = tile_build::mamaps::read::decompress_with(a.hdr.compression, &stored, a.zd.as_ref()).expect("inflate");- let _ = Body::parse(&raw).expect("parse");- let t_now = t.elapsed().as_nanos() as u64;- let p = &raw[H..];- let rs = zstd_rs(p, 19);- let t = Instant::now();- let mut out = vec![0u8; p.len()];- dec.decode_all(&rs, &mut out).expect("ruzstd");- let mut full = raw[..H].to_vec();- full.extend_from_slice(&out);- let _ = Body::parse(&full).expect("parse zstd");- let t_z = t.elapsed().as_nanos() as u64;- let s = &mut loc[e.z.min(14) as usize];- s.n += 1;- s.now += e.len as u64;- s.raw += raw.len() as u64;- s.rs19 += (H + rs.len()) as u64;- s.rs19d += (H + match &rs_dicts[band(e.z)] {- Some(d) => zstd_rs_dict(p, 19, d).len(),- None => rs.len(),- }) as u64;- s.c19 += (H + zstd_c(p, 19)) as u64;- s.c22 += (H + zstd_c(p, 22)) as u64;- s.t_now += t_now;- s.t_zstd += t_z;- }- let mut g = acc.lock().unwrap();- for z in 0..15 {- let (o, l) = (&mut g[z], loc[z]);- o.n += l.n;- o.now += l.now;- o.raw += l.raw;- o.rs19 += l.rs19;- o.rs19d += l.rs19d;- o.c19 += l.c19;- o.c22 += l.c22;- o.t_now += l.t_now;- o.t_zstd += l.t_zstd;- }- });- let g = acc.into_inner().unwrap();- let mut out = format!(- "archive {path}\nunique bodies {} tile data now {:.4} GB (all, every body recompressed; exact)\ndictionaries: {} B total (5 zoom bands, 112 KiB each)\n",- ents.len(),- total_now as f64 / 1e9,- dict_bytes- );- out += "zoom bodies now_MB raw_MB zstdRS19 zstdRS19+dict zstdC19 zstdC22 decode_us(now) decode_us(zstd)\n";- let mut t = S::default();- for (z, &s) in g.iter().enumerate() {- if s.n == 0 {- continue;- }- out += &format!(- "z{z:<3} {:>9} {:>8.1} {:>8.1} {:>9.1} {:>12.1} {:>9.1} {:>8.1} {:>12.1} {:>12.1}\n",- s.n,- s.now as f64 / 1e6,- s.raw as f64 / 1e6,- s.rs19 as f64 / 1e6,- s.rs19d as f64 / 1e6,- s.c19 as f64 / 1e6,- s.c22 as f64 / 1e6,- s.t_now as f64 / s.n as f64 / 1e3,- s.t_zstd as f64 / s.n as f64 / 1e3- );- t.n += s.n;- t.now += s.now;- t.raw += s.raw;- t.rs19 += s.rs19;- t.rs19d += s.rs19d;- t.c19 += s.c19;- t.c22 += s.c22;- t.t_now += s.t_now;- t.t_zstd += s.t_zstd;- }- out += &format!(- "TOTAL {:>9} {:>8.1} {:>8.1} {:>9.1} {:>12.1} {:>9.1} {:>8.1} {:>12.1} {:>12.1}\n",- t.n,- t.now as f64 / 1e6,- t.raw as f64 / 1e6,- t.rs19 as f64 / 1e6,- (t.rs19d as f64 + dict_bytes as f64) / 1e6,- t.c19 as f64 / 1e6,- t.c22 as f64 / 1e6,- t.t_now as f64 / t.n as f64 / 1e3,- t.t_zstd as f64 / t.n as f64 / 1e3- );- out += &format!("RECOMPRESS_TSV\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n", t.now, t.rs19, t.rs19d + dict_bytes as u64, t.c19, t.c22, t.t_now / t.n.max(1), t.t_zstd / t.n.max(1));- out += &format!("(decode = decompress + Body::parse on one host core; {:.0}s)\n", t0.elapsed().as_secs_f64());- print!("{out}");- std::fs::write(format!("{out_dir}/recompress.txt"), &out).unwrap();-}--// ------------------------------------------------------------ geometry / DEM comparison--struct SegGrid {- cell: f64,- origin: f64,- n: usize,- cells: Vec<Vec<u32>>,- segs: Vec<((f64, f64), (f64, f64))>,-}--impl SegGrid {- fn new(segs: Vec<((f64, f64), (f64, f64))>) -> SegGrid {- let (origin, span, n) = (-1024.0, 6144.0, 48usize);- let cell = span / n as f64;- let mut cells = vec![Vec::new(); n * n];- let ci = |v: f64| (((v - origin) / cell).floor() as i64).clamp(0, n as i64 - 1) as usize;- for (k, (a, b)) in segs.iter().enumerate() {- let (x0, x1) = (ci(a.0.min(b.0)), ci(a.0.max(b.0)));- let (y0, y1) = (ci(a.1.min(b.1)), ci(a.1.max(b.1)));- for y in y0..=y1 {- for x in x0..=x1 {- cells[y * n + x].push(k as u32);- }- }- }- SegGrid { cell, origin, n, cells, segs }- }- /// Distance to the nearest segment, or None beyond `cap`.- fn nearest(&self, p: (f64, f64), cap: f64) -> Option<f64> {- let n = self.n as i64;- let cx = ((p.0 - self.origin) / self.cell).floor() as i64;- let cy = ((p.1 - self.origin) / self.cell).floor() as i64;- let mut best = f64::INFINITY;- let rmax = (cap / self.cell).ceil() as i64 + 1;- for r in 0..=rmax {- if best.is_finite() && best <= (r as f64 - 1.0).max(0.0) * self.cell {- break;- }- for y in cy - r..=cy + r {- for x in cx - r..=cx + r {- if (y - cy).abs() != r && (x - cx).abs() != r {- continue;- }- if x < 0 || y < 0 || x >= n || y >= n {- continue;- }- for &k in &self.cells[(y * n + x) as usize] {- let (a, b) = self.segs[k as usize];- best = best.min(seg_dist_sq_f(p, a, b).sqrt());- }- }- }- }- (best <= cap).then_some(best)- }-}--fn seg_dist_sq_f(p: (f64, f64), a: (f64, f64), b: (f64, f64)) -> f64 {- let (dx, dy) = (b.0 - a.0, b.1 - a.1);- let l2 = dx * dx + dy * dy;- let t = if l2 == 0.0 { 0.0 } else { (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / l2).clamp(0.0, 1.0) };- let (qx, qy) = (a.0 + t * dx, a.1 + t * dy);- (p.0 - qx).powi(2) + (p.1 - qy).powi(2)-}--fn layer_segs_pts(l: &Layer) -> (Vec<Seg>, Vec<Pt2>) {- let mut segs = Vec::new();- let mut pts = Vec::new();- for f in &l.features {- if f.geom_type == GEOM_POINT {- continue;- }- let from = f.parts_offset as usize;- for p in &l.parts[from..from + f.part_count as usize] {- let v = l.points(p);- for w in v.windows(2) {- segs.push(((w[0].0 as f64, w[0].1 as f64), (w[1].0 as f64, w[1].1 as f64)));- }- if f.geom_type == GEOM_POLYGON && v.len() > 2 && v.first() != v.last() {- let (a, b) = (v[v.len() - 1], v[0]);- segs.push(((a.0 as f64, a.1 as f64), (b.0 as f64, b.1 as f64)));- }- pts.extend(v.iter().map(|q| (q.0 as f64, q.1 as f64)));- }- }- (segs, pts)-}--fn tile_lat(z: u8, y: u64) -> f64 {- let n = std::f64::consts::PI * (1.0 - 2.0 * (y as f64 + 0.5) / (1u64 << z) as f64);- n.sinh().atan().to_degrees()-}--/// Metres per extent unit for tile (z, y).-fn m_per_unit(z: u8, y: u64) -> f64 {- 40_075_016.686 * tile_lat(z, y).to_radians().cos() / (1u64 << z) as f64 / 4096.0-}--#[derive(Default, Clone)]-struct DevAcc {- n: u64,- sum_m: f64,- max_m: f64,- max_units: f64,- hist: Vec<u64>, // 0.01-unit buckets up to the cap (32 units)- missing: u64,- sym_max_u: f64,-}-impl DevAcc {- fn add(&mut self, d_units: f64, mpu: f64) {- if self.hist.is_empty() {- self.hist = vec![0; 3_201];- }- let m = d_units * mpu;- self.n += 1;- self.sum_m += m;- self.max_m = self.max_m.max(m);- self.max_units = self.max_units.max(d_units);- self.hist[((d_units * 100.0) as usize).min(3_200)] += 1;- }- fn merge(&mut self, o: &DevAcc) {- if self.hist.is_empty() {- self.hist = vec![0; 3_201];- }- if o.hist.is_empty() {- self.missing += o.missing;- return;- }- self.n += o.n;- self.sum_m += o.sum_m;- self.max_m = self.max_m.max(o.max_m);- self.max_units = self.max_units.max(o.max_units);- self.missing += o.missing;- self.sym_max_u = self.sym_max_u.max(o.sym_max_u);- for (a, b) in self.hist.iter_mut().zip(o.hist.iter()) {- *a += b;- }- }- fn pct(&self, q: f64) -> f64 {- let target = (self.n as f64 * q).ceil() as u64;- let mut c = 0;- for (i, h) in self.hist.iter().enumerate() {- c += h;- if c >= target {- return i as f64 / 100.0;- }- }- 32.0- }-}--fn cmd_cmp(base: &str, cand: &str, per_zoom: usize, out_dir: &str) {- let a = open(base);- let b = open(cand);- let ia = TileIndex::build(&a);- let ib = TileIndex::build(&b);- let mut by_z: BTreeMap<u8, Vec<(u64, u64, u32)>> = BTreeMap::new();- for &(id, _, off, len) in &ia.ents {- let (z, _, _) = tile_zxy(id);- by_z.entry(z).or_default().push((id, off, len));- }- let mut sample = Vec::new();- for v in by_z.values() {- let step = (v.len() / per_zoom.max(1)).max(1);- sample.extend(v.iter().step_by(step).copied());- }- let nl = a.dict.layers.len();- // key (zoom, layer) -> deviations; DEM per zoom- let acc: Mutex<(DevMap, DemMap)> = Mutex::new((BTreeMap::new(), BTreeMap::new()));- let cap = 32.0;- sample.par_chunks(32).for_each(|chunk| {- let mut dev: BTreeMap<(u8, u8), DevAcc> = BTreeMap::new();- let mut dem: BTreeMap<u8, (f64, f64, u64, u64, u64)> = BTreeMap::new();- for &(id, off, len) in chunk {- let (z, _x, y) = tile_zxy(id);- let Some((boff, blen)) = ib.find(id) else { continue };- let ba = body_at(&a, id, off, len);- let bb = body_at(&b, id, boff, blen);- let mpu = m_per_unit(z, y);- for lid in 0..nl as u8 {- let (la, lb) = (ba.layer(lid), bb.layer(lid));- let Some(la) = la else { continue };- let (sa, pa) = layer_segs_pts(la);- if pa.is_empty() {- continue;- }- let d = dev.entry((z, lid)).or_default();- let Some(lb) = lb else {- d.missing += pa.len() as u64;- continue;- };- let (sb, pb) = layer_segs_pts(lb);- if sb.is_empty() {- d.missing += pa.len() as u64;- continue;- }- let gb = SegGrid::new(sb);- // A -> B: how far each original vertex now is from the candidate geometry.- for p in &pa {- match gb.nearest(*p, cap) {- Some(dd) => d.add(dd, mpu),- None => d.missing += 1,- }- }- // B -> A (symmetric Hausdorff half): candidate vertices against the original.- if !sa.is_empty() {- let ga = SegGrid::new(sa);- for p in &pb {- if let Some(dd) = ga.nearest(*p, cap) {- d.sym_max_u = d.sym_max_u.max(dd);- }- }- }- }- // DEM: both bilinear surfaces on a 33x33 lattice.- let e = dem.entry(z).or_insert((0.0, 0.0, 0, 0, 0));- match (&ba.heightmap, &bb.heightmap) {- (Some(ha), Some(hb)) => {- for r in 0..33 {- for c in 0..33 {- let (fr, fc) = (r as f64 / 32.0, c as f64 / 32.0);- let d = (bilin(&ha.samples, ha.dim as usize, fr, fc) - bilin(&hb.samples, hb.dim as usize, fr, fc)).abs();- e.0 = e.0.max(d);- e.1 += d * d;- e.2 += 1;- }- }- }- (Some(_), None) | (None, Some(_)) => e.3 += 1,- _ => {}- }- e.4 += 1;- }- let mut g = acc.lock().unwrap();- for (k, v) in dev {- g.0.entry(k).or_default().merge(&v);- }- for (k, v) in dem {- let e = g.1.entry(k).or_insert((0.0, 0.0, 0, 0, 0));- e.0 = e.0.max(v.0);- e.1 += v.1;- e.2 += v.2;- e.3 += v.3;- e.4 += v.4;- }- });- let (dev, dem) = acc.into_inner().unwrap();- let mut out = format!("cmp base={base}\n cand={cand}\n(sampled {} tiles; deviation = distance from each base vertex to the candidate's geometry in the same tile/layer, in extent units (1/4096 tile) and metres; vertices with nothing within 32 units = dropped features; Hausdorff_u = max(base->cand, cand->base) over matched geometry. px: 1 unit = 1/16 px at the tile's own zoom (256-px tiles), 1/4 px for a z14 tile at z16, 1 px at z18)\n", sample.len());- out += "band layer verts mean_m max_m p50_u p99_u p99.9_u max_u hausdorff_u dropped%\n";- let bands: [(&str, std::ops::RangeInclusive<u8>); 5] = [("z0-9", 0..=9), ("z10-11", 10..=11), ("z12", 12..=12), ("z13", 13..=13), ("z14", 14..=14)];- let mut tsv = String::from("band\tlayer\tverts\tmean_m\tmax_m\tp99_u\tp999_u\tmax_u\thausdorff_u\tdropped_pct\n");- for (bn, r) in bands.iter() {- for lid in 0..nl as u8 {- let mut d = DevAcc::default();- for z in r.clone() {- if let Some(v) = dev.get(&(z, lid)) {- d.merge(v);- }- }- if d.n == 0 {- continue;- }- let name = a.dict.layers[lid as usize].clone();- let miss = 100.0 * d.missing as f64 / (d.n + d.missing).max(1) as f64;- out += &format!(- "{bn:<8} {name:<11} {:>9} {:>8.3} {:>7.2} {:>6.2} {:>6.2} {:>7.2} {:>6.2} {:>11.2} {:>9.4}\n",- d.n,- d.sum_m / d.n as f64,- d.max_m,- d.pct(0.5),- d.pct(0.99),- d.pct(0.999),- d.max_units,- d.max_units.max(d.sym_max_u),- miss- );- tsv += &format!("{bn}\t{name}\t{}\t{:.4}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{:.4}\n", d.n, d.sum_m / d.n as f64, d.max_m, d.pct(0.99), d.pct(0.999), d.max_units, d.max_units.max(d.sym_max_u), miss);- }- }- out += "\nDEM (candidate vs base surface, 33x33 lattice per tile; metres)\n";- let (mut gm, mut gs, mut gn) = (0.0f64, 0.0f64, 0u64);- for (z, (m, ss, n, mism, tiles)) in &dem {- if *n == 0 && *mism == 0 {- continue;- }- gm = gm.max(*m);- gs += ss;- gn += n;- out += &format!(" z{z:<2} tiles {tiles:>7} max {m:>8.2} rms {:>7.3} presence_mismatch {mism}\n", (ss / (*n).max(1) as f64).sqrt());- }- out += &format!(" all max {gm:.2} rms {:.3}\n", (gs / gn.max(1) as f64).sqrt());- tsv += &format!("DEM\tall\t{gn}\t\t\t{gm:.3}\t\t\t{:.4}\n", (gs / gn.max(1) as f64).sqrt());- print!("{out}");- std::fs::write(format!("{out_dir}/cmp.txt"), &out).unwrap();- std::fs::write(format!("{out_dir}/cmp.tsv"), &tsv).unwrap();-}--// ------------------------------------------------------------ render--struct Canvas {- w: usize,- h: usize,- px: Vec<[u8; 3]>,-}--impl Canvas {- fn new(w: usize, h: usize, bg: [u8; 3]) -> Canvas {- Canvas { w, h, px: vec![bg; w * h] }- }- fn blend(&mut self, x: i64, y: i64, c: [u8; 3], a: f32) {- if x < 0 || y < 0 || x as usize >= self.w || y as usize >= self.h {- return;- }- let p = &mut self.px[y as usize * self.w + x as usize];- for i in 0..3 {- p[i] = (p[i] as f32 * (1.0 - a) + c[i] as f32 * a) as u8;- }- }- /// Even-odd scanline fill of a set of rings (pixel coords).- fn fill(&mut self, rings: &[Vec<(f64, f64)>], c: [u8; 3], a: f32) {- let (mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY);- for r in rings {- for p in r {- y0 = y0.min(p.1);- y1 = y1.max(p.1);- }- }- let ys = (y0.floor().max(0.0)) as i64;- let ye = (y1.ceil().min(self.h as f64 - 1.0)) as i64;- let mut xs: Vec<f64> = Vec::new();- for y in ys..=ye {- let fy = y as f64 + 0.5;- xs.clear();- for r in rings {- let n = r.len();- for i in 0..n {- let (p, q) = (r[i], r[(i + 1) % n]);- if (p.1 <= fy) != (q.1 <= fy) {- xs.push(p.0 + (fy - p.1) / (q.1 - p.1) * (q.0 - p.0));- }- }- }- xs.sort_by(|a, b| a.partial_cmp(b).unwrap());- for pair in xs.chunks(2) {- if pair.len() < 2 {- break;- }- let (xa, xb) = ((pair[0].round().max(0.0)) as i64, (pair[1].round().min(self.w as f64)) as i64);- for x in xa..xb {- self.blend(x, y, c, a);- }- }- }- }- fn line(&mut self, p: (f64, f64), q: (f64, f64), wpx: f64, c: [u8; 3]) {- let len = ((q.0 - p.0).powi(2) + (q.1 - p.1).powi(2)).sqrt();- let steps = (len * 2.0).ceil().max(1.0) as usize;- let r = (wpx / 2.0).max(0.5);- let ri = r.ceil() as i64;- for s in 0..=steps {- let t = s as f64 / steps as f64;- let (x, y) = (p.0 + (q.0 - p.0) * t, p.1 + (q.1 - p.1) * t);- for dy in -ri..=ri {- for dx in -ri..=ri {- if ((dx * dx + dy * dy) as f64) <= r * r {- self.blend(x.round() as i64 + dx, y.round() as i64 + dy, c, 1.0);- }- }- }- }- }-}--fn kind_style(name: &str) -> Option<[u8; 3]> {- let n = name;- Some(if n.contains("water") || n == "lake" || n == "river" || n == "bay" || n == "strait" || n == "reservoir" || n == "ocean" || n == "canal" || n == "stream" || n == "basin" {- [170, 211, 223]- } else if n.contains("forest") || n.contains("wood") || n == "nature_reserve" || n == "national_park" || n == "protected_area" {- [173, 209, 158]- } else if n.contains("grass") || n == "park" || n == "meadow" || n == "golf_course" || n == "recreation_ground" || n == "cemetery" || n == "scrub" {- [205, 235, 176]- } else if n == "farmland" || n == "orchard" || n == "vineyard" || n == "allotments" {- [238, 240, 213]- } else if n == "residential" || n == "commercial" || n == "industrial" || n == "retail" {- [224, 223, 223]- } else if n == "sand" || n == "beach" || n == "bare_rock" || n == "glacier" || n == "wetland" || n == "quarry" {- [242, 239, 233]- } else {- return None;- })-}--fn render_body(body: &Body, dict: &Dictionary, z: u8, crop: (f64, f64, f64), size: usize, parent: Option<(&Body, u64, u64)>) -> Canvas {- let mut cv = Canvas::new(size, size, [242, 239, 233]);- let (cx, cy, cs) = crop;- let s = size as f64 / cs;- let to_px = |p: &(i16, i16)| ((p.0 as f64 - cx) * s, (p.1 as f64 - cy) * s);- let lid = |n: &str| dict.layers.iter().position(|l| l == n).map(|i| i as u8);- let draw_polys = |cv: &mut Canvas, l: &Layer, colour: &dyn Fn(u16) -> Option<[u8; 3]>, alpha: f32| {- for f in &l.features {- if f.geom_type != GEOM_POLYGON {- continue;- }- let Some(c) = colour(f.kind) else { continue };- let from = f.parts_offset as usize;- let rings: Vec<Vec<(f64, f64)>> = l.parts[from..from + f.part_count as usize].iter().map(|p| l.points(p).iter().map(to_px).collect()).collect();- cv.fill(&rings, c, alpha);- }- };- // The app stitches the z13 parent's wash under a z14 tile (z14 drops wash areas the parent- // already has): draw the parent's landtype polygons, mapped into this tile's frame.- if let Some((pb, qx, qy)) = parent {- if let Some(l) = lid("landtype").and_then(|i| pb.layer(i)) {- for f in &l.features {- if f.geom_type != GEOM_POLYGON {- continue;- }- let Some(c) = kind_style(dict.kind_name(f.kind).unwrap_or("")) else { continue };- let from = f.parts_offset as usize;- let rings: Vec<Vec<(f64, f64)>> = l.parts[from..from + f.part_count as usize]- .iter()- .map(|p| {- l.points(p)- .iter()- .map(|q| (((q.0 as f64 * 2.0 - qx as f64 * 4096.0) - cx) * s, ((q.1 as f64 * 2.0 - qy as f64 * 4096.0) - cy) * s))- .collect()- })- .collect();- cv.fill(&rings, c, 0.85);- }- }- }- if let Some(l) = lid("landtype").and_then(|i| body.layer(i)) {- draw_polys(&mut cv, l, &|k| kind_style(dict.kind_name(k).unwrap_or("")), 0.85);- for f in &l.features {- if f.geom_type == 1 {- let from = f.parts_offset as usize;- for p in &l.parts[from..from + f.part_count as usize] {- for w in l.points(p).windows(2) {- cv.line(to_px(&w[0]), to_px(&w[1]), 1.5, [130, 180, 210]);- }- }- }- }- }- // Hillshade over the fills (from the heightmap): per-node normals by central differences, shade- // interpolated across cells (Gouraud-like, as the app lights its terrain mesh per vertex).- if let Some(hm) = &body.heightmap {- let d = hm.dim as usize;- let cell_m = 40_075_016.686 / (1u64 << z) as f64 / (d - 1).max(1) as f64 * 0.75; // ~cos(41deg)- let h = |r: usize, c: usize| hm.samples[r.min(d - 1) * d + c.min(d - 1)] as f64;- let mut shade = vec![0.0f64; d * d];- for r in 0..d {- for c in 0..d {- let (c0, c1) = (c.saturating_sub(1), (c + 1).min(d - 1));- let (r0, r1) = (r.saturating_sub(1), (r + 1).min(d - 1));- let gx = (h(r, c1) - h(r, c0)) / ((c1 - c0).max(1) as f64 * cell_m) * 4.0;- let gy = (h(r1, c) - h(r0, c)) / ((r1 - r0).max(1) as f64 * cell_m) * 4.0;- shade[r * d + c] = ((-gx * 0.7 - gy * 0.7 + 1.0) / (1.0 + gx * gx + gy * gy).sqrt()).clamp(0.0, 1.4);- }- }- for py in 0..size {- for px in 0..size {- let (ux, uy) = ((cx + px as f64 / s) / 4096.0, (cy + py as f64 / s) / 4096.0);- if !(0.0..=1.0).contains(&ux) || !(0.0..=1.0).contains(&uy) {- continue;- }- let sh = {- let gr = uy * (d - 1) as f64;- let gc = ux * (d - 1) as f64;- let (r0, c0) = ((gr.floor() as usize).min(d - 1), (gc.floor() as usize).min(d - 1));- let (r1, c1) = ((r0 + 1).min(d - 1), (c0 + 1).min(d - 1));- let (fy, fx) = (gr - r0 as f64, gc - c0 as f64);- let t = shade[r0 * d + c0] * (1.0 - fx) + shade[r0 * d + c1] * fx;- let b = shade[r1 * d + c0] * (1.0 - fx) + shade[r1 * d + c1] * fx;- t * (1.0 - fy) + b * fy- };- let v = (sh * 180.0).clamp(0.0, 255.0) as u8;- cv.blend(px as i64, py as i64, [v, v, v], 0.45);- }- }- }- if let Some(l) = lid("buildings").and_then(|i| body.layer(i)) {- draw_polys(&mut cv, l, &|_| Some([200, 190, 180]), 1.0);- for f in &l.features {- let from = f.parts_offset as usize;- for p in &l.parts[from..from + f.part_count as usize] {- let v = l.points(p);- for i in 0..v.len() {- cv.line(to_px(&v[i]), to_px(&v[(i + 1) % v.len()]), 1.0, [150, 140, 130]);- }- }- }- }- if let Some(l) = lid("boundaries").and_then(|i| body.layer(i)) {- for f in &l.features {- let from = f.parts_offset as usize;- for p in &l.parts[from..from + f.part_count as usize] {- for w in l.points(p).windows(2) {- cv.line(to_px(&w[0]), to_px(&w[1]), 1.5, [160, 100, 170]);- }- }- }- }- if let Some(l) = lid("roads").and_then(|i| body.layer(i)) {- for pass in 0..2 {- for f in &l.features {- let name = dict.kind_name(f.kind).unwrap_or("");- let major = name.contains("highway") || name.contains("major") || name.contains("motorway") || name.contains("trunk") || name.contains("primary");- let w = if major { 5.0 } else if name.contains("path") || name.contains("foot") || name.contains("track") { 1.2 } else { 3.0 };- let (c, ww) = if pass == 0 { ([120, 120, 120], w + 1.5) } else if major { ([252, 214, 164], w) } else { ([255, 255, 255], w) };- let from = f.parts_offset as usize;- for p in &l.parts[from..from + f.part_count as usize] {- for wv in l.points(p).windows(2) {- cv.line(to_px(&wv[0]), to_px(&wv[1]), ww, c);- }- }- }- }- }- cv-}--fn write_png(path: &str, cv: &Canvas) {- let f = File::create(path).expect("png create");- let mut enc = png::Encoder::new(std::io::BufWriter::new(f), cv.w as u32, cv.h as u32);- enc.set_color(png::ColorType::Rgb);- enc.set_depth(png::BitDepth::Eight);- let mut w = enc.write_header().expect("png header");- let data: Vec<u8> = cv.px.iter().flat_map(|p| p.iter().copied()).collect();- w.write_image_data(&data).expect("png data");-}--/// `render OUT.png Z X Y CROP_Q ARCH [ARCH...]`: side-by-side renders of one tile from each-/// archive. CROP_Q = 1 renders the whole tile (its native zoom); 4 renders the top-left-of-centre-/// quarter-of-a-quarter, i.e. what the z+2 view of that tile shows (overzoom), and so on.-fn cmd_render(args: &[String]) {- let out = &args[2];- let z: u8 = args[3].parse().unwrap();- let x: u64 = args[4].parse().unwrap();- let y: u64 = args[5].parse().unwrap();- let q: f64 = args[6].parse().unwrap();- let archs = &args[7..];- let size = 768usize;- let cs = 4096.0 / q;- let crop = ((4096.0 - cs) / 2.0, (4096.0 - cs) / 2.0, cs);- let mut panels = Vec::new();- for p in archs {- let a = open(p);- let ix = TileIndex::build(&a);- let id = tilecodec::pmtiles::tile_id(z, x, y);- let cv = match ix.find(id) {- Some((off, len)) => {- let pid = tilecodec::pmtiles::tile_id(z - 1, x / 2, y / 2);- let parent = if z == 14 { ix.find(pid).map(|(o, l)| body_at(&a, pid, o, l)) } else { None };- render_body(&body_at(&a, id, off, len), &a.dict, z, crop, size, parent.as_ref().map(|p| (p, x % 2, y % 2)))- }- None => Canvas::new(size, size, [255, 0, 255]),- };- panels.push(cv);- }- let gap = 8;- let mut all = Canvas::new(size * panels.len() + gap * (panels.len() - 1), size, [255, 255, 255]);- for (i, p) in panels.iter().enumerate() {- for yy in 0..size {- for xx in 0..size {- all.px[yy * all.w + i * (size + gap) + xx] = p.px[yy * size + xx];- }- }- }- write_png(out, &all);- println!("wrote {out}");-}--// ------------------------------------------------------------ DEM pyramid redundancy--/// `dem-pyramid ARCH TOL_M`: how much the heightmaps would shrink if a tile whose grid is within-/// TOL_M of its nearest kept ancestor's (bilinearly upsampled) surface stored none and the-/// reader fell back to that ancestor (a format change: the shipped reader draws such a tile-/// flat). Measured exactly over every body: each body re-encoded without its heightmap and-/// zstd-19 compressed, against the same body with it.-fn cmd_dem_pyramid(path: &str, tol: f64, out_dir: &str) {- let a = open(path);- let ix = TileIndex::build(&a);- // Kept heightmaps per tile id, processed zoom by zoom (parents first).- let mut kept: std::collections::HashMap<u64, (u8, u64, u64)> = std::collections::HashMap::new(); // tile -> ancestor (z,x,y) whose grid serves it- let mut grids: std::collections::HashMap<u64, Heightmap> = std::collections::HashMap::new();- let mut by_z: BTreeMap<u8, Vec<(u64, u64, u32)>> = BTreeMap::new();- for &(id, _, off, len) in &ix.ents {- let (z, _, _) = tile_zxy(id);- by_z.entry(z).or_default().push((id, off, len));- }- let mut out = format!("dem-pyramid {path} tol={tol} m\n zoom with_dem dropped saved_MB(zstd19)\n");- let (mut tot_saved, mut tot_drop, mut tot_dem) = (0i64, 0u64, 0u64);- for (z, v) in &by_z {- let res: Vec<DemRow> = v- .par_iter()- .map(|&(id, off, len)| {- let (_, x, y) = tile_zxy(id);- let body = body_at(&a, id, off, len);- let Some(hm) = body.heightmap.clone() else { return (id, None, None, 0) };- if *z == 0 {- return (id, Some(hm), None, 0);- }- // Serving ancestor: the parent's own grid, or whatever serves the parent.- let pid = tilecodec::pmtiles::tile_id(z - 1, x / 2, y / 2);- let anc = kept.get(&pid).copied().unwrap_or((z - 1, x / 2, y / 2));- let aid = tilecodec::pmtiles::tile_id(anc.0, anc.1, anc.2);- let Some(ag) = grids.get(&aid) else { return (id, Some(hm), None, 0) };- let k = 1u64 << (z - anc.0);- let (ox, oy) = ((x - anc.1 * k) as f64, (y - anc.2 * k) as f64);- let d = hm.dim as usize;- let mut mx = 0.0f64;- for r in 0..d {- for c in 0..d {- let fr = (oy + r as f64 / (d - 1) as f64) / k as f64;- let fc = (ox + c as f64 / (d - 1) as f64) / k as f64;- let e = (bilin(&ag.samples, ag.dim as usize, fr, fc) - hm.samples[r * d + c] as f64).abs();- mx = mx.max(e);- }- }- if mx <= tol {- let mut nb = body.clone();- nb.heightmap = None;- let with = zstd_rs(&ser(&body)[H..], 19).len() as i64;- let without = zstd_rs(&ser(&nb)[H..], 19).len() as i64;- (id, None, Some(anc), with - without)- } else {- (id, Some(hm), None, 0)- }- })- .collect();- let (mut saved, mut dropped, mut with_dem) = (0i64, 0u64, 0u64);- for (id, hm, anc, s) in res {- if let Some(h) = hm {- grids.insert(id, h);- with_dem += 1;- }- if let Some(an) = anc {- kept.insert(id, an);- dropped += 1;- with_dem += 1;- saved += s;- }- }- out += &format!(" z{z:<3} {with_dem:>9} {dropped:>8} {:>10.2}\n", saved as f64 / 1e6);- tot_saved += saved;- tot_drop += dropped;- tot_dem += with_dem;- }- out += &format!(" all {tot_dem:>9} {tot_drop:>8} {:>10.2}\nDEMPYR_TSV\t{tol}\t{tot_dem}\t{tot_drop}\t{tot_saved}\n", tot_saved as f64 / 1e6);- print!("{out}");- std::fs::write(format!("{out_dir}/dem_pyramid_{tol}.txt"), &out).unwrap();-}--// ------------------------------------------------------------ transit pack analysis--fn rd_u32(b: &[u8], at: usize) -> u32 {- u32::from_le_bytes(b[at..at + 4].try_into().unwrap())-}--fn uvar(b: &[u8], pos: &mut usize) -> u64 {- let (mut r, mut s) = (0u64, 0);- loop {- let c = b[*pos];- *pos += 1;- r |= ((c & 0x7f) as u64) << s;- if c < 0x80 {- return r;- }- s += 7;- }-}--fn uvar_len(v: u64) -> usize {- let mut n = 1;- let mut v = v >> 7;- while v > 0 {- n += 1;- v >>= 7;- }- n-}--/// `transit WORLD.transit`: exact sizes of SHAPE_COORDS after error-bounded thinning (stop-/// vertices kept, so ROUTE_STOP_SHAPE stays valid after an index remap) at several-/// tolerances, with and without a 1e-6 deg grid; and what EXCEPTIONS would take packed.-fn cmd_transit(path: &str, out_dir: &str) {- let f = File::open(path).expect("open");- let m = unsafe { memmap2::Mmap::map(&f).expect("mmap") };- let nsec = rd_u32(&m, 8) as usize;- let route_count = rd_u32(&m, 16) as usize;- let sec = |i: usize| -> &[u8] {- let at = 80 + i * 16;- let off = u64::from_le_bytes(m[at..at + 8].try_into().unwrap()) as usize;- let len = u64::from_le_bytes(m[at + 8..at + 16].try_into().unwrap()) as usize;- &m[off..off + len]- };- let mut out = format!("transit {path}: {nsec} sections, {route_count} routes\n");- let shapes = sec(20);- let shape_idx = sec(21);- let routes = sec(2);- let rss = sec(22);- // Protected vertices per blob offset: every stop's vertex of every route using it.- let mut prot: std::collections::HashMap<u32, Vec<u32>> = std::collections::HashMap::new();- for r in 0..route_count {- let off = rd_u32(shape_idx, r * 4);- if off == u32::MAX {- continue;- }- let n_stops = rd_u32(routes, r * 32 + 16) as usize;- let first = rd_u32(routes, r * 32 + 20) as usize;- let e = prot.entry(off).or_default();- for k in 0..n_stops {- let v = rd_u32(rss, (first + k) * 4);- if v != u32::MAX {- e.push(v);- }- }- }- let offs: Vec<u32> = {- let mut v: Vec<u32> = prot.keys().copied().collect();- v.sort();- v- };- let tols = [0.0f64, 0.5, 1.0, 2.0, 5.0];- // (bytes e7, bytes 1e-6 grid, points) per tolerance- let res: Vec<Vec<(u64, u64, u64)>> = offs- .par_iter()- .map(|&off| {- let mut pos = off as usize;- let n = rd_u32(shapes, pos) as usize;- pos += 4;- let (mut la, mut lo) = (0i64, 0i64);- let mut pts = Vec::with_capacity(n);- for _ in 0..n {- let dla = uvar(shapes, &mut pos);- let dlo = uvar(shapes, &mut pos);- la += ((dla >> 1) as i64) ^ -((dla & 1) as i64);- lo += ((dlo >> 1) as i64) ^ -((dlo & 1) as i64);- pts.push((la, lo));- }- let mut keep_base = vec![false; n];- if n > 0 {- keep_base[0] = true;- keep_base[n - 1] = true;- }- for &v in &prot[&off] {- if (v as usize) < n {- keep_base[v as usize] = true;- }- }- let lat0 = if n > 0 { pts[0].0 as f64 * 1e-7 } else { 0.0 };- let kx = 0.011_131_949 * lat0.to_radians().cos();- let xy: Vec<(f64, f64)> = pts.iter().map(|p| (p.1 as f64 * kx, p.0 as f64 * 0.011_131_949)).collect();- tols.iter()- .map(|&tol| {- let mut keep = keep_base.clone();- if tol > 0.0 && n > 2 {- // DP between consecutive protected vertices.- let anchors: Vec<usize> = (0..n).filter(|&i| keep_base[i]).collect();- for w in anchors.windows(2) {- let mut stack = vec![(w[0], w[1])];- while let Some((a, b)) = stack.pop() {- if b <= a + 1 {- continue;- }- let (mut worst, mut wi) = (tol * tol, usize::MAX);- for i in a + 1..b {- let d = seg_dist_sq_f(xy[i], xy[a], xy[b]);- if d > worst {- worst = d;- wi = i;- }- }- if wi != usize::MAX {- keep[wi] = true;- stack.push((a, wi));- stack.push((wi, b));- }- }- }- } else {- keep.iter_mut().for_each(|k| *k = true);- }- let (mut b7, mut b6, mut np) = (4u64, 4u64, 0u64);- let (mut p7, mut p6) = ((0i64, 0i64), (0i64, 0i64));- for i in 0..n {- if !keep[i] {- continue;- }- let (a, o) = pts[i];- let z = |v: i64| ((v << 1) ^ (v >> 63)) as u64;- b7 += (uvar_len(z(a - p7.0)) + uvar_len(z(o - p7.1))) as u64;- p7 = (a, o);- let q = ((a as f64 / 10.0).round() as i64, (o as f64 / 10.0).round() as i64);- b6 += (uvar_len(z(q.0 - p6.0)) + uvar_len(z(q.1 - p6.1))) as u64;- p6 = q;- np += 1;- }- (b7, b6, np)- })- .collect()- })- .collect();- out += &format!("SHAPE_COORDS now {} B, {} unique blobs\n tol_m bytes_e7 bytes_1e-6 points\n", shapes.len(), offs.len());- for (ti, tol) in tols.iter().enumerate() {- let (b7, b6, np) = res.iter().fold((0u64, 0u64, 0u64), |a, r| (a.0 + r[ti].0, a.1 + r[ti].1, a.2 + r[ti].2));- out += &format!(" {tol:<5} {b7:>12} {b6:>12} {np:>10}\nTRANSIT_SHAPES_TSV\t{tol}\t{b7}\t{b6}\t{np}\n");- }- // EXCEPTIONS packed: per service CSR (EXCEPTIONS_IDX) => drop service_idx, varint date- // delta (days) + added bit in the low bit.- let exc = sec(12);- let rows = exc.len() / 12;- let mut packed = 0u64;- let mut prev_svc = u32::MAX;- let mut prev_date = 0i64;- let days = |d: u32| -> i64 {- // YYYYMMDD -> day number (approx, monotone within a service)- let (y, mo, da) = ((d / 10000) as i64, ((d / 100) % 100) as i64, (d % 100) as i64);- y * 372 + mo * 31 + da- };- for r in 0..rows {- let svc = rd_u32(exc, r * 12);- let date = days(rd_u32(exc, r * 12 + 4));- let added = rd_u32(exc, r * 12 + 8) as i64;- let delta = if svc != prev_svc { date } else { date - prev_date };- packed += uvar_len(((delta.max(0) as u64) << 1) | added as u64) as u64;- prev_svc = svc;- prev_date = date;- }- out += &format!("EXCEPTIONS now {} B ({} rows x 12 B); packed (CSR keeps service, varint date delta + added bit) {} B\nTRANSIT_EXC_TSV\t{}\t{}\n", exc.len(), rows, packed, exc.len(), packed);- out += &format!("ROUTE_TRIPS (varint stream, unread when ROUTE_TRIP_RECS is present) {} B\nTRANSIT_RT_TSV\t{}\n", sec(4).len(), sec(4).len());- print!("{out}");- std::fs::write(format!("{out_dir}/transit.txt"), &out).unwrap();-}--// ------------------------------------------------------------ ZBLK re-encode--/// `zblk FILE`: exact size of a ZBLK section re-encoded at zstd 10/19/22 with 4096- and-/// 16384-record blocks, plus ruzstd decode time per block (what one cold lookup costs).-fn cmd_zblk(path: &str) {- let f = File::open(path).expect("open");- let m = unsafe { memmap2::Mmap::map(&f).expect("mmap") };- let b = tilecodec::blocked::Blocked::parse(&m).expect("zblk");- let rl = b.record_len();- let nb = b.block_count();- let raw: Vec<Vec<u8>> = (0..nb).into_par_iter().map(|i| b.block(i).expect("block")).collect();- let all: Vec<u8> = raw.concat();- let mut out = format!("{path}: {} B, record_len {rl}, {} blocks of {} records, unpacked {} B\n", m.len(), nb, b.records_per_block(), all.len());- for per in [4096usize, 16384] {- for level in [10, 19, 22] {- let chunks: Vec<&[u8]> = all.chunks(per * rl).collect();- let frames: Vec<Vec<u8>> = chunks.par_iter().map(|c| zstd_rs(c, level)).collect();- let total: usize = 28 + 8 * (frames.len() + 1) + frames.iter().map(|f| f.len()).sum::<usize>();- // Decode cost: sample 2000 frames.- let step = (frames.len() / 2000).max(1);- let t = Instant::now();- let mut n = 0;- let mut dec = ruzstd::decoding::FrameDecoder::new();- for (fr, c) in frames.iter().zip(chunks.iter()).step_by(step) {- let mut o = vec![0u8; c.len()];- dec.decode_all(fr, &mut o).expect("dec");- n += 1;- }- let us = t.elapsed().as_secs_f64() * 1e6 / n as f64;- out += &format!(" block {per:>5} level {level:>2}: {total:>12} B ({:.3}x of now) decode {us:.0} us/block\nZBLK_TSV\t{path}\t{per}\t{level}\t{total}\t{us:.1}\n", total as f64 / m.len() as f64);- }- }- print!("{out}");-}--/// `zooms ARCH`: exact stored bytes of unique bodies per zoom (a body shared across zooms is-/// counted once, at the lowest zoom that references it).-fn cmd_zooms(path: &str) {- let a = open(path);- let ents = entries(&a);- let mut z = [0u64; 15];- let mut n = [0u64; 15];- for e in &ents {- z[e.z.min(14) as usize] += e.len as u64;- n[e.z.min(14) as usize] += 1;- }- for i in 0..15 {- println!("ZOOM\t{i}\t{}\t{}", n[i], z[i]);- }- println!("LEAVES\t{}", a.hdr.leaf_len);-}
scripts/maps/tile_build/examples/size_lab/p50.rs
diff --git a/scripts/maps/tile_build/examples/size_lab/p50.rs b/scripts/maps/tile_build/examples/size_lab/p50.rsdeleted file mode 100644index 472bfa1255..0000000000--- a/scripts/maps/tile_build/examples/size_lab/p50.rs+++ /dev/null@@ -1,689 +0,0 @@-// Included into size_lab (main.rs): the planet-50 GB candidate measurements.-//-// size_lab p50-layers IN STRIDE marginal dictionary-zstd bytes per layer / table-// size_lab p50-pyramid IN STRIDE z14 (z13) tiles reproducible by overzooming the parent-// size_lab p50-buildings IN STRIDE rectangle / shared-edge / height stats for buildings-// size_lab p50-super IN STRIDE G 2^G x 2^G superblocks vs per-tile dictionary frames-// size_lab p50-arcs IN STRIDE shared polygon edges per tile (topology encoding)-//-// STRIDE samples every STRIDE-th unique body (1 = all). Sizes are zstd level 19 against the-// archive's own band dictionary, which is how planet5 stores bodies.--use std::cell::RefCell;-use std::collections::HashMap;-use tile_build::mamaps::dict::{- LAYER_BOUNDARIES, LAYER_BUILDINGS, LAYER_JUNCTION, LAYER_LANDTYPE, LAYER_PLACES, LAYER_POI, LAYER_ROADS,- LAYER_SAFETY, LAYER_TRANSIT,-};--/// A body-mutating table-drop step (see the `tables` array in `cmd_p50_layers`).-type BodyMut = fn(&mut Body);-/// A polygon edge between two tile-local points.-type EdgeKey = ((i16, i16), (i16, i16));-/// Edge-use counts keyed by [`EdgeKey`].-type EdgeMap = HashMap<EdgeKey, u32>;-/// Four byte/count totals accumulated per component.-type Count4 = (u64, u64, u64, u64);-/// Per-`(band, component)` [`Count4`] totals.-type ArcCounts = BTreeMap<(u8, String), Count4>;--fn layer_name(id: u8) -> &'static str {- match id {- x if x == LAYER_LANDTYPE => "landtype",- x if x == LAYER_ROADS => "roads",- x if x == LAYER_BOUNDARIES => "boundaries",- x if x == LAYER_BUILDINGS => "buildings",- x if x == LAYER_PLACES => "places",- x if x == LAYER_POI => "poi",- x if x == LAYER_TRANSIT => "transit",- x if x == LAYER_JUNCTION => "junction",- x if x == LAYER_SAFETY => "safety",- _ => "other",- }-}--fn ser11(body: &Body) -> Vec<u8> {- let mut s = Scratch::default();- match tile_build::mamaps::body::serialize_into_v11(body, &mut s) {- Ok(b) => b.to_vec(),- Err(_) => {- let mut b = body.clone();- b.convention = None;- b.carriageways.clear();- let mut s = Scratch::default();- tile_build::mamaps::body::serialize_into_v11(&b, &mut s).expect("serialize v11").to_vec()- }- }-}--thread_local! {- static CDICT: RefCell<Vec<Option<zstd::bulk::Compressor<'static>>>> = const { RefCell::new(Vec::new()) };-}--/// zstd-19 size of `raw` against the archive's dictionary for `z`'s band (C reference encoder).-fn dsize(a: &Arch, z: u8, raw: &[u8]) -> usize {- let dicts = a.zd.as_ref().expect("a planet5 (dictionary) archive").dictionaries();- let b = band(z).min(dicts.len() - 1);- CDICT.with(|c| {- let mut c = c.borrow_mut();- if c.len() < dicts.len() {- c.resize_with(dicts.len(), || None);- }- if c[b].is_none() {- let d: &'static [u8] = Box::leak(dicts[b].clone().into_boxed_slice());- c[b] = Some(zstd::bulk::Compressor::with_dictionary(19, d).expect("dict"));- }- c[b].as_mut().unwrap().compress(raw).expect("zstd").len()- })-}--fn sample(ents: &[Ent], stride: usize, keep: impl Fn(&Ent) -> bool) -> Vec<Ent> {- ents.iter().filter(|e| keep(e)).step_by(stride.max(1)).copied().collect()-}--// ------------------------------------------------------------------ layers (marginal bytes)--fn cmd_p50_layers(path: &str, stride: usize) {- let a = open(path);- let ents = entries(&a);- let mut exact = [0u64; 5];- for e in &ents {- exact[band(e.z)] += e.len as u64;- }- let s = sample(&ents, stride, |_| true);- let acc: Mutex<BTreeMap<(usize, String), (u64, u64)>> = Mutex::new(BTreeMap::new());- s.par_iter().for_each(|e| {- let raw = raw_of(&a, e);- let body = Body::parse(&raw).expect("parse");- let full = dsize(&a, e.z, &ser11(&body));- let mut local: Vec<(String, u64, u64)> = vec![("_full".into(), full as u64, e.len as u64)];- let mut drop = |k: String, b: Body| {- let m = full.saturating_sub(dsize(&a, e.z, &ser11(&b)));- local.push((k, m as u64, 0));- };- for l in &body.layers {- let mut b = body.clone();- b.layers.retain(|x| x.layer_id != l.layer_id);- b.names.clear();- let lid = l.layer_id;- b.ids.retain(|t| t.0 != lid);- b.turn_lanes.retain(|t| t.0 != lid);- b.buildings.retain(|t| t.0 != lid);- b.carriageways.retain(|t| t.0 != lid);- b.region_links.retain(|t| t.0 != lid);- if b.carriageways.is_empty() {- b.convention = None;- }- // names stay (shared): measure geometry+records of the layer, not the name pool- b.names = body.names.clone();- drop(format!("layer:{}", layer_name(lid)), b);- }- let tables: [(&str, BodyMut); 7] = [- ("table:names", |b| {- b.names.clear();- for l in &mut b.layers {- for f in &mut l.features {- f.name_idx = tile_build::mamaps::body::NAME_NONE;- }- }- }),- ("table:ids", |b| b.ids.clear()),- ("table:turn_lanes", |b| b.turn_lanes.clear()),- ("table:buildings", |b| b.buildings.clear()),- ("table:heightmap", |b| b.heightmap = None),- ("table:carriageways", |b| {- b.carriageways.clear();- b.convention = None- }),- ("table:region_links", |b| b.region_links.clear()),- ];- for (k, f) in tables {- let mut b = body.clone();- f(&mut b);- if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| ser11(&b))).is_ok() {- drop(k.to_string(), b);- }- }- let mut g = acc.lock().unwrap();- for (k, m, st) in local {- let v = g.entry((band(e.z), k)).or_default();- v.0 += m;- v.1 += st;- }- });- let g = acc.into_inner().unwrap();- println!("band\tcomponent\tsample_marginal_B\tshare_of_full\tprojected_GB(archive)");- for b in 0..5 {- let full = g.get(&(b, "_full".to_string())).map(|v| v.0).unwrap_or(0);- let stored = g.get(&(b, "_full".to_string())).map(|v| v.1).unwrap_or(0);- if full == 0 {- continue;- }- println!("{}\t_exact_stored\t{}\t-\t{:.3}", BANDS[b], stored, exact[b] as f64 / 1e9);- for ((bb, k), v) in &g {- if *bb != b || k == "_full" {- continue;- }- let share = v.0 as f64 / full as f64;- println!("{}\t{}\t{}\t{:.4}\t{:.3}", BANDS[b], k, v.0, share, share * exact[b] as f64 / 1e9);- }- }-}--// ------------------------------------------------------------------ pyramid (parent overzoom)--/// Geometry of every layer of `body` mapped into child (quadrant qx,qy) coordinates.-fn quad_layer(l: &Layer, qx: u64, qy: u64, ext: f64) -> (Vec<Seg>, Vec<Pt2>) {- let (segs, pts) = layer_segs_pts(l);- let ox = qx as f64 * ext / 2.0;- let oy = qy as f64 * ext / 2.0;- let m = |p: (f64, f64)| ((p.0 - ox) * 2.0, (p.1 - oy) * 2.0);- (segs.into_iter().map(|(a, b)| (m(a), m(b))).collect(), pts.into_iter().map(m).collect())-}--fn inside(p: (f64, f64), ext: f64) -> bool {- p.0 >= 0.0 && p.1 >= 0.0 && p.0 <= ext && p.1 <= ext-}--/// Max deviation (child units) between the child's features and the parent's quadrant, both-/// ways, for one layer; f64::INFINITY when something has no counterpart within 64 units.-fn layer_dev(child: &Layer, parent: Option<&Layer>, qx: u64, qy: u64, ext: f64) -> f64 {- let (cs, cp) = layer_segs_pts(child);- let (ps, pp) = match parent {- Some(p) => quad_layer(p, qx, qy, ext),- None => (Vec::new(), Vec::new()),- };- let cp: Vec<_> = cp.into_iter().filter(|p| inside(*p, ext)).collect();- let pp: Vec<_> = pp.into_iter().filter(|p| inside(*p, ext)).collect();- if cp.is_empty() && pp.is_empty() {- return 0.0;- }- if cs.is_empty() || ps.is_empty() {- return f64::INFINITY;- }- let gp = SegGrid::new(ps);- let gc = SegGrid::new(cs);- let mut worst = 0.0f64;- for p in &cp {- worst = worst.max(gp.nearest(*p, 64.0).unwrap_or(f64::INFINITY));- if worst.is_infinite() {- return worst;- }- }- for p in &pp {- worst = worst.max(gc.nearest(*p, 64.0).unwrap_or(f64::INFINITY));- if worst.is_infinite() {- return worst;- }- }- worst-}--/// Max |child - bilinear(parent quadrant)| over the child's heightmap samples, metres.-fn dem_dev(child: &Heightmap, parent: &Heightmap, qx: u64, qy: u64) -> f64 {- let cd = child.dim as usize;- let pd = parent.dim as usize;- if cd < 2 || pd < 2 {- return 0.0;- }- let mut worst = 0.0f64;- for r in 0..cd {- for c in 0..cd {- let fr = (qy as f64 + r as f64 / (cd - 1) as f64) / 2.0 * (pd - 1) as f64;- let fc = (qx as f64 + c as f64 / (cd - 1) as f64) / 2.0 * (pd - 1) as f64;- let v = bilin(&parent.samples, pd, fr, fc);- worst = worst.max((child.samples[r * cd + c] as f64 - v).abs());- }- }- worst-}--fn cmd_p50_pyramid(path: &str, stride: usize) {- let a = open(path);- let ti = TileIndex::build(&a);- // Every addressed z13 and z14 tile (runs expanded), one sample per STRIDE.- let mut tiles: Vec<(u64, u64, u32)> = Vec::new();- for &(id, run, off, len) in &ti.ents {- for k in 0..run as u64 {- let (z, _, _) = tile_zxy(id + k);- if z >= 13 {- tiles.push((id + k, off, len));- }- }- }- let mut seen: HashMap<u64, u32> = HashMap::new();- for t in &tiles {- *seen.entry(t.1).or_default() += 1;- }- let tiles: Vec<_> = tiles.into_iter().step_by(stride.max(1)).collect();- let tols = [0.5f64, 1.0, 2.0, 4.0, 8.0];- // per zoom: tiles, unique-body bytes (each body's bytes divided by its references), and- // per tolerance: qualifying tiles + bytes; plus reasons.- #[derive(Default)]- struct Z {- tiles: u64,- bytes: f64,- q_tiles: [u64; 5],- q_bytes: [f64; 5],- reasons: BTreeMap<String, (u64, f64)>,- }- let acc: Mutex<[Z; 2]> = Mutex::new([Z::default(), Z::default()]);- tiles.par_iter().for_each(|&(id, off, len)| {- let (z, x, y) = tile_zxy(id);- let share = len as f64 / *seen.get(&off).unwrap_or(&1) as f64;- let child = body_at(&a, id, off, len);- let pid = tilecodec::pmtiles::tile_id(z - 1, x / 2, y / 2);- let parent = ti.find(pid).map(|(po, pl)| body_at(&a, pid, po, pl));- let ext = child.extent as f64;- let (qx, qy) = (x % 2, y % 2);- let mut reason: Option<String> = None;- let mut worst = 0.0f64;- let mut dem_ok = true;- let mut z14only = false;- match &parent {- None => reason = Some("no parent".into()),- Some(p) => {- for l in &child.layers {- let lid = l.layer_id;- if l.features.is_empty() {- continue;- }- let in_parent = p.layer(lid).is_some_and(|pl| !pl.features.is_empty());- if !in_parent && [LAYER_BUILDINGS, LAYER_JUNCTION, LAYER_SAFETY, LAYER_POI].contains(&lid) {- z14only = true;- }- }- if child.carriageways.iter().any(|t| !t.1.is_empty()) {- z14only = true;- }- for l in &child.layers {- worst = worst.max(layer_dev(l, p.layer(l.layer_id), qx, qy, ext));- }- for l in &p.layers {- if child.layer(l.layer_id).is_none() {- worst = worst.max(layer_dev(&Layer::new(l.layer_id), Some(l), qx, qy, ext));- }- }- if let (Some(ch), Some(ph)) = (&child.heightmap, &p.heightmap) {- let px = m_per_unit(z, y) * 4096.0 / 256.0;- dem_ok = dem_dev(ch, ph, qx, qy) <= 0.5 * px;- } else if child.heightmap.is_some() != p.heightmap.is_some() {- dem_ok = false;- }- }- }- // heightmap bytes of this tile if the DEM alone fell back to the parent- let hm_share = if dem_ok && child.heightmap.is_some() {- let mut nb = child.clone();- nb.heightmap = None;- let full = dsize(&a, z, &ser11(&child));- (full.saturating_sub(dsize(&a, z, &ser11(&nb)))) as f64 / full.max(1) as f64 * share- } else {- 0.0- };- let geo_key = if worst <= 2.0 { "geom<=2u" } else if worst <= 8.0 { "geom<=8u" } else { "geom>8u" };- let k = format!("{}|dem_{}|{}", if z14only { "zonly" } else { "nozonly" }, if dem_ok { "ok" } else { "bad" }, geo_key);- if reason.is_none() {- reason = Some(k);- }- if !(reason.as_deref().unwrap_or("").starts_with("nozonly|dem_ok|geom<=2u")) {- worst = f64::INFINITY;- }- {- let mut g = acc.lock().unwrap();- let e = g[(z - 13) as usize].reasons.entry("_dem_only_droppable_hm_bytes".into()).or_default();- e.1 += hm_share;- }- let zi = (z - 13) as usize;- let mut g = acc.lock().unwrap();- let zz = &mut g[zi];- zz.tiles += 1;- zz.bytes += share;- match reason {- Some(r) => {- let e = zz.reasons.entry(r).or_default();- e.0 += 1;- e.1 += share;- }- None => {- for (i, t) in tols.iter().enumerate() {- if worst <= *t {- zz.q_tiles[i] += 1;- zz.q_bytes[i] += share;- }- }-- }- }- });- let g = acc.into_inner().unwrap();- for (zi, zz) in g.iter().enumerate() {- println!("z{}: sampled tiles {} body-bytes {:.0}", 13 + zi, zz.tiles, zz.bytes);- for (i, t) in tols.iter().enumerate() {- println!(- " qualify at <= {t} child units ({:.3} px at z{}): tiles {:.2}% bytes {:.2}%",- t * 256.0 / 4096.0 * 4.0,- 14 + zi + 2 - 1,- 100.0 * zz.q_tiles[i] as f64 / zz.tiles.max(1) as f64,- 100.0 * zz.q_bytes[i] / zz.bytes.max(1.0)- );- }- for (r, (n, b)) in &zz.reasons {- println!(" reason {r}: tiles {:.2}% bytes {:.2}%", 100.0 * *n as f64 / zz.tiles.max(1) as f64, 100.0 * b / zz.bytes.max(1.0));- }- }-}--// ------------------------------------------------------------------ buildings--fn cmd_p50_buildings(path: &str, stride: usize) {- let a = open(path);- let ents = entries(&a);- let s = sample(&ents, stride, |e| e.z >= 13);- #[derive(Default)]- struct B {- polys: u64,- verts: u64,- rects: u64,- rect_verts: u64,- shared_edges: u64,- edges: u64,- old_stream: u64,- new_stream: u64,- tab_old: u64,- tab_q: u64,- }- let acc = Mutex::new(B::default());- s.par_iter().for_each(|e| {- let body = Body::parse(&raw_of(&a, e)).expect("parse");- let Some(l) = body.layer(LAYER_BUILDINGS) else { return };- let mut b = B::default();- let mut old = Vec::new();- let mut new = Vec::new();- let zz = |v: i64| ((v << 1) ^ (v >> 63)) as u64;- let put = |o: &mut Vec<u8>, mut v: u64| loop {- let byte = (v & 0x7f) as u8;- v >>= 7;- if v == 0 {- o.push(byte);- break;- }- o.push(byte | 0x80);- };- let mut edges: EdgeMap = HashMap::new();- let (mut pcx, mut pcy) = (0i64, 0i64);- for f in &l.features {- let from = f.parts_offset as usize;- for p in &l.parts[from..from + f.part_count as usize] {- let mut v: Vec<(i16, i16)> = l.points(p).to_vec();- if v.len() > 1 && v.first() == v.last() {- v.pop();- }- b.polys += 1;- b.verts += v.len() as u64;- // old stream: zigzag varint deltas from the part's first point- let (mut px, mut py) = (0i64, 0i64);- for q in &v {- put(&mut old, zz(q.0 as i64 - px));- put(&mut old, zz(q.1 as i64 - py));- px = q.0 as i64;- py = q.1 as i64;- }- for i in 0..v.len() {- let (p0, p1) = (v[i], v[(i + 1) % v.len()]);- let k = if p0 <= p1 { (p0, p1) } else { (p1, p0) };- *edges.entry(k).or_default() += 1;- }- // rectangle test: 4 corners, reconstructable from centre, w, h, angle within 1 unit- let mut is_rect = false;- if v.len() == 4 {- let f64p = |q: (i16, i16)| (q.0 as f64, q.1 as f64);- let (a0, a1, a2, a3) = (f64p(v[0]), f64p(v[1]), f64p(v[2]), f64p(v[3]));- let cx = (a0.0 + a1.0 + a2.0 + a3.0) / 4.0;- let cy = (a0.1 + a1.1 + a2.1 + a3.1) / 4.0;- let ang = (a1.1 - a0.1).atan2(a1.0 - a0.0);- let w = ((a1.0 - a0.0).hypot(a1.1 - a0.1) + (a2.0 - a3.0).hypot(a2.1 - a3.1)) / 2.0;- let h = ((a2.0 - a1.0).hypot(a2.1 - a1.1) + (a3.0 - a0.0).hypot(a3.1 - a0.1)) / 2.0;- // quantize: centre to 0.5 unit, w/h to 0.5 unit, angle to 1/4096 turn- let q = |x: f64, s: f64| (x / s).round() * s;- let (cx, cy, w, h) = (q(cx, 0.5), q(cy, 0.5), q(w, 0.5), q(h, 0.5));- let ang = q(ang, std::f64::consts::TAU / 4096.0);- let (c, s_) = (ang.cos(), ang.sin());- let corner = |sx: f64, sy: f64| (cx + (sx * w * c - sy * h * s_) / 2.0, cy + (sx * w * s_ + sy * h * c) / 2.0);- let rec = [corner(-1.0, -1.0), corner(1.0, -1.0), corner(1.0, 1.0), corner(-1.0, 1.0)];- let orig = [a0, a1, a2, a3];- let err = rec.iter().zip(orig.iter()).map(|(r, o)| (r.0 - o.0).hypot(r.1 - o.1)).fold(0.0, f64::max);- if err <= 1.0 {- is_rect = true;- b.rects += 1;- b.rect_verts += 4;- new.push(1);- put(&mut new, zz((cx * 2.0) as i64 - pcx));- put(&mut new, zz((cy * 2.0) as i64 - pcy));- pcx = (cx * 2.0) as i64;- pcy = (cy * 2.0) as i64;- put(&mut new, (w * 2.0) as u64);- put(&mut new, (h * 2.0) as u64);- let ai = ((ang / (std::f64::consts::TAU / 4096.0)).round() as i64).rem_euclid(4096) as u16;- new.extend_from_slice(&ai.to_le_bytes());- }- }- if !is_rect {- new.push(0);- let (mut px, mut py) = (0i64, 0i64);- for q in &v {- put(&mut new, zz(q.0 as i64 - px));- put(&mut new, zz(q.1 as i64 - py));- px = q.0 as i64;- py = q.1 as i64;- }- }- }- }- b.edges = edges.values().map(|&n| n as u64).sum();- b.shared_edges = edges.values().filter(|&&n| n >= 2).map(|&n| n as u64).sum();- b.old_stream = zstd_c(&old, 19) as u64;- b.new_stream = zstd_c(&new, 19) as u64;- // building attribute table: heights as stored vs quantized to 1 m (values are decimetres)- if let Some((_, rows)) = body.buildings.iter().find(|t| t.0 == LAYER_BUILDINGS) {- let mut t0 = Vec::new();- let mut t1 = Vec::new();- for r in rows {- for v in [r.height, r.min_height, r.roof_height] {- t0.extend_from_slice(&v.to_le_bytes());- t1.extend_from_slice(&((v + 5) / 10 * 10).to_le_bytes());- }- t0.extend_from_slice(&[r.roof_shape, r.roof_direction, r.roof_orientation]);- t1.extend_from_slice(&[r.roof_shape, r.roof_direction, r.roof_orientation]);- t0.extend_from_slice(&r.building_colour.to_le_bytes());- t0.extend_from_slice(&r.roof_colour.to_le_bytes());- t1.extend_from_slice(&r.building_colour.to_le_bytes());- t1.extend_from_slice(&r.roof_colour.to_le_bytes());- }- b.tab_old = zstd_c(&t0, 19) as u64;- b.tab_q = zstd_c(&t1, 19) as u64;- }- let mut g = acc.lock().unwrap();- g.polys += b.polys;- g.verts += b.verts;- g.rects += b.rects;- g.rect_verts += b.rect_verts;- g.shared_edges += b.shared_edges;- g.edges += b.edges;- g.old_stream += b.old_stream;- g.new_stream += b.new_stream;- g.tab_old += b.tab_old;- g.tab_q += b.tab_q;- });- let g = acc.into_inner().unwrap();- println!(- "buildings: polygons {} vertices {} | rectangles (<=1 unit after centre/w/h/angle quantization) {:.1}% of polygons, {:.1}% of vertices",- g.polys,- g.verts,- 100.0 * g.rects as f64 / g.polys.max(1) as f64,- 100.0 * g.rect_verts as f64 / g.verts.max(1) as f64- );- println!(- " shared edges (terraces): {:.1}% of polygon edges appear in two buildings",- 100.0 * g.shared_edges as f64 / g.edges.max(1) as f64- );- println!(- " coordinate stream zstd-19 per tile: current {} B, rect-coded {} B ({:+.1}%)",- g.old_stream,- g.new_stream,- 100.0 * (g.new_stream as f64 / g.old_stream.max(1) as f64 - 1.0)- );- println!(- " attribute table zstd-19: as stored {} B, heights to 1 m {} B ({:+.1}%)",- g.tab_old,- g.tab_q,- 100.0 * (g.tab_q as f64 / g.tab_old.max(1) as f64 - 1.0)- );-}--// ------------------------------------------------------------------ superblocks--fn cmd_p50_super(path: &str, stride: usize, g: u32) {- let a = open(path);- let ti = TileIndex::build(&a);- // group key -> member (off, len) of unique bodies referenced once (shared bodies stay apart)- let mut refs: HashMap<u64, u32> = HashMap::new();- for &(_, run, off, _) in &ti.ents {- *refs.entry(off).or_default() += run;- }- let mut groups: BTreeMap<(u8, u64, u64), Vec<(u64, u32)>> = BTreeMap::new();- for &(id, run, off, len) in &ti.ents {- if run != 1 || refs[&off] != 1 {- continue;- }- let (z, x, y) = tile_zxy(id);- if z < 10 {- continue;- }- groups.entry((z, x >> g, y >> g)).or_default().push((off, len));- }- let keys: Vec<_> = groups.keys().copied().step_by(stride.max(1)).collect();- #[derive(Default)]- struct S {- groups: u64,- tiles: u64,- stored: u64,- separate: u64,- together: u64,- dec_ns: u64,- dec_tile_ns: u64,- }- let acc: Mutex<BTreeMap<u8, S>> = Mutex::new(BTreeMap::new());- keys.par_iter().for_each(|k| {- let members = &groups[k];- let raws: Vec<Vec<u8>> = members- .iter()- .map(|&(off, len)| {- let e = Ent { z: k.0, off, len };- raw_of(&a, &e)- })- .collect();- let sep: usize = raws.iter().map(|r| dsize(&a, k.0, r)).sum();- let cat: Vec<u8> = raws.concat();- let dicts = a.zd.as_ref().unwrap().dictionaries();- let d = &dicts[band(k.0).min(dicts.len() - 1)];- let mut c = zstd::bulk::Compressor::with_dictionary(19, d).expect("dict");- c.set_parameter(zstd::stream::raw::CParameter::WindowLog(22)).ok();- let frame = c.compress(&cat).expect("zstd");- let t = Instant::now();- let mut dctx = zstd::bulk::Decompressor::with_dictionary(d).expect("d");- let back = dctx.decompress(&frame, cat.len()).expect("dec");- let dec = t.elapsed().as_nanos() as u64;- assert_eq!(back.len(), cat.len());- let t = Instant::now();- let mut dctx2 = zstd::bulk::Decompressor::with_dictionary(d).expect("d");- let one = c.compress(&raws[0]).expect("z");- let _ = dctx2.decompress(&one, raws[0].len()).expect("dec1");- let dec1 = t.elapsed().as_nanos() as u64;- let mut g = acc.lock().unwrap();- let s = g.entry(k.0).or_default();- s.groups += 1;- s.tiles += members.len() as u64;- s.stored += members.iter().map(|m| m.1 as u64).sum::<u64>();- s.separate += sep as u64;- s.together += frame.len() as u64 + 8 * members.len() as u64;- s.dec_ns += dec;- s.dec_tile_ns += dec1;- });- for (z, s) in acc.into_inner().unwrap() {- println!(- "z{z} {}x{} superblocks: groups {} tiles {} | separate {} B together {} B ({:+.1}%) | decode per block {:.0} us vs one tile {:.0} us",- 1 << g,- 1 << g,- s.groups,- s.tiles,- s.separate,- s.together,- 100.0 * (s.together as f64 / s.separate.max(1) as f64 - 1.0),- s.dec_ns as f64 / s.groups.max(1) as f64 / 1e3,- s.dec_tile_ns as f64 / s.groups.max(1) as f64 / 1e3- );- }-}--// ------------------------------------------------------------------ shared arcs--fn cmd_p50_arcs(path: &str, stride: usize) {- let a = open(path);- let ents = entries(&a);- let s = sample(&ents, stride, |e| e.z >= 10);- let acc: Mutex<ArcCounts> = Mutex::new(BTreeMap::new());- s.par_iter().for_each(|e| {- let body = Body::parse(&raw_of(&a, e)).expect("parse");- let mut local: Vec<((u8, String), Count4)> = Vec::new();- // all polygon edges of the tile, any layer: an edge used twice is a shared arc- let mut edges: EdgeMap = HashMap::new();- let mut rings: Vec<(u8, Vec<(i16, i16)>)> = Vec::new();- for l in &body.layers {- for f in &l.features {- if f.geom_type != GEOM_POLYGON {- continue;- }- let from = f.parts_offset as usize;- for p in &l.parts[from..from + f.part_count as usize] {- let mut v = l.points(p).to_vec();- if v.len() > 1 && v.first() == v.last() {- v.pop();- }- for i in 0..v.len() {- let (p0, p1) = (v[i], v[(i + 1) % v.len()]);- let k = if p0 <= p1 { (p0, p1) } else { (p1, p0) };- *edges.entry(k).or_default() += 1;- }- rings.push((l.layer_id, v));- }- }- }- for (lid, v) in &rings {- let n = v.len() as u64;- // a vertex is "on a shared arc" when both incident edges are shared- let mut on = 0u64;- for i in 0..v.len() {- let prev = v[(i + v.len() - 1) % v.len()];- let next = v[(i + 1) % v.len()];- let k1 = if prev <= v[i] { (prev, v[i]) } else { (v[i], prev) };- let k2 = if v[i] <= next { (v[i], next) } else { (next, v[i]) };- if edges.get(&k1).copied().unwrap_or(0) >= 2 && edges.get(&k2).copied().unwrap_or(0) >= 2 {- on += 1;- }- }- local.push(((band(e.z) as u8, layer_name(*lid).to_string()), (1, n, on, 0)));- }- let mut g = acc.lock().unwrap();- for (k, v) in local {- let x = g.entry(k).or_default();- x.0 += v.0;- x.1 += v.1;- x.2 += v.2;- }- });- println!("band\tlayer\trings\tvertices\ton_shared_arc\tshare");- for ((b, l), v) in acc.into_inner().unwrap() {- println!("{}\t{}\t{}\t{}\t{}\t{:.1}%", BANDS[b as usize], l, v.0, v.1, v.2, 100.0 * v.2 as f64 / v.1.max(1) as f64);- }-}
scripts/maps/tile_build/src/bin/mamaps_sizes.rs
diff --git a/scripts/maps/tile_build/src/bin/mamaps_sizes.rs b/scripts/maps/tile_build/src/bin/mamaps_sizes.rsdeleted file mode 100644index 0ee479b110..0000000000--- a/scripts/maps/tile_build/src/bin/mamaps_sizes.rs+++ /dev/null@@ -1,592 +0,0 @@-//! `mamaps_sizes` — byte breakdown of a `.mamaps` archive without inflating bodies.-//!-//! Usage: mamaps_sizes IN.mamaps [--sample-every N]-//!-//! Sections:-//! A. File envelope: header/dict/root/leaves/data/sidecars/footer + alignment.-//! B. Sidecar directory: per-section kind/offset/len.-//! C. Tile overhead: index bytes per tile + empty-body cost (the zero-feature-//! baseline: 16B body header + per-layer index entries with zero-length payloads).-//! D. Per-layer stored bytes, attributed by raw-share: each body's stored-//! (compressed) length is split across its layers by raw payload share.-//! Bodies are compressed as a unit, so this is an estimate — exact for the-//! total, approximate per layer (layers with similar entropy split evenly).-//! E. Wire anatomy: feature records (24B), part entries (12B), point counts,-//! trailing-table presence from body flags.-//!-//! Reads only structural metadata: header, dict, root, leaves, and each body's-//! 16B frame prefix + layer index. Never inflates, never reads coordinates.-//! Bodies are walked through a single sequential pass over the leaf table with-//! the body-prefix reads batched per leaf, so a 66GB file scans in minutes.-use std::collections::BTreeMap;-use std::process::ExitCode;--use tile_build::mamaps::body::{- BODY_FLAG_EXTENDED_COUNTS, BODY_HEADER_LEN, LAYER_INDEX_LEN,-};-use tile_build::mamaps::dict::Dictionary;-use tile_build::mamaps::header::Header;-use tile_build::mamaps::index::{decompress_leaf, parse_leaf, parse_root, LEAF_ENTRY_LEN, ROOT_ENTRY_LEN};--const KIND_NAMES: [(u8, &str); 15] = [- (1, "graph_meta"), (2, "graph_nodes"), (3, "graph_edges"), (4, "graph_intermediate"),- (5, "graph_names"), (6, "graph_lanes"), (7, "graph_elevation"), (8, "poi_index"),- (9, "poi_names"), (10, "poi_attrs"), (11, "poi_spatial"), (12, "poi_words"),- (13, "transit"), (15, "poi_region"), (16, "poi_admin"),-];--fn gb(n: u64) -> f64 {- n as f64 / 1e9-}--fn th(n: u64) -> String {- let s = n.to_string();- let mut out = String::with_capacity(s.len() + s.len() / 3);- for (i, c) in s.chars().rev().enumerate() {- if i > 0 && i % 3 == 0 {- out.push(',');- }- out.push(c);- }- out.chars().rev().collect()-}--fn kind_name(kind: u8) -> String {- KIND_NAMES.iter().find(|(k, _)| *k == kind).map(|(_, n)| n.to_string()).unwrap_or_else(|| format!("kind{kind}"))-}--/// One leaf's worth of the D/E scan, computed on a worker thread with its own-/// file handle. Aggregated by the caller; never shared mid-scan.-#[derive(Default)]-struct Partial {- bodies_seen: u64,- total_stored: u64,- total_raw: u64,- empty_bodies: u64,- empty_stored: u64,- extended_count: u64,- layer_stored: BTreeMap<u8, u64>,- layer_raw: BTreeMap<u8, u64>,- layer_bodies: BTreeMap<u8, u64>,- layer_features: BTreeMap<u8, u64>,- flags_hist: BTreeMap<u8, u64>,- // Stored bytes by (zoom, layer): exact per-zoom totals need no sampling —- // the zoom comes from the tile id, the layer split from the sample below.- // Keyed (zoom, layer) -> sampled stored bytes; scaled like layer_stored.- zoom_layer_stored: BTreeMap<(u8, u8), u64>,- // Trailing-table bytes by section, measured on the RAW (decompressed) body:- // names, ids, turn-lanes, buildings, heightmap, carriageways. Compressed- // share is attributed by raw-share like the layers.- table_raw: BTreeMap<&'static str, u64>,- table_stored: BTreeMap<&'static str, u64>,-}--fn scan_leaf(- path: &str,- header: &Header,- re: &tile_build::mamaps::index::RootEntry,- sample_every: u64,- body_counter: &std::sync::atomic::AtomicU64,-) -> Result<Partial, String> {- use std::fs::File;- use std::io::{Read, Seek, SeekFrom};- let mut f = File::open(path).map_err(|e| format!("cannot open: {e}"))?;- let mut p = Partial::default();- f.seek(SeekFrom::Start(header.leaf_offset + re.leaf_offset))- .map_err(|e| format!("cannot seek to leaf: {e}"))?;- // v9 leaf framing: `stored_len == 0` is a raw legacy leaf, anything else is- // one raw-DEFLATE frame of that length (see `index::decompress_leaf`).- let raw_len = re.leaf_entry_count as usize * LEAF_ENTRY_LEN;- let stored_len = if re.stored_len == 0 { raw_len } else { re.stored_len as usize };- let mut stored_buf = vec![0u8; stored_len];- f.read_exact(&mut stored_buf).map_err(|e| format!("cannot read leaf: {e}"))?;- let leaf_buf = if re.stored_len == 0 {- stored_buf- } else {- decompress_leaf(&stored_buf, raw_len).map_err(|e| format!("bad leaf frame: {e:?}"))?- };- let leaf = parse_leaf(&leaf_buf).map_err(|e| format!("bad leaf: {e:?}"))?;- // Dedup: a run of consecutive tiles shares one body — count each stored body- // once (keyed by data offset), while crediting addressed tiles separately.- // The zoom for the (zoom, layer) table comes from each body's own tile id.- let mut seen_offsets = std::collections::HashSet::new();- for le in &leaf {- let start = header.data_offset + re.base_data_offset + le.offset_delta as u64;- if !seen_offsets.insert(start) {- continue;- }- let tile_id = re.base_tile_id + le.tile_id_lo as u64;- let zoom = tile_build::pmtiles::tile_zxy(tile_id).0;- // Exact totals need every body; layer attribution needs only a sample.- // Inflate every `sample_every`-th body (global counter): the index parse- // below runs on DECOMPRESSED bytes, which the old code got wrong by- // reading the compressed frame.- let n = body_counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);- let sampled = sample_every == 0 || n % sample_every == 0;- // Stored length + raw length come from the leaf + frame prefix (cheap,- // exact, every body).- f.seek(SeekFrom::Start(start)).map_err(|e| format!("cannot seek to body: {e}"))?;- let mut prefix = [0u8; BODY_HEADER_LEN];- f.read_exact(&mut prefix).map_err(|e| format!("cannot read body prefix: {e}"))?;- if &prefix[0..3] != b"MBD" {- continue;- }- let raw_len = u32::from_le_bytes(prefix[4..8].try_into().unwrap()) as u64;- let bflags = prefix[11];- *p.flags_hist.entry(bflags).or_default() += 1;- p.total_stored += le.length as u64;- p.total_raw += raw_len;- p.bodies_seen += 1;- if !sampled {- continue;- }- // Sampled: read the whole stored frame, inflate, parse the layer index.- let mut stored = vec![0u8; le.length as usize];- f.seek(SeekFrom::Start(start)).map_err(|e| format!("cannot seek to body: {e}"))?;- f.read_exact(&mut stored).map_err(|e| format!("cannot read body: {e}"))?;- let raw = tile_build::mamaps::read::helpers::decompress(header.compression, &stored)- .map_err(|e| format!("cannot inflate body: {e:?}"))?;- let nlayers = raw[10] as usize;- let bflags = raw[11];- if bflags & BODY_FLAG_EXTENDED_COUNTS != 0 {- p.extended_count += 1;- }- let mut payloads: Vec<(u8, u64, u64)> = Vec::with_capacity(nlayers);- let mut raw_sum = 0u64;- for i in 0..nlayers {- let at = BODY_HEADER_LEN + i * LAYER_INDEX_LEN;- let lid = raw[at];- let fcount = u16::from_le_bytes([raw[at + 2], raw[at + 3]]) as u64;- let plen = u32::from_le_bytes(raw[at + 8..at + 12].try_into().unwrap()) as u64;- payloads.push((lid, fcount, plen));- raw_sum += plen;- }- if payloads.iter().all(|(_, fc, _)| *fc == 0) {- p.empty_bodies += 1;- p.empty_stored += le.length as u64;- }- let denom = raw_sum.max(1);- for (lid, fcount, plen) in payloads {- let share_num = plen as f64 / denom as f64;- let attrib = (le.length as f64 * share_num) as u64;- *p.layer_stored.entry(lid).or_default() += attrib;- *p.zoom_layer_stored.entry((zoom, lid)).or_default() += attrib;- *p.layer_raw.entry(lid).or_default() += plen;- if fcount > 0 {- *p.layer_bodies.entry(lid).or_default() += 1;- *p.layer_features.entry(lid).or_default() += fcount;- }- }- // Trailing tables: parse the inflated body for real and re-measure- // each section with the same serializers the writer uses. Exact raw- // bytes; stored share by raw-share like the layers.- {- use tile_build::mamaps::body::Body;- use tile_build::mamaps::body::{tables, tables_extra};- if let Ok(body) = Body::parse(&raw) {- let mut sections: Vec<(&'static str, usize)> = Vec::new();- // header + layer index (incl. extended counts), 4-aligned- let mut idx = BODY_HEADER_LEN + nlayers * LAYER_INDEX_LEN;- if bflags & BODY_FLAG_EXTENDED_COUNTS != 0 {- idx += nlayers * 4;- }- sections.push(("header+index", (idx + 3) & !3));- let mut scratch = Vec::new();- if !body.names.is_empty() {- scratch = tables::serialize_names(&body.names);- sections.push(("names", scratch.len()));- }- if !body.ids.is_empty() {- scratch.clear();- tables::serialize_ids(&body.ids, &mut scratch);- sections.push(("ids", scratch.len()));- }- if !body.turn_lanes.is_empty() {- scratch.clear();- tables::serialize_lanes(&body.turn_lanes, &mut scratch);- sections.push(("turn_lanes", scratch.len()));- }- if !body.buildings.is_empty() {- scratch.clear();- tables_extra::serialize_buildings(&body.buildings, &mut scratch);- sections.push(("buildings_table", scratch.len()));- }- if let Some(grid) = &body.heightmap {- scratch.clear();- tables::serialize_heightmap(grid, &mut scratch);- sections.push(("heightmap", scratch.len()));- }- if !body.carriageways.is_empty() {- scratch.clear();- tables::serialize_carriageways(- &body.carriageways,- body.convention.unwrap_or_default(),- &mut scratch,- );- sections.push(("carriageways", scratch.len()));- }- for (name, len) in sections {- let len = len as u64;- *p.table_raw.entry(name).or_default() += len;- *p.table_stored.entry(name).or_default() +=- ((le.length as f64) * (len as f64) / (raw_len.max(1) as f64)) as u64;-
Diff truncated.