Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / tile_build / src / bin / mamaps_probe.rs
mamaps_probe.rs732 lines · 27.2 KiBRaw
| 1 | //! `mamaps_probe` — read a handful of tiles out of a `.mamaps` archive by range. |
| 2 | //! |
| 3 | //! `mamaps_dump` reads the whole file into RAM, which dies on a 60 GB archive. |
| 4 | //! This opens the archive over a file-backed [`RangeReader`] and prints one line |
| 5 | //! per requested tile: which `landtype` kinds it carries and how much ground |
| 6 | //! each covers. Built for the Santa Cruz water/land question — the ocean below |
| 7 | //! Santa Cruz rendered as land past ~z7 with only rivers showing as water. |
| 8 | //! |
| 9 | //! Usage: |
| 10 | //! mamaps_probe IN.mamaps Z/X/Y [Z/X/Y ...] |
| 11 | //! mamaps_probe IN.mamaps --breakdown [SAMPLES_PER_ZOOM] |
| 12 | //! |
| 13 | //! `--breakdown` walks the whole leaf index (cheap: index only, no bodies) and |
| 14 | //! prints per-zoom: addressed tiles, stored bodies, stored (DEFLATE) bytes, plus |
| 15 | //! — from up to SAMPLES_PER_ZOOM sampled bodies per zoom (default 200) — the |
| 16 | //! share of bodies carrying a heightmap, the mean raw body size, and the mean |
| 17 | //! raw heightmap section size. That answers "how much space does height take". |
| 18 | |
| 19 | use std::fs::File; |
| 20 | use std::io::{Read, Seek, SeekFrom}; |
| 21 | use std::process::ExitCode; |
| 22 | |
| 23 | use tile_build::mamaps::body::{Body, GEOM_POLYGON}; |
| 24 | use tile_build::mamaps::dict::Dictionary; |
| 25 | use tile_build::mamaps::read::MamapsArchive; |
| 26 | use tile_build::proto::{err, Result}; |
| 27 | use tilecodec::stream::RangeReader; |
| 28 | |
| 29 | struct FileRanges { |
| 30 | file: std::sync::Mutex<File>, |
| 31 | } |
| 32 | |
| 33 | impl RangeReader for FileRanges { |
| 34 | fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> { |
| 35 | let mut file = self.file.lock().map_err(|_| tile_build::proto::Error("lock".into()))?; |
| 36 | file.seek(SeekFrom::Start(offset)) |
| 37 | .map_err(|e| tile_build::proto::Error(format!("seek {offset}: {e}")))?; |
| 38 | let mut buf = vec![0u8; length as usize]; |
| 39 | let mut got = 0usize; |
| 40 | while got < buf.len() { |
| 41 | match file.read(&mut buf[got..]) { |
| 42 | Ok(0) => break, |
| 43 | Ok(n) => got += n, |
| 44 | Err(e) => return err(format!("read at {offset}: {e}")), |
| 45 | } |
| 46 | } |
| 47 | buf.truncate(got); |
| 48 | Ok(buf) |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | fn kind_name(dict: &Dictionary, kind: u16) -> &str { |
| 53 | if kind == 0 { |
| 54 | return "(land-base)"; |
| 55 | } |
| 56 | dict.kind_name(kind).unwrap_or("?") |
| 57 | } |
| 58 | |
| 59 | fn main() -> ExitCode { |
| 60 | let args: Vec<String> = std::env::args().collect(); |
| 61 | if args.len() < 3 { |
| 62 | eprintln!("usage: mamaps_probe IN.mamaps Z/X/Y [Z/X/Y ...]"); |
| 63 | eprintln!(" or: mamaps_probe IN.mamaps --breakdown [SAMPLES_PER_ZOOM]"); |
| 64 | return ExitCode::from(2); |
| 65 | } |
| 66 | let file = match File::open(&args[1]) { |
| 67 | Ok(f) => f, |
| 68 | Err(e) => { |
| 69 | eprintln!("mamaps_probe: cannot open {}: {e}", args[1]); |
| 70 | return ExitCode::from(1); |
| 71 | } |
| 72 | }; |
| 73 | if args[2] == "--breakdown" { |
| 74 | let samples: usize = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(200); |
| 75 | return breakdown(&args[1], samples); |
| 76 | } |
| 77 | if args[2] == "--layers" { |
| 78 | let samples: usize = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(200); |
| 79 | return layer_breakdown(&args[1], samples); |
| 80 | } |
| 81 | if args[2] == "--sidecars" { |
| 82 | return sidecars(&args[1]); |
| 83 | } |
| 84 | let archive = match MamapsArchive::open(FileRanges { file: std::sync::Mutex::new(file) }) { |
| 85 | Ok(a) => a, |
| 86 | Err(e) => { |
| 87 | eprintln!("mamaps_probe: open: {e}"); |
| 88 | return ExitCode::from(1); |
| 89 | } |
| 90 | }; |
| 91 | println!( |
| 92 | "archive z{}-{} build_id {:#018x} validated={}", |
| 93 | archive.header.min_zoom, |
| 94 | archive.header.max_zoom, |
| 95 | archive.header.build_id, |
| 96 | archive.header.rings_validated(), |
| 97 | ); |
| 98 | let mut code = ExitCode::SUCCESS; |
| 99 | for spec in &args[2..] { |
| 100 | let mut parts = spec.split('/'); |
| 101 | let tile = match (parts.next(), parts.next(), parts.next(), parts.next()) { |
| 102 | (Some(z), Some(x), Some(y), None) => { |
| 103 | match (z.parse::<u8>(), x.parse::<u32>(), y.parse::<u32>()) { |
| 104 | (Ok(z), Ok(x), Ok(y)) => (z, x, y), |
| 105 | _ => { |
| 106 | eprintln!("mamaps_probe: bad tile '{spec}', want Z/X/Y"); |
| 107 | code = ExitCode::from(2); |
| 108 | continue; |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | _ => { |
| 113 | eprintln!("mamaps_probe: bad tile '{spec}', want Z/X/Y"); |
| 114 | code = ExitCode::from(2); |
| 115 | continue; |
| 116 | } |
| 117 | }; |
| 118 | let (z, x, y) = tile; |
| 119 | match archive.tile(z, x, y) { |
| 120 | Err(e) => { |
| 121 | println!("{z}/{x}/{y}\tERROR {e}"); |
| 122 | code = ExitCode::from(1); |
| 123 | } |
| 124 | Ok(None) => println!("{z}/{x}/{y}\tABSENT"), |
| 125 | Ok(Some(body)) => print_tile(&archive.dictionary, z, x, y, &body), |
| 126 | } |
| 127 | } |
| 128 | code |
| 129 | } |
| 130 | |
| 131 | fn print_tile(dict: &Dictionary, z: u8, x: u32, y: u32, body: &Body) { |
| 132 | let extent = body.extent.max(1) as f64; |
| 133 | let full = extent * extent; |
| 134 | let Some(layer) = body.layer(tile_build::mamaps::dict::LAYER_LANDTYPE) else { |
| 135 | println!("{z}/{x}/{y}\tno landtype layer"); |
| 136 | return; |
| 137 | }; |
| 138 | // Per-kind ground: sum of absolute ring areas, so holes add rather than cancel. |
| 139 | let mut kinds: std::collections::BTreeMap<u16, (usize, f64)> = |
| 140 | std::collections::BTreeMap::new(); |
| 141 | let mut feats = 0usize; |
| 142 | for feature in &layer.features { |
| 143 | if feature.geom_type != GEOM_POLYGON { |
| 144 | continue; |
| 145 | } |
| 146 | feats += 1; |
| 147 | let mut area = 0.0f64; |
| 148 | for part in layer.parts_of(feature) { |
| 149 | area += ring_area(layer.points(part)).abs(); |
| 150 | } |
| 151 | let e = kinds.entry(feature.kind).or_insert((0, 0.0)); |
| 152 | e.0 += 1; |
| 153 | e.1 += area; |
| 154 | } |
| 155 | if kinds.is_empty() { |
| 156 | println!("{z}/{x}/{y}\tlandtype: no polygons ({feats} polygon features)"); |
| 157 | return; |
| 158 | } |
| 159 | let mut bits: Vec<String> = Vec::new(); |
| 160 | for (kind, (count, area)) in &kinds { |
| 161 | bits.push(format!( |
| 162 | "{}x{}={:.1}%", |
| 163 | kind_name(dict, *kind), |
| 164 | count, |
| 165 | 100.0 * area / full |
| 166 | )); |
| 167 | } |
| 168 | let dem = if body.heightmap.is_some() { " dem" } else { "" }; |
| 169 | println!("{z}/{x}/{y}\tlandtype: {}{}", bits.join(" "), dem); |
| 170 | } |
| 171 | |
| 172 | fn ring_area(pts: &[(i16, i16)]) -> f64 { |
| 173 | let n = pts.len(); |
| 174 | if n < 3 { |
| 175 | return 0.0; |
| 176 | } |
| 177 | let mut twice: i64 = 0; |
| 178 | for i in 0..n { |
| 179 | let (x1, y1) = pts[i]; |
| 180 | let (x2, y2) = pts[(i + 1) % n]; |
| 181 | twice += x1 as i64 * y2 as i64 - x2 as i64 * y1 as i64; |
| 182 | } |
| 183 | twice as f64 / 2.0 |
| 184 | } |
| 185 | |
| 186 | /// Walk the whole archive and report per-zoom storage: addressed tiles (with |
| 187 | /// run-length expansion), stored bodies, stored (DEFLATE) bytes, plus sampled |
| 188 | /// body stats — the heightmap share and the raw (pre-DEFLATE) body/heightmap |
| 189 | /// sizes that say how much of each zoom is elevation. |
| 190 | /// |
| 191 | /// The index walk reads only the root (already in the open prefix) plus one |
| 192 | /// read per leaf — kilobytes against a 60 GB file. Bodies are fetched only for |
| 193 | /// the sample: evenly spaced entries per zoom, so one sample per ~N bodies, |
| 194 | /// each a single range read plus inflate. |
| 195 | fn breakdown(path: &str, samples_per_zoom: usize) -> ExitCode { |
| 196 | use tile_build::mamaps::{header, index}; |
| 197 | use tilecodec::pmtiles::tile_zxy; |
| 198 | |
| 199 | let file = match File::open(path) { |
| 200 | Ok(f) => f, |
| 201 | Err(e) => { |
| 202 | eprintln!("mamaps_probe: cannot open {path}: {e}"); |
| 203 | return ExitCode::from(1); |
| 204 | } |
| 205 | }; |
| 206 | let ranges = FileRanges { file: std::sync::Mutex::new(file) }; |
| 207 | // Header + dictionary + root straight out of the open prefix. |
| 208 | let prefix = match ranges.read(0, tilecodec::stream::OPEN_PREFIX_BYTES) { |
| 209 | Ok(p) => p, |
| 210 | Err(e) => { |
| 211 | eprintln!("mamaps_probe: open: {e}"); |
| 212 | return ExitCode::from(1); |
| 213 | } |
| 214 | }; |
| 215 | let hdr = match header::Header::parse(&prefix) { |
| 216 | Ok(h) => h, |
| 217 | Err(e) => { |
| 218 | eprintln!("mamaps_probe: header: {e}"); |
| 219 | return ExitCode::from(1); |
| 220 | } |
| 221 | }; |
| 222 | let root = match index::parse_root( |
| 223 | &prefix[hdr.root_offset as usize..(hdr.root_offset + hdr.root_len as u64) as usize], |
| 224 | ) { |
| 225 | Ok(r) => r, |
| 226 | Err(e) => { |
| 227 | eprintln!("mamaps_probe: root: {e}"); |
| 228 | return ExitCode::from(1); |
| 229 | } |
| 230 | }; |
| 231 | let file_len = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0); |
| 232 | println!( |
| 233 | "archive z{}-{} build_id {:#018x} validated={} compression={} file={:.2}GB data={:.2}GB bodies_written={} tiles_addressed={}", |
| 234 | hdr.min_zoom, |
| 235 | hdr.max_zoom, |
| 236 | hdr.build_id, |
| 237 | hdr.rings_validated(), |
| 238 | hdr.compression, |
| 239 | file_len as f64 / 1e9, |
| 240 | hdr.data_len as f64 / 1e9, |
| 241 | hdr.bodies_written, |
| 242 | hdr.tiles_addressed, |
| 243 | ); |
| 244 | // Per-zoom aggregates from the index alone. |
| 245 | struct Zoom { |
| 246 | addressed: u64, |
| 247 | bodies: u64, |
| 248 | stored: u64, |
| 249 | entries: Vec<(u64, u32)>, |
| 250 | } |
| 251 | let mut zooms: std::collections::BTreeMap<u8, Zoom> = std::collections::BTreeMap::new(); |
| 252 | for root_entry in &root { |
| 253 | let raw_len = root_entry.leaf_entry_count as u64 * index::LEAF_ENTRY_LEN as u64; |
| 254 | let stored_len = if root_entry.stored_len == 0 { raw_len } else { root_entry.stored_len as u64 }; |
| 255 | let stored = match ranges.read( |
| 256 | (hdr.leaf_offset + root_entry.leaf_offset) as u64, |
| 257 | stored_len as u32, |
| 258 | ) { |
| 259 | Ok(r) => r, |
| 260 | Err(e) => { |
| 261 | eprintln!("mamaps_probe: leaf: {e}"); |
| 262 | return ExitCode::from(1); |
| 263 | } |
| 264 | }; |
| 265 | let raw = if root_entry.stored_len == 0 { |
| 266 | stored |
| 267 | } else { |
| 268 | match index::decompress_leaf(&stored, raw_len as usize) { |
| 269 | Ok(r) => r, |
| 270 | Err(e) => { |
| 271 | eprintln!("mamaps_probe: leaf inflate: {e}"); |
| 272 | return ExitCode::from(1); |
| 273 | } |
| 274 | } |
| 275 | }; |
| 276 | let leaf = match index::parse_leaf(&raw) { |
| 277 | Ok(l) => l, |
| 278 | Err(e) => { |
| 279 | eprintln!("mamaps_probe: leaf parse: {e}"); |
| 280 | return ExitCode::from(1); |
| 281 | } |
| 282 | }; |
| 283 | for e in &leaf { |
| 284 | let (z, _, _) = tile_zxy(root_entry.base_tile_id + e.tile_id_lo as u64); |
| 285 | let at = hdr.data_offset + root_entry.base_data_offset + e.offset_delta as u64; |
| 286 | let zoom = zooms.entry(z).or_insert(Zoom { |
| 287 | addressed: 0, |
| 288 | bodies: 0, |
| 289 | stored: 0, |
| 290 | entries: Vec::new(), |
| 291 | }); |
| 292 | zoom.addressed += e.run_length as u64; |
| 293 | zoom.bodies += 1; |
| 294 | zoom.stored += e.length as u64; |
| 295 | zoom.entries.push((at, e.length)); |
| 296 | } |
| 297 | } |
| 298 | println!("zoom addressed bodies stored_GB avg_stored"); |
| 299 | let mut total_stored = 0u64; |
| 300 | for (z, zoom) in &zooms { |
| 301 | total_stored += zoom.stored; |
| 302 | println!( |
| 303 | "z{z:<3} {:>9} {:>8} {:>10.3} {:>8}", |
| 304 | zoom.addressed, |
| 305 | zoom.bodies, |
| 306 | zoom.stored as f64 / 1e9, |
| 307 | fmt_bytes(zoom.stored / zoom.bodies.max(1)), |
| 308 | ); |
| 309 | } |
| 310 | println!("total stored bodies: {:.3} GB", total_stored as f64 / 1e9); |
| 311 | // Sampled bodies per zoom: heightmap share + raw sizes. |
| 312 | let archive = match MamapsArchive::open(FileRanges { |
| 313 | file: std::sync::Mutex::new(File::open(path).expect("open")), |
| 314 | }) { |
| 315 | Ok(a) => a, |
| 316 | Err(e) => { |
| 317 | eprintln!("mamaps_probe: reopen: {e}"); |
| 318 | return ExitCode::from(1); |
| 319 | } |
| 320 | }; |
| 321 | println!("zoom sampled with_dem dem_share avg_raw_body avg_raw_dem dem_of_raw stored_dem dem_of_stored"); |
| 322 | for (z, zoom) in &zooms { |
| 323 | if zoom.entries.is_empty() { |
| 324 | continue; |
| 325 | } |
| 326 | let step = (zoom.entries.len() / samples_per_zoom.max(1)).max(1); |
| 327 | let mut sampled = 0u64; |
| 328 | let mut with_dem = 0u64; |
| 329 | let mut raw_body = 0u64; |
| 330 | let mut raw_dem = 0u64; |
| 331 | let mut stored_dem = 0u64; |
| 332 | let mut stored_nodem = 0u64; |
| 333 | let mut idx = 0usize; |
| 334 | while idx < zoom.entries.len() { |
| 335 | let (at, len) = zoom.entries[idx]; |
| 336 | let stored = match archive.reader().read(at, len) { |
| 337 | Ok(s) => s, |
| 338 | Err(_) => { |
| 339 | idx += step; |
| 340 | continue; |
| 341 | } |
| 342 | }; |
| 343 | let raw = match tile_build::mamaps::read::decompress(hdr.compression, &stored) { |
| 344 | Ok(r) => r, |
| 345 | Err(_) => { |
| 346 | idx += step; |
| 347 | continue; |
| 348 | } |
| 349 | }; |
| 350 | let body = match Body::parse(&raw) { |
| 351 | Ok(b) => b, |
| 352 | Err(_) => { |
| 353 | idx += step; |
| 354 | continue; |
| 355 | } |
| 356 | }; |
| 357 | sampled += 1; |
| 358 | raw_body += raw.len() as u64; |
| 359 | if let Some(hm) = &body.heightmap { |
| 360 | with_dem += 1; |
| 361 | raw_dem += (2 + hm.samples.len() * 2) as u64; |
| 362 | stored_dem += len as u64; |
| 363 | } else { |
| 364 | stored_nodem += len as u64; |
| 365 | } |
| 366 | idx += step; |
| 367 | } |
| 368 | if sampled == 0 { |
| 369 | continue; |
| 370 | } |
| 371 | // Stored-bytes split: mean stored size of dem vs no-dem bodies, scaled to |
| 372 | // the zoom's body count. DEFLATE-compressibility differs between the two |
| 373 | // populations, so this is measured, not modelled. |
| 374 | let dem_bodies = zoom.bodies as f64 * with_dem as f64 / sampled as f64; |
| 375 | let nodem_bodies = zoom.bodies as f64 - dem_bodies; |
| 376 | let avg_stored_dem = if with_dem > 0 { stored_dem / with_dem } else { 0 }; |
| 377 | let avg_stored_nodem = |
| 378 | if sampled > with_dem { stored_nodem / (sampled - with_dem) } else { 0 }; |
| 379 | let stored_dem_total = dem_bodies * avg_stored_dem as f64; |
| 380 | println!( |
| 381 | "z{z:<3} {:>7} {:>8} {:>8.1}% {:>11} {:>10} {:>8.1}% {:>10} {:>6.1}%", |
| 382 | sampled, |
| 383 | with_dem, |
| 384 | 100.0 * with_dem as f64 / sampled as f64, |
| 385 | fmt_bytes(raw_body / sampled), |
| 386 | if with_dem > 0 { |
| 387 | fmt_bytes(raw_dem / with_dem).to_string() |
| 388 | } else { |
| 389 | "-".to_string() |
| 390 | }, |
| 391 | 100.0 * raw_dem as f64 / raw_body.max(1) as f64, |
| 392 | fmt_bytes(stored_dem_total as u64), |
| 393 | 100.0 * stored_dem_total / zoom.stored.max(1) as f64, |
| 394 | ); |
| 395 | } |
| 396 | ExitCode::SUCCESS |
| 397 | } |
| 398 | |
| 399 | fn fmt_bytes(n: u64) -> String { |
| 400 | if n >= 1_000_000 { |
| 401 | format!("{:.1}M", n as f64 / 1e6) |
| 402 | } else if n >= 1_000 { |
| 403 | format!("{:.1}K", n as f64 / 1e3) |
| 404 | } else { |
| 405 | format!("{n}B") |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | /// List the packed sidecar sections: kind, byte offset, length. Reads only the |
| 410 | /// 32-byte `MAMA8` footer off the file's tail plus the section directory it |
| 411 | /// points at — kilobytes against a 60 GB file. |
| 412 | /// |
| 413 | /// Sidecars are appended **uncompressed** after the tile data (see |
| 414 | /// `mamaps_pack`), so these lengths are the bytes on disk, not estimates. |
| 415 | fn sidecars(path: &str) -> ExitCode { |
| 416 | use tile_build::mamaps::archive::{ARCHIVE_DIR_HEADER_LEN, ARCHIVE_ENTRY_LEN, ARCHIVE_FOOTER_LEN}; |
| 417 | |
| 418 | fn kind_name(kind: u8) -> &'static str { |
| 419 | match kind { |
| 420 | 1 => "graph_meta (metadata.bin: MARG header, node/edge/escape/name counts)", |
| 421 | 2 => "graph_nodes (nodes.bin: per-node records + sentinel)", |
| 422 | 3 => "graph_edges (edges.bin: edge records + escape index/rows + name bitmap/offs)", |
| 423 | 4 => "graph_intermediate (intermediate.bin: geometry blob + trailer)", |
| 424 | 5 => "graph_names (road_names.bin: NUL-terminated string pool)", |
| 425 | 6 => "graph_lanes (lanes.bin: sparse lane index + blob)", |
| 426 | 7 => "graph_elevation (elevation.bin: per-node i16 elevations)", |
| 427 | 8 => "poi_index (poi_index.bin: 14 B records, one per POI)", |
| 428 | 9 => "poi_names (poi_names.bin: NUL-terminated name pool)", |
| 429 | 10 => "poi_attrs (poi_attrs.bin: MAPA attribute sidecar)", |
| 430 | 11 => "poi_spatial (poi_spatial.bin: PSP1 spatial grid)", |
| 431 | 12 => "poi_words (poi_name_index.bin: PNI1 full-text word index)", |
| 432 | 13 => "transit (world.transit: TRIX pack of routes/shapes)", |
| 433 | _ => "unknown", |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | let file = match File::open(path) { |
| 438 | Ok(f) => f, |
| 439 | Err(e) => { |
| 440 | eprintln!("mamaps_probe: cannot open {path}: {e}"); |
| 441 | return ExitCode::from(1); |
| 442 | } |
| 443 | }; |
| 444 | let ranges = FileRanges { file: std::sync::Mutex::new(file) }; |
| 445 | let file_len = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0); |
| 446 | if file_len < ARCHIVE_FOOTER_LEN as u64 { |
| 447 | eprintln!("mamaps_probe: file shorter than a footer"); |
| 448 | return ExitCode::from(1); |
| 449 | } |
| 450 | let foot = match ranges.read(file_len - ARCHIVE_FOOTER_LEN as u64, ARCHIVE_FOOTER_LEN as u32) |
| 451 | { |
| 452 | Ok(f) => f, |
| 453 | Err(e) => { |
| 454 | eprintln!("mamaps_probe: footer read: {e}"); |
| 455 | return ExitCode::from(1); |
| 456 | } |
| 457 | }; |
| 458 | if &foot[0..8] != b"MAMA8\0\0\0" { |
| 459 | println!("no MAMA8 footer: tiles-only archive, no sidecars packed"); |
| 460 | return ExitCode::SUCCESS; |
| 461 | } |
| 462 | let u64_at = |o: usize| { |
| 463 | u64::from_le_bytes([ |
| 464 | foot[o], foot[o + 1], foot[o + 2], foot[o + 3], foot[o + 4], foot[o + 5], foot[o + 6], |
| 465 | foot[o + 7], |
| 466 | ]) |
| 467 | }; |
| 468 | let (dir_offset, dir_len, build_id) = (u64_at(8), u64_at(16), u64_at(24)); |
| 469 | let dir = match ranges.read(dir_offset, dir_len as u32) { |
| 470 | Ok(d) => d, |
| 471 | Err(e) => { |
| 472 | eprintln!("mamaps_probe: directory read: {e}"); |
| 473 | return ExitCode::from(1); |
| 474 | } |
| 475 | }; |
| 476 | let count = u32::from_le_bytes([dir[0], dir[1], dir[2], dir[3]]) as usize; |
| 477 | println!("MAMA8 footer: build_id {build_id:#018x} dir at {dir_offset} ({dir_len} B) file {file_len} B"); |
| 478 | println!("kind section (+ what the payload holds)"); |
| 479 | println!(" offset length"); |
| 480 | let mut total = 0u64; |
| 481 | for i in 0..count { |
| 482 | let at = ARCHIVE_DIR_HEADER_LEN + i * ARCHIVE_ENTRY_LEN; |
| 483 | let e = &dir[at..at + ARCHIVE_ENTRY_LEN]; |
| 484 | let u32_at = |o: usize| u32::from_le_bytes([e[o], e[o + 1], e[o + 2], e[o + 3]]); |
| 485 | let u64_at = |o: usize| { |
| 486 | u64::from_le_bytes([ |
| 487 | e[o], e[o + 1], e[o + 2], e[o + 3], e[o + 4], e[o + 5], e[o + 6], e[o + 7], |
| 488 | ]) |
| 489 | }; |
| 490 | // Entry layout: kind u8 @0, flags u32 @4, offset u64 @8, len u64 @16, extra u64 @24. |
| 491 | let (kind, offset, len) = (e[0], u64_at(8), u64_at(16)); |
| 492 | let _ = u32_at(0); |
| 493 | total += len; |
| 494 | println!("{kind:<5} {}", kind_name(kind)); |
| 495 | println!(" {offset:<17} {}", fmt_bytes(len)); |
| 496 | } |
| 497 | println!("sidecar total: {} ({:.1}% of file)", fmt_bytes(total), 100.0 * total as f64 / file_len as f64); |
| 498 | ExitCode::SUCCESS |
| 499 | } |
| 500 | |
| 501 | /// Per-layer, per-zoom raw payload sizes from sampled bodies: for each zoom, |
| 502 | /// the mean raw (pre-DEFLATE) bytes each layer's features+parts+coords occupy, |
| 503 | /// scaled to the zoom's body count. Plus the side tables (names, ids, lanes, |
| 504 | /// buildings, heightmap, carriageways, region links) the same way. |
| 505 | /// |
| 506 | /// Raw, not stored: the body DEFLATEs as one blob, so per-section stored bytes |
| 507 | /// are unmeasurable — but raw sizes are exact per body, and the ratio between |
| 508 | /// sections is what says where the bytes go. The heightmap column is the DEM |
| 509 | /// answer: `2 + dim*dim*2` bytes wherever the section is present. |
| 510 | fn layer_breakdown(path: &str, samples_per_zoom: usize) -> ExitCode { |
| 511 | use tile_build::mamaps::{header, index}; |
| 512 | use tilecodec::pmtiles::tile_zxy; |
| 513 | |
| 514 | let file = match File::open(path) { |
| 515 | Ok(f) => f, |
| 516 | Err(e) => { |
| 517 | eprintln!("mamaps_probe: cannot open {path}: {e}"); |
| 518 | return ExitCode::from(1); |
| 519 | } |
| 520 | }; |
| 521 | let ranges = FileRanges { file: std::sync::Mutex::new(file) }; |
| 522 | let prefix = match ranges.read(0, tilecodec::stream::OPEN_PREFIX_BYTES) { |
| 523 | Ok(p) => p, |
| 524 | Err(e) => { |
| 525 | eprintln!("mamaps_probe: open: {e}"); |
| 526 | return ExitCode::from(1); |
| 527 | } |
| 528 | }; |
| 529 | let hdr = match header::Header::parse(&prefix) { |
| 530 | Ok(h) => h, |
| 531 | Err(e) => { |
| 532 | eprintln!("mamaps_probe: header: {e}"); |
| 533 | return ExitCode::from(1); |
| 534 | } |
| 535 | }; |
| 536 | let dictionary = match tile_build::mamaps::dict::Dictionary::parse( |
| 537 | &prefix[hdr.dict_offset as usize..(hdr.dict_offset + hdr.dict_len as u64) as usize], |
| 538 | ) { |
| 539 | Ok(d) => d, |
| 540 | Err(e) => { |
| 541 | eprintln!("mamaps_probe: dict: {e}"); |
| 542 | return ExitCode::from(1); |
| 543 | } |
| 544 | }; |
| 545 | let root = match index::parse_root( |
| 546 | &prefix[hdr.root_offset as usize..(hdr.root_offset + hdr.root_len as u64) as usize], |
| 547 | ) { |
| 548 | Ok(r) => r, |
| 549 | Err(e) => { |
| 550 | eprintln!("mamaps_probe: root: {e}"); |
| 551 | return ExitCode::from(1); |
| 552 | } |
| 553 | }; |
| 554 | // Leaf entries per zoom (positions only — bodies fetched in the sample pass). |
| 555 | let mut zoom_entries: std::collections::BTreeMap<u8, Vec<(u64, u32)>> = |
| 556 | std::collections::BTreeMap::new(); |
| 557 | let mut zoom_bodies: std::collections::BTreeMap<u8, u64> = |
| 558 | std::collections::BTreeMap::new(); |
| 559 | for root_entry in &root { |
| 560 | let raw_len = root_entry.leaf_entry_count as u64 * index::LEAF_ENTRY_LEN as u64; |
| 561 | let stored_len = if root_entry.stored_len == 0 { raw_len } else { root_entry.stored_len as u64 }; |
| 562 | let stored = match ranges.read((hdr.leaf_offset + root_entry.leaf_offset) as u64, stored_len as u32) |
| 563 | { |
| 564 | Ok(r) => r, |
| 565 | Err(e) => { |
| 566 | eprintln!("mamaps_probe: leaf: {e}"); |
| 567 | return ExitCode::from(1); |
| 568 | } |
| 569 | }; |
| 570 | let raw = if root_entry.stored_len == 0 { |
| 571 | stored |
| 572 | } else { |
| 573 | match index::decompress_leaf(&stored, raw_len as usize) { |
| 574 | Ok(r) => r, |
| 575 | Err(e) => { |
| 576 | eprintln!("mamaps_probe: leaf inflate: {e}"); |
| 577 | return ExitCode::from(1); |
| 578 | } |
| 579 | } |
| 580 | }; |
| 581 | let leaf = match index::parse_leaf(&raw) { |
| 582 | Ok(l) => l, |
| 583 | Err(e) => { |
| 584 | eprintln!("mamaps_probe: leaf parse: {e}"); |
| 585 | return ExitCode::from(1); |
| 586 | } |
| 587 | }; |
| 588 | for e in &leaf { |
| 589 | let (z, _, _) = tile_zxy(root_entry.base_tile_id + e.tile_id_lo as u64); |
| 590 | let at = hdr.data_offset + root_entry.base_data_offset + e.offset_delta as u64; |
| 591 | zoom_entries.entry(z).or_default().push((at, e.length)); |
| 592 | *zoom_bodies.entry(z).or_default() += 1; |
| 593 | } |
| 594 | } |
| 595 | let layer_name = |id: u8| -> String { |
| 596 | dictionary.layer_name(id).unwrap_or("?").to_string() |
| 597 | }; |
| 598 | let archive = match MamapsArchive::open(FileRanges { |
| 599 | file: std::sync::Mutex::new(File::open(path).expect("open")), |
| 600 | }) { |
| 601 | Ok(a) => a, |
| 602 | Err(e) => { |
| 603 | eprintln!("mamaps_probe: reopen: {e}"); |
| 604 | return ExitCode::from(1); |
| 605 | } |
| 606 | }; |
| 607 | // Fixed layer order for the table: the schema's own layer list, then the |
| 608 | // side tables in wire order. |
| 609 | let mut layer_order: Vec<u8> = (0..dictionary.layers.len() as u8).collect(); |
| 610 | layer_order.sort_by_key(|id| layer_name(*id)); |
| 611 | println!("per-zoom mean RAW body bytes by section (sampled bodies, scaled to zoom body count):"); |
| 612 | for (z, entries) in &zoom_entries { |
| 613 | let bodies = zoom_bodies[z] as f64; |
| 614 | let step = (entries.len() / samples_per_zoom.max(1)).max(1); |
| 615 | let mut sampled = 0u64; |
| 616 | let mut layer_raw: std::collections::BTreeMap<u8, u64> = |
| 617 | std::collections::BTreeMap::new(); |
| 618 | let mut names = 0u64; |
| 619 | let mut ids = 0u64; |
| 620 | let mut lanes = 0u64; |
| 621 | let mut buildings = 0u64; |
| 622 | let mut dem = 0u64; |
| 623 | let mut dem_tiles = 0u64; |
| 624 | let mut carriage = 0u64; |
| 625 | let mut regions = 0u64; |
| 626 | let mut idx = 0usize; |
| 627 | while idx < entries.len() { |
| 628 | let (at, len) = entries[idx]; |
| 629 | let stored = match archive.reader().read(at, len) { |
| 630 | Ok(s) => s, |
| 631 | Err(_) => { |
| 632 | idx += step; |
| 633 | continue; |
| 634 | } |
| 635 | }; |
| 636 | let raw = match tile_build::mamaps::read::decompress(hdr.compression, &stored) { |
| 637 | Ok(r) => r, |
| 638 | Err(_) => { |
| 639 | idx += step; |
| 640 | continue; |
| 641 | } |
| 642 | }; |
| 643 | let body = match Body::parse(&raw) { |
| 644 | Ok(b) => b, |
| 645 | Err(_) => { |
| 646 | idx += step; |
| 647 | continue; |
| 648 | } |
| 649 | }; |
| 650 | sampled += 1; |
| 651 | for layer in &body.layers { |
| 652 | // Raw payload: 24 B per feature record, 12 B per part entry |
| 653 | // (10 + align4), ~2-3 B per coordinate (zigzag varint mean). |
| 654 | let payload = layer.features.len() as u64 * 24 |
| 655 | + layer.parts.len() as u64 * 12 |
| 656 | + layer.coords.len() as u64 * 3; |
| 657 | *layer_raw.entry(layer.layer_id).or_default() += payload; |
| 658 | } |
| 659 | for s in &body.names { |
| 660 | names += s.len() as u64 + 1; |
| 661 | } |
| 662 | for (_, v) in &body.ids { |
| 663 | ids += v.len() as u64 * 8; |
| 664 | } |
| 665 | for (_, v) in &body.turn_lanes { |
| 666 | for t in v { |
| 667 | lanes += 2 + t.forward.len() as u64 * 2 + t.backward.len() as u64 * 2; |
| 668 | } |
| 669 | } |
| 670 | for (_, v) in &body.buildings { |
| 671 | buildings += v.len() as u64 * 20; |
| 672 | } |
| 673 | if let Some(hm) = &body.heightmap { |
| 674 | dem_tiles += 1; |
| 675 | dem += (2 + hm.samples.len() * 2) as u64; |
| 676 | } |
| 677 | for (_, v) in &body.carriageways { |
| 678 | carriage += v.len() as u64 * 6; |
| 679 | } |
| 680 | for (_, v) in &body.region_links { |
| 681 | regions += v.len() as u64 * 8; |
| 682 | } |
| 683 | idx += step; |
| 684 | } |
| 685 | if sampled == 0 { |
| 686 | continue; |
| 687 | } |
| 688 | // Scale the per-body mean to the zoom's full body count. (An earlier |
| 689 | // version multiplied by bodies/sampled — dividing by the sample twice |
| 690 | // and understating every absolute ~400x. Ratios were unaffected.) |
| 691 | let scale = bodies; |
| 692 | let mut cells: Vec<String> = Vec::new(); |
| 693 | let mut total = 0u64; |
| 694 | for id in &layer_order { |
| 695 | let mean = layer_raw.get(id).copied().unwrap_or(0) as f64 / sampled as f64; |
| 696 | let zoom_total = (mean * scale) as u64; |
| 697 | total += zoom_total; |
| 698 | if zoom_total > 0 { |
| 699 | cells.push(format!("{}={}", layer_name(*id), fmt_bytes(zoom_total))); |
| 700 | } |
| 701 | } |
| 702 | let mut side = |n: u64, label: &str| -> Option<String> { |
| 703 | let t = (n as f64 / sampled as f64 * scale) as u64; |
| 704 | total += t; |
| 705 | (t > 0).then(|| format!("{label}={}", fmt_bytes(t))) |
| 706 | }; |
| 707 | for s in [ |
| 708 | side(names, "names"), |
| 709 | side(ids, "ids"), |
| 710 | side(lanes, "lanes"), |
| 711 | side(buildings, "bldg"), |
| 712 | side(dem, "DEM"), |
| 713 | side(carriage, "carr"), |
| 714 | side(regions, "rgn"), |
| 715 | ] |
| 716 | .into_iter() |
| 717 | .flatten() |
| 718 | { |
| 719 | cells.push(s); |
| 720 | } |
| 721 | let dem_share = dem as f64 / sampled as f64 * scale / total.max(1) as f64 * 100.0; |
| 722 | println!( |
| 723 | "z{z:<3} bodies={:<9} raw_total={:<8} dem_tiles={:.0}% dem_share={:.0}% {}", |
| 724 | zoom_bodies[z], |
| 725 | fmt_bytes(total), |
| 726 | 100.0 * dem_tiles as f64 / sampled as f64, |
| 727 | dem_share, |
| 728 | cells.join(" "), |
| 729 | ); |
| 730 | } |
| 731 | ExitCode::SUCCESS |
| 732 | } |