feat: route GPX deviations back to the nearest point ahead

After a sustained deviation from an imported route, a road leg from the
current position is prepended to the rest of the route, starting at the
nearest point ahead of the progress made (never behind). While off the
route, passing within 100 m of a later point counts as reaching it.
The imported geometry itself is never replaced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-26 17:17:33 +01:00
1 parent 31eea182b9
commit 997816f2e4
6 files changed
+156 -14

No files matched your search

@@ -34,6 +34,11 @@ class TftService : Service() {
private var reroutePaused = false
/** True once the rider is past the leg prepended to reach an imported route's first point. */
private var approachDone = false
/** Metres reached along the imported part still to ride (the plan's importedBase, or the route). */
private var importedProgressMeters = 0.0
private var importedLength: Pair<RouteResult, Double>? = null
private fun importedLength(route: RouteResult): Double =
importedLength?.takeIf { it.first === route }?.second ?: routeLength(route).also { importedLength = route to it }
private var lastGpsFix: LocationFix? = null
private var lastGpsElapsed = 0L
private val mutableRouteInfo = MutableStateFlow("Sin ruta calculada")
@@ -701,6 +706,7 @@ class TftService : Service() {
rerouteFailures = 0
reroutePaused = false
approachDone = false
importedProgressMeters = 0.0
if (plan.demo) startDemo(true, preserveRoute = true) else startGps(true, preserveRoute = true)
if (plan.route.imported) {
mutableRouteInfo.value = if (plan.route.maneuvers.isNotEmpty()) "Ruta GPX iniciada · %.1f km · indicaciones de giro activas".format(java.util.Locale.ROOT, plan.route.distanceMeters / 1000.0)
@@ -740,16 +746,40 @@ class TftService : Service() {
val fix = lastGpsFix ?: return state.copy(route = plan.route, navigationStatus = NavigationStatus.GPS_LOST)
requireNotNull(guidance).update(fix, SystemClock.elapsedRealtime(), System.currentTimeMillis(), SystemClock.elapsedRealtime() - lastGpsElapsed)
}
plan.importedBase?.let { base -> guided.remainingDistanceMeters?.let { if (guided.navigationStatus != NavigationStatus.OFF_ROUTE && it <= base.distanceMeters) approachDone = true } }
if (!demo && plan.route.imported) trackImportedProgress(plan, guided)
return if (rerouteJob?.isActive == true && guided.navigationStatus != NavigationStatus.GPS_LOST) guided.copy(navigationStatus = NavigationStatus.REROUTING, nextManeuver = null, distanceToNextManeuverMeters = null, remainingDistanceMeters = null, etaEpochMillis = null) else guided
}
private fun trackImportedProgress(plan: RoutePlan, state: NavigationState) {
val base = plan.importedBase ?: plan.route
val length = importedLength(base)
val remaining = state.remainingDistanceMeters
if (state.navigationStatus != NavigationStatus.OFF_ROUTE && remaining != null && remaining <= length) {
approachDone = true
importedProgressMeters = maxOf(importedProgressMeters, length - remaining)
}
// Off the route, passing close to a later point and heading on counts as having reached it.
if (state.navigationStatus == NavigationStatus.OFF_ROUTE && (approachDone || plan.importedBase == null))
passedAlong(base, state.position, importedProgressMeters)?.let { importedProgressMeters = maxOf(importedProgressMeters, it) }
}
fun requestReroute(manual: Boolean = true) {
val plan = shownRoute ?: return
// Only the leg to an imported route's first point is recalculated; the GPX itself is kept.
val approachBase = plan.importedBase?.takeIf { plan.route.imported && !approachDone }
if (plan.route.imported && approachBase == null) {
if (manual) mutableRouteInfo.value = "Ruta GPX · vuelve al trazado; no se modifica ni recalcula la ruta importada."
// An imported route is never replaced: only the way back to it is calculated. Before reaching
// it, that is its first point; afterwards, the nearest point ahead of the progress made.
if (plan.route.imported && manual && latestNavigationState.navigationStatus != NavigationStatus.OFF_ROUTE) {
if (rerouteJob?.isActive != true) mutableRouteInfo.value = "Ruta GPX · se recalcula el camino de vuelta solo cuando te desvías."
return
}
val rejoin = if (!plan.route.imported) null else {
val base = plan.importedBase ?: plan.route
val position = lastGpsFix?.position
if (plan.importedBase != null && !approachDone) base
else position?.let { rejoinRemainder(base, it, importedProgressMeters) }
}
if (plan.route.imported && rejoin == null) {
if (manual) mutableRouteInfo.value = "Ruta GPX · estás cerca del final; continúa hasta el último punto."
else SystemClock.elapsedRealtime().let { if (reroutePolicy.shouldRequest(latestNavigationState, it)) { reroutePolicy.markRequested(it); reroutePolicy.markFinished(it) } } // Cool down.
return
}
if (plan.demo || routePreview || rerouteJob?.isActive == true) return
@@ -773,11 +803,13 @@ class TftService : Service() {
var retryAfterMs = 0L
try {
val engine = routingEngineFactory(routingEndpoint())
val result = if (approachBase != null) prependApproach(engine.calculateRoute(fix.position, approachBase.geometry.first(), APPROACH_OPTIONS), approachBase)
val result = if (rejoin != null) prependApproach(engine.calculateRoute(fix.position, rejoin.geometry.first(), APPROACH_OPTIONS), rejoin)
else engine.calculateRoute(fix.position, plan.route.destination ?: plan.route.geometry.last(), plan.options)
ensureActive()
if (epoch != navigationEpoch || generation != routeGeneration || shownRoute !== plan) return@launch
val replacement = RoutePlan(result, fix.position, false, plan.options, approachBase)
val replacement = RoutePlan(result, fix.position, false, plan.options, rejoin)
// A new base starts where the rider rejoins: the route has been reached.
if (rejoin != null && rejoin !== plan.importedBase) { importedProgressMeters = 0.0; approachDone = true }
shownRoute = replacement
if (!preparedDestinationDirty && routePlan === plan) routePlan = replacement
guidance = RouteGuidanceTracker(result)
@@ -74,7 +74,7 @@ class ImportedRouteTest {
assertTrue(service.hasActiveGuidance())
assertSame(route.route, service.navigationState.value.route)
service.requestReroute(); tick()
assertTrue(service.routeInfo.value.contains("no se modifica"))
assertTrue(service.routeInfo.value.contains("solo cuando te desvías"))
assertSame(route.route, service.navigationState.value.route)
assertNull(service.navigationState.value.nextManeuver)
assertNull(service.navigationState.value.etaEpochMillis)
@@ -280,7 +280,7 @@ class ImportedRouteTest {
latitude = 43.34; longitude = -5.84; accuracy = 5f
time = System.currentTimeMillis(); elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()
}); tick()
service.requestReroute(); tick()
service.requestReroute(false); tick()
assertEquals(GeoPoint(43.34, -5.84) to route.route.geometry.first(), engine.requests.last())
val shown = TftService::class.java.getDeclaredField("shownRoute").apply { isAccessible = true }.get(service)!!
val rerouted = shown.javaClass.getDeclaredMethod("getRoute").apply { isAccessible = true }.invoke(shown) as RouteResult
@@ -289,5 +289,40 @@ class ImportedRouteTest {
assertTrue(rerouted.imported)
} finally { activityController.destroy(); serviceController.destroy() }
}
@Test fun deviationFromAnImportedTraceRoutesBackToTheNearestPointAhead() {
val controller = Robolectric.buildService(TftService::class.java).create()
val service = controller.get()
service.mapRenderOverride = { _, _ -> TftFrame(encodedBytes = byteArrayOf(1), timestampMs = 0) }
try {
val application = RuntimeEnvironment.getApplication()
shadowOf(application).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
val manager = application.getSystemService(LocationManager::class.java)
shadowOf(manager).setProviderEnabled(LocationManager.GPS_PROVIDER, true)
fun fix(latitude: Double, longitude: Double) {
shadowOf(manager).simulateLocation(Location(LocationManager.GPS_PROVIDER).apply {
this.latitude = latitude; this.longitude = longitude; accuracy = 5f
time = System.currentTimeMillis(); elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()
}); tick()
}
val route = imported()
service.prepareImportedRoute(route); tick()
service.setPhoneVisible(true); tick()
fix(43.36, -5.85)
service.startRoute(); tick()
assertTrue(service.hasActiveGuidance())
val engine = RoadEngine()
service.routingEngineFactory = { engine }
fix(43.365, -5.847) // About 240 m east of the trace's midpoint.
service.requestReroute(false); tick()
assertEquals(GeoPoint(43.365, -5.847) to GeoPoint(43.365, -5.85), engine.requests.single())
val shown = TftService::class.java.getDeclaredField("shownRoute").apply { isAccessible = true }.get(service)!!
val rerouted = shown.javaClass.getDeclaredMethod("getRoute").apply { isAccessible = true }.invoke(shown) as RouteResult
assertEquals(GeoPoint(43.365, -5.847), rerouted.geometry.first())
assertEquals(route.route.geometry.last(), rerouted.geometry.last())
assertTrue(rerouted.imported)
assertTrue(rerouted.maneuvers.isEmpty())
} finally { controller.destroy() }
}
}
@@ -279,6 +279,53 @@ private fun wrappedLongitude(value: Double): Double = ((value + 180) % 360 + 360
const val IMPORTED_APPROACH_MIN_METERS = 150.0
fun needsApproach(position: GeoPoint, route: RouteResult): Boolean =
route.geometry.isNotEmpty() && earthDistance(position, route.geometry.first()) > IMPORTED_APPROACH_MIN_METERS
/** Length of [route]'s geometry in metres, as measured by guidance. */
fun routeLength(route: RouteResult): Double = route.geometry.zipWithNext().sumOf { (a, b) -> earthDistance(a, b) }
/**
* Off an imported route, passing within [radiusMeters] of a later point counts as having reached it:
* returns the furthest such distance along [route] in the [windowMeters] after [fromMeters], or null.
*/
fun passedAlong(route: RouteResult, position: GeoPoint, fromMeters: Double, radiusMeters: Double = 100.0, windowMeters: Double = 3_000.0): Double? {
var along = 0.0
var passed: Double? = null
route.geometry.forEachIndexed { i, point ->
if (i > 0) along += earthDistance(route.geometry[i - 1], point)
if (along > fromMeters + windowMeters) return passed
if (along >= fromMeters && earthDistance(position, point) <= radiusMeters) passed = along
}
return passed
}
/**
* The rest of [route] from its point nearest to [position] among those in the [windowMeters] after
* [fromMeters] (never behind it), with maneuvers rebased and distance/duration prorated. Null when
* only the final point is left.
*/
fun rejoinRemainder(route: RouteResult, position: GeoPoint, fromMeters: Double, windowMeters: Double = 10_000.0): RouteResult? {
val cumulative = DoubleArray(route.geometry.size)
for (i in 1 until route.geometry.size) cumulative[i] = cumulative[i - 1] + earthDistance(route.geometry[i - 1], route.geometry[i])
val total = cumulative.last()
val start = cumulative.indexOfFirst { it >= fromMeters }.takeIf { it >= 0 } ?: return null
var best = start
var bestDistance = Double.POSITIVE_INFINITY
for (i in start until route.geometry.size) {
if (cumulative[i] > fromMeters + windowMeters) break
val distance = earthDistance(position, route.geometry[i])
if (distance < bestDistance) { best = i; bestDistance = distance }
}
if (best >= route.geometry.lastIndex) return null
if (best == 0) return route
val share = if (total > 0) (total - cumulative[best]) / total else 0.0
return route.copy(
geometry = route.geometry.drop(best),
maneuvers = route.maneuvers.filter { (it.beginShapeIndex ?: -1) >= best }.map {
it.copy(beginShapeIndex = it.beginShapeIndex?.minus(best), endShapeIndex = it.endShapeIndex?.minus(best))
},
distanceMeters = (route.distanceMeters * share).roundToInt().coerceAtLeast(1),
durationSeconds = (route.durationSeconds * share).roundToInt(),
)
}
private fun earthDistance(a: GeoPoint, b: GeoPoint): Double {
val lat1 = Math.toRadians(a.latitude); val lat2 = Math.toRadians(b.latitude)
val dlat = lat2 - lat1; val dlon = Math.toRadians(wrappedLongitude(b.longitude - a.longitude))
@@ -198,7 +198,8 @@ fun mergeRouteLegs(parts: List<RouteResult>): RouteResult {
*/
fun prependApproach(approach: RouteResult, route: RouteResult): RouteResult {
val merged = mergeRouteLegs(listOf(approach, route))
return if (route.imported && route.maneuvers.isEmpty()) merged.copy(maneuvers = emptyList(), durationSeconds = 0) else merged
// Raw traces carry no travel time; road-routed imports keep it even if no maneuver is left ahead.
return if (route.imported && route.durationSeconds == 0) merged.copy(maneuvers = emptyList(), durationSeconds = 0) else merged
}
private fun validatePoint(point: GeoPoint) {
@@ -207,5 +207,28 @@ class ValhallaRouteTest {
assertEquals(trace.destination, merged.destination)
assertEquals(0, merged.durationSeconds) // A trace never shows an ETA.
}
@Test fun `rejoining an imported route never goes back and counts points passed nearby`() {
val points = (0..10).map { GeoPoint(43.0 + it * 0.001, -5.0) } // About 111 m apart.
val route = RouteResult(points, listOf(
Maneuver("right", 100, type = 10, beginShapeIndex = 3, endShapeIndex = 4),
Maneuver("left", 100, type = 15, beginShapeIndex = 7, endShapeIndex = 8),
), 1_110, 100, points.last(), imported = true)
val step = routeLength(route) / 10
// Off to the side of point 2, but progress already reached point 5.
val ahead = rejoinRemainder(route, GeoPoint(43.002, -4.998), 5 * step - 1)!!
assertEquals(points[5], ahead.geometry.first())
assertEquals(listOf(15), ahead.maneuvers.map { it.type })
assertEquals(2, ahead.maneuvers.single().beginShapeIndex)
assertEquals(555, ahead.distanceMeters)
assertEquals(50, ahead.durationSeconds)
// Nearest point ahead, not the next one.
assertEquals(points[8], rejoinRemainder(route, GeoPoint(43.008, -4.999), 0.0)!!.geometry.first())
assertNull(rejoinRemainder(route, points.last(), 0.0))
// Riding past point 4 within 100 m counts; a point beyond the window does not.
assertEquals(4 * step, passedAlong(route, GeoPoint(43.004, -4.9995), 0.0)!!, 1e-6)
assertNull(passedAlong(route, GeoPoint(43.004, -4.99), 0.0))
assertNull(passedAlong(route, points[9], 0.0, windowMeters = 500.0))
}
}
+8 -4
View File
@@ -14,20 +14,24 @@ Files are limited to 5 MiB, 10,000 total route and track points and 64 XML nesti
Route points (`rtept`), waypoints and sparse tracks (median gap between points above 250 m, typical of planner exports with hand-placed clicks) are not drawn as straight lines. The app sends the ordered points to the configured Valhalla server with the motorcycle profile, avoiding unpaved roads; route points and waypoints also avoid motorways, while sparse tracks may use them because the recording may have. The first and last points are `break` locations and the rest are `through`, so the route passes every point without announcing an arrival at each one. Requests carry at most 20 points; longer lists are split into consecutive requests that share their boundary point and are merged into one route. At most 400 points are sent; longer lists are evenly downsampled keeping both ends.
The result has real turn instructions, voice announcements and an ETA. It is not recalculated automatically during navigation so that the planned points are respected. If the calculation fails (no connection, server busy), the panel says so and offers **Reintentar**; the app never falls back to straight lines. Dense recorded tracks are followed as they are, without contacting the routing server.
The result has real turn instructions, voice announcements and an ETA. The route itself is never replaced during navigation, so the planned points are respected; deviations are handled as described in [Deviations](#deviations). If the calculation fails (no connection, server busy), the panel says so and offers **Reintentar**; the app never falls back to straight lines. Dense recorded tracks are followed as they are, without contacting the routing server.
## Starting away from the first point
On start, if the rider is more than 150 m from the route's first point, the app calculates a road leg from the current position to that point (fastest motorcycle route, avoiding unpaved roads) and prepends it, so guidance begins where the rider actually is. A dense trace stays a trace: the leg extends the line to follow, without turn instructions or ETA. If you leave that leg before reaching the route, it is recalculated from your position with the normal off-route policy (sustained deviation, 30 s between attempts). Once you are on the imported route, deviations are never rerouted. If the leg cannot be calculated, navigation starts on the imported route alone and the app asks the rider to head to the first point. Pressing start again later recalculates the leg from the new position.
On start, if the rider is more than 150 m from the route's first point, the app calculates a road leg from the current position to that point (fastest motorcycle route, avoiding unpaved roads) and prepends it, so guidance begins where the rider actually is. A dense trace stays a trace: the leg extends the line to follow, without turn instructions or ETA. If you leave that leg before reaching the route, it is recalculated from your position with the normal off-route policy (sustained deviation, 30 s between attempts). If the leg cannot be calculated, navigation starts on the imported route alone and the app asks the rider to head to the first point. Pressing start again later recalculates the leg from the new position.
## Following a trace
Dense tracks keep their original coordinates in memory and are drawn on the phone and TFT. Following such a trace sends no GPX coordinates to a routing server; only the optional leg from your position to its first point is calculated online. It works with the installed offline map; online background tiles still require a connection when no offline map is selected. Standard trace points do not establish legal roads, surface quality, reliable turns or travel time.
The display says **Sigue el trazado GPX**. It shows progress, remaining distance, sustained deviations and arrival using the existing GPS guidance policy. It does not invent turn instructions, speak turn announcements, show an ETA, or automatically reroute away from the imported trace. On a deviation, return to the trace using the map and road signs. Manual recalculation also preserves the trace. After a confirmed deviation, three fresh, stable GPS fixes spanning at least two seconds automatically resume progress at the nearest point of the original trace, whether you rejoin ahead of or behind the previous position. GPS jumps and inaccurate fixes cannot confirm a rejoin.
The display says **Sigue el trazado GPX**. It shows progress, remaining distance, sustained deviations and arrival using the existing GPS guidance policy. It does not invent turn instructions, speak turn announcements or show an ETA. After a confirmed deviation, three fresh, stable GPS fixes spanning at least two seconds automatically resume progress at the nearest point of the original trace, whether you rejoin ahead of or behind the previous position. GPS jumps and inaccurate fixes cannot confirm a rejoin.
The imported route is not persisted across process death or device reboot: reload the original document to resume. The document remains in its selected provider; the app does not request long-term file access or copy the GPX into its own storage. Map diagnostics do not include route coordinates, document paths or route names.
## Deviations
After a sustained deviation from an imported route (the normal off-route policy: confirmed fixes, at most one attempt every 30 s), the app calculates a road leg from your position back to the route and prepends it; the imported geometry itself is kept. Before you have reached the route, the leg goes to its first point. Afterwards it goes to the nearest route point ahead of the progress you had made, searched within the next 10 km, so it never sends you back. While off the route, passing within 100 m of a later route point (within the next 3 km) counts as having reached it: riding past a point towards the next one is fine. Near the last point there is nothing to rejoin and the route simply ends. **Recalcular ahora** only acts while off the route. The leg back follows the same rules as the route: a trace gets no turn instructions or ETA.
## Validation
Core tests exercise standard GPX routes/tracks, stop extraction for routes, waypoints and sparse tracks, multi-point Valhalla requests and leg merging, namespaces, malicious XML, resource limits and trace guidance without invented turns or ETA. Android unit tests exercise road calculation of route points and its retry on failure, the document picker, cancellation, precise-location permission denial, preview/start/stop and prevention of online recalculation with the renderer replaced to avoid device-only JNI.
Core tests exercise standard GPX routes/tracks, stop extraction for routes, waypoints and sparse tracks, multi-point Valhalla requests and leg merging, rejoin points that never go backwards and points passed nearby, namespaces, malicious XML, resource limits and trace guidance without invented turns or ETA. Android unit tests exercise road calculation of route points and its retry on failure, the document picker, cancellation, precise-location permission denial, preview/start/stop the leg from the rider's position to the first point, rerouting back to the nearest point ahead with the renderer replaced to avoid device-only JNI.