Modern Apps git

← Modern-Apps.git

maps: plan transit journeys from the offline GTFS pack

Commit
c2e4478f5471af87c49d600a4b700c28a724a6df
Author
vayun-mathur <[email protected]>
When
2026-08-21 00:59 UTC (3 months ago)
Parents
93b0d7f

Diff

maps/src/main/java/com/vayunmathur/maps/MainActivity.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt b/maps/src/main/java/com/vayunmathur/maps/MainActivity.ktindex 734f0329f2..c73c8ba64e 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -214,7 +214,7 @@ class MainActivity : ComponentActivity() {             }              val computed = try {-                OfflineRouter.getRouteMulti(applicationContext, route, origin, mode)+                OfflineRouter.getRouteForMode(applicationContext, route, origin, mode)             } catch (e: Exception) {                 Log.w(TAG, "navigateTo: routing failed", e); null             }
maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.ktindex 94c9f26a8e..eec9ce8879 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt@@ -1,6 +1,5 @@ package com.vayunmathur.maps.ui -import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row@@ -11,7 +10,6 @@ import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items-import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableLongStateOf@@ -19,7 +17,6 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier-import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight@@ -145,21 +142,6 @@ private fun DepartureList(departures: List<Departure>, now: Long) {     } } -@Composable-private fun LineBadge(line: String, routeColor: String?) {-    val bg = parseHexColor(routeColor) ?: MaterialTheme.colorScheme.primary-    Text(-        text = line.ifBlank { "—" },-        style = MaterialTheme.typography.labelLarge,-        fontWeight = FontWeight.Bold,-        color = onColorFor(bg),-        modifier = Modifier-            .clip(RoundedCornerShape(6.dp))-            .background(bg)-            .padding(horizontal = 8.dp, vertical = 2.dp),-    )-}- @Composable private fun DepartureRow(dep: Departure, now: Long) {     Row(@@ -231,18 +213,6 @@ private fun delayColor(delayMinutes: Int): Color = when {     else -> DELAY_LATE } -/** Parse a 6-digit hex (with or without `#`) → [Color], or null. */-private fun parseHexColor(hex: String?): Color? {-    if (hex.isNullOrBlank()) return null-    return runCatching { Color(android.graphics.Color.parseColor("#" + hex.removePrefix("#"))) }.getOrNull()-}--/** Readable text colour (black/white) for a coloured badge background. */-private fun onColorFor(bg: Color): Color {-    val luminance = 0.299 * bg.red + 0.587 * bg.green + 0.114 * bg.blue-    return if (luminance > 0.6) Color.Black else Color.White-}- /** A once-per-15s ticker that reports the current epoch millis to [onTick]. */ @Composable private fun LaunchedEffectTicker(onTick: (Long) -> Unit) {
maps/src/main/java/com/vayunmathur/maps/ui/LineBadge.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/LineBadge.kt b/maps/src/main/java/com/vayunmathur/maps/ui/LineBadge.ktnew file mode 100644index 0000000000..73f79ce412--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/LineBadge.kt@@ -0,0 +1,51 @@+package com.vayunmathur.maps.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++/**+ * The coloured transit line chip, shared by the departure board+ * ([DeparturesSheet]) and the transit directions list (`RouteSheet`) so both+ * render a line the same way.+ */+@Composable+fun LineBadge(line: String, routeColor: String?, modifier: Modifier = Modifier) {+    val bg = parseHexColor(routeColor) ?: MaterialTheme.colorScheme.primary+    Text(+        text = line.ifBlank { "—" },+        style = MaterialTheme.typography.labelLarge,+        fontWeight = FontWeight.Bold,+        color = onColorFor(bg),+        modifier = modifier+            .clip(RoundedCornerShape(6.dp))+            .background(bg)+            .padding(horizontal = 8.dp, vertical = 2.dp),+    )+}++/**+ * Parse a 6-digit hex colour → [Color], or null when absent/malformed. Accepts+ * it with or without a leading `#`: `Departure.routeColor` has none while+ * `TransitLine.color` always does.+ */+fun parseHexColor(hex: String?): Color? {+    if (hex.isNullOrBlank()) return null+    return runCatching {+        Color(android.graphics.Color.parseColor("#" + hex.removePrefix("#")))+    }.getOrNull()+}++/** Readable text colour (black/white) for a coloured badge background. */+fun onColorFor(bg: Color): Color {+    val luminance = 0.299 * bg.red + 0.587 * bg.green + 0.114 * bg.blue+    return if (luminance > 0.6) Color.Black else Color.White+}
maps/src/main/java/com/vayunmathur/maps/util/GTFSProvider.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/GTFSProvider.kt b/maps/src/main/java/com/vayunmathur/maps/util/GTFSProvider.ktindex 4f525bcf2c..b1629d3483 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/GTFSProvider.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/GTFSProvider.kt@@ -1,6 +1,7 @@ package com.vayunmathur.maps.util  import android.content.Context+import android.util.Log import java.util.concurrent.ConcurrentHashMap  object GTFSProvider {@@ -18,7 +19,7 @@ object GTFSProvider {             val assetPath = "$feedName/routes.txt"             context.assets.open(assetPath).use { inputStream ->                 val reader = inputStream.bufferedReader()-                val header = reader.readLine()?.split(",") ?: return null+                val header = parseCsvLine(reader.readLine() ?: return null).map { it.trim() }                 val shortNameIdx = header.indexOf("route_short_name")                 val longNameIdx = header.indexOf("route_long_name")                 val colorIdx = header.indexOf("route_color")@@ -27,7 +28,7 @@ object GTFSProvider {                  var line: String?                 while (reader.readLine().also { line = it } != null) {-                    val parts = line!!.split(",")+                    val parts = parseCsvLine(line ?: continue)                     val shortName = if (shortNameIdx != -1) parts.getOrNull(shortNameIdx) else null                     val longName = if (longNameIdx != -1) parts.getOrNull(longNameIdx) else null @@ -42,8 +43,47 @@ object GTFSProvider {                 }             }         } catch (e: Exception) {-            // Asset not found or read error+            Log.w("GTFSProvider", "Failed to read routes.txt for $feedName", e)         }         return null     }++    /**+     * Split one RFC 4180 CSV record into fields, honouring double-quoted fields+     * that contain commas (GTFS routinely quotes `route_long_name`, e.g.+     * `"Judah, Ocean Beach"`) and `""` escapes. A leading UTF-8 BOM is stripped.+     * Records with embedded newlines are not supported — this is line-oriented,+     * which is fine for the short rows in `routes.txt`.+     */+    internal fun parseCsvLine(line: String): List<String> {+        val fields = mutableListOf<String>()+        val current = StringBuilder()+        var inQuotes = false+        var i = 0+        if (line.startsWith('\uFEFF')) i = 1+        while (i < line.length) {+            val c = line[i]+            when {+                inQuotes ->+                        when {+                            c == '"' && i + 1 < line.length && line[i + 1] == '"' -> {+                                current.append('"')+                                i+++                            }+                            c == '"' -> inQuotes = false+                            else -> current.append(c)+                        }+                c == '"' -> inQuotes = true+                c == ',' -> {+                    fields.add(current.toString())+                    current.setLength(0)+                }+                c == '\r' -> {} // trailing CR from a CRLF file+                else -> current.append(c)+            }+            i+++        }+        fields.add(current.toString())+        return fields+    } }
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 2b536fcf37..87b45f60d0 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt@@ -4,9 +4,11 @@ import android.content.Context import android.util.Log import androidx.annotation.Keep import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.util.ConnectivityMonitor import com.vayunmathur.maps.R import com.vayunmathur.maps.data.SpecificFeature import com.vayunmathur.maps.data.transit.Departure+import com.vayunmathur.maps.data.transit.TransitousDataSource import java.io.File import java.io.OutputStream import java.net.InetAddress@@ -16,6 +18,9 @@ import java.util.concurrent.Executors import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking@@ -91,21 +96,30 @@ object OfflineRouter {         }     } -    private external fun init(basePath: String, presentFeeds: Array<String>): Boolean+    private external fun init(basePath: String): Boolean     private external fun findRouteNative(             sLat: Double,             sLon: Double,             eLat: Double,             eLon: Double,-            mode: Int,-            startTime: Long+            mode: Int     ): Array<RawStep>?     /**      * Offline transit journey planning (P11b): RAPTOR over the per-region      * `<feed>.transit` index at `<basePath>/<feed>.transit`. `depSecs` is seconds-     * since local midnight, `weekday` is 0=Mon..6=Sun, `date` is yyyymmdd.-     * Returns walk + ride legs as [RawStep]s, or null when the feed is missing,-     * doesn't cover the endpoints, or no journey exists.+     * since midnight, `weekday` is 0=Mon..6=Sun, `date` is yyyymmdd — all in the+     * **feed's** timezone (see [getFeedTimezoneNative]), since the index is+     * world-merged. `prevWeekday`/`prevDate` describe the preceding service day,+     * whose GTFS `>24:00:00` trips run into the query day.+     *+     * `overlay*` carry MOTIS realtime so the planner skips cancelled trips and+     * uses live times; pass empty arrays for a schedule-only plan.+     * `overlayCoords` is interleaved `[lat, lon, ...]` and `overlayTimes` is+     * interleaved `[schedSecs, delaySecs, cancelled, ...]`, both parallel to+     * `overlayRoutes`.+     *+     * Returns walk + wait + ride legs as [RawStep]s, or null when the feed is+     * missing, doesn't cover the endpoints, or no journey exists.      */     private external fun findTransitRouteNative(             basePath: String,@@ -116,12 +130,17 @@ object OfflineRouter {             eLon: Double,             depSecs: Int,             weekday: Int,-            date: Int+            date: Int,+            prevWeekday: Int,+            prevDate: Int,+            overlayCoords: DoubleArray,+            overlayRoutes: Array<String>,+            overlayTimes: IntArray     ): Array<RawStep>?     /**-     * Offline scheduled departure board (no internet): upcoming departures from-     * the stop nearest `(lat,lon)` in `<basePath>/<feed>.transit`. `depSecs` is-     * seconds since local midnight, `weekday` 0=Mon..6=Sun, `date` yyyymmdd.+     * Offline scheduled departure board: upcoming departures from the stop+     * nearest `(lat,lon)` in `<basePath>/<feed>.transit`. Time and overlay+     * arguments are as in [findTransitRouteNative].      * Returns null when the feed is missing or doesn't cover the point.      */     private external fun getStopDeparturesNative(@@ -132,8 +151,24 @@ object OfflineRouter {             depSecs: Int,             weekday: Int,             date: Int,+            prevWeekday: Int,+            prevDate: Int,+            overlayCoords: DoubleArray,+            overlayRoutes: Array<String>,+            overlayTimes: IntArray,             max: Int     ): Array<RawDeparture>?+    /**+     * IANA timezone of the feed covering `(lat,lon)` in the given pack, or null+     * when the pack is stale/absent, doesn't cover the point, or its GTFS had no+     * `agency.txt`. Callers resolve this before deriving any query times.+     */+    private external fun getFeedTimezoneNative(+            basePath: String,+            feed: String,+            lat: Double,+            lon: Double+    ): String?     private external fun updateTrafficNative(             edgeIds: LongArray,             speeds: ByteArray,@@ -236,7 +271,18 @@ object OfflineRouter {             val stopCount: Int,             /** Packed turn lanes: one int per lane, `dirMask * 2 + valid`, where              * `dirMask` is a bitmask of Maneuver ordinals the lane offers. */-            val lanePacked: IntArray+            val lanePacked: IntArray,+            // Transit-only tail. The JNI ctor descriptor is shared with the+            // driving path, which passes null/0 — keep these LAST so adding to+            // them never renumbers the arguments above.+            /** GTFS `trip_headsign` of the ridden trip. */+            val headsign: String?,+            /** GTFS `route_color` packed as 0xRRGGBB, or 0 when absent. */+            val routeColor: Int,+            /** Departure, seconds since feed-local midnight (0 when unknown). */+            val depSecs: Int,+            /** Arrival, seconds since feed-local midnight (0 when unknown). */+            val arrSecs: Int,     )      /** One offline scheduled departure from the baked `.transit` index. */@@ -251,10 +297,33 @@ object OfflineRouter {             val routeColor: Int,             /** GTFS route_type. */             val routeType: Int,-            /** Seconds since local (service-day) midnight. */-            val depSecs: Int+            /** Scheduled departure, seconds since feed-local midnight. */+            val depSecs: Int,+            /** Realtime shift in seconds; 0 without live data. */+            val delaySecs: Int,+            val cancelled: Boolean,+            /** Whether the realtime overlay covered this departure. */+            val realTime: Boolean     ) +    /**+     * MOTIS realtime, flattened for the JNI overlay arguments. [coords] is+     * interleaved `[lat, lon, ...]`, [times] is interleaved+     * `[schedSecs, delaySecs, cancelled, ...]`, and both are parallel to+     * [routes]. Empty means "plan against the schedule only".+     */+    private class Overlay(+            val coords: DoubleArray,+            val routes: Array<String>,+            val times: IntArray,+    ) {+        val isEmpty: Boolean get() = routes.isEmpty()++        companion object {+            val EMPTY = Overlay(DoubleArray(0), emptyArray(), IntArray(0))+        }+    }+     private var isInitialized = false     /** Base dir (external files) holding downloaded packs incl. `*.transit`. */     private var basePath: String? = null@@ -266,11 +335,7 @@ object OfflineRouter {         basePath = path         Log.d("OfflineRouter", "Initializing with path: $path") -        val presentFeeds = context.assets.list("")?.filter {-            try { context.assets.list(it)?.contains("routes.txt") == true } catch(_: Exception) { false }-        }?.toTypedArray() ?: emptyArray()--        isInitialized = init(path, presentFeeds)+        isInitialized = init(path)         Log.d("OfflineRouter", "Initialization result: $isInitialized")         cacheDirPath = context.cacheDir.absolutePath     }@@ -287,17 +352,36 @@ object OfflineRouter {         initialize(context)     } -    suspend fun getRoute(+    /**+     * Plan a route for any [mode]. TRANSIT goes to the on-device RAPTOR planner+     * (falling back to the online MOTIS planner); every other mode goes to the+     * road graph via [getRouteMulti].+     *+     * This is the **only** correct entry point for a caller whose mode is not a+     * literal: the road graph carries no timetable, so TRANSIT must never reach+     * [getRouteMulti]. Routing every mode-agnostic caller through here is what+     * guarantees that.+     */+    suspend fun getRouteForMode(             context: Context,             route: SpecificFeature.Route,             userPosition: Position,-            type: RouteService.TravelMode-    ): RouteService.Route =-            withContext(Dispatchers.Default) {-                val start = route.waypoints.first()?.position ?: userPosition-                val end = route.waypoints.last()?.position ?: userPosition-                return@withContext getRoute(context, start, end, type)-            }+            mode: RouteService.TravelMode,+    ): RouteService.Route? = withContext(Dispatchers.Default) {+        if (mode != RouteService.TravelMode.TRANSIT) {+            return@withContext getRouteMulti(context, route, userPosition, mode)+        }+        val positions = route.waypoints.map { it?.position ?: userPosition }+        if (positions.size < 2) return@withContext null+        val start = positions.first()+        val end = positions.last()+        getTransitRouteOffline(context, start, end)+                ?: if (ConnectivityMonitor.isOnline(context)) {+                    TransitousDataSource.planRoute(start, end)+                } else {+                    null+                }+    }      /**      * Offline-only multi-waypoint chaining. Replaces the old server-side@@ -340,6 +424,12 @@ object OfflineRouter {      * planner over any downloaded per-region `*.transit` index that covers the      * endpoints. Returns null when no index is present/covering or no journey is      * found — the caller then falls back to the P10 online Transitous planner.+     *+     * Runs at most **two** RAPTOR passes: a schedule-only plan, then, when the+     * device is online, a replan against MOTIS realtime for the stops that plan+     * actually touches, so a cancelled or badly delayed trip is avoided. If the+     * replan finds nothing we keep the schedule-only journey rather than+     * iterating.      */     suspend fun getTransitRouteOffline(             context: Context,@@ -354,40 +444,104 @@ object OfflineRouter {                 ?: emptyList()         if (feeds.isEmpty()) return@withContext null -        val now = java.util.Calendar.getInstance()-        val depSecs = now.get(java.util.Calendar.HOUR_OF_DAY) * 3600 +-                now.get(java.util.Calendar.MINUTE) * 60 +-                now.get(java.util.Calendar.SECOND)-        // Calendar: SUNDAY=1..SATURDAY=7 -> Mon=0..Sun=6 for the index masks.-        val weekday = (now.get(java.util.Calendar.DAY_OF_WEEK) + 5) % 7-        val date = now.get(java.util.Calendar.YEAR) * 10000 +-                (now.get(java.util.Calendar.MONTH) + 1) * 100 +-                now.get(java.util.Calendar.DAY_OF_MONTH)-         for (feed in feeds) {-            val raw = try {-                findTransitRouteNative(-                        base, feed,-                        start.latitude, start.longitude,-                        end.latitude, end.longitude,-                        depSecs, weekday, date-                )-            } catch (_: Exception) {-                null-            }-            if (raw != null && raw.isNotEmpty()) {-                return@withContext buildRoute(context, raw, RouteService.TravelMode.TRANSIT)+            // The index is world-merged, so query times must be in the feed's+            // timezone. Journeys spanning two zones use the origin's — a known+            // limitation, but far better than always using the device's.+            val clock = transitClock(+                    runCatching {+                        getFeedTimezoneNative(base, feed, start.latitude, start.longitude)+                    }.getOrNull()+            )+            val plan = { overlay: Overlay ->+                try {+                    findTransitRouteNative(+                            base, feed,+                            start.latitude, start.longitude,+                            end.latitude, end.longitude,+                            clock.depSecs, clock.weekday, clock.date,+                            clock.prevWeekday, clock.prevDate,+                            overlay.coords, overlay.routes, overlay.times+                    )+                } catch (_: Exception) {+                    null+                }             }++            val scheduled = plan(Overlay.EMPTY)+            if (scheduled == null || scheduled.isEmpty()) continue++            val overlay = realtimeOverlay(context, journeyStops(scheduled), clock)+            val raw = if (overlay.isEmpty) scheduled else plan(overlay) ?: scheduled+            return@withContext buildRoute(context, raw, RouteService.TravelMode.TRANSIT)         }         null     }      /**-     * Offline scheduled departure board: upcoming departures for the stop nearest-     * `(lat,lon)` from any downloaded `*.transit` index covering it. Scheduled-     * times only (`realTime=false`); the online Transitous board (which already-     * carries GTFS-RT delays) is preferred when the device is online — this is-     * the no-internet fallback. Returns an empty list when nothing is available.+     * Board and alight coordinates of every ride in a planned journey. A ride+     * leg's geometry runs through its stops, so the first and last points are+     * exactly the two stops whose realtime we need.+     */+    private fun journeyStops(steps: Array<RawStep>): List<Position> =+            steps.filter { it.isTransit && it.geometry.size >= 4 }+                    .flatMap { s ->+                        val g = s.geometry+                        listOf(+                                Position(g[0], g[1]),+                                Position(g[g.size - 2], g[g.size - 1]),+                        )+                    }+                    .distinct()++    /**+     * Fetch MOTIS boards for [stops] concurrently and flatten them into an+     * [Overlay]. Returns [Overlay.EMPTY] when the device is offline — without+     * that gate every offline plan would pay a full HTTP timeout per stop before+     * `runCatching` swallowed it.+     */+    private suspend fun realtimeOverlay(+            context: Context,+            stops: List<Position>,+            clock: TransitClock,+    ): Overlay {+        if (stops.isEmpty() || !ConnectivityMonitor.isOnline(context)) return Overlay.EMPTY+        val boards = coroutineScope {+            stops.map { p ->+                async(Dispatchers.IO) {+                    p to runCatching {+                        TransitousDataSource.departuresNear(p.latitude, p.longitude)+                    }.getOrDefault(emptyList())+                }+            }.awaitAll()+        }++        val coords = mutableListOf<Double>()+        val routes = mutableListOf<String>()+        val times = mutableListOf<Int>()+        for ((pos, deps) in boards) {+            for (d in deps) {+                if (d.line.isBlank()) continue+                val delaySecs = ((d.realtimeMillis - d.scheduledMillis) / 1000L).toInt()+                if (delaySecs == 0 && !d.cancelled) continue+                coords.add(pos.latitude)+                coords.add(pos.longitude)+                routes.add(d.line)+                times.add(((d.scheduledMillis - clock.midnightMillis) / 1000L).toInt())+                times.add(delaySecs)+                times.add(if (d.cancelled) 1 else 0)+            }+        }+        if (routes.isEmpty()) return Overlay.EMPTY+        return Overlay(coords.toDoubleArray(), routes.toTypedArray(), times.toIntArray())+    }++    /**+     * Departure board from the baked `*.transit` index for the stop nearest+     * `(lat,lon)`. Scheduled times come from the pack; when the device is online+     * the MOTIS board for that stop is folded in as a realtime overlay, so+     * `delayMinutes`/`realTime`/`cancelled` are live. Returns an empty list when+     * no pack covers the point.      */     suspend fun getStopDeparturesOffline(             context: Context,@@ -403,48 +557,42 @@ object OfflineRouter {                 ?: emptyList()         if (feeds.isEmpty()) return@withContext emptyList() -        val now = java.util.Calendar.getInstance()-        val depSecs = now.get(java.util.Calendar.HOUR_OF_DAY) * 3600 +-                now.get(java.util.Calendar.MINUTE) * 60 +-                now.get(java.util.Calendar.SECOND)-        val weekday = (now.get(java.util.Calendar.DAY_OF_WEEK) + 5) % 7-        val date = now.get(java.util.Calendar.YEAR) * 10000 +-                (now.get(java.util.Calendar.MONTH) + 1) * 100 +-                now.get(java.util.Calendar.DAY_OF_MONTH)-        // Epoch millis of local midnight, so depSecs -> absolute scheduled time.-        now.set(java.util.Calendar.HOUR_OF_DAY, 0)-        now.set(java.util.Calendar.MINUTE, 0)-        now.set(java.util.Calendar.SECOND, 0)-        now.set(java.util.Calendar.MILLISECOND, 0)-        val midnightMillis = now.timeInMillis-         val all = mutableListOf<Departure>()         for (feed in feeds) {+            val clock = transitClock(+                    runCatching { getFeedTimezoneNative(base, feed, lat, lon) }.getOrNull()+            )+            val overlay = realtimeOverlay(context, listOf(Position(lon, lat)), clock)             val raw = try {-                getStopDeparturesNative(base, feed, lat, lon, depSecs, weekday, date, max)+                getStopDeparturesNative(+                        base, feed, lat, lon,+                        clock.depSecs, clock.weekday, clock.date,+                        clock.prevWeekday, clock.prevDate,+                        overlay.coords, overlay.routes, overlay.times, max+                )             } catch (_: Exception) {                 null             } ?: continue             for (d in raw) {-                val scheduled = midnightMillis + d.depSecs.toLong() * 1000L+                val scheduled = clock.midnightMillis + d.depSecs.toLong() * 1000L                 all.add(                         Departure(                                 line = d.routeName,                                 headsign = d.headsign,                                 scheduledMillis = scheduled,-                                realtimeMillis = scheduled,-                                delayMinutes = 0,-                                realTime = false,+                                realtimeMillis = scheduled + d.delaySecs * 1000L,+                                delayMinutes = d.delaySecs / 60,+                                realTime = d.realTime,                                 platform = null,                                 mode = gtfsRouteTypeToMode(d.routeType),                                 routeColor = if (d.routeColor == 0) null                                              else String.format("%06X", d.routeColor and 0xFFFFFF),-                                cancelled = false,+                                cancelled = d.cancelled,                         )                 )             }         }-        all.sortBy { it.scheduledMillis }+        all.sortBy { it.realtimeMillis }         all.take(max)     } @@ -475,20 +623,13 @@ object OfflineRouter {                 }                 Log.d("OfflineRouter", "isInitialized=$isInitialized") -                val now = java.util.Calendar.getInstance()-                val secondsSinceMidnight = now.get(java.util.Calendar.HOUR_OF_DAY) * 3600 +-                        now.get(java.util.Calendar.MINUTE) * 60 +-                        now.get(java.util.Calendar.SECOND)-                val startTime10ms = secondsSinceMidnight * 100L-                 val rawSteps =                         findRouteNative(                                 start.latitude,                                 start.longitude,                                 end.latitude,                                 end.longitude,-                                mode.ordinal,-                                startTime10ms+                                mode.ordinal                         )                                 ?: throw IllegalStateException("No route found") @@ -740,15 +881,23 @@ object OfflineRouter {                                     lanes = lanes,                                     transitDetails = if (raw.isTransit && raw.gtfsFeed != null && raw.stopCode != null) {                                         RouteService.API.TransitDetails(-                                            headsign = "", // Not stored yet+                                            headsign = raw.headsign ?: "",                                             stopCount = raw.stopCount,                                             transitLine = RouteService.API.TransitLine(                                                 name = raw.roadName,-                                                color = raw.gtfsFeed.let { GTFSProvider.getRouteColor(context, it, raw.roadName) } ?: "#FF0000"+                                                // The index carries route_color for+                                                // every feed; GTFSProvider only sees+                                                // the bundled APK asset feed, so it is+                                                // just a fallback now.+                                                color = raw.routeColor+                                                    .takeIf { it != 0 }+                                                    ?.let { "#%06X".format(it and 0xFFFFFF) }+                                                    ?: GTFSProvider.getRouteColor(context, raw.gtfsFeed, raw.roadName)+                                                    ?: "#FF0000"                                             ),                                             stopDetails = RouteService.API.StopDetails(-                                                arrivalTime = "",-                                                departureTime = "",+                                                arrivalTime = formatServiceTime(raw.arrSecs),+                                                departureTime = formatServiceTime(raw.depSecs),                                                 arrivalStop = RouteService.API.Stop(raw.endStopCode ?: ""),                                                 departureStop = RouteService.API.Stop(raw.stopCode)                                             ),
maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.ktindex ffadaf1386..1e7ce6c5b0 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt@@ -150,18 +150,11 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli                 // TRANSIT prefers the on-device RAPTOR planner over any                 // downloaded region index (P11d); if none covers the trip, it                 // falls back to the P10 online Transitous (MOTIS) planner.+                // getRouteForMode owns that split so the road graph, which has no+                // timetable, never sees TRANSIT.                 RouteService.TravelMode.entries.forEach { mode ->                     val result = try {-                        if (mode == RouteService.TravelMode.TRANSIT) {-                            val positions = routeFeature.waypoints.map { it?.position ?: pos }-                            val start = positions.first()-                            val end = positions.last()-                            OfflineRouter.getTransitRouteOffline(application, start, end)-                                ?: com.vayunmathur.maps.data.transit.TransitousDataSource-                                    .planRoute(start, end)-                        } else {-                            OfflineRouter.getRouteMulti(application, routeFeature, pos, mode)-                        }+                        OfflineRouter.getRouteForMode(application, routeFeature, pos, mode)                     } catch (_: Exception) {                         null                     }
maps/src/main/java/com/vayunmathur/maps/util/TransitClock.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/TransitClock.kt b/maps/src/main/java/com/vayunmathur/maps/util/TransitClock.ktnew file mode 100644index 0000000000..f391a7767a--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/TransitClock.kt@@ -0,0 +1,62 @@+package com.vayunmathur.maps.util++import java.time.LocalDate+import java.time.ZoneId+import java.time.ZonedDateTime+import java.util.Locale++/**+ * Query-time fields for the offline transit index, all derived in one timezone.+ * [weekday] is 0=Mon..6=Sun to match the index's service masks, [date] is+ * `yyyymmdd`, and `prev*` describe the preceding service day (GTFS trips stored+ * as `24:30:00` belong to it but run in this one).+ *+ * Lives outside [OfflineRouter] so it can be unit-tested: that object's+ * initializer loads the native library.+ */+internal data class TransitClock(+    val depSecs: Int,+    val weekday: Int,+    val date: Int,+    val prevWeekday: Int,+    val prevDate: Int,+    /** Epoch millis of midnight in that zone, so `depSecs` is absolute. */+    val midnightMillis: Long,+)++/**+ * Derive a [TransitClock] in IANA zone [zoneId] at [now], falling back to the+ * device zone when [zoneId] is null or unknown. The `.transit` index is+ * world-merged, so using the device zone for a distant feed picks trips hours+ * off.+ */+internal fun transitClock(+    zoneId: String?,+    now: (ZoneId) -> ZonedDateTime = { ZonedDateTime.now(it) },+): TransitClock {+    val zone = zoneId?.let { runCatching { ZoneId.of(it) }.getOrNull() } ?: ZoneId.systemDefault()+    val at = now(zone)+    val today = at.toLocalDate()+    val yesterday = today.minusDays(1)+    return TransitClock(+        depSecs = at.toLocalTime().toSecondOfDay(),+        // DayOfWeek is Mon=1..Sun=7.+        weekday = today.dayOfWeek.value - 1,+        date = yyyymmdd(today),+        prevWeekday = yesterday.dayOfWeek.value - 1,+        prevDate = yyyymmdd(yesterday),+        midnightMillis = today.atStartOfDay(zone).toInstant().toEpochMilli(),+    )+}++private fun yyyymmdd(d: LocalDate): Int = d.year * 10000 + d.monthValue * 100 + d.dayOfMonth++/**+ * Format a GTFS service-day time (which may exceed 86400 for a trip running+ * past midnight) as a wall clock `HH:mm`. Empty for a missing time.+ */+internal fun formatServiceTime(secs: Int): String {+    if (secs <= 0) return ""+    val s = secs % 86_400+    return "%02d:%02d".format(Locale.ROOT, s / 3600, (s % 3600) / 60)+}
maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.ktindex a676b922a7..aa1c317533 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt@@ -3,6 +3,7 @@ package com.vayunmathur.maps.util import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.util.ConnectivityMonitor import com.vayunmathur.maps.data.transit.Departure import com.vayunmathur.maps.data.transit.TransitStop import com.vayunmathur.maps.data.transit.TransitousDataSource@@ -39,7 +40,11 @@ import kotlin.math.abs  *    [refresh]. The live countdown itself is computed client-side in the sheet  *    from each departure's epoch time, so no polling is needed here.  *- * All network is on [Dispatchers.IO]. ONLINE-ONLY (P11 adds offline).+ * All network is on [Dispatchers.IO], and is skipped entirely when+ * [ConnectivityMonitor] reports no validated internet — otherwise every offline+ * lookup pays a full HTTP timeout. The departure board is offline-first: the+ * baked `.transit` pack supplies the schedule and MOTIS supplies the realtime+ * overlay on top of it.  */ class TransitStopsViewModel(application: Application) : AndroidViewModel(application) { @@ -53,7 +58,10 @@ class TransitStopsViewModel(application: Application) : AndroidViewModel(applica         .filterNotNull()         .debounce(DEBOUNCE_MS)         .distinctUntilChanged()-        .mapLatest { b -> TransitousDataSource.stopsInBbox(b.south, b.west, b.north, b.east) }+        .mapLatest { b ->+            if (!ConnectivityMonitor.isOnline(getApplication())) emptyList()+            else TransitousDataSource.stopsInBbox(b.south, b.west, b.north, b.east)+        }         .flowOn(Dispatchers.IO)         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList()) @@ -88,18 +96,22 @@ class TransitStopsViewModel(application: Application) : AndroidViewModel(applica                     flow {                         emit(DeparturesState.Loading(stop))                         val force = tick > 0-                        val online = TransitousDataSource.departures(stop.id, force = force)-                        // Offline scheduled fallback (no internet / feed gap): the-                        // online board already carries GTFS-RT delays, so only fall-                        // back to the baked .transit schedule when it's empty.-                        val deps = if (online.isNotEmpty()) {-                            online-                        } else {-                            runCatching {-                                OfflineRouter.getStopDeparturesOffline(-                                    getApplication(), stop.lat, stop.lon,-                                )-                            }.getOrDefault(emptyList())+                        // Offline-first now that the baked board folds MOTIS+                        // realtime in as an overlay: the pack has the complete+                        // schedule, the overlay supplies the live delays. Fall+                        // back to the pure online board only when no pack covers+                        // this stop.+                        val offline = runCatching {+                            OfflineRouter.getStopDeparturesOffline(+                                getApplication(), stop.lat, stop.lon,+                            )+                        }.getOrDefault(emptyList())+                        val deps = offline.ifEmpty {+                            if (ConnectivityMonitor.isOnline(getApplication())) {+                                TransitousDataSource.departures(stop.id, force = force)+                            } else {+                                emptyList()+                            }                         }                         emit(DeparturesState.Loaded(stop, deps))                     }.flowOn(Dispatchers.IO)
maps/src/main/res/values/strings.xml
diff --git a/maps/src/main/res/values/strings.xml b/maps/src/main/res/values/strings.xmlindex 75a047fa3a..60d9fffdf9 100644--- a/maps/src/main/res/values/strings.xml+++ b/maps/src/main/res/values/strings.xml@@ -321,6 +321,15 @@     <string name="transit_minutes">%1$d min</string>     <!-- Departure board: realtime delay vs schedule, signed. %1$d = signed minutes e.g. "+3 min" -->     <string name="transit_delay_minutes">%1$+d min</string>+    <!-- Transit directions: the direction a line is heading. %1$s = headsign e.g. "Ocean Beach" -->+    <string name="transit_towards">Towards %1$s</string>+    <!-- Transit directions: how many stops are ridden. %1$d = stop count -->+    <plurals name="transit_stop_count">+        <item quantity="one">%1$d stop</item>+        <item quantity="other">%1$d stops</item>+    </plurals>+    <!-- Transit directions: joins the headsign and the stop count, e.g. "Towards Ocean Beach · 4 stops" -->+    <string name="transit_detail_separator">%1$s \u00b7 %2$s</string>      <!-- Settings: screen title. Noun. -->     <string name="settings_title">Settings</string>
maps/src/main/rust/src/geometry.rs
diff --git a/maps/src/main/rust/src/geometry.rs b/maps/src/main/rust/src/geometry.rsindex 546b746ba8..6ffa4098c3 100644--- a/maps/src/main/rust/src/geometry.rs+++ b/maps/src/main/rust/src/geometry.rs@@ -7,8 +7,7 @@ use std::collections::HashMap;  use crate::graph::{-    Edge, Graph, DEG_TO_RAD, DRIVING, INVALID_EDGE, LIVING_STREET, MAX_DRIVING_KMH, MOTORWAY,-    PUBLIC_TRANSIT, STEPS, TRANSIT_FLAG,+    Graph, DEG_TO_RAD, DRIVING, INVALID_EDGE, LIVING_STREET, MAX_DRIVING_KMH, MOTORWAY, STEPS, };  /// Live traffic snapshot: global edge id -> speed (km/h). 0 means "unknown".@@ -20,9 +19,9 @@ pub fn is_mode_allowed(road_type: u8, mode: i32) -> bool {     if mode == DRIVING {         return (MOTORWAY..=LIVING_STREET).contains(&ty);     }-    if mode == PUBLIC_TRANSIT {-        return (road_type & TRANSIT_FLAG != 0) || (MOTORWAY..=STEPS).contains(&ty);-    }+    // PUBLIC_TRANSIT reaches the road graph only for a journey's walking legs+    // (the timetable lives in the separate `.transit` index), so it permits+    // exactly what WALK does.     (MOTORWAY..=STEPS).contains(&ty) } @@ -110,89 +109,7 @@ pub fn heuristic_time_10ms(g: &Graph, lat1: i32, lon1: i32, lat2: i32, lon2: i32     (scaled_time >> 32) as u32 } -/// GTFS transit edge cost with next-departure scheduling. Returns-/// `0xFFFFFFFF` when no voyage is usable. Mirrors `get_transit_edge_time_10ms`. #[inline]-pub fn get_transit_edge_time_10ms(-    g: &Graph,-    edge: &Edge,-    current_time_from_start: u32,-    start_time_abs: u32,-    feed_off: u32,-    is_boarding_or_transfer: bool,-) -> (u32, u32, u32) {-    // Returns (total_time, wait_out, travel_out).-    if !g.has_transit_voyages() {-        return (0xFFFF_FFFF, 0, 0);-    }--    let voyage_offset = edge.dist_mm as u64;-    let voyage_count = edge.speed_limit as u32;-    if voyage_count == 0 {-        return (0xFFFF_FFFF, 0, 0);-    }--    // Feed not present offline: report just the (unscheduled) voyage-0 duration.-    if feed_off != 0xFFFF_FFFF && (feed_off as usize) < g.road_names_size {-        if let Some(feed_name) = g.road_name(feed_off) {-            if !g.present_feeds.contains(&feed_name) {-                let travel = g.transit_voyage_at(voyage_offset + 1).dep_delta as u32;-                return (travel, 0, travel);-            }-        }-    }--    const BOARDING_PENALTY: u32 = 6000; // 1 minute to platform-    const DAY_10MS: u32 = 24 * 3600 * 100;-    let abs_now = (start_time_abs + current_time_from_start) % DAY_10MS;-    let arrival_at_platform =-        (abs_now + if is_boarding_or_transfer { BOARDING_PENALTY } else { 0 }) % DAY_10MS;--    let mut best_wait: u32 = 0xFFFF_FFFF;-    let mut best_travel: u32 = 0;--    let wait_for = |dep: u32| -> u32 {-        let dep_mod = dep % DAY_10MS;-        if dep_mod >= arrival_at_platform {-            dep_mod - arrival_at_platform-        } else {-            (DAY_10MS - arrival_at_platform) + dep_mod-        }-    };--    // Voyage 0.-    let dep0 = g.transit_dep_u32(voyage_offset);-    let duration0 = g.transit_voyage_at(voyage_offset + 1).dep_delta as u32;-    {-        let wait = wait_for(dep0);-        if wait < best_wait {-            best_wait = wait;-            best_travel = duration0;-        }-    }--    // Voyages 1+.-    let mut dep_prev = dep0;-    for i in 1..voyage_count as u64 {-        let compact = g.transit_voyage_at(voyage_offset + 1 + i);-        let dep = dep_prev.wrapping_add(compact.dep_delta as u32 * 100);-        dep_prev = dep;-        let wait = wait_for(dep);-        if wait < best_wait {-            best_wait = wait;-            best_travel = compact.duration as u32;-        }-    }--    if best_wait == 0xFFFF_FFFF {-        return (0xFFFF_FFFF, 0, 0);-    }--    let total =-        (if is_boarding_or_transfer { BOARDING_PENALTY } else { 0 }) + best_wait + best_travel;-    (total, best_wait, best_travel)-}- pub fn get_bearing(lat1: i32, lon1: i32, lat2: i32, lon2: i32) -> f64 {     let f1 = (lat1 as f64 / 1e7) * DEG_TO_RAD;     let f2 = (lat2 as f64 / 1e7) * DEG_TO_RAD;
maps/src/main/rust/src/graph.rs
diff --git a/maps/src/main/rust/src/graph.rs b/maps/src/main/rust/src/graph.rsindex bb9333e47f..73ccec5b01 100644--- a/maps/src/main/rust/src/graph.rs+++ b/maps/src/main/rust/src/graph.rs@@ -2,11 +2,11 @@ //! cost tables, spatial (Morton) indexing and delta-decoded edge geometry. //! //! Faithful port of the data model in the old `native-lib.cpp` (`NodeMaster`,-//! `Edge`, `TransitVoyageCompact`, `TransitAttribute`, the `m_file` mmap loader-//! in `init`, and the geometry helpers around it). The graph is loaded once and-//! is read-only afterwards, so it is shared behind an `Arc` (see `lib.rs`).+//! `Edge`, the `m_file` mmap loader in `init`, and the geometry helpers around+//! it). The graph is loaded once and is read-only afterwards, so it is shared+//! behind an `Arc` (see `lib.rs`). -use std::collections::HashSet;+#[cfg(unix)] use std::ffi::CString; use std::ptr; @@ -22,13 +22,12 @@ pub const LIVING_STREET: u8 = 9; pub const STEPS: u8 = 15;  pub const REVERSE_GEOMETRY_FLAG: u8 = 0x40;-pub const TRANSIT_FLAG: u8 = 0x80;  // --- OSM turn:lanes indication bits (one u16 mask per lane) ----// Emitted per directed edge by `scripts/maps/generator.cpp` into `lanes.bin`-// and decoded here into per-lane turn-direction sets. A lane with no marking-// ("none"/empty) is stored as `LANE_NONE`. These bits are an on-disk contract-// with the generator; keep the two in sync.+// Emitted per directed edge by `scripts/maps/osm_ingest` (`road_graph`) into+// `lanes.bin` and decoded here into per-lane turn-direction sets. A lane with no+// marking ("none"/empty) is stored as `LANE_NONE`. These bits are an on-disk+// contract with the generator; keep the two in sync. pub const LANE_NONE: u16 = 1 << 0; pub const LANE_THROUGH: u16 = 1 << 1; pub const LANE_LEFT: u16 = 1 << 2;@@ -55,11 +54,16 @@ pub const BICYCLE_SPEED_M_S: f64 = 16.0 / 3.6; /// mis-buckets it, and A* terminates on a suboptimal path (the "detours the /// wrong way / no route" bug). 130 km/h ≈ 80 mph covers every real US limit. pub const MAX_DRIVING_KMH: f64 = 130.0;-/// Upper bound on any transit in-vehicle speed (km/h) for the same consistency-/// reason — CA rail (BART/Caltrain/Amtrak) all exceed the old 80 km/h estimate.-pub const MAX_TRANSIT_KMH: f64 = 150.0; pub const DEG_TO_RAD: f64 = std::f64::consts::PI / 180.0; +// --- metadata.bin header ---+/// `"MARG"` (Modern-Apps Road Graph), little-endian. Added when the duplicated+/// per-OSM-node transit nodes were removed: that changed `node_count` and+/// `edge_count`, so a pack directory holding files from two vintages reads+/// garbage. The magic + version make that a clean rejection instead.+pub const GRAPH_MAGIC: u32 = 0x4752_414D;+pub const GRAPH_VERSION: u32 = 1;+ // --- On-disk packed structs --- // `#[repr(C, packed)]` reproduces the exact byte strides the generator writes // (notably `Edge` is 14 bytes, not the 16 a naturally-aligned layout would give).@@ -83,20 +87,6 @@ pub struct Edge {     pub speed_limit: u8, } -#[repr(C, packed)]-#[derive(Clone, Copy)]-pub struct TransitVoyageCompact {-    pub dep_delta: u16,-    pub duration: u16,-}--#[repr(C, packed)]-#[derive(Clone, Copy)]-pub struct TransitAttribute {-    pub stop_code_off: u32,-    pub feed_name_off: u32,-}- #[derive(Clone, Copy)] pub struct LatLon {     pub lat_e7: i32,@@ -117,6 +107,7 @@ unsafe impl Sync for MmapRegion {} impl MmapRegion {     /// mmap `path` read-only. Returns `None` for missing/empty/unreadable files,     /// mirroring the C++ `m_file` lambda.+    #[cfg(unix)]     pub(crate) fn map(path: &str) -> Option<MmapRegion> {         let c = CString::new(path).ok()?;         unsafe {@@ -146,12 +137,21 @@ impl MmapRegion {         }     } +    /// This crate ships to Android, so the real loader is Unix-only. The stub+    /// exists purely so a host `cargo test` can build and exercise the parts+    /// that don't need a pack file (the in-memory transit index).+    #[cfg(not(unix))]+    pub(crate) fn map(_path: &str) -> Option<MmapRegion> {+        None+    }+     #[inline]     pub(crate) fn base(&self) -> *const u8 {         self.ptr as *const u8     } } +#[cfg(unix)] impl Drop for MmapRegion {     fn drop(&mut self) {         unsafe {@@ -172,8 +172,6 @@ pub struct Graph {     // mmap regions kept alive for the lifetime of the graph.     _nodes_region: MmapRegion,     _edges_region: MmapRegion,-    _transit_voyages_region: Option<MmapRegion>,-    _transit_attributes_region: Option<MmapRegion>,     _intermediate_region: Option<MmapRegion>,     _road_names_region: Option<MmapRegion>,     _lanes_region: Option<MmapRegion>,@@ -182,10 +180,6 @@ pub struct Graph {     pub node_count: u32, // real nodes; nodes.bin has node_count + 1 (sentinel)     edges: *const u8,     pub edge_count: u64,-    transit_voyages: *const u8,-    #[allow(dead_code)]-    transit_voyage_count: u64,-    transit_attributes: *const u8,      intermediate_edge_offsets: *const u8, // u64[edge_count + 1] byte offsets     intermediate_data: *const u8,         // delta-encoded coordinate bytes@@ -201,8 +195,6 @@ pub struct Graph {     road_names: *const u8,     pub road_names_size: usize, -    pub present_feeds: HashSet<String>,-     // Derived cost tables (computed in `load`, matching the C++ `init`).     pub lon_to_mm_scale: [u32; 4096],     pub time_scale_fixed: [u64; 4],@@ -214,43 +206,45 @@ unsafe impl Sync for Graph {}  impl Graph {     /// Load the graph from `base` (a directory path, trailing slash optional).-    /// Returns `None` if the mandatory nodes/edges/metadata files are absent,-    /// mirroring the failure cases of the C++ `init`.-    pub fn load(base: &str, present_feeds: HashSet<String>) -> Option<Graph> {+    /// Returns `None` if the mandatory nodes/edges/metadata files are absent, if+    /// `metadata.bin` is not a [`GRAPH_VERSION`] header, or if `intermediate.bin`+    /// is too short for this `edge_count` (a mixed-vintage pack directory).+    pub fn load(base: &str) -> Option<Graph> {         let mut base = base.to_string();         if !base.is_empty() && !base.ends_with('/') {             base.push('/');         } -        // metadata.bin is a single u64 node_count.-        let meta = MmapRegion::map(&format!("{base}metadata.bin"))?;-        if meta.len < std::mem::size_of::<u64>() {-            return None;-        }-        let node_count = unsafe { read_at::<u64>(meta.base(), 0) } as u32;-        drop(meta);+        // metadata.bin: u32 magic, u32 version, u64 node_count. Scoped so the+        // mapping is released before the big regions are mapped.+        let node_count = {+            let meta = MmapRegion::map(&format!("{base}metadata.bin"))?;+            if meta.len < 16 {+                return None;+            }+            let magic = unsafe { read_at::<u32>(meta.base(), 0) };+            let version = unsafe { read_at::<u32>(meta.base(), 1) };+            if magic != GRAPH_MAGIC || version != GRAPH_VERSION {+                return None;+            }+            (unsafe { read_at::<u64>(meta.base().add(8), 0) }) as u32+        };          let nodes_region = MmapRegion::map(&format!("{base}nodes.bin"))?;         let edges_region = MmapRegion::map(&format!("{base}edges.bin"))?;         let edge_count = (edges_region.len / std::mem::size_of::<Edge>()) as u64; -        let transit_voyages_region = MmapRegion::map(&format!("{base}transit_voyages.bin"));-        let transit_voyage_count = transit_voyages_region-            .as_ref()-            .map(|r| (r.len / std::mem::size_of::<TransitVoyageCompact>()) as u64)-            .unwrap_or(0);-        let transit_attributes_region = MmapRegion::map(&format!("{base}transit_attributes.bin"));-         // intermediate.bin: [ u64 edge_offsets[edge_count + 1] ][ coord blob ].-        let intermediate_region = MmapRegion::map(&format!("{base}intermediate.bin"));+        // Length-validated: the offset array is sized from `edge_count`, so a+        // stale file from a different graph vintage would be read out of bounds.+        let offsets_bytes = (edge_count + 1) * std::mem::size_of::<u64>() as u64;+        let intermediate_region = MmapRegion::map(&format!("{base}intermediate.bin"))+            .filter(|r| r.len as u64 >= offsets_bytes);         let (intermediate_edge_offsets, intermediate_data, has_intermediate) =             match &intermediate_region {                 Some(r) => {                     let offsets = r.base();-                    let data = unsafe {-                        r.base()-                            .add(((edge_count + 1) * std::mem::size_of::<u64>() as u64) as usize)-                    };+                    let data = unsafe { r.base().add(offsets_bytes as usize) };                     (offsets, data, true)                 }                 None => (ptr::null(), ptr::null(), false),@@ -267,14 +261,9 @@ impl Graph {         // lanes so routing falls back to topology inference.         let lanes_region = MmapRegion::map(&format!("{base}lanes.bin"));         let (lane_edge_offsets, lane_data, has_lanes) = match &lanes_region {-            Some(r)-                if r.len as u64 >= (edge_count + 1) * std::mem::size_of::<u64>() as u64 =>-            {+            Some(r) if r.len as u64 >= offsets_bytes => {                 let offsets = r.base();-                let data = unsafe {-                    r.base()-                        .add(((edge_count + 1) * std::mem::size_of::<u64>() as u64) as usize)-                };+                let data = unsafe { r.base().add(offsets_bytes as usize) };                 (offsets, data, true)             }             _ => (ptr::null(), ptr::null(), false),@@ -282,14 +271,6 @@ impl Graph {          let nodes = nodes_region.base();         let edges = edges_region.base();-        let transit_voyages = transit_voyages_region-            .as_ref()-            .map(|r| r.base())-            .unwrap_or(ptr::null());-        let transit_attributes = transit_attributes_region-            .as_ref()-            .map(|r| r.base())-            .unwrap_or(ptr::null());          // --- Derived tables (identical formulas to the C++ init) ---         let mut lon_to_mm_scale = [0u32; 4096];@@ -308,8 +289,11 @@ impl Graph {         // clamped to MAX_DRIVING_KMH in get_edge_time_10ms) so the heuristic stays         // consistent for the monotonic radix heap. See MAX_DRIVING_KMH.         time_scale_fixed[DRIVING as usize] = calc_scale(MAX_DRIVING_KMH / 3.6);-        // Same consistency requirement for transit in-vehicle speed.-        time_scale_fixed[PUBLIC_TRANSIT as usize] = calc_scale(MAX_TRANSIT_KMH / 3.6);+        // PUBLIC_TRANSIT only ever walks in the road graph (see is_mode_allowed),+        // so it MUST use walk speed. Leaving it at a vehicle speed makes the A*+        // heuristic wildly over-optimistic: still correct, but catastrophically+        // slow because almost the whole graph gets expanded.+        time_scale_fixed[PUBLIC_TRANSIT as usize] = calc_scale(WALK_SPEED_M_S);          let mut edge_time_multipliers = [[0u64; 16]; 4];         for (m, row) in edge_time_multipliers.iter_mut().enumerate() {@@ -335,8 +319,6 @@ impl Graph {         Some(Graph {             _nodes_region: nodes_region,             _edges_region: edges_region,-            _transit_voyages_region: transit_voyages_region,-            _transit_attributes_region: transit_attributes_region,             _intermediate_region: intermediate_region,             _road_names_region: road_names_region,             _lanes_region: lanes_region,@@ -344,9 +326,6 @@ impl Graph {             node_count,             edges,             edge_count,-            transit_voyages,-            transit_voyage_count,-            transit_attributes,             intermediate_edge_offsets,             intermediate_data,             has_intermediate,@@ -355,7 +334,6 @@ impl Graph {             has_lanes,             road_names,             road_names_size,-            present_feeds,             lon_to_mm_scale,             time_scale_fixed,             edge_time_multipliers,@@ -420,38 +398,6 @@ impl Graph {         unsafe { read_at::<u64>(self.intermediate_edge_offsets, idx as usize) }     } -    #[inline]-    fn transit_voyage(&self, idx: u64) -> TransitVoyageCompact {-        unsafe { read_at::<TransitVoyageCompact>(self.transit_voyages, idx as usize) }-    }--    #[inline]-    pub fn has_transit_voyages(&self) -> bool {-        !self.transit_voyages.is_null()-    }--    #[inline]-    pub fn get_node_transit_attr(&self, node_id: u32) -> TransitAttribute {-        if !self.transit_attributes.is_null() && node_id < self.node_count {-            unsafe { read_at::<TransitAttribute>(self.transit_attributes, node_id as usize) }-        } else {-            TransitAttribute {-                stop_code_off: 0xFFFF_FFFF,-                feed_name_off: 0xFFFF_FFFF,-            }-        }-    }--    #[inline]-    pub fn get_node_feed_name_off(&self, node_id: u32) -> u32 {-        self.get_node_transit_attr(node_id).feed_name_off-    }--    #[inline]-    pub fn get_node_stop_code_off(&self, node_id: u32) -> u32 {-        self.get_node_transit_attr(node_id).stop_code_off-    }-     /// Borrow a NUL-terminated road/feed/stop name from the string pool at     /// `offset`. Returns `None` for the sentinel or out-of-range offsets.     pub fn road_name(&self, offset: u32) -> Option<String> {@@ -577,19 +523,6 @@ impl Graph {         }         count     }--    /// Voyage record at absolute index `idx` (used for durations / deltas).-    #[inline]-    pub fn transit_voyage_at(&self, idx: u64) -> TransitVoyageCompact {-        self.transit_voyage(idx)-    }--    /// The first 4 bytes at voyage index `idx` reinterpreted as a u32 — the-    /// absolute departure time of voyage 0 (`*(uint32_t*)base` in the C++).-    #[inline]-    pub fn transit_dep_u32(&self, idx: u64) -> u32 {-        unsafe { read_at::<u32>(self.transit_voyages, idx as usize) }-    } }  /// Fetch point `idx` from a decoded coordinate buffer, honouring reversal.
maps/src/main/rust/src/routing.rs
diff --git a/maps/src/main/rust/src/routing.rs b/maps/src/main/rust/src/routing.rsindex 12838faad3..e6f58640b8 100644--- a/maps/src/main/rust/src/routing.rs+++ b/maps/src/main/rust/src/routing.rs@@ -47,7 +47,6 @@ pub struct RoutingContext {     pub end: SnappedEdge,     pub target_node: u32,     pub iterations: i32,-    pub start_time: u32, }  /// One coalesced navigation step (pre-localization). Marshaled to Kotlin@@ -59,11 +58,6 @@ pub struct StepData {     pub coords: Vec<f64>, // flat [lon, lat, lon, lat, ...]     pub maneuver: i32,     pub speed_ratio: f64,-    pub is_transit: bool,-    pub feed_off: u32,-    pub code_off: u32,-    pub end_code_off: u32,-    pub stop_count: i32,     /// Derived turn-lane guidance for this step's maneuver. Each entry is one     /// available turn lane at the junction (ordered left→right), packed as     /// `dir_mask * 2 + valid` where `dir_mask` is a bitmask of maneuver-enum@@ -197,9 +191,6 @@ fn junction_lanes(      for k in s..e_ptr {         let edge = g.edge(k);-        if edge.type_ & TRANSIT_FLAG != 0 {-            continue;-        }         if !is_mode_allowed(edge.type_, DRIVING) {             continue;         }@@ -294,9 +285,6 @@ pub fn find_nearest_edge(g: &Graph, lat: f64, lon: f64, mode: i32) -> SnappedEdg         let e_ptr = g.node(u_global + 1).edge_ptr; // sentinel valid         for j in node_u.edge_ptr..e_ptr {             let e = g.edge(j);-            if e.type_ & TRANSIT_FLAG != 0 {-                continue;-            }             if !is_mode_allowed(e.type_, mode) {                 continue;             }@@ -373,7 +361,6 @@ pub fn prepare_routing(     e_lat: f64,     e_lon: f64,     mode: i32,-    start_time: u32,     scratch: &mut RoutingScratchpad,     heap: &mut RadixHeap, ) -> Option<RoutingContext> {@@ -395,14 +382,14 @@ pub fn prepare_routing(             g, traffic, INVALID_EDGE, travel_dist_mm, start.type_, start.speed_limit, mode,         );         {-            let entry = scratch.get_entry(node, 0);+            let entry = scratch.get_entry(node);             entry.g_fwd = t_actual;             entry.g_bwd = t_actual;             entry.last_type = start.type_;         }         let n_data = g.get_node(node);         let h = heuristic_time_10ms(g, n_data.lat_e7, n_data.lon_e7, end.proj_lat, end.proj_lon, mode);-        heap.push(t_actual.wrapping_add(h), node << 1);+        heap.push(t_actual.wrapping_add(h), node);     };     push(start.node_a, start.dist_a_mm, scratch, heap);     push(start.node_b, start.dist_b_mm, scratch, heap);@@ -412,7 +399,6 @@ pub fn prepare_routing(         end,         target_node: 0xFFFF_FFFF,         iterations: 0,-        start_time,     }) } @@ -430,21 +416,14 @@ pub fn perform_search_loop(     // the longest routes (SF->LA), so the old 1M cap aborted them ("no route").     while !heap.empty() && ctx.iterations < 25_000_000 {         ctx.iterations += 1;-        let u_idx = heap.pop();-        let u = u_idx >> 1;-        let u_state = (u_idx & 1) as i32;+        let u = heap.pop(); -        if (u == ctx.end.node_a || u == ctx.end.node_b)-            && (mode != PUBLIC_TRANSIT || u_state == 1)-        {-            ctx.target_node = u_idx;+        if u == ctx.end.node_a || u == ctx.end.node_b {+            ctx.target_node = u;             break;         } -        let (u_cost, u_actual_time, u_last_type, u_last_name_off) = {-            let e = scratch.get_entry(u, u_state);-            (e.g_fwd, e.g_bwd, e.last_type, e.last_name_off)-        };+        let u_cost = scratch.get_entry(u).g_fwd;         if u >= g.node_count {             continue;         }@@ -462,52 +441,17 @@ pub fn perform_search_loop(                 continue;             } -            let v_state: i32 = if mode == PUBLIC_TRANSIT && (edge.type_ & TRANSIT_FLAG) != 0 {-                1-            } else {-                0-            };-            let travel_time: u32 = if v_state == 1 {-                let is_boarding = (u_last_type & TRANSIT_FLAG) == 0;-                let is_transfer = !is_boarding && (edge.name_offset != u_last_name_off);--                let ta_u = g.get_node_transit_attr(u);-                // Only board/transfer at recognized transit stops.-                if (is_boarding || is_transfer) && ta_u.stop_code_off == 0xFFFF_FFFF {-                    continue;-                }--                let (tt, _wait, _move) = get_transit_edge_time_10ms(-                    g,-                    &edge,-                    u_actual_time,-                    ctx.start_time,-                    ta_u.feed_name_off,-                    is_boarding || is_transfer,-                );-                if tt == 0xFFFF_FFFF {-                    continue;-                }-                tt-            } else {-                // Only alight from transit at recognized transit stops.-                if mode == PUBLIC_TRANSIT && (u_last_type & TRANSIT_FLAG) != 0 {-                    let ta_u = g.get_node_transit_attr(u);-                    if ta_u.stop_code_off == 0xFFFF_FFFF {-                        continue;-                    }-                }-                get_edge_time_10ms(g, traffic, i, edge.dist_mm, edge.type_, edge.speed_limit, mode)-            };+            let travel_time =+                get_edge_time_10ms(g, traffic, i, edge.dist_mm, edge.type_, edge.speed_limit, mode);              let v = edge.target;             let new_g = u_cost.wrapping_add(travel_time);             let update = {-                let entry_v = scratch.get_entry(v, v_state);+                let entry_v = scratch.get_entry(v);                 if new_g < entry_v.g_fwd {                     entry_v.g_fwd = new_g;                     entry_v.g_bwd = new_g;-                    entry_v.p_fwd = u_idx;+                    entry_v.p_fwd = u;                     entry_v.last_type = edge.type_;                     entry_v.last_name_off = edge.name_offset;                     true@@ -520,7 +464,7 @@ pub fn perform_search_loop(                 let h = heuristic_time_10ms(                     g, n_v.lat_e7, n_v.lon_e7, ctx.end.proj_lat, ctx.end.proj_lon, mode,                 );-                heap.push(new_g.wrapping_add(h), (v << 1) | v_state as u32);+                heap.push(new_g.wrapping_add(h), v);             }         }     }@@ -531,11 +475,8 @@ struct StepBuilder<'a> {     g: &'a Graph,     traffic: &'a TrafficSpeeds,     mode: i32,-    start_time_abs: u32,     steps: Vec<StepData>,     last_bearing: f64,-    current_elapsed_10ms: u32,-    last_was_transit: bool,     /// Junction node for the next segment's maneuver (or [`INVALID_NODE`]).     pending_junction: u32,     /// Node we arrive from at that junction, to exclude the U-turn lane.@@ -558,9 +499,6 @@ impl<'a> StepBuilder<'a> {         limit: u8,         dist_mm: u32,         edge_idx: u64,-        feed_off: u32,-        code_off: u32,-        target_code_off: u32,     ) {         // Junction context for lane derivation is set on the builder before the         // first segment of a main-path edge and consumed (then cleared) here.@@ -578,59 +516,8 @@ impl<'a> StepBuilder<'a> {             }         } -        let time_10ms: u32;-        let mut is_transit = false;-        if self.mode == PUBLIC_TRANSIT && (type_ & TRANSIT_FLAG) != 0 {-            is_transit = true;-            if edge_idx != INVALID_EDGE {-                let is_boarding = !self.last_was_transit;-                let is_transfer =-                    self.last_was_transit && (name_off != self.steps.last().unwrap().name_off);-                let edge = self.g.edge(edge_idx);-                let (tt, wait, transit_move) = get_transit_edge_time_10ms(-                    self.g,-                    &edge,-                    self.current_elapsed_10ms,-                    self.start_time_abs,-                    feed_off,-                    is_boarding || is_transfer,-                );-                let (wait, transit_move) = if tt == 0xFFFF_FFFF {-                    (0, 0)-                } else {-                    (wait, transit_move)-                };--                if is_boarding || is_transfer {-                    let penalty: u32 = 6000;-                    self.steps.push(StepData {-                        name_off,-                        dist_mm: 0,-                        time_10ms: (wait + penalty) as u64,-                        coords: vec![lon1, lat1],-                        maneuver: 21,-                        speed_ratio: 1.0,-                        is_transit: true,-                        feed_off,-                        code_off,-                        end_code_off: 0xFFFF_FFFF,-                        stop_count: 0,-                        lanes: Vec::new(),-                    });-                    self.current_elapsed_10ms += wait + penalty;-                    time_10ms = transit_move;-                } else {-                    time_10ms = transit_move;-                }-            } else {-                time_10ms = 0;-            }-        } else {-            time_10ms =-                get_edge_time_10ms(self.g, self.traffic, edge_idx, dist_mm, type_, limit, self.mode);-        }-        self.current_elapsed_10ms += time_10ms;-        self.last_was_transit = (type_ & TRANSIT_FLAG) != 0;+        let time_10ms =+            get_edge_time_10ms(self.g, self.traffic, edge_idx, dist_mm, type_, limit, self.mode);         let bearing = get_bearing(             (lat1 * 1e7) as i32,             (lon1 * 1e7) as i32,@@ -648,14 +535,11 @@ impl<'a> StepBuilder<'a> {             }         }; -        let mut maneuver = if self.steps.is_empty() {+        let maneuver = if self.steps.is_empty() {             0         } else {             get_maneuver(self.last_bearing, bearing)         };-        if is_transit && !self.steps.is_empty() && self.steps.last().unwrap().maneuver != 21 {-            maneuver = 23; // RIDE-        }          let push_new = {             match self.steps.last() {@@ -663,9 +547,7 @@ impl<'a> StepBuilder<'a> {                 Some(back) => {                     name_off != back.name_off                         || ratio_cat(ratio) != ratio_cat(back.speed_ratio)-                        || is_transit != back.is_transit-                        || (maneuver != 9 && maneuver != 0 && maneuver != 23)-                        || back.maneuver == 21+                        || (maneuver != 9 && maneuver != 0)                 }             }         };@@ -686,11 +568,6 @@ impl<'a> StepBuilder<'a> {                 coords: vec![lon1, lat1],                 maneuver,                 speed_ratio: ratio,-                is_transit,-                feed_off,-                code_off,-                end_code_off: 0xFFFF_FFFF,-                stop_count: 0,                 lanes,             });         }@@ -700,10 +577,6 @@ impl<'a> StepBuilder<'a> {         back.time_10ms += time_10ms as u64;         back.coords.push(lon2);         back.coords.push(lat2);-        if is_transit && back.maneuver != 21 {-            back.end_code_off = target_code_off;-            back.stop_count += 1;-        }         self.last_bearing = bearing;     } }@@ -717,30 +590,25 @@ pub fn reconstruct_path(     ctx: &RoutingContext,     scratch: &mut RoutingScratchpad, ) -> Vec<StepData> {-    let mut path_indices: Vec<u32> = Vec::new();+    let mut path_nodes: Vec<u32> = Vec::new();     let mut curr = ctx.target_node;     let mut safety = 0u32;     while curr != 0xFFFF_FFFF && safety < 1_000_000 {-        path_indices.push(curr);-        curr = scratch.get_entry(curr >> 1, (curr & 1) as i32).p_fwd;+        path_nodes.push(curr);+        curr = scratch.get_entry(curr).p_fwd;         safety += 1;     }-    path_indices.reverse();-    if path_indices.is_empty() {+    path_nodes.reverse();+    if path_nodes.is_empty() {         return Vec::new();     } -    let path_nodes: Vec<u32> = path_indices.iter().map(|&idx| idx >> 1).collect();-     let mut b = StepBuilder {         g,         traffic,         mode,-        start_time_abs: ctx.start_time,         steps: Vec::new(),         last_bearing: 0.0,-        current_elapsed_10ms: 0,-        last_was_transit: false,         pending_junction: INVALID_NODE,         pending_prev: INVALID_NODE,         pending_approach: INVALID_EDGE,@@ -762,8 +630,6 @@ pub fn reconstruct_path(         if let Some((count, is_reversed)) = geom.filter(|&(c, _)| c >= 2) {             let num_pts = count;             let seg_idx = ctx.start.segment_idx;-            let feed = g.get_node_feed_name_off(n0);-            let code = g.get_node_stop_code_off(n0);              if n0 == ctx.start.node_a {                 let p_next = get_pt_at(&coords, count, is_reversed, seg_idx);@@ -775,7 +641,7 @@ pub fn reconstruct_path(                     ctx.start.proj_lon as f64 * 1e-7,                     p_next.lat_e7 as f64 * 1e-7,                     p_next.lon_e7 as f64 * 1e-7,-                    ctx.start.name_offset, ctx.start.type_, ctx.start.speed_limit, d1, j, feed, code, code,+                    ctx.start.name_offset, ctx.start.type_, ctx.start.speed_limit, d1, j,                 );                 let mut p = seg_idx as i32;                 while p >= 1 {@@ -785,7 +651,7 @@ pub fn reconstruct_path(                     b.add_segment(                         p_from.lat_e7 as f64 * 1e-7, p_from.lon_e7 as f64 * 1e-7,                         p_to.lat_e7 as f64 * 1e-7, p_to.lon_e7 as f64 * 1e-7,-                        ctx.start.name_offset, ctx.start.type_, ctx.start.speed_limit, d_seg, j, feed, code, code,+                        ctx.start.name_offset, ctx.start.type_, ctx.start.speed_limit, d_seg, j,                     );                     p -= 1;                 }@@ -799,7 +665,7 @@ pub fn reconstruct_path(                     ctx.start.proj_lon as f64 * 1e-7,                     p_next.lat_e7 as f64 * 1e-7,                     p_next.lon_e7 as f64 * 1e-7,-                    ctx.start.name_offset, ctx.start.type_, ctx.start.speed_limit, d1, j, feed, code, code,+                    ctx.start.name_offset, ctx.start.type_, ctx.start.speed_limit, d1, j,                 );                 for p in seg_idx + 1..num_pts - 1 {                     let p_from = get_pt_at(&coords, count, is_reversed, p);@@ -808,7 +674,7 @@ pub fn reconstruct_path(                     b.add_segment(                         p_from.lat_e7 as f64 * 1e-7, p_from.lon_e7 as f64 * 1e-7,                         p_to.lat_e7 as f64 * 1e-7, p_to.lon_e7 as f64 * 1e-7,-                        ctx.start.name_offset, ctx.start.type_, ctx.start.speed_limit, d_seg, j, feed, code, code,+                        ctx.start.name_offset, ctx.start.type_, ctx.start.speed_limit, d_seg, j,                     );                 }             }@@ -824,7 +690,6 @@ pub fn reconstruct_path(                 node0.lat_e7 as f64 * 1e-7,                 node0.lon_e7 as f64 * 1e-7,                 ctx.start.name_offset, ctx.start.type_, ctx.start.speed_limit, dist, INVALID_EDGE,-                g.get_node_feed_name_off(n0), g.get_node_stop_code_off(n0), g.get_node_stop_code_off(n0),             );         }     }@@ -856,14 +721,10 @@ pub fn reconstruct_path(          let e = g.edge(best_e_idx);         let mut d = e.dist_mm;-        if d == 0 || (e.type_ & TRANSIT_FLAG) != 0 {+        if d == 0 {             d = accurate_dist_mm(node_u.lat_e7, node_u.lon_e7, node_v.lat_e7, node_v.lon_e7);         } -        let feed = g.get_node_feed_name_off(u);-        let code_u = g.get_node_stop_code_off(u);-        let code_v = g.get_node_stop_code_off(v);-         // Lane guidance is derived at the junction where this edge begins         // (node u), excluding the node we arrived from. Set it just before the         // edge's first segment; add_segment consumes and clears it so only the@@ -886,14 +747,14 @@ pub fn reconstruct_path(                 b.add_segment(                     p1.lat_e7 as f64 * 1e-7, p1.lon_e7 as f64 * 1e-7,                     p2.lat_e7 as f64 * 1e-7, p2.lon_e7 as f64 * 1e-7,-                    e.name_offset, e.type_, e.speed_limit, seg_dist, best_e_idx, feed, code_u, code_v,+                    e.name_offset, e.type_, e.speed_limit, seg_dist, best_e_idx,                 );             }         } else {             b.add_segment(                 node_u.lat_e7 as f64 * 1e-7, node_u.lon_e7 as f64 * 1e-7,                 node_v.lat_e7 as f64 * 1e-7, node_v.lon_e7 as f64 * 1e-7,-                e.name_offset, e.type_, e.speed_limit, d, best_e_idx, feed, code_u, code_v,+                e.name_offset, e.type_, e.speed_limit, d, best_e_idx,             );         }     }@@ -912,8 +773,6 @@ pub fn reconstruct_path(         if let Some((count, is_reversed)) = geom.filter(|&(c, _)| c >= 2) {             let num_pts = count;             let seg_idx = ctx.end.segment_idx;-            let feed = g.get_node_feed_name_off(nk);-            let code = g.get_node_stop_code_off(nk);              if nk == ctx.end.node_a {                 for p in 0..seg_idx {@@ -923,7 +782,7 @@ pub fn reconstruct_path(                     b.add_segment(                         p_from.lat_e7 as f64 * 1e-7, p_from.lon_e7 as f64 * 1e-7,                         p_to.lat_e7 as f64 * 1e-7, p_to.lon_e7 as f64 * 1e-7,-                        ctx.end.name_offset, ctx.end.type_, ctx.end.speed_limit, d_seg, j, feed, code, 0xFFFF_FFFF,+                        ctx.end.name_offset, ctx.end.type_, ctx.end.speed_limit, d_seg, j,                     );                 }                 let p_last = get_pt_at(&coords, count, is_reversed, seg_idx);@@ -931,7 +790,7 @@ pub fn reconstruct_path(                 b.add_segment(                     p_last.lat_e7 as f64 * 1e-7, p_last.lon_e7 as f64 * 1e-7,                     ctx.end.proj_lat as f64 * 1e-7, ctx.end.proj_lon as f64 * 1e-7,-                    ctx.end.name_offset, ctx.end.type_, ctx.end.speed_limit, d2, j, feed, code, 0xFFFF_FFFF,+                    ctx.end.name_offset, ctx.end.type_, ctx.end.speed_limit, d2, j,                 );             } else {                 let mut p = num_pts as i32 - 1;@@ -942,7 +801,7 @@ pub fn reconstruct_path(                     b.add_segment(                         p_from.lat_e7 as f64 * 1e-7, p_from.lon_e7 as f64 * 1e-7,                         p_to.lat_e7 as f64 * 1e-7, p_to.lon_e7 as f64 * 1e-7,-                        ctx.end.name_offset, ctx.end.type_, ctx.end.speed_limit, d_seg, j, feed, code, 0xFFFF_FFFF,+                        ctx.end.name_offset, ctx.end.type_, ctx.end.speed_limit, d_seg, j,                     );                     p -= 1;                 }@@ -951,7 +810,7 @@ pub fn reconstruct_path(                 b.add_segment(                     p_last.lat_e7 as f64 * 1e-7, p_last.lon_e7 as f64 * 1e-7,                     ctx.end.proj_lat as f64 * 1e-7, ctx.end.proj_lon as f64 * 1e-7,-                    ctx.end.name_offset, ctx.end.type_, ctx.end.speed_limit, d2, j, feed, code, 0xFFFF_FFFF,+                    ctx.end.name_offset, ctx.end.type_, ctx.end.speed_limit, d2, j,                 );             }         } else {@@ -964,7 +823,6 @@ pub fn reconstruct_path(                 nodek.lat_e7 as f64 * 1e-7, nodek.lon_e7 as f64 * 1e-7,                 ctx.end.proj_lat as f64 * 1e-7, ctx.end.proj_lon as f64 * 1e-7,                 ctx.end.name_offset, ctx.end.type_, ctx.end.speed_limit, dist, INVALID_EDGE,-                g.get_node_feed_name_off(nk), g.get_node_stop_code_off(nk), 0xFFFF_FFFF,             );         }     }
maps/src/main/rust/src/state.rs
diff --git a/maps/src/main/rust/src/state.rs b/maps/src/main/rust/src/state.rsindex cea97d9097..302d760f34 100644--- a/maps/src/main/rust/src/state.rs+++ b/maps/src/main/rust/src/state.rs@@ -121,7 +121,7 @@ const ROUTING_PAGE_SIZE: usize = 1 << PAGE_BITS; const ROUTING_PAGE_MASK: u32 = (ROUTING_PAGE_SIZE as u32) - 1; const DIR_SIZE: usize = (1usize << 32) >> PAGE_BITS; -/// Two-level page table indexed by `(node_id << 1) | state`, sparsely allocated.+/// Two-level page table indexed by node id, sparsely allocated. pub struct RoutingScratchpad {     directory: Vec<Option<Box<[Entry]>>>,     active_pages: Vec<u32>,@@ -145,10 +145,9 @@ impl RoutingScratchpad {     }      #[inline]-    pub fn get_entry(&mut self, node_id: u32, state: i32) -> &mut Entry {-        let index = (node_id << 1) | (state as u32 & 1);-        let dir_idx = (index >> PAGE_BITS) as usize;-        let page_offset = (index & ROUTING_PAGE_MASK) as usize;+    pub fn get_entry(&mut self, node_id: u32) -> &mut Entry {+        let dir_idx = (node_id >> PAGE_BITS) as usize;+        let page_offset = (node_id & ROUTING_PAGE_MASK) as usize;          if self.directory[dir_idx].is_none() {             let page = vec![Entry::FRESH; ROUTING_PAGE_SIZE].into_boxed_slice();
maps/src/test/java/com/vayunmathur/maps/util/GTFSProviderTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/GTFSProviderTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/GTFSProviderTest.ktnew file mode 100644index 0000000000..f9426e6d24--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/GTFSProviderTest.kt@@ -0,0 +1,55 @@+package com.vayunmathur.maps.util++import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * GTFS `routes.txt` routinely quotes `route_long_name`, so a naive+ * `split(",")` shifts every column after it and the colour lookup silently+ * returns the wrong field.+ */+class GTFSProviderTest {++    @Test+    fun `splits a plain row`() {+        assertEquals(+            listOf("R1", "N", "Judah", "0", "0000FF"),+            GTFSProvider.parseCsvLine("R1,N,Judah,0,0000FF"),+        )+    }++    @Test+    fun `keeps a comma inside a quoted field`() {+        val fields = GTFSProvider.parseCsvLine("R1,N,\"Judah, Ocean Beach\",0,0000FF")+        assertEquals(5, fields.size)+        assertEquals("Judah, Ocean Beach", fields[2])+        // The columns after the quoted field must not shift.+        assertEquals("0000FF", fields[4])+    }++    @Test+    fun `unescapes a doubled quote`() {+        assertEquals(+            listOf("R1", "The \"L\" Line", "3"),+            GTFSProvider.parseCsvLine("R1,\"The \"\"L\"\" Line\",3"),+        )+    }++    @Test+    fun `keeps empty fields including trailing ones`() {+        assertEquals(listOf("R1", "", "3", ""), GTFSProvider.parseCsvLine("R1,,3,"))+    }++    @Test+    fun `strips a utf8 bom from the header`() {+        assertEquals(+            listOf("route_id", "route_short_name"),+            GTFSProvider.parseCsvLine("\uFEFFroute_id,route_short_name"),+        )+    }++    @Test+    fun `strips a trailing carriage return from a crlf file`() {+        assertEquals(listOf("R1", "0000FF"), GTFSProvider.parseCsvLine("R1,0000FF\r"))+    }+}
maps/src/test/java/com/vayunmathur/maps/util/TransitClockTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/TransitClockTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/TransitClockTest.ktnew file mode 100644index 0000000000..a6011b315a--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/TransitClockTest.kt@@ -0,0 +1,86 @@+package com.vayunmathur.maps.util++import java.time.ZoneId+import java.time.ZonedDateTime+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals++/**+ * The offline transit index is world-merged, so every query time must be derived+ * in the *feed's* timezone. These lock that down without a device: the whole+ * point is that the device's own zone must not leak in.+ */+class TransitClockTest {++    /** Wed 2024-01-03, 08:30 local, in whatever zone is asked for. */+    private fun at(y: Int, m: Int, d: Int, h: Int, min: Int): (ZoneId) -> ZonedDateTime =+        { zone -> ZonedDateTime.of(y, m, d, h, min, 0, 0, zone) }++    @Test+    fun `derives seconds since midnight in the feed zone`() {+        val clock = transitClock("America/Los_Angeles", at(2024, 1, 3, 8, 30))+        assertEquals(8 * 3600 + 30 * 60, clock.depSecs)+    }++    @Test+    fun `maps weekday to Monday zero`() {+        // 2024-01-03 is a Wednesday, 2024-01-07 a Sunday.+        assertEquals(2, transitClock("UTC", at(2024, 1, 3, 8, 0)).weekday)+        assertEquals(6, transitClock("UTC", at(2024, 1, 7, 8, 0)).weekday)+    }++    @Test+    fun `encodes the date as yyyymmdd`() {+        assertEquals(20240103, transitClock("UTC", at(2024, 1, 3, 8, 0)).date)+    }++    @Test+    fun `previous service day wraps the month and the week`() {+        val clock = transitClock("UTC", at(2024, 3, 1, 0, 30))+        assertEquals(20240301, clock.date)+        // 2024 is a leap year, so the day before 1 March is 29 February.+        assertEquals(20240229, clock.prevDate)+        // 2024-03-01 was a Friday, so the previous day is a Thursday.+        assertEquals(4, clock.weekday)+        assertEquals(3, clock.prevWeekday)+    }++    @Test+    fun `two feeds an ocean apart get different query times for one instant`() {+        // 2024-01-03T08:30 in New York is 05:30 in Los Angeles: the same wall+        // clock reading in each zone must NOT produce the same depSecs, which is+        // exactly the bug of using the device zone against a world pack.+        val west = transitClock("America/Los_Angeles", at(2024, 1, 3, 8, 30))+        val east = transitClock("America/New_York", at(2024, 1, 3, 8, 30))+        assertEquals(west.depSecs, east.depSecs, "same wall clock in both zones")+        // ...but midnight is a different instant, so absolute times differ.+        assertNotEquals(west.midnightMillis, east.midnightMillis)+        assertEquals(3 * 3600 * 1000L, west.midnightMillis - east.midnightMillis)+    }++    @Test+    fun `midnight millis is feed-local midnight`() {+        val clock = transitClock("America/Los_Angeles", at(2024, 1, 3, 8, 30))+        val expected = ZonedDateTime.of(2024, 1, 3, 0, 0, 0, 0, ZoneId.of("America/Los_Angeles"))+            .toInstant().toEpochMilli()+        assertEquals(expected, clock.midnightMillis)+    }++    @Test+    fun `an unknown or missing zone falls back to the device zone`() {+        val fixed = at(2024, 1, 3, 8, 30)+        val device = transitClock(ZoneId.systemDefault().id, fixed)+        assertEquals(device, transitClock(null, fixed))+        assertEquals(device, transitClock("Not/AZone", fixed))+    }++    @Test+    fun `formats a service time as a wall clock`() {+        assertEquals("08:30", formatServiceTime(8 * 3600 + 30 * 60))+        assertEquals("23:59", formatServiceTime(23 * 3600 + 59 * 60))+        // A GTFS 24:30:00 trip renders as the 00:30 it actually runs at.+        assertEquals("00:30", formatServiceTime(24 * 3600 + 30 * 60))+        assertEquals("", formatServiceTime(0))+    }+}