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

Modern-Apps.git / scripts / maps / gtfs_ingest / src / bin / transit_shapes.rs

transit_shapes.rs398 lines · 16.0 KiBRaw
1//! `transit_shapes` — host build tool emitting the basemap's `transit` layer as
2//! newline-delimited GeoJSON (geojsonseq), one `LineString` per distinct rail
3//! polyline, carrying the agency's own `route_color`.
4//!
5//! Usage:
6//! transit_shapes <out.geojsonseq> <feed>...
7//! transit_shapes <out.geojsonseq> --manifest FILE
8//!
9//! `<feed>` is `feed_name=gtfs_dir[=motis_prefix]` or a bare `gtfs_dir`, exactly
10//! as `gtfs_ingest` takes them, so the same `feeds.manifest`
11//! `build_world_transit.ps1` writes drives every tool in this crate.
12//!
13//! # Why GTFS rather than OSM route relations
14//!
15//! The layer used to be derived from `type=route` relations in the `.osm.pbf`,
16//! which got both halves wrong. A relation's members include its **platforms**,
17//! and the member role is not available where the colour is assigned, so every
18//! platform way came out as a wide coloured band beside the track. And the colour
19//! itself was the relation's `colour=` tag when it had one and a per-mode guess
20//! when it did not. `routes.txt` carries the agency's official `route_color` and
21//! `shapes.txt` carries the vehicle's real path with no platforms in it at all.
22//!
23//! # Reading the `.transit` pack instead (`--pack`)
24//!
25//! The pack's ride geometry is fitted to a stop pattern and trimmed to
26//! `[first stop, last stop]`: right for a journey leg, wrong for a basemap line,
27//! which wants the whole alignment. So a v7 pack also carries RAIL_LINES, the
28//! exact shapes this tool reads from each feed, and `--pack` derives the same
29//! layer from it without the raw feeds.
30//!
31//! Like the rest of the crate: no serde, the JSON lines are hand-written.
32
33#[path = "transit_shapes_extra2.rs"]
34mod extra2;
35
36#[path = "transit_shapes_intercity.rs"]
37mod intercity;
38
39#[path = "transit_shapes_pack.rs"]
40mod pack;
41
42#[path = "transit_shapes_extra.rs"]
43#[cfg(test)]
44mod extra;
45
46use gtfs_ingest::bundle;
47use gtfs_ingest::gtfs::{self, Csv};
48use gtfs_ingest::manifest::{parse_feed_spec, read_manifest, FeedSpec};
49use gtfs_ingest::rail::{fallback_color, mode_of, rail_routes, shape_ids_by_route};
50use gtfs_ingest::timing::PhaseTimer;
51
52/// How many distinct services may draw over one stretch of track before the rest are dropped.
53///
54/// Four, because that is what the renderer can show: `Layer::lane_offset_px` clamps the drawn
55/// lanes to the style's `lanes` ramp, which tops out at 4 at z13. A fifth service over the same
56/// track gets squashed onto a lane it shares with another and adds nothing but over-draw.
57///
58/// The cap exists because the dedup gates above it are colour-scoped on purpose — two services
59/// sharing a track are two real services and both should draw. That reasoning holds for one city
60/// and fails for a planet, where one alignment is republished by a city feed, the regional feed
61/// containing it and a national feed on top, each under its own `route_color` and often its own
62/// `route_type`. Fifteen lines over one railway is not fifteen services; it is one service seen
63/// fifteen times.
64const MAX_SERVICES_PER_TRACK: usize = 4;
65
66/// How much of a line must already be drawn in its colour for it to count as a duplicate.
67///
68/// Not 100%, which is what "is this line already drawn" used to mean. A route published twice at
69/// slightly different lengths — a short-turn, or one feed running two stops further than another —
70/// shares nearly all of its alignment with what is drawn, adds a little new track at one end, and
71/// under an all-or-nothing rule is kept whole. That duplicates the shared 95%: the A line came out
72/// as two strands a metre apart, each fanned into its own corridor lane and tapered, so one line
73/// read as two diverging and reconverging.
74///
75/// High enough that a genuine branch survives. A route sharing a trunk and then diverging is well
76/// under this — the branch is the point of it — while a re-publication with a couple of extra
77/// stops is well over.
78const MOSTLY_DRAWN: f64 = 0.95;
79use std::collections::{BTreeMap, HashSet};
80use std::io::{BufWriter, Write};
81use std::path::{Path, PathBuf};
82use std::process::ExitCode;
83use std::sync::atomic::{AtomicUsize, Ordering};
84use std::sync::Mutex;
85
86fn main() -> ExitCode {
87 let mut args: Vec<String> = std::env::args().collect();
88 // `--threads N` anywhere, taken out before the positional parse. It and `MAPS_THREADS`
89 // size every pool this tool runs; neither changes a byte of the output.
90 if let Some(at) = args.iter().position(|a| a == "--threads") {
91 let Some(value) = args.get(at + 1).cloned() else {
92 eprintln!("ERROR: transit_shapes: --threads requires a count");
93 return ExitCode::from(2);
94 };
95 match gtfs_ingest::par::parse_threads(&value) {
96 Ok(n) => gtfs_ingest::par::set_threads(n),
97 Err(e) => {
98 eprintln!("ERROR: transit_shapes: {e}");
99 return ExitCode::from(2);
100 }
101 }
102 args.drain(at..at + 2);
103 }
104 // One pool for every rayon call in the run, sized by the thread budget rather than by
105 // the whole box, so `--threads` / `MAPS_THREADS` govern the parallel sorts and maps too.
106 let pool = match rayon::ThreadPoolBuilder::new()
107 .num_threads(gtfs_ingest::par::threads())
108 .thread_name(|i| format!("transit_shapes-{i}"))
109 .build()
110 {
111 Ok(p) => p,
112 Err(e) => {
113 eprintln!("ERROR: transit_shapes: cannot start the thread pool: {e}");
114 return ExitCode::FAILURE;
115 }
116 };
117 pool.install(|| run_main(args))
118}
119
120fn run_main(args: Vec<String>) -> ExitCode {
121 if args.len() >= 2 && (args[1] == "-h" || args[1] == "--help") {
122 usage();
123 return ExitCode::SUCCESS;
124 }
125 if args.len() < 3 {
126 usage();
127 return ExitCode::from(2);
128 }
129 let out = PathBuf::from(&args[1]);
130
131 let mut timer = PhaseTimer::start("transit");
132 timer.switch("manifest-resolve");
133
134 // A built pack stands in for the raw feeds it was made from.
135 if args[2] == "--pack" {
136 let Some(file) = args.get(3) else {
137 eprintln!("ERROR: transit_shapes: --pack requires a world.transit path");
138 return ExitCode::from(2);
139 };
140 return match extra2::run_with_timer(
141 &out,
142 extra2::Inputs::Pack(Path::new(file)),
143 Some(timer),
144 ) {
145 Ok(()) => ExitCode::SUCCESS,
146 Err(e) => {
147 eprintln!("ERROR: transit_shapes: {e}");
148 ExitCode::FAILURE
149 }
150 };
151 }
152
153 let specs: Vec<FeedSpec> = if args[2] == "--manifest" {
154 let Some(file) = args.get(3) else {
155 eprintln!("ERROR: transit_shapes: --manifest requires a file path");
156 return ExitCode::from(2);
157 };
158 match read_manifest(Path::new(file)) {
159 Ok(v) => v,
160 Err(e) => {
161 eprintln!("ERROR: transit_shapes: {e}");
162 return ExitCode::FAILURE;
163 }
164 }
165 } else {
166 args[2..].iter().map(|s| parse_feed_spec(s)).collect()
167 };
168
169 if specs.is_empty() {
170 eprintln!("ERROR: transit_shapes: no feeds given");
171 usage();
172 return ExitCode::from(2);
173 }
174
175 match extra2::run_with_timer(&out, extra2::Inputs::Feeds(&specs), Some(timer)) {
176 Ok(()) => ExitCode::SUCCESS,
177 Err(e) => {
178 eprintln!("ERROR: transit_shapes: {e}");
179 ExitCode::FAILURE
180 }
181 }
182}
183
184fn usage() {
185 eprintln!("usage: transit_shapes <out.geojsonseq> <feed>...");
186 eprintln!(" transit_shapes <out.geojsonseq> --manifest FILE");
187 eprintln!(" transit_shapes <out.geojsonseq> --pack world.transit");
188 eprintln!(" <feed> = feed_name=gtfs_dir[=motis_prefix] | gtfs_dir");
189}
190
191/// One emitted polyline.
192#[derive(Clone)]
193struct Line {
194 /// The shape's points in `shape_pt_sequence` order, as `(lat_e7, lon_e7)`.
195 points: Vec<(i32, i32)>,
196 /// `0xRRGGBB`, never zero — zero means "no colour" on the wire and
197 /// `Sink::push_transit` refuses it.
198 color: u32,
199 mode: &'static str,
200 /// True when `color` is this mode's fallback rather than the agency's.
201 fallback: bool,
202 /// `route_short_name` or, failing that, `route_long_name`. The order within a
203 /// bundle is the colour and then this, and the tiler reads neither.
204 route: String,
205 /// Feed name and `route_id`, which is what makes a route one route across the
206 /// branches and short-turns it publishes. Never emitted.
207 route_key: String,
208 /// This colour's index among its corridor's distinct colours. See [`bundle`].
209 ordinal: u8,
210 /// How many distinct colours that corridor carries. One outside a corridor.
211 lanes: u8,
212 /// How far into its lane this piece sits, over 255. See [`bundle`].
213 taper: u8,
214 /// Long-distance rail, carried from country zoom. See [`intercity`].
215 intercity: bool,
216}
217
218/// What one feed contributes, before the cross-feed passes.
219#[derive(Default)]
220struct FeedLines {
221 lines: Vec<Line>,
222 routes_kept: usize,
223 routes_without_shape: usize,
224 /// Distinct usable `shape_id`s seen.
225 shapes_read: usize,
226}
227
228/// A content hash of one polyline, for dedup.
229///
230/// Rounded to e6 — about 0.1 m — so that two feeds publishing the same alignment
231/// with the last digit differing still collapse to one line. FNV-1a over the
232/// rounded pairs rather than the coordinates themselves: a world feed set is
233/// millions of polylines and holding every one of them as a key would cost more
234/// than the layer does. Sixty-four bits over that many lines is a collision
235/// chance around one in ten million, against heavy visible over-draw if the
236/// dedup is skipped.
237///
238/// Exact after rounding, and so direction-sensitive. The near-match that
239/// collapses a route's two directions is [`bundle::same_line`]; this is the
240/// cheap cross-feed pass that runs over every line in the set.
241fn polyline_hash(points: &[(i32, i32)]) -> u64 {
242 let mut h = 0xcbf2_9ce4_8422_2325u64;
243 let mut eat = |v: i32| {
244 for b in v.to_le_bytes() {
245 h ^= b as u64;
246 h = h.wrapping_mul(0x100_0000_01b3);
247 }
248 };
249 for (lat, lon) in points {
250 eat(lat.div_euclid(10));
251 eat(lon.div_euclid(10));
252 }
253 h
254}
255
256/// Read one feed and reduce it to candidate lines.
257fn read_feed(spec: &FeedSpec) -> Result<FeedLines, String> {
258 let (name, dir, _) = spec;
259 // Shapes are the only thing this layer draws, so a feed without a usable shapes.txt
260 // contributes nothing — decided first, before the (often multi-GB) routes.txt and
261 // trips.txt are touched. A national feed with no shapes.txt still carries a huge
262 // routes/trips/stop_times, and reading those only to return empty is what stalled the
263 // chunk barrier on mega-feeds like gb_great_britain while the other cores idled.
264 let Some(shapes) = gtfs::read_shapes(dir) else {
265 // Optional in GTFS, and a feed without it can still route — it just draws
266 // nothing. Not an error, or one bus-only agency would fail a whole region.
267 eprintln!(
268 "WARN: transit_shapes: feed '{name}' has no usable shapes.txt, so it draws no lines"
269 );
270 return Ok(FeedLines::default());
271 };
272 let require = |file: &str| -> Result<Csv, String> {
273 gtfs::read_table(dir, file).ok_or_else(|| {
274 format!("feed '{name}' ({}) missing required GTFS file: {file}", dir.display())
275 })
276 };
277 let routes_csv = require("routes.txt")?;
278 let trips_csv = require("trips.txt")?;
279
280 let rail = rail_routes(&routes_csv);
281 let by_route = shape_ids_by_route(&trips_csv, &rail);
282
283 let mut out = FeedLines { routes_kept: rail.len(), ..FeedLines::default() };
284 for (route_id, shape_ids) in &by_route {
285 let (mode, color, fallback, route, route_type) = &rail[route_id.as_str()];
286 let before = out.lines.len();
287 // Every distinct shape, whole. What a route publishes is one alignment per
288 // direction plus a short-turn or a branch variant or two, all of them overlapping,
289 // and sorting that out is not a per-route job: the same track is published again by
290 // every other feed that covers the city. `run` subtracts them all at once.
291 for shape_id in shape_ids {
292 let Some(shape) = shapes.get(shape_id.as_str()) else { continue };
293 // Two points at minimum, or it is not a line.
294 if shape.lat_e7.len() < 2 {
295 continue;
296 }
297 out.shapes_read += 1;
298 let points: Vec<(i32, i32)> =
299 shape.lat_e7.iter().zip(&shape.lon_e7).map(|(&lat, &lon)| (lat, lon)).collect();
300 out.lines.push(Line {
301 intercity: intercity::is_intercity(
302 intercity::is_long_distance_type(*route_type),
303 &points,
304 ),
305 points,
306 color: *color,
307 mode,
308 fallback: *fallback,
309 route: route.clone(),
310 route_key: format!("{name}\u{0}{route_id}"),
311 ordinal: 0,
312 lanes: 1,
313 taper: 255,
314 });
315 }
316 if out.lines.len() == before {
317 out.routes_without_shape += 1;
318 }
319 }
320 // A rail route no trip references at all never reaches the loop above.
321 out.routes_without_shape += rail.len() - by_route.len();
322 Ok(out)
323}
324
325/// Cut every line at its corridor boundaries and give each piece its lane, so one line in
326/// becomes several out — the stretch before a corridor on its own geometry, the stretch
327/// inside it on the corridor's reference geometry at its lane, and a taper between. Returns
328/// how many pieces came out offset into a corridor.
329fn expand_corridor_spans(lines: &mut Vec<Line>, timer: Option<&mut PhaseTimer>) -> usize {
330 // A route is a route across every branch and short-turn it publishes, so all of
331 // them take one lane. `BTreeMap` and first-seen ids, because a `HashMap`'s order
332 // would decide the lanes and the output has to be byte-identical between runs.
333 let mut ids: BTreeMap<&str, u32> = BTreeMap::new();
334 let mut routes: Vec<u32> = Vec::with_capacity(lines.len());
335 for line in lines.iter() {
336 let next = ids.len() as u32;
337 routes.push(*ids.entry(line.route_key.as_str()).or_insert(next));
338 }
339 let spans = {
340 let candidates: Vec<bundle::Candidate> = lines
341 .iter()
342 .zip(&routes)
343 .map(|(line, route)| bundle::Candidate {
344 points: &line.points,
345 route: *route,
346 color: line.color,
347 name: &line.route,
348 })
349 .collect();
350 bundle::assign_with_timer(&candidates, timer)
351 };
352 let mut bundled = 0usize;
353 let mut out: Vec<Line> = Vec::with_capacity(lines.len());
354 for (line, spans) in lines.drain(..).zip(spans) {
355 for span in spans {
356 // A cut can leave nothing between its two ends, and two points at minimum is
357 // what makes a line.
358 if span.points.len() < 2 {
359 continue;
360 }
361 if span.lanes > 1 {
362 bundled += 1;
363 }
364 out.push(Line {
365 points: span.points,
366 ordinal: span.ordinal,
367 lanes: span.lanes,
368 taper: span.taper,
369 ..line.clone()
370 });
371 }
372 }
373 *lines = out;
374 bundled
375}
376
377fn io_err(e: impl std::fmt::Display) -> String {
378 format!("write failed: {e}")
379}
380
381/// Escape a name for a JSON string. UTF-8 bytes pass through verbatim; only the
382/// JSON-mandatory escapes and C0 controls are rewritten. Mirrors
383/// `transit_stops`' escaper so both layers quote identically.
384fn json_escape(s: &[u8], out: &mut Vec<u8>) {
385 for &b in s {
386 match b {
387 b'"' => out.extend_from_slice(b"\\\""),
388 b'\\' => out.extend_from_slice(b"\\\\"),
389 b'\n' => out.extend_from_slice(b"\\n"),
390 b'\r' => out.extend_from_slice(b"\\r"),
391 b'\t' => out.extend_from_slice(b"\\t"),
392 0x00..=0x1f => {
393 out.extend_from_slice(format!("\\u{:04x}", b).as_bytes());
394 }
395 _ => out.push(b),
396 }
397 }
398}