maps: corridor fan-out for pack rail lines
- Commit
fd70ba36574df940d6f0a3f52b5fa8332ae7f296- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-14 15:52 UTC (2 months ago)
- Parents
fa30c1c
Diff
maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.ktindex 7089587d82..d3186bf813 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt@@ -67,8 +67,8 @@ data class TripItinerary( ) /**- * One drawable rail line for the pack-driven lines overlay: the route's full- * GTFS-shape polyline with its agency colour.+ * One drawable rail-line span for the pack-driven lines overlay: part of a+ * route's shape with its lane in the corridor it crosses. */ data class RailLine( val name: String,@@ -76,6 +76,12 @@ data class RailLine( val color: String?, val mode: String, val points: List<GeoPoint>,+ /** This colour's index among the corridor's distinct colours. */+ val ordinal: Int,+ /** Distinct colours the corridor carries (1 outside one). */+ val lanes: Int,+ /** How far into its lane this span sits, over 255. */+ val taper: Int, ) /**
maps/src/main/java/com/vayunmathur/maps/ui/map/RailLines.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/RailLines.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/RailLines.ktindex da2d162f46..d07ddaf858 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/RailLines.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/RailLines.kt@@ -20,6 +20,7 @@ import com.vayunmathur.maps.util.visibleBoundsOrWorld import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.debounce+import kotlin.math.pow /** * How long the camera must sit still before the rail network refetches: the@@ -52,6 +53,107 @@ private fun packHexColor(hex: String?): Color? = runCatching { Color(android.graphics.Color.parseColor("#$it")) }.getOrNull() } +/**+ * How many parallel lanes a corridor draws at `zoom`, floored at read.+ * Ported from the tile style's `transit-rail` entry (`lanes` ramp+ * `[[0,1],[9,2],[11,3],[13,4]]`, linear): the lane count is a property of+ * the camera, not of the route, so a corridor fans wider as you zoom in and+ * collapses toward its centerline as you zoom out.+ */+internal fun railLaneCount(zoom: Double): Int {+ val stops = listOf(0.0 to 1.0f, 9.0 to 2.0f, 11.0 to 3.0f, 13.0 to 4.0f)+ if (zoom <= stops.first().first) return stops.first().second.toInt()+ if (zoom >= stops.last().first) return stops.last().second.toInt()+ for (i in 0 until stops.size - 1) {+ val (z0, v0) = stops[i]+ val (z1, v1) = stops[i + 1]+ if (zoom <= z1) {+ val t = (zoom - z0) / (z1 - z0)+ return (v0 + (v1 - v0) * t).toInt()+ }+ }+ return stops.last().second.toInt()+}++/**+ * How far sideways a corridor span's mesh shifts at `zoom`, in Dp. Ported+ * from `lane_offset_px` in the tile style: past the lane count the colours+ * squash onto shared lanes from the middle (ordinal 0 keeps lane 0, the+ * last ordinal the last lane) so two colours can share a lane but never+ * swap sides. `spread` is the tile entry's constant 6.0 Dp between adjacent+ * lanes; `taper/255` eases mouth pieces into their lane.+ */+internal fun railLaneOffsetDp(zoom: Double, ordinal: Int, count: Int, taper: Int): Double {+ val lanes = minOf(railLaneCount(zoom), count)+ if (lanes < 2 || count < 2) return 0.0+ val span = lanes - 1+ val steps = count - 1+ val lane = (2 * ordinal * span + steps) / (2 * steps)+ return (2 * lane - (lanes - 1)) * 6.0 / 2.0 * (taper / 255.0)+}++/**+ * Ground metres per Dp at `latitude`/`zoom` for the 512-unit tile schema.+ */+internal fun metersPerDp(latitude: Double, zoom: Double): Double {+ val worldPx = 512.0 * 2.0.pow(zoom)+ return 40_075_016.686 * kotlin.math.cos(Math.toRadians(latitude)) / worldPx+}++/**+ * A polyline shifted sideways by `meters` (positive = right of travel),+ * for fanning corridor spans into parallel lanes host-side.+ *+ * Per-vertex averaged normals: each interior vertex moves along the mean of+ * its two segment normals, endpoints along their single segment's normal.+ * Ends stay glued (zero-length segments skipped), so fanned spans meet the+ * same way centred ones do.+ */+internal fun offsetPolyline(+ points: List<com.vayunmathur.library.map.GeoPoint>,+ meters: Double,+): List<com.vayunmathur.library.map.GeoPoint> {+ if (points.size < 2 || meters == 0.0) return points+ data class Vec(val east: Double, val north: Double)+ // Segment normals (east, north), length-weighted by averaging below.+ val normals = mutableListOf<Vec>()+ for (i in 0 until points.size - 1) {+ val a = points[i]+ val b = points[i + 1]+ val cosLat = kotlin.math.cos(+ Math.toRadians((a.latitude + b.latitude) / 2.0)+ ).coerceAtLeast(1e-6)+ val east = (b.longitude - a.longitude) * 111_320.0 * cosLat+ val north = (b.latitude - a.latitude) * 111_320.0+ val len = kotlin.math.hypot(east, north)+ // Right-of-travel normal: (north, -east) normalized. Matches the+ // tool's `d.east * uy - d.north * ux` side: positive offset draws+ // right of travel, like ascending ordinals.+ normals.add(+ if (len <= 0.0) Vec(0.0, 0.0)+ else Vec(north / len, -east / len)+ )+ }+ return points.mapIndexed { i, p ->+ val n = when (i) {+ 0 -> normals.first()+ points.size - 1 -> normals.last()+ else -> {+ val a = normals[i - 1]+ val b = normals[i]+ val s = Vec(a.east + b.east, a.north + b.north)+ val len = kotlin.math.hypot(s.east, s.north)+ if (len <= 0.0) a else Vec(s.east / len, s.north / len)+ }+ }+ val cosLat = kotlin.math.cos(Math.toRadians(p.latitude)).coerceAtLeast(1e-6)+ com.vayunmathur.library.map.GeoPoint(+ p.longitude + n.east * meters / (111_320.0 * cosLat),+ p.latitude + n.north * meters / 111_320.0,+ )+ }+}+ /** * The pack-driven rail-lines network for the viewport, as a [RouteOverlay * ], or null when the transit layer is off, zoomed too far out, or the pack@@ -72,18 +174,52 @@ fun rememberRailLines( ): RouteOverlay? { val context = LocalContext.current var overlay by remember { mutableStateOf<RouteOverlay?>(null) }- // Last fetch footprint: reused while the camera stays inside it.+ // Last fetch footprint: reused while the camera stays inside it. The+ // fetched spans (with corridor slots) are kept separately from the+ // built overlay so a zoom-band change re-fans cached geometry without+ // re-querying the pack. var fetchedCentre by remember { mutableStateOf<Pair<Double, Double>?>(null) } var fetchedZoom by remember { mutableStateOf(Double.NaN) }+ var fetchedSpans by remember {+ mutableStateOf<List<com.vayunmathur.maps.data.transit.RailLine>>(emptyList())+ }+ var fannedZoom by remember { mutableStateOf(Double.NaN) } LaunchedEffect(transitEnabled) { if (!transitEnabled) { overlay = null fetchedCentre = null fetchedZoom = Double.NaN+ fetchedSpans = emptyList()+ fannedZoom = Double.NaN } } + // Re-fan cached spans when the lane count steps (z9/11/13 bands). Pure+ // geometry post-processing: no pack query, no tessellation here (the+ // push re-tessellates native-side, like any overlay update).+ fun fan(spans: List<com.vayunmathur.maps.data.transit.RailLine>, zoom: Double, lat: Double) {+ val mpd = metersPerDp(lat, zoom)+ overlay = if (spans.isEmpty()) {+ null+ } else {+ RouteOverlay(+ segments = spans.map { line ->+ val offsetDp = railLaneOffsetDp(zoom, line.ordinal, line.lanes, line.taper)+ RouteSegment(+ points = offsetPolyline(line.points, offsetDp * mpd),+ color = packHexColor(line.color)+ ?: tokens.routeTransitFallback,+ )+ },+ // Thinner than the 8 dp navigation route with no+ // casing: a network backdrop, not a followed line.+ style = RouteStyle(width = 4.dp, casingWidth = 0.dp),+ )+ }+ fannedZoom = zoom+ }+ LaunchedEffect(camera, transitEnabled) { if (!transitEnabled) return@LaunchedEffect snapshotFlow { camera.position }@@ -103,6 +239,11 @@ fun rememberRailLines( kotlin.math.abs(centre.second - last.second) < RAIL_RECENTER_DEGREES && kotlin.math.abs(zoom - fetchedZoom) < 1.0 ) {+ // Inside the fetched footprint: re-fan only when the+ // lane count stepped.+ if (railLaneCount(zoom) != railLaneCount(fannedZoom)) {+ fan(fetchedSpans, zoom, centre.first)+ } return@collectLatest } // Pad the query past the viewport so small pans stay covered.@@ -121,22 +262,8 @@ fun rememberRailLines( } fetchedCentre = centre fetchedZoom = zoom- overlay = if (lines.isEmpty()) {- null- } else {- RouteOverlay(- segments = lines.map { line ->- RouteSegment(- points = line.points,- color = packHexColor(line.color)- ?: tokens.routeTransitFallback,- )- },- // Thinner than the 8 dp navigation route with no- // casing: a network backdrop, not a followed line.- style = RouteStyle(width = 4.dp, casingWidth = 0.dp),- )- }+ fetchedSpans = lines+ fan(lines, zoom, centre.first) } } return overlay
maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.ktindex 068c740d67..00e3691b6b 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt@@ -522,6 +522,10 @@ object OfflineRouter { val feed: String, /** Flat `[lon0, lat0, ...]`, like a [RawStep] geometry. */ val coords: DoubleArray,+ // Corridor slot, appended LAST.+ val ordinal: Int,+ val lanes: Int,+ val taper: Int, ) /**@@ -723,10 +727,8 @@ object OfflineRouter { /** Drawable rail lines — see [OfflineRouterTransit.railLines]. */ suspend fun railLines( context: Context,- minLat: Double,- minLon: Double,- maxLat: Double,- maxLon: Double,+ minLat: Double, minLon: Double,+ maxLat: Double, maxLon: Double, ): List<com.vayunmathur.maps.data.transit.RailLine> = OfflineRouterTransit.railLines(context, minLat, minLon, maxLat, maxLon)
maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.kt b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.ktindex afb05b8a71..9305f673c9 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.kt@@ -352,6 +352,9 @@ internal object OfflineRouterTransit { else String.format("%06X", line.color and 0xFFFFFF), mode = gtfsRouteTypeToMode(line.routeType), points = points,+ ordinal = line.ordinal,+ lanes = line.lanes,+ taper = line.taper, ) ) }
maps/src/main/rust/src/corridor_geom.rs
diff --git a/maps/src/main/rust/src/corridor_geom.rs b/maps/src/main/rust/src/corridor_geom.rsnew file mode 100644index 0000000000..e8f5e82f66--- /dev/null+++ b/maps/src/main/rust/src/corridor_geom.rs@@ -0,0 +1,277 @@+//! Polyline ground geometry for corridor bundling, ported from+//! `scripts/maps/gtfs_ingest/src/shapes.rs` (the `project` / `distance_m` /+//! `resample` primitives) and `bundle_part2.rs` (cumulative measurement,+//! slicing, side tests and probe walks).+//!+//! Points are `(lat_e7, lon_e7)` integer pairs and distances are ground+//! metres in a local equirectangular frame, exactly as the tool measures+//! them — the corridor thresholds (`CORRIDOR_M` etc. in [`super::corridor`])+//! are calibrated in those units. Only the measurement subset is ported:+//! fitting (`fit`), simplification and wire encoding stay build-side.++/// Nearest point on segment `a`-`b` to `p`, with the parameter forced to at+/// least `t_min`. Returns `(t, distance in metres)`. Local equirectangular+/// metres about the segment's own mean latitude, exact enough at+/// shape-segment scale.+pub fn project(p: (i32, i32), a: (i32, i32), b: (i32, i32), t_min: f64) -> (f64, f64) {+ let cos_lat = f64::from(a.0 + b.0) * 0.5 * 1e-7;+ let cos_lat = cos_lat.to_radians().cos();+ let m = |q: (i32, i32)| {+ (+ f64::from(q.1) * 1e-7 * 111_320.0 * cos_lat,+ f64::from(q.0) * 1e-7 * 111_320.0,+ )+ };+ let (ax, ay) = m(a);+ let (bx, by) = m(b);+ let (px, py) = m(p);+ let (dx, dy) = (bx - ax, by - ay);+ let len2 = dx * dx + dy * dy;+ let t = if len2 <= 0.0 {+ t_min+ } else {+ (((px - ax) * dx + (py - ay) * dy) / len2).clamp(t_min, 1.0)+ };+ let (cx, cy) = (ax + t * dx, ay + t * dy);+ (t, ((px - cx).powi(2) + (py - cy).powi(2)).sqrt())+}++/// Ground distance between two e7 points in metres, in the same local+/// equirectangular frame [`project`] measures in.+pub fn distance_m(a: (i32, i32), b: (i32, i32)) -> f64 {+ let cos_lat = f64::from(a.0 + b.0) * 0.5 * 1e-7;+ let cos_lat = cos_lat.to_radians().cos();+ let dy = (f64::from(b.0) - f64::from(a.0)) * 1e-7 * 111_320.0;+ let dx = (f64::from(b.1) - f64::from(a.1)) * 1e-7 * 111_320.0 * cos_lat;+ (dx * dx + dy * dy).sqrt()+}++/// Walk `points` emitting a point every `step_m` metres along it.+///+/// The first and last points are always kept, so the walk covers the whole+/// polyline and a short one still yields both ends.+pub fn resample(points: &[(i32, i32)], step_m: f64) -> Vec<(i32, i32)> {+ if points.len() < 2 || !(step_m > 0.0) {+ return points.to_vec();+ }+ let lerp = |a: i32, b: i32, t: f64| (f64::from(a) + (f64::from(b) - f64::from(a)) * t).round() as i32;+ let mut out = vec![points[0]];+ // Distance already walked since the last emitted sample, carried across+ // the segment boundary so the spacing is along the polyline, not per+ // segment.+ let mut carry = 0.0f64;+ for pair in points.windows(2) {+ let (a, b) = (pair[0], pair[1]);+ let length = distance_m(a, b);+ if length <= 0.0 {+ continue;+ }+ let mut at = step_m - carry;+ while at < length {+ let t = at / length;+ out.push((lerp(a.0, b.0, t), lerp(a.1, b.1, t)));+ at += step_m;+ }+ carry = length - (at - step_m);+ }+ if let Some(&last) = points.last() {+ if out[out.len() - 1] != last {+ out.push(last);+ }+ }+ out+}++/// Cumulative ground distance to each vertex of a polyline.+pub fn cumulative(points: &[(i32, i32)]) -> Vec<f64> {+ let mut out = Vec::with_capacity(points.len());+ let mut total = 0.0;+ for (at, point) in points.iter().enumerate() {+ if at > 0 {+ total += distance_m(points[at - 1], *point);+ }+ out.push(total);+ }+ out+}++/// The point `at` metres along a polyline, interpolated within its segment.+pub fn point_at(points: &[(i32, i32)], cum: &[f64], at: f64) -> (i32, i32) {+ if points.len() < 2 {+ return points.first().copied().unwrap_or((0, 0));+ }+ let last = points.len() - 1;+ if at <= 0.0 {+ return points[0];+ }+ if at >= cum[last] {+ return points[last];+ }+ let seg = cum.partition_point(|d| *d <= at).max(1) - 1;+ let span = cum[seg + 1] - cum[seg];+ let t = if span > 0.0 { (at - cum[seg]) / span } else { 0.0 };+ let (a, b) = (points[seg], points[seg + 1]);+ (+ (f64::from(a.0) + (f64::from(b.0) - f64::from(a.0)) * t).round() as i32,+ (f64::from(a.1) + (f64::from(b.1) - f64::from(a.1)) * t).round() as i32,+ )+}++/// The part of a polyline between two distances along it, with both ends+/// interpolated.+///+/// Both ends land exactly on the polyline, so two adjacent slices share+/// their boundary vertex and the pieces of one route meet. Empty when the+/// two distances leave nothing between them.+pub fn slice_between(points: &[(i32, i32)], cum: &[f64], from: f64, to: f64) -> Vec<(i32, i32)> {+ if points.len() < 2 {+ return Vec::new();+ }+ let total = cum[cum.len() - 1];+ let (from, to) = (from.clamp(0.0, total), to.clamp(0.0, total));+ let (from, to) = if from <= to { (from, to) } else { (to, from) };+ let mut out = vec![point_at(points, cum, from)];+ for (at, along) in cum.iter().enumerate() {+ if *along > from && *along < to && out[out.len() - 1] != points[at] {+ out.push(points[at]);+ }+ }+ let end = point_at(points, cum, to);+ if out[out.len() - 1] != end {+ out.push(end);+ }+ if out.len() < 2 {+ Vec::new()+ } else {+ out+ }+}++/// How far to the side of a reference polyline `p` lies, in metres, signed+/// positive to the right of its direction of travel. Only segments within+/// `extent` (cumulative metres) are searched: past a corridor mouth the+/// reference heads wherever it goes next, which is no axis to measure a side+/// against. Ported from the tool's `signed_offset`, minus the corridor+/// wrapper: callers pass the reference's own points, cum and extent.+pub fn signed_offset_side(+ points: &[(i32, i32)],+ cum: &[f64],+ extent: (f64, f64),+ p: (i32, i32),+) -> f64 {+ let mut best = (f64::INFINITY, 0.0f64);+ for at in 0..points.len().saturating_sub(1) {+ let (Some(&ca), Some(&cb)) = (cum.get(at), cum.get(at + 1)) else {+ continue;+ };+ if cb < extent.0 || ca > extent.1 {+ continue;+ }+ let (a, b) = (points[at], points[at + 1]);+ let (_, distance) = project(p, a, b, 0.0);+ if distance >= best.0 {+ continue;+ }+ let cos_lat = f64::from(a.0 + b.0) * 0.5 * 1e-7;+ let cos_lat = cos_lat.to_radians().cos();+ let (east, north) = (f64::from(b.1 - a.1) * cos_lat, f64::from(b.0 - a.0));+ let length = (east * east + north * north).sqrt();+ if length <= 0.0 {+ continue;+ }+ let (ux, uy) = (east / length, north / length);+ let d_east = f64::from(p.1 - a.1) * 1e-7 * 111_320.0 * cos_lat;+ let d_north = f64::from(p.0 - a.0) * 1e-7 * 111_320.0;+ best = (distance, d_east * uy - d_north * ux);+ }+ best.1+}++/// One probe point along a candidate, with the unit direction of travel there.+pub struct DirectedPoint {+ /// The e7 point.+ pub point: (i32, i32),+ /// Unit tangent in an (east, north) frame with cosine latitude scaling.+ pub ux: f64,+ /// Unit tangent in an (east, north) frame with cosine latitude scaling.+ pub uy: f64,+}++/// Each point of `line` with the unit direction of travel there. One entry+/// per input point: a degenerate segment carries the previous direction+/// forward rather than dropping the point, so the result stays+/// index-aligned with its input.+pub fn directed(line: &[(i32, i32)]) -> Vec<DirectedPoint> {+ let mut out = Vec::with_capacity(line.len());+ let (mut ux, mut uy) = (1.0f64, 0.0f64);+ for i in 0..line.len() {+ let (a, b) = if i + 1 < line.len() {+ (line[i], line[i + 1])+ } else if i > 0 {+ (line[i - 1], line[i])+ } else {+ // A single point has no direction; the initial east stands in.+ out.push(DirectedPoint { point: line[i], ux, uy });+ continue;+ };+ let cos_lat = (f64::from(a.0 + b.0) * 0.5 * 1e-7).to_radians().cos();+ let dy = f64::from(b.0 - a.0);+ let dx = f64::from(b.1 - a.1) * cos_lat;+ let length = (dx * dx + dy * dy).sqrt();+ if length > 0.0 {+ (ux, uy) = (dx / length, dy / length);+ }+ out.push(DirectedPoint { point: line[i], ux, uy });+ }+ out+}++/// Walk a polyline at `step_m`, returning each sample with its unit+/// direction of travel.+pub fn walk_directed(points: &[(i32, i32)], step_m: f64) -> Vec<DirectedPoint> {+ let walked = resample(points, step_m);+ if walked.len() < 2 {+ return Vec::new();+ }+ directed(&walked)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_metre_is_a_metre_in_both_axes() {+ // 0.001 degrees of latitude is 111.3 m anywhere.+ let north = distance_m((377_000_000, -1_224_000_000), (377_010_000, -1_224_000_000));+ assert!((north - 111.32).abs() < 0.1, "{north}");+ // The same longitude span is shorter, by cos(37.7).+ let east = distance_m((377_000_000, -1_224_000_000), (377_000_000, -1_223_990_000));+ assert!((east - 111.32 * 37.7f64.to_radians().cos()).abs() < 0.1, "{east}");+ }++ #[test]+ fn resampling_walks_the_polyline_at_a_fixed_spacing() {+ // 0.1 degrees of latitude: 11,132 m due north.+ let line = [(37_700_000, -122_400_000), (38_700_000, -122_400_000)];+ let walked = resample(&line, 1000.0);+ // Eleven interior samples plus both ends.+ assert_eq!(walked.len(), 13, "{walked:?}");+ assert_eq!(walked[0], line[0], "the first point is always kept");+ assert_eq!(walked[walked.len() - 1], line[1], "and so is the last");+ for pair in walked[..walked.len() - 1].windows(2) {+ let step = distance_m(pair[0], pair[1]);+ assert!((step - 1000.0).abs() < 1.0, "uneven step {step}");+ }+ }++ #[test]+ fn slicing_shares_its_boundary_vertex() {+ let line = [(0, 0), (0, 1_113_200), (0, 2_226_400)];+ let cum = cumulative(&line);+ let a = slice_between(&line, &cum, 0.0, 1000.0);+ let b = slice_between(&line, &cum, 1000.0, 2000.0);+ assert!(a.len() >= 2 && b.len() >= 2);+ assert_eq!(a[a.len() - 1], b[0], "adjacent slices meet exactly");+ }+}
maps/src/main/rust/src/corridor_grid.rs
diff --git a/maps/src/main/rust/src/corridor_grid.rs b/maps/src/main/rust/src/corridor_grid.rsnew file mode 100644index 0000000000..3c44d02ec8--- /dev/null+++ b/maps/src/main/rust/src/corridor_grid.rs@@ -0,0 +1,124 @@+//! Probe sampling and the spatial grid for corridor grouping, ported from+//! `scripts/maps/gtfs_ingest/src/bundle_part3.rs` (`sample_all`, `Grid`,+//! `routes_near`) and the cell helpers.+//!+//! Split from `corridor_group` along module lines (the `rustFileLength`+//! gate): sampling + lookup live here, runs + corridors + spans stay there.++use super::corridor_geom::{distance_m, walk_directed};+use super::corridor_group::{Candidate, CORRIDOR_M, COS_FOLD, SAMPLE_M};+use std::ops::Range;++/// One probe point along a candidate, with the unit direction of travel.+pub struct Sample {+ /// Owning route id.+ pub route: u32,+ /// e7 point.+ pub point: (i32, i32),+ /// Unit tangent x (east).+ pub ux: f64,+ /// Unit tangent y (north).+ pub uy: f64,+}++/// Every candidate's samples, flat, with the range each candidate's own+/// block occupies.+pub fn sample_all(candidates: &[Candidate]) -> (Vec<Sample>, Vec<Range<usize>>) {+ let mut out = Vec::new();+ let mut blocks = Vec::with_capacity(candidates.len());+ for candidate in candidates {+ let start = out.len();+ for dp in walk_directed(candidate.points, SAMPLE_M) {+ out.push(Sample {+ route: candidate.route,+ point: dp.point,+ ux: dp.ux,+ uy: dp.uy,+ });+ }+ blocks.push(start..out.len());+ }+ (out, blocks)+}++type Cell = (i32, i32);++/// Grid cell in metres, just above the search radius so a probe never has to+/// scan more than the nine cells around it.+const CELL_M: f64 = 40.0;++/// The cell a point falls in. Square in metres rather than in degrees, so a+/// cell near the pole is not a sliver.+fn cell_of(point: (i32, i32)) -> Cell {+ let lat = f64::from(point.0) * 1e-7;+ let cos_lat = lat.to_radians().cos().max(1e-6);+ let y = lat * 111_320.0 / CELL_M;+ let x = f64::from(point.1) * 1e-7 * 111_320.0 * cos_lat / CELL_M;+ (x.floor() as i32, y.floor() as i32)+}++/// A sorted flat `(cell, sample)` vector grid.+pub struct Grid {+ entries: Vec<(Cell, u32)>,+}++impl Grid {+ /// Build the grid over `samples`.+ pub fn build(samples: &[Sample]) -> Grid {+ let mut entries: Vec<(Cell, u32)> = samples+ .iter()+ .enumerate()+ .map(|(i, s)| (cell_of(s.point), i as u32))+ .collect();+ entries.sort_unstable();+ Grid { entries }+ }++ /// Routes with a sample within [`CORRIDOR_M`] of `at` running parallel+ /// to it, ascending and deduplicated. Always contains `at`'s own route.+ ///+ /// `seen` is a caller-owned scratch array of one slot per route holding+ /// the stamp of the sample a route was last accepted for; a route+ /// rejected against one sample stays eligible against a nearer one.+ pub fn routes_near(+ &self,+ samples: &[Sample],+ at: &Sample,+ out: &mut Vec<u32>,+ seen: &mut [u32],+ stamp: u32,+ ) {+ out.clear();+ out.push(at.route);+ if let Some(slot) = seen.get_mut(at.route as usize) {+ *slot = stamp;+ }+ let (cx, cy) = cell_of(at.point);+ for dx in -1..=1 {+ for dy in -1..=1 {+ let key = (cx + dx, cy + dy);+ let lo = self.entries.partition_point(|(k, _)| *k < key);+ let hi = self.entries.partition_point(|(k, _)| *k <= key);+ for &(_, i) in &self.entries[lo..hi] {+ let Some(other) = samples.get(i as usize) else {+ continue;+ };+ let Some(slot) = seen.get_mut(other.route as usize) else {+ continue;+ };+ if *slot == stamp {+ continue;+ }+ if (at.ux * other.ux + at.uy * other.uy).abs() < COS_FOLD {+ continue;+ }+ if distance_m(at.point, other.point) <= CORRIDOR_M {+ *slot = stamp;+ out.push(other.route);+ }+ }+ }+ }+ out.sort_unstable();+ }+}
maps/src/main/rust/src/corridor_group.rs
diff --git a/maps/src/main/rust/src/corridor_group.rs b/maps/src/main/rust/src/corridor_group.rsnew file mode 100644index 0000000000..f331e587b1--- /dev/null+++ b/maps/src/main/rust/src/corridor_group.rs@@ -0,0 +1,475 @@+//! Corridor grouping, ported from `scripts/maps/gtfs_ingest/src/bundle.rs`+//! and `bundle_part1.rs`.+//!+//! Decides which routes share a corridor and in what order their colours sit+//! across it. Single-threaded and silent: the tool spreads the probe and the+//! corridor loop across the machine with progress bars because a world feed+//! set carries hundreds of millions of samples; a viewport fetch carries+//! dozens of routes, so the same math runs inline with no threads and no+//! stderr traffic. Everything else — constants, the membership/run/corridor+//! shape, the reference pick, the canonical fold, the approach-side order —+//! is the tool's logic verbatim, so the lanes agree with the tile path.++use super::corridor_grid::{Grid, sample_all};+use std::collections::BTreeMap;++/// Two polylines closer than this everywhere are the same line, and two+/// tracks closer than this are one corridor.+pub const CORRIDOR_M: f64 = 30.0;++/// How close a member's own survey has to come to the reference before it+/// stops drawing its own track and hands over to the corridor's.+const SNAP_M: f64 = 8.0;++/// Spacing of the probe samples along a polyline.+pub const SAMPLE_M: f64 = 10.0;++/// How much track two routes have to share before it counts as a corridor,+/// and the smoothing window on the runs.+const MIN_SHARED_M: f64 = 300.0;++/// Cosine of the angle within which two bearings count as parallel (25°),+/// compared on `|u · v|` so opposite directions over one track are parallel.+pub const COS_FOLD: f64 = 0.906_307_787;++/// The shortest ease a member spends coming into its lane.+const TAPER_M: f64 = 100.0;++/// How much of a member's own survey, immediately outside the corridor+/// mouth, decides which side of the corridor it takes.+const APPROACH_M: f64 = 150.0;++/// Points sampled along the approach.+const APPROACH_SAMPLES: usize = 8;++/// One route's polyline, offered for slotting.+pub struct Candidate<'a> {+ /// e7 points in travel order.+ pub points: &'a [(i32, i32)],+ /// Which route this polyline belongs to. Lane membership is per route;+ /// the corridor order is per colour (see [`Corridor::colours`]).+ pub route: u32,+ /// `0xRRGGBB` effective colour (agency colour, or the mode fallback when+ /// the pack carries none).+ pub color: u32,+ /// The route's display name: tie-break keeping a rebuild deterministic.+ pub name: &'a str,+}++/// A maximal stretch of one candidate's samples holding the same membership,+/// as inclusive indices into that candidate's own block of samples.+#[derive(Clone, Copy)]+pub struct Run {+ /// First sample index in the candidate's block.+ pub from: usize,+ /// Last sample index in the candidate's block.+ pub to: usize,+ /// Interned membership-set id.+ pub set: u32,+}++/// A shared corridor: the geometry every member draws, and the lane order.+pub struct Corridor {+ /// One member's polyline, folded into the canonical direction, which the+ /// whole corridor draws slices of.+ pub points: Vec<(i32, i32)>,+ /// Cumulative ground metres along [`Corridor::points`].+ pub cum: Vec<f64>,+ /// Distinct colours ordered across the corridor: index 0 is the+ /// left-hand side of the reference's direction of travel.+ pub colours: Vec<u32>,+}++/// Cut a candidate's samples into runs of constant membership, then smooth+/// away the ones too short to be a corridor.+fn cut_runs(per_sample: &[u32], cum: &[f64]) -> Vec<Run> {+ let Some(&first) = per_sample.first() else {+ return Vec::new();+ };+ let mut runs = vec![Run { from: 0, to: 0, set: first }];+ for (at, &set) in per_sample.iter().enumerate().skip(1) {+ let Some(last) = runs.last_mut() else {+ break;+ };+ if last.set == set {+ last.to = at;+ } else {+ runs.push(Run { from: at, to: at, set });+ }+ }+ smooth(&mut runs, cum);+ runs+}++/// Absorb every run shorter than [`MIN_SHARED_M`] into a neighbour, longest+/// neighbour first, and coalesce neighbours that end up equal.+fn smooth(runs: &mut Vec<Run>, cum: &[f64]) {+ let length = |run: &Run| {+ cum.get(run.to).copied().unwrap_or(0.0) - cum.get(run.from).copied().unwrap_or(0.0)+ };+ while runs.len() > 1 {+ let Some(at) = (0..runs.len())+ .filter(|&i| length(&runs[i]) < MIN_SHARED_M)+ .min_by(|&a, &b| {+ length(&runs[a])+ .total_cmp(&length(&runs[b]))+ .then(a.cmp(&b))+ })+ else {+ break;+ };+ let into = match (at.checked_sub(1), runs.get(at + 1)) {+ (None, _) => at + 1,+ (Some(before), None) => before,+ (Some(before), Some(after)) => {+ if length(after) > length(&runs[before]) {+ at + 1+ } else {+ before+ }+ }+ };+ if into < at {+ runs[into].to = runs[at].to;+ } else {+ let from = runs[at].from;+ if let Some(target) = runs.get_mut(into) {+ target.from = from;+ }+ }+ runs.remove(at);+ let mut i = 1;+ while i < runs.len() {+ if runs[i].set == runs[i - 1].set {+ runs[i - 1].to = runs[i].to;+ runs.remove(i);+ } else {+ i += 1;+ }+ }+ }+}++/// Fold a polyline into a fixed half-plane: northward, or exactly east-west+/// and eastward. The lane side is measured along the reference, so an+/// inherited direction would mirror the whole fan when a lower-coloured+/// route joins at a junction.+fn canonical(points: &[(i32, i32)]) -> Vec<(i32, i32)> {+ let (Some(&first), Some(&last)) = (points.first(), points.last()) else {+ return points.to_vec();+ };+ let (north, east) = (last.0 - first.0, last.1 - first.1);+ if north < 0 || (north == 0 && east < 0) {+ points.iter().rev().copied().collect()+ } else {+ points.to_vec()+ }+}++/// Which side of the corridor one member arrives on, in metres, positive to+/// the right of the reference's direction of travel. Measured on the+/// approach — the member's own untouched survey just outside the mouth —+/// where the sign is tens of metres, not survey noise.+fn approach_offset(+ corridor: &Corridor,+ extent: (f64, f64),+ points: &[(i32, i32)],+ own_cum: &[f64],+ from: f64,+ to: f64,+) -> f64 {+ let total = own_cum.last().copied().unwrap_or(0.0);+ let (lo, hi) = if from <= to { (from, to) } else { (to, from) };+ let (a, b) = if lo > 0.0 {+ ((lo - APPROACH_M).max(0.0), lo)+ } else if hi < total {+ (hi, (hi + APPROACH_M).min(total))+ } else {+ (lo, hi)+ };+ let mut sum = 0.0;+ for k in 0..APPROACH_SAMPLES {+ let t = k as f64 / (APPROACH_SAMPLES - 1) as f64;+ sum += super::corridor_geom::signed_offset_side(+ &corridor.points,+ &corridor.cum,+ extent,+ point_at_owned(points, own_cum, a + (b - a) * t),+ );+ }+ sum / APPROACH_SAMPLES as f64+}++/// The taper fraction of step `step`, climbing toward but never reaching+/// 255 — the full lane belongs to the corridor span the taper leads into.+fn taper_fraction(step: usize) -> u8 {+ (255.0 * step as f64 / (TAPER_STEPS + 1) as f64).round() as u8+}++const TAPER_STEPS: usize = 8;++/// Point query helpers over a candidate's own survey shared by grouping and+/// spans; thin wrappers over [`super::corridor_geom`].+fn point_at_owned(points: &[(i32, i32)], cum: &[f64], at: f64) -> (i32, i32) {+ super::corridor_geom::point_at(points, cum, at)+}++/// Every membership that survived as a multi-route run, with the geometry+/// and lane order its members share. No transitive closure: unioning+/// neighbouring corridors collapses whole networks into one.+pub fn corridors_of(+ candidates: &[Candidate],+ sets: &[Vec<u32>],+ runs: &[Vec<Run>],+ named: &[Option<(u32, &str)>],+ own_cum: &[Vec<f64>],+ probe_cum: &[Vec<f64>],+) -> BTreeMap<u32, Corridor> {+ let mut members: BTreeMap<u32, Vec<(usize, f64, f64)>> = BTreeMap::new();+ for (at, candidate_runs) in runs.iter().enumerate() {+ for run in candidate_runs {+ let Some(set) = sets.get(run.set as usize) else {+ continue;+ };+ if set.len() > 1 {+ let from = probe_cum+ .get(at)+ .and_then(|c| c.get(run.from))+ .copied()+ .unwrap_or(0.0);+ let to = probe_cum+ .get(at)+ .and_then(|c| c.get(run.to))+ .copied()+ .unwrap_or(0.0);+ members.entry(run.set).or_default().push((at, from, to));+ }+ }+ }+ let length = |at: usize| own_cum.get(at).and_then(|c| c.last()).copied().unwrap_or(0.0);+ let mut out = BTreeMap::new();+ for (set, in_corridor) in members {+ out.insert(+ set,+ one_corridor(set, &in_corridor, candidates, sets, named, own_cum, &length),+ );+ }+ out+}++/// One corridor's reference geometry and the order its colours sit in.+fn one_corridor(+ set: u32,+ in_corridor: &[(usize, f64, f64)],+ candidates: &[Candidate],+ sets: &[Vec<u32>],+ named: &[Option<(u32, &str)>],+ own_cum: &[Vec<f64>],+ length: &dyn Fn(usize) -> f64,+) -> Corridor {+ // Whose geometry the corridor draws: first member by colour then name+ // (stable across rebuilds), longest on ties (a shorter reference clips+ // every other member to itself).+ let pick = in_corridor+ .iter()+ .map(|&(at, _, _)| at)+ .reduce(|a, b| {+ let better = match (candidates[a].color, candidates[a].name)+ .cmp(&(candidates[b].color, candidates[b].name))+ {+ std::cmp::Ordering::Less => true,+ std::cmp::Ordering::Greater => false,+ std::cmp::Ordering::Equal => match length(b).total_cmp(&length(a)) {+ std::cmp::Ordering::Less => true,+ std::cmp::Ordering::Greater => false,+ std::cmp::Ordering::Equal => candidates[a].points <= candidates[b].points,+ },+ };+ if better {+ a+ } else {+ b+ }+ })+ .unwrap_or(0);+ let points = canonical(candidates[pick].points);+ let cum = super::corridor_geom::cumulative(&points);+ let mut reference = Corridor { points, cum, colours: Vec::new() };++ let projected = |at: usize, along: f64| {+ distance_along_ref(&reference, point_at_owned(candidates[at].points, &own_cum[at], along))+ };+ let extent = in_corridor.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &(at, from, to)| {+ let (a, b) = (projected(at, from), projected(at, to));+ (lo.min(a).min(b), hi.max(a).max(b))+ });+ // Less a taper at each end: a run boundary is only located to a sample+ // step, so the extent bleeds past the mouth, past which the reference is+ // no axis to measure a side against.+ let margin = TAPER_M.min((extent.1 - extent.0) / 4.0);+ let extent = (extent.0 + margin, extent.1 - margin);+ let mut sides: BTreeMap<u32, (f64, u32)> = BTreeMap::new();+ for &(at, from, to) in in_corridor {+ let side = approach_offset(+ &reference,+ extent,+ candidates[at].points,+ &own_cum[at],+ from,+ to,+ );+ let seen = sides.entry(candidates[at].color).or_insert((0.0, 0));+ seen.0 += side;+ seen.1 += 1;+ }+ // A route in the membership without a run of its own still takes a+ // place (the reference's, zero) since it still occupies a colour.+ let mut ordered: Vec<(f64, u32, &str)> = sets+ .get(set as usize)+ .map(|members| {+ members+ .iter()+ .map(|&member| {+ let (colour, name) = named+ .get(member as usize)+ .copied()+ .flatten()+ .unwrap_or((0, ""));+ let side = sides+ .get(&colour)+ .map(|&(sum, n)| sum / f64::from(n))+ .unwrap_or(0.0);+ (side, colour, name)+ })+ .collect()+ })+ .unwrap_or_default();+ // Ascending offset is ascending ordinal: ordinal zero takes the most+ // negative offset, the left of the reference's travel. Colour/name tail+ // keeps a rebuild deterministic.+ ordered.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)).then(a.2.cmp(b.2)));+ let mut colours: Vec<u32> = ordered.into_iter().map(|(_, c, _)| c).collect();+ colours.dedup();+ Corridor { colours, ..reference }+}++/// How far along a corridor's reference the nearest point to `p` lies.+fn distance_along_ref(corridor: &Corridor, p: (i32, i32)) -> f64 {+ nearest_ref(corridor, p).1+}++/// Nearest point on a corridor's reference to `p`, as `(distance, along)`.+fn nearest_ref(corridor: &Corridor, p: (i32, i32)) -> (f64, f64) {+ let mut best = (f64::INFINITY, 0.0f64);+ for at in 0..corridor.points.len().saturating_sub(1) {+ let a = corridor.points[at];+ let b = corridor.points[at + 1];+ let (t, offset) = super::corridor_geom::project(p, a, b, 0.0);+ if offset < best.0 {+ let seg_len = corridor.cum[at + 1] - corridor.cum[at];+ best = (offset, corridor.cum[at] + t * seg_len);+ }+ }+ best+}++/// Full grouping pipeline: sample, probe memberships single-threaded,+/// intern in sample order, cut runs, build corridors. Returns the per-sample+/// set ids, the per-candidate runs, and the corridors keyed by set id.+#[allow(clippy::too_many_arguments)]+pub fn group(+ candidates: &[Candidate],+ named: &[Option<(u32, &str)>],+) -> (Vec<u32>, Vec<Vec<Run>>, BTreeMap<u32, Corridor>) {+ let (samples, blocks) = sample_all(candidates);+ let grid = Grid::build(&samples);+ let route_count = candidates.iter().map(|c| c.route as usize + 1).max().unwrap_or(0);++ // Single-threaded probe: viewport scale is dozens of routes, so the+ // tool's thread pool buys nothing and only risks logspam on Android.+ let mut sets: Vec<Vec<u32>> = Vec::new();+ let mut set_ids: BTreeMap<Vec<u32>, u32> = BTreeMap::new();+ let mut per_sample: Vec<u32> = Vec::with_capacity(samples.len());+ let mut seen = vec![0u32; route_count.max(1)];+ let mut stamp: u32 = 0;+ let mut near = Vec::new();+ for sample in &samples {+ stamp = stamp.wrapping_add(1);+ grid.routes_near(&samples, sample, &mut near, &mut seen, stamp);+ let id = match set_ids.get(&near) {+ Some(id) => *id,+ None => {+ let id = sets.len() as u32;+ sets.push(near.clone());+ set_ids.insert(near.clone(), id);+ id+ }+ };+ per_sample.push(id);+ }++ let own_cum: Vec<Vec<f64>> =+ candidates.iter().map(|c| super::corridor_geom::cumulative(c.points)).collect();+ let mut offset = 0usize;+ let mut probe_cums: Vec<Vec<f64>> = Vec::with_capacity(candidates.len());+ let mut runs = Vec::with_capacity(candidates.len());+ for (block, own) in blocks.iter().zip(&own_cum) {+ // Probe `k` sits exactly `k * SAMPLE_M` along, last one at the end.+ let total = own.last().copied().unwrap_or(0.0);+ let count = block.len();+ let cum: Vec<f64> = (0..count)+ .map(|k| {+ if k + 1 == count {+ total+ } else {+ (k as f64 * SAMPLE_M).min(total)+ }+ })+ .collect();+ let run_block: Vec<u32> = per_sample[offset..offset + block.len()].to_vec();+ runs.push(cut_runs(&run_block, &cum));+ probe_cums.push(cum);+ offset += block.len();+ }++ let corridors = corridors_of(candidates, &sets, &runs, named, &own_cum, &probe_cums);+ (per_sample, runs, corridors)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn cand<'a>(+ points: &'a [(i32, i32)],+ route: u32,+ color: u32,+ name: &'a str,+ ) -> Candidate<'a> {+ Candidate { points, route, color, name }+ }++ #[test]+ fn disjoint_routes_share_no_corridor() {+ let a = [(0, 0), (0, 100_000)];+ let b = [(500_000, 0), (500_000, 100_000)];+ let named = [Some((1, "a")), Some((2, "b"))];+ let (_, _, corridors) =+ group(&[cand(&a, 0, 1, "a"), cand(&b, 1, 0xFF0001, "b")], &named);+ assert!(corridors.is_empty(), "far apart: no corridor");+ }++ #[test]+ fn overlapping_routes_share_one_corridor() {+ // Two ~1.1 km lines 5 m apart: well within CORRIDOR_M for their+ // whole shared kilometre, which clears MIN_SHARED_M.+ let a = [(0, 0), (0, 100_000)];+ let b = [(0, 450), (0, 100_450)];+ let named = [Some((1, "a")), Some((2, "b"))];+ let (_, _, corridors) =+ group(&[cand(&a, 0, 0xFF0001, "a"), cand(&b, 1, 0x00FF02, "b")], &named);+ assert_eq!(corridors.len(), 1, "one shared corridor");+ let corridor = corridors.values().next().expect("one corridor");+ assert_eq!(corridor.colours.len(), 2, "both colours ordered across it");+ }+}
maps/src/main/rust/src/corridor_spans.rs
diff --git a/maps/src/main/rust/src/corridor_spans.rs b/maps/src/main/rust/src/corridor_spans.rsnew file mode 100644index 0000000000..e20e854510--- /dev/null+++ b/maps/src/main/rust/src/corridor_spans.rs@@ -0,0 +1,477 @@+//! Corridor spans and duplicate suppression, ported from+//! `scripts/maps/gtfs_ingest/src/bundle_part2.rs` (`spans_of` and friends)+//! and `bundle_part3.rs` (`Covered`).+//!+//! Turns grouped runs into drawable spans: each candidate cut at corridor+//! mouths, drawing the corridor's reference geometry over the body with its+//! lane, its own survey across tapers, and welded seams between pieces.+//! Single-threaded like the grouping port: the tool spreads candidates+//! across cores, but a viewport fetch holds dozens of routes.++use super::corridor_geom::{cumulative, point_at, slice_between};+use super::corridor_group::{Corridor, Run};+use std::collections::{BTreeMap, HashMap};++/// One stretch of a candidate as it should be drawn.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Span {+ /// e7 polyline to emit: own geometry outside a corridor and across the+ /// ease, the corridor's reference geometry over the body.+ pub points: Vec<(i32, i32)>,+ /// This colour's index among the corridor's distinct colours. Zero+ /// outside a corridor. Positional: ascending offset is ascending ordinal.+ pub ordinal: u8,+ /// Distinct colours the corridor carries. One outside a corridor.+ pub lanes: u8,+ /// How far into its lane this piece sits, over 255. 255 outside a+ /// corridor and on a body; less only across a mouth taper.+ pub taper: u8,+}++/// Where a run begins and ends on the ground, as `(entry, exit)` in the+/// candidate's own order of travel.+type Bounds = ((i32, i32), (i32, i32));++/// One run's placement decision, computed for every run before any of it is+/// emitted: a run has to know whether its neighbours ease to decide its own.+struct Placement<'a> {+ corridor: &'a Corridor,+ /// Whether the candidate travels in the reference's direction here.+ forward: bool,+ /// The run's extent along the reference.+ lo: f64,+ hi: f64,+ /// First and last sample indices within [`SNAP_M`] of the reference.+ /// `None` where it never comes that close: the run keeps its own survey+ /// across the whole run, fanned but not exactly parallel.+ snap: Option<(usize, usize)>,+}++/// How close a member's own survey must come to hand over to the reference.+const SNAP_M: f64 = 8.0;++/// Probe spacing the grouping sampled at.+const SAMPLE_M: f64 = 10.0;++/// The shortest ease a member spends coming into its lane.+const TAPER_M: f64 = 100.0;++/// Features in one taper; the fraction ramps equally so each jump is ~1 Dp.+const TAPER_STEPS: usize = 8;++/// The taper fraction of step `step`, climbing toward but never reaching+/// 255 — the full lane belongs to the body the taper leads into.+fn taper_fraction(step: usize) -> u8 {+ (255.0 * step as f64 / (TAPER_STEPS + 1) as f64).round() as u8+}++/// The points a run begins and ends at, which is what the runs either side+/// have to reach.+fn bounds_of(pieces: &[Span]) -> Option<Bounds> {+ let entry = *pieces.first()?.points.first()?;+ let exit = *pieces.last()?.points.last()?;+ Some((entry, exit))+}++/// One candidate's spans, in its own order of travel.+///+/// `runs` are the candidate's smoothed membership runs, `samples` its probe+/// points in block order, `probe_cum`/`own_cum` the probe-space and own-space+/// distances, and `corridors` the shared map from [`super::corridor_group`].+#[allow(clippy::too_many_arguments)]+pub fn spans_of(+ points: &[(i32, i32)],+ color: u32,+ runs: &[Run],+ samples: &[(i32, i32)],+ probe_cum: &[f64],+ own_cum: &[f64],+ corridors: &BTreeMap<u32, Corridor>,+) -> Vec<Span> {+ let whole = || {+ vec![Span { points: points.to_vec(), ordinal: 0, lanes: 1, taper: 255 }]+ };+ if runs.is_empty() || (runs.len() == 1 && !corridors.contains_key(&runs[0].set)) {+ return whole();+ }++ let placements: Vec<Option<Placement>> = runs+ .iter()+ .map(|run| {+ let corridor = corridors.get(&run.set)?;+ let a = distance_along(corridor, samples.get(run.from).copied()?);+ let b = distance_along(corridor, samples.get(run.to).copied()?);+ let (forward, lo, hi) = if a <= b { (true, a, b) } else { (false, b, a) };+ // A run with no usable extent on the reference keeps its own+ // geometry: nothing to snap to.+ if hi - lo < SAMPLE_M {+ return None;+ }+ let near = |at: usize| {+ samples.get(at).map(|&p| nearest_dist(corridor, p) <= SNAP_M).unwrap_or(false)+ };+ let snap = (run.from..=run.to).find(|&at| near(at)).map(|first| {+ (+ first,+ (first..=run.to).rev().find(|&at| near(at)).unwrap_or(first),+ )+ });+ Some(Placement { corridor, forward, lo, hi, snap })+ })+ .collect();++ let mut pieces: Vec<Vec<Span>> = Vec::with_capacity(runs.len());+ let mut ends: Vec<Option<Bounds>> = Vec::with_capacity(runs.len());+ let mut against: Vec<bool> = Vec::with_capacity(runs.len());++ for (at, run) in runs.iter().enumerate() {+ let (own_from, own_to) = (+ probe_cum.get(run.from).copied().unwrap_or(0.0),+ probe_cum.get(run.to).copied().unwrap_or(0.0),+ );+ let own_piece = |from: f64, to: f64, ordinal: u8, lanes: u8, taper: u8| -> Option<Span> {+ let points = slice_between(points, own_cum, from, to);+ (points.len() >= 2).then_some(Span { points, ordinal, lanes, taper })+ };++ let Some(place) = placements.get(at).and_then(|p| p.as_ref()) else {+ let out: Vec<Span> = own_piece(own_from, own_to, 0, 1, 255).into_iter().collect();+ ends.push(bounds_of(&out));+ pieces.push(out);+ against.push(false);+ continue;+ };+ let corridor = place.corridor;+ let lanes = u8::try_from(corridor.colours.len()).unwrap_or(u8::MAX);+ let ordinal = corridor+ .colours+ .iter()+ .position(|c| *c == color)+ .and_then(|at| u8::try_from(at).ok())+ .unwrap_or(0);++ let Some((first, last)) = place.snap else {+ let out: Vec<Span> =+ own_piece(own_from, own_to, ordinal, lanes, 255).into_iter().collect();+ ends.push(bounds_of(&out));+ pieces.push(out);+ against.push(!place.forward);+ continue;+ };++ // A taper opens the fan off the member's own alignment: only where a+ // lane exists to open into (more than one colour) and the neighbour+ // is not itself on a corridor (then the line steps lane to lane).+ let fanned = lanes > 1;+ let eases = |other: Option<usize>| {+ fanned && matches!(other, Some(i) if placements.get(i).is_none_or(|p| p.is_none()))+ };+ let at_start = eases(at.checked_sub(1));+ let at_end = eases((at + 1 < runs.len()).then_some(at + 1));++ // The ease runs from the run's start to where the survey first comes+ // within SNAP_M: adaptive (shallow convergence, long ease), at least+ // TAPER_M, never more than a quarter of the run.+ let extent = own_to - own_from;+ let ease = |to_snap: f64| to_snap.max(TAPER_M).min(extent / 4.0);+ let lead = if at_start {+ ease(probe_cum.get(first).copied().unwrap_or(own_from) - own_from)+ } else {+ 0.0+ };+ let trail = if at_end {+ ease(own_to - probe_cum.get(last).copied().unwrap_or(own_to))+ } else {+ 0.0+ };++ let ref_at =+ |own: f64| distance_along(corridor, point_at(points, own_cum, own));+ let (from_end, to_end) =+ if place.forward { (place.lo, place.hi) } else { (place.hi, place.lo) };+ let body_from = if lead > 0.0 { ref_at(own_from + lead) } else { from_end };+ let body_to = if trail > 0.0 { ref_at(own_to - trail) } else { to_end };++ let mut out: Vec<Span> = Vec::new();+ if lead > 0.0 {+ let step = lead / TAPER_STEPS as f64;+ for k in 0..TAPER_STEPS {+ let base = own_from + k as f64 * step;+ out.extend(own_piece(base, base + step, ordinal, lanes, taper_fraction(k + 1)));+ }+ }+ let mut body = slice_between(&corridor.points, &corridor.cum, body_from, body_to);+ if !place.forward {+ body.reverse();+ }+ let mut body_exit = None;+ if body.len() >= 2 {+ let (head, tail) = (body[0], body[body.len() - 1]);+ // The ease is on the member's own survey and the body on the+ // reference, up to SNAP_M apart: carry one vertex across so the+ // two meet.+ if let Some(lead_end) = out.last_mut() {+ if lead_end.points.last() != Some(&head) {+ lead_end.points.push(head);+ }+ }+ out.push(Span { points: body, ordinal, lanes, taper: 255 });+ body_exit = Some(tail);+ }+ if trail > 0.0 {+ let step = trail / TAPER_STEPS as f64;+ let starts_at = out.len();+ for k in 0..TAPER_STEPS {+ let base = own_to - trail + k as f64 * step;+ out.extend(own_piece(+ base,+ base + step,+ ordinal,+ lanes,+ taper_fraction(TAPER_STEPS - k),+ ));+ }+ if let (Some(tail), Some(trail_start)) = (body_exit, out.get_mut(starts_at)) {+ if trail_start.points.first() != Some(&tail) {+ trail_start.points.insert(0, tail);+ }+ }+ }++ ends.push(bounds_of(&out));+ pieces.push(out);+ against.push(!place.forward);+ }++ // Carry one vertex across each seam so pieces meet: the corridor's own+ // geometry where there is one to preserve, the following run otherwise.+ for at in 1..pieces.len() {+ let (Some(before), Some(after)) = (ends[at - 1], ends[at]) else { continue };+ if placements[at - 1].is_some() && placements[at].is_none() {+ let Some(head) = pieces[at].first_mut() else { continue };+ if head.points.first() != Some(&before.1) {+ head.points.insert(0, before.1);+ }+ } else {+ let Some(tail) = pieces[at - 1].last_mut() else { continue };+ if tail.points.last() != Some(&after.0) {+ tail.points.push(after.0);+ }+ }+ }++ // Corridor-run pieces are stored reference-oriented so members share one+ // left normal; ease pieces inherit the survey's direction, so+ // against-reference runs turn round here or the fan mirrors.+ for (run_pieces, is_against) in pieces.iter_mut().zip(&against) {+ if *is_against {+ for span in run_pieces.iter_mut() {+ span.points.reverse();+ }+ }+ }++ let flat: Vec<Span> = pieces.into_iter().flatten().collect();+ if flat.is_empty() {+ vec![Span { points: points.to_vec(), ordinal: 0, lanes: 1, taper: 255 }]+ } else {+ flat+ }+}++/// How far along a corridor's reference the nearest point to `p` lies.+fn distance_along(corridor: &Corridor, p: (i32, i32)) -> f64 {+ nearest_dist_along(corridor, p).1+}++/// Nearest distance to a corridor's reference.+fn nearest_dist(corridor: &Corridor, p: (i32, i32)) -> f64 {+ nearest_dist_along(corridor, p).0+}++/// Nearest point on a corridor's reference to `p`, as `(distance, along)`.+fn nearest_dist_along(corridor: &Corridor, p: (i32, i32)) -> (f64, f64) {+ use super::corridor_geom::project;+ let mut best = (f64::INFINITY, 0.0f64);+ for at in 0..corridor.points.len().saturating_sub(1) {+ let (t, offset) = project(p, corridor.points[at], corridor.points[at + 1], 0.0);+ if offset < best.0 {+ let seg_len = corridor.cum[at + 1] - corridor.cum[at];+ best = (offset, corridor.cum[at] + t * seg_len);+ }+ }+ best+}++/// Track already drawn, for suppressing a line that adds nothing.+///+/// Whole lines only: subtracting covered parts was tried and leaves holes.+/// A `HashMap` of cells is fine here — nothing iterates it, the answer is a+/// boolean per point, so no order leaks into the output.+#[derive(Default)]+pub struct Covered {+ points: Vec<((i32, i32), f64, f64)>,+ cells: HashMap<Cell, Vec<u32>>,+ /// Which service drew each sample.+ tags: Vec<u32>,+}++type Cell = (i32, i32);++/// The cell a point falls in, square in metres.+fn cell_of(point: (i32, i32)) -> Cell {+ const CELL_M: f64 = 40.0;+ let lat = f64::from(point.0) * 1e-7;+ let cos_lat = lat.to_radians().cos().max(1e-6);+ let y = lat * 111_320.0 / CELL_M;+ let x = f64::from(point.1) * 1e-7 * 111_320.0 * cos_lat / CELL_M;+ (x.floor() as i32, y.floor() as i32)+}++/// Cosine of the parallel angle (25°), compared folded so opposite+/// directions over one track count as parallel.+const COS_FOLD: f64 = 0.906_307_787;++/// Corridor half-width: samples within this running parallel count as drawn.+const CORRIDOR_M: f64 = 30.0;++impl Covered {+ /// Record every metre of `line` as drawn by service `tag`.+ pub fn add_tagged(&mut self, line: &[(i32, i32)], tag: u32) {+ for dp in super::corridor_geom::walk_directed(line, 10.0) {+ let at = self.points.len() as u32;+ self.cells.entry(cell_of(dp.point)).or_default().push(at);+ self.points.push((dp.point, dp.ux, dp.uy));+ self.tags.push(tag);+ }+ }++ /// The most distinct services already drawn over any one metre of `line`.+ /// A few services over one track is real; fifteen is a republished-feeds+ /// artefact, so the caller caps it. Stops once `limit` is reached.+ pub fn crowd_reaches(&self, line: &[(i32, i32)], limit: usize) -> bool {+ if limit == 0 {+ return true;+ }+ let mut seen: Vec<u32> = Vec::new();+ for dp in super::corridor_geom::walk_directed(line, 10.0) {+ seen.clear();+ self.tags_over(dp.point, dp.ux, dp.uy, &mut seen, limit);+ if seen.len() >= limit {+ return true;+ }+ }+ false+ }++ /// How much of `line` is already drawn, 0 to 1. Too short to walk covers+ /// nothing, so it reports 0 and is kept.+ pub fn covered_fraction(&self, line: &[(i32, i32)]) -> f64 {+ let walked = super::corridor_geom::walk_directed(line, 10.0);+ if walked.is_empty() {+ return 0.0;+ }+ let drawn = walked+ .iter()+ .filter(|dp| self.covers(dp.point, dp.ux, dp.uy))+ .count();+ drawn as f64 / walked.len() as f64+ }++ /// Every distinct service drawn within [`CORRIDOR_M`] of this point,+ /// running parallel to it. Stops once `limit` is reached.+ fn tags_over(+ &self,+ point: (i32, i32),+ ux: f64,+ uy: f64,+ out: &mut Vec<u32>,+ limit: usize,+ ) {+ let (cx, cy) = cell_of(point);+ for dx in -1..=1 {+ for dy in -1..=1 {+ let Some(bucket) = self.cells.get(&(cx + dx, cy + dy)) else {+ continue;+ };+ for &i in bucket {+ let Some(&(other, oux, ouy)) = self.points.get(i as usize) else {+ continue;+ };+ if (ux * oux + uy * ouy).abs() < COS_FOLD {+ continue;+ }+ if super::corridor_geom::distance_m(point, other) <= CORRIDOR_M {+ let Some(&tag) = self.tags.get(i as usize) else {+ continue;+ };+ if !out.contains(&tag) {+ out.push(tag);+ if out.len() >= limit {+ return;+ }+ }+ }+ }+ }+ }+ }++ /// Is this point already drawn, by track running parallel to it?+ fn covers(&self, point: (i32, i32), ux: f64, uy: f64) -> bool {+ let (cx, cy) = cell_of(point);+ for dx in -1..=1 {+ for dy in -1..=1 {+ let Some(bucket) = self.cells.get(&(cx + dx, cy + dy)) else {+ continue;+ };+ for &i in bucket {+ let Some(&(other, oux, ouy)) = self.points.get(i as usize) else {+ continue;+ };+ if (ux * oux + uy * ouy).abs() < COS_FOLD {+ continue;+ }+ if super::corridor_geom::distance_m(point, other) <= CORRIDOR_M {+ return true;+ }+ }+ }+ }+ false+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn whole_lines_survive_untouched_without_corridors() {+ let line = [(0, 0), (0, 100_000)];+ let corridors = BTreeMap::new();+ let out = spans_of(+ &line,+ 1,+ &[Run { from: 0, to: 0, set: 0 }],+ &[(0, 0)],+ &[0.0],+ &[0.0, 11_132.0],+ &corridors,+ );+ assert_eq!(out.len(), 1);+ assert_eq!((out[0].ordinal, out[0].lanes, out[0].taper), (0, 1, 255));+ assert_eq!(out[0].points, line);+ }++ #[test]+ fn covered_fraction_counts_drawn_metres() {+ let mut covered = Covered::default();+ let line = [(0, 0), (0, 100_000)];+ assert_eq!(covered.covered_fraction(&line), 0.0, "nothing drawn yet");+ covered.add_tagged(&line, 1);+ assert!((covered.covered_fraction(&line) - 1.0).abs() < 1e-9, "fully drawn");+ let far = [(500_000, 0), (500_000, 100_000)];+ assert_eq!(covered.covered_fraction(&far), 0.0, "far line untouched");+ }+}
maps/src/main/rust/src/jni/transit_jni/lines.rs
diff --git a/maps/src/main/rust/src/jni/transit_jni/lines.rs b/maps/src/main/rust/src/jni/transit_jni/lines.rsindex acf5e5ddfe..2296cb8469 100644--- a/maps/src/main/rust/src/jni/transit_jni/lines.rs+++ b/maps/src/main/rust/src/jni/transit_jni/lines.rs@@ -53,8 +53,9 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_getRailLines Ok(c) => c, Err(_) => return null, };- // MUST match the RawRailLine ctor: name, color, routeType (I), feed, coords ([D).- let ctor = "(Ljava/lang/String;IILjava/lang/String;[D)V";+ // MUST match the RawRailLine ctor: name, color, routeType (I), feed,+ // coords ([D), then the corridor slot (ordinal, lanes, taper) LAST.+ let ctor = "(Ljava/lang/String;IILjava/lang/String;[DIII)V"; let array = match env.new_object_array(lines.len() as i32, &class, JObject::null()) { Ok(a) => a, Err(_) => return null,@@ -88,6 +89,9 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_getRailLines JValue::Int(l.route_type as i32), JValue::Object(&jfeed), JValue::Object(&jcoords_obj),+ JValue::Int(i32::from(l.ordinal)),+ JValue::Int(i32::from(l.lanes)),+ JValue::Int(i32::from(l.taper)), ], ) { Ok(o) => o,
maps/src/main/rust/src/lib.rs
diff --git a/maps/src/main/rust/src/lib.rs b/maps/src/main/rust/src/lib.rsindex d3731e982b..38a7360b38 100644--- a/maps/src/main/rust/src/lib.rs+++ b/maps/src/main/rust/src/lib.rs@@ -13,6 +13,10 @@ // so the wider surface costs nothing on device. pub mod geometry; pub mod graph;+mod corridor_geom;+mod corridor_grid;+mod corridor_group;+mod corridor_spans; mod jni; mod mvt; pub mod routing;
maps/src/main/rust/src/transit.rs
diff --git a/maps/src/main/rust/src/transit.rs b/maps/src/main/rust/src/transit.rsindex e788e51e73..f86ac64f77 100644--- a/maps/src/main/rust/src/transit.rs+++ b/maps/src/main/rust/src/transit.rs@@ -324,4 +324,5 @@ mod tests { include!("transit_part7.rs"); include!("transit_part8.rs"); include!("transit_part9.rs");+ include!("transit_part12.rs"); }
maps/src/main/rust/src/transit_part11.rs
diff --git a/maps/src/main/rust/src/transit_part11.rs b/maps/src/main/rust/src/transit_part11.rsindex e038a93034..d1e4575516 100644--- a/maps/src/main/rust/src/transit_part11.rs+++ b/maps/src/main/rust/src/transit_part11.rs@@ -14,7 +14,10 @@ // via `Schedule::runs`, `delayed`, `abs_time_on`) and the `HashMap` import // are all in scope without qualification, exactly as in `transit_part10.rs`. -/// One drawable rail line: the route's full shape with its agency colour.+/// One drawable rail-line span: part of a route's shape with its lane in+/// the corridor it crosses. A route outside any corridor is one span over+/// its whole shape (`ordinal` 0, `lanes` 1, `taper` 255).+#[derive(Debug)] pub struct RailLine { pub name: String, pub color: u32,@@ -22,16 +25,32 @@ pub struct RailLine { pub feed: String, /// Interleaved `[lon0, lat0, lon1, lat1, ...]`, like a `RawStep` geometry. pub coords: Vec<f64>,+ /// This colour's index among the corridor's distinct colours.+ pub ordinal: u8,+ /// Distinct colours the corridor carries. One outside a corridor.+ pub lanes: u8,+ /// How far into its lane this span sits, over 255.+ pub taper: u8, } -/// Bound on lines per query: a metro bbox holds dozens of rail routes, but an-/// unbounded world-zoom enumeration would serialize thousands of polylines.+/// Bound on spans per query: a metro bbox holds dozens of rail routes, but+/// an unbounded world-zoom enumeration would serialize thousands of+/// polylines. pub const MAX_RAIL_LINES: usize = 1500; /// Margin (degrees) matching the vehicle enumeration, so a line whose stops /// sit just off-screen still draws to the viewport edge. const RAIL_BBOX_MARGIN_DEG: f64 = 0.02; +/// A line already drawn in its colour over 95% of its length adds nothing.+const MOSTLY_DRAWN: f64 = 0.95;++/// How many distinct services may draw over one stretch of track before the+/// rest are dropped. Past the style's lane count the colours squash onto+/// shared lanes anyway; fifteen republished feeds over one railway is data+/// artefact, not fifteen services.+const MAX_SERVICES_PER_TRACK: usize = 4;+ /// Whether a GTFS `route_type` draws as a rail line. Mirrors the Kotlin /// `gtfsRouteTypeToMode` split inversely: everything except the bus family. /// Buses have shapes too, but drawing every bus polyline would bury the rail@@ -40,13 +59,28 @@ fn is_rail_line(t: u32) -> bool { !matches!(t, 3 | 800 | 200..=299 | 700..=799) } -/// Every rail line serving the bbox, with agency colours.+/// Fallback line colour per rail mode, for routes naming none. A matched+/// pair with the tile path's table in `transit_shapes`: grouping and drawing+/// must agree, or indistinguishable lines take separate lanes.+fn fallback_color(route_type: u32) -> u32 {+ match route_type {+ 1 | 400..=499 => 0xE4_002B,+ 0 | 5 | 900 => 0xFF_D200,+ 2 | 100..=199 => 0x00_57A8,+ 12 => 0x9D_9D9D,+ _ => 0x66_6666,+ }+}++/// Every rail line serving the bbox, cut into corridor spans with lanes. /// /// Shape-first: the route's fitted GTFS polyline (`route_shape_off` + /// full-span `shape_slice`); routes the ingester could not fit fall back to-/// stop-to-stop, the same fallback the ride legs use. Direction variants of-/// one GTFS route are distinct RAPTOR routes and both enumerate — the caller-/// dedups by name when it wants one line per named route.+/// stop-to-stop, the same fallback the ride legs use. Corridor assignment is+/// the tile path's algorithm (`crate::corridor_group` + `spans_of`),+/// single-threaded at viewport scale: overlapping services fan into+/// parallel lanes, 95%-redrawn duplicates drop, and no track carries more+/// than four services. pub fn rail_lines( idx: &TransitIndex, min_lat: f64,@@ -54,14 +88,24 @@ pub fn rail_lines( max_lat: f64, max_lon: f64, ) -> Vec<RailLine> {- let mut out = Vec::new(); if idx.stop_count == 0 {- return out;+ return Vec::new(); } let m = RAIL_BBOX_MARGIN_DEG; let near_bbox = |lat: f64, lon: f64| { lat >= min_lat - m && lat <= max_lat + m && lon >= min_lon - m && lon <= max_lon + m };+ // Collect serving routes with e7 shapes, deterministic order (colour,+ // name) so a rebuild fans identically.+ struct Serving {+ route_idx: u32,+ name: String,+ color: u32,+ route_type: u32,+ feed: String,+ points: Vec<(i32, i32)>,+ }+ let mut serving: Vec<Serving> = Vec::new(); for r in 0..idx.route_count { let route = idx.route(r); if route.n_stops < 2 || !is_rail_line(route.route_type) {@@ -80,47 +124,165 @@ pub fn rail_lines( } let first = route.first_route_stop; let last = first + route.n_stops - 1;- let coords: Vec<f64> = match idx.route_shape_off(r) {+ let e7: Vec<(i32, i32)> = match idx.route_shape_off(r) { Some(off) => { let fv = idx.route_stop_shape(first); let tv = idx.route_stop_shape(last); if fv == NONE || tv == NONE || tv < fv {- stop_to_stop(idx, &route)+ stop_to_stop_e7(idx, &route) } else { idx.shape_slice(off, fv, tv) .into_iter()- .flat_map(|(lat, lon)| [lon, lat])+ .map(|(lat, lon)| {+ (lat * 1e7, lon * 1e7)+ })+ .map(|(lat, lon)| (lat.round() as i32, lon.round() as i32)) .collect() } }- None => stop_to_stop(idx, &route),+ None => stop_to_stop_e7(idx, &route), };- if coords.len() < 4 {+ if e7.len() < 2 { continue; }- out.push(RailLine {+ let color =+ if route.color == 0 { fallback_color(route.route_type) } else { route.color };+ serving.push(Serving {+ route_idx: r, name: idx.read_str(route.name_off),- color: route.color,+ color, route_type: route.route_type, feed: idx.feed_name_of(route.feed_idx),- coords,+ points: e7, });- if out.len() >= MAX_RAIL_LINES {- break;+ }+ serving.sort_by(|a, b| {+ a.color.cmp(&b.color).then(a.name.cmp(&b.name)).then(a.route_idx.cmp(&b.route_idx))+ });++ // Dedup: whole lines only. A line 95% drawn in its colour adds nothing;+ // past four services over one metre the track is fully said.+ let mut kept: Vec<usize> = Vec::with_capacity(serving.len());+ let mut by_color: std::collections::HashMap<u32, crate::corridor_spans::Covered> =+ std::collections::HashMap::new();+ let mut mode_cover: std::collections::HashMap<u32, crate::corridor_spans::Covered> =+ std::collections::HashMap::new();+ for (at, s) in serving.iter().enumerate() {+ let color_cover = by_color.entry(s.color).or_default();+ if color_cover.covered_fraction(&s.points) >= MOSTLY_DRAWN {+ continue;+ }+ let mode = mode_bucket(s.route_type);+ let cover = mode_cover.entry(mode).or_default();+ if cover.crowd_reaches(&s.points, MAX_SERVICES_PER_TRACK) {+ continue;+ }+ cover.add_tagged(&s.points, s.color);+ color_cover.add_tagged(&s.points, 0);+ kept.push(at);+ }++ // Corridor assignment over the survivors.+ let candidates: Vec<crate::corridor_group::Candidate> = kept+ .iter()+ .map(|&at| crate::corridor_group::Candidate {+ points: &serving[at].points,+ route: serving[at].route_idx,+ color: serving[at].color,+ name: &serving[at].name,+ })+ .collect();+ let named: Vec<Option<(u32, &str)>> = {+ let max_route = candidates.iter().map(|c| c.route as usize + 1).max().unwrap_or(0);+ let mut named = vec![None; max_route];+ for c in &candidates {+ named[c.route as usize].get_or_insert((c.color, c.name));+ }+ named+ };+ let (_sets, runs, corridors) = crate::corridor_group::group(&candidates, &named);++ // Cut spans per survivor. Runs/samples live in candidate order; map back+ // through `kept` for route metadata.+ let mut out = Vec::new();+ // Rebuild per-candidate samples for spans_of: probe points in block+ // order with probe-space cum. The grouping port owns sampling; replay+ // the same walk here so spans cut on identical geometry.+ for (nth, &at) in kept.iter().enumerate() {+ let s = &serving[at];+ let walked = crate::corridor_geom::resample(&s.points, crate::corridor_group::SAMPLE_M);+ if walked.len() < 2 {+ continue;+ }+ let own_cum = crate::corridor_geom::cumulative(&s.points);+ // Probe-space cum: probe k sits at k*SAMPLE_M, last at the total.+ let total = own_cum.last().copied().unwrap_or(0.0);+ let probe_pts: Vec<(i32, i32)> = walked;+ let probe_cum: Vec<f64> = (0..probe_pts.len())+ .map(|k| {+ if k + 1 == probe_pts.len() {+ total+ } else {+ (k as f64 * crate::corridor_group::SAMPLE_M).min(total)+ }+ })+ .collect();+ let spans = crate::corridor_spans::spans_of(+ &s.points,+ s.color,+ runs.get(nth).map(|r| r.as_slice()).unwrap_or(&[]),+ &probe_pts,+ &probe_cum,+ &own_cum,+ &corridors,+ );+ for span in spans {+ if span.points.len() < 2 {+ continue;+ }+ out.push(RailLine {+ name: s.name.clone(),+ color: s.color,+ route_type: s.route_type,+ feed: s.feed.clone(),+ coords: span+ .points+ .iter()+ .flat_map(|&(lat, lon)| [f64::from(lon) * 1e-7, f64::from(lat) * 1e-7])+ .collect(),+ ordinal: span.ordinal,+ lanes: span.lanes,+ taper: span.taper,+ });+ if out.len() >= MAX_RAIL_LINES {+ return out;+ } } } out } -/// A route's stops joined straight, for routes with no fitted shape.-fn stop_to_stop(idx: &TransitIndex, route: &RouteRec) -> Vec<f64> {- let mut coords = Vec::with_capacity(route.n_stops as usize * 2);+/// Coarse mode bucket for the crowd ceiling: distinct rail modes each get+/// their own crowd budget, so a subway trunk and a tramway sharing track do+/// not suppress each other.+fn mode_bucket(route_type: u32) -> u32 {+ match route_type {+ 1 | 400..=499 => 1,+ 0 | 5 | 900 => 2,+ 2 | 100..=199 => 3,+ _ => 0,+ }+}++/// A route's stops joined straight, as e7 pairs, for routes with no fitted+/// shape.+fn stop_to_stop_e7(idx: &TransitIndex, route: &RouteRec) -> Vec<(i32, i32)> {+ let mut out = Vec::with_capacity(route.n_stops as usize); for pos in 0..route.n_stops { let (lat, lon) = idx.stop_ll(idx.route_stop(route.first_route_stop + pos));- coords.push(lon);- coords.push(lat);+ out.push(((lat * 1e7).round() as i32, (lon * 1e7).round() as i32)); }- coords+ out } /// One stop on a trip's itinerary, with query-day-frame times.
maps/src/main/rust/src/transit_part12.rs
diff --git a/maps/src/main/rust/src/transit_part12.rs b/maps/src/main/rust/src/transit_part12.rsnew file mode 100644index 0000000000..ba65dc69b5--- /dev/null+++ b/maps/src/main/rust/src/transit_part12.rs@@ -0,0 +1,160 @@+ // --- Corridor-bundled rail lines + trip itineraries (`transit_part11`) ---++ #[test]+ fn rail_lines_serve_a_shaped_route_with_its_colour() {+ let idx = shaped_route_pack().index();+ let lines = rail_lines(&idx, 37.69, -122.41, 37.73, -122.39);+ assert_eq!(lines.len(), 1, "the one shaped route serves the bbox");+ let l = &lines[0];+ assert_eq!(l.name, "N");+ assert_eq!(l.color, 0x0000FF);+ assert_eq!(l.feed, "sfmuni");+ // The fitted shape detours east: 5 vertices = 10 doubles, and the+ // second point must swing off the stops' shared meridian.+ assert_eq!(l.coords.len(), 10);+ assert!(l.coords[2] > -122.400, "on the eastward detour");+ }++ #[test]+ fn rail_lines_skip_a_bbox_no_stop_serves() {+ let idx = shaped_route_pack().index();+ let lines = rail_lines(&idx, 40.0, -75.0, 41.0, -74.0);+ assert!(lines.is_empty(), "far from the SF stops: nothing to draw");+ }++ #[test]+ fn trip_itinerary_lists_every_stop_with_times() {+ let idx = one_route_pack().index();+ // Vehicle id for route 0, trip 0, today: the packing active_vehicles uses.+ let id = (0i64 << 32) | (0i64 << 1) | 0;+ let itin =+ trip_itinerary(&idx, id, sched(wednesday())).expect("trip 0 runs Wednesday");+ assert_eq!(itin.route_name, "N");+ assert_eq!(itin.headsign, "Downtown");+ assert!(!itin.cancelled);+ assert_eq!(itin.stops.len(), 3);+ assert_eq!(itin.stops[0].name, "Alpha");+ assert_eq!(itin.stops[2].name, "Gamma");+ assert_eq!(+ (itin.stops[0].dep_secs, itin.stops[2].arr_secs),+ (28_800, 29_400)+ );+ // Dwell at Beta: arrives 29_100, departs 29_160.+ assert_eq!(+ (itin.stops[1].arr_secs, itin.stops[1].dep_secs),+ (29_100, 29_160)+ );+ }++ #[test]+ fn trip_itinerary_refuses_an_unknown_trip() {+ let idx = one_route_pack().index();+ // Route 9 does not exist; trip 99 neither.+ assert!(+ trip_itinerary(&idx, (9i64 << 32) | (0i64 << 1), sched(wednesday())).is_none()+ );+ assert!(+ trip_itinerary(&idx, (0i64 << 32) | (99i64 << 1), sched(wednesday())).is_none()+ );+ }++ /// Two routes over one track, in different agency colours, fan into+ /// adjacent lanes rather than stacking.+ fn two_colour_pack() -> Pack {+ let mut pack = one_route_pack();+ pack.routes.push(Route {+ name: "M",+ color: 0xFF0000,+ route_type: 0,+ feed: 0,+ pattern: vec![0, 1, 2],+ trips: vec![Trip {+ start: 28_800,+ stoptimes: vec![(28_800, 28_800), (29_100, 29_160), (29_400, 29_400)],+ service: 0,+ headsign: "Downtown",+ }],+ // Same alignment, surveyed a metre east: one corridor, not two.+ shape: Some(Shape {+ points: vec![+ (37.700, -122.39999),+ (37.705, -122.38999),+ (37.710, -122.39999),+ (37.715, -122.38999),+ (37.720, -122.39999),+ ],+ stop_vertices: vec![0, 2, 4],+ }),+ });+ pack.routes[0].shape = Some(Shape {+ points: vec![+ (37.700, -122.400),+ (37.705, -122.390),+ (37.710, -122.400),+ (37.715, -122.390),+ (37.720, -122.400),+ ],+ stop_vertices: vec![0, 2, 4],+ });+ pack+ }++ #[test]+ fn shared_track_fans_into_adjacent_lanes() {+ let idx = two_colour_pack().index();+ let lines = rail_lines(&idx, 37.69, -122.41, 37.73, -122.39);+ assert!(!lines.is_empty(), "both routes serve the bbox");+ // Every span of the two colours shares one corridor: same lane+ // count, complementary ordinals.+ let mut by_color: std::collections::HashMap<u32, Vec<(u8, u8)>> =+ std::collections::HashMap::new();+ for l in &lines {+ by_color.entry(l.color).or_default().push((l.ordinal, l.lanes));+ }+ assert_eq!(by_color.len(), 2, "both agency colours draw: {by_color:?}");+ for (color, spans) in &by_color {+ assert!(+ spans.iter().any(|&(_, lanes)| lanes == 2),+ "colour {color:06X} fans as one of two: {spans:?}"+ );+ }+ let ordinals: std::collections::HashSet<u8> =+ lines.iter().filter(|l| l.lanes == 2).map(|l| l.ordinal).collect();+ assert_eq!(ordinals, std::collections::HashSet::from([0, 1]), "{ordinals:?}");+ }++ #[test]+ fn a_byte_identical_republication_draws_once() {+ let shape_points = vec![+ (37.700, -122.400),+ (37.705, -122.390),+ (37.710, -122.400),+ (37.715, -122.390),+ (37.720, -122.400),+ ];+ let mut pack = one_route_pack();+ pack.routes[0].shape = Some(Shape {+ points: shape_points.clone(),+ stop_vertices: vec![0, 2, 4],+ });+ // Same geometry, same colour, new name: a republished feed.+ pack.routes.push(Route {+ name: "N-dup",+ color: 0x0000FF,+ route_type: 0,+ feed: 0,+ pattern: vec![0, 1, 2],+ trips: vec![Trip {+ start: 28_800,+ stoptimes: vec![(28_800, 28_800), (29_100, 29_160), (29_400, 29_400)],+ service: 0,+ headsign: "Downtown",+ }],+ shape: Some(Shape { points: shape_points, stop_vertices: vec![0, 2, 4] }),+ });+ let idx = pack.index();+ let lines = rail_lines(&idx, 37.69, -122.41, 37.73, -122.39);+ let blue: Vec<_> = lines.iter().filter(|l| l.color == 0x0000FF).collect();+ assert_eq!(blue.len(), 1, "one blue line, not two: {lines:?}");+ }+
maps/src/main/rust/src/transit_part9.rs
diff --git a/maps/src/main/rust/src/transit_part9.rs b/maps/src/main/rust/src/transit_part9.rsindex f9682113b3..6ca96f85f7 100644--- a/maps/src/main/rust/src/transit_part9.rs+++ b/maps/src/main/rust/src/transit_part9.rs@@ -5,66 +5,6 @@ /// -122.400 meridian between 37.700 and 37.720). const VEH_BBOX: (f64, f64, f64, f64) = (37.69, -122.41, 37.73, -122.39); - // --- `transit_part11`: pack-driven rail lines + trip itineraries ----- #[test]- fn rail_lines_serve_a_shaped_route_with_its_colour() {- let idx = shaped_route_pack().index();- let lines = rail_lines(&idx, 37.69, -122.41, 37.73, -122.39);- assert_eq!(lines.len(), 1, "the one shaped route serves the bbox");- let l = &lines[0];- assert_eq!(l.name, "N");- assert_eq!(l.color, 0x0000FF);- assert_eq!(l.feed, "sfmuni");- // The fitted shape detours east: 5 vertices = 10 doubles, and the- // second point must swing off the stops' shared meridian.- assert_eq!(l.coords.len(), 10);- assert!(l.coords[2] > -122.400, "on the eastward detour");- }-- #[test]- fn rail_lines_skip_a_bbox_no_stop_serves() {- let idx = shaped_route_pack().index();- let lines = rail_lines(&idx, 40.0, -75.0, 41.0, -74.0);- assert!(lines.is_empty(), "far from the SF stops: nothing to draw");- }-- #[test]- fn trip_itinerary_lists_every_stop_with_times() {- let idx = one_route_pack().index();- // Vehicle id for route 0, trip 0, today: the packing active_vehicles uses.- let id = (0i64 << 32) | (0i64 << 1) | 0;- let itin =- trip_itinerary(&idx, id, sched(wednesday())).expect("trip 0 runs Wednesday");- assert_eq!(itin.route_name, "N");- assert_eq!(itin.headsign, "Downtown");- assert!(!itin.cancelled);- assert_eq!(itin.stops.len(), 3);- assert_eq!(itin.stops[0].name, "Alpha");- assert_eq!(itin.stops[2].name, "Gamma");- assert_eq!(- (itin.stops[0].dep_secs, itin.stops[2].arr_secs),- (28_800, 29_400)- );- // Dwell at Beta: arrives 29_100, departs 29_160.- assert_eq!(- (itin.stops[1].arr_secs, itin.stops[1].dep_secs),- (29_100, 29_160)- );- }-- #[test]- fn trip_itinerary_refuses_an_unknown_trip() {- let idx = one_route_pack().index();- // Route 9 does not exist; trip 99 neither.- assert!(- trip_itinerary(&idx, (9i64 << 32) | (0i64 << 1), sched(wednesday())).is_none()- );- assert!(- trip_itinerary(&idx, (0i64 << 32) | (99i64 << 1), sched(wednesday())).is_none()- );- }- #[test] fn a_vehicle_sits_exactly_on_a_stop_at_its_scheduled_time() { let idx = one_route_pack().index();
maps/src/test/java/com/vayunmathur/maps/ui/map/RailFanTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/RailFanTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/RailFanTest.ktnew file mode 100644index 0000000000..904fde9262--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/RailFanTest.kt@@ -0,0 +1,73 @@+package com.vayunmathur.maps.ui.map++import com.vayunmathur.library.map.GeoPoint+import kotlin.math.abs+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * The host-side corridor fan: lane counts step with the zoom bands, offsets+ * squash from the middle, tapers ease mouth pieces. Ported from the tile+ * style (`transit-rail`: spread 6.0, lanes ramp `[[0,1],[9,2],[11,3],[13,4]]`,+ * `lane_offset_px`), so the pack overlay fans exactly like the tile layer.+ */+class RailFanTest {++ @Test+ fun `lane count steps at the style bands`() {+ assertEquals(1, railLaneCount(0.0))+ assertEquals(1, railLaneCount(8.9))+ assertEquals(2, railLaneCount(9.0))+ assertEquals(2, railLaneCount(10.0))+ assertEquals(3, railLaneCount(11.0))+ assertEquals(3, railLaneCount(12.0))+ assertEquals(4, railLaneCount(13.0))+ assertEquals(4, railLaneCount(16.0))+ }++ @Test+ fun `a lone line never offsets`() {+ assertEquals(0.0, railLaneOffsetDp(13.0, 0, 1, 255))+ assertEquals(0.0, railLaneOffsetDp(13.0, 0, 1, 0))+ }++ @Test+ fun `two lanes split symmetrically`() {+ assertEquals(-3.0, railLaneOffsetDp(13.0, 0, 2, 255))+ assertEquals(3.0, railLaneOffsetDp(13.0, 1, 2, 255))+ }++ @Test+ fun `six colours squash from the middle`() {+ // The tile oracle: 0,1,1,2,2,3 — edges keep lanes, middle doubles.+ val offsets = (0 until 6).map { railLaneOffsetDp(13.0, it, 6, 255) }+ assertEquals(listOf(-9.0, -3.0, -3.0, 3.0, 3.0, 9.0), offsets)+ }++ @Test+ fun `taper scales the offset linearly`() {+ assertEquals(0.0, railLaneOffsetDp(13.0, 1, 2, 0))+ val half = railLaneOffsetDp(13.0, 1, 2, 128)+ assertTrue(abs(half - 3.0 * 128 / 255) < 1e-9, "$half")+ }++ @Test+ fun `offset polyline shifts right of travel`() {+ // Due-north line: right of travel is east.+ val line = listOf(GeoPoint(-122.4, 37.7), GeoPoint(-122.4, 37.71))+ val shifted = offsetPolyline(line, 10.0)+ assertEquals(2, shifted.size)+ assertTrue(shifted[0].longitude > -122.4, "east of the line")+ assertTrue(abs(shifted[0].latitude - 37.7) < 1e-9, "latitude unchanged")+ // ~10 m east at this latitude.+ val east = (shifted[0].longitude + 122.4) * 111_320.0 * 0.79+ assertTrue(abs(east - 10.0) < 0.5, "$east")+ }++ @Test+ fun `zero offset returns the line untouched`() {+ val line = listOf(GeoPoint(-122.4, 37.7), GeoPoint(-122.4, 37.71))+ assertEquals(line, offsetPolyline(line, 0.0))+ }+}