//! `transit`: coloured rail lines, and the one layer whose data is not in the `.osm.pbf` at all. //! //! A transit line is a **GTFS shape**: one polyline out of an agency's own `shapes.txt`, carrying //! the official `route_color` out of its `routes.txt`. `scripts/maps/gtfs_ingest`'s `transit_shapes` //! binary turns a set of feeds into a `.geojsonseq` of them, and [`stream_routes`] reads that file //! the way [`crate::schema::landtype::stream_prepared`] reads a prepared land polygon. The rail track //! itself stays on the `roads` layer as the grey dashed casing from the reference style's //! `roads_rail`, so the coloured line draws over neutral track exactly like a metro map. //! # Why not OSM route relations //! //! It used to be exactly that: a `type=route` relation's member ways, coloured by the relation's //! `colour=` tag or a per-mode guess. Both halves were wrong. A relation's members include its //! **platforms**, and the member role is not in scope where the colour is assigned, so every //! platform way came out as a wide coloured band beside the track. And a guessed colour is a guess //! — GTFS has the agency's answer, so the layer takes it. //! //! The trade is coverage: anywhere with no feed in the built region loses lines it had from OSM, //! and an agency-supplied shape does not sit exactly on OSM's rail casing. //! //! # Stations //! //! Stations stay on the `poi` layer as kind `station` (task 50), but with a `kind_detail` //! naming the station mode — which is what makes them identifiable as *transit* stations when //! the POI toggle is off. That half is still a tag query over the `.osm.pbf`. See //! [`station_detail`]; its `station` tag reaches the pre-screen through `poi`'s own `FILTERS`. use std::path::Path; use osm_ingest::proto::{err, Result}; use tile_build::geom::Geometry; use tile_build::progress::Progress; use tilecodec::mamaps::dict::LAYER_TRANSIT; use tilecodec::mvt::Value; use super::{detail, kind, Class, TagSource}; /// The modes this layer carries. /// /// **A matched pair with `gtfs_ingest`'s `transit_shapes`**, which maps GTFS `route_type` onto /// these five names and carries the fallback colour for each. The two crates cannot share code, so /// a name added here has to be added there or nothing will ever be classified into it. const MODES: &[&str] = &["subway", "light_rail", "tram", "train", "monorail"]; /// The zoom every transit line surfaces at, whatever its mode. /// /// One floor rather than [`crate::schema::roads`]' per-mode ladder, because a transit layer is a /// **network** and half a network is worse than none: trunk rail at z8 with the metro withheld /// until z12 draws a city as though it had no metro. The zoom that matters is the one where the /// whole network first reads, and that is the trunk's. const MIN_ZOOM: u8 = 8; /// The zoom long-distance rail surfaces at. /// /// The one exception to the single floor: an Amtrak or VIA line is the network at country zoom, /// where nothing else on this layer would read. `transit_shapes` marks these lines `intercity`. const INTERCITY_MIN_ZOOM: u8 = 3; /// A transit line's class: layer `transit`, kind `rail`, detail naming the mode. /// /// The kind stays `rail` (what the reference style's `roads_rail` matches) while the detail /// distinguishes a subway from a tram — which is what lets the renderer vary width by mode /// while keying colour off `transit_color`. An intercity line's detail is `intercity` rather /// than its mode, which is what the style's country-zoom `transit-intercity` filters on. pub fn transit_class(mode: &str, intercity: bool) -> Option { if !MODES.contains(&mode) { return None; } Some(Class { layer: LAYER_TRANSIT, kind: kind("rail"), kind_detail: detail(if intercity { "intercity" } else { mode }), flags: 0, area: false, min_zoom: if intercity { INTERCITY_MIN_ZOOM } else { MIN_ZOOM }, min_area_px: 0.0, }) } /// Stream a prepared transit-routes file into the feature sink, clipped to `bbox`. /// /// The `.geojsonseq` `transit_shapes` writes: one `LineString` per rail route, with `color` /// (`RRGGBB`), `mode`, `ordinal`, `lanes` and `taper` properties. Modelled on /// [`crate::schema::landtype::stream_prepared`] down to the streaming read and the "this file yielded /// nothing, so you passed the wrong one" error at the end. /// /// Every malformed line is a hard error rather than a skip. The file is written by a tool in this /// repo, so anything this cannot read means the wrong file was handed over — and a transit layer /// that is quietly half a city is the failure mode that took a device pass to notice. The three /// lane properties are the one exception: **absent** ones default to a route on its own alignment /// (`ordinal 0, lanes 1, taper 255`), so a file written before corridors existed still reads. One /// that is present and unreadable is still an error. /// /// `bbox` is `(min_lon, min_lat, max_lon, max_lat)` in degrees and is an intersection test, not a /// clip: a route running out of the extract is drawn to where the tiler cuts it, exactly as an OSM /// way straddling the same edge is. /// /// An empty file (no non-blank lines) yields zero routes rather than an /// error: that is what a `--notransit` build feeds in, and zero feeds means /// an empty transit layer, not a wrong file. A non-empty file with no /// meeting route is still an error below. pub fn stream_routes( path: &Path, bbox: (f64, f64, f64, f64), sink: &mut crate::store::Sink, ) -> Result { let text = std::fs::read_to_string(path) .map_err(|e| osm_ingest::proto::Error(format!("cannot read {}: {e}", path.display())))?; if text.lines().all(|line| line.trim().is_empty()) { println!(" 0 transit route(s): empty routes file, the transit layer is empty"); return Ok(0); } let mut written = 0u64; let mut skipped = 0u64; // File order is feature order and the layer is coalesced, so the push // stays serial; the bar is what keeps a large feed from reading as a // hang. Ticked per line read (not per route kept), so it spans the // whole file even when most of it is outside the extract. let total_lines = text.lines().filter(|line| !line.trim().is_empty()).count(); let mut bar = Progress::new("Transit: routes".to_string(), total_lines, "line(s)", true); for (line_number, line) in text.lines().enumerate() { if line.trim().is_empty() { continue; } bar.tick("line(s)"); let at = |what: &str| { osm_ingest::proto::Error(format!("{}:{}: {what}", path.display(), line_number + 1)) }; let Some(feature) = tile_build::geojson::parse_feature(line) else { return Err(at("not a GeoJSON feature")); }; // Lines only. A prepared transit-routes file has nothing else in it, and a polygon in // there would be a sign the coastline product was passed by mistake. let Geometry::Lines(lines) = feature.geometry else { return Err(at("not a LineString; is this the transit-routes file?")); }; let Some(mode) = prop(&feature.props, "mode") else { return Err(at("no `mode` property")); }; // Absent is an ordinary line, like the lane inputs below; present and not 0/1 is an error. let Some(intercity) = byte_prop(&feature.props, "intercity", 0).filter(|v| *v <= 1) else { return Err(at("an `intercity` property that is not 0 or 1")); }; let Some(class) = transit_class(&mode, intercity == 1) else { return Err(at(&format!("`{mode}` is not a mode this layer carries"))); }; let Some(color) = prop(&feature.props, "color").as_deref().and_then(hex_rrggbb) else { return Err(at("no usable `color` property; it must be non-zero bare RRGGBB hex")); }; let Some(ordinal) = byte_prop(&feature.props, "ordinal", 0) else { return Err(at("an `ordinal` property that is not a whole number in 0..=255")); }; let Some(lanes) = byte_prop(&feature.props, "lanes", 1) else { return Err(at("a `lanes` property that is not a whole number in 0..=255")); }; let Some(taper) = byte_prop(&feature.props, "taper", 255) else { return Err(at("a `taper` property that is not a whole number in 0..=255")); }; for line in lines { if line.len() < 2 || !meets(&line, bbox) { skipped += 1; continue; } sink.push_transit( &class, &crate::store::EncodedGeom::live(&Geometry::Lines(vec![line]))?, color, ordinal, lanes, taper, )?; written += 1; } } if written == 0 { return err(format!( "{} holds no transit route meeting {bbox:?}; is it the right area?", path.display(), )); } bar.finish("line(s)"); println!(" {written} transit route(s) kept, {skipped} outside the extract"); Ok(written) } /// A string-valued property, by name. fn prop(props: &[(String, Value)], name: &str) -> Option { props.iter().find(|(k, _)| k == name).and_then(|(_, v)| match v { Value::String(s) => Some(s.clone()), _ => None, }) } /// One of the lane inputs as a byte. `None` only for a property that is there and unreadable. /// /// Absent is `missing` on purpose: everything else in this reader hard-errors, and falling into /// that path would make a routes file written before corridors existed unreadable rather than /// simply un-fanned. The GeoJSON reader gives a non-negative literal back as a `Uint` and a /// negative one as a `Double`, so every arm is the same number. fn byte_prop(props: &[(String, Value)], name: &str, missing: u8) -> Option { match props.iter().find(|(k, _)| k == name) { None => Some(missing), Some((_, Value::Uint(v))) => u8::try_from(*v).ok(), Some((_, Value::Int(v))) | Some((_, Value::SInt(v))) => u8::try_from(*v).ok(), Some((_, Value::Double(v))) if v.fract() == 0.0 => { (*v >= 0.0 && *v <= u8::MAX as f64).then_some(*v as u8) } Some(_) => None, } } /// A bare `RRGGBB` hex colour as `0xRRGGBB`, or `None`. /// /// Zero is refused: it means "no colour" on the wire and [`crate::store::Sink::push_transit`] /// rejects it, so catching it here names the offending line instead. fn hex_rrggbb(raw: &str) -> Option { let hex = raw.trim(); if hex.len() != 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) { return None; } u32::from_str_radix(hex, 16).ok().filter(|c| *c != 0) } /// Does a polyline meet `bbox`? Intersection, not containment. fn meets(line: &[(f64, f64)], bbox: (f64, f64, f64, f64)) -> bool { let (mut min_x, mut min_y) = (f64::MAX, f64::MAX); let (mut max_x, mut max_y) = (f64::MIN, f64::MIN); for &(x, y) in line { min_x = min_x.min(x); min_y = min_y.min(y); max_x = max_x.max(x); max_y = max_y.max(y); } !(max_x < bbox.0 || min_x > bbox.2 || max_y < bbox.1 || min_y > bbox.3) } /// The station mode for a `poi` station feature's `kind_detail`. /// /// `station=subway/light_rail/tram` name the mode directly; a bare `railway=station` is a /// `station`; a `railway=halt` is a `halt`. This is the tag the renderer reads to show stations /// when Transit is ON even with POIs OFF: `poi` layer, kind `station`, detail naming one of /// these — everything else on the layer is a different kind already. pub fn station_detail(tags: &(impl TagSource + ?Sized)) -> &'static str { match tags.get("station") { Some("subway") => "subway", Some("light_rail") => "light_rail", Some("tram") => "tram", Some("monorail") => "monorail", _ => match tags.get("railway") { Some("halt") => "halt", _ => "station", }, } } include!("transit_s1.rs");