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

Modern-Apps.git / scripts / maps / mamaps_build / src / main.rs

main.rs313 lines · 13.3 KiBRaw
1//! `mamaps_build` — one `.osm.pbf` in, one `.mamaps` archive out.
2//!
3//! The generator this project exists to build. It produces all 9 layers (`landtype`, `roads`,
4//! `boundaries`, `buildings`, `places`, `poi`, `transit`, `traffic`, `junction`), and the shape
5//! does not change when a rule does because every layer is one module under [`schema`].
6//!
7//! ```text
8//! mamaps_build --input california.osm.pbf --out california.mamaps
9//! --coastline LAND.shp --graph GRAPH_DIR
10//! --transit-routes ROUTES.geojsonseq --dem HEIGHTMAPS.mdem
11//! [--region california|world]
12//! [--build-graph-to DIR] [--build-poi-to DIR]
13//!
14//! All six flags are required. Every build carries all 9 layers at z0-14 as
15//! FORMAT_VERSION 8: there is no layer selection, no zoom selection and no
16//! store reuse, so a build is a pure function of its six inputs.
17//!
18//! `--region` filters the built layers (`roads`, `poi`, `buildings`) to the
19//! region's bbox. Everything else is always included regardless. `world` (the
20//! default) disables the filter.
21//!
22//! `--graph-ready-file PATH` lets the build start while `road_graph` is still writing
23//! `--graph`: every stage that does not read the graph runs first, and the build waits for PATH
24//! to exist (polling once a second, logging "waiting for graph") before the first one that does.
25//! See [`GraphGate`] for exactly which stages those are. Without the flag nothing changes.
26//!
27//! `--build-graph-to` / `--build-poi-to` fold the routing graph and POI
28//! sidecars into this process instead of running `road_graph` / `poi_extract`
29//! as separate binaries first. Same thread pool, one shared blob scan, and the
30//! graph coverage is validated against the region before stage A runs — which
31//! is what stops a 43-minute tile build dying on a missing `metadata.bin`.
32//! ```
33//!
34//! # Why not through the existing tiler
35//!
36//! `tile_build` already turns GeoJSON-seq into PMTiles, and routing through it would have been less
37//! new code. But it would also mean encoding to MVT and decoding again, which loses exactly the
38//! attributes this format was built to carry: a road's `is_bridge`, a boundary's numeric admin
39//! level, a ring's stated winding. So the geometry is reused — projection, significance,
40//! simplification, tile bisection, clipping, all of `tile_build` — and only the last step, turning a
41//! clipped shape into bytes, is this crate's.
42
43use std::path::PathBuf;
44use std::process::ExitCode;
45
46mod coalesce;
47mod coalesce_extra;
48mod corridor;
49mod dem;
50mod extract;
51mod extract_fallback;
52mod lanefill;
53mod rings;
54mod schema;
55mod shapefile;
56mod store;
57mod tiler;
58mod tilespill;
59mod timing;
60
61/// The allocator, replaced because the default one was three quarters of the build.
62///
63/// A build tool has no business caring which allocator it gets, and this one did not until the
64/// encode pass was measured against the machine it runs on: **1358 s of worker CPU against 180 s of
65/// wall on a 32-core, 64-thread box** — a speed-up of 7.5 where the pool can give 64. Nothing in
66/// that pass is shared. [`rings::normalise`], `body::serialize_into` and DEFLATE each read one tile
67/// and write one tile, there is no lock and no atomic in the path, and the
68/// memory traffic works out at a few hundred MB/s against eight channels of DDR5. The only thing
69/// all sixty-four threads still contend on is the heap.
70///
71/// And they hit it hard. `normalise` allocates a `Vec` per polygon group, another for its exterior
72/// and one per hole it keeps, on the way to rebuilding a layer's arenas; z14 of a us-west build is
73/// 44.4 M features across 943,401 tiles, which is tens of millions of allocate/free pairs on
74/// Windows' process heap in about two and a half minutes.
75///
76/// Swapping it out took the tiling stage from **351 s to 110 s** on the same spill, for a
77/// byte-identical archive:
78///
79/// | phase | default heap | mimalloc |
80/// |---|---|---|
81/// | map | 125.1 s | 72.9 s |
82/// | merge | 33.2 s | 9.6 s |
83/// | encode | 180.3 s | 21.6 s |
84/// | append | 12.4 s | 3.3 s |
85/// | *encode CPU: stage C* | *452.6 s* | *54.4 s* |
86/// | *encode CPU: serialise* | *355.9 s* | *5.4 s* |
87/// | *encode CPU: deflate* | *550.0 s* | *181.1 s* |
88///
89/// Serialisation is the one that says what this really was. It is a memcpy into a reused
90/// [`tilecodec::mamaps::body::Scratch`] and it cost 356 s of CPU; it now costs 5.4 s. That was never
91/// encoding, it was the handful of buffer growths per tile going to `HeapAlloc` under sixty-four
92/// threads of contention.
93///
94/// Two things this is not. It is not a substitute for allocating less — `normalise` should be
95/// threading scratch buffers through rather than building a `Vec` per ring, and a cheaper allocator
96/// only makes that less urgent. And it is not free: mimalloc holds freed pages back rather than
97/// returning them promptly, which took peak RSS from 6.86 GB to 10.14 GB on the same build. That
98/// trade is worth revisiting if memory becomes the binding constraint again.
99///
100/// No `mi_collect` purge is wired after stage A's phase drops for the same reason: `mi_collect`
101/// lives behind the `extended` feature (plus its `cty` dependency), which is not in the offline
102/// registry cache, and the drops that matter for the planet peak are not heap frees at all --
103/// unmapping an anon segment releases pagefile commit immediately, and a file mapping never
104/// charged it. A purge would only return heap slack (relations, members, rayon buffers), which
105/// is measured in hundreds of MB against the multi-GB anon/mmap peaks above.
106///
107/// It cannot change a byte of the output — an allocator decides *where*, never *what* — so it needed
108/// no argument about ordering, only a measurement. The us-west archive hashes the same either way.
109#[global_allocator]
110static ALLOCATOR: mimalloc::MiMalloc = mimalloc::MiMalloc;
111
112/// The deepest zoom an archive is built to. Fixed: every build is z0-14.
113///
114/// Named rather than inlined because layer code is bounded by it: a layer's tiler-side `min_zoom`
115/// past this lands its features in no tile at all, so [`schema::junction`] pins itself against
116/// this constant and lowering it fails that test instead of silently emptying a layer.
117pub const DEFAULT_MAX_ZOOM: u8 = 14;
118
119fn main() -> ExitCode {
120 let args: Vec<String> = std::env::args().collect();
121 let mut input: Option<PathBuf> = None;
122 let mut out: Option<PathBuf> = None;
123 let mut coastline: Option<PathBuf> = None;
124 let mut transit_routes: Option<PathBuf> = None;
125 let mut graph: Option<PathBuf> = None;
126 let mut dem: Option<PathBuf> = None;
127 let mut region: Option<String> = None;
128 let mut build_graph_to: Option<PathBuf> = None;
129 let mut build_poi_to: Option<PathBuf> = None;
130 let mut graph_ready_file: Option<PathBuf> = None;
131 let mut v8_bodies = false;
132 let mut size = tiler::SizeOpts::DEFAULT;
133
134 let mut i = 1;
135 while i < args.len() {
136 let value = |name: &str| -> Result<String, String> {
137 args.get(i + 1).cloned().ok_or_else(|| format!("{name} needs a value"))
138 };
139 let taken = match args[i].as_str() {
140 "--input" => value("--input").map(|v| {
141 input = Some(PathBuf::from(v));
142 2
143 }),
144 "--out" => value("--out").map(|v| {
145 out = Some(PathBuf::from(v));
146 2
147 }),
148 "--coastline" => value("--coastline").map(|v| {
149 coastline = Some(PathBuf::from(v));
150 2
151 }),
152 "--transit-routes" => value("--transit-routes").map(|v| {
153 transit_routes = Some(PathBuf::from(v));
154 2
155 }),
156 "--graph" => value("--graph").map(|v| {
157 graph = Some(PathBuf::from(v));
158 2
159 }),
160 "--dem" => value("--dem").map(|v| {
161 dem = Some(PathBuf::from(v));
162 2
163 }),
164 "--region" => value("--region").map(|v| {
165 region = Some(v);
166 2
167 }),
168 "--build-graph-to" => value("--build-graph-to").map(|v| {
169 build_graph_to = Some(PathBuf::from(v));
170 2
171 }),
172 "--build-poi-to" => value("--build-poi-to").map(|v| {
173 build_poi_to = Some(PathBuf::from(v));
174 2
175 }),
176 "--graph-ready-file" => value("--graph-ready-file").map(|v| {
177 graph_ready_file = Some(PathBuf::from(v));
178 2
179 }),
180 // Dense v8 bodies instead of the v10 default (was the `MAMAPS_V8` environment
181 // variable; a flag, so no environment value can change an output byte).
182 "--v8-bodies" => {
183 v8_bodies = true;
184 Ok(1)
185 }
186 // Planet-size prototype knobs (see `tiler::SizeOpts`); defaults = today's bytes.
187 "--body-zstd" => value("--body-zstd").and_then(|v| {
188 size.zstd_level = v.parse().map_err(|_| format!("--body-zstd: bad level '{v}'"))?;
189 Ok(2)
190 }),
191 "--dem-max-error" => value("--dem-max-error").and_then(|v| {
192 size.dem_max_error_m =
193 v.parse().map_err(|_| format!("--dem-max-error: bad '{v}'"))?;
194 Ok(2)
195 }),
196 "--dem-px" => value("--dem-px").and_then(|v| {
197 size.dem_px = v.parse().map_err(|_| format!("--dem-px: bad '{v}'"))?;
198 Ok(2)
199 }),
200 "--simplify-scale" => value("--simplify-scale").and_then(|v| {
201 size.simplify_scale =
202 v.parse().map_err(|_| format!("--simplify-scale: bad '{v}'"))?;
203 Ok(2)
204 }),
205 "--z14-tolerance" => value("--z14-tolerance").and_then(|v| {
206 size.z14_tolerance =
207 v.parse().map_err(|_| format!("--z14-tolerance: bad '{v}'"))?;
208 Ok(2)
209 }),
210 "--keep-z13-wash" => {
211 size.keep_z13_wash = true;
212 Ok(1)
213 }
214 "--no-junction-layer" => {
215 size.no_junction = true;
216 Ok(1)
217 }
218 "--coord-quant" => {
219 size.coord_quant = true;
220 Ok(1)
221 }
222 "-h" | "--help" => {
223 usage();
224 return ExitCode::SUCCESS;
225 }
226 other => Err(format!("unexpected argument '{other}'")),
227 };
228 match taken {
229 Ok(step) => i += step,
230 Err(e) => {
231 eprintln!("mamaps_build: {e}");
232 usage();
233 return ExitCode::from(2);
234 }
235 }
236 }
237
238 let (Some(input), Some(out), Some(coastline), Some(transit_routes), Some(graph), Some(dem)) =
239 (input, out, coastline, transit_routes, graph, dem)
240 else {
241 usage();
242 return ExitCode::from(2);
243 };
244
245 // `--region` defaults to world (no filtering). Parsed here so a bad value
246 // fails in seconds, not after stage A.
247 let region = match osm_ingest::region::Region::parse(region.as_deref().unwrap_or("world")) {
248 Ok(r) => r,
249 Err(e) => {
250 eprintln!("mamaps_build: {}", e.0);
251 usage();
252 return ExitCode::from(2);
253 }
254 };
255
256 if tiler::SIZE_OPTS.set(size).is_err() {
257 eprintln!("mamaps_build: size options set twice");
258 return ExitCode::from(2);
259 }
260 if !size.is_default() {
261 println!("size options: {}", size.tag());
262 }
263 let settings = RunSettings {
264 coastline,
265 transit_routes,
266 graph,
267 dem,
268 region,
269 build_graph_to,
270 build_poi_to,
271 graph_ready_file,
272 v8_bodies,
273 };
274 match run(&input, &out, &settings) {
275 Ok(()) => ExitCode::SUCCESS,
276 Err(e) => {
277 eprintln!("mamaps_build: {e}");
278 ExitCode::FAILURE
279 }
280 }
281}
282
283/// Everything a run needs beyond its input and output paths.
284///
285/// All four side inputs are required: every build carries all 9 layers.
286struct RunSettings {
287 /// A prepared land polygon for `landtype`'s mainland — see [`check_required`].
288 coastline: PathBuf,
289 /// A prepared GTFS export for `transit`'s coloured rail lines.
290 transit_routes: PathBuf,
291 /// The v6 routing graph directory (`nodes.bin`/`edges.bin`/`intermediate.bin`/`metadata.bin`)
292 /// for `traffic`'s per-component lines and `junction`'s lane connectors.
293 graph: PathBuf,
294 /// The `.mdem` heightmap dataset `dem_ingest` produced.
295 /// Every tile carries the DEM grid sampled to its own z/x/y.
296 dem: PathBuf,
297 /// Which region's bbox filters roads/pois/buildings. `world` = no filter.
298 region: osm_ingest::region::Region,
299 /// When set, build the routing graph in-process into this dir (shared pool,
300 /// shared blob scan) instead of reading `--graph`.
301 build_graph_to: Option<PathBuf>,
302 /// When set, build the POI sidecars in-process into this dir instead of
303 /// expecting them from a prior `poi_extract` run.
304 build_poi_to: Option<PathBuf>,
305 /// `--graph-ready-file`: start before the routing graph exists and wait for this file to
306 /// appear before the first stage that reads `--graph`. See [`GraphGate`].
307 graph_ready_file: Option<PathBuf>,
308 /// `--v8-bodies`: encode dense v8 tile bodies instead of the v10 default. In the build id.
309 v8_bodies: bool,
310}
311
312include!("main_part1.rs");
313include!("main_part2.rs");