Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / scripts / maps / tile_build / src / bin / mamaps_probe.rs

mamaps_probe.rs386 lines · 13.9 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
19use std::fs::File;
20use std::io::{Read, Seek, SeekFrom};
21use std::process::ExitCode;
22
23use tile_build::mamaps::body::{Body, GEOM_POLYGON};
24use tile_build::mamaps::dict::Dictionary;
25use tile_build::mamaps::read::MamapsArchive;
26use tile_build::proto::{err, Result};
27use tilecodec::stream::RangeReader;
28
29struct FileRanges {
30 file: std::sync::Mutex<File>,
31}
32
33impl 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
52fn 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
59fn 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
131fn 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!("{}x{}={:.1}%", kind_name(dict, *kind), count, 100.0 * area / full));
162 }
163 let dem = if body.heightmap.is_some() { " dem" } else { "" };
164 println!("{z}/{x}/{y}\tlandtype: {}{}", bits.join(" "), dem);
165}
166
167fn ring_area(pts: &[(i16, i16)]) -> f64 {
168 let n = pts.len();
169 if n < 3 {
170 return 0.0;
171 }
172 let mut twice: i64 = 0;
173 for i in 0..n {
174 let (x1, y1) = pts[i];
175 let (x2, y2) = pts[(i + 1) % n];
176 twice += x1 as i64 * y2 as i64 - x2 as i64 * y1 as i64;
177 }
178 twice as f64 / 2.0
179}
180
181/// Walk the whole archive and report per-zoom storage: addressed tiles (with
182/// run-length expansion), stored bodies, stored (DEFLATE) bytes, plus sampled
183/// body stats — the heightmap share and the raw (pre-DEFLATE) body/heightmap
184/// sizes that say how much of each zoom is elevation.
185///
186/// The index walk reads only the root (already in the open prefix) plus one
187/// read per leaf — kilobytes against a 60 GB file. Bodies are fetched only for
188/// the sample: evenly spaced entries per zoom, so one sample per ~N bodies,
189/// each a single range read plus inflate.
190fn breakdown(path: &str, samples_per_zoom: usize) -> ExitCode {
191 use tile_build::mamaps::{header, index};
192 use tilecodec::pmtiles::tile_zxy;
193
194 let file = match File::open(path) {
195 Ok(f) => f,
196 Err(e) => {
197 eprintln!("mamaps_probe: cannot open {path}: {e}");
198 return ExitCode::from(1);
199 }
200 };
201 let ranges = FileRanges { file: std::sync::Mutex::new(file) };
202 // Header + dictionary + root straight out of the open prefix.
203 let prefix = match ranges.read(0, tilecodec::stream::OPEN_PREFIX_BYTES) {
204 Ok(p) => p,
205 Err(e) => {
206 eprintln!("mamaps_probe: open: {e}");
207 return ExitCode::from(1);
208 }
209 };
210 let hdr = match header::Header::parse(&prefix) {
211 Ok(h) => h,
212 Err(e) => {
213 eprintln!("mamaps_probe: header: {e}");
214 return ExitCode::from(1);
215 }
216 };
217 let root = match index::parse_root(
218 &prefix[hdr.root_offset as usize..(hdr.root_offset + hdr.root_len as u64) as usize],
219 ) {
220 Ok(r) => r,
221 Err(e) => {
222 eprintln!("mamaps_probe: root: {e}");
223 return ExitCode::from(1);
224 }
225 };
226 let file_len = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
227 println!(
228 "archive z{}-{} build_id {:#018x} validated={} compression={} file={:.2}GB data={:.2}GB bodies_written={} tiles_addressed={}",
229 hdr.min_zoom,
230 hdr.max_zoom,
231 hdr.build_id,
232 hdr.rings_validated(),
233 hdr.compression,
234 file_len as f64 / 1e9,
235 hdr.data_len as f64 / 1e9,
236 hdr.bodies_written,
237 hdr.tiles_addressed,
238 );
239 // Per-zoom aggregates from the index alone.
240 struct Zoom {
241 addressed: u64,
242 bodies: u64,
243 stored: u64,
244 entries: Vec<(u64, u32)>,
245 }
246 let mut zooms: std::collections::BTreeMap<u8, Zoom> = std::collections::BTreeMap::new();
247 for root_entry in &root {
248 let raw_len = root_entry.leaf_entry_count as u64 * index::LEAF_ENTRY_LEN as u64;
249 let stored_len =
250 if root_entry.stored_len == 0 { raw_len } else { root_entry.stored_len as u64 };
251 let stored = match ranges
252 .read((hdr.leaf_offset + root_entry.leaf_offset) as u64, stored_len as u32)
253 {
254 Ok(r) => r,
255 Err(e) => {
256 eprintln!("mamaps_probe: leaf: {e}");
257 return ExitCode::from(1);
258 }
259 };
260 let raw = if root_entry.stored_len == 0 {
261 stored
262 } else {
263 match index::decompress_leaf(&stored, raw_len as usize) {
264 Ok(r) => r,
265 Err(e) => {
266 eprintln!("mamaps_probe: leaf inflate: {e}");
267 return ExitCode::from(1);
268 }
269 }
270 };
271 let leaf = match index::parse_leaf(&raw) {
272 Ok(l) => l,
273 Err(e) => {
274 eprintln!("mamaps_probe: leaf parse: {e}");
275 return ExitCode::from(1);
276 }
277 };
278 for e in &leaf {
279 let (z, _, _) = tile_zxy(root_entry.base_tile_id + e.tile_id_lo as u64);
280 let at = hdr.data_offset + root_entry.base_data_offset + e.offset_delta as u64;
281 let zoom = zooms.entry(z).or_insert(Zoom {
282 addressed: 0,
283 bodies: 0,
284 stored: 0,
285 entries: Vec::new(),
286 });
287 zoom.addressed += e.run_length as u64;
288 zoom.bodies += 1;
289 zoom.stored += e.length as u64;
290 zoom.entries.push((at, e.length));
291 }
292 }
293 println!("zoom addressed bodies stored_GB avg_stored");
294 let mut total_stored = 0u64;
295 for (z, zoom) in &zooms {
296 total_stored += zoom.stored;
297 println!(
298 "z{z:<3} {:>9} {:>8} {:>10.3} {:>8}",
299 zoom.addressed,
300 zoom.bodies,
301 zoom.stored as f64 / 1e9,
302 fmt_bytes(zoom.stored / zoom.bodies.max(1)),
303 );
304 }
305 println!("total stored bodies: {:.3} GB", total_stored as f64 / 1e9);
306 // Sampled bodies per zoom: heightmap share + raw sizes.
307 let archive = match MamapsArchive::open(FileRanges {
308 file: std::sync::Mutex::new(File::open(path).expect("open")),
309 }) {
310 Ok(a) => a,
311 Err(e) => {
312 eprintln!("mamaps_probe: reopen: {e}");
313 return ExitCode::from(1);
314 }
315 };
316 println!("zoom sampled with_dem dem_share avg_raw_body avg_raw_dem dem_of_raw stored_dem dem_of_stored");
317 for (z, zoom) in &zooms {
318 if zoom.entries.is_empty() {
319 continue;
320 }
321 let step = (zoom.entries.len() / samples_per_zoom.max(1)).max(1);
322 let mut sampled = 0u64;
323 let mut with_dem = 0u64;
324 let mut raw_body = 0u64;
325 let mut raw_dem = 0u64;
326 let mut stored_dem = 0u64;
327 let mut idx = 0usize;
328 while idx < zoom.entries.len() {
329 let (at, len) = zoom.entries[idx];
330 let stored = match archive.reader().read(at, len) {
331 Ok(s) => s,
332 Err(_) => {
333 idx += step;
334 continue;
335 }
336 };
337 let raw = match tile_build::mamaps::read::decompress(hdr.compression, &stored) {
338 Ok(r) => r,
339 Err(_) => {
340 idx += step;
341 continue;
342 }
343 };
344 let body = match Body::parse(&raw) {
345 Ok(b) => b,
346 Err(_) => {
347 idx += step;
348 continue;
349 }
350 };
351 sampled += 1;
352 raw_body += raw.len() as u64;
353 if let Some(hm) = &body.heightmap {
354 with_dem += 1;
355 raw_dem += (2 + hm.samples.len() * 2) as u64;
356 stored_dem += len as u64;
357 }
358 idx += step;
359 }
360 if sampled == 0 {
361 continue;
362 }
363 // Stored-bytes split: mean stored size of dem vs no-dem bodies, scaled to
364 // the zoom's body count. DEFLATE-compressibility differs between the two
365 // populations, so this is measured, not modelled.
366 let dem_bodies = zoom.bodies as f64 * with_dem as f64 / sampled as f64;
367 let avg_stored_dem = stored_dem.checked_div(with_dem).unwrap_or(0);
368 let stored_dem_total = dem_bodies * avg_stored_dem as f64;
369 println!(
370 "z{z:<3} {:>7} {:>8} {:>8.1}% {:>11} {:>10} {:>8.1}% {:>10} {:>6.1}%",
371 sampled,
372 with_dem,
373 100.0 * with_dem as f64 / sampled as f64,
374 fmt_bytes(raw_body / sampled),
375 raw_dem
376 .checked_div(with_dem)
377 .map_or_else(|| "-".to_string(), |v| fmt_bytes(v).to_string()),
378 100.0 * raw_dem as f64 / raw_body.max(1) as f64,
379 fmt_bytes(stored_dem_total as u64),
380 100.0 * stored_dem_total / zoom.stored.max(1) as f64,
381 );
382 }
383 ExitCode::SUCCESS
384}
385
386include!("mamaps_probe_parts/mamaps_probe_part1.rs");