Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / schema / transit.rs
transit.rs255 lines · 11.9 KiBRaw
| 1 | //! `transit`: coloured rail lines, and the one layer whose data is not in the `.osm.pbf` at all. |
| 2 | //! |
| 3 | //! A transit line is a **GTFS shape**: one polyline out of an agency's own `shapes.txt`, carrying |
| 4 | //! the official `route_color` out of its `routes.txt`. `scripts/maps/gtfs_ingest`'s `transit_shapes` |
| 5 | //! binary turns a set of feeds into a `.geojsonseq` of them, and [`stream_routes`] reads that file |
| 6 | //! the way [`crate::schema::landtype::stream_prepared`] reads a prepared land polygon. The rail track |
| 7 | //! itself stays on the `roads` layer as the grey dashed casing from the reference style's |
| 8 | //! `roads_rail`, so the coloured line draws over neutral track exactly like a metro map. |
| 9 | //! # Why not OSM route relations |
| 10 | //! |
| 11 | //! It used to be exactly that: a `type=route` relation's member ways, coloured by the relation's |
| 12 | //! `colour=` tag or a per-mode guess. Both halves were wrong. A relation's members include its |
| 13 | //! **platforms**, and the member role is not in scope where the colour is assigned, so every |
| 14 | //! platform way came out as a wide coloured band beside the track. And a guessed colour is a guess |
| 15 | //! — GTFS has the agency's answer, so the layer takes it. |
| 16 | //! |
| 17 | //! The trade is coverage: anywhere with no feed in the built region loses lines it had from OSM, |
| 18 | //! and an agency-supplied shape does not sit exactly on OSM's rail casing. |
| 19 | //! |
| 20 | //! # Stations |
| 21 | //! |
| 22 | //! Stations stay on the `poi` layer as kind `station` (task 50), but with a `kind_detail` |
| 23 | //! naming the station mode — which is what makes them identifiable as *transit* stations when |
| 24 | //! the POI toggle is off. That half is still a tag query over the `.osm.pbf`. See |
| 25 | //! [`station_detail`]; its `station` tag reaches the pre-screen through `poi`'s own `FILTERS`. |
| 26 | |
| 27 | use std::path::Path; |
| 28 | |
| 29 | use osm_ingest::proto::{err, Result}; |
| 30 | use tile_build::geom::Geometry; |
| 31 | use tile_build::progress::Progress; |
| 32 | use tilecodec::mamaps::dict::LAYER_TRANSIT; |
| 33 | use tilecodec::mvt::Value; |
| 34 | |
| 35 | use super::{detail, kind, Class, TagSource}; |
| 36 | |
| 37 | /// The modes this layer carries. |
| 38 | /// |
| 39 | /// **A matched pair with `gtfs_ingest`'s `transit_shapes`**, which maps GTFS `route_type` onto |
| 40 | /// these five names and carries the fallback colour for each. The two crates cannot share code, so |
| 41 | /// a name added here has to be added there or nothing will ever be classified into it. |
| 42 | const MODES: &[&str] = &["subway", "light_rail", "tram", "train", "monorail"]; |
| 43 | |
| 44 | /// The zoom every transit line surfaces at, whatever its mode. |
| 45 | /// |
| 46 | /// One floor rather than [`crate::schema::roads`]' per-mode ladder, because a transit layer is a |
| 47 | /// **network** and half a network is worse than none: trunk rail at z8 with the metro withheld |
| 48 | /// until z12 draws a city as though it had no metro. The zoom that matters is the one where the |
| 49 | /// whole network first reads, and that is the trunk's. |
| 50 | const MIN_ZOOM: u8 = 8; |
| 51 | |
| 52 | /// The zoom long-distance rail surfaces at. |
| 53 | /// |
| 54 | /// The one exception to the single floor: an Amtrak or VIA line is the network at country zoom, |
| 55 | /// where nothing else on this layer would read. `transit_shapes` marks these lines `intercity`. |
| 56 | const INTERCITY_MIN_ZOOM: u8 = 3; |
| 57 | |
| 58 | /// A transit line's class: layer `transit`, kind `rail`, detail naming the mode. |
| 59 | /// |
| 60 | /// The kind stays `rail` (what the reference style's `roads_rail` matches) while the detail |
| 61 | /// distinguishes a subway from a tram — which is what lets the renderer vary width by mode |
| 62 | /// while keying colour off `transit_color`. An intercity line's detail is `intercity` rather |
| 63 | /// than its mode, which is what the style's country-zoom `transit-intercity` filters on. |
| 64 | pub fn transit_class(mode: &str, intercity: bool) -> Option<Class> { |
| 65 | if !MODES.contains(&mode) { |
| 66 | return None; |
| 67 | } |
| 68 | Some(Class { |
| 69 | layer: LAYER_TRANSIT, |
| 70 | kind: kind("rail"), |
| 71 | kind_detail: detail(if intercity { "intercity" } else { mode }), |
| 72 | flags: 0, |
| 73 | area: false, |
| 74 | min_zoom: if intercity { INTERCITY_MIN_ZOOM } else { MIN_ZOOM }, |
| 75 | min_area_px: 0.0, |
| 76 | }) |
| 77 | } |
| 78 | |
| 79 | /// Stream a prepared transit-routes file into the feature sink, clipped to `bbox`. |
| 80 | /// |
| 81 | /// The `.geojsonseq` `transit_shapes` writes: one `LineString` per rail route, with `color` |
| 82 | /// (`RRGGBB`), `mode`, `ordinal`, `lanes` and `taper` properties. Modelled on |
| 83 | /// [`crate::schema::landtype::stream_prepared`] down to the streaming read and the "this file yielded |
| 84 | /// nothing, so you passed the wrong one" error at the end. |
| 85 | /// |
| 86 | /// Every malformed line is a hard error rather than a skip. The file is written by a tool in this |
| 87 | /// repo, so anything this cannot read means the wrong file was handed over — and a transit layer |
| 88 | /// that is quietly half a city is the failure mode that took a device pass to notice. The three |
| 89 | /// lane properties are the one exception: **absent** ones default to a route on its own alignment |
| 90 | /// (`ordinal 0, lanes 1, taper 255`), so a file written before corridors existed still reads. One |
| 91 | /// that is present and unreadable is still an error. |
| 92 | /// |
| 93 | /// `bbox` is `(min_lon, min_lat, max_lon, max_lat)` in degrees and is an intersection test, not a |
| 94 | /// clip: a route running out of the extract is drawn to where the tiler cuts it, exactly as an OSM |
| 95 | /// way straddling the same edge is. |
| 96 | /// |
| 97 | /// An empty file (no non-blank lines) yields zero routes rather than an |
| 98 | /// error: that is what a `--notransit` build feeds in, and zero feeds means |
| 99 | /// an empty transit layer, not a wrong file. A non-empty file with no |
| 100 | /// meeting route is still an error below. |
| 101 | pub fn stream_routes( |
| 102 | path: &Path, |
| 103 | bbox: (f64, f64, f64, f64), |
| 104 | sink: &mut crate::store::Sink, |
| 105 | ) -> Result<u64> { |
| 106 | let text = std::fs::read_to_string(path) |
| 107 | .map_err(|e| osm_ingest::proto::Error(format!("cannot read {}: {e}", path.display())))?; |
| 108 | if text.lines().all(|line| line.trim().is_empty()) { |
| 109 | println!(" 0 transit route(s): empty routes file, the transit layer is empty"); |
| 110 | return Ok(0); |
| 111 | } |
| 112 | let mut written = 0u64; |
| 113 | let mut skipped = 0u64; |
| 114 | // File order is feature order and the layer is coalesced, so the push |
| 115 | // stays serial; the bar is what keeps a large feed from reading as a |
| 116 | // hang. Ticked per line read (not per route kept), so it spans the |
| 117 | // whole file even when most of it is outside the extract. |
| 118 | let total_lines = text.lines().filter(|line| !line.trim().is_empty()).count(); |
| 119 | let mut bar = Progress::new("Transit: routes".to_string(), total_lines, "line(s)", true); |
| 120 | for (line_number, line) in text.lines().enumerate() { |
| 121 | if line.trim().is_empty() { |
| 122 | continue; |
| 123 | } |
| 124 | bar.tick("line(s)"); |
| 125 | let at = |what: &str| { |
| 126 | osm_ingest::proto::Error(format!("{}:{}: {what}", path.display(), line_number + 1)) |
| 127 | }; |
| 128 | let Some(feature) = tile_build::geojson::parse_feature(line) else { |
| 129 | return Err(at("not a GeoJSON feature")); |
| 130 | }; |
| 131 | // Lines only. A prepared transit-routes file has nothing else in it, and a polygon in |
| 132 | // there would be a sign the coastline product was passed by mistake. |
| 133 | let Geometry::Lines(lines) = feature.geometry else { |
| 134 | return Err(at("not a LineString; is this the transit-routes file?")); |
| 135 | }; |
| 136 | let Some(mode) = prop(&feature.props, "mode") else { |
| 137 | return Err(at("no `mode` property")); |
| 138 | }; |
| 139 | // Absent is an ordinary line, like the lane inputs below; present and not 0/1 is an error. |
| 140 | let Some(intercity) = byte_prop(&feature.props, "intercity", 0).filter(|v| *v <= 1) else { |
| 141 | return Err(at("an `intercity` property that is not 0 or 1")); |
| 142 | }; |
| 143 | let Some(class) = transit_class(&mode, intercity == 1) else { |
| 144 | return Err(at(&format!("`{mode}` is not a mode this layer carries"))); |
| 145 | }; |
| 146 | let Some(color) = prop(&feature.props, "color").as_deref().and_then(hex_rrggbb) else { |
| 147 | return Err(at("no usable `color` property; it must be non-zero bare RRGGBB hex")); |
| 148 | }; |
| 149 | let Some(ordinal) = byte_prop(&feature.props, "ordinal", 0) else { |
| 150 | return Err(at("an `ordinal` property that is not a whole number in 0..=255")); |
| 151 | }; |
| 152 | let Some(lanes) = byte_prop(&feature.props, "lanes", 1) else { |
| 153 | return Err(at("a `lanes` property that is not a whole number in 0..=255")); |
| 154 | }; |
| 155 | let Some(taper) = byte_prop(&feature.props, "taper", 255) else { |
| 156 | return Err(at("a `taper` property that is not a whole number in 0..=255")); |
| 157 | }; |
| 158 | for line in lines { |
| 159 | if line.len() < 2 || !meets(&line, bbox) { |
| 160 | skipped += 1; |
| 161 | continue; |
| 162 | } |
| 163 | sink.push_transit( |
| 164 | &class, |
| 165 | &crate::store::EncodedGeom::live(&Geometry::Lines(vec![line]))?, |
| 166 | color, |
| 167 | ordinal, |
| 168 | lanes, |
| 169 | taper, |
| 170 | )?; |
| 171 | written += 1; |
| 172 | } |
| 173 | } |
| 174 | if written == 0 { |
| 175 | return err(format!( |
| 176 | "{} holds no transit route meeting {bbox:?}; is it the right area?", |
| 177 | path.display(), |
| 178 | )); |
| 179 | } |
| 180 | bar.finish("line(s)"); |
| 181 | println!(" {written} transit route(s) kept, {skipped} outside the extract"); |
| 182 | Ok(written) |
| 183 | } |
| 184 | |
| 185 | /// A string-valued property, by name. |
| 186 | fn prop(props: &[(String, Value)], name: &str) -> Option<String> { |
| 187 | props.iter().find(|(k, _)| k == name).and_then(|(_, v)| match v { |
| 188 | Value::String(s) => Some(s.clone()), |
| 189 | _ => None, |
| 190 | }) |
| 191 | } |
| 192 | |
| 193 | /// One of the lane inputs as a byte. `None` only for a property that is there and unreadable. |
| 194 | /// |
| 195 | /// Absent is `missing` on purpose: everything else in this reader hard-errors, and falling into |
| 196 | /// that path would make a routes file written before corridors existed unreadable rather than |
| 197 | /// simply un-fanned. The GeoJSON reader gives a non-negative literal back as a `Uint` and a |
| 198 | /// negative one as a `Double`, so every arm is the same number. |
| 199 | fn byte_prop(props: &[(String, Value)], name: &str, missing: u8) -> Option<u8> { |
| 200 | match props.iter().find(|(k, _)| k == name) { |
| 201 | None => Some(missing), |
| 202 | Some((_, Value::Uint(v))) => u8::try_from(*v).ok(), |
| 203 | Some((_, Value::Int(v))) | Some((_, Value::SInt(v))) => u8::try_from(*v).ok(), |
| 204 | Some((_, Value::Double(v))) if v.fract() == 0.0 => { |
| 205 | (*v >= 0.0 && *v <= u8::MAX as f64).then_some(*v as u8) |
| 206 | } |
| 207 | Some(_) => None, |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | /// A bare `RRGGBB` hex colour as `0xRRGGBB`, or `None`. |
| 212 | /// |
| 213 | /// Zero is refused: it means "no colour" on the wire and [`crate::store::Sink::push_transit`] |
| 214 | /// rejects it, so catching it here names the offending line instead. |
| 215 | fn hex_rrggbb(raw: &str) -> Option<u32> { |
| 216 | let hex = raw.trim(); |
| 217 | if hex.len() != 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) { |
| 218 | return None; |
| 219 | } |
| 220 | u32::from_str_radix(hex, 16).ok().filter(|c| *c != 0) |
| 221 | } |
| 222 | |
| 223 | /// Does a polyline meet `bbox`? Intersection, not containment. |
| 224 | fn meets(line: &[(f64, f64)], bbox: (f64, f64, f64, f64)) -> bool { |
| 225 | let (mut min_x, mut min_y) = (f64::MAX, f64::MAX); |
| 226 | let (mut max_x, mut max_y) = (f64::MIN, f64::MIN); |
| 227 | for &(x, y) in line { |
| 228 | min_x = min_x.min(x); |
| 229 | min_y = min_y.min(y); |
| 230 | max_x = max_x.max(x); |
| 231 | max_y = max_y.max(y); |
| 232 | } |
| 233 | !(max_x < bbox.0 || min_x > bbox.2 || max_y < bbox.1 || min_y > bbox.3) |
| 234 | } |
| 235 | |
| 236 | /// The station mode for a `poi` station feature's `kind_detail`. |
| 237 | /// |
| 238 | /// `station=subway/light_rail/tram` name the mode directly; a bare `railway=station` is a |
| 239 | /// `station`; a `railway=halt` is a `halt`. This is the tag the renderer reads to show stations |
| 240 | /// when Transit is ON even with POIs OFF: `poi` layer, kind `station`, detail naming one of |
| 241 | /// these — everything else on the layer is a different kind already. |
| 242 | pub fn station_detail(tags: &(impl TagSource + ?Sized)) -> &'static str { |
| 243 | match tags.get("station") { |
| 244 | Some("subway") => "subway", |
| 245 | Some("light_rail") => "light_rail", |
| 246 | Some("tram") => "tram", |
| 247 | Some("monorail") => "monorail", |
| 248 | _ => match tags.get("railway") { |
| 249 | Some("halt") => "halt", |
| 250 | _ => "station", |
| 251 | }, |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | include!("transit_s1.rs"); |