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

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

extract.rs211 lines · 11.2 KiBRaw
1//! Stage A: `.osm.pbf` in, classified geometry in lon/lat out.
2//!
3//! Three passes, because a PBF is ordered nodes-then-ways-then-relations and a way's geometry needs
4//! coordinates that arrived before its tags did:
5//!
6//! 1. **ways + relations.** Classify tags. Spill the node refs of every classified way to a
7//! sequential file and keep the member way ids of every classified relation. Node blobs are
8//! skipped outright.
9//! 2. **ways again**, keeping the refs of the ways some relation lists as a member. A second pass
10//! rather than keeping every untagged way's refs from the first, because "every untagged way in
11//! California" is 40 M node ids and the members are a few hundred thousand.
12//! 3. **nodes.** Fill coordinates for exactly the ids the first two passes asked for, at 16 bytes
13//! per needed node.
14//!
15//! That last point is the whole memory argument. [`osm_ingest::nodeloc::NodeLocations`] costs
16//! `O(needed)`; `graph_build`'s bitset costs 2.5 GB keyed by raw OSM node id whatever the extract,
17//! and peaks near 10 GB on California. A water-and-buildings build needs a few million nodes, so it
18//! pays tens of megabytes.
19//!
20//! # Nothing large is resident across the passes
21//!
22//! Neither of the two big tables this stage produces is held in memory. Features go to
23//! [`Store`]; classified ways go to [`WaySink`], exploiting the fact that pass 1 already sees them
24//! in ascending id order so no sort is needed to read them back in the order the archive wants.
25//! What stays resident is the set a sequential file cannot serve: the refs of the ways that some
26//! relation lists as a member, because a relation reaches those by id in its own order.
27//!
28//! # Collecting the needed ids: two shapes, one switch
29//!
30//! Pass 3 needs the ids sorted and unique, and there are two ways to get there. The obvious one --
31//! one `Vec<i64>` of every ref **with duplicates**, sorted and deduped in place -- is what
32//! [`collect_needed_in_memory`] does, and it is right up to a point: it is exact, it needs no
33//! assumption about the ids, and on anything smaller than a continent it is smaller than the
34//! alternative. Past that point it is the largest thing in the whole build. North-america is ~19 GB
35//! of it; planet projects to ~96 GB and a sort of 12 G elements.
36//!
37//! [`collect_needed_by_bitset`] is the other shape, taken above [`REFS_IN_MEMORY`]: a bit per node
38//! id, which is at most ~1.7 GB *for any extract, forever*, because OSM's node ids are monotonic and
39//! near 13 G. The bitset's words move into the rank index directly ([`NodeLocations::from_bitset`])
40//! rather than being walked out as ids and re-set -- walking them out would hold two ~1.5 GB words
41//! arrays at once. Both paths must produce the same sequence and
42//! `the_two_ref_collectors_agree_on_the_same_input` holds them to it.
43//!
44//! # Nothing large outlives its phase
45//!
46//! The tables above are freed as soon as their last reader is done, not at the end of the stage:
47//! the blob-kinds mask after the node pass, the ways spill (plus corridor overrides and inherited
48//! lane counts) after `materialise_ways`, and relations, member refs and the coordinate table
49//! after `materialise_relations` -- before the coastline, transit and routing-graph externals.
50//! The planet build died at the junction tail with the OSM tables still resident beside a freshly
51//! `Graph::load`ed graph; the frees plus the graph's own file mappings (no heap `Vec`s, no commit
52//! charge) are what keep those two peaks apart. `plan_ways_spill` / `plan_feature_spill` decide
53//! the anon-vs-file backend from the counts before the bytes are asked for.
54
55use std::collections::HashMap;
56use std::path::Path;
57
58use osm_ingest::nodeloc::{resolve_nodes_with, NodeLocations};
59use osm_ingest::osm::{visit_block, Element, NodeView, MEMBER_NODE, MEMBER_WAY};
60use osm_ingest::pbf::{self, KIND_RELATIONS, KIND_WAYS};
61use osm_ingest::proto::{err, Result};
62use osm_ingest::rings::{self, MemberWay, RingStats};
63use osm_ingest::select::Select;
64use tile_build::geom::Geometry;
65use tile_build::par;
66use tile_build::progress::Progress;
67use rayon::prelude::*;
68
69use crate::schema::{self, Class, Layers};
70use crate::store::{Sink, Store, WayCounts, WayReader, WaySink};
71use tilecodec::mamaps::body::{BuildingAttrs, Carriageway};
72use tilecodec::mamaps::dict::LAYER_BUILDINGS;
73
74/// One classified feature, in lon/lat, ready to tile.
75///
76/// `name` is the coalesced display label for `places` and `poi` points, `None` for every other
77/// layer. Carried here (not in [`Class`]) because it is a string and `Class` is `Copy`.
78/// `transit_color` is the aggregated route colour for `transit` lines (`0xRRGGBB`), zero for
79/// every other layer, and `transit_ordinal`/`transit_lanes`/`transit_taper` are the inputs the
80/// renderer needs to place such a line in a lane of the corridor it shares.
81pub struct Feature {
82 pub class: Class,
83 pub geometry: Geometry,
84 pub name: Option<String>,
85 /// The OSM element this came from, tagged by id space — see [`tagged_id`].
86 ///
87 /// [`ID_NONE`](tilecodec::mamaps::body::ID_NONE) for every layer but `places` and `poi`.
88 /// Only those two reach the archive's id table, and only those two are pure points that
89 /// `coalesce` never merges, so only those two have an id that means anything.
90 pub id: u64,
91 pub transit_color: u32,
92 pub transit_ordinal: u8,
93 pub transit_lanes: u8,
94 pub transit_taper: u8,
95 /// A `roads` feature's carriageway lane count, zero for every other layer and for a road with
96 /// no `lanes` tag. Baked into the body feature so the renderer can draw the carriageway as its
97 /// individual lanes at high zoom. See [`crate::schema::roads::lane_count`].
98 pub lane_count: u8,
99 /// A road's per-lane turn-indication masks, `(forward, backward)`, left to right — the
100 /// `LANE_*` bits of OSM `turn:lanes[:forward|:backward]`. Empty for every other layer and for
101 /// a road with no `turn:lanes`. Baked into the body's turn-lane side table so the renderer can
102 /// draw per-lane arrows at junctions. See [`crate::schema::roads::turn_masks`].
103 pub turn_fwd: Vec<u16>,
104 pub turn_bwd: Vec<u16>,
105 /// How a road's lanes divide between the two directions, and which dividers between them may
106 /// not be crossed. Default for every other layer and for a road whose split was never
107 /// surveyed. Baked into the body's carriageway side table so the renderer can put the centre
108 /// line where it belongs rather than down the middle. See [`crate::schema::roads::carriageway`].
109 pub carriageway: Carriageway,
110 /// A building's OSM Simple 3D Buildings attributes (height, roof, colours), `None` for every
111 /// non-building feature. Baked into the body's building side table so the renderer can extrude
112 /// the footprint in 3D. See [`crate::schema::buildings::attrs`].
113 pub building: Option<BuildingAttrs>,
114}
115
116/// The id space an [`Feature::id`] came from, in the low two bits.
117///
118/// OSM numbers nodes, ways and relations independently and the three sequences overlap freely,
119/// so a bare id does not identify an element. Tags start at one rather than zero so that a fully
120/// zero id stays reserved for [`ID_NONE`](tilecodec::mamaps::body::ID_NONE).
121pub const ELEMENT_NODE: u64 = 1;
122pub const ELEMENT_WAY: u64 = 2;
123pub const ELEMENT_RELATION: u64 = 3;
124
125/// An OSM id tagged with its id space, or `ID_NONE` for an id OSM would never issue.
126pub fn tagged_id(id: i64, element: u64) -> u64 {
127 // OSM element ids start at 1. A zero or negative one is a synthetic element (a coastline
128 // polygon, a GTFS shape) with no upstream identity to carry.
129 if id <= 0 {
130 return tilecodec::mamaps::body::ID_NONE;
131 }
132 ((id as u64) << 2) | element
133}
134
135/// What a run of stage A did, for the build report.
136#[derive(Debug, Default, Clone)]
137pub struct Stats {
138 pub ways_classified: u64,
139 pub relations_classified: u64,
140 pub features: u64,
141 /// Classified elements whose geometry could not be built — an extract cut through them, or a
142 /// relation's rings would not close.
143 pub geometry_failed: u64,
144 pub nodes_needed: u64,
145 /// Land polygons read from a prepared coastline product, if one was given.
146 pub land_polygons: u64,
147 /// Nodes classified as `places`/`poi` labels.
148 pub nodes_classified: u64,
149 /// Coloured rail lines read from a prepared GTFS transit-routes export, if one was given.
150 pub transit_routes: u64,
151 /// Drivable component segments emitted into the `traffic` layer from the v6 routing graph.
152 pub traffic_segments: u64,
153 /// Lane connectors emitted into the `junction` layer from the same graph.
154 pub junction_connectors: u64,
155 /// Road ways whose `min_zoom` was pulled shallower to match their corridor.
156 pub corridor_promotions: u64,
157 /// Untagged road ways that took a lane count from a tagged neighbour. See [`crate::lanefill`].
158 pub lanes_inherited: u64,
159 pub rings: RingStats,
160}
161
162/// A classified way, held only from the blob it was decoded in until its chunk reaches [`WaySink`].
163struct Way {
164 class: Class,
165 refs: Vec<i64>,
166 /// The display label for `places`/`poi` ways, `None` for every other layer.
167 name: Option<String>,
168 /// A road's carriageway lane count, zero for every other layer and for a road with no `lanes`
169 /// tag. See [`crate::schema::roads::lane_count`].
170 lane_count: u8,
171 /// A road's per-lane turn masks `(forward, backward)`; empty otherwise. See
172 /// [`crate::schema::roads::turn_masks`].
173 turn_fwd: Vec<u16>,
174 turn_bwd: Vec<u16>,
175 /// A road's directional lane split and solid dividers; default otherwise. See
176 /// [`crate::schema::roads::carriageway`].
177 carriageway: Carriageway,
178 /// A building's S3DB attributes, `None` for every non-building. See
179 /// [`crate::schema::buildings::attrs`].
180 building: Option<BuildingAttrs>,
181}
182
183/// A classified relation, held between passes.
184struct Relation {
185 class: Class,
186 /// `(way id, role is inner)`, in the order the relation lists them, which is what
187 /// [`rings::assemble`] stitches.
188 members: Vec<(i64, bool)>,
189 /// A relation carrying a shape is stitched into rings; one carrying a border is emitted as its
190 /// member lines. Which it is comes from [`Class::area`] rather than from the relation's `type`
191 /// tag, because both an administrative border and a protected area are `type=boundary`.
192 area: bool,
193 /// The display label for a `places` relation (a country, a region), `None` otherwise.
194 name: Option<String>,
195 /// The relation's own OSM id, tagged — see [`tagged_id`]. Only read for label relations.
196 id: i64,
197 /// A building relation's S3DB attributes (a multipolygon `building=*`), `None` otherwise.
198 building: Option<BuildingAttrs>,
199 /// A `place` relation's headcount (`population` tag), for country label zoom scoring
200 /// (see `extract_fallback::country_zoom`). Read in pass 1 while the tags are in hand;
201 /// `None` for every non-place relation and for places nobody counted (Antarctica).
202 population: Option<u64>,
203 /// The ISO 3166-1 code of an `admin_level=2` relation, `None` for every other relation. What
204 /// the tile's marking convention is resolved from — see [`crate::schema::boundaries::Conventions`].
205 iso: Option<String>,
206}
207
208include!("extract_part1.rs");
209include!("extract_part2.rs");
210include!("extract_part3.rs");
211include!("extract_part4.rs");