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

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

mamaps_dump.rs444 lines · 19.2 KiBRaw
1//! `mamaps_dump` — print a canonical, line-oriented summary of a `.mamaps` archive.
2//!
3//! Usage:
4//! mamaps_dump IN.mamaps [--mode summary|tiles|header|dict] [--layer NAME]
5//!
6//! Print a canonical, line-oriented summary of a `.mamaps` archive: a binary
7//! container is only reviewable if there is a text rendering of it, and a golden
8//! file only diffs if that rendering is deterministic. Everything here is
9//! `BTreeMap`/`BTreeSet` ordered, so there is no sort step and no way for output
10//! order to depend on a hash seed.
11//!
12//! Modes:
13//! summary one line per (zoom, layer): tile/feature counts, geometry-type counts and the
14//! sorted union of `kind`s. The default.
15//! tiles one line per (z/x/y, layer). Verbose, for chasing a single tile.
16//! rings one line per (z/x/y, layer, feature, part): winding, point count and signed area.
17//! The finest grain there is, and only sensible with `--tile`.
18//! geometry one line per (z/x/y, layer) carrying the MEASURES of the shapes rather than their
19//! counts: ring count, total absolute ring area, net signed area and total line length.
20//! What `test/diff_mamaps.py` compares, and the check that says two archives hold the
21//! same picture when they do not hold the same bytes.
22//! header the header fields, one per line. Also what checks a published file is sane.
23//! dict the interned tables, one id per line.
24//!
25//! Unlike the on-device reader this reads the whole file into memory. A `.mamaps` archive is opened by
26//! range request on device, but a dump is a host tool run against a file that is already local, and
27//! the format's whole point is that it is smaller than the MVT it replaces.
28
29use std::collections::{BTreeMap, BTreeSet};
30use std::process::ExitCode;
31
32use tile_build::mamaps::body::{Body, GEOM_LINE, GEOM_POINT, GEOM_POLYGON};
33use tile_build::mamaps::{dict, read};
34use tile_build::pmtiles::tile_zxy;
35
36fn main() -> ExitCode {
37 let args: Vec<String> = std::env::args().collect();
38 let mut input = None;
39 let mut mode = "summary".to_string();
40 let mut only_layer: Option<String> = None;
41 let mut only_tile: Option<(u8, u64, u64)> = None;
42
43 let mut i = 1;
44 while i < args.len() {
45 let take = |i: usize| args.get(i + 1).cloned();
46 match args[i].as_str() {
47 "--mode" => {
48 match take(i) {
49 Some(m) => mode = m,
50 None => {
51 eprintln!("mamaps_dump: --mode needs a value");
52 return ExitCode::from(2);
53 }
54 }
55 i += 2;
56 }
57 "--layer" => {
58 only_layer = take(i);
59 i += 2;
60 }
61 "--tile" => {
62 match take(i).as_deref().and_then(parse_tile) {
63 Some(t) => only_tile = Some(t),
64 None => {
65 eprintln!("mamaps_dump: --tile needs a z/x/y, e.g. 13/1308/2994");
66 return ExitCode::from(2);
67 }
68 }
69 i += 2;
70 }
71 "-h" | "--help" => {
72 usage();
73 return ExitCode::SUCCESS;
74 }
75 other if other.starts_with('-') => {
76 eprintln!("mamaps_dump: unexpected argument '{other}'");
77 usage();
78 return ExitCode::from(2);
79 }
80 other => {
81 if input.is_some() {
82 eprintln!("mamaps_dump: more than one input archive given");
83 return ExitCode::from(2);
84 }
85 input = Some(other.to_string());
86 i += 1;
87 }
88 }
89 }
90
91 let Some(input) = input else {
92 usage();
93 return ExitCode::from(2);
94 };
95 let bytes = match std::fs::read(&input) {
96 Ok(b) => b,
97 Err(e) => {
98 eprintln!("mamaps_dump: cannot read {input}: {e}");
99 return ExitCode::from(1);
100 }
101 };
102 match run(&bytes, &mode, only_layer.as_deref(), only_tile) {
103 Ok(code) => code,
104 Err(e) => {
105 eprintln!("mamaps_dump: {input}: {e}");
106 ExitCode::from(1)
107 }
108 }
109}
110
111/// `z/x/y` as three integers, or `None` if it is not that.
112fn parse_tile(s: &str) -> Option<(u8, u64, u64)> {
113 let mut parts = s.split('/');
114 let z = parts.next()?.parse().ok()?;
115 let x = parts.next()?.parse().ok()?;
116 let y = parts.next()?.parse().ok()?;
117 parts.next().is_none().then_some((z, x, y))
118}
119
120fn run(
121 bytes: &[u8],
122 mode: &str,
123 only_layer: Option<&str>,
124 only_tile: Option<(u8, u64, u64)>,
125) -> tile_build::proto::Result<ExitCode> {
126 let (header, dictionary, _root) = read::open_prefix(bytes)?;
127 if mode == "header" {
128 // The byte the archive actually carries, not the constant this binary was built with.
129 // `open_prefix` refuses anything but the current version, so the two agree by the time we
130 // get here — but printing the constant would report "3" for a v3 reader no matter what
131 // was on disk, which makes the line useless as a check on a freshly built archive.
132 println!("format_version\t{}", bytes[7]);
133 println!("build_id\t{:#018x}", header.build_id);
134 println!("flags\t{:#06x}", header.flags);
135 println!("bodies_compressed\t{}", header.compressed());
136 println!("rings_validated\t{}", header.rings_validated());
137 println!("compression\t{}", header.compression);
138 println!("layer_count\t{}", header.layer_count);
139 println!("min_zoom\t{}", header.min_zoom);
140 println!("max_zoom\t{}", header.max_zoom);
141 println!("file_len\t{}", header.file_len);
142 println!("dict\t{}+{}", header.dict_offset, header.dict_len);
143 println!("root\t{}+{}", header.root_offset, header.root_len);
144 println!("leaves\t{}+{}\tcount={}", header.leaf_offset, header.leaf_len, header.leaf_count);
145 println!("data\t{}+{}", header.data_offset, header.data_len);
146 println!("leaf_entry_capacity\t{}", header.leaf_entry_capacity);
147 println!("tiles_addressed\t{}", header.tiles_addressed);
148 println!("bodies_written\t{}", header.bodies_written);
149 // The dedup ratio, which is the number worth watching between builds: it is what makes
150 // ocean and empty tiles nearly free.
151 println!(
152 "dedup\t{:.3}",
153 header.bodies_written as f64 / header.tiles_addressed.max(1) as f64,
154 );
155 println!("min_lon_e7\t{}", header.min_lon_e7);
156 println!("min_lat_e7\t{}", header.min_lat_e7);
157 println!("max_lon_e7\t{}", header.max_lon_e7);
158 println!("max_lat_e7\t{}", header.max_lat_e7);
159 println!("prefix_bytes\t{}", 128 + header.dict_len + header.root_len);
160 return Ok(ExitCode::SUCCESS);
161 }
162 if mode == "dict" {
163 for (id, name) in dictionary.layers.iter().enumerate() {
164 println!("layer\t{id}\t{name}");
165 }
166 for (index, name) in dictionary.kinds.iter().enumerate() {
167 println!("kind\t{}\t{name}", index + 1);
168 }
169 for (index, name) in dictionary.details.iter().enumerate() {
170 println!("kind_detail\t{}\t{name}", index + 1);
171 }
172 return Ok(ExitCode::SUCCESS);
173 }
174 if !matches!(mode, "summary" | "tiles" | "geometry" | "rings" | "names" | "ids") {
175 eprintln!("mamaps_dump: unknown mode '{mode}'");
176 return Ok(ExitCode::from(2));
177 }
178
179 let mut agg: BTreeMap<(u8, String), Agg> = BTreeMap::new();
180 let mut undecodable = 0usize;
181 for (tile_id, run_length, body) in read::read_all(bytes)? {
182 let body = match Body::parse(&body) {
183 Ok(b) => b,
184 Err(_) => {
185 undecodable += 1;
186 continue;
187 }
188 };
189 // A run is one body standing in for several tiles, and each of those tiles is really
190 // present — so expanding it is what makes the counts comparable with an archive that
191 // happened not to dedup.
192 for offset in 0..run_length as u64 {
193 let (z, x, y) = tile_zxy(tile_id + offset);
194 if only_tile.is_some_and(|want| want != (z, x, y)) {
195 continue;
196 }
197 for layer in &body.layers {
198 let name = dictionary
199 .layer_name(layer.layer_id)
200 .map(str::to_string)
201 .unwrap_or_else(|| format!("layer{}", layer.layer_id));
202 if only_layer.is_some_and(|want| want != name) {
203 continue;
204 }
205 let mut geoms: BTreeMap<&str, usize> = BTreeMap::new();
206 if mode == "names" {
207 // One line per named feature: the label spot-check. Unnamed features are
208 // silent, so an empty result means "no names here" rather than "no features".
209 for (fi, feature) in layer.features.iter().enumerate() {
210 if let Some(label) = feature.name(&body) {
211 let kind = dictionary
212 .kind_name(feature.kind)
213 .unwrap_or("?");
214 println!(
215 "{z}/{x}/{y}\t{name}\tfeature={fi}\tkind={kind}\tlabel={label}"
216 );
217 }
218 }
219 continue;
220 }
221 if mode == "ids" {
222 // One line per feature carrying an archive id. Only `places` and `poi`
223 // have an id table at all, so an empty result on those two means the
224 // build dropped the ids, while an empty result elsewhere is correct.
225 for (fi, feature) in layer.features.iter().enumerate() {
226 let Some(id) = body.feature_id(layer.layer_id, fi) else { break };
227 let kind = dictionary.kind_name(feature.kind).unwrap_or("?");
228 let label = feature.name(&body).unwrap_or("");
229 // The low two bits are the OSM id space; see `extract::tagged_id`.
230 let (space, osm) = match id & 0b11 {
231 0 => ("none", 0),
232 1 => ("node", id >> 2),
233 2 => ("way", id >> 2),
234 _ => ("relation", id >> 2),
235 };
236 println!(
237 "{z}/{x}/{y}\t{name}\tfeature={fi}\tkind={kind}\tid={id}\t{space}/{osm}\tlabel={label}"
238 );
239 }
240 continue;
241 }
242 let mut kinds: BTreeSet<String> = BTreeSet::new();
243 let mut points = 0usize;
244 for feature in &layer.features {
245 *geoms.entry(geom_name(feature.geom_type)).or_default() += 1;
246 kinds.insert(kind_label(&dictionary, feature));
247 points +=
248 layer.parts_of(feature).iter().map(|p| p.point_count as usize).sum::<usize>();
249 }
250 if mode == "rings" {
251 for (fi, feature) in layer.features.iter().enumerate() {
252 for (pi, part) in layer.parts_of(feature).iter().enumerate() {
253 let pts = layer.points(part);
254 // Transit colour and lane inputs ride along when set: the
255 // spot-check for coloured lines and for the parallel fan-out
256 // (both empty for every other layer).
257 let color = if feature.transit_color != 0 {
258 format!(
259 "\ttcolor={:06X}\ttordinal={}\ttlanes={}\tttaper={}",
260 feature.transit_color,
261 feature.transit_ordinal,
262 feature.transit_lanes,
263 feature.transit_taper,
264 )
265 } else {
266 String::new()
267 };
268 println!(
269 "{z}/{x}/{y}\t{name}\tfeature={fi}\tpart={pi}\tkind={}\twinding={}\tpoints={}\tsigned={:.2}\tfirst={:?}\tlast={:?}{color}",
270 kind_label(&dictionary, feature),
271 if part.is_hole() { "hole" } else { "outer" },
272 part.point_count,
273 ring_area(pts),
274 pts.first(),
275 pts.last(),
276 );
277 }
278 }
279 continue;
280 }
281 if mode == "geometry" {
282 // Three measures, because they fail differently and the difference
283 // between them is diagnostic:
284 //
285 // rings how many parts. A dropped hole shows up here and nowhere
286 // else -- the geom= column counts FEATURES by type, so a
287 // feature losing a ring looks identical there.
288 // area absolute, summed per ring, so a hole adds rather than
289 // cancels. Sensitive to a ring being lost.
290 // net signed, summed per FEATURE, so holes subtract. This is
291 // the ground actually covered, and it is what a renderer
292 // fills. A self-touching ring's zero-width sliver
293 // contributes nothing to it, which is the point.
294 //
295 // `area` and `net` disagreeing is how a prong of a self-touching
296 // ring changing orientation is told apart from one going missing.
297 let mut rings = 0usize;
298 let mut area = 0.0f64;
299 let mut net = 0.0f64;
300 let mut length = 0.0f64;
301 for feature in &layer.features {
302 for part in layer.parts_of(feature) {
303 let pts = layer.points(part);
304 rings += 1;
305 if feature.geom_type == GEOM_POLYGON {
306 let signed = ring_area(pts);
307 area += signed.abs();
308 net += signed;
309 } else {
310 length += path_length(pts);
311 }
312 }
313 }
314 // Two decimals of an extent unit: far below the quantisation grid the
315 // coordinates are already on, so this cannot manufacture a difference,
316 // and fixed-width so a text diff is meaningful.
317 println!(
318 "{z}/{x}/{y}\t{name}\tfeatures={}\tpoints={points}\trings={rings}\tgeom={}\tarea={area:.2}\tnet={net:.2}\tlength={length:.2}",
319 layer.features.len(),
320 join_counts(&geoms),
321 );
322 continue;
323 }
324 if mode == "tiles" {
325 println!(
326 "{z}/{x}/{y}\t{name}\tfeatures={}\tpoints={points}\textent={}\tgeom={}\tkinds={}",
327 layer.features.len(),
328 body.extent,
329 join_counts(&geoms),
330 kinds.iter().cloned().collect::<Vec<_>>().join(","),
331 );
332 continue;
333 }
334 let entry = agg.entry((z, name)).or_default();
335 entry.tiles += 1;
336 entry.features += layer.features.len();
337 entry.points += points;
338 entry.extents.insert(body.extent);
339 for (geom, count) in geoms {
340 *entry.geoms.entry(geom.to_string()).or_default() += count;
341 }
342 entry.kinds.extend(kinds);
343 }
344 }
345 }
346
347 if mode == "summary" {
348 for ((z, layer), a) in &agg {
349 println!(
350 "z{z}\t{layer}\ttiles={}\tfeatures={}\tpoints={}\textent={}\tgeom={}\tkinds={}",
351 a.tiles,
352 a.features,
353 a.points,
354 a.extents.iter().map(|e| e.to_string()).collect::<Vec<_>>().join("/"),
355 join_counts_owned(&a.geoms),
356 a.kinds.iter().cloned().collect::<Vec<_>>().join(","),
357 );
358 }
359 }
360 // Counted and reported, but not fatal: a dump of a mostly-good archive is more use than no
361 // dump at all, and the count is what says whether to trust the rest.
362 if undecodable > 0 {
363 eprintln!("mamaps_dump: {undecodable} tile(s) could not be decoded");
364 }
365 Ok(ExitCode::SUCCESS)
366}
367
368#[derive(Default)]
369struct Agg {
370 tiles: usize,
371 features: usize,
372 points: usize,
373 extents: BTreeSet<u16>,
374 geoms: BTreeMap<String, usize>,
375 kinds: BTreeSet<String>,
376}
377
378/// How a feature's `kind` prints: its interned name, its numeric detail, or `-` for neither.
379///
380/// `boundaries` carries an admin level rather than a `kind`, so printing the number is the only way
381/// its rows say anything at all.
382fn kind_label(dictionary: &dict::Dictionary, feature: &tile_build::mamaps::body::Feature) -> String {
383 if let Some(level) = feature.detail_number() {
384 return format!("level{level}");
385 }
386 match dictionary.kind_name(feature.kind) {
387 Some(name) => match dictionary.detail_name(feature.kind_detail) {
388 Some(detail) => format!("{name}:{detail}"),
389 None => name.to_string(),
390 },
391 None => "-".to_string(),
392 }
393}
394
395fn geom_name(geom_type: u8) -> &'static str {
396 match geom_type {
397 GEOM_LINE => "line",
398 GEOM_POLYGON => "polygon",
399 GEOM_POINT => "point",
400 _ => "unknown",
401 }
402}
403
404/// Twice-the-signed-area over two, by the shoelace formula, treating the ring as closed.
405///
406/// `i64` throughout before the divide: two `i16` spans multiply to 32 bits and a ring can hold
407/// thousands of them, so accumulating in `f64` would round while `i64` cannot overflow.
408fn ring_area(pts: &[(i16, i16)]) -> f64 {
409 let n = pts.len();
410 if n < 3 {
411 return 0.0;
412 }
413 let mut twice: i64 = 0;
414 for i in 0..n {
415 let (x1, y1) = pts[i];
416 let (x2, y2) = pts[(i + 1) % n];
417 twice += x1 as i64 * y2 as i64 - x2 as i64 * y1 as i64;
418 }
419 twice as f64 / 2.0
420}
421
422fn path_length(pts: &[(i16, i16)]) -> f64 {
423 pts.windows(2)
424 .map(|w| {
425 let dx = w[1].0 as f64 - w[0].0 as f64;
426 let dy = w[1].1 as f64 - w[0].1 as f64;
427 (dx * dx + dy * dy).sqrt()
428 })
429 .sum()
430}
431
432fn join_counts(m: &BTreeMap<&str, usize>) -> String {
433 m.iter().map(|(k, v)| format!("{k}:{v}")).collect::<Vec<_>>().join(",")
434}
435
436fn join_counts_owned(m: &BTreeMap<String, usize>) -> String {
437 m.iter().map(|(k, v)| format!("{k}:{v}")).collect::<Vec<_>>().join(",")
438}
439
440fn usage() {
441 eprintln!(
442 "usage: mamaps_dump IN.mamaps [--mode summary|tiles|geometry|rings|names|ids|header|dict] [--layer NAME] [--tile Z/X/Y]"
443 );
444}