Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / gtfs_ingest / src / bin / transit_shapes.rs
transit_shapes.rs361 lines · 14.6 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"] |
| 34 | mod extra2; |
| 35 | |
| 36 | #[path = "transit_shapes_intercity.rs"] |
| 37 | mod intercity; |
| 38 | |
| 39 | #[path = "transit_shapes_pack.rs"] |
| 40 | mod pack; |
| 41 | |
| 42 | #[path = "transit_shapes_extra.rs"] |
| 43 | #[cfg(test)] |
| 44 | mod extra; |
| 45 | |
| 46 | use gtfs_ingest::bundle; |
| 47 | use gtfs_ingest::gtfs::{self, Csv}; |
| 48 | use gtfs_ingest::rail::{fallback_color, mode_of, rail_routes, shape_ids_by_route}; |
| 49 | use gtfs_ingest::manifest::{parse_feed_spec, read_manifest, FeedSpec}; |
| 50 | use 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. |
| 64 | const 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. |
| 78 | const MOSTLY_DRAWN: f64 = 0.95; |
| 79 | use std::collections::{BTreeMap, HashSet}; |
| 80 | use std::io::{BufWriter, Write}; |
| 81 | use std::path::{Path, PathBuf}; |
| 82 | use std::process::ExitCode; |
| 83 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 84 | use std::sync::Mutex; |
| 85 | |
| 86 | fn main() -> ExitCode { |
| 87 | let args: Vec<String> = std::env::args().collect(); |
| 88 | if args.len() >= 2 && (args[1] == "-h" || args[1] == "--help") { |
| 89 | usage(); |
| 90 | return ExitCode::SUCCESS; |
| 91 | } |
| 92 | if args.len() < 3 { |
| 93 | usage(); |
| 94 | return ExitCode::from(2); |
| 95 | } |
| 96 | let out = PathBuf::from(&args[1]); |
| 97 | |
| 98 | let mut timer = PhaseTimer::start("transit"); |
| 99 | timer.switch("manifest-resolve"); |
| 100 | |
| 101 | // A built pack stands in for the raw feeds it was made from. |
| 102 | if args[2] == "--pack" { |
| 103 | let Some(file) = args.get(3) else { |
| 104 | eprintln!("ERROR: transit_shapes: --pack requires a world.transit path"); |
| 105 | return ExitCode::from(2); |
| 106 | }; |
| 107 | return match extra2::run_with_timer(&out, extra2::Inputs::Pack(Path::new(file)), Some(timer)) { |
| 108 | Ok(()) => ExitCode::SUCCESS, |
| 109 | Err(e) => { |
| 110 | eprintln!("ERROR: transit_shapes: {e}"); |
| 111 | ExitCode::FAILURE |
| 112 | } |
| 113 | }; |
| 114 | } |
| 115 | |
| 116 | let specs: Vec<FeedSpec> = if args[2] == "--manifest" { |
| 117 | let Some(file) = args.get(3) else { |
| 118 | eprintln!("ERROR: transit_shapes: --manifest requires a file path"); |
| 119 | return ExitCode::from(2); |
| 120 | }; |
| 121 | match read_manifest(Path::new(file)) { |
| 122 | Ok(v) => v, |
| 123 | Err(e) => { |
| 124 | eprintln!("ERROR: transit_shapes: {e}"); |
| 125 | return ExitCode::FAILURE; |
| 126 | } |
| 127 | } |
| 128 | } else { |
| 129 | args[2..].iter().map(|s| parse_feed_spec(s)).collect() |
| 130 | }; |
| 131 | |
| 132 | if specs.is_empty() { |
| 133 | eprintln!("ERROR: transit_shapes: no feeds given"); |
| 134 | usage(); |
| 135 | return ExitCode::from(2); |
| 136 | } |
| 137 | |
| 138 | match extra2::run_with_timer(&out, extra2::Inputs::Feeds(&specs), Some(timer)) { |
| 139 | Ok(()) => ExitCode::SUCCESS, |
| 140 | Err(e) => { |
| 141 | eprintln!("ERROR: transit_shapes: {e}"); |
| 142 | ExitCode::FAILURE |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | fn usage() { |
| 148 | eprintln!("usage: transit_shapes <out.geojsonseq> <feed>..."); |
| 149 | eprintln!(" transit_shapes <out.geojsonseq> --manifest FILE"); |
| 150 | eprintln!(" transit_shapes <out.geojsonseq> --pack world.transit"); |
| 151 | eprintln!(" <feed> = feed_name=gtfs_dir[=motis_prefix] | gtfs_dir"); |
| 152 | } |
| 153 | |
| 154 | /// One emitted polyline. |
| 155 | #[derive(Clone)] |
| 156 | struct Line { |
| 157 | /// The shape's points in `shape_pt_sequence` order, as `(lat_e7, lon_e7)`. |
| 158 | points: Vec<(i32, i32)>, |
| 159 | /// `0xRRGGBB`, never zero — zero means "no colour" on the wire and |
| 160 | /// `Sink::push_transit` refuses it. |
| 161 | color: u32, |
| 162 | mode: &'static str, |
| 163 | /// True when `color` is this mode's fallback rather than the agency's. |
| 164 | fallback: bool, |
| 165 | /// `route_short_name` or, failing that, `route_long_name`. The order within a |
| 166 | /// bundle is the colour and then this, and the tiler reads neither. |
| 167 | route: String, |
| 168 | /// Feed name and `route_id`, which is what makes a route one route across the |
| 169 | /// branches and short-turns it publishes. Never emitted. |
| 170 | route_key: String, |
| 171 | /// This colour's index among its corridor's distinct colours. See [`bundle`]. |
| 172 | ordinal: u8, |
| 173 | /// How many distinct colours that corridor carries. One outside a corridor. |
| 174 | lanes: u8, |
| 175 | /// How far into its lane this piece sits, over 255. See [`bundle`]. |
| 176 | taper: u8, |
| 177 | /// Long-distance rail, carried from country zoom. See [`intercity`]. |
| 178 | intercity: bool, |
| 179 | } |
| 180 | |
| 181 | /// What one feed contributes, before the cross-feed passes. |
| 182 | #[derive(Default)] |
| 183 | struct FeedLines { |
| 184 | lines: Vec<Line>, |
| 185 | routes_kept: usize, |
| 186 | routes_without_shape: usize, |
| 187 | /// Distinct usable `shape_id`s seen. |
| 188 | shapes_read: usize, |
| 189 | } |
| 190 | |
| 191 | /// A content hash of one polyline, for dedup. |
| 192 | /// |
| 193 | /// Rounded to e6 — about 0.1 m — so that two feeds publishing the same alignment |
| 194 | /// with the last digit differing still collapse to one line. FNV-1a over the |
| 195 | /// rounded pairs rather than the coordinates themselves: a world feed set is |
| 196 | /// millions of polylines and holding every one of them as a key would cost more |
| 197 | /// than the layer does. Sixty-four bits over that many lines is a collision |
| 198 | /// chance around one in ten million, against heavy visible over-draw if the |
| 199 | /// dedup is skipped. |
| 200 | /// |
| 201 | /// Exact after rounding, and so direction-sensitive. The near-match that |
| 202 | /// collapses a route's two directions is [`bundle::same_line`]; this is the |
| 203 | /// cheap cross-feed pass that runs over every line in the set. |
| 204 | fn polyline_hash(points: &[(i32, i32)]) -> u64 { |
| 205 | let mut h = 0xcbf2_9ce4_8422_2325u64; |
| 206 | let mut eat = |v: i32| { |
| 207 | for b in v.to_le_bytes() { |
| 208 | h ^= b as u64; |
| 209 | h = h.wrapping_mul(0x100_0000_01b3); |
| 210 | } |
| 211 | }; |
| 212 | for (lat, lon) in points { |
| 213 | eat(lat.div_euclid(10)); |
| 214 | eat(lon.div_euclid(10)); |
| 215 | } |
| 216 | h |
| 217 | } |
| 218 | |
| 219 | /// Read one feed and reduce it to candidate lines. |
| 220 | fn read_feed(spec: &FeedSpec) -> Result<FeedLines, String> { |
| 221 | let (name, dir, _) = spec; |
| 222 | // Shapes are the only thing this layer draws, so a feed without a usable shapes.txt |
| 223 | // contributes nothing — decided first, before the (often multi-GB) routes.txt and |
| 224 | // trips.txt are touched. A national feed with no shapes.txt still carries a huge |
| 225 | // routes/trips/stop_times, and reading those only to return empty is what stalled the |
| 226 | // chunk barrier on mega-feeds like gb_great_britain while the other cores idled. |
| 227 | let Some(shapes) = gtfs::read_shapes(dir) else { |
| 228 | // Optional in GTFS, and a feed without it can still route — it just draws |
| 229 | // nothing. Not an error, or one bus-only agency would fail a whole region. |
| 230 | eprintln!( |
| 231 | "WARN: transit_shapes: feed '{name}' has no usable shapes.txt, so it draws no lines" |
| 232 | ); |
| 233 | return Ok(FeedLines::default()); |
| 234 | }; |
| 235 | let require = |file: &str| -> Result<Csv, String> { |
| 236 | gtfs::read_table(dir, file).ok_or_else(|| { |
| 237 | format!("feed '{name}' ({}) missing required GTFS file: {file}", dir.display()) |
| 238 | }) |
| 239 | }; |
| 240 | let routes_csv = require("routes.txt")?; |
| 241 | let trips_csv = require("trips.txt")?; |
| 242 | |
| 243 | let rail = rail_routes(&routes_csv); |
| 244 | let by_route = shape_ids_by_route(&trips_csv, &rail); |
| 245 | |
| 246 | let mut out = FeedLines { routes_kept: rail.len(), ..FeedLines::default() }; |
| 247 | for (route_id, shape_ids) in &by_route { |
| 248 | let (mode, color, fallback, route, route_type) = &rail[route_id.as_str()]; |
| 249 | let before = out.lines.len(); |
| 250 | // Every distinct shape, whole. What a route publishes is one alignment per |
| 251 | // direction plus a short-turn or a branch variant or two, all of them overlapping, |
| 252 | // and sorting that out is not a per-route job: the same track is published again by |
| 253 | // every other feed that covers the city. `run` subtracts them all at once. |
| 254 | for shape_id in shape_ids { |
| 255 | let Some(shape) = shapes.get(shape_id.as_str()) else { continue }; |
| 256 | // Two points at minimum, or it is not a line. |
| 257 | if shape.lat_e7.len() < 2 { |
| 258 | continue; |
| 259 | } |
| 260 | out.shapes_read += 1; |
| 261 | let points: Vec<(i32, i32)> = |
| 262 | shape.lat_e7.iter().zip(&shape.lon_e7).map(|(&lat, &lon)| (lat, lon)).collect(); |
| 263 | out.lines.push(Line { |
| 264 | intercity: intercity::is_intercity(intercity::is_long_distance_type(*route_type), &points), |
| 265 | points, |
| 266 | color: *color, |
| 267 | mode, |
| 268 | fallback: *fallback, |
| 269 | route: route.clone(), |
| 270 | route_key: format!("{name}\u{0}{route_id}"), |
| 271 | ordinal: 0, |
| 272 | lanes: 1, |
| 273 | taper: 255, |
| 274 | }); |
| 275 | } |
| 276 | if out.lines.len() == before { |
| 277 | out.routes_without_shape += 1; |
| 278 | } |
| 279 | } |
| 280 | // A rail route no trip references at all never reaches the loop above. |
| 281 | out.routes_without_shape += rail.len() - by_route.len(); |
| 282 | Ok(out) |
| 283 | } |
| 284 | |
| 285 | /// Cut every line at its corridor boundaries and give each piece its lane, so one line in |
| 286 | /// becomes several out — the stretch before a corridor on its own geometry, the stretch |
| 287 | /// inside it on the corridor's reference geometry at its lane, and a taper between. Returns |
| 288 | /// how many pieces came out offset into a corridor. |
| 289 | fn expand_corridor_spans( |
| 290 | lines: &mut Vec<Line>, |
| 291 | timer: Option<&mut PhaseTimer>, |
| 292 | ) -> usize { |
| 293 | // A route is a route across every branch and short-turn it publishes, so all of |
| 294 | // them take one lane. `BTreeMap` and first-seen ids, because a `HashMap`'s order |
| 295 | // would decide the lanes and the output has to be byte-identical between runs. |
| 296 | let mut ids: BTreeMap<&str, u32> = BTreeMap::new(); |
| 297 | let mut routes: Vec<u32> = Vec::with_capacity(lines.len()); |
| 298 | for line in lines.iter() { |
| 299 | let next = ids.len() as u32; |
| 300 | routes.push(*ids.entry(line.route_key.as_str()).or_insert(next)); |
| 301 | } |
| 302 | let spans = { |
| 303 | let candidates: Vec<bundle::Candidate> = lines |
| 304 | .iter() |
| 305 | .zip(&routes) |
| 306 | .map(|(line, route)| bundle::Candidate { |
| 307 | points: &line.points, |
| 308 | route: *route, |
| 309 | color: line.color, |
| 310 | name: &line.route, |
| 311 | }) |
| 312 | .collect(); |
| 313 | bundle::assign_with_timer(&candidates, timer) |
| 314 | }; |
| 315 | let mut bundled = 0usize; |
| 316 | let mut out: Vec<Line> = Vec::with_capacity(lines.len()); |
| 317 | for (line, spans) in lines.drain(..).zip(spans) { |
| 318 | for span in spans { |
| 319 | // A cut can leave nothing between its two ends, and two points at minimum is |
| 320 | // what makes a line. |
| 321 | if span.points.len() < 2 { |
| 322 | continue; |
| 323 | } |
| 324 | if span.lanes > 1 { |
| 325 | bundled += 1; |
| 326 | } |
| 327 | out.push(Line { |
| 328 | points: span.points, |
| 329 | ordinal: span.ordinal, |
| 330 | lanes: span.lanes, |
| 331 | taper: span.taper, |
| 332 | ..line.clone() |
| 333 | }); |
| 334 | } |
| 335 | } |
| 336 | *lines = out; |
| 337 | bundled |
| 338 | } |
| 339 | |
| 340 | fn io_err(e: impl std::fmt::Display) -> String { |
| 341 | format!("write failed: {e}") |
| 342 | } |
| 343 | |
| 344 | /// Escape a name for a JSON string. UTF-8 bytes pass through verbatim; only the |
| 345 | /// JSON-mandatory escapes and C0 controls are rewritten. Mirrors |
| 346 | /// `transit_stops`' escaper so both layers quote identically. |
| 347 | fn json_escape(s: &[u8], out: &mut Vec<u8>) { |
| 348 | for &b in s { |
| 349 | match b { |
| 350 | b'"' => out.extend_from_slice(b"\\\""), |
| 351 | b'\\' => out.extend_from_slice(b"\\\\"), |
| 352 | b'\n' => out.extend_from_slice(b"\\n"), |
| 353 | b'\r' => out.extend_from_slice(b"\\r"), |
| 354 | b'\t' => out.extend_from_slice(b"\\t"), |
| 355 | 0x00..=0x1f => { |
| 356 | out.extend_from_slice(format!("\\u{:04x}", b).as_bytes()); |
| 357 | } |
| 358 | _ => out.push(b), |
| 359 | } |
| 360 | } |
| 361 | } |