Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / maps / src / main / java / com / vayunmathur / maps / data / OfflineRouterRouteBuilder.kt

OfflineRouterRouteBuilder.kt417 lines · 18.2 KiBRaw
1package com.vayunmathur.maps.data
2import com.vayunmathur.maps.util.OfflineRouter
3import com.vayunmathur.maps.domain.WALK_LEG_PLACEHOLDER
4import com.vayunmathur.maps.domain.RouteService
5import com.vayunmathur.maps.domain.arriveAt
6import com.vayunmathur.maps.domain.formatServiceTime
7import com.vayunmathur.maps.domain.leaveAt
8import com.vayunmathur.maps.domain.phraseWalkLegs
9
10import android.content.Context
11import com.vayunmathur.library.map.GeoPoint
12import com.vayunmathur.maps.R
13import com.vayunmathur.library.ui.R as UiR
14import kotlin.time.Duration.Companion.seconds
15
16/**
17 * Converts native [OfflineRouter.RawStep]s into a [RouteService.Route], extracted from
18 * [OfflineRouter] to keep that file under the length limit.
19 *
20 * Shared by the driving/walking `findRouteNative` path and the offline transit
21 * `findTransitRouteNative` path (via [OfflineRouterTransit]).
22 */
23internal object OfflineRouterRouteBuilder {
24 /** Millimetres per metre (native distance unit). */
25 private const val MM_PER_METER = 1000.0
26 /** Native durations are centiseconds (10 ms units). */
27 private const val CENTISEC_PER_SECOND = 100.0
28 /** Stride of one [lon, lat] pair in a native geometry array. */
29 private const val GEOMETRY_PAIR_STRIDE = 2
30 /** Bit 0 of a packed lane int: the lane leads onto the taken route. */
31 private const val LANE_ACTIVE_BIT = 1
32 /** Packed lane int holds `dirMask * 2 + valid`: shift to the mask. */
33 private const val LANE_MASK_SHIFT = 1
34 /** Mask for one unsigned RGB byte of a GTFS `route_color`. */
35 private const val RGB_MASK = 0xFFFFFF
36 /** Fallback line colour when neither the pack nor GTFS names one. */
37 private const val FALLBACK_ROUTE_COLOR = "#FF0000"
38 /** Native wait durations are centiseconds (10 ms units). */
39 private const val WAIT_CENTISEC_PER_SECOND = 100
40 /** Seconds per minute, for the wait-text split. */
41 private const val SECONDS_PER_MINUTE = 60
42 /** Metres per degree of latitude, for the elevation-profile distance. */
43 private const val METERS_PER_DEGREE = 111_320.0
44 /** Midpoint factor when averaging two latitudes. */
45 private const val LAT_MIDPOINT = 0.5
46 /**
47 * Convert native [OfflineRouter.RawStep]s into a [RouteService.Route]: decode geometry,
48 * localize maneuver text, attach transit details, and coalesce consecutive
49 * same-road maneuvers. Shared by the driving/walking [findRouteNative] path
50 * and the offline transit [findTransitRouteNative] path.
51 */
52 fun buildRoute(
53 context: Context,
54 rawSteps: Array<OfflineRouter.RawStep>,
55 mode: RouteService.TravelMode
56 ): RouteService.Route {
57 val fullPolyline = mutableListOf<GeoPoint>()
58 val processedSteps = rawSteps.map { raw -> buildStep(context, raw, mode, fullPolyline) }
59 return assembleRoute(context, rawSteps, mode, fullPolyline, processedSteps)
60 }
61
62 private fun buildStep(
63 context: Context,
64 raw: OfflineRouter.RawStep,
65 mode: RouteService.TravelMode,
66 fullPolyline: MutableList<GeoPoint>,
67 ): RouteService.Step {
68 val positions = mutableListOf<GeoPoint>()
69 for (i in raw.geometry.indices step GEOMETRY_PAIR_STRIDE) {
70 val pos = GeoPoint(raw.geometry[i], raw.geometry[i + 1])
71 positions.add(pos)
72 if (fullPolyline.isEmpty() || fullPolyline.last() != pos) {
73 fullPolyline.add(pos)
74 }
75 }
76
77 val maneuver = maneuverOf(raw.maneuverId)
78 val lanes = raw.lanePacked.map { code -> decodeLane(code) }
79 val hasName = raw.roadName.isNotBlank()
80 val instructionText = instructionText(context, raw, mode, maneuver, hasName)
81 return RouteService.Step(
82 distanceMeters = raw.distanceMm / MM_PER_METER,
83 staticDuration = (raw.duration10ms / CENTISEC_PER_SECOND).seconds,
84 polyline = positions,
85 navInstruction = RouteService.API.NavInstruction(maneuver, instructionText),
86 travelMode = stepTravelMode(raw, mode),
87 speedRatio = raw.speedRatio,
88 lanes = lanes,
89 transitDetails = transitDetails(context, raw),
90 )
91 }
92
93 private fun instructionText(
94 context: Context,
95 raw: OfflineRouter.RawStep,
96 mode: RouteService.TravelMode,
97 maneuver: RouteService.API.Maneuver,
98 hasName: Boolean,
99 ): String = namedInstruction(context, raw, maneuver, hasName)
100 ?: waitInstruction(context, raw)
101 ?: fallbackInstruction(context, raw, mode, hasName)
102
103 /** Named/unnamed template for the plain road maneuvers, or null when [maneuver] is special. */
104 private fun namedInstruction(
105 context: Context,
106 raw: OfflineRouter.RawStep,
107 maneuver: RouteService.API.Maneuver,
108 hasName: Boolean,
109 ): String? {
110 val templates = MANEUVER_TEMPLATES[maneuver] ?: return null
111 val res = if (hasName) templates.first else templates.second
112 return context.getString(res, raw.roadName)
113 }
114
115 /** Road maneuver → (named template, unnamed template). */
116 private val MANEUVER_TEMPLATES: Map<RouteService.API.Maneuver, Pair<Int, Int>> = mapOf(
117 RouteService.API.Maneuver.DEPART to
118 (R.string.maneuver_depart to R.string.maneuver_depart_unnamed),
119 RouteService.API.Maneuver.STRAIGHT to
120 (R.string.maneuver_straight to R.string.maneuver_straight_unnamed),
121 RouteService.API.Maneuver.TURN_LEFT to
122 (R.string.maneuver_turn_left to R.string.maneuver_turn_left_unnamed),
123 RouteService.API.Maneuver.TURN_RIGHT to
124 (R.string.maneuver_turn_right to R.string.maneuver_turn_right_unnamed),
125 RouteService.API.Maneuver.TURN_SLIGHT_LEFT to
126 (R.string.maneuver_turn_slight_left to
127 R.string.maneuver_turn_slight_left_unnamed),
128 RouteService.API.Maneuver.TURN_SLIGHT_RIGHT to
129 (R.string.maneuver_turn_slight_right to
130 R.string.maneuver_turn_slight_right_unnamed),
131 RouteService.API.Maneuver.TURN_SHARP_LEFT to
132 (R.string.maneuver_turn_sharp_left to
133 R.string.maneuver_turn_sharp_left_unnamed),
134 RouteService.API.Maneuver.TURN_SHARP_RIGHT to
135 (R.string.maneuver_turn_sharp_right to
136 R.string.maneuver_turn_sharp_right_unnamed),
137 RouteService.API.Maneuver.UTURN_LEFT to
138 (R.string.maneuver_uturn to R.string.maneuver_uturn_unnamed),
139 RouteService.API.Maneuver.UTURN_RIGHT to
140 (R.string.maneuver_uturn to R.string.maneuver_uturn_unnamed),
141 RouteService.API.Maneuver.MERGE to
142 (R.string.maneuver_merge to R.string.maneuver_merge_unnamed),
143 RouteService.API.Maneuver.RAMP_LEFT to
144 (R.string.maneuver_ramp_left to R.string.maneuver_ramp_left_unnamed),
145 RouteService.API.Maneuver.RAMP_RIGHT to
146 (R.string.maneuver_ramp_right to R.string.maneuver_ramp_right_unnamed),
147 RouteService.API.Maneuver.FORK_LEFT to
148 (R.string.maneuver_fork_left to R.string.maneuver_fork_left_unnamed),
149 RouteService.API.Maneuver.FORK_RIGHT to
150 (R.string.maneuver_fork_right to R.string.maneuver_fork_right_unnamed),
151 RouteService.API.Maneuver.ROUNDABOUT_LEFT to
152 (R.string.maneuver_roundabout to R.string.maneuver_roundabout_unnamed),
153 RouteService.API.Maneuver.ROUNDABOUT_RIGHT to
154 (R.string.maneuver_roundabout to R.string.maneuver_roundabout_unnamed),
155 )
156
157 private fun waitInstruction(
158 context: Context,
159 raw: OfflineRouter.RawStep,
160 ): String? {
161 if (maneuverOf(raw.maneuverId) != RouteService.API.Maneuver.WAIT) return null
162 val waitSeconds = raw.duration10ms / WAIT_CENTISEC_PER_SECOND
163 val waitText = if (waitSeconds >= SECONDS_PER_MINUTE) {
164 "${waitSeconds / SECONDS_PER_MINUTE} min"
165 } else {
166 "$waitSeconds sec"
167 }
168 return if (raw.stopCode != null && raw.stopCode.isNotBlank()) {
169 context.getString(R.string.maneuver_wait_at, waitText, raw.roadName, raw.stopCode)
170 } else {
171 context.getString(R.string.maneuver_wait, waitText, raw.roadName)
172 }
173 }
174
175 private fun fallbackInstruction(
176 context: Context,
177 raw: OfflineRouter.RawStep,
178 mode: RouteService.TravelMode,
179 hasName: Boolean,
180 ): String {
181 if (raw.isTransit && raw.stopCode != null && raw.endStopCode != null) {
182 return context.resources.getQuantityString(
183 R.plurals.maneuver_ride_transit, raw.stopCount,
184 raw.roadName, raw.stopCode, raw.endStopCode, raw.stopCount,
185 )
186 }
187 if (mode == RouteService.TravelMode.TRANSIT) {
188 // A walk leg of an itinerary. The planner names
189 // every one of them "Walk", which the road-name
190 // templates below turn into "Continue onto Walk".
191 // Phrased for real after coalescing, from the
192 // merged duration; this placeholder only has to
193 // compare equal between adjacent walk legs so
194 // they still merge.
195 return WALK_LEG_PLACEHOLDER
196 }
197 return namedOrUnnamed(
198 context, hasName, raw.roadName,
199 R.string.maneuver_unspecified, UiR.string.continue_label,
200 )
201 }
202
203 private fun namedOrUnnamed(
204 context: Context,
205 hasName: Boolean,
206 roadName: String,
207 named: Int,
208 unnamed: Int,
209 ): String = if (hasName) {
210 context.getString(named, roadName)
211 } else {
212 context.getString(unnamed)
213 }
214
215 private fun maneuverOf(maneuverId: Int): RouteService.API.Maneuver =
216 RouteService.API.Maneuver.entries.getOrElse(maneuverId) {
217 RouteService.API.Maneuver.MANEUVER_UNSPECIFIED
218 }
219
220 /**
221 * Decode packed turn lanes into ordered left→right lane guidance. Each int
222 * is `dirMask * 2 + valid`, where dirMask is a bitmask of Maneuver ordinals
223 * the lane offers (real OSM turn:lanes can allow several turns, e.g.
224 * through+right) and bit0 is the active flag (lane leads onto the taken
225 * route).
226 */
227 private fun decodeLane(code: Int): RouteService.API.Lane {
228 val active = (code and LANE_ACTIVE_BIT) == 1
229 val mask = code ushr LANE_MASK_SHIFT
230 val directions = RouteService.API.Maneuver.entries.filter { m ->
231 (mask and (1 shl m.ordinal)) != 0
232 }
233 return RouteService.API.Lane(
234 directions = directions.ifEmpty {
235 listOf(RouteService.API.Maneuver.STRAIGHT)
236 },
237 active = active,
238 )
239 }
240
241 private fun stepTravelMode(
242 raw: OfflineRouter.RawStep,
243 mode: RouteService.TravelMode,
244 ): RouteService.TravelMode = when {
245 raw.isTransit -> RouteService.TravelMode.TRANSIT
246 mode == RouteService.TravelMode.TRANSIT -> RouteService.TravelMode.WALK
247 else -> mode
248 }
249
250 private fun transitDetails(
251 context: Context,
252 raw: OfflineRouter.RawStep,
253 ): RouteService.API.TransitDetails? {
254 if (!raw.isTransit || raw.gtfsFeed == null || raw.stopCode == null) return null
255 return RouteService.API.TransitDetails(
256 headsign = raw.headsign ?: "",
257 stopCount = raw.stopCount,
258 transitLine = RouteService.API.TransitLine(
259 name = raw.roadName,
260 // The index carries route_color for
261 // every feed; GTFSProvider only sees
262 // the bundled APK asset feed, so it is
263 // just a fallback now.
264 color = raw.routeColor
265 .takeIf { it != 0 }
266 ?.let { "#%06X".format(it and RGB_MASK) }
267 ?: GTFSProvider.getRouteColor(context, raw.gtfsFeed, raw.roadName)
268 ?: FALLBACK_ROUTE_COLOR
269 ),
270 stopDetails = RouteService.API.StopDetails(
271 arrivalTime = formatServiceTime(raw.arrSecs),
272 departureTime = formatServiceTime(raw.depSecs),
273 arrivalStop = RouteService.API.Stop(raw.endStopCode ?: ""),
274 departureStop = RouteService.API.Stop(raw.stopCode)
275 ),
276 feedName = raw.gtfsFeed
277 )
278 }
279
280 private fun assembleRoute(
281 context: Context,
282 rawSteps: Array<OfflineRouter.RawStep>,
283 mode: RouteService.TravelMode,
284 fullPolyline: List<GeoPoint>,
285 processedSteps: List<RouteService.Step>,
286 ): RouteService.Route {
287 val coalescedSteps = coalesceSteps(processedSteps)
288 return RouteService.Route(
289 duration = coalescedSteps.sumOf { it.staticDuration.inWholeSeconds }.seconds,
290 distanceMeters = coalescedSteps.sumOf { it.distanceMeters },
291 polyline = fullPolyline,
292 step = phraseWalkLegs(coalescedSteps, mode) { minutes ->
293 context.resources.getQuantityString(
294 R.plurals.maneuver_walk_minutes,
295 minutes,
296 minutes,
297 )
298 },
299 departureTime = leaveAt(rawSteps),
300 arrivalTime = arriveAt(rawSteps),
301 elevationProfile = elevationProfile(rawSteps),
302 // The whole-route total is carried on every RawStep (0 on transit legs),
303 // so the first one is enough.
304 ascentMeters = rawSteps.firstOrNull()?.ascentM ?: 0.0,
305 descentMeters = rawSteps.firstOrNull()?.descentM ?: 0.0,
306 )
307 }
308
309 /**
310 * Build the route-wide elevation profile from the native [OfflineRouter.RawStep]s: walk every step's
311 * per-coordinate [OfflineRouter.RawStep.elevations] (parallel to its geometry), drop the join point each step
312 * shares with the previous one, and pair each with its cumulative ground distance from the
313 * start. Empty when no step carries elevation (transit, or a graph with no DEM).
314 */
315 private fun elevationProfile(rawSteps: Array<OfflineRouter.RawStep>): List<RouteService.ElevationPoint> {
316 val out = mutableListOf<RouteService.ElevationPoint>()
317 var cumDist = 0.0
318 var prevLon = Double.NaN
319 var prevLat = Double.NaN
320 for (raw in rawSteps) {
321 if (raw.elevations.isEmpty()) continue
322 val g = raw.geometry
323 var k = 0
324 while (k + 1 < g.size) {
325 val lon = g[k]
326 val lat = g[k + 1]
327 val elev = raw.elevations.getOrNull(k / 2) ?: break
328 val first = prevLon.isNaN()
329 val dup = !first && lon == prevLon && lat == prevLat
330 if (!dup) {
331 if (!first) cumDist += crowMeters(prevLat, prevLon, lat, lon)
332 out.add(RouteService.ElevationPoint(cumDist, elev))
333 prevLon = lon
334 prevLat = lat
335 }
336 k += 2
337 }
338 }
339 return out
340 }
341
342 /** Approximate ground distance in metres between two lat/lon points (equirectangular). */
343 private fun crowMeters(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
344 val dlat = (lat2 - lat1) * METERS_PER_DEGREE
345 val dlon = (lon2 - lon1) * METERS_PER_DEGREE *
346 Math.cos(Math.toRadians((lat1 + lat2) * LAT_MIDPOINT))
347 return Math.hypot(dlat, dlon)
348 }
349
350 // Coalesce consecutive maneuvers that stay on the same road.
351 // The native router can emit a chain of small "slight left /
352 // slight right" entries along a curving stretch of road
353 // (e.g. El Camino Real bending through Palo Alto) where
354 // the road name never changes — visually that's "stay on
355 // the same road", not a series of turns. Merge those into
356 // a single step whose polyline + distance + duration is the
357 // sum of the merged steps.
358 private fun coalesceSteps(processedSteps: List<RouteService.Step>): List<RouteService.Step> {
359 val coalescedSteps = mutableListOf<RouteService.Step>()
360 for (step in processedSteps) {
361 val prev = coalescedSteps.lastOrNull()
362 // Smart-cast prev to non-null in the merge branch by
363 // gating on prev != null first.
364 if (prev != null && mergesWith(prev, step)) {
365 coalescedSteps[coalescedSteps.lastIndex] = prev.copy(
366 distanceMeters = prev.distanceMeters + step.distanceMeters,
367 staticDuration = prev.staticDuration + step.staticDuration,
368 polyline = mergePolylines(prev.polyline, step.polyline),
369 )
370 } else {
371 coalescedSteps.add(step)
372 }
373 }
374 return coalescedSteps
375 }
376
377 private fun mergesWith(prev: RouteService.Step, step: RouteService.Step): Boolean =
378 prev.travelMode == step.travelMode &&
379 step.travelMode != RouteService.TravelMode.TRANSIT &&
380 step.navInstruction.maneuver in NON_TURNING_MANEUVERS &&
381 // Road name unchanged (instruction text is
382 // road-name-templated, so equal strings ⇒ same road).
383 sameRoadName(prev.navInstruction.instructions, step.navInstruction.instructions)
384
385 /**
386 * Maneuvers that we treat as "still on the same road" when their
387 * instruction text doesn't change between steps. A SHARP turn or a
388 * RAMP / FORK / MERGE / ROUNDABOUT is always a real maneuver even if
389 * the road name happens to match.
390 */
391 private val NON_TURNING_MANEUVERS = setOf(
392 RouteService.API.Maneuver.STRAIGHT,
393 RouteService.API.Maneuver.TURN_SLIGHT_LEFT,
394 RouteService.API.Maneuver.TURN_SLIGHT_RIGHT,
395 RouteService.API.Maneuver.NAME_CHANGE,
396 RouteService.API.Maneuver.MANEUVER_UNSPECIFIED,
397 )
398
399 /**
400 * Two adjacent maneuvers are considered "on the same road" when the
401 * instruction strings match. Instruction text is templated from the
402 * road name (see the maneuver_* string templates), so identical
403 * instruction strings ⇒ same road.
404 */
405 private fun sameRoadName(prev: String, curr: String): Boolean =
406 prev.isNotBlank() && prev == curr
407
408 /** Concatenate two step polylines, skipping the duplicate join point. */
409 private fun mergePolylines(
410 a: List<GeoPoint>,
411 b: List<GeoPoint>,
412 ): List<GeoPoint> {
413 if (a.isEmpty()) return b
414 if (b.isEmpty()) return a
415 return if (a.last() == b.first()) a + b.drop(1) else a + b
416 }
417}