feat: road-route imported GPX stops and widen the TFT camera

- Route points, waypoints and sparse tracks are joined along roads with
  multi-location Valhalla requests (chunks of 20, merged legs); failures
  offer a retry instead of straight lines.
- TFT camera: lower zoom, 45 degree pitch and rider lower in the frame;
  rider zoom offset from Settings and NaviLite zoom requests 51/52.
- Online map failures fall back to an installed offline pack for 30 s.
- Production-facing copy cleanup and docs; version 0.14.8 (25).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-26 16:27:51 +01:00
1 parent 694fefd98b
commit b7bf2c2b43
22 files changed
+453 -116

No files matched your search

@@ -58,6 +58,12 @@ data class RouteOptions(
interface RoutingEngine {
suspend fun calculateRoute(origin: GeoPoint, destination: GeoPoint, options: RouteOptions): RouteResult
suspend fun recalculateRoute(origin: GeoPoint, previousRoute: RouteResult, options: RouteOptions): RouteResult
/** Route along roads through ordered stops. The default joins independent legs. */
suspend fun calculateRouteThrough(stops: List<GeoPoint>, options: RouteOptions): RouteResult {
require(stops.size >= 2) { "At least two stops are required" }
return mergeRouteLegs(stops.zipWithNext().map { (from, to) -> calculateRoute(from, to, options) })
.copy(destination = stops.last())
}
}
data class SearchResult(
val name: String,
@@ -9,12 +9,22 @@ import org.xml.sax.SAXException
import org.xml.sax.ext.DefaultHandler2
import kotlin.math.*
data class ImportedRoute(val name: String?, val route: RouteResult, val isTrack: Boolean = false)
/**
* [stops] is non-empty when the geometry is a list of points to be joined along roads
* (route points, waypoints or a sparse track) rather than a trace that can be followed as is.
*/
data class ImportedRoute(val name: String?, val route: RouteResult, val isTrack: Boolean = false, val stops: List<GeoPoint> = emptyList()) {
val needsRoadRouting: Boolean get() = stops.size >= 2
}
/** Imports geometry only: GPX points do not establish road turns, speeds or travel time. */
object GpxRouteImporter {
const val MAX_BYTES = 5 * 1024 * 1024
const val MAX_POINTS = 10_000
/** Upper bound of points sent to the routing server for one import. */
const val MAX_STOPS = 400
/** Recorded or road-snapped traces are much denser; planners' hand-placed points are not. */
const val SPARSE_TRACK_MEDIAN_METERS = 250.0
const val MAX_DEPTH = 64
private val namespaces = setOf("", "http://www.topografix.com/GPX/1/0", "http://www.topografix.com/GPX/1/1")
@@ -49,18 +59,30 @@ object GpxRouteImporter {
if (points.size < 2) fail("El GPX necesita al menos dos puntos de ruta o track.")
val distance = points.zipWithNext().sumOf { (a, b) -> distance(a, b) }
if (!distance.isFinite() || distance <= 0.0) fail("El GPX necesita al menos dos puntos distintos.")
val stops = if (!handler.isTrack || isSparse(points)) downsample(points.filterIndexed { i, point -> i == 0 || point != points[i - 1] }) else emptyList()
return ImportedRoute(handler.name?.trim()?.takeIf { it.isNotEmpty() }, RouteResult(
geometry = points.toList(), maneuvers = emptyList(), distanceMeters = distance.roundToInt().coerceAtLeast(1),
durationSeconds = 0, destination = points.last(), imported = true,
), handler.isTrack)
), handler.isTrack, stops)
}
private fun isSparse(points: List<GeoPoint>): Boolean {
val gaps = points.zipWithNext().map { (a, b) -> distance(a, b) }.filter { it > 0.0 }.sorted()
return gaps.isNotEmpty() && gaps[gaps.size / 2] > SPARSE_TRACK_MEDIAN_METERS
}
/** Keep the endpoints and an even spread of the remaining points. */
private fun downsample(points: List<GeoPoint>): List<GeoPoint> {
if (points.size <= MAX_STOPS) return points
return (0 until MAX_STOPS).map { points[(it.toLong() * points.lastIndex / (MAX_STOPS - 1)).toInt()] }
}
private class Handler : DefaultHandler2() {
private val routePoints = mutableListOf<GeoPoint>()
private val trackPoints = mutableListOf<GeoPoint>()
private val waypoints = mutableListOf<GeoPoint>()
private var routeName: String? = null
private var trackName: String? = null
val points: List<GeoPoint> get() = if (tracks > 0) trackPoints else routePoints
val points: List<GeoPoint> get() = if (tracks > 0) trackPoints else if (routes > 0) routePoints else waypoints
val isTrack: Boolean get() = tracks > 0
val name: String? get() = if (tracks > 0) trackName else routeName
private val path = mutableListOf<String>()
@@ -88,15 +110,16 @@ object GpxRouteImporter {
}
if (path == listOf("gpx", "trk", "trkseg")) segmentPoints = 0
if (path == listOf("gpx", "rte", "name") || path == listOf("gpx", "trk", "name")) nameText = StringBuilder()
if (path == listOf("gpx", "rte", "rtept") || path == listOf("gpx", "trk", "trkseg", "trkpt")) {
if (routePoints.size + trackPoints.size >= MAX_POINTS) fail("El GPX supera los 10000 puntos. Simplifica la ruta antes de importarla.")
if (path == listOf("gpx", "rte", "rtept") || path == listOf("gpx", "trk", "trkseg", "trkpt") || path == listOf("gpx", "wpt")) {
if (routePoints.size + trackPoints.size + waypoints.size >= MAX_POINTS) fail("El GPX supera los 10000 puntos. Simplifica la ruta antes de importarla.")
val lat = attributes.getValue("lat")?.toDoubleOrNull()
val lon = attributes.getValue("lon")?.toDoubleOrNull()
if (lat == null || lon == null || !lat.isFinite() || !lon.isFinite() || lat !in -90.0..90.0 || lon !in -180.0..180.0) fail("El GPX contiene coordenadas inválidas.")
if (path[1] == "trk") {
trackPoints.add(GeoPoint(lat, lon))
segmentPoints++
} else routePoints.add(GeoPoint(lat, lon))
when (path[1]) {
"trk" -> { trackPoints.add(GeoPoint(lat, lon)); segmentPoints++ }
"rte" -> routePoints.add(GeoPoint(lat, lon))
else -> waypoints.add(GeoPoint(lat, lon))
}
}
}
override fun characters(ch: CharArray, start: Int, length: Int) {
@@ -22,6 +22,9 @@ data class GuidanceConfig(
}
}
/** Raw imported traces carry no travel time; road-routed imports keep the server's estimate. */
val RouteResult.hasEta: Boolean get() = !imported || durationSeconds > 0
/** Stateful projection/progress for one route. Create another tracker when replacing the route. */
class RouteGuidanceTracker(private val route: RouteResult, private val config: GuidanceConfig = GuidanceConfig()) {
private val line = RouteLine(route)
@@ -55,7 +58,7 @@ class RouteGuidanceTracker(private val route: RouteResult, private val config: G
val distinct = lastTimestamp != fix.timestampMs
if (!distinct) return lastState ?: base.copy(navigationStatus = NavigationStatus.GPS_LOST)
if (arrived) return remember(base.copy(speed = 0f, remainingDistanceMeters = 0,
etaEpochMillis = if (route.imported) null else epochMs, navigationStatus = NavigationStatus.ARRIVED))
etaEpochMillis = if (!route.hasEta) null else epochMs, navigationStatus = NavigationStatus.ARRIVED))
if (needsRecovery || lastNow?.let { nowMs - it > config.maxFixAgeMs } == true) {
outside.reset(); arrival.reset(); rejoin.reset(); rejoinProgress = null
needsRecovery = false
@@ -119,7 +122,7 @@ class RouteGuidanceTracker(private val route: RouteResult, private val config: G
earthDistance(fix.position, route.geometry.last()) <= config.arrivalRadiusMeters
arrived = arrival.observe(close, distinct, nowMs, config.arrivalFixes, config.arrivalDurationMs)
if (arrived) return remember(base.copy(speed = 0f, remainingDistanceMeters = 0,
etaEpochMillis = if (route.imported) null else epochMs, navigationStatus = NavigationStatus.ARRIVED))
etaEpochMillis = if (!route.hasEta) null else epochMs, navigationStatus = NavigationStatus.ARRIVED))
return remember(line.guidedState(base, progress, epochMs))
}
}
@@ -154,9 +157,9 @@ class RouteDemo(private val route: RouteResult, private val speedMetersPerSecond
val base = NavigationState(position = position, bearing = bearing, speed = speedMetersPerSecond,
route = route, accuracyMeters = 3f)
if (progress >= line.total) return base.copy(speed = 0f, remainingDistanceMeters = 0,
etaEpochMillis = if (route.imported) null else epochMs, navigationStatus = NavigationStatus.ARRIVED)
etaEpochMillis = if (!route.hasEta) null else epochMs, navigationStatus = NavigationStatus.ARRIVED)
val state = line.guidedState(base, progress, epochMs)
return state.copy(etaEpochMillis = if (route.imported) null else saturatedAdd(epochMs, ((line.total - progress) / speedMetersPerSecond * 1000).roundToLong()))
return state.copy(etaEpochMillis = if (!route.hasEta) null else saturatedAdd(epochMs, ((line.total - progress) / speedMetersPerSecond * 1000).roundToLong()))
}
}
@@ -249,7 +252,7 @@ private class RouteLine(private val route: RouteResult) {
val etaMs = (route.durationSeconds * 1000.0 * remaining / total).roundToLong()
return base.copy(nextManeuver = next?.first,
distanceToNextManeuverMeters = next?.let { (it.second - progress).coerceAtLeast(0.0).roundToInt() },
remainingDistanceMeters = remaining.roundToInt(), etaEpochMillis = if (route.imported) null else saturatedAdd(epochMs, etaMs),
remainingDistanceMeters = remaining.roundToInt(), etaEpochMillis = if (!route.hasEta) null else saturatedAdd(epochMs, etaMs),
navigationStatus = NavigationStatus.NAVIGATING)
}
fun pointAt(progress: Double): Pair<GeoPoint, Float> {
@@ -4,20 +4,35 @@ package dev.navframe.core
data class TftCameraParameters(
val bearingDegrees: Float,
val zoom: Double,
val riderAnchorY: Float = 0.72f,
/** Rider position as a fraction of the frame height, measured from the top. */
val riderAnchorY: Float = 0.78f,
/** Perspective tilt; the road ahead stays visible further away than in a flat view. */
val pitchDegrees: Double = 0.0,
)
class TftCameraPolicy {
/**
* Wide enough to read the next bends before reaching them. [zoomOffset] is the rider's own
* adjustment (handlebar or phone controls), added to the speed-based level.
*/
class TftCameraPolicy(private val zoomOffset: Double = 0.0) {
fun parameters(state: NavigationState): TftCameraParameters {
val kmh = state.speed.coerceAtLeast(0f) * 3.6f
val approachingTurn = state.nextManeuver != null &&
state.distanceToNextManeuverMeters?.let { it in 0..150 } == true
val zoom = when {
approachingTurn -> 17.5
kmh < 30 -> 17.0
kmh <= 70 -> 16.0
else -> 15.0
state.distanceToNextManeuverMeters?.let { it in 0..200 } == true
val base = when {
approachingTurn -> 15.5
kmh < 30 -> 15.5
kmh <= 70 -> 15.0
else -> 14.5
}
return TftCameraParameters(normalizeBearing(state.bearing), zoom)
val zoom = (base + zoomOffset.coerceIn(MIN_OFFSET, MAX_OFFSET)).coerceIn(12.0, 18.0)
return TftCameraParameters(normalizeBearing(state.bearing), zoom, pitchDegrees = PITCH_DEGREES)
}
companion object {
const val PITCH_DEGREES = 45.0
const val ZOOM_STEP = 0.5
const val MIN_OFFSET = -2.0
const val MAX_OFFSET = 2.0
fun stepOffset(current: Double, steps: Int): Double = (current + steps * ZOOM_STEP).coerceIn(MIN_OFFSET, MAX_OFFSET)
}
}
@@ -9,22 +9,28 @@ import kotlin.math.roundToInt
private const val MAX_RESPONSE_CHARS = 2 * 1024 * 1024
private const val MAX_SHAPE_POINTS = 100_000
/** Public Valhalla instances commonly cap a request at 20 locations. */
const val MAX_REQUEST_LOCATIONS = 20
private val routeJson = GsonBuilder().setStrictness(Strictness.STRICT).create()
/** Original adapter; no Valhalla implementation code is embedded. Errors omit response contents. */
class ValhallaRouteException(message: String) : IllegalArgumentException(message)
/** Explicit coordinate request. The HTTP adapter owns rate limits, headers and cancellation. */
fun buildValhallaRequest(origin: GeoPoint, destination: GeoPoint, options: RouteOptions = RouteOptions(), language: String = "es-ES"): String {
validatePoint(origin)
validatePoint(destination)
fun buildValhallaRequest(origin: GeoPoint, destination: GeoPoint, options: RouteOptions = RouteOptions(), language: String = "es-ES"): String =
buildValhallaRequest(listOf(origin, destination), options, language)
/** Intermediate stops are `through` locations: one leg, no arrival announcements or U-turns at them. */
fun buildValhallaRequest(stops: List<GeoPoint>, options: RouteOptions = RouteOptions(), language: String = "es-ES"): String {
if (stops.size !in 2..MAX_REQUEST_LOCATIONS) invalid("Invalid routing location count")
stops.forEach(::validatePoint)
val request = JsonObject()
request.add("locations", JsonArray().apply {
listOf(origin, destination).forEach { point ->
stops.forEachIndexed { index, point ->
add(JsonObject().apply {
addProperty("lat", point.latitude)
addProperty("lon", point.longitude)
addProperty("type", "break")
addProperty("type", if (index == 0 || index == stops.lastIndex) "break" else "through")
})
}
})
@@ -153,6 +159,39 @@ fun parseValhallaRoute(json: String, destination: GeoPoint? = null): RouteResult
}
}
/**
* Join consecutive routes that share their boundary stop into one route. Maneuver indices are
* rebased onto the merged geometry and arrivals at intermediate boundaries are dropped.
*/
fun mergeRouteLegs(parts: List<RouteResult>): RouteResult {
require(parts.isNotEmpty()) { "No route parts" }
if (parts.size == 1) return parts.single()
val geometry = ArrayList<GeoPoint>()
val maneuvers = ArrayList<Maneuver>()
var meters = 0L
var seconds = 0L
parts.forEachIndexed { index, part ->
require(part.geometry.size >= 2) { "Route part has insufficient geometry" }
val skipFirst = geometry.isNotEmpty() && geometry.last() == part.geometry.first()
val offset = geometry.size - if (skipFirst) 1 else 0
geometry.addAll(if (skipFirst) part.geometry.drop(1) else part.geometry)
val last = index == parts.lastIndex
// Chunk boundaries are not real stops: drop their arrivals and the next chunk's depart (types 1-3).
part.maneuvers.filter { (last || maneuverDirection(it.type) != ManeuverDirection.ARRIVAL) && (index == 0 || it.type !in 1..3) }.mapTo(maneuvers) {
it.copy(beginShapeIndex = it.beginShapeIndex?.plus(offset), endShapeIndex = it.endShapeIndex?.plus(offset))
}
meters += part.distanceMeters
seconds += part.durationSeconds
}
if (geometry.size > MAX_SHAPE_POINTS + 1) invalid("Too many route shape points")
val surfaces = parts.map { it.hasUnpaved }
return parts.last().copy(geometry = geometry, maneuvers = maneuvers,
distanceMeters = meters.coerceAtMost(Int.MAX_VALUE.toLong()).toInt(),
durationSeconds = seconds.coerceAtMost(Int.MAX_VALUE.toLong()).toInt(),
hasUnpaved = if (true in surfaces) true else if (surfaces.all { it == false }) false else null,
guidanceLanguage = parts.first().guidanceLanguage)
}
private fun validatePoint(point: GeoPoint) {
if (!point.latitude.isFinite() || !point.longitude.isFinite() ||
point.latitude !in -90.0..90.0 || point.longitude !in -180.0..180.0) invalid("Invalid routing coordinate")
@@ -34,8 +34,19 @@ class DemoNavigationTest {
assertTrue(fast.zoom < slow.zoom)
assertEquals(359f, slow.bearingDegrees)
assertEquals(1f, fast.bearingDegrees)
assertTrue(fast.riderAnchorY in 0.66f..0.8f)
assertTrue(fast.riderAnchorY in 0.7f..0.85f)
assertTrue(fast.pitchDegrees > 0)
val approaching = policy.parameters(NavigationState(speed = 25f, nextManeuver = Maneuver("derecha", 100), distanceToNextManeuverMeters = 100))
assertTrue(approaching.zoom > slow.zoom)
assertTrue(approaching.zoom > fast.zoom)
// Never so close that the bend after the turn is off screen.
assertTrue(approaching.zoom <= slow.zoom)
}
@Test fun riderZoomOffsetIsBoundedAndApplied() {
val state = NavigationState(speed = 10f)
val base = TftCameraPolicy().parameters(state).zoom
assertEquals(base + 1.0, TftCameraPolicy(1.0).parameters(state).zoom, 1e-9)
assertEquals(base + TftCameraPolicy.MAX_OFFSET, TftCameraPolicy(99.0).parameters(state).zoom, 1e-9)
assertEquals(TftCameraPolicy.MIN_OFFSET, TftCameraPolicy.stepOffset(-1.5, -3), 1e-9)
assertEquals(0.5, TftCameraPolicy.stepOffset(0.0, 1), 1e-9)
}
}
@@ -103,4 +103,27 @@ class GpxRouteImporterTest {
assertNull(outside.etaEpochMillis)
}
@Test fun `route points and waypoints are stops to join along roads`() {
val route = parse("<gpx><rte>$points<rtept lat=\"43.001\" lon=\"-5\"/></rte></gpx>")
assertTrue(route.needsRoadRouting)
// Consecutive duplicates would only produce zero-length legs.
assertEquals(listOf(GeoPoint(43.0, -5.0), GeoPoint(43.001, -5.0)), route.stops)
val waypoints = parse("<gpx><metadata/><wpt lat=\"43\" lon=\"-5\"/><wpt lat=\"43.2\" lon=\"-5.1\"/><wpt lat=\"43.4\" lon=\"-5\"/></gpx>")
assertFalse(waypoints.isTrack)
assertEquals(3, waypoints.stops.size)
}
@Test fun `detailed tracks are followed but sparse tracks are road routed`() {
fun track(step: Double, count: Int) = parse("<gpx><trk><trkseg>" +
(0 until count).joinToString("") { "<trkpt lat=\"${43 + it * step}\" lon=\"-5\"/>" } + "</trkseg></trk></gpx>")
val recorded = track(0.0002, 200) // About 22 m apart.
assertTrue(recorded.isTrack)
assertFalse(recorded.needsRoadRouting)
val planned = track(0.01, 30) // About 1.1 km apart: straight lines between clicks.
assertTrue(planned.needsRoadRouting)
assertEquals(30, planned.stops.size)
val long = track(0.004, 1_000)
assertEquals(GpxRouteImporter.MAX_STOPS, long.stops.size)
assertEquals(long.route.geometry.first(), long.stops.first())
assertEquals(long.route.geometry.last(), long.stops.last())
}
}
@@ -163,4 +163,30 @@ class ValhallaRouteTest {
try { block(); fail("Expected invalid routing data to be rejected") }
catch (_: ValhallaRouteException) { /* expected */ }
}
@Test fun `multi stop request routes through intermediate stops in one leg`() {
val stops = (0..4).map { GeoPoint(43.3 + it * 0.01, -5.8) }
val locations = JsonParser.parseString(buildValhallaRequest(stops)).asJsonObject.getAsJsonArray("locations")
assertEquals(listOf("break", "through", "through", "through", "break"), locations.map { it.asJsonObject["type"].asString })
assertEquals(43.32, locations[2].asJsonObject["lat"].asDouble, 1e-9)
try { buildValhallaRequest(List(MAX_REQUEST_LOCATIONS + 1) { stops[0] }); fail("Expected location limit") } catch (_: ValhallaRouteException) { }
}
@Test fun `merged legs rebase maneuvers and drop intermediate arrivals`() {
val a = GeoPoint(43.0, -5.0); val b = GeoPoint(43.01, -5.0); val c = GeoPoint(43.02, -5.0); val d = GeoPoint(43.03, -5.0)
fun part(from: GeoPoint, mid: GeoPoint, to: GeoPoint, unpaved: Boolean?) = RouteResult(listOf(from, mid, to), listOf(
Maneuver("start", 10, type = 1, beginShapeIndex = 0, endShapeIndex = 1),
Maneuver("right", 10, type = 10, beginShapeIndex = 1, endShapeIndex = 2),
Maneuver("arrive", 0, type = 4, beginShapeIndex = 2, endShapeIndex = 2),
), 1_000, 60, to, hasUnpaved = unpaved)
val merged = mergeRouteLegs(listOf(part(a, b, c, false), part(c, GeoPoint(43.025, -5.0), d, null)))
assertEquals(5, merged.geometry.size)
assertEquals(listOf(1, 10, 10, 4), merged.maneuvers.map { it.type })
assertEquals(listOf(0, 1, 3, 4), merged.maneuvers.map { it.beginShapeIndex })
assertEquals(2_000, merged.distanceMeters)
assertEquals(120, merged.durationSeconds)
assertNull(merged.hasUnpaved)
assertEquals(d, merged.destination)
// Independently snapped endpoints that do not coincide keep both points.
assertEquals(6, mergeRouteLegs(listOf(part(a, b, c, true), part(GeoPoint(43.0201, -5.0), GeoPoint(43.025, -5.0), d, false))).geometry.size)
}
}