diff --git a/assets/navigation/arrowhead-dark.png b/assets/navigation/arrowhead-dark.png new file mode 100644 index 0000000..23a5c06 Binary files /dev/null and b/assets/navigation/arrowhead-dark.png differ diff --git a/assets/navigation/arrowhead-dark@2x.png b/assets/navigation/arrowhead-dark@2x.png new file mode 100644 index 0000000..f9b11fd Binary files /dev/null and b/assets/navigation/arrowhead-dark@2x.png differ diff --git a/assets/navigation/arrowhead-dark@3x.png b/assets/navigation/arrowhead-dark@3x.png new file mode 100644 index 0000000..234f099 Binary files /dev/null and b/assets/navigation/arrowhead-dark@3x.png differ diff --git a/assets/navigation/arrowhead-light.png b/assets/navigation/arrowhead-light.png new file mode 100644 index 0000000..b49554c Binary files /dev/null and b/assets/navigation/arrowhead-light.png differ diff --git a/assets/navigation/arrowhead-light@2x.png b/assets/navigation/arrowhead-light@2x.png new file mode 100644 index 0000000..43d9a65 Binary files /dev/null and b/assets/navigation/arrowhead-light@2x.png differ diff --git a/assets/navigation/arrowhead-light@3x.png b/assets/navigation/arrowhead-light@3x.png new file mode 100644 index 0000000..02ab0df Binary files /dev/null and b/assets/navigation/arrowhead-light@3x.png differ diff --git a/assets/navigation/maneuver-arrive-left.png b/assets/navigation/maneuver-arrive-left.png new file mode 100644 index 0000000..6793f91 Binary files /dev/null and b/assets/navigation/maneuver-arrive-left.png differ diff --git a/assets/navigation/maneuver-arrive-left@2x.png b/assets/navigation/maneuver-arrive-left@2x.png new file mode 100644 index 0000000..61691ce Binary files /dev/null and b/assets/navigation/maneuver-arrive-left@2x.png differ diff --git a/assets/navigation/maneuver-arrive-left@3x.png b/assets/navigation/maneuver-arrive-left@3x.png new file mode 100644 index 0000000..001bd57 Binary files /dev/null and b/assets/navigation/maneuver-arrive-left@3x.png differ diff --git a/assets/navigation/maneuver-arrive.png b/assets/navigation/maneuver-arrive.png new file mode 100644 index 0000000..99c3c2a Binary files /dev/null and b/assets/navigation/maneuver-arrive.png differ diff --git a/assets/navigation/maneuver-arrive@2x.png b/assets/navigation/maneuver-arrive@2x.png new file mode 100644 index 0000000..18be92d Binary files /dev/null and b/assets/navigation/maneuver-arrive@2x.png differ diff --git a/assets/navigation/maneuver-arrive@3x.png b/assets/navigation/maneuver-arrive@3x.png new file mode 100644 index 0000000..9e7f454 Binary files /dev/null and b/assets/navigation/maneuver-arrive@3x.png differ diff --git a/assets/navigation/maneuver-fork-left.png b/assets/navigation/maneuver-fork-left.png new file mode 100644 index 0000000..074deea Binary files /dev/null and b/assets/navigation/maneuver-fork-left.png differ diff --git a/assets/navigation/maneuver-fork-left@2x.png b/assets/navigation/maneuver-fork-left@2x.png new file mode 100644 index 0000000..897eb8c Binary files /dev/null and b/assets/navigation/maneuver-fork-left@2x.png differ diff --git a/assets/navigation/maneuver-fork-left@3x.png b/assets/navigation/maneuver-fork-left@3x.png new file mode 100644 index 0000000..0e8eed1 Binary files /dev/null and b/assets/navigation/maneuver-fork-left@3x.png differ diff --git a/assets/navigation/maneuver-left.png b/assets/navigation/maneuver-left.png new file mode 100644 index 0000000..c9f3aeb Binary files /dev/null and b/assets/navigation/maneuver-left.png differ diff --git a/assets/navigation/maneuver-left@2x.png b/assets/navigation/maneuver-left@2x.png new file mode 100644 index 0000000..88fc1d9 Binary files /dev/null and b/assets/navigation/maneuver-left@2x.png differ diff --git a/assets/navigation/maneuver-left@3x.png b/assets/navigation/maneuver-left@3x.png new file mode 100644 index 0000000..3a8e0ae Binary files /dev/null and b/assets/navigation/maneuver-left@3x.png differ diff --git a/assets/navigation/maneuver-merge-left.png b/assets/navigation/maneuver-merge-left.png new file mode 100644 index 0000000..c46bfc7 Binary files /dev/null and b/assets/navigation/maneuver-merge-left.png differ diff --git a/assets/navigation/maneuver-merge-left@2x.png b/assets/navigation/maneuver-merge-left@2x.png new file mode 100644 index 0000000..0f4527d Binary files /dev/null and b/assets/navigation/maneuver-merge-left@2x.png differ diff --git a/assets/navigation/maneuver-merge-left@3x.png b/assets/navigation/maneuver-merge-left@3x.png new file mode 100644 index 0000000..4f09b30 Binary files /dev/null and b/assets/navigation/maneuver-merge-left@3x.png differ diff --git a/assets/navigation/maneuver-ramp-left.png b/assets/navigation/maneuver-ramp-left.png new file mode 100644 index 0000000..583176f Binary files /dev/null and b/assets/navigation/maneuver-ramp-left.png differ diff --git a/assets/navigation/maneuver-ramp-left@2x.png b/assets/navigation/maneuver-ramp-left@2x.png new file mode 100644 index 0000000..db7da0e Binary files /dev/null and b/assets/navigation/maneuver-ramp-left@2x.png differ diff --git a/assets/navigation/maneuver-ramp-left@3x.png b/assets/navigation/maneuver-ramp-left@3x.png new file mode 100644 index 0000000..41fe879 Binary files /dev/null and b/assets/navigation/maneuver-ramp-left@3x.png differ diff --git a/assets/navigation/maneuver-roundabout-left.png b/assets/navigation/maneuver-roundabout-left.png new file mode 100644 index 0000000..dcf6cd7 Binary files /dev/null and b/assets/navigation/maneuver-roundabout-left.png differ diff --git a/assets/navigation/maneuver-roundabout-left@2x.png b/assets/navigation/maneuver-roundabout-left@2x.png new file mode 100644 index 0000000..d5128d5 Binary files /dev/null and b/assets/navigation/maneuver-roundabout-left@2x.png differ diff --git a/assets/navigation/maneuver-roundabout-left@3x.png b/assets/navigation/maneuver-roundabout-left@3x.png new file mode 100644 index 0000000..c26e0f7 Binary files /dev/null and b/assets/navigation/maneuver-roundabout-left@3x.png differ diff --git a/assets/navigation/maneuver-roundabout-right.png b/assets/navigation/maneuver-roundabout-right.png new file mode 100644 index 0000000..e04f583 Binary files /dev/null and b/assets/navigation/maneuver-roundabout-right.png differ diff --git a/assets/navigation/maneuver-roundabout-right@2x.png b/assets/navigation/maneuver-roundabout-right@2x.png new file mode 100644 index 0000000..3c4839f Binary files /dev/null and b/assets/navigation/maneuver-roundabout-right@2x.png differ diff --git a/assets/navigation/maneuver-roundabout-right@3x.png b/assets/navigation/maneuver-roundabout-right@3x.png new file mode 100644 index 0000000..c3730d9 Binary files /dev/null and b/assets/navigation/maneuver-roundabout-right@3x.png differ diff --git a/assets/navigation/maneuver-roundabout-sharp-left.png b/assets/navigation/maneuver-roundabout-sharp-left.png new file mode 100644 index 0000000..d0fa015 Binary files /dev/null and b/assets/navigation/maneuver-roundabout-sharp-left.png differ diff --git a/assets/navigation/maneuver-roundabout-sharp-left@2x.png b/assets/navigation/maneuver-roundabout-sharp-left@2x.png new file mode 100644 index 0000000..fa542f9 Binary files /dev/null and b/assets/navigation/maneuver-roundabout-sharp-left@2x.png differ diff --git a/assets/navigation/maneuver-roundabout-sharp-left@3x.png b/assets/navigation/maneuver-roundabout-sharp-left@3x.png new file mode 100644 index 0000000..0c27c98 Binary files /dev/null and b/assets/navigation/maneuver-roundabout-sharp-left@3x.png differ diff --git a/assets/navigation/maneuver-roundabout-slight-left.png b/assets/navigation/maneuver-roundabout-slight-left.png new file mode 100644 index 0000000..9674fdb Binary files /dev/null and b/assets/navigation/maneuver-roundabout-slight-left.png differ diff --git a/assets/navigation/maneuver-roundabout-slight-left@2x.png b/assets/navigation/maneuver-roundabout-slight-left@2x.png new file mode 100644 index 0000000..7562fae Binary files /dev/null and b/assets/navigation/maneuver-roundabout-slight-left@2x.png differ diff --git a/assets/navigation/maneuver-roundabout-slight-left@3x.png b/assets/navigation/maneuver-roundabout-slight-left@3x.png new file mode 100644 index 0000000..14d5a3c Binary files /dev/null and b/assets/navigation/maneuver-roundabout-slight-left@3x.png differ diff --git a/assets/navigation/maneuver-roundabout-slight-right.png b/assets/navigation/maneuver-roundabout-slight-right.png new file mode 100644 index 0000000..d6b851a Binary files /dev/null and b/assets/navigation/maneuver-roundabout-slight-right.png differ diff --git a/assets/navigation/maneuver-roundabout-slight-right@2x.png b/assets/navigation/maneuver-roundabout-slight-right@2x.png new file mode 100644 index 0000000..1518301 Binary files /dev/null and b/assets/navigation/maneuver-roundabout-slight-right@2x.png differ diff --git a/assets/navigation/maneuver-roundabout-slight-right@3x.png b/assets/navigation/maneuver-roundabout-slight-right@3x.png new file mode 100644 index 0000000..a7b30ef Binary files /dev/null and b/assets/navigation/maneuver-roundabout-slight-right@3x.png differ diff --git a/assets/navigation/maneuver-roundabout-straight.png b/assets/navigation/maneuver-roundabout-straight.png new file mode 100644 index 0000000..ad27081 Binary files /dev/null and b/assets/navigation/maneuver-roundabout-straight.png differ diff --git a/assets/navigation/maneuver-roundabout-straight@2x.png b/assets/navigation/maneuver-roundabout-straight@2x.png new file mode 100644 index 0000000..46ee175 Binary files /dev/null and b/assets/navigation/maneuver-roundabout-straight@2x.png differ diff --git a/assets/navigation/maneuver-roundabout-straight@3x.png b/assets/navigation/maneuver-roundabout-straight@3x.png new file mode 100644 index 0000000..951dec6 Binary files /dev/null and b/assets/navigation/maneuver-roundabout-straight@3x.png differ diff --git a/assets/navigation/maneuver-roundabout-uturn.png b/assets/navigation/maneuver-roundabout-uturn.png new file mode 100644 index 0000000..daa8d0f Binary files /dev/null and b/assets/navigation/maneuver-roundabout-uturn.png differ diff --git a/assets/navigation/maneuver-roundabout-uturn@2x.png b/assets/navigation/maneuver-roundabout-uturn@2x.png new file mode 100644 index 0000000..58329a4 Binary files /dev/null and b/assets/navigation/maneuver-roundabout-uturn@2x.png differ diff --git a/assets/navigation/maneuver-roundabout-uturn@3x.png b/assets/navigation/maneuver-roundabout-uturn@3x.png new file mode 100644 index 0000000..daa1555 Binary files /dev/null and b/assets/navigation/maneuver-roundabout-uturn@3x.png differ diff --git a/assets/navigation/maneuver-sharp-left.png b/assets/navigation/maneuver-sharp-left.png new file mode 100644 index 0000000..128ac11 Binary files /dev/null and b/assets/navigation/maneuver-sharp-left.png differ diff --git a/assets/navigation/maneuver-sharp-left@2x.png b/assets/navigation/maneuver-sharp-left@2x.png new file mode 100644 index 0000000..2f038ea Binary files /dev/null and b/assets/navigation/maneuver-sharp-left@2x.png differ diff --git a/assets/navigation/maneuver-sharp-left@3x.png b/assets/navigation/maneuver-sharp-left@3x.png new file mode 100644 index 0000000..cffa174 Binary files /dev/null and b/assets/navigation/maneuver-sharp-left@3x.png differ diff --git a/assets/navigation/maneuver-slight-left.png b/assets/navigation/maneuver-slight-left.png new file mode 100644 index 0000000..123b806 Binary files /dev/null and b/assets/navigation/maneuver-slight-left.png differ diff --git a/assets/navigation/maneuver-slight-left@2x.png b/assets/navigation/maneuver-slight-left@2x.png new file mode 100644 index 0000000..8e80b68 Binary files /dev/null and b/assets/navigation/maneuver-slight-left@2x.png differ diff --git a/assets/navigation/maneuver-slight-left@3x.png b/assets/navigation/maneuver-slight-left@3x.png new file mode 100644 index 0000000..025c152 Binary files /dev/null and b/assets/navigation/maneuver-slight-left@3x.png differ diff --git a/assets/navigation/maneuver-straight.png b/assets/navigation/maneuver-straight.png new file mode 100644 index 0000000..483018f Binary files /dev/null and b/assets/navigation/maneuver-straight.png differ diff --git a/assets/navigation/maneuver-straight@2x.png b/assets/navigation/maneuver-straight@2x.png new file mode 100644 index 0000000..241d85e Binary files /dev/null and b/assets/navigation/maneuver-straight@2x.png differ diff --git a/assets/navigation/maneuver-straight@3x.png b/assets/navigation/maneuver-straight@3x.png new file mode 100644 index 0000000..0f60ed9 Binary files /dev/null and b/assets/navigation/maneuver-straight@3x.png differ diff --git a/assets/navigation/maneuver-unknown.png b/assets/navigation/maneuver-unknown.png new file mode 100644 index 0000000..13fcd03 Binary files /dev/null and b/assets/navigation/maneuver-unknown.png differ diff --git a/assets/navigation/maneuver-unknown@2x.png b/assets/navigation/maneuver-unknown@2x.png new file mode 100644 index 0000000..a836219 Binary files /dev/null and b/assets/navigation/maneuver-unknown@2x.png differ diff --git a/assets/navigation/maneuver-unknown@3x.png b/assets/navigation/maneuver-unknown@3x.png new file mode 100644 index 0000000..010fe80 Binary files /dev/null and b/assets/navigation/maneuver-unknown@3x.png differ diff --git a/assets/navigation/maneuver-uturn-left.png b/assets/navigation/maneuver-uturn-left.png new file mode 100644 index 0000000..7e8d2d8 Binary files /dev/null and b/assets/navigation/maneuver-uturn-left.png differ diff --git a/assets/navigation/maneuver-uturn-left@2x.png b/assets/navigation/maneuver-uturn-left@2x.png new file mode 100644 index 0000000..602dc3d Binary files /dev/null and b/assets/navigation/maneuver-uturn-left@2x.png differ diff --git a/assets/navigation/maneuver-uturn-left@3x.png b/assets/navigation/maneuver-uturn-left@3x.png new file mode 100644 index 0000000..2e69901 Binary files /dev/null and b/assets/navigation/maneuver-uturn-left@3x.png differ diff --git a/assets/navigation/oneway-dark.png b/assets/navigation/oneway-dark.png new file mode 100644 index 0000000..1bfed0a Binary files /dev/null and b/assets/navigation/oneway-dark.png differ diff --git a/assets/navigation/oneway-dark@2x.png b/assets/navigation/oneway-dark@2x.png new file mode 100644 index 0000000..6019dce Binary files /dev/null and b/assets/navigation/oneway-dark@2x.png differ diff --git a/assets/navigation/oneway-dark@3x.png b/assets/navigation/oneway-dark@3x.png new file mode 100644 index 0000000..91ae3ef Binary files /dev/null and b/assets/navigation/oneway-dark@3x.png differ diff --git a/assets/navigation/oneway-light.png b/assets/navigation/oneway-light.png new file mode 100644 index 0000000..74543dc Binary files /dev/null and b/assets/navigation/oneway-light.png differ diff --git a/assets/navigation/oneway-light@2x.png b/assets/navigation/oneway-light@2x.png new file mode 100644 index 0000000..a283265 Binary files /dev/null and b/assets/navigation/oneway-light@2x.png differ diff --git a/assets/navigation/oneway-light@3x.png b/assets/navigation/oneway-light@3x.png new file mode 100644 index 0000000..216eef8 Binary files /dev/null and b/assets/navigation/oneway-light@3x.png differ diff --git a/assets/navigation/puck-dot-dark.png b/assets/navigation/puck-dot-dark.png new file mode 100644 index 0000000..0d2cc8a Binary files /dev/null and b/assets/navigation/puck-dot-dark.png differ diff --git a/assets/navigation/puck-dot-dark@2x.png b/assets/navigation/puck-dot-dark@2x.png new file mode 100644 index 0000000..7fb1a32 Binary files /dev/null and b/assets/navigation/puck-dot-dark@2x.png differ diff --git a/assets/navigation/puck-dot-dark@3x.png b/assets/navigation/puck-dot-dark@3x.png new file mode 100644 index 0000000..b10f4e4 Binary files /dev/null and b/assets/navigation/puck-dot-dark@3x.png differ diff --git a/assets/navigation/puck-dot-light.png b/assets/navigation/puck-dot-light.png new file mode 100644 index 0000000..0bd5c3e Binary files /dev/null and b/assets/navigation/puck-dot-light.png differ diff --git a/assets/navigation/puck-dot-light@2x.png b/assets/navigation/puck-dot-light@2x.png new file mode 100644 index 0000000..e01c88e Binary files /dev/null and b/assets/navigation/puck-dot-light@2x.png differ diff --git a/assets/navigation/puck-dot-light@3x.png b/assets/navigation/puck-dot-light@3x.png new file mode 100644 index 0000000..902856f Binary files /dev/null and b/assets/navigation/puck-dot-light@3x.png differ diff --git a/assets/navigation/puck-retained-dark.png b/assets/navigation/puck-retained-dark.png new file mode 100644 index 0000000..072fd52 Binary files /dev/null and b/assets/navigation/puck-retained-dark.png differ diff --git a/assets/navigation/puck-retained-dark@2x.png b/assets/navigation/puck-retained-dark@2x.png new file mode 100644 index 0000000..fbc4b57 Binary files /dev/null and b/assets/navigation/puck-retained-dark@2x.png differ diff --git a/assets/navigation/puck-retained-dark@3x.png b/assets/navigation/puck-retained-dark@3x.png new file mode 100644 index 0000000..a21283f Binary files /dev/null and b/assets/navigation/puck-retained-dark@3x.png differ diff --git a/assets/navigation/puck-retained-light.png b/assets/navigation/puck-retained-light.png new file mode 100644 index 0000000..a203fb5 Binary files /dev/null and b/assets/navigation/puck-retained-light.png differ diff --git a/assets/navigation/puck-retained-light@2x.png b/assets/navigation/puck-retained-light@2x.png new file mode 100644 index 0000000..c4d96b7 Binary files /dev/null and b/assets/navigation/puck-retained-light@2x.png differ diff --git a/assets/navigation/puck-retained-light@3x.png b/assets/navigation/puck-retained-light@3x.png new file mode 100644 index 0000000..2da507a Binary files /dev/null and b/assets/navigation/puck-retained-light@3x.png differ diff --git a/assets/navigation/puck-wedge-dark.png b/assets/navigation/puck-wedge-dark.png new file mode 100644 index 0000000..b3cc33c Binary files /dev/null and b/assets/navigation/puck-wedge-dark.png differ diff --git a/assets/navigation/puck-wedge-dark@2x.png b/assets/navigation/puck-wedge-dark@2x.png new file mode 100644 index 0000000..b1d7888 Binary files /dev/null and b/assets/navigation/puck-wedge-dark@2x.png differ diff --git a/assets/navigation/puck-wedge-dark@3x.png b/assets/navigation/puck-wedge-dark@3x.png new file mode 100644 index 0000000..136e0f7 Binary files /dev/null and b/assets/navigation/puck-wedge-dark@3x.png differ diff --git a/assets/navigation/puck-wedge-light.png b/assets/navigation/puck-wedge-light.png new file mode 100644 index 0000000..8314271 Binary files /dev/null and b/assets/navigation/puck-wedge-light.png differ diff --git a/assets/navigation/puck-wedge-light@2x.png b/assets/navigation/puck-wedge-light@2x.png new file mode 100644 index 0000000..01d3c2c Binary files /dev/null and b/assets/navigation/puck-wedge-light@2x.png differ diff --git a/assets/navigation/puck-wedge-light@3x.png b/assets/navigation/puck-wedge-light@3x.png new file mode 100644 index 0000000..a9add01 Binary files /dev/null and b/assets/navigation/puck-wedge-light@3x.png differ diff --git a/docs/development/delivery.md b/docs/development/delivery.md index 8df1a91..953be2d 100644 --- a/docs/development/delivery.md +++ b/docs/development/delivery.md @@ -6,6 +6,10 @@ Version **0.2.0-beta.1 / Android code 12** is a GitHub **pre-release** for a phy Emulator evidence (Android 16 AOSP, no Google services) covers launch, theme switching, sheets, search, stop boards, road navigation start at 30–45 m accuracy, replayed walking with reroute, transit following by confirmations with device location off, the date/time dialogs and the Organic Maps hand-off. Physical GPS, screen-off guidance, real boarding/transfers, audible voice and battery remain field-test checks; the release notes carry the checklist. +## Unreleased: first-person guidance + +Development-client evidence on the Android 16 AOSP emulator (no Google services, software ANGLE rendering) with 1 Hz test-provider replays of FOSSGIS walking, cycling and driving routes in Turin: the puck stays on its anchor (median error 0.08–0.19% of the screen height, p95 ≤ 0.66% during steady segments), the planner's projection matches MapLibre's own `project()` within about 1–2 px median, turn framing begins within one fix of the 8/10/12 s window, a 30 s stop holds bearing and zoom, a pan enters free at gesture start (about 60–75 ms to the free intent) and reroutes leave a free camera untouched, Ricentra issues one 500 ms move, degraded fixes stop the lead and keep the labelled last instruction, a live light/dark switch keeps the route, puck and basemap adjustments, and a transit access walk uses the walking camera. Emulator frame times (median 57 ms under screen recording) qualify the emulator only; physical-device smoothness, GPS course and speed quality, screen-off guidance and battery use remain field checks. + ## Current release line: 0.1.9 Version **0.1.9 / Android code 11** combines compact map-first UI, stable task/navigation geometry, foreground location acquisition and read-only provider diagnostics. Navigation still uses its existing GPS source and 20 m / 10 s acceptance policy. The production launcher exclusion keeps Google barcode-scanner dependencies out of the runtime graph while the separate development client remains available. diff --git a/docs/development/navigation.md b/docs/development/navigation.md index 5f37a04..b8de3aa 100644 --- a/docs/development/navigation.md +++ b/docs/development/navigation.md @@ -23,6 +23,20 @@ Road guidance consumes one [packaged policy](../../modules/avoid-navigation/andr The [host trajectory harness](../../tests/navigation-core/README.md) executes the real Ferrostar 0.57.0 Rust controller against that policy. It covers sparse turn samples, sidewalk offset, progress/deviation at accepted accuracy and a short final step. It does not execute the Android library or UniFFI/JNA bridge; Android runtime and physical-route acceptance remain separate. +## First-person guidance presentation + +Road guidance uses an app-controlled MapLibre camera fed only by accepted native navigation state: no second location stream and no MapLibre user tracking. The native snapshot exposes, besides the Italian text, structured maneuvers and kinematics (`src/domain/navigation.ts`): + +- `upcomingManeuver` (Ferrostar's `remainingSteps[1]`, whose text is `instruction`) and `followingManeuver` (`nextInstruction`) carry the raw OSRM type, modifier, roundabout exit, street name/ref, bearings, driving side, maneuver coordinate and its index in the route geometry. Ids are `:` and change on every reroute. `followingManeuver` adds the distance/time between the two maneuvers. Raw facts are kept beside Ferrostar's parsed steps because the adapter empties its visual instructions; Italian prose is never parsed back into types. +- `routeProgress.traveledMeters` is the snapped position measured with the native haversine on the bridged route geometry, so the interface can split travelled and remaining route on exactly what it draws. `snappedLocation` and `alignment` (`aligned`, `deviating`, `unknown` when the fix was too coarse to judge deviation) tell the camera whether the snapped position is credible. +- `location` adds speed, course and their accuracies when the platform supplies finite values, plus the monotonic `elapsedMs` sample time used for fix intervals and duplicate detection. + +The camera planner (`src/features/navigation/guidance-camera.ts`) produces one frame per distinct fix. The map eases linearly to it over the measured fix interval, so the puck (drawn at the camera anchor while following) and the map move on one clock with React rendering at 1 Hz. It is course-up with circular filtering (the short way across north) and holds its bearing when slow; pitch, zoom and the puck anchor are per mode (walking 34°, zoom 18.3, 67% of the map left between banner and strip; cycling 42°, 17.1–18, 71.5%; driving 48°, 15.7–17.7 by smoothed speed, 73.5%). The anchor is placed with top padding: MapLibre centres the padded rectangle, so bottom padding alone would raise the puck. Turn framing starts 8/10/12 s before the maneuver (walking/cycling/driving), keeps the junction and a short outgoing path (and a second turn that follows within about ten seconds) inside the visible map, and releases over 2–3 s. Cycling and driving draw at the route-snapped position only while `alignment` is `aligned`; walking keeps the real offset. Cycling and driving add a presentation-only lead of at most one fix interval that never passes the upcoming maneuver and stops on degraded, late or recovering fixes; it never feeds navigation state. When a provider omits speed or course, the planner estimates them for presentation only: a displacement counts only beyond the combined horizontal accuracy of the two fixes (at least 3 m, within 10 s), entering motion needs two consecutive consistent estimates, the course accuracy reports the geometric uncertainty, and stationary jitter yields no speed, course or lead. + +Camera intent is follow, free or overview. A gesture enters free at gesture start (`onRegionWillChange` with user interaction) and blocks every pending move; **Ricentra** restores the follow pose in one 500 ms transition (in a transit ride or wait it fits the current leg again); overview frames the remaining route north-up and flat once. Fixes and reroutes never take the camera back from free or overview. The visible map is a rectangle: below the banner, above the strip and, in a landscape layout, left of the side panel; anchoring, projection and fits use it. Leaving guidance returns the browsing map to north-up and flat with whichever browse camera command is issued next. + +Development builds log `[nav-cam]` rows comparing MapLibre's own `project()` of the camera centre and the next junction with the planner (anchor error, projection error, commanded versus native zoom/bearing). Emulator replays (`adb shell cmd location providers set-test-provider-location` at 1 Hz) exercise this path; physical-device GPS, frame pacing and battery use remain separate acceptance. + ## Android acceptance Build and install following [android.md](android.md). Record version/code, Android version, permissions, installed voice and network state using public routes/stops. Each row above needs an observed result for its affected mode; provider failure is an explicit outcome, and an install alone is not runtime acceptance. diff --git a/docs/development/ux.md b/docs/development/ux.md index 58a6834..b7eacc5 100644 --- a/docs/development/ux.md +++ b/docs/development/ux.md @@ -53,7 +53,7 @@ The app belongs to the avoid.quest family. Launcher name: **avoid maps** (develo Keep one map mounted across browsing, sheet expansion and navigation. Small inset task cards overlay that viewport at a compact height or an explicitly expanded height; keyboard resizing may reduce the sheet's available space while preserving the map. Status, loading and error updates change content inside reserved regions. Anchor route actions outside scrolling details, and keep navigation instruction, trip summary, Retry and Stop geometry independent of position quality. -Frame a planning route once for the requested origin, destination and mode, or when the user selects an alternative or requests the full route. Refreshes update its line without reframing. Panning consumes any pending frame so a late response respects the chosen view. Camera padding must leave visible map space on narrow, expanded and side-sheet layouts. Navigation follows accepted positions until the user pans; Locate deliberately resumes following. +Frame a planning route once for the requested origin, destination and mode, or when the user selects an alternative or requests the full route. Refreshes update its line without reframing. Panning consumes any pending frame so a late response respects the chosen view. Camera padding must leave visible map space on narrow, expanded and side-sheet layouts. Road guidance uses the first-person camera described in [navigation](navigation.md#first-person-guidance-presentation): a gesture enters free at its start, **Ricentra** restores following in one move, and the overview button frames the remaining route once. Fixes and reroutes never take the camera back. Keep current quality separate from retained coordinates. The native snapshot supplies the last accepted accuracy and current usability/problem, not the accuracy of rejected samples. Label retained numbers **Ultima posizione accettata** and paused maneuvers **Ultima indicazione**; keep their geometry while guidance is suspended. Provider selection and accuracy/age policy are separate concerns. @@ -65,6 +65,12 @@ Trasporti lists the nearest pilot rail stations above the GTT stops; a station o ## Active guidance +Road guidance is first-person: a flush banner in the chrome colour on top, the map with the puck low in the space between banner and strip, and a compact bottom strip. + +- **Banner:** a maneuver glyph drawn from the OSRM type and modifier (straight, slight/normal/sharp turns, U-turn, fork, merge, ramps, roundabout with exit number and circulation, arrival; an unknown maneuver shows a neutral glyph with the supplied text, never a guessed turn), the distance in heavy Mona Sans with a smaller unit, then the street and the action in Geist with two lines reserved. A reserved row shows **Poi …** only when the following maneuver comes within about ten seconds of travel after the upcoming one; a roundabout exit number sits beside its glyph. Status (**Ricalcolo del percorso…**, **Fuori percorso**, reduced precision, **Guida in pausa · Ultima indicazione**, the search signal) floats in its own pill just below the banner, so a warning is never hidden by **Poi**; both are also in the banner's spoken label. Each banner row has a fixed height measured for the current font scale (text capped at 2×), so no instruction or status changes the banner height. +- **Strip:** arrival time labelled **arrivo stimato**, remaining time and distance **senza traffico**, the voice toggle (active, muted and unavailable are distinct icons and labels), overview and **Interrompi**. On narrow screens or with large text the summary takes its own row above the controls, so no label or number is truncated. Tapping the summary opens details. **Riprova** appears only beside an active problem, floating above the strip with Ricentra. A paused position never advances an apparently current arrival time: the strip shows **Stima sospesa** and labels the remaining values as the last estimate. +- **Map:** the remaining route in the brand ink with a contrasting casing, the travelled part thinner and muted, one cased arrow through the next junction from the real geometry, and the puck (a wedge with a live green centre, a disc when the direction is unknown, a subdued ring for a retained position). Driving and cycling hide generic business dots and labels but keep street names; driving shows one-way chevrons. + Prioritize the next instruction, map, current problem and Stop action. Present recovery beside the problem. Keep voice status and setup in navigation details. Anchor the active transit confirmation beside Stop. Transit following has its own screen, not the road panel: the stage and instruction on top, the next boarding with its live provenance (or **Corsa non confermata**), the stop to get off at, journey age and passed/missed warnings, then the remaining timeline; the large confirmation sits beside Stop. Preserve transit confirmation controls and uncertainty when simplifying the layout. Route previews remain planning; native voice, position and background behavior require the separate [navigation acceptance checks](navigation.md). ## Task model and modules diff --git a/modules/avoid-navigation/android/src/main/java/quest/avoid/maps/navigation/FerrostarNavigationEngine.kt b/modules/avoid-navigation/android/src/main/java/quest/avoid/maps/navigation/FerrostarNavigationEngine.kt index a87c8ab..5166ca6 100644 --- a/modules/avoid-navigation/android/src/main/java/quest/avoid/maps/navigation/FerrostarNavigationEngine.kt +++ b/modules/avoid-navigation/android/src/main/java/quest/avoid/maps/navigation/FerrostarNavigationEngine.kt @@ -15,11 +15,17 @@ import uniffi.ferrostar.createNavigationSession /** Pure navigation core; Android owns lifecycle, fixes, network and speech. No SDK auto-rerouting. */ internal class FerrostarNavigationEngine(responseJson: String, mode: String, firstFix: Location) : AutoCloseable { val route: Route + /** Raw OSRM maneuver facts aligned with [route] steps (Ferrostar's public steps drop them). */ + val facts: List + val index: RouteGuideIndex private val config: NavigationControllerConfig private val session: NavigationSession private var state: NavState init { route = FerrostarRouteParser.parse(responseJson, mode) + facts = try { ManeuverFacts.parse(responseJson) } catch (_: org.json.JSONException) { throw NavigationFailure("invalid") } + if (facts.size != route.steps.size) throw NavigationFailure("invalid") + index = RouteGuideIndex(route.geometry, route.steps, facts) config = RoadGuidancePolicy.controllerConfig(mode) try { session = createNavigationSession(route, config, emptyList()) diff --git a/modules/avoid-navigation/android/src/main/java/quest/avoid/maps/navigation/GuidanceModel.kt b/modules/avoid-navigation/android/src/main/java/quest/avoid/maps/navigation/GuidanceModel.kt new file mode 100644 index 0000000..afab7f3 --- /dev/null +++ b/modules/avoid-navigation/android/src/main/java/quest/avoid/maps/navigation/GuidanceModel.kt @@ -0,0 +1,233 @@ +package quest.avoid.maps.navigation + +import kotlin.math.abs +import kotlin.math.cos +import kotlin.math.roundToInt +import org.json.JSONObject +import uniffi.ferrostar.GeographicCoordinate +import uniffi.ferrostar.RouteStep + +/** + * Raw OSRM maneuver facts for one route step. Ferrostar 0.57's public route keeps the step geometry, + * distance and our Italian text, but the adapter empties its visual instructions, so the maneuver + * type, modifier and roundabout exit come from the provider response itself — never from parsing + * Italian prose back into types. + */ +internal data class ManeuverFacts( + val type: String, + val modifier: String?, + val exit: Int?, + val name: String?, + val ref: String?, + val latitude: Double, + val longitude: Double, + val bearingBefore: Int?, + val bearingAfter: Int?, + val drivingSide: String?, +) { + companion object { + /** One entry per OSRM step across every leg, in route order (the same order Ferrostar uses). */ + fun parse(responseJson: String): List { + val legs = JSONObject(responseJson).getJSONArray("routes").getJSONObject(0).getJSONArray("legs") + return (0 until legs.length()).flatMap { leg -> + val steps = legs.getJSONObject(leg).getJSONArray("steps") + (0 until steps.length()).map { from(steps.getJSONObject(it)) } + } + } + + fun from(step: JSONObject): ManeuverFacts { + val maneuver = step.optJSONObject("maneuver") ?: JSONObject() + val location = maneuver.optJSONArray("location") + val longitude = location?.optDouble(0, Double.NaN) ?: Double.NaN + val latitude = location?.optDouble(1, Double.NaN) ?: Double.NaN + fun bearing(key: String) = if (maneuver.has(key)) maneuver.optInt(key, -1).takeIf { it in 0..360 } else null + return ManeuverFacts( + type = text(maneuver.optString("type"), 32) ?: "unknown", + modifier = text(maneuver.optString("modifier"), 32)?.takeIf { it in MODIFIERS }, + exit = if (maneuver.has("exit")) maneuver.optInt("exit", 0).takeIf { it in 1..99 } else null, + name = text(step.optString("name"), 160), + ref = text(step.optString("ref"), 40), + latitude = latitude, longitude = longitude, + bearingBefore = bearing("bearing_before"), bearingAfter = bearing("bearing_after"), + drivingSide = text(step.optString("driving_side"), 8)?.takeIf { it == "left" || it == "right" }, + ) + } + + private val MODIFIERS = setOf("uturn", "sharp right", "right", "slight right", "straight", "slight left", "left", "sharp left") + private fun text(value: String?, limit: Int) = value?.replace(Regex("[\\p{Cntrl}\\s]+"), " ")?.trim()?.take(limit)?.takeIf { it.isNotEmpty() } + } +} + +/** + * Immutable per-route index: cumulative distance along the route geometry the interface renders and + * the route-geometry index of every maneuver. Progress is measured on exactly the bridged geometry, + * so the traveled/remaining split drawn on the map matches the snapped position. + */ +internal class RouteGuideIndex(private val geometry: List, steps: List, facts: List) { + val cumulative: DoubleArray = DoubleArray(geometry.size).also { sums -> + for (i in 1 until geometry.size) sums[i] = sums[i - 1] + distance(geometry[i - 1], geometry[i]) + } + val length: Double get() = cumulative.lastOrNull() ?: 0.0 + /** Route-geometry index of the point where step k's maneuver happens (its first point). */ + val maneuverIndex: IntArray + + init { + require(geometry.size >= 2 && steps.isNotEmpty()) + val indexes = IntArray(steps.size) + var from = 0 + steps.forEachIndexed { k, step -> + val fact = facts.getOrNull(k) + val target = step.geometry.firstOrNull() + ?: fact?.takeIf { NavigationGeometry.valid(it.latitude, it.longitude) }?.let { GeographicCoordinate(it.latitude, it.longitude) } + // Maneuvers advance monotonically; a U-turn folds the line back over itself, so search + // forward from the previous maneuver and stop at the first exact (or nearest) match. + indexes[k] = if (k == 0) 0 else if (target == null) from else nearestForward(target, from) + from = indexes[k] + } + maneuverIndex = indexes + } + + private fun nearestForward(target: GeographicCoordinate, from: Int): Int { + var best = from + var bestDistance = Double.MAX_VALUE + for (i in from until geometry.size) { + val d = distance(geometry[i], target) + if (d < 0.05) return i + if (d < bestDistance) { bestDistance = d; best = i } + } + return best + } + + data class Progress(val traveledMeters: Double, val segmentIndex: Int) + + /** + * Projects [position] onto the route between the current step's maneuver and the next maneuver + * (a bounded window, so a later stretch of a looping or U-turn route never captures it). + */ + fun progress(currentStep: Int, position: GeographicCoordinate): Progress { + val start = maneuverIndex.getOrElse(currentStep) { 0 }.coerceIn(0, geometry.size - 2) + val end = (maneuverIndex.getOrNull(currentStep + 1) ?: (geometry.size - 1)).coerceIn(start + 1, geometry.size - 1) + var bestSegment = start + var bestFraction = 0.0 + var bestDistance = Double.MAX_VALUE + for (i in start until end) { + val (fraction, d) = project(geometry[i], geometry[i + 1], position) + if (d < bestDistance) { bestDistance = d; bestSegment = i; bestFraction = fraction } + } + val segmentLength = cumulative[bestSegment + 1] - cumulative[bestSegment] + return Progress(cumulative[bestSegment] + bestFraction * segmentLength, bestSegment) + } + + companion object { + fun distance(a: GeographicCoordinate, b: GeographicCoordinate) = NavigationGeometry.distance(a.lat, a.lng, b.lat, b.lng) + + /** Local equirectangular projection of [p] on segment a–b: (fraction along, distance in metres). */ + fun project(a: GeographicCoordinate, b: GeographicCoordinate, p: GeographicCoordinate): Pair { + val k = cos(Math.toRadians(a.lat)) + val ax = 0.0; val ay = 0.0 + val bx = (b.lng - a.lng) * k; val by = b.lat - a.lat + val px = (p.lng - a.lng) * k; val py = p.lat - a.lat + val length2 = (bx - ax) * (bx - ax) + (by - ay) * (by - ay) + val t = if (length2 <= 0.0) 0.0 else (((px - ax) * (bx - ax) + (py - ay) * (by - ay)) / length2).coerceIn(0.0, 1.0) + val qx = ax + t * (bx - ax); val qy = ay + t * (by - ay) + val metres = Math.hypot(px - qx, py - qy) * 111_195.0 + return t to metres + } + } +} + +/** + * Structured snapshot fields for the interface: the upcoming and following maneuvers (stable ids + * tied to the route revision), the route-relative progress and Ferrostar's snapped position. Pure, + * so the JVM tests cover it with deterministic fixtures; native values never contain null or NaN. + */ +internal object GuidanceFields { + /** Ids are `:`; a reroute changes every id. */ + fun maneuverId(routeRevision: Long, index: Int) = "$routeRevision:$index" + + fun build( + routeRevision: Long, + index: RouteGuideIndex, + steps: List, + facts: List, + remainingSteps: Int, + snapped: GeographicCoordinate?, + alignment: String, + ): Map { + val fields = mutableMapOf() + // Ferrostar drops completed steps from the front; the current step is remainingSteps[0]. + val current = (steps.size - remainingSteps).coerceIn(0, steps.size - 1) + val upcoming = current + 1 + maneuver(routeRevision, index, steps, facts, upcoming)?.let { fields["upcomingManeuver"] = it } + maneuver(routeRevision, index, steps, facts, upcoming + 1)?.let { following -> + // Distance/time between the two maneuvers: the whole upcoming step. + val between = steps[upcoming] + fields["followingManeuver"] = following + mapOf( + "afterUpcomingMeters" to finite(between.distance), "afterUpcomingSeconds" to finite(between.duration), + ) + } + if (snapped != null && NavigationGeometry.valid(snapped.lat, snapped.lng)) { + val progress = index.progress(current, snapped) + fields["routeProgress"] = mapOf( + "traveledMeters" to round(progress.traveledMeters), "routeLengthMeters" to round(index.length), + "segmentIndex" to progress.segmentIndex, "stepIndex" to current, + ) + fields["snappedLocation"] = mapOf("latitude" to snapped.lat, "longitude" to snapped.lng) + } + fields["alignment"] = alignment + return fields + } + + private fun maneuver(routeRevision: Long, index: RouteGuideIndex, steps: List, facts: List, k: Int): Map? { + val step = steps.getOrNull(k) ?: return null + val fact = facts.getOrNull(k) + val geometryIndex = index.maneuverIndex.getOrElse(k) { 0 } + val point = step.geometry.firstOrNull() + val result = mutableMapOf( + "id" to maneuverId(routeRevision, k), "stepIndex" to k, "geometryIndex" to geometryIndex, + "type" to (fact?.type ?: "unknown"), "instruction" to step.instruction, + ) + val latitude = fact?.latitude?.takeIf { it.isFinite() } ?: point?.lat + val longitude = fact?.longitude?.takeIf { it.isFinite() } ?: point?.lng + if (latitude != null && longitude != null && NavigationGeometry.valid(latitude, longitude)) { + result["latitude"] = latitude; result["longitude"] = longitude + } + fact?.modifier?.let { result["modifier"] = it } + fact?.exit?.let { result["exit"] = it } + (fact?.name ?: step.roadName?.takeIf { it.isNotBlank() })?.let { result["name"] = it } + fact?.ref?.let { result["ref"] = it } + fact?.bearingBefore?.let { result["bearingBefore"] = it } + fact?.bearingAfter?.let { result["bearingAfter"] = it } + fact?.drivingSide?.let { result["drivingSide"] = it } + return result + } + + private fun finite(value: Double) = if (value.isFinite() && value >= 0) round(value) else 0.0 + private fun round(value: Double) = (value * 10).roundToInt() / 10.0 +} + +/** How credible Ferrostar's snapped position is for drawing the puck on the route. */ +internal object Alignment { + const val ALIGNED = "aligned" + const val DEVIATING = "deviating" + /** The fix was too coarse to judge deviation, or no route is installed. */ + const val UNKNOWN = "unknown" + fun of(judged: Boolean, offRoute: Boolean, deviation: Boolean): String = when { + offRoute || (judged && deviation) -> DEVIATING + judged -> ALIGNED + else -> UNKNOWN + } +} + +/** Fix kinematics for the camera: never NaN or negative; absent values are omitted. */ +internal object FixKinematics { + fun fields( + speed: Float?, speedAccuracy: Float?, course: Float?, courseAccuracy: Float?, elapsedRealtimeNanos: Long, + ): Map = buildMap { + speed?.takeIf { it.isFinite() && it >= 0f }?.let { put("speedMps", (it * 100).roundToInt() / 100.0) } + speedAccuracy?.takeIf { it.isFinite() && it > 0f }?.let { put("speedAccuracyMps", (it * 100).roundToInt() / 100.0) } + course?.takeIf { it.isFinite() }?.let { put("course", (((it.toDouble() % 360 + 360) % 360) * 10).roundToInt().rem(3600) / 10.0) } + courseAccuracy?.takeIf { it.isFinite() && it > 0f }?.let { put("courseAccuracyDegrees", abs(it).toDouble()) } + if (elapsedRealtimeNanos > 0) put("elapsedMs", elapsedRealtimeNanos / 1_000_000L) + } +} diff --git a/modules/avoid-navigation/android/src/main/java/quest/avoid/maps/navigation/NavigationRuntime.kt b/modules/avoid-navigation/android/src/main/java/quest/avoid/maps/navigation/NavigationRuntime.kt index e3fa2e1..2c21a96 100644 --- a/modules/avoid-navigation/android/src/main/java/quest/avoid/maps/navigation/NavigationRuntime.kt +++ b/modules/avoid-navigation/android/src/main/java/quest/avoid/maps/navigation/NavigationRuntime.kt @@ -379,6 +379,8 @@ internal class NavigationRuntime private constructor(private val context: Contex val (upcoming, following) = ItalianManeuvers.upcoming(state.remainingSteps) if (upcoming != null) fields["instruction"] = upcoming else fields.remove("instruction") if (following != null) fields["nextInstruction"] = following else fields.remove("nextInstruction") + publishGuidance(state.remainingSteps.size, state.snappedUserLocation.coordinates, + Alignment.of(judged, offRoute, state.deviation is RouteDeviation.Deviation)) fields["status"] = if (offRoute) "off-route" else "navigating" fields.remove("problem"); fields["canRetry"] = offRoute arrivalFixes = 0 @@ -411,6 +413,9 @@ internal class NavigationRuntime private constructor(private val context: Contex fields["status"] = "navigating"; fields.remove("problem"); fields["canRetry"] = false fields["instruction"] = "Stai arrivando a destinazione"; fields.remove("nextInstruction") fields["distanceRemainingMeters"] = result[0].toDouble() + // The final step is next: the arrival maneuver, measured from the route end. + publishGuidance(2, destination, Alignment.UNKNOWN) + fields.remove("followingManeuver") publish() } is TripState.Idle -> { @@ -418,12 +423,25 @@ internal class NavigationRuntime private constructor(private val context: Contex runCatching { engine?.close() }; engine = null recovery.roadFailed(); speech?.flush() fields["status"] = "error"; fields["problem"] = "route-not-started"; fields["canRetry"] = true - fields.remove("route"); fields.remove("routeRevision") + fields.remove("route"); fields.remove("routeRevision"); clearGuidance() publish() } } } + /** Structured maneuvers and progress for the interface; ids belong to the installed route revision. */ + private fun publishGuidance(remainingSteps: Int, snapped: uniffi.ferrostar.GeographicCoordinate?, alignment: String) { + val active = engine ?: return + clearGuidance() + try { + fields.putAll(GuidanceFields.build(routeSequence, active.index, active.route.steps, active.facts, remainingSteps, snapped, alignment)) + } catch (error: RuntimeException) { + // Presentation data must never stop guidance; the text instructions remain. + Log.w(TAG, "guidance fields failed ${error.javaClass.name}") + } + } + private fun clearGuidance() { GUIDANCE_KEYS.forEach { fields.remove(it) } } + private fun arrive(instruction: String, routeEnd: Point?) { val destinationDistance = routeEnd?.let { end -> target?.let { selected -> FloatArray(1).also { Location.distanceBetween(end.latitude, end.longitude, selected.latitude, selected.longitude, it) }[0].toDouble() @@ -514,6 +532,7 @@ internal class NavigationRuntime private constructor(private val context: Contex engine?.close(); engine = next; spoken.clear(); deviation.reset() Log.i(TAG, "route installed fresh=$fresh steps=${next.route.steps.size}") fields["routeRevision"] = ++routeSequence + clearGuidance() fields["route"] = mapOf("geometry" to next.route.geometry.map { Point(it.lat, it.lng).bridge() }, "source" to "FOSSGIS / OpenStreetMap", "fetchedAt" to response.fetchedAt) if (!fresh) { @@ -581,9 +600,18 @@ internal class NavigationRuntime private constructor(private val context: Contex private fun fixMap(fix: Location): Map = mutableMapOf("latitude" to fix.latitude, "longitude" to fix.longitude, "accuracyMeters" to fix.accuracy.toDouble(), "timestamp" to fix.time).apply { if (fix.hasBearing() && fix.bearing.isFinite() && fix.hasSpeed() && fix.speed.isFinite() && fix.speed >= 1f) put("bearing", fix.bearing.toDouble()) + val modern = Build.VERSION.SDK_INT >= 26 + putAll(FixKinematics.fields( + speed = if (fix.hasSpeed()) fix.speed else null, + speedAccuracy = if (modern && fix.hasSpeedAccuracy()) fix.speedAccuracyMetersPerSecond else null, + course = if (fix.hasBearing()) fix.bearing else null, + courseAccuracy = if (modern && fix.hasBearingAccuracy()) fix.bearingAccuracyDegrees else null, + elapsedRealtimeNanos = fix.elapsedRealtimeNanos, + )) } companion object { const val TAG = "AvoidNav" + private val GUIDANCE_KEYS = listOf("upcomingManeuver", "followingManeuver", "routeProgress", "snappedLocation", "alignment") private val LOCATION_PROBLEMS = setOf("location-permission", "location-disabled", "location-stale", "location-inaccurate", "location-unavailable") @Volatile private var instance: NavigationRuntime? = null fun get(context: Context): NavigationRuntime = instance ?: synchronized(this) { diff --git a/modules/avoid-navigation/android/src/test/java/quest/avoid/maps/navigation/GuidanceModelTest.kt b/modules/avoid-navigation/android/src/test/java/quest/avoid/maps/navigation/GuidanceModelTest.kt new file mode 100644 index 0000000..e0d3629 --- /dev/null +++ b/modules/avoid-navigation/android/src/test/java/quest/avoid/maps/navigation/GuidanceModelTest.kt @@ -0,0 +1,194 @@ +package quest.avoid.maps.navigation + +import kotlin.math.cos +import kotlin.math.sin +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.* +import org.junit.Test +import uniffi.ferrostar.BoundingBox +import uniffi.ferrostar.GeographicCoordinate +import uniffi.ferrostar.Route +import uniffi.ferrostar.RouteStep + +/** + * Deterministic route fixtures for the structured guidance snapshot: straight, left/right turns, + * close turns, roundabout, U-turn, arrival, deviation and degraded fix kinematics. + */ +class GuidanceModelTest { + private val origin = GeographicCoordinate(45.0703, 7.6869) + + /** Point [meters] from [from] along compass [bearing]. */ + private fun move(from: GeographicCoordinate, bearing: Double, meters: Double): GeographicCoordinate { + val radians = Math.toRadians(bearing) + val lat = from.lat + meters * cos(radians) / 111_195.0 + val lng = from.lng + meters * sin(radians) / (111_195.0 * cos(Math.toRadians(from.lat))) + return GeographicCoordinate(lat, lng) + } + + /** Legs of (bearing, metres) walked in 10 m points; returns the polyline and each leg's slice. */ + private fun polyline(legs: List>): Pair, List>> { + val points = mutableListOf(origin) + val slices = mutableListOf>() + for ((bearing, meters) in legs) { + val start = points.size - 1 + val count = maxOf(1, (meters / 10).toInt()) + repeat(count) { points.add(move(points.last(), bearing, meters / count)) } + slices.add(points.subList(start, points.size).toList()) + } + return points to slices + } + + private fun rawStep(type: String, at: GeographicCoordinate, modifier: String? = null, name: String = "", exit: Int? = null, + before: Int? = null, after: Int? = null): JSONObject { + val maneuver = JSONObject().put("type", type).put("location", JSONArray().put(at.lng).put(at.lat)) + modifier?.let { maneuver.put("modifier", it) } + exit?.let { maneuver.put("exit", it) } + before?.let { maneuver.put("bearing_before", it) } + after?.let { maneuver.put("bearing_after", it) } + return JSONObject().put("name", name).put("maneuver", maneuver).put("driving_side", "right") + } + + private class Fixture(val route: Route, val facts: List) { + val index = RouteGuideIndex(route.geometry, route.steps, facts) + fun fields(remaining: Int, snapped: GeographicCoordinate?, alignment: String = Alignment.ALIGNED, revision: Long = 7) = + GuidanceFields.build(revision, index, route.steps, facts, remaining, snapped, alignment) + } + + /** One step per leg plus the arrival; raw[k] describes step k's maneuver. */ + private fun fixture(legs: List>, raw: (Int, GeographicCoordinate) -> JSONObject): Fixture { + val (points, slices) = polyline(legs) + val steps = slices.mapIndexed { k, slice -> + val length = slice.zipWithNext { a, b -> RouteGuideIndex.distance(a, b) }.sum() + RouteStep(slice, length, length / 1.4, null, emptyList(), "Passo $k", emptyList(), emptyList(), null, emptyList(), null, null) + } + RouteStep(listOf(points.last(), points.last()), 0.0, 0.0, null, emptyList(), "Arrivo", emptyList(), emptyList(), null, emptyList(), null, null) + val json = JSONObject().put("code", "Ok").put("routes", JSONArray().put(JSONObject().put("legs", JSONArray().put( + JSONObject().put("steps", JSONArray(steps.indices.map { k -> raw(k, steps[k].geometry.first()) })), + )))).toString() + val route = Route(points, BoundingBox(points.first(), points.last()), steps.sumOf { it.distance }, emptyList(), steps) + return Fixture(route, ManeuverFacts.parse(json)) + } + + @Test fun straightRouteProgressIsMonotonicAndMatchesRenderedGeometry() { + val f = fixture(listOf(0.0 to 300.0)) { k, at -> if (k == 0) rawStep("depart", at) else rawStep("arrive", at) } + assertEquals(300.0, f.index.length, 0.5) + var previous = -1.0 + for (meters in listOf(0.0, 15.0, 100.0, 222.0, 299.0)) { + val traveled = f.index.progress(0, move(origin, 0.0, meters)).traveledMeters + assertEquals(meters, traveled, 0.5) + assertTrue(traveled > previous); previous = traveled + } + // A sidewalk offset of 8 m does not change the along-route progress. + assertEquals(100.0, f.index.progress(0, move(move(origin, 0.0, 100.0), 90.0, 8.0)).traveledMeters, 0.5) + val fields = f.fields(remaining = 2, snapped = move(origin, 0.0, 50.0)) + @Suppress("UNCHECKED_CAST") val upcoming = fields["upcomingManeuver"] as Map + assertEquals("arrive", upcoming["type"]); assertEquals("7:1", upcoming["id"]) + assertNull(fields["followingManeuver"]) + @Suppress("UNCHECKED_CAST") val progress = fields["routeProgress"] as Map + assertEquals(50.0, progress["traveledMeters"] as Double, 0.5) + assertEquals(300.0, progress["routeLengthMeters"] as Double, 0.5) + } + + @Test fun leftAndRightTurnsExposeTypedUpcomingAndFollowingWithStableIds() { + val f = fixture(listOf(0.0 to 200.0, 90.0 to 150.0, 0.0 to 100.0)) { k, at -> when (k) { + 0 -> rawStep("depart", at, name = "Via Po", after = 0) + 1 -> rawStep("turn", at, "right", "Via Roma", before = 0, after = 90) + 2 -> rawStep("turn", at, "left", "Via Garibaldi", before = 90, after = 0) + else -> rawStep("arrive", at) + } } + assertArrayEquals(intArrayOf(0, 20, 35, 45), f.index.maneuverIndex) + val fields = f.fields(remaining = 4, snapped = move(origin, 0.0, 120.0)) + @Suppress("UNCHECKED_CAST") val upcoming = fields["upcomingManeuver"] as Map + @Suppress("UNCHECKED_CAST") val following = fields["followingManeuver"] as Map + assertEquals(listOf("7:1", "turn", "right", "Via Roma", 20, 0, 90, "right"), + listOf(upcoming["id"], upcoming["type"], upcoming["modifier"], upcoming["name"], upcoming["geometryIndex"], upcoming["bearingBefore"], upcoming["bearingAfter"], upcoming["drivingSide"])) + assertEquals(listOf("7:2", "left", 35), listOf(following["id"], following["modifier"], following["geometryIndex"])) + // The following maneuver is a whole upcoming step away: 150 m, about 107 s on foot. + assertEquals(150.0, following["afterUpcomingMeters"] as Double, 0.5) + assertEquals(107.1, following["afterUpcomingSeconds"] as Double, 0.5) + // A reroute changes every id even for the same step index. + @Suppress("UNCHECKED_CAST") + assertEquals("8:1", (f.fields(4, null, revision = 8)["upcomingManeuver"] as Map)["id"]) + // Ferrostar advanced past the first turn: the left turn is next and progress continues. + val after = f.fields(remaining = 3, snapped = move(move(origin, 0.0, 200.0), 90.0, 40.0)) + @Suppress("UNCHECKED_CAST") assertEquals("7:2", (after["upcomingManeuver"] as Map)["id"]) + @Suppress("UNCHECKED_CAST") assertEquals(240.0, (after["routeProgress"] as Map)["traveledMeters"] as Double, 0.6) + } + + @Test fun closeTurnsReportTheShortGapBetweenManeuvers() { + val f = fixture(listOf(0.0 to 200.0, 90.0 to 20.0, 0.0 to 120.0)) { k, at -> when (k) { + 0 -> rawStep("depart", at); 1 -> rawStep("turn", at, "right"); 2 -> rawStep("turn", at, "left"); else -> rawStep("arrive", at) + } } + @Suppress("UNCHECKED_CAST") val following = f.fields(4, move(origin, 0.0, 150.0))["followingManeuver"] as Map + assertEquals(20.0, following["afterUpcomingMeters"] as Double, 0.5) + assertEquals("left", following["modifier"]) + } + + @Test fun roundaboutKeepsExitNumberModifierAndDrivingSide() { + val f = fixture(listOf(0.0 to 120.0, 45.0 to 60.0, 90.0 to 100.0)) { k, at -> when (k) { + 0 -> rawStep("depart", at); 1 -> rawStep("roundabout", at, "right", "Corso Francia", exit = 3) + 2 -> rawStep("exit roundabout", at, "right", "Corso Francia"); else -> rawStep("arrive", at) + } } + @Suppress("UNCHECKED_CAST") val upcoming = f.fields(4, move(origin, 0.0, 60.0))["upcomingManeuver"] as Map + assertEquals(listOf("roundabout", "right", 3, "right"), listOf(upcoming["type"], upcoming["modifier"], upcoming["exit"], upcoming["drivingSide"])) + } + + @Test fun uTurnSearchesForwardAndProgressNeverJumpsToTheOutboundLeg() { + // North 100 m, U-turn back south 100 m over the same line, then east 80 m. + val f = fixture(listOf(0.0 to 100.0, 180.0 to 100.0, 90.0 to 80.0)) { k, at -> when (k) { + 0 -> rawStep("depart", at); 1 -> rawStep("continue", at, "uturn"); 2 -> rawStep("turn", at, "left"); else -> rawStep("arrive", at) + } } + assertArrayEquals(intArrayOf(0, 10, 20, 28), f.index.maneuverIndex) + // Returning past the 70 m mark: on step 1 the projection stays on the return leg (130 m traveled). + assertEquals(130.0, f.index.progress(1, move(origin, 0.0, 70.0)).traveledMeters, 0.6) + assertEquals(70.0, f.index.progress(0, move(origin, 0.0, 70.0)).traveledMeters, 0.6) + @Suppress("UNCHECKED_CAST") val upcoming = f.fields(4, move(origin, 0.0, 50.0))["upcomingManeuver"] as Map + assertEquals("continue" to "uturn", upcoming["type"] to upcoming["modifier"]) + } + + @Test fun arrivalHasNoFollowingManeuverAndUnknownTypesStayUnguessed() { + val f = fixture(listOf(0.0 to 80.0)) { k, at -> if (k == 0) rawStep("depart", at) else rawStep("future-type", at, "sideways") } + val fields = f.fields(remaining = 2, snapped = move(origin, 0.0, 79.0)) + @Suppress("UNCHECKED_CAST") val upcoming = fields["upcomingManeuver"] as Map + assertEquals("future-type", upcoming["type"]) + assertFalse("an unknown modifier is dropped, never guessed", upcoming.containsKey("modifier")) + assertFalse(fields.containsKey("followingManeuver")) + // Ferrostar on the last step: nothing upcoming, progress still published. + val last = f.fields(remaining = 1, snapped = move(origin, 0.0, 80.0)) + assertFalse(last.containsKey("upcomingManeuver")) + assertTrue(last.containsKey("routeProgress")) + } + + @Test fun alignmentFollowsDeviationOnlyForJudgedFixes() { + assertEquals(Alignment.ALIGNED, Alignment.of(judged = true, offRoute = false, deviation = false)) + assertEquals(Alignment.DEVIATING, Alignment.of(judged = true, offRoute = false, deviation = true)) + assertEquals(Alignment.DEVIATING, Alignment.of(judged = false, offRoute = true, deviation = false)) + // A coarse fix neither declares nor clears deviation: the snapped position is not credible. + assertEquals(Alignment.UNKNOWN, Alignment.of(judged = false, offRoute = false, deviation = true)) + val f = fixture(listOf(0.0 to 80.0)) { k, at -> rawStep(if (k == 0) "depart" else "arrive", at) } + assertEquals(Alignment.UNKNOWN, f.fields(2, null, Alignment.UNKNOWN)["alignment"]) + assertFalse(f.fields(2, null).containsKey("snappedLocation")) + } + + @Test fun degradedKinematicsAreOmittedAndCourseWrapsIntoOneTurn() { + val clean = FixKinematics.fields(1.4f, 0.3f, 359.6f, 12f, 5_000_000_000L) + assertEquals(mapOf("speedMps" to 1.4, "speedAccuracyMps" to 0.3, "course" to 359.6, "courseAccuracyDegrees" to 12.0, "elapsedMs" to 5_000L), clean) + assertEquals(0.0, FixKinematics.fields(null, null, 360f, null, 1L)["course"]) + assertEquals(0.0, FixKinematics.fields(null, null, 359.97f, null, 1L)["course"]) + assertEquals(350.0, FixKinematics.fields(null, null, -10f, null, 1L)["course"]) + // NaN, negative speed and missing monotonic time never reach the bridge. + assertEquals(emptyMap(), FixKinematics.fields(Float.NaN, -1f, Float.POSITIVE_INFINITY, Float.NaN, 0L)) + val values = FixKinematics.fields(-0.5f, Float.NaN, 10f, -3f, 2_000_000L).values + assertTrue(values.all { (it as? Double)?.isFinite() ?: true }) + } + + @Test fun factsParseEveryLegInOrderAndBoundText() { + fun leg(name: String) = JSONObject().put("steps", JSONArray().put(rawStep("depart", origin, name = name)).put(rawStep("arrive", origin))) + val json = JSONObject().put("code", "Ok").put("routes", JSONArray().put(JSONObject().put("legs", JSONArray().put(leg("Via Po")).put(leg("x".repeat(400)))))) + val facts = ManeuverFacts.parse(json.toString()) + assertEquals(listOf("depart", "arrive", "depart", "arrive"), facts.map { it.type }) + assertEquals("Via Po", facts[0].name) + assertEquals(160, facts[2].name?.length) + assertEquals(origin.lat, facts[0].latitude, 1e-9) + } +} diff --git a/scripts/render-navigation-assets.mjs b/scripts/render-navigation-assets.mjs new file mode 100644 index 0000000..7ce1b13 --- /dev/null +++ b/scripts/render-navigation-assets.mjs @@ -0,0 +1,128 @@ +// Renders the navigation puck and maneuver glyphs from the SVG sources below into PNGs at 1×/2×/3×. +// Deterministic: resvg, no system fonts, fixed sizes. Original artwork in the brand's black/white +// with signal green only for the live position centre. +// Usage: node scripts/render-navigation-assets.mjs [--check] (--check fails if committed PNGs differ) +import { Resvg } from '@resvg/resvg-js'; +import { createHash } from 'node:crypto'; +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +const root = fileURLToPath(new URL('../', import.meta.url)); +const out = `${root}assets/navigation/`; + +// Brand inks (src/theme/palette.ts): light map ink/casing and live green, dark the same inverted. +const inks = { + light: { ink: '#09090B', edge: '#FFFFFF', live: '#066F44', muted: '#8A8A93' }, + dark: { ink: '#FFFFFF', edge: '#000000', live: '#3DDC97', muted: '#8E8E96' }, +}; + +/** 48 dp canvas; the image centre is the position, so map rotation pivots on it. */ +const puck = { + // A broad wedge with a notched tail: heading is readable at a glance and under pitch. + wedge: ({ ink, edge, live }) => `` + + ``, + // Direction unknown: a disc, never a guessed heading. + dot: ({ ink, edge, live }) => `` + + ``, + // Last accepted position while guidance is paused: hollow, grey, no live green. + retained: ({ edge, muted }) => `` + + ``, +}; + +const outputs = {}; +for (const [name, draw] of Object.entries(puck)) { + for (const [scheme, colors] of Object.entries(inks)) { + for (const scale of [1, 2, 3]) { + const size = 48 * scale; + outputs[`puck-${name}-${scheme}${scale === 1 ? '' : `@${scale}x`}.png`] = + `${draw(colors)}`; + } + } +} + +/** + * Maneuver glyphs: single-ink (tinted at runtime), 48 dp, drawn for left turns and right-hand + * traffic; the interface mirrors them for right turns and left-hand circulation. + */ +const W = 'stroke="#FFFFFF" fill="none" stroke-linecap="round" stroke-linejoin="round"'; +const head = (x, y, angle) => ``; +const thick = d => ``; +const thin = d => ``; +// Roundabout ring centre and entry; the exit arm leaves at `exitAngle` (compass degrees, screen). +const ring = { x: 24, y: 23, r: 7.5 }; +function roundabout(exitAngle) { + const rad = deg => (deg - 90) * Math.PI / 180; + const on = deg => [ring.x + ring.r * Math.cos(rad(deg)), ring.y + ring.r * Math.sin(rad(deg))]; + const [ex, ey] = on(exitAngle); + const [ox, oy] = [ring.x + (ring.r + 8) * Math.cos(rad(exitAngle)), ring.y + (ring.r + 8) * Math.sin(rad(exitAngle))]; + // Counter-clockwise from the entry to the exit: decreasing compass angle. + // Right-hand traffic enters on the right of the approach (160°), so a U-turn exit stays apart. + const entry = 160; + const sweep = ((entry - exitAngle) % 360 + 360) % 360 || 360; + const large = sweep > 180 ? 1 : 0; + const [sx, sy] = on(entry); + return `` + + thick(`M${sx.toFixed(2)} 45 L${sx.toFixed(2)} ${sy.toFixed(2)} A${ring.r} ${ring.r} 0 ${large} 0 ${ex.toFixed(2)} ${ey.toFixed(2)} L${ox.toFixed(2)} ${oy.toFixed(2)}`) + + head(ox, oy, exitAngle); +} +const glyphs = { + straight: thick('M24 45 L24 12') + head(24, 9, 0), + 'slight-left': thick('M28 45 L28 28 L16 14') + head(14, 11.5, -40), + left: thick('M30 45 L30 26 Q30 20 24 20 L12 20') + head(9, 20, -90), + 'sharp-left': thick('M32 45 L32 16 L15 33') + head(13, 35, -135), + 'uturn-left': thick('M31 45 L31 18 A7.5 7.5 0 0 0 16 18 L16 30') + head(16, 33, 180), + 'fork-left': thin('M24 45 L24 30 L34 12') + thick('M24 45 L24 30 L14 14') + head(12.5, 11.5, -30), + 'merge-left': thin('M16 45 L16 6') + thick('M34 45 L34 32 Q34 24 24 18 L24 12') + head(24, 9, 0), + 'ramp-left': thin('M30 45 L30 6') + thick('M30 45 L30 30 L16 16') + head(14, 13.5, -45), + 'roundabout-right': roundabout(90), + 'roundabout-slight-right': roundabout(45), + 'roundabout-straight': roundabout(0), + 'roundabout-slight-left': roundabout(315), + 'roundabout-left': roundabout(270), + 'roundabout-sharp-left': roundabout(225), + 'roundabout-uturn': roundabout(210), + arrive: thick('M24 45 L24 26') + '', + 'arrive-left': thick('M30 45 L30 18') + '', + // Unknown maneuver: a neutral marker; the supplied text carries the instruction. + unknown: '', +}; +for (const [name, body] of Object.entries(glyphs)) { + for (const scale of [1, 2, 3]) { + const size = 48 * scale; + outputs[`maneuver-${name}${scale === 1 ? '' : `@${scale}x`}.png`] = + `${body}`; + } +} + +// Map symbols: the turn arrowhead (inverse of the route ink, so it reads on top of the route) and +// the one-way chevron restored for driving. Both point up and are rotated on the map. +const arrowhead = { light: ['#FFFFFF', '#09090B'], dark: ['#000000', '#FFFFFF'] }; +const oneway = { light: '#71717A', dark: '#8E8E96' }; +for (const scheme of ['light', 'dark']) { + const [fill, edge] = arrowhead[scheme]; + for (const scale of [1, 2, 3]) { + const suffix = scale === 1 ? '' : `@${scale}x`; + outputs[`arrowhead-${scheme}${suffix}.png`] = `` + + ``; + outputs[`oneway-${scheme}${suffix}.png`] = `` + + ``; + } +} + +const check = process.argv.includes('--check'); +mkdirSync(out, { recursive: true }); +let stale = 0; +for (const [file, svg] of Object.entries(outputs)) { + const png = new Resvg(svg, { font: { loadSystemFonts: false }, shapeRendering: 2, background: undefined }).render().asPng(); + const path = `${out}${file}`; + if (check) { + let current = null; + try { current = readFileSync(path); } catch {} + const same = current && createHash('sha256').update(current).digest('hex') === createHash('sha256').update(png).digest('hex'); + if (!same) { stale += 1; console.error(`stale: assets/navigation/${file}`); } + } else { + writeFileSync(path, png); + } +} +if (!check) console.log(`wrote ${Object.keys(outputs).length} files to assets/navigation/`); +if (stale) process.exit(1); diff --git a/src/domain/navigation.ts b/src/domain/navigation.ts index b53d2af..89449e4 100644 --- a/src/domain/navigation.ts +++ b/src/domain/navigation.ts @@ -19,7 +19,7 @@ export interface NavigationSnapshot { notificationGranted: boolean; /** Independent of retained route/admission errors: only a current accepted fix is usable. */ locationUsable?: boolean; - location?: Coordinate & { accuracyMeters: number; bearing?: number; timestamp: number }; + location?: NavigationFix; instruction?: string; nextInstruction?: string; distanceToManeuverMeters?: number; @@ -27,6 +27,15 @@ export interface NavigationSnapshot { durationRemainingSeconds?: number; destinationDistanceMeters?: number; routeRevision?: number; + /** The next maneuver (Ferrostar's remainingSteps[1]); `instruction` is its Italian text. */ + upcomingManeuver?: GuidanceManeuver; + /** The maneuver after it (`nextInstruction`), with the distance/time separating the two. */ + followingManeuver?: FollowingManeuver; + /** Snapped progress measured on the bridged route geometry, for the traveled/remaining split. */ + routeProgress?: RouteProgress; + /** Ferrostar's route-snapped position; credible only while `alignment` is `aligned`. */ + snappedLocation?: Coordinate; + alignment?: 'aligned' | 'deviating' | 'unknown'; /** Events omit an unchanged route; null or a terminal session clears it. Reads include the full route. */ route?: { geometry: Coordinate[]; source: string; fetchedAt: number } | null; problem?: 'location-permission' | 'location-disabled' | 'location-stale' | 'location-inaccurate' | 'location-unavailable' @@ -58,6 +67,52 @@ export interface NavigationSnapshot { }; canRetry: boolean; } +/** An accepted fix. Kinematics are present only when the platform supplied finite values. */ +export interface NavigationFix extends Coordinate { + accuracyMeters: number; + /** Course while moving at 1 m/s or more (legacy field kept for older consumers). */ + bearing?: number; + /** Wall-clock sample time (ms). */ + timestamp: number; + speedMps?: number; + speedAccuracyMps?: number; + /** Course over ground in [0, 360), with its 68% accuracy when the platform reports one. */ + course?: number; + courseAccuracyDegrees?: number; + /** Monotonic sample time (Android elapsed realtime, ms): intervals, never wall time. */ + elapsedMs?: number; +} +export type ManeuverModifier = 'uturn' | 'sharp right' | 'right' | 'slight right' | 'straight' | 'slight left' | 'left' | 'sharp left'; +/** Raw OSRM maneuver facts; `id` is stable for one route revision and changes on every reroute. */ +export interface GuidanceManeuver { + id: string; + stepIndex: number; + /** Index of the maneuver point in the immutable route geometry of the same revision. */ + geometryIndex: number; + /** OSRM maneuver type, passed through unchanged; unknown values must not be guessed into turns. */ + type: string; + modifier?: ManeuverModifier; + exit?: number; + name?: string; + ref?: string; + instruction: string; + latitude?: number; + longitude?: number; + bearingBefore?: number; + bearingAfter?: number; + drivingSide?: 'left' | 'right'; +} +export interface FollowingManeuver extends GuidanceManeuver { + afterUpcomingMeters: number; + afterUpcomingSeconds: number; +} +export interface RouteProgress { + traveledMeters: number; + routeLengthMeters: number; + /** Route-geometry segment holding the snapped position. */ + segmentIndex: number; + stepIndex: number; +} export interface NavigationStart { destination: Coordinate; mode: RoadMode } export interface TransitNavigationStart { plan: RoutePlan; origin: Coordinate; destination: Coordinate } export type TransitConfirmation = 'board' | 'alight' | 'walk-complete'; diff --git a/src/features/app/AppMap.tsx b/src/features/app/AppMap.tsx index 8b41280..d681a3b 100644 --- a/src/features/app/AppMap.tsx +++ b/src/features/app/AppMap.tsx @@ -8,6 +8,8 @@ import { resultFrameBounds } from "../map/map-presentation"; import { searchMapStops } from "../search/search-rows"; import { useMapContext } from "../map/useMapModel"; import { useNavigationContext } from "../navigation/useNavigation"; +import { useGuidanceCamera } from "../navigation/useGuidanceCamera"; +import type { GuidanceViewport } from "../navigation/guidance-camera"; import { usePlacesContext } from "../places/usePlaces"; import { usePlannerContext } from "../planner/usePlanner"; import { useSearchContext } from "../search/useSearch"; @@ -17,8 +19,10 @@ import { useTaskState } from "./useTaskModel"; import { useTheme } from "../../theme"; /** The one mounted map: task pins, planning or guidance route, and camera intent. */ -export function AppMap({ height, padding, attributionLeft, attributionTop }: { +export function AppMap({ height, padding, attributionLeft, attributionTop, guidanceViewport }: { height: number; + /** The unobscured map between the guidance banner and the bottom strip. */ + guidanceViewport: GuidanceViewport; padding: { top: number; right: number; bottom: number; left: number }; attributionLeft: number; attributionTop: number; @@ -63,13 +67,16 @@ export function AppMap({ height, padding, attributionLeft, attributionTop }: { ? { type: "LineString", coordinates: navGeometry.map(toMapCoordinate) } : null, [navGeometry]); const navCenter = navigation.snapshot.location ?? navigation.snapshot.destination ?? camera.center; const navigating = navigation.visible; + // Road guidance: the app-controlled first-person camera; the map never follows on its own. + const guidance = useGuidanceCamera({ snapshot: navigation.snapshot, camera, viewport: guidanceViewport, active: navigating, transitPlan: navigation.transitPlan }); return ( planner.chooseOrigin(toCoordinate(coordinate))} onRegionChanged={(coordinate, zoom) => { - if (navigating) { camera.stopFollowing(); return; } + // Guidance enters free at gesture start (see MapCanvas); this settles later. + if (navigating) { if (!guidance) camera.stopFollowing(); return; } userPanned(toCoordinate(coordinate), zoom); }} onPressMarker={(id) => { diff --git a/src/features/app/AppShell.tsx b/src/features/app/AppShell.tsx index 5b70b8e..447addf 100644 --- a/src/features/app/AppShell.tsx +++ b/src/features/app/AppShell.tsx @@ -1,4 +1,4 @@ -import { useLayoutEffect, useRef } from "react"; +import { useLayoutEffect, useMemo, useRef, useState } from "react"; import { ActivityIndicator, Pressable, StyleSheet, useWindowDimensions, View } from "react-native"; import { Text } from "../../ui/Text"; import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context"; @@ -64,6 +64,15 @@ export function AppShell() { const mapPadding = mapCameraPadding({ width, height: mapHeight, sheetHeight: currentSheetHeight + 8, panelVisible, navigating: navigation.visible, fontScale }); const message = location.message || feedback.message; const dismissMessage = () => location.message ? location.setMessage("") : feedback.dismiss(); + // Measured guidance chrome: the camera places the puck inside the map left between them. + // `right` is a side panel's width (landscape), so the map left of it is what the camera frames. + const [guidanceChrome, setGuidanceChrome] = useState({ top: 120, bottom: 190, right: 0 }); + const guidanceViewport = useMemo(() => { + const top = Math.min(guidanceChrome.top, mapHeight - 160); + return { width, height: mapHeight, top, bottom: Math.max(top + 120, mapHeight - guidanceChrome.bottom), left: 0, right: Math.max(160, width - guidanceChrome.right) }; + }, [width, mapHeight, guidanceChrome]); + const onGuidanceChrome = (top: number, bottom: number, right = 0) => setGuidanceChrome(current => + Math.abs(current.top - top) < 1 && Math.abs(current.bottom - bottom) < 1 && Math.abs(current.right - right) < 1 ? current : { top, bottom, right }); const overlayPosition = { bottom: !wide && panelVisible ? currentSheetHeight + 24 : 88, left: wide && panelVisible ? SIDE_SHEET_WIDTH + 8 : 16, right: 16 }; return ( @@ -72,15 +81,17 @@ export function AppShell() { height={mapHeight} padding={mapPadding} attributionLeft={wide && panelVisible && !navigation.visible ? SIDE_SHEET_WIDTH - 4 : 8} - attributionTop={navigation.visible ? Math.min(height * 0.3, 104 * Math.min(fontScale, 1.5)) + 8 : 68} + attributionTop={navigation.visible ? guidanceViewport.top + 8 : 68} + guidanceViewport={guidanceViewport} /> {navigation.visible && (navigation.snapshot.mode === "transit" || (navigation.busy === "start" && navigation.startKind === "transit")) ? ( - { void navigation.stop(); }} onRetry={() => { void navigation.retry(); }} onConfirm={action => { void navigation.confirmTransit(action); }} onReplan={() => { void planner.replanFromNavigation(); }} onMute={() => { void navigation.toggleMuted(); }} /> ) : navigation.visible ? ( - { void navigation.stop(); }} onRetry={() => { void navigation.retry(); }} onMute={() => { void navigation.toggleMuted(); }} onConfirmTransit={action => { void navigation.confirmTransit(action); }} onReplan={() => { void planner.replanFromNavigation(); }} /> ) : <> diff --git a/src/features/map/GuidanceMapLayers.tsx b/src/features/map/GuidanceMapLayers.tsx new file mode 100644 index 0000000..a863970 --- /dev/null +++ b/src/features/map/GuidanceMapLayers.tsx @@ -0,0 +1,65 @@ +import { useMemo } from 'react'; +import { GeoJSONSource, Layer } from '@maplibre/maplibre-react-native'; +import type { LineString } from 'geojson'; +import type { MapColors } from '../../theme'; +import type { ColorScheme } from '../../theme/palette'; +import type { ManeuverArrow } from '../navigation/guidance-route'; +import { remainingGradient } from '../navigation/guidance-route'; + +/** Route and turn arrow sit under street names, so labels stay readable over the line. */ +const BELOW_LABELS = 'highway-name-path'; +/** Generic business dots and labels: hidden while driving or cycling; street names stay. */ +const POI_LAYERS: { id: string; type: 'circle' | 'symbol' }[] = [ + { id: 'avoid_poi_dot_r1', type: 'circle' }, { id: 'avoid_poi_dot_r7', type: 'circle' }, { id: 'avoid_poi_dot_r20', type: 'circle' }, + { id: 'poi_r1', type: 'symbol' }, { id: 'poi_r7', type: 'symbol' }, { id: 'poi_r20', type: 'symbol' }, +]; + +const EMPTY = { type: 'FeatureCollection' as const, features: [] }; +/** + * Basemap adjustments during guidance: generic business dots and labels hidden while driving or + * cycling, one-way chevrons (a hidden brand-basemap layer) shown while driving. The style layers are + * adopted as children of an empty app source because MapLibre RN re-adds sources, and with them + * their layers, after every style load (a live theme switch); standalone adopted layers would go stale. + */ +export function BasemapGuidanceAdjustments({ reduceBusinesses, oneWayArrows }: { reduceBusinesses: boolean; oneWayArrows: boolean }) { + const visibility = reduceBusinesses ? 'none' : 'visible'; + return + {POI_LAYERS.map(layer => layer.type === 'circle' + ? + : )} + + ; +} + +/** + * Guidance route: a thin muted full route (the travelled part shows through), the active remaining + * route with a contrasting casing cut at the snapped progress, and one cased arrow through the next + * junction. Progress changes only paint, never the source geometry. + */ +export function GuidanceRouteLayers({ route, fraction, arrow, colors, scheme }: { + route: LineString; fraction: number; arrow: ManeuverArrow | null; colors: MapColors; scheme: ColorScheme; +}) { + const data = useMemo(() => ({ type: 'Feature' as const, geometry: route, properties: {} }), [route]); + const arrowData = useMemo(() => arrow ? { type: 'Feature' as const, geometry: { type: 'LineString' as const, coordinates: arrow.shaft }, properties: {} } : null, [arrow]); + const headData = useMemo(() => arrow ? { type: 'Feature' as const, geometry: { type: 'Point' as const, coordinates: arrow.head.coordinate }, properties: { bearing: arrow.head.bearing } } : null, [arrow]); + const round = { 'line-cap': 'round', 'line-join': 'round' } as const; + return <> + + + + + + {arrowData && headData ? <> + + + + + + + + : null} + ; +} diff --git a/src/features/map/MapCanvas.native.tsx b/src/features/map/MapCanvas.native.tsx index d37b716..2fe9b4c 100644 --- a/src/features/map/MapCanvas.native.tsx +++ b/src/features/map/MapCanvas.native.tsx @@ -1,19 +1,23 @@ import React, { useEffect, useMemo, useRef, useState } from 'react'; -import { StyleSheet, View } from 'react-native'; +import { Image, StyleSheet, View } from 'react-native'; import { Text } from '../../ui/Text'; -import { Camera, GeoJSONSource, Layer, Map, type CameraRef, type MapRef } from '@maplibre/maplibre-react-native'; +import { Camera, GeoJSONSource, Images, Layer, Map, type CameraRef, type MapRef } from '@maplibre/maplibre-react-native'; import type { FeatureCollection, Point } from 'geojson'; import { useTheme } from '../../theme'; import { diagnostics } from '../../services/diagnostics'; import type { MapCanvasProps } from './MapCanvas.types'; import { createOnceFraming, createRouteFraming, frameCamera } from './map-presentation'; import { lineLayout, markerLabelLayout, overlayPaint } from './map-overlay-style'; +import { GUIDANCE_IMAGES, puckImage, puckLayout } from './guidance-puck'; +import { BasemapGuidanceAdjustments, GuidanceRouteLayers } from './GuidanceMapLayers'; +import { useGuidanceCameraDriver } from './useGuidanceCameraDriver'; +import { createOrientationReset } from './orientation-reset'; /** * The one native map. An appearance change swaps `mapStyle` and layer paint in place: Map and Camera * stay mounted, so the camera, route, markers and position survive a Sistema/Chiaro/Scuro switch. */ -export default function MapCanvas({ center, zoom = 14.5, cameraRevision, routeFitKey, resultFrame, cameraPadding, attributionTop = 68, attributionLeft = 8, markers = [], selectedMarkerId, route, coverageBounds, userLocation, followLocation, onPressMarker, onMapPress, onRegionChanged, onViewChanged }: MapCanvasProps) { +export default function MapCanvas({ center, zoom = 14.5, cameraRevision, routeFitKey, resultFrame, cameraPadding, attributionTop = 68, attributionLeft = 8, markers = [], selectedMarkerId, route, coverageBounds, userLocation, followLocation, onPressMarker, onMapPress, onRegionChanged, onViewChanged, guidance }: MapCanvasProps) { const theme = useTheme(); const paint = useMemo(() => overlayPaint(theme.map), [theme.map]); const framing = useRef(createRouteFraming()); @@ -37,15 +41,20 @@ export default function MapCanvas({ center, zoom = 14.5, cameraRevision, routeFi // centre or bounds, so re-centre on the camera's actual centre: the point the user was looking at // (including after a pan) moves into the newly visible area instead of under the sheet. const { top = 0, right = 0, bottom = 0, left = 0 } = cameraPadding ?? {}; + const guiding = !!guidance; + // After guidance the browsing map returns to north-up and flat, carried by whichever browse + // command is actually issued next (see orientation-reset.ts). + const orientation = useRef(createOrientationReset()); useEffect(() => { + if (guiding) { orientation.current.arm(); return; } if (!loaded || followLocation === true) return; let current = true; const issued = commands.current; void map.current?.getCenter().then(center => { - if (current && issued === commands.current) camera.current?.easeTo({ center, padding: { top, right, bottom, left }, duration: 250 }); + if (current && issued === commands.current) camera.current?.easeTo(orientation.current.apply({ center, padding: { top, right, bottom, left }, duration: 250 })); }).catch(() => undefined); return () => { current = false; }; - }, [loaded, top, right, bottom, left, followLocation]); + }, [loaded, top, right, bottom, left, followLocation, guiding]); // A submitted search frames its results once; a pan before the results settle consumes the frame. const frameKey = resultFrame?.key; const frameBounds = resultFrame?.ready ? resultFrame.bounds : null; @@ -55,20 +64,30 @@ export default function MapCanvas({ center, zoom = 14.5, cameraRevision, routeFi // fitBounds has no zoom cap here, and padding taller than the map zoomed to the maximum (a blank // building interior for two results 30 m apart): ease to a computed, capped camera instead. const inset = padding.current ?? { top: 50, right: 50, bottom: 50, left: 50 }; - camera.current?.easeTo({ ...frameCamera(frameBounds, size.current, inset), padding: inset, duration: 500 }); + camera.current?.easeTo(orientation.current.apply({ ...frameCamera(frameBounds, size.current, inset), padding: inset, duration: 500 })); }, [loaded, frameKey, frameBounds]); - useEffect(() => { if (followLocation !== false) { commands.current += 1; camera.current?.easeTo({ center: [longitude, latitude], zoom, padding: padding.current, duration: 450 }); } }, [longitude, latitude, zoom, followLocation, cameraRevision]); + const gesture = useGuidanceCameraDriver({ guidance: guidance ?? null, loaded, camera, map, commands, size }); + useEffect(() => { if (followLocation !== false && !guiding) { commands.current += 1; camera.current?.easeTo(orientation.current.apply({ center: [longitude, latitude] as [number, number], zoom, padding: padding.current, duration: 450 })); } }, [longitude, latitude, zoom, followLocation, cameraRevision, guiding]); useEffect(() => { if (followLocation !== undefined || !framing.current.claim(routeFitKey, !!route?.coordinates.length) || !route) return; const xs = route.coordinates.map(p => p[0]!); const ys = route.coordinates.map(p => p[1]!); commands.current += 1; - camera.current?.fitBounds([Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)], { padding: padding.current ?? { top: 50, right: 50, bottom: 50, left: 50 }, duration: 500 }); + camera.current?.fitBounds([Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)], orientation.current.apply({ padding: padding.current ?? { top: 50, right: 50, bottom: 50, left: 50 }, duration: 500 })); }, [route, routeFitKey, followLocation]); + // Follow: the puck is drawn at the camera's anchor, so it and the map share one animation clock. + // Free, overview or a paused fix: a map symbol at the accepted (or retained) position. + const frame = guidance?.frame ?? null; + const followPuck = guidance?.intent === 'follow' && frame !== null && frame.puck.kind !== 'retained'; + const mapPuck = guidance && !followPuck ? guidance.puck : null; + const overlayPuck = followPuck && frame ? { + source: GUIDANCE_IMAGES[puckImage(frame.puck.kind, theme.scheme)]!, x: frame.anchor.x, y: frame.anchor.y, + rotation: frame.puck.heading === null ? 0 : frame.puck.heading - frame.bearing, tilt: Math.round(frame.pitch * 0.55), + } : null; return { size.current = event.nativeEvent.layout; }}> onMapPress?.(event.nativeEvent.lngLat)} // A user gesture outranks a pending padding re-centre (see `commands`). - onRegionWillChange={event => { if (event.nativeEvent.userInteraction) commands.current += 1; }} + onRegionWillChange={event => { if (event.nativeEvent.userInteraction) { commands.current += 1; if (!guiding) orientation.current.userMoved(); gesture(); } }} onRegionDidChange={event => { const { center: shown, zoom: shownZoom, userInteraction } = event.nativeEvent; onViewChanged?.(shown, shownZoom); @@ -76,11 +95,14 @@ export default function MapCanvas({ center, zoom = 14.5, cameraRevision, routeFi }} onDidFailLoadingMap={() => { setMapError(true); diagnostics.record({ type: 'map', state: 'failed' }); }} onDidFinishLoadingMap={() => { setLoaded(true); setMapError(false); diagnostics.record({ type: 'map', state: 'loaded' }); }}> + {coverage && } - {route && + + {route && guidance?.route ? : null} + {route && !guidance?.route && } @@ -91,7 +113,14 @@ export default function MapCanvas({ center, zoom = 14.5, cameraRevision, routeFi {userLocation && } + {mapPuck && + + } + {overlayPuck && + + } {mapError && Mappa non disponibile · riprova con una connessione} ; } diff --git a/src/features/map/MapCanvas.types.ts b/src/features/map/MapCanvas.types.ts index af55f22..632b4c2 100644 --- a/src/features/map/MapCanvas.types.ts +++ b/src/features/map/MapCanvas.types.ts @@ -1,4 +1,5 @@ import type { LineString } from 'geojson'; +import type { GuidanceMapState } from '../navigation/useGuidanceCamera'; export type MapCoordinate = [number, number]; export interface MapMarker { id: string; @@ -34,4 +35,9 @@ export interface MapCanvasProps { onViewChanged?: (center: MapCoordinate, zoom: number) => void; /** A user-driven camera change: the new centre and zoom. */ onRegionChanged?: (center: MapCoordinate, zoom: number) => void; + /** + * Active road guidance: the app-controlled first-person camera and puck. While present, the map + * never runs its own following, padding re-centre or route fit, and a gesture enters free at once. + */ + guidance?: GuidanceMapState | null; } diff --git a/src/features/map/guidance-puck.ts b/src/features/map/guidance-puck.ts new file mode 100644 index 0000000..e26421a --- /dev/null +++ b/src/features/map/guidance-puck.ts @@ -0,0 +1,30 @@ +import type { SymbolLayerSpecification } from '@maplibre/maplibre-gl-style-spec'; +import type { ColorScheme } from '../../theme/palette'; +import type { PuckKind } from '../navigation/guidance-camera'; + +/** + * Original puck artwork rendered by scripts/render-navigation-assets.mjs: a wedge with a live green + * centre, a disc when the direction is unknown, and a subdued hollow ring for a retained position. + */ +export const GUIDANCE_IMAGES: Record = { + 'puck-wedge-light': require('../../../assets/navigation/puck-wedge-light.png'), + 'puck-wedge-dark': require('../../../assets/navigation/puck-wedge-dark.png'), + 'puck-dot-light': require('../../../assets/navigation/puck-dot-light.png'), + 'puck-dot-dark': require('../../../assets/navigation/puck-dot-dark.png'), + 'puck-retained-light': require('../../../assets/navigation/puck-retained-light.png'), + 'puck-retained-dark': require('../../../assets/navigation/puck-retained-dark.png'), + 'arrowhead-light': require('../../../assets/navigation/arrowhead-light.png'), + 'arrowhead-dark': require('../../../assets/navigation/arrowhead-dark.png'), + 'oneway-light': require('../../../assets/navigation/oneway-light.png'), + 'oneway-dark': require('../../../assets/navigation/oneway-dark.png'), +}; + +export const puckImage = (kind: PuckKind, scheme: ColorScheme) => `puck-${kind}-${scheme}`; + +/** Map-aligned heading; the icon faces the viewer so it stays legible under pitch. */ +export function puckLayout(image: string, heading: number): NonNullable { + return { + 'icon-image': image, 'icon-rotate': heading, 'icon-rotation-alignment': 'map', 'icon-pitch-alignment': 'viewport', + 'icon-allow-overlap': true, 'icon-ignore-placement': true, + }; +} diff --git a/src/features/map/orientation-reset.test.ts b/src/features/map/orientation-reset.test.ts new file mode 100644 index 0000000..8d8fbdb --- /dev/null +++ b/src/features/map/orientation-reset.test.ts @@ -0,0 +1,21 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createOrientationReset } from './orientation-reset'; + +test('the reset survives a superseded command and is carried by the next issued one, once', () => { + const reset = createOrientationReset(); + assert.deepEqual(reset.apply({ duration: 250 }), { duration: 250 }, 'nothing armed: unchanged'); + reset.arm(); + // The padding re-centre was superseded before its async centre resolved: it never called apply. + // The browsing follow ease issued in the same flush carries the pose instead. + assert.deepEqual(reset.apply({ duration: 450 }), { duration: 450, bearing: 0, pitch: 0 }); + assert.equal(reset.armed, false); + assert.deepEqual(reset.apply({ duration: 250 }), { duration: 250 }, 'applied once only'); +}); + +test('a user gesture after guidance keeps the chosen view', () => { + const reset = createOrientationReset(); + reset.arm(); + reset.userMoved(); + assert.deepEqual(reset.apply({ duration: 250 }), { duration: 250 }); +}); diff --git a/src/features/map/orientation-reset.ts b/src/features/map/orientation-reset.ts new file mode 100644 index 0000000..b2e203d --- /dev/null +++ b/src/features/map/orientation-reset.ts @@ -0,0 +1,21 @@ +/** + * The browsing map returns to north-up and flat after guidance. Several browse commands can race + * when guidance closes (padding re-centre, follow ease, route fit); some are skipped because a newer + * command superseded them. The reset therefore stays armed until a command that is actually issued + * carries it, and only a user gesture (a deliberate view) cancels it. + */ +export function createOrientationReset() { + let armed = false; + return { + arm() { armed = true; }, + get armed() { return armed; }, + /** A user gesture chose the view: no reset is applied any more. */ + userMoved() { armed = false; }, + /** Adds the north-up, flat pose to the command being issued, once. */ + apply(options: T): T & { bearing?: number; pitch?: number } { + if (!armed) return options; + armed = false; + return { ...options, bearing: 0, pitch: 0 }; + }, + }; +} diff --git a/src/features/map/useGuidanceCameraDriver.ts b/src/features/map/useGuidanceCameraDriver.ts new file mode 100644 index 0000000..e6a7754 --- /dev/null +++ b/src/features/map/useGuidanceCameraDriver.ts @@ -0,0 +1,85 @@ +import { useCallback, useEffect, useRef, type RefObject } from 'react'; +import type { CameraRef, MapRef } from '@maplibre/maplibre-react-native'; +import type { GuidanceMapState } from '../navigation/useGuidanceCamera'; +import type { CameraFrame } from '../navigation/guidance-camera'; +import { project } from '../navigation/map-projection'; +import { pendingGuidanceCommand, type IssuedCommands } from '../navigation/guidance-commands'; + +/** Development-only screen assertions, read from the device log (`[nav-cam]`). */ +const ASSERT = typeof __DEV__ !== 'undefined' && __DEV__; + +/** + * Issues the guidance camera (see `pendingGuidanceCommand`): one native ease per frame in follow, a + * fit per transit leg or overview request, nothing in free. A gesture is reported at its start and + * blocks every pending move at once. + */ +export function useGuidanceCameraDriver({ guidance, loaded, camera, map, commands, size }: { + guidance: GuidanceMapState | null; loaded: boolean; camera: RefObject; map: RefObject; + commands: RefObject; size: RefObject<{ width: number; height: number }>; +}) { + const intent = guidance?.intent; + const frame = guidance?.frame ?? null; + const overview = guidance?.overview ?? null; + const fit = guidance?.fit ?? null; + const issued = useRef({ frame: null, overview: null, fit: null }); + const gestureActive = useRef(false); + const latest = useRef(guidance); + latest.current = guidance; + useEffect(() => { if (intent !== 'free') gestureActive.current = false; }, [intent]); + useEffect(() => { + if (!loaded || !intent) return; + const command = pendingGuidanceCommand({ intent, frame, overview, fit, gesture: gestureActive.current }, issued.current); + if (!command) return; + issued.current = { ...issued.current, [command.kind]: command.key }; + commands.current += 1; + if (command.kind === 'frame') { + const next = command.frame; + camera.current?.easeTo({ + center: [next.center.longitude, next.center.latitude], bearing: next.bearing, pitch: next.pitch, zoom: next.zoom, + padding: next.padding, duration: next.durationMs, easing: next.easing, + }); + if (ASSERT) assertFrame(map, next, size.current, latest); + } else { + // Overview and transit leg fits are flat and north-up. + camera.current?.fitBounds(command.fit.bounds, { padding: command.fit.padding, bearing: 0, pitch: 0, duration: 700 }); + } + }, [loaded, intent, frame, overview, fit, camera, map, commands, size]); + useEffect(() => { if (!guidance) issued.current = { frame: null, overview: null, fit: null }; }, [guidance]); + return useCallback(() => { + const current = latest.current; + if (!current) return; + gestureActive.current = true; + if (ASSERT) console.log(`[nav-cam] gesture intent=${current.intent} at=${Date.now()}`); + if (current.intent !== 'free') current.onUserGesture(); + }, []); +} + +/** + * Near the end of the move, compare MapLibre's own projection with the planned anchor and framing: + * the camera centre must land on the anchor, the junction and outgoing path inside the map. + */ +function assertFrame(map: RefObject, frame: CameraFrame, size: { width: number; height: number }, latest: RefObject) { + const issuedAt = Date.now(); + setTimeout(() => { + const ref = map.current; + // Guidance ended or the camera left follow: nothing to assert. + if (!ref || latest.current?.intent !== 'follow') return; + const puck: [number, number] = [frame.center.longitude, frame.center.latitude]; + const junction = frame.framing?.points[0]; + void Promise.all([ + ref.project(puck), ref.getZoom(), ref.getBearing(), ref.getPitch(), + junction ? ref.project([junction.longitude, junction.latitude]) : Promise.resolve(null), + ]).then(([screen, zoom, bearing, pitch, junctionScreen]) => { + const predicted = junction ? project(frame, size, junction) : null; + const row = { + key: frame.key.split(':')[0], dt: Date.now() - issuedAt, dur: frame.durationMs, anchorY: round(frame.anchor.y), puckY: round(screen[1]), puckX: round(screen[0]), + dyPct: round(100 * (screen[1] - frame.anchor.y) / size.height, 2), zoom: round(zoom, 2), zoomCmd: frame.zoom, bearing: round(bearing, 1), bearingCmd: round(frame.bearing, 1), + pitch: round(pitch, 1), lead: frame.leadMeters, framing: frame.framing?.maneuverId ?? null, + junction: junctionScreen ? [round(junctionScreen[0]), round(junctionScreen[1])] : null, + junctionPredicted: predicted ? [round(predicted.x), round(predicted.y)] : null, + }; + console.log(`[nav-cam] ${JSON.stringify(row)}`); + }).catch(() => undefined); + }, Math.max(0, frame.durationMs - 60)); +} +const round = (value: number, digits = 0) => Math.round(value * 10 ** digits) / 10 ** digits; diff --git a/src/features/map/useMapCamera.ts b/src/features/map/useMapCamera.ts index 6fc7caf..fdc271b 100644 --- a/src/features/map/useMapCamera.ts +++ b/src/features/map/useMapCamera.ts @@ -1,6 +1,7 @@ import AsyncStorage from '@react-native-async-storage/async-storage'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import type { Coordinate } from '../../domain/types'; +import { nextIntent, type CameraIntent, type CameraIntentEvent } from '../navigation/guidance-camera'; import { TURIN_OVERVIEW } from './coordinates'; import { createViewportStore, mayPersistSettledView } from './viewport-store'; @@ -18,6 +19,12 @@ export interface MapCamera { areaChanged: boolean; /** Guidance follows accepted positions until the user pans. */ following: boolean; + /** Guidance camera intent: follow, free (after a gesture) or overview. */ + guidanceIntent: CameraIntent; + /** Changes on every explicit Ricentra, so the camera issues exactly one transition. */ + guidanceRecenter: number; + /** Changes on every explicit overview request; the remaining route is framed once per value. */ + guidanceOverview: number; /** Changes when the user asks to frame the planning route again. */ frameRevision: number; /** The launch overview, a restored view, a fix, or a view the user chose. */ @@ -38,9 +45,12 @@ export interface MapCamera { userMoved(coordinate: Coordinate, zoom?: number): void; /** Any settled camera move reported by the map outside guidance, including fits and animations. */ viewSettled(coordinate: Coordinate, zoom?: number): void; + /** A guidance-map gesture began: enter free immediately and keep it until Ricentra. */ stopFollowing(): void; follow(): void; recenterGuidance(): void; + /** Frame the remaining route north-up and flat, once. */ + overviewGuidance(): void; frameRoute(): void; /** Forgets the stored last view; the next launch without a fix opens on the overview. */ forgetLastView(): Promise; @@ -66,7 +76,10 @@ export function useMapCamera(): MapCamera { const [searchCenter, setSearchCenterState] = useState(TURIN_OVERVIEW.center); const searchCenterRef = useRef(TURIN_OVERVIEW.center); const [areaChanged, setAreaChanged] = useState(false); - const [following, setFollowing] = useState(true); + const [guidanceIntent, setGuidanceIntent] = useState('follow'); + const [guidanceRecenter, setGuidanceRecenter] = useState(0); + const [guidanceOverview, setGuidanceOverview] = useState(0); + const intentEvent = useCallback((event: CameraIntentEvent) => setGuidanceIntent(current => nextIntent(current, event)), []); const [frameRevision, setFrameRevision] = useState(0); const [view, setView] = useState('overview'); const [viewCenter, setViewCenter] = useState(TURIN_OVERVIEW.center); @@ -137,11 +150,13 @@ export function useMapCamera(): MapCamera { // Programmatic fits are what the user last saw too; persist them once the user has engaged. if (mayPersistSettledView({ engaged: touched.current || located.current, forgotten: forgotten.current })) scheduleSave(); }, - stopFollowing: () => setFollowing(false), - follow: () => setFollowing(true), - recenterGuidance: () => { setFollowing(true); setRevision(value => value + 1); }, + stopFollowing: () => intentEvent('gesture'), + follow: () => intentEvent('reset'), + recenterGuidance: () => { intentEvent('recenter'); setGuidanceRecenter(value => value + 1); setRevision(value => value + 1); }, + overviewGuidance: () => { intentEvent('overview'); setGuidanceOverview(value => value + 1); }, frameRoute: () => setFrameRevision(value => value + 1), forgetLastView: () => { forgotten.current = true; clearTimeout(saveTimer.current); return viewportStore.clear(); }, - }), [setCenter, setCameraZoom, setSearchCenter, scheduleSave]); - return { center, zoom, revision, searchCenter, areaChanged, following, frameRevision, view, viewCenter, ...actions }; + }), [setCenter, setCameraZoom, setSearchCenter, scheduleSave, intentEvent]); + const following = guidanceIntent === 'follow'; + return { center, zoom, revision, searchCenter, areaChanged, following, guidanceIntent, guidanceRecenter, guidanceOverview, frameRevision, view, viewCenter, ...actions }; } diff --git a/src/features/navigation/BannerReserveProbe.tsx b/src/features/navigation/BannerReserveProbe.tsx new file mode 100644 index 0000000..6e113fd --- /dev/null +++ b/src/features/navigation/BannerReserveProbe.tsx @@ -0,0 +1,40 @@ +import { useRef } from 'react'; +import { View } from 'react-native'; +import { Display, Text } from '../../ui'; +import { MAX_FONT_SCALE, type BannerMetrics } from './guidance-layout'; + +type Row = 'firstRow' | 'street2' | 'streetAction' | 'message2' | 'thenRow'; +/** + * Android scales text non-linearly at large font sizes, so the banner's row reserves are measured + * from the tallest content each row can hold, rendered invisibly with the same type styles. The + * banner rows then have fixed heights: instruction, status or pause changes never resize it. + */ +export function BannerReserveProbe({ onMeasure }: { onMeasure: (metrics: Omit) => void }) { + const rows = useRef>>({}); + const measure = (row: Row) => (event: { nativeEvent: { layout: { height: number } } }) => { + const height = Math.ceil(event.nativeEvent.layout.height); + if (rows.current[row] === height) return; + const next = { ...rows.current, [row]: height }; + rows.current = next; + if (next.firstRow && next.street2 && next.streetAction && next.message2 && next.thenRow) { + onMeasure({ firstRow: next.firstRow, lines: Math.max(next.street2, next.streetAction, next.message2), thenRow: Math.max(22, next.thenRow) }); + } + }; + return + 0 + + {'Ag\nAg'} + + + Ag + Ag + + + {'Ag\nAg'} + + + Poi + + ; +} diff --git a/src/features/navigation/ManeuverGlyphImage.tsx b/src/features/navigation/ManeuverGlyphImage.tsx new file mode 100644 index 0000000..3d66e47 --- /dev/null +++ b/src/features/navigation/ManeuverGlyphImage.tsx @@ -0,0 +1,39 @@ +import { Image, View } from 'react-native'; +import { Text } from '../../ui/Text'; +import type { GlyphName, ManeuverGlyph } from './maneuver-presentation'; +import { exitNumberSize } from './exit-number'; + +/** Single-ink maneuver artwork (scripts/render-navigation-assets.mjs), tinted to the text colour. */ +const GLYPHS: Record = { + straight: require('../../../assets/navigation/maneuver-straight.png'), + 'slight-left': require('../../../assets/navigation/maneuver-slight-left.png'), + left: require('../../../assets/navigation/maneuver-left.png'), + 'sharp-left': require('../../../assets/navigation/maneuver-sharp-left.png'), + 'uturn-left': require('../../../assets/navigation/maneuver-uturn-left.png'), + 'fork-left': require('../../../assets/navigation/maneuver-fork-left.png'), + 'merge-left': require('../../../assets/navigation/maneuver-merge-left.png'), + 'ramp-left': require('../../../assets/navigation/maneuver-ramp-left.png'), + 'roundabout-right': require('../../../assets/navigation/maneuver-roundabout-right.png'), + 'roundabout-slight-right': require('../../../assets/navigation/maneuver-roundabout-slight-right.png'), + 'roundabout-straight': require('../../../assets/navigation/maneuver-roundabout-straight.png'), + 'roundabout-slight-left': require('../../../assets/navigation/maneuver-roundabout-slight-left.png'), + 'roundabout-left': require('../../../assets/navigation/maneuver-roundabout-left.png'), + 'roundabout-sharp-left': require('../../../assets/navigation/maneuver-roundabout-sharp-left.png'), + 'roundabout-uturn': require('../../../assets/navigation/maneuver-roundabout-uturn.png'), + arrive: require('../../../assets/navigation/maneuver-arrive.png'), + 'arrive-left': require('../../../assets/navigation/maneuver-arrive-left.png'), + unknown: require('../../../assets/navigation/maneuver-unknown.png'), +}; + +/** Decorative: the banner's accessibility label already says what the glyph shows. */ +export function ManeuverGlyphImage({ glyph, size, color }: { glyph: ManeuverGlyph; size: number; color: string }) { + const exitSize = exitNumberSize(size); + return + + {glyph.exit !== undefined ? ( + {glyph.exit} + ) : null} + ; +} diff --git a/src/features/navigation/NavigationPanel.tsx b/src/features/navigation/NavigationPanel.tsx index 87d06fa..e87910b 100644 --- a/src/features/navigation/NavigationPanel.tsx +++ b/src/features/navigation/NavigationPanel.tsx @@ -1,17 +1,34 @@ -import { useEffect, useState } from 'react'; -import { ActivityIndicator, Linking, Modal, Pressable, ScrollView, useWindowDimensions, View } from 'react-native'; -import { Text } from '../../ui/Text'; -import { useThemeColors } from '../../theme'; +import { useEffect, useRef, useState } from 'react'; +import { ActivityIndicator, Linking, Modal, ScrollView, useWindowDimensions, View } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; +import { useThemeColors } from '../../theme'; import type { TransitConfirmation } from '../../domain/navigation'; import { navigationLocationForReplan, navigationPresentation } from '../../domain/navigation'; -import { Button, Display, Icon, IconButton, Notice, Num, useHairlines } from '../../ui'; -import type { NavigationState } from './navigation-controller'; +import { Button, Display, Icon, IconButton, Notice, Num, Text, useHairlines } from '../../ui'; +import { PressableSurface } from '../../ui/PressableSurface'; import { journeyDuration } from '../planner/journey-presentation'; +import type { CameraIntent } from './guidance-camera'; +import { bannerDistance, maneuverGlyph, maneuverLines, thenManeuver } from './maneuver-presentation'; +import { ManeuverGlyphImage } from './ManeuverGlyphImage'; +import { bannerMetrics, MAX_FONT_SCALE, stripLayout, type BannerMetrics } from './guidance-layout'; +import { BannerReserveProbe } from './BannerReserveProbe'; +import type { NavigationState } from './navigation-controller'; const distance = (meters: number) => meters < 1000 ? `${Math.round(meters)} m` : `${(meters / 1000).toFixed(1).replace('.', ',')} km`; -export function NavigationPanel({ snapshot, busy, error, following, onRecenter, onStop, onRetry, onMute, onConfirmTransit, onReplan }: NavigationState & { - following: boolean; onRecenter: () => void; onStop: () => void; onRetry: () => void; onMute: () => void; +/** Landscape side panel width (dp): the strip and details move beside the map. */ +const SIDE_PANEL = 320; +const clock = (value: number) => new Date(value).toLocaleTimeString('it-IT', { hour: '2-digit', minute: '2-digit' }); + +/** + * Road guidance: a flush maneuver banner on top, the map, and a compact bottom strip (arrival, + * remaining time/distance, voice, overview, Interrompi). Status lives in a reserved row, so position + * quality, rerouting and pauses never move the banner, the strip or the camera's anchor. + */ +export function NavigationPanel({ snapshot, busy, error, intent, onRecenter, onOverview, onChromeLayout, onStop, onRetry, onMute, onConfirmTransit, onReplan }: NavigationState & { + following: boolean; intent: CameraIntent; onRecenter: () => void; onOverview: () => void; + /** Heights of the banner and the bottom strip, so the camera anchors the puck between them. */ + onChromeLayout: (top: number, bottom: number, right?: number) => void; + onStop: () => void; onRetry: () => void; onMute: () => void; onConfirmTransit: (action: TransitConfirmation) => void; onReplan: () => void; }) { const colors = useThemeColors(); @@ -19,94 +36,182 @@ export function NavigationPanel({ snapshot, busy, error, following, onRecenter, const { width, height, fontScale } = useWindowDimensions(); const [detailsOpen, setDetailsOpen] = useState(false); const [now, setNow] = useState(Date.now()); + const banner = useRef(0); + const strip = useRef(0); + const [stripHeight, setStripHeight] = useState(0); + const [bannerHeight, setBannerHeight] = useState(0); const transitMode = snapshot.mode === 'transit'; - const cues = snapshot.locationUsable === true; const waiting = busy === 'start' || snapshot.status === 'waiting-for-fix' || snapshot.status === 'routing' || snapshot.status === 'rerouting'; - const remainingSeconds = snapshot.mode !== 'transit' ? snapshot.durationRemainingSeconds : undefined; - const arrival = remainingSeconds != null && snapshot.location ? new Date(snapshot.location.timestamp + remainingSeconds * 1000).toLocaleTimeString('it-IT', { hour: '2-digit', minute: '2-digit' }) : null; + const remainingSeconds = !transitMode ? snapshot.durationRemainingSeconds : undefined; + const text0 = navigationPresentation(snapshot, now, null, busy === 'start'); + // Only a current fix advances the estimate; a paused position never shows an apparently current ETA. + const arrival = remainingSeconds != null && snapshot.location && text0.guiding ? clock(snapshot.location.timestamp + remainingSeconds * 1000) : null; const text = navigationPresentation(snapshot, now, arrival, busy === 'start'); const { terminal, guiding, paused, searching } = text; useEffect(() => { const timer = setInterval(() => setNow(Date.now()), searching ? 1_000 : 15_000); return () => clearInterval(timer); }, [searching]); const transit = snapshot.transit; - const time = (value: number) => new Date(value).toLocaleTimeString('it-IT', { hour: '2-digit', minute: '2-digit' }); const transitAge = transit ? Math.max(0, Math.floor((now - transit.fetchedAt) / 60_000)) : 0; const replanLocation = navigationLocationForReplan(snapshot); const confirmation: TransitConfirmation | undefined = transit?.canConfirmWalking ? 'walk-complete' : transit?.canConfirmBoarding ? 'board' : transit?.canConfirmAlighting ? 'alight' : undefined; - const voiceLabel = snapshot.voice === 'ready' ? 'Voce attiva' : snapshot.voice === 'muted' ? 'Voce disattivata' : snapshot.voice === 'initializing' ? 'Preparazione voce' : 'Voce non disponibile'; - const source = snapshot.route?.source ?? (snapshot.mode === 'transit' ? 'MATO / 5T' : 'FOSSGIS / OpenStreetMap'); + const source = snapshot.route?.source ?? (transitMode ? 'MATO / 5T' : 'FOSSGIS / OpenStreetMap'); const landscape = width >= 650 && height < 500; - const panelHeight = Math.min(height * 0.46, Math.max(176, 176 * Math.min(fontScale, 1.5))); + // Landscape: the strip is a side panel on the right, not a bottom occlusion. + const report = () => landscape ? onChromeLayout(banner.current, 0, SIDE_PANEL) : onChromeLayout(banner.current, strip.current, 0); + + // Banner content: the upcoming maneuver while there is one (kept, labelled, while paused). + const maneuver = snapshot.upcomingManeuver; + const showManeuver = !terminal && !searching && (snapshot.status === 'navigating' || snapshot.status === 'off-route' || paused) && !!(maneuver ?? snapshot.instruction); + const glyph = maneuverGlyph(maneuver); + const lines = maneuverLines(maneuver, snapshot.instruction); + const meters = guiding && snapshot.distanceToManeuverMeters != null ? bannerDistance(snapshot.distanceToManeuverMeters) : null; + const then = showManeuver && !paused ? thenManeuver(snapshot) : null; + const status = snapshot.status === 'rerouting' ? 'Ricalcolo del percorso…' : snapshot.status === 'off-route' ? 'Fuori percorso · ricalcolo se prosegui' + : paused ? 'Guida in pausa · Ultima indicazione' : searching ? text.signal : text.precision; + const statusTone = paused || snapshot.status === 'off-route' || (!searching && text.precision) ? 'text-caution' : 'text-secondary'; + const problem = snapshot.problem && !(paused && snapshot.problem.startsWith('location-') && !snapshot.canRetry) ? text.quality : null; + const showRetry = snapshot.canRetry && !confirmation && (!!snapshot.problem || snapshot.status === 'interrupted' || snapshot.status === 'off-route' || text.searching); + const thenText = then ? maneuverLines(then, then.instruction).secondary ?? then.instruction : null; + const bannerLabel = (showManeuver ? `${meters ? `Tra ${meters.label}, ` : ''}${maneuver?.instruction ?? snapshot.instruction ?? ''}` : `${text.header}. ${text.instruction}`) + + (thenText ? `. Poi ${thenText}` : '') + (status ? `. ${status}` : ''); + const voice = snapshot.voice === 'ready' ? { icon: 'volume-high-outline' as const, label: 'Voce attiva. Disattiva la voce' } + : snapshot.voice === 'muted' ? { icon: 'volume-mute-outline' as const, label: 'Voce disattivata. Attiva la voce' } + : snapshot.voice === 'initializing' ? { icon: 'volume-low-outline' as const, label: 'Preparazione della voce' } + : { icon: 'volume-off-outline' as const, label: 'Voce non disponibile: nessuna voce italiana offline' }; + // Formula reserves until the probe measures the real (non-linearly scaled) text heights. + const [measured, setMeasured] = useState<{ scale: number; rows: Omit } | null>(null); + const metrics = measured && measured.scale === fontScale ? { ...bannerMetrics(fontScale), ...measured.rows } : bannerMetrics(fontScale); + const glyphSize = metrics.glyph; + const firstRow = metrics.firstRow; + const stacked = stripLayout(width, fontScale) === 'stacked' && !landscape; + + const summary = ( + setDetailsOpen(true)}> + {arrival ? + {arrival} + + {stacked ? arrivo stimato · senza traffico : <> + arrivo stimato + senza traffico + } + + : {remainingSeconds != null && paused ? 'Stima sospesa' : terminal ? text.header : 'Il tuo viaggio'}} + {!transit && snapshot.distanceRemainingMeters != null && !terminal + ? {remainingSeconds != null ? `${journeyDuration(remainingSeconds)} · ` : ''}{distance(snapshot.distanceRemainingMeters)} + : transit ? {`Tratta ${transit.legIndex + 1} di ${transit.legCount}`} : null} + + ); + const controls = <> + {!terminal && snapshot.sessionId ? : null} + {!terminal ? : null} + + ; + return - - - - {waiting ? : } - {guiding && !transitMode && snapshot.distanceToManeuverMeters != null - ? {distance(snapshot.distanceToManeuverMeters)} - : {text.header}} + { banner.current = event.nativeEvent.layout.height; setBannerHeight(banner.current); report(); }} + style={{ backgroundColor: colors.chrome, ...hairlines.bottom, ...(landscape ? { position: 'absolute', top: 0, left: 0, right: SIDE_PANEL } : {}) }} className="px-4 pb-2 pt-3"> + setMeasured(current => current && current.scale === fontScale + && current.rows.firstRow === rows.firstRow && current.rows.lines === rows.lines && current.rows.thenRow === rows.thenRow ? current : { scale: fontScale, rows })} /> + {/* Every row has a fixed height for the font scale (guidance-layout.ts): no instruction, + status or pause changes the banner height, so the camera anchor never moves. */} + + + {showManeuver ? + : waiting ? + : } + + + {showManeuver ? <> + + {meters ? <>{meters.value} + {meters.unit} : null} + + {/* Street on two lines, or one street line and the action. */} + + {lines.primary} + {lines.secondary ? {lines.secondary} : null} + + : <> + {text.header} + + {text.instruction} + + } - {text.instruction} - - - - - - - - - {searching && text.signal ? {text.signal} - : {!transit && snapshot.distanceRemainingMeters != null ? `${remainingSeconds != null ? journeyDuration(remainingSeconds) + ' · ' : ''}${distance(snapshot.distanceRemainingMeters)}` : transit ? `Tratta ${transit.legIndex + 1} di ${transit.legCount}` : 'Il tuo viaggio'}} - setDetailsOpen(true)} className="min-h-12 min-w-12 items-center justify-center px-2">Dettagli + {/* "Poi …" only; status has its own space below the banner, so neither hides the other. */} + + {then ? <> + Poi + + {thenText} + : null} - - {/* Only about two lines are visible above the actions: precision and warnings come first. */} - {text.precision ? {text.precision} : null} - {!searching && text.signal ? {text.signal} : null} - {text.transitWarning ? : null} - {text.quality} - {paused && snapshot.location && !transitMode ? Ultima posizione accettata: {time(snapshot.location.timestamp)} · ±{distance(snapshot.location.accuracyMeters)} : null} - {!terminal && snapshot.sessionId && !snapshot.notificationGranted ? { void Linking.openSettings(); }} /> : null} - {!terminal && snapshot.sessionId && snapshot.voice === 'unavailable' ? Solo indicazioni visive: nessuna voce italiana offline installata. : null} - {snapshot.problem === 'location-permission' ? : null} - {error ? : null} - {transit ? {transit.line ? `${transit.line} · ` : ''}{transit.timingStatus === 'prediction' ? 'Previsioni' : transit.timingStatus === 'scheduled' ? 'Da orario' : transit.timingStatus === 'cancelled' ? 'Corsa cancellata' : 'Orari non disponibili'} · consultato {time(transit.fetchedAt)}{transitAge >= 2 ? ` · consultato ${transitAge} min fa, da aggiornare` : ''} : null} - {snapshot.mode === 'transit' && (snapshot.problem === 'transit-replan-needed' || transitAge >= 2 || text.transitWarning) ? : null} - {snapshot.status === 'arrived' ? Guida terminata. Verifica l’ingresso sul posto. : null} - {snapshot.status === 'arrived' && snapshot.destinationDistanceMeters != null && snapshot.destinationDistanceMeters > 30 ? La destinazione dista ancora {distance(snapshot.destinationDistanceMeters)} in linea d’aria. : null} - - - - {!terminal && confirmation ? : } - - + + + {/* Status (reduced precision, rerouting, off route, paused, search signal) floats just below the + banner, clear of the attribution control, so it never competes with "Poi" for space and never + changes the layout. */} + {status ? + + {status} + : null} + + + + { strip.current = event.nativeEvent.layout.height; setStripHeight(strip.current); report(); }} + style={[hairlines.top, landscape ? { position: 'absolute', right: 0, top: 0, bottom: 0, width: SIDE_PANEL } : null]} className="bg-surface px-3 pb-2 pt-2"> + {/* One row when the summary has room; otherwise the summary takes its own row above the + controls (guidance-layout.ts), so labels and numbers are never truncated. */} + {stacked ? <>{summary}{controls} + : {summary}{controls}} + + + {/* Above the strip, over the map: a problem or Ricentra never changes the strip height, so the + camera's anchor (and the puck) never jump. It lives in the screen container: Android delivers + no touches to children drawn outside their parent's bounds. */} + + {intent !== 'follow' && snapshot.location ? + + Ricentra + + : null} + {problem || error || showRetry ? + {error ?? problem ?? text.quality} + {showRetry ? : null} + : null} + {!terminal && confirmation ? : null} setDetailsOpen(false)}> - + Dettagli navigazione setDetailsOpen(false)} /> - {transit ? - {transit.line ?? ((transit.phase === 'walk' || transit.phase === 'transfer') ? 'A piedi' : 'Mezzo pubblico')}{transit.headsign ? ` verso ${transit.headsign}` : ''} - {transit.from || transit.to ? {transit.from ?? 'Partenza'} → {transit.to ?? 'Destinazione'} : null} - {transit.timingStatus === 'scheduled' ? 'Orari programmati' : transit.timingStatus === 'prediction' ? 'Previsioni consultate' : transit.timingStatus === 'cancelled' ? 'Corsa cancellata' : 'Stato della corsa non disponibile'}{transit.departureAt ? ` · partenza ${time(transit.departureAt)}` : ''}{transit.arrivalAt ? ` · arrivo ${time(transit.arrivalAt)}` : ''}. Dati consultati {transitAge < 1 ? 'meno di un minuto fa' : `${transitAge} min fa`}. - {transitAge >= 2 ? : null} - {guiding && cues && snapshot.distanceToManeuverMeters != null ? Distanza dal punto da raggiungere in linea d’aria: {distance(snapshot.distanceToManeuverMeters)}. : null} - {transit.proximityAvailable === false ? : null} - {(transit.phase === 'walk' || transit.phase === 'transfer') ? Tratta a piedi senza indicazioni di svolta. : null} - {!terminal && !cues ? : null} - : null} + {text.precision ? {text.precision} : null} + {text.signal ? {text.signal} : null} + {text.transitWarning ? : null} + {transit ? {transit.line ? `${transit.line} · ` : ''}{transit.timingStatus === 'prediction' ? 'Previsioni' : transit.timingStatus === 'scheduled' ? 'Da orario' : transit.timingStatus === 'cancelled' ? 'Corsa cancellata' : 'Orari non disponibili'} · consultato {clock(transit.fetchedAt)}{transitAge >= 2 ? ` · ${transitAge} min fa, da aggiornare` : ''} : null} + {transitMode && (snapshot.problem === 'transit-replan-needed' || transitAge >= 2 || text.transitWarning) ? : null} {snapshot.nextInstruction ? Poi: {snapshot.nextInstruction} : null} - {snapshot.location ? Ultima posizione accettata: {time(snapshot.location.timestamp)} · ±{distance(snapshot.location.accuracyMeters)} : null} + {snapshot.location ? Ultima posizione accettata: {clock(snapshot.location.timestamp)} · ±{distance(snapshot.location.accuracyMeters)} : null} + {snapshot.status === 'arrived' ? Guida terminata. Verifica l’ingresso sul posto. : null} + {snapshot.status === 'arrived' && snapshot.destinationDistanceMeters != null && snapshot.destinationDistanceMeters > 30 ? La destinazione dista ancora {distance(snapshot.destinationDistanceMeters)} in linea d’aria. : null} + {!terminal && snapshot.sessionId && !snapshot.notificationGranted ? { void Linking.openSettings(); }} /> : null} + {snapshot.problem === 'location-permission' ? : null} {!terminal && snapshot.sessionId ? <> - {snapshot.voice === 'ready' ? 'Voce italiana disponibile sul dispositivo.' : snapshot.voice === 'muted' ? 'Voce disattivata.' : snapshot.voice === 'initializing' ? 'Preparazione della voce…' : 'Installa una voce italiana offline per la guida vocale.'} + {snapshot.voice === 'ready' ? 'Voce italiana disponibile sul dispositivo.' : snapshot.voice === 'muted' ? 'Voce disattivata.' : snapshot.voice === 'initializing' ? 'Preparazione della voce…' : 'Solo indicazioni visive: installa una voce italiana offline per la guida vocale.'} {(snapshot.voice === 'ready' || snapshot.voice === 'muted') ? : null} : null} - {source}. {snapshot.mode === 'transit' ? 'La posizione non conferma la presenza a bordo: conferma salita e discesa.' : 'Stime senza traffico in tempo reale.'} {snapshot.route ? `Percorso consultato alle ${time(snapshot.route.fetchedAt)}.` : ''} + {source}. {transitMode ? 'La posizione non conferma la presenza a bordo: conferma salita e discesa.' : 'Orario di arrivo stimato senza traffico in tempo reale.'} {snapshot.route ? `Percorso consultato alle ${clock(snapshot.route.fetchedAt)}.` : ''} La guida può continuare con lo schermo spento finché Android mantiene la sessione attiva. diff --git a/src/features/navigation/TransitFollowPanel.tsx b/src/features/navigation/TransitFollowPanel.tsx index bc6af3c..fefff05 100644 --- a/src/features/navigation/TransitFollowPanel.tsx +++ b/src/features/navigation/TransitFollowPanel.tsx @@ -1,3 +1,4 @@ +import { useRef } from 'react'; import { ActivityIndicator, Linking, ScrollView, useWindowDimensions, View } from 'react-native'; import type { TransitConfirmation } from '../../domain/navigation'; import { navigationLocationForReplan } from '../../domain/navigation'; @@ -21,8 +22,10 @@ export const FOLLOW_ACTIONS_HEIGHT = 80; * Following a transit journey: what to do now, the next boarding with its live provenance, and one * large confirmation beside Stop. Nothing here needs a position fix; GPS distance is advisory only. */ -export function TransitFollowPanel({ state, following, follow, onRecenter, onStop, onRetry, onConfirm, onReplan, onMute }: { +export function TransitFollowPanel({ state, following, follow, onRecenter, onStop, onRetry, onConfirm, onReplan, onMute, onChromeLayout }: { state: NavigationState; following: boolean; + /** Heights of the header and the sheet, so a walking camera anchors the puck between them. */ + onChromeLayout?: (top: number, bottom: number) => void; follow: { leg: RouteLeg | null; stop: Stop | null; board: ReturnType }; onRecenter: () => void; onStop: () => void; onRetry: () => void; onConfirm: (action: TransitConfirmation) => void; onReplan: () => void; /** Mutes or restores spoken announcements of the native session. */ @@ -30,6 +33,8 @@ export function TransitFollowPanel({ state, following, follow, onRecenter, onSto }) { const colors = useThemeColors(); const hairlines = useHairlines(); + const header = useRef(0); + const sheet = useRef(0); const { height, fontScale } = useWindowDimensions(); // Passed/missed times are re-evaluated at least every 15 s, as the native contract requires. const now = useNow(15_000); @@ -47,7 +52,7 @@ export function TransitFollowPanel({ state, following, follow, onRecenter, onSto ? liveBoarding({ leg: follow.leg, rows: follow.board.board?.rows ?? null, boardAvailable: !!follow.stop, loading: follow.board.arrivalsLoading || follow.board.schedules.phase === 'preparing', error: follow.board.arrivalsError, now }) : null; return - + { header.current = event.nativeEvent.layout.height; onChromeLayout?.(header.current, sheet.current); }} style={{ height: headerHeight, backgroundColor: colors.chrome, ...hairlines.bottom }} className="gap-1 px-4 py-3"> {starting ? : null} {model.title} @@ -61,7 +66,7 @@ export function TransitFollowPanel({ state, following, follow, onRecenter, onSto {voice.visible ? : null} - + { sheet.current = event.nativeEvent.layout.height; onChromeLayout?.(header.current, sheet.current); }} style={[{ height: Math.min(height * 0.56, Math.max(300, height - headerHeight - 160)) }, hairlines.top]} className="rounded-t-3xl bg-surface"> {model.warning ? : null} {error ? : null} diff --git a/src/features/navigation/exit-number.ts b/src/features/navigation/exit-number.ts new file mode 100644 index 0000000..0e4768f --- /dev/null +++ b/src/features/navigation/exit-number.ts @@ -0,0 +1,6 @@ +/** + * Exit number size for a glyph box: in proportion to the glyph (about a third), never below 11 sp. + * It is laid out beside the glyph, not over it, so it never collides with neighbouring text at any + * font scale. + */ +export const exitNumberSize = (glyphSize: number) => Math.max(11, Math.round(glyphSize * 0.36)); diff --git a/src/features/navigation/guidance-camera.test.ts b/src/features/navigation/guidance-camera.test.ts new file mode 100644 index 0000000..4ce75c9 --- /dev/null +++ b/src/features/navigation/guidance-camera.test.ts @@ -0,0 +1,221 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { CAMERA_PROFILES, followsClosely, framesManeuver, GuidanceCamera, nextIntent, overviewBounds, type CameraFrame, type CameraInput } from './guidance-camera'; +import { LANDSCAPE, maneuverPoint, PHONE, routeFixture, trajectory, TURIN } from './guidance-fixtures'; +import { inside, paddingForAnchor, principalPoint, project } from './map-projection'; +import { angleDelta, distanceMeters, offsetCoordinate, offsetOfIndex } from './route-measure'; + +const run = (inputs: CameraInput[]) => { const camera = new GuidanceCamera(); return inputs.map(input => camera.update(input)!); }; +const rect = { left: 16, right: PHONE.width - 16, top: PHONE.top + 12, bottom: PHONE.bottom - 12 }; +const size = { width: PHONE.width, height: PHONE.height }; +const anchorOf = (frame: CameraFrame) => project(frame, size, frame.center)!; + +test('padding draws the camera centre at a low anchor under pitch; bottom padding alone would move it up', () => { + for (const pitch of [0, 30, 48]) { + const padding = paddingForAnchor(size, 0.72 * PHONE.height); + const point = project({ center: TURIN, zoom: 17, bearing: 33, pitch, padding }, size, TURIN)!; + assert.ok(Math.abs(point.y - 0.72 * PHONE.height) < 0.01 && Math.abs(point.x - PHONE.width / 2) < 0.01); + const ahead = project({ center: TURIN, zoom: 17, bearing: 0, pitch, padding }, size, offsetCoordinate(TURIN, 0, 50))!; + assert.ok(ahead.y < point.y, 'a point ahead is drawn above the puck'); + } + assert.ok(principalPoint(size, { top: 0, right: 0, bottom: 200, left: 0 }).y < PHONE.height / 2, 'bottom padding raises the centre'); +}); + +test('straight cruise: course-up, steady zoom and the puck on its mode anchor', () => { + const fixture = routeFixture([{ bearing: 20, meters: 900 }]); + for (const [mode, speed] of [['walk', 1.4], ['bicycle', 5], ['car', 12]] as const) { + const frames = run(trajectory(fixture, { mode, speed, seconds: 25 })); + const steady = frames.slice(5); + const profile = CAMERA_PROFILES[mode]; + const target = PHONE.top + profile.anchor * (PHONE.bottom - PHONE.top); + for (const frame of steady) { + assert.ok(Math.abs(angleDelta(frame.bearing, 20)) < 1, `${mode} bearing ${frame.bearing}`); + assert.equal(frame.pitch, profile.pitch); + // ±3% of the unobscured height: here exact, the camera centre is the puck. + assert.ok(Math.abs(anchorOf(frame).y - target) / (PHONE.bottom - PHONE.top) < 0.03); + assert.equal(frame.puck.kind, 'wedge'); + assert.equal(frame.easing, 'linear'); + } + assert.ok(Math.max(...steady.map(f => f.zoom)) - Math.min(...steady.map(f => f.zoom)) < 0.01, `${mode} zoom steady`); + // Lead: none walking; at most one interval (speed × 1 s) for bicycle/car. + for (const frame of steady) assert.ok(frame.leadMeters <= (mode === 'walk' ? 0 : speed + 0.01)); + } +}); + +test('bearing across 359°→1° takes the short way and never orbits', () => { + const fixture = routeFixture([{ bearing: 0, meters: 600 }]); + const courses = [350, 353, 356, 359, 1, 3, 6, 2, 358, 355]; + const frames = run(trajectory(fixture, { mode: 'car', speed: 10, seconds: courses.length, alignment: 'deviating', course: t => courses[t] })); + for (let i = 1; i < frames.length; i += 1) assert.ok(Math.abs(angleDelta(frames[i - 1]!.bearing, frames[i]!.bearing)) < 8); + for (const frame of frames) assert.ok(Math.abs(angleDelta(frame.bearing, 0)) <= 12, `bearing ${frame.bearing}`); +}); + +test('30 s stationary with noisy courses: no orbiting and no zoom pumping', () => { + const fixture = routeFixture([{ bearing: 75, meters: 400 }]); + let seed = 7; + const noise = () => { seed = (seed * 1103515245 + 12345) % 2 ** 31; return seed / 2 ** 31; }; + const inputs = trajectory(fixture, { mode: 'car', speed: 10, seconds: 36, speedAt: t => t < 6 ? 10 : 0.2 * noise(), course: (_, route) => _ < 6 ? route : noise() * 360 }); + // Stopped fixes jitter around one point. + for (const input of inputs.slice(6)) Object.assign(input.fix!, offsetCoordinate(inputs[6]!.fix!, noise() * 360, noise() * 4)); + const frames = run(inputs).slice(7); + assert.ok(frames.every(frame => Math.abs(angleDelta(frames[0]!.bearing, frame.bearing)) < 0.01), 'bearing held'); + assert.ok(Math.max(...frames.map(f => f.zoom)) - Math.min(...frames.map(f => f.zoom)) < 0.06, 'zoom held'); + assert.ok(frames.every(frame => frame.leadMeters === 0), 'no extrapolation while stopped'); +}); + +for (const [mode, speed, window] of [['walk', 1.4, 8], ['bicycle', 5, 10], ['car', 10, 12]] as const) { + test(`${mode}: turn framing starts ${window} s before the turn and shows the junction and outgoing path`, () => { + const fixture = routeFixture([{ bearing: 0, meters: 400 }, { bearing: 90, meters: 300, modifier: 'right' }]); + const inputs = trajectory(fixture, { mode, speed, seconds: Math.ceil(520 / speed) }); + const frames = run(inputs); + const turn = offsetOfIndex(fixture.route, fixture.maneuvers[1]!.geometryIndex); + const first = frames.findIndex(frame => frame.framing?.maneuverId === '1:1'); + assert.ok(first > 0); + const secondsBefore = (turn - inputs[first]!.progress!.traveledMeters) / speed; + assert.ok(secondsBefore <= window + 0.01 && secondsBefore > window - 1 - 0.01, `${mode} framing began ${secondsBefore.toFixed(1)} s before`); + // Once the zoom has settled, the junction and outgoing path are inside the unobscured map. + const framed = frames.slice(first + 2).filter(frame => frame.framing?.maneuverId === '1:1'); + assert.ok(framed.length > 0); + for (const frame of framed) for (const point of frame.framing!.points) assert.ok(inside(project(frame, size, point), rect), `${mode} framed point outside`); + // After the turn: the zoom returns to cruise over 2–3 s, not in one jump. + const after = frames.findIndex((frame, i) => i > first && frame.framing === null); + const cruise = frames[first - 1]!.zoom; + const back = frames.findIndex((frame, i) => i >= after && Math.abs(frame.zoom - cruise) < 0.05); + if (frames[after]!.zoom < cruise - 0.3) assert.ok(back - after >= 2 && back - after <= 4, `${mode} release ${back - after} s`); + }); +} + +test('close turns: both junctions are framed', () => { + const fixture = routeFixture([{ bearing: 0, meters: 300 }, { bearing: 90, meters: 25, modifier: 'right' }, { bearing: 0, meters: 200, modifier: 'left' }]); + const frames = run(trajectory(fixture, { mode: 'car', speed: 9, seconds: 32 })); + const framed = frames.filter(frame => frame.framing?.maneuverId === '1:1'); + assert.ok(framed.length > 0); + const second = maneuverPoint(fixture.maneuvers[2]!); + for (const frame of framed.slice(2)) { + assert.ok(frame.framing!.points.some(point => distanceMeters(point, second) < 1), 'second junction included'); + for (const point of frame.framing!.points) assert.ok(inside(project(frame, size, point), rect)); + } +}); + +test('roundabouts and U-turns are framed; arrival and straight continuations are not', () => { + assert.ok(framesManeuver({ id: 'a', stepIndex: 1, geometryIndex: 1, type: 'roundabout', exit: 2, modifier: 'right', instruction: '' })); + assert.ok(framesManeuver({ id: 'a', stepIndex: 1, geometryIndex: 1, type: 'continue', modifier: 'uturn', instruction: '' })); + assert.ok(!framesManeuver({ id: 'a', stepIndex: 1, geometryIndex: 1, type: 'arrive', instruction: '' })); + assert.ok(!framesManeuver({ id: 'a', stepIndex: 1, geometryIndex: 1, type: 'new name', modifier: 'straight', instruction: '' })); +}); + +test('U-turn: the presentation lead never passes the unconfirmed maneuver', () => { + const fixture = routeFixture([{ bearing: 0, meters: 200 }, { bearing: 180, meters: 200, type: 'continue', modifier: 'uturn' }]); + const inputs = trajectory(fixture, { mode: 'car', speed: 12, seconds: 18 }); + const frames = run(inputs); + const turn = offsetOfIndex(fixture.route, fixture.maneuvers[1]!.geometryIndex); + frames.forEach((frame, i) => { + const traveled = inputs[i]!.progress!.traveledMeters; + if (traveled < turn) assert.ok(traveled + frame.leadMeters <= turn - 3 + 0.01 || frame.leadMeters === 0); + }); +}); + +test('deviation: cycling/driving leave the snapped line; walking always keeps its real offset', () => { + const fixture = routeFixture([{ bearing: 0, meters: 500 }]); + const offRoute = run(trajectory(fixture, { mode: 'car', speed: 10, seconds: 4, lateralMeters: 12, alignment: 'deviating' })); + const aligned = run(trajectory(fixture, { mode: 'car', speed: 10, seconds: 4, lateralMeters: 12 })); + const walking = run(trajectory(fixture, { mode: 'walk', speed: 1.4, seconds: 4, lateralMeters: 6 })); + const inputs = trajectory(fixture, { mode: 'car', speed: 10, seconds: 4, lateralMeters: 12 }); + assert.ok(distanceMeters(offRoute[3]!.puck.coordinate, inputs[3]!.fix!) < 0.01); + assert.ok(distanceMeters(aligned[3]!.puck.coordinate, inputs[3]!.snapped!) < 0.01); + const walkInputs = trajectory(fixture, { mode: 'walk', speed: 1.4, seconds: 4, lateralMeters: 6 }); + assert.ok(distanceMeters(walking[3]!.puck.coordinate, walkInputs[3]!.fix!) < 0.01); +}); + +test('degraded fixes stop extrapolation, hold the camera and show a retained puck', () => { + const fixture = routeFixture([{ bearing: 0, meters: 800 }]); + const inputs = trajectory(fixture, { mode: 'car', speed: 12, seconds: 8 }); + const camera = new GuidanceCamera(); + const frames = inputs.slice(0, 5).map(input => camera.update(input)!); + const live = frames[4]!; + assert.ok(live.leadMeters > 0); + // The same retained fix, now unusable: no camera move, puck subdued at the accepted position. + const degraded = camera.update({ ...inputs[4]!, usable: false })!; + assert.equal(degraded.key, live.key); + assert.equal(degraded.puck.kind, 'retained'); + assert.ok(distanceMeters(degraded.puck.coordinate, inputs[4]!.fix!) < 0.01); + // A late fix after the gap eases in without any lead. + const late = camera.update({ ...inputs[7]!, fix: { ...inputs[7]!.fix!, elapsedMs: inputs[4]!.fix!.elapsedMs! + 9000 } })!; + assert.equal(late.leadMeters, 0); + assert.equal(late.easing, 'ease'); +}); + +test('duplicate timestamps return the same frame; arrival is not framed', () => { + const fixture = routeFixture([{ bearing: 0, meters: 120 }]); + const inputs = trajectory(fixture, { mode: 'walk', speed: 1.4, seconds: 6, startOffset: 110 }); + const camera = new GuidanceCamera(); + const first = camera.update(inputs[0]!); + assert.equal(camera.update({ ...inputs[0]!, fix: { ...inputs[0]!.fix!, latitude: inputs[0]!.fix!.latitude + 0.0001 } }), first); + for (const input of inputs) assert.equal(camera.update(input)!.framing, null); +}); + +test('intent: a gesture enters free, overview and recenter are explicit; recenter is one ~500 ms move', () => { + assert.equal(nextIntent('follow', 'gesture'), 'free'); + assert.equal(nextIntent('overview', 'gesture'), 'free'); + assert.equal(nextIntent('free', 'overview'), 'overview'); + assert.equal(nextIntent('free', 'recenter'), 'follow'); + const fixture = routeFixture([{ bearing: 0, meters: 300 }]); + const camera = new GuidanceCamera(); + const frame = camera.update(trajectory(fixture, { mode: 'walk', speed: 1.4, seconds: 1 })[0]!)!; + const recenter = camera.recenter()!; + assert.notEqual(recenter.key, frame.key); + assert.equal(recenter.durationMs, 500); + assert.deepEqual([recenter.bearing, recenter.pitch, recenter.zoom], [frame.bearing, frame.pitch, frame.zoom]); + const bounds = overviewBounds(fixture.route, 100, TURIN)!; + assert.ok(bounds[0] < bounds[2] && bounds[1] < bounds[3]); +}); + +test('"Poi" appears only when the following maneuver is within about ten seconds of travel', () => { + const near = { id: '1:2', stepIndex: 2, geometryIndex: 4, type: 'turn', instruction: '', afterUpcomingMeters: 25, afterUpcomingSeconds: 18 }; + assert.ok(followsClosely(near, 9), 'by distance at driving speed'); + assert.ok(!followsClosely({ ...near, afterUpcomingMeters: 400, afterUpcomingSeconds: 40 }, 9)); + assert.ok(followsClosely({ ...near, afterUpcomingMeters: 400, afterUpcomingSeconds: 8 }, 9), 'by route time'); + assert.ok(!followsClosely(undefined, 9)); +}); + +test('providers without speed or course: kinematics are derived from consecutive fixes for presentation', () => { + const fixture = routeFixture([{ bearing: 300, meters: 600 }]); + const inputs = trajectory(fixture, { mode: 'car', speed: 10, seconds: 8, alignment: 'deviating' }).map(input => { + const { speedMps: _speed, course: _course, courseAccuracyDegrees: _accuracy, ...fix } = input.fix!; + return { ...input, fix }; + }); + const frames = run(inputs); + assert.equal(frames[0]!.puck.kind, 'dot', 'no direction before a second fix'); + assert.ok(Math.abs(angleDelta(frames[7]!.bearing, 300)) < 1); + assert.ok(frames[7]!.leadMeters > 5, 'derived speed allows the bounded lead'); +}); + +test('stationary replay without platform kinematics: no bearing swings, no lead, no fabricated course (bike and car)', () => { + const fixture = routeFixture([{ bearing: 0, meters: 400 }, { bearing: 90, meters: 200, modifier: 'right' }]); + for (const mode of ['bicycle', 'car'] as const) { + const inputs = trajectory(fixture, { mode, speed: 0, seconds: 30, startOffset: 120, alignment: 'deviating' }).map((input, t) => { + const { speedMps: _speed, course: _course, courseAccuracyDegrees: _accuracy, ...fix } = input.fix!; + return { ...input, fix: { ...fix, ...offsetCoordinate(input.fix!, t % 2 ? 90 : 270, 2) } }; + }); + const frames = run(inputs); + assert.ok(frames.every(frame => frame.bearing === frames[0]!.bearing), `${mode} bearing held`); + assert.ok(frames.every(frame => frame.leadMeters === 0), `${mode} no lead`); + assert.ok(frames.every(frame => frame.puck.kind === 'dot'), `${mode} direction stays unknown`); + } +}); + +test('landscape side panel: the puck is centred in the map left of the panel and turns are framed there', () => { + const fixture = routeFixture([{ bearing: 0, meters: 400 }, { bearing: 90, meters: 300, modifier: 'right' }]); + const view = { width: LANDSCAPE.width, height: LANDSCAPE.height }; + const rectangle = { left: LANDSCAPE.left + 16, right: LANDSCAPE.right - 16, top: LANDSCAPE.top + 12, bottom: LANDSCAPE.bottom - 12 }; + const frames = run(trajectory(fixture, { mode: 'car', speed: 10, seconds: 40, viewport: LANDSCAPE })); + for (const frame of frames.slice(3)) { + const puck = project(frame, view, frame.center)!; + assert.ok(Math.abs(puck.x - (LANDSCAPE.left + LANDSCAPE.right) / 2) < 0.01, `x ${puck.x}`); + assert.ok(puck.x < LANDSCAPE.right, 'never under the side panel'); + assert.equal(frame.anchor.x, (LANDSCAPE.left + LANDSCAPE.right) / 2); + } + const framed = frames.filter(frame => frame.framing).slice(2); + assert.ok(framed.length > 0); + for (const frame of framed) for (const point of frame.framing!.points) assert.ok(inside(project(frame, view, point), rectangle), 'junction inside the map left of the panel'); +}); diff --git a/src/features/navigation/guidance-camera.ts b/src/features/navigation/guidance-camera.ts new file mode 100644 index 0000000..4a8b5e4 --- /dev/null +++ b/src/features/navigation/guidance-camera.ts @@ -0,0 +1,339 @@ +import type { Coordinate } from '../../domain/types'; +import type { FollowingManeuver, GuidanceManeuver, NavigationFix, RouteProgress } from '../../domain/navigation'; +import { inside, paddingForAnchor, project, type CameraPose, type Padding, type ScreenPoint, type VisibleRect } from './map-projection'; +import { MotionEstimator } from './motion-estimator'; +import { angleDelta, distanceMeters, normalizeBearing, offsetCoordinate, offsetOfIndex, pointAt, routeBearingAt, sliceRoute, type RouteMeasure } from './route-measure'; + +export type CameraMode = 'walk' | 'bicycle' | 'car'; + +/** + * Per-mode first-person camera. Values are starting points tuned by replay; see + * docs/development/navigation.md. Zoom is MapLibre zoom (512 px tiles), pitch in degrees, anchor + * is the puck's position as a fraction of the unobscured map height (between banner and strip). + */ +export interface CameraProfile { + pitch: number; + /** Cruise zoom for a smoothed speed (m/s). */ + cruiseZoom: (speed: number) => number; + /** Lowest zoom turn framing may reach. */ + minZoom: number; + anchor: number; + /** Turn framing starts this many seconds before the maneuver. */ + anticipationSeconds: number; + /** Outgoing path framed after the junction (metres). */ + outgoingMeters: number; + /** Below this speed a GPS course is not trusted (m/s). */ + courseSpeed: number; + /** Below this speed the camera holds its bearing (stopped at lights, waiting to cross). */ + holdSpeed: number; + /** Speed used to judge "within N seconds" when the fix reports none. */ + typicalSpeed: number; + /** Presentation-only lead along the route, bounded to one fix interval. */ + extrapolate: boolean; + /** Aim at Ferrostar's snapped position while alignment is credible. */ + snapToRoute: boolean; + routeLookAhead: number; + /** Bearing smoothing per fix (0..1) and dead band (degrees). */ + bearingGain: number; + bearingDeadBand: number; +} + +const lerp = (a: number, b: number, t: number) => a + (b - a) * Math.min(1, Math.max(0, t)); +export const CAMERA_PROFILES: Record = { + walk: { + pitch: 34, cruiseZoom: () => 18.3, minZoom: 16.9, anchor: 0.67, anticipationSeconds: 8, outgoingMeters: 30, + courseSpeed: 0.8, holdSpeed: 0.35, typicalSpeed: 1.3, extrapolate: false, snapToRoute: false, routeLookAhead: 20, + bearingGain: 0.5, bearingDeadBand: 4, + }, + bicycle: { + pitch: 42, cruiseZoom: speed => lerp(18, 17.1, (speed - 3) / 5), minZoom: 16.6, anchor: 0.715, anticipationSeconds: 10, + outgoingMeters: 45, courseSpeed: 1.6, holdSpeed: 0.8, typicalSpeed: 4.5, extrapolate: true, snapToRoute: true, + routeLookAhead: 25, bearingGain: 0.62, bearingDeadBand: 3, + }, + car: { + pitch: 48, cruiseZoom: speed => lerp(17.7, 15.7, (speed - 6) / 19), minZoom: 15.4, anchor: 0.735, anticipationSeconds: 12, + outgoingMeters: 70, courseSpeed: 2.5, holdSpeed: 1.2, typicalSpeed: 9, extrapolate: true, snapToRoute: true, + routeLookAhead: 35, bearingGain: 0.7, bearingDeadBand: 2.5, + }, +}; + +/** + * The unobscured map inside the map view (screen points): below the maneuver banner, above the + * bottom strip and, in landscape, left of the side panel (`right` < `width`). + */ +export interface GuidanceViewport { width: number; height: number; top: number; bottom: number; left: number; right: number } + +export interface CameraInput { + mode: CameraMode; + fix?: NavigationFix; + /** A current accepted fix (not degraded, stale or paused). */ + usable: boolean; + route: RouteMeasure | null; + routeRevision?: number; + progress?: RouteProgress; + alignment?: 'aligned' | 'deviating' | 'unknown'; + snapped?: Coordinate; + upcoming?: GuidanceManeuver; + following?: FollowingManeuver; + distanceToManeuverMeters?: number; + viewport: GuidanceViewport; + /** Transit walks: walking camera on the supplied trace, never turn framing. */ + traceOnly?: boolean; +} + +export type PuckKind = 'wedge' | 'dot' | 'retained'; +export interface CameraFrame { + /** Identity of the fix this frame answers; equal keys mean "no new move". */ + key: string; + center: Coordinate; + bearing: number; + pitch: number; + zoom: number; + padding: Padding; + durationMs: number; + easing: 'linear' | 'ease'; + /** Screen point where the camera centre (and the follow puck) is drawn. */ + anchor: ScreenPoint; + puck: { coordinate: Coordinate; heading: number | null; kind: PuckKind }; + /** Junction + outgoing points the frame must show, for screen assertions. */ + framing: { maneuverId: string; points: Coordinate[] } | null; + /** Lead added ahead of the accepted fix (presentation only, metres). */ + leadMeters: number; +} + +const median = (values: number[]) => { const sorted = [...values].sort((a, b) => a - b); return sorted[Math.floor(sorted.length / 2)] ?? 1000; }; +const TURN_FREE_TYPES = new Set(['arrive', 'depart']); +const STRAIGHT_TYPES = new Set(['continue', 'new name', 'notification', 'use lane']); +/** Whether a maneuver changes direction enough to deserve framing. */ +export function framesManeuver(maneuver: GuidanceManeuver | undefined): boolean { + if (!maneuver || TURN_FREE_TYPES.has(maneuver.type)) return false; + return !(STRAIGHT_TYPES.has(maneuver.type) && (maneuver.modifier === undefined || maneuver.modifier === 'straight')); +} + +/** Whether the following maneuver comes within about ten seconds of travel after the upcoming one. */ +export function followsClosely(following: FollowingManeuver | undefined, typicalSpeed: number, seconds = 10): boolean { + if (!following) return false; + const byTime = following.afterUpcomingSeconds > 0 ? following.afterUpcomingSeconds : Infinity; + const byDistance = following.afterUpcomingMeters / Math.max(0.5, typicalSpeed); + return Math.min(byTime, byDistance) <= seconds; +} + +/** + * Stateful first-person camera planner, fed only by accepted native navigation state. One frame + * per distinct fix (duplicate timestamps return the previous frame); the map animates linearly + * to it over one fix interval, so puck and camera share one clock and React renders at 1 Hz. + */ +export class GuidanceCamera { + private frame: CameraFrame | null = null; + private lastFixMs: number | null = null; + private intervals: number[] = []; + private bearing: number | null = null; + private bearingTrusted = false; + /** Converging after leaving the dead band; stops once within half a degree (no residual tilt). */ + private rotating = false; + private zoom: number | null = null; + private cruise: number | null = null; + private speed = 0; + private latchedManeuver: string | null = null; + private mode: CameraMode | null = null; + private viewportKey = ''; + private recenters = 0; + private motion = new MotionEstimator(); + + get current() { return this.frame; } + get expectedIntervalMs() { return this.intervals.length ? Math.min(2000, Math.max(600, median(this.intervals))) : 1000; } + + /** A one-off ~500 ms transition back to the follow pose (Ricentra). */ + recenter(): CameraFrame | null { + if (!this.frame) return null; + this.recenters += 1; + this.frame = { ...this.frame, key: `${this.frame.key}#r${this.recenters}`, durationMs: 500, easing: 'ease' }; + return this.frame; + } + + /** + * Some providers omit speed and course. For presentation only, an accuracy-aware estimator + * derives them from accepted fixes; stationary jitter yields neither (see MotionEstimator). + */ + private withKinematics(fix: NavigationFix): NavigationFix { + if (fix.speedMps !== undefined && fix.course !== undefined) return fix; + const motion = this.motion.update({ latitude: fix.latitude, longitude: fix.longitude }, fix.elapsedMs ?? fix.timestamp, fix.accuracyMeters); + return { + ...fix, + ...(fix.speedMps === undefined ? { speedMps: motion.speedMps } : {}), + ...(fix.course === undefined && motion.course !== undefined ? { course: motion.course, courseAccuracyDegrees: motion.courseAccuracyDegrees } : {}), + }; + } + + update(input: CameraInput): CameraFrame | null { + const profile = CAMERA_PROFILES[input.mode]; + if (!input.fix) return this.frame; + const fix = this.withKinematics(input.fix); + const fixMs = fix.elapsedMs ?? fix.timestamp; + const { viewport } = input; + const viewportKey = `${viewport.width}x${viewport.height}:${viewport.top}:${viewport.bottom}:${viewport.left}:${viewport.right}`; + const modeChanged = this.mode !== input.mode; + const layoutChanged = viewportKey !== this.viewportKey; + // Duplicate or re-delivered samples (GPS + fused, a re-published snapshot) never move the camera. + if (this.frame && fixMs === this.lastFixMs && !modeChanged && !layoutChanged) { + const wasUsable = this.frame.puck.kind !== 'retained'; + if (wasUsable === input.usable) return this.frame; + // Usability changed without a new fix: the camera holds still (no lead is taken back); only + // the puck changes, drawn at the last accepted position. + const coordinate = { latitude: fix.latitude, longitude: fix.longitude }; + this.frame = { ...this.frame, puck: { ...this.frame.puck, coordinate, kind: !input.usable ? 'retained' : this.bearingTrusted ? 'wedge' : 'dot' } }; + return this.frame; + } + if (modeChanged) { this.mode = input.mode; this.cruise = null; this.zoom = null; } + this.viewportKey = viewportKey; + + let gapMs = 0; + if (this.lastFixMs !== null && fixMs > this.lastFixMs) { + gapMs = fixMs - this.lastFixMs; + if (gapMs <= 3000) { this.intervals.push(gapMs); if (this.intervals.length > 5) this.intervals.shift(); } + } + const fresh = this.lastFixMs === null || fixMs !== this.lastFixMs; + this.lastFixMs = fixMs; + const interval = this.expectedIntervalMs; + // A first fix, a fix after a long gap or a layout change eases instead of gliding. + const recovering = this.frame === null || gapMs > 2.5 * interval || layoutChanged || modeChanged; + + if (fresh && fix.speedMps !== undefined) this.speed = this.speed * 0.6 + fix.speedMps * 0.4; + const speed = fix.speedMps ?? this.speed; + const route = input.route; + const traveled = input.progress?.traveledMeters; + const aligned = input.alignment === 'aligned' && route !== null && traveled !== undefined; + const maneuverOffset = route && input.upcoming ? offsetOfIndex(route, input.upcoming.geometryIndex) : undefined; + + // Position: route-snapped only for cycling/driving while alignment is credible. + const useSnapped = profile.snapToRoute && aligned && input.snapped !== undefined + && distanceMeters(input.snapped, fix) <= Math.max(15, fix.accuracyMeters); + const base: Coordinate = useSnapped ? input.snapped! : { latitude: fix.latitude, longitude: fix.longitude }; + + // Course-up bearing, circularly filtered; held when slow or untrustworthy. + const moving = fix.speedMps === undefined ? true : fix.speedMps >= profile.holdSpeed; + if (!moving) this.rotating = false; + const courseOk = fix.course !== undefined && (fix.speedMps ?? 0) >= profile.courseSpeed + && (fix.courseAccuracyDegrees === undefined || fix.courseAccuracyDegrees <= 35); + let target: number | null = null; + if (input.usable && moving) { + const routeBearing = aligned && !input.traceOnly + ? routeBearingAt(route!, traveled!, profile.routeLookAhead, maneuverOffset ?? Infinity) : null; + if (routeBearing !== null && courseOk && Math.abs(angleDelta(routeBearing, fix.course!)) > 45) target = fix.course!; + else target = routeBearing ?? (courseOk ? fix.course! : null); + } + if (target !== null) { + if (this.bearing === null) this.bearing = target; + else { + const delta = angleDelta(normalizeBearing(this.bearing), target); + if (Math.abs(delta) > profile.bearingDeadBand) this.rotating = true; + else if (Math.abs(delta) < 0.5) this.rotating = false; + if (this.rotating) this.bearing += delta * (recovering ? 1 : profile.bearingGain); + } + this.bearingTrusted = true; + } + const bearing = this.bearing ?? 0; + + // Presentation-only lead: bounded to one interval, never through the upcoming maneuver, + // never on a degraded, recovering or late fix. It never feeds navigation state. + let center = base; + let lead = 0; + if (profile.extrapolate && input.usable && !recovering && !input.traceOnly && speed >= profile.courseSpeed) { + lead = Math.min(30, speed * interval / 1000); + if (useSnapped && route && traveled !== undefined) { + if (maneuverOffset !== undefined) lead = Math.max(0, Math.min(lead, maneuverOffset - traveled - 3)); + center = pointAt(route, traveled + lead); + } else if (courseOk) center = offsetCoordinate(base, fix.course!, lead); + else lead = 0; + } + + // Zoom: speed-aware cruise with hysteresis; turn framing pulls it out, release eases it back. + const cruiseNow = profile.cruiseZoom(this.speed); + if (this.cruise === null || Math.abs(cruiseNow - this.cruise) >= 0.3) this.cruise = cruiseNow; + const anchorY = viewport.top + profile.anchor * Math.max(0, viewport.bottom - viewport.top); + const anchorX = (viewport.left + viewport.right) / 2; + const padding = paddingForAnchor(viewport, anchorY, anchorX); + const size = { width: viewport.width, height: viewport.height }; + const rect: VisibleRect = { left: viewport.left + 16, right: viewport.right - 16, top: viewport.top + 12, bottom: viewport.bottom - 12 }; + + let framing: CameraFrame['framing'] = null; + let targetZoom = this.cruise; + const upcoming = input.upcoming; + if (upcoming && input.usable && !input.traceOnly && route && maneuverOffset !== undefined && traveled !== undefined && framesManeuver(upcoming)) { + const toManeuver = input.distanceToManeuverMeters ?? Math.max(0, maneuverOffset - traveled); + const seconds = toManeuver / Math.max(speed, profile.courseSpeed); + if (this.latchedManeuver !== upcoming.id && seconds <= profile.anticipationSeconds) this.latchedManeuver = upcoming.id; + if (this.latchedManeuver === upcoming.id) { + const points = sample(sliceRoute(route, maneuverOffset, maneuverOffset + profile.outgoingMeters), 8); + const following = input.following; + if (following && followsClosely(following, profile.typicalSpeed)) { + const followingOffset = offsetOfIndex(route, following.geometryIndex); + points.push(...sample(sliceRoute(route, followingOffset, followingOffset + profile.outgoingMeters * 0.6), 6)); + } + framing = { maneuverId: upcoming.id, points }; + targetZoom = solveZoom({ center, bearing: normalizeBearing(bearing), pitch: profile.pitch, padding, zoom: this.cruise }, size, rect, points, profile.minZoom); + } + } + if (this.zoom === null || recovering) this.zoom = targetZoom; + else { + const seconds = Math.max(0.5, Math.min(2, interval / 1000)); + const delta = targetZoom - this.zoom; + // Zoom out quickly enough to show the junction; ease back in over 2–3 s after the turn. + const limit = (delta < 0 ? 1.1 : 0.45) * seconds; + if (Math.abs(delta) >= 0.05) this.zoom += Math.max(-limit, Math.min(limit, delta)); + } + + const kind: PuckKind = !input.usable ? 'retained' : this.bearingTrusted ? 'wedge' : 'dot'; + this.frame = { + key: `${fixMs}:${input.routeRevision ?? 0}:${input.mode}:${viewportKey}:${input.usable ? 1 : 0}`, + center, bearing: normalizeBearing(bearing), pitch: profile.pitch, zoom: round(this.zoom, 3), padding, + durationMs: recovering ? 500 : interval, easing: recovering ? 'ease' : 'linear', + anchor: { x: anchorX, y: anchorY }, + puck: { coordinate: base, heading: this.bearingTrusted ? normalizeBearing(bearing) : null, kind }, + framing, leadMeters: round(lead, 1), + }; + return this.frame; + } +} + +const round = (value: number, digits: number) => Math.round(value * 10 ** digits) / 10 ** digits; +/** At most `count` evenly spread points (always including both ends). */ +function sample(points: Coordinate[], count: number): Coordinate[] { + if (points.length <= count) return [...points]; + return Array.from({ length: count }, (_, i) => points[Math.round(i * (points.length - 1) / (count - 1))]!); +} + +/** Largest zoom (≤ pose.zoom, ≥ minZoom) at which every point projects inside `rect`. */ +export function solveZoom(pose: CameraPose, size: { width: number; height: number }, rect: VisibleRect, points: Coordinate[], minZoom: number): number { + for (let zoom = pose.zoom; zoom >= minZoom; zoom -= 0.1) { + const candidate = { ...pose, zoom }; + if (points.every(point => inside(project(candidate, size, point), rect))) return round(zoom, 2); + } + return minZoom; +} + +/** Overview: the remaining route, north-up and flat, framed once. */ +export function overviewBounds(route: RouteMeasure, traveled: number, position?: Coordinate): [number, number, number, number] | null { + const points = sliceRoute(route, traveled, route.length); + if (position) points.push(position); + if (points.length === 0) return null; + let [west, south, east, north] = [Infinity, Infinity, -Infinity, -Infinity]; + for (const point of points) { + west = Math.min(west, point.longitude); east = Math.max(east, point.longitude); + south = Math.min(south, point.latitude); north = Math.max(north, point.latitude); + } + const pad = 0.0004; + return [west - pad, south - pad, east + pad, north + pad]; +} + +/** Follow / free / overview. Gestures enter free at gesture start; fixes and reroutes never leave it. */ +export type CameraIntent = 'follow' | 'free' | 'overview'; +export type CameraIntentEvent = 'gesture' | 'recenter' | 'overview' | 'reset'; +export function nextIntent(current: CameraIntent, event: CameraIntentEvent): CameraIntent { + switch (event) { + case 'gesture': return 'free'; + case 'overview': return 'overview'; + case 'recenter': case 'reset': return 'follow'; + } + return current; +} diff --git a/src/features/navigation/guidance-commands.test.ts b/src/features/navigation/guidance-commands.test.ts new file mode 100644 index 0000000..1a61291 --- /dev/null +++ b/src/features/navigation/guidance-commands.test.ts @@ -0,0 +1,35 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { legFitKey, pendingGuidanceCommand, type GuidanceFit, type IssuedCommands } from './guidance-commands'; +import { GuidanceCamera } from './guidance-camera'; +import { routeFixture, trajectory } from './guidance-fixtures'; + +const padding = { top: 0, right: 0, bottom: 0, left: 0 }; +const leg = (recenter: number): GuidanceFit => ({ key: legFitKey('s1', '2', recenter), bounds: [7.6, 45, 7.7, 45.1], padding }); +const none: IssuedCommands = { frame: null, overview: null, fit: null }; + +test('transit ride: the leg is fitted once, a pan blocks it, and Ricentra fits it again', () => { + const first = pendingGuidanceCommand({ intent: 'follow', frame: null, overview: null, fit: leg(0), gesture: false }, none); + assert.equal(first?.kind, 'fit'); + const issued = { ...none, fit: first!.key }; + assert.equal(pendingGuidanceCommand({ intent: 'follow', frame: null, overview: null, fit: leg(0), gesture: false }, issued), null, 'once per leg'); + assert.equal(pendingGuidanceCommand({ intent: 'free', frame: null, overview: null, fit: leg(0), gesture: true }, issued), null, 'free issues nothing'); + // Ricentra: follow again with the recenter counter in the fit identity. + const again = pendingGuidanceCommand({ intent: 'follow', frame: null, overview: null, fit: leg(1), gesture: false }, issued); + assert.deepEqual([again?.kind, again?.key], ['fit', 'leg:s1:2:1']); +}); + +test('road follow issues each frame once, Ricentra frames anew, overview once per request', () => { + const camera = new GuidanceCamera(); + const frame = camera.update(trajectory(routeFixture([{ bearing: 0, meters: 300 }]), { mode: 'car', speed: 10, seconds: 1 })[0]!)!; + const command = pendingGuidanceCommand({ intent: 'follow', frame, overview: null, fit: null, gesture: false }, none); + assert.equal(command?.kind, 'frame'); + const issued = { ...none, frame: frame.key }; + assert.equal(pendingGuidanceCommand({ intent: 'follow', frame, overview: null, fit: null, gesture: false }, issued), null); + assert.equal(pendingGuidanceCommand({ intent: 'follow', frame, overview: null, fit: null, gesture: true }, none), null, 'a gesture blocks pending moves'); + const recentred = camera.recenter()!; + assert.equal(pendingGuidanceCommand({ intent: 'follow', frame: recentred, overview: null, fit: null, gesture: false }, issued)?.kind, 'frame'); + const overview: GuidanceFit = { key: 'overview:1', bounds: [7.6, 45, 7.7, 45.1], padding }; + assert.equal(pendingGuidanceCommand({ intent: 'overview', frame, overview, fit: null, gesture: false }, issued)?.kind, 'overview'); + assert.equal(pendingGuidanceCommand({ intent: 'overview', frame, overview, fit: null, gesture: false }, { ...issued, overview: 'overview:1' }), null); +}); diff --git a/src/features/navigation/guidance-commands.ts b/src/features/navigation/guidance-commands.ts new file mode 100644 index 0000000..cfdd75c --- /dev/null +++ b/src/features/navigation/guidance-commands.ts @@ -0,0 +1,28 @@ +import type { CameraFrame, CameraIntent } from './guidance-camera'; +import type { Padding } from './map-projection'; + +export interface GuidanceFit { key: string; bounds: [number, number, number, number]; padding: Padding } +export interface IssuedCommands { frame: string | null; overview: string | null; fit: string | null } +export type GuidanceCommand = + | { kind: 'frame'; key: string; frame: CameraFrame } + | { kind: 'overview' | 'fit'; key: string; fit: GuidanceFit }; + +/** + * The one camera command guidance should issue now, if any: the follow frame (road or transit + * walking), otherwise the transit leg fit while following, or the overview once per request. Free + * issues nothing, and neither does a gesture still in progress. A key is issued at most once; an + * explicit Ricentra changes the follow frame key and the leg fit key, so it always moves the map. + */ +export function pendingGuidanceCommand(state: { + intent: CameraIntent; frame: CameraFrame | null; overview: GuidanceFit | null; fit: GuidanceFit | null; gesture: boolean; +}, issued: IssuedCommands): GuidanceCommand | null { + if (state.intent === 'overview') { + return state.overview && issued.overview !== state.overview.key ? { kind: 'overview', key: state.overview.key, fit: state.overview } : null; + } + if (state.intent !== 'follow' || state.gesture) return null; + if (state.frame) return issued.frame !== state.frame.key ? { kind: 'frame', key: state.frame.key, frame: state.frame } : null; + return state.fit && issued.fit !== state.fit.key ? { kind: 'fit', key: state.fit.key, fit: state.fit } : null; +} + +/** Leg fit identity: one per leg, and again after every explicit recenter request. */ +export const legFitKey = (sessionId: string | null, legKey: string, recenter: number) => `leg:${sessionId}:${legKey}:${recenter}`; diff --git a/src/features/navigation/guidance-fixtures.ts b/src/features/navigation/guidance-fixtures.ts new file mode 100644 index 0000000..2e16401 --- /dev/null +++ b/src/features/navigation/guidance-fixtures.ts @@ -0,0 +1,83 @@ +import type { Coordinate } from '../../domain/types'; +import type { FollowingManeuver, GuidanceManeuver, NavigationFix } from '../../domain/navigation'; +import { bearingDegrees, measureRoute, offsetCoordinate, offsetOfIndex, pointAt, type RouteMeasure } from './route-measure'; +import type { CameraInput, CameraMode, GuidanceViewport } from './guidance-camera'; + +/** + * Deterministic route fixtures for camera and banner tests: a polyline built from (bearing, metres) + * legs in 5 m points, with one maneuver at each leg start, and a 1 Hz trajectory generator. + */ +export const TURIN: Coordinate = { latitude: 45.0703, longitude: 7.6869 }; +export const PHONE: GuidanceViewport = { width: 412, height: 860, top: 150, bottom: 780, left: 0, right: 412 }; +/** Landscape: banner over the left part, a 320 dp side panel on the right, no bottom strip. */ +export const LANDSCAPE: GuidanceViewport = { width: 915, height: 380, top: 120, bottom: 380, left: 0, right: 595 }; + +/** A fixture maneuver's point (fixtures always carry coordinates). */ +export const maneuverPoint = (m: GuidanceManeuver): Coordinate => ({ latitude: m.latitude!, longitude: m.longitude! }); + +export interface FixtureLeg { bearing: number; meters: number; type?: string; modifier?: GuidanceManeuver['modifier']; exit?: number } +export interface RouteFixture { route: RouteMeasure; maneuvers: GuidanceManeuver[] } + +export function routeFixture(legs: FixtureLeg[], revision = 1): RouteFixture { + const points: Coordinate[] = [TURIN]; + const starts: number[] = []; + for (const leg of legs) { + starts.push(points.length - 1); + const count = Math.max(1, Math.round(leg.meters / 5)); + for (let i = 0; i < count; i += 1) points.push(offsetCoordinate(points[points.length - 1]!, leg.bearing, leg.meters / count)); + } + const route = measureRoute(points); + const maneuvers: GuidanceManeuver[] = legs.map((leg, k) => ({ + id: `${revision}:${k}`, stepIndex: k, geometryIndex: starts[k]!, type: k === 0 ? 'depart' : leg.type ?? 'turn', + ...(leg.modifier ? { modifier: leg.modifier } : {}), ...(leg.exit ? { exit: leg.exit } : {}), + instruction: `Passo ${k}`, ...pointAt(route, offsetOfIndex(route, starts[k]!)), + })); + maneuvers.push({ id: `${revision}:${legs.length}`, stepIndex: legs.length, geometryIndex: points.length - 1, type: 'arrive', instruction: 'Arrivo', ...points[points.length - 1]! }); + return { route, maneuvers }; +} + +/** Upcoming/following maneuvers and distance at a route offset, like the native snapshot. */ +export function guidanceAt(fixture: RouteFixture, traveled: number, speed: number) { + const offsets = fixture.maneuvers.map(m => offsetOfIndex(fixture.route, m.geometryIndex)); + // Ferrostar advances once the maneuver point is passed. + const upcomingIndex = offsets.findIndex((offset, k) => k > 0 && offset > traveled + 0.5); + const index = upcomingIndex < 0 ? fixture.maneuvers.length - 1 : upcomingIndex; + const upcoming = fixture.maneuvers[index]; + const next = fixture.maneuvers[index + 1]; + const following: FollowingManeuver | undefined = next ? { + ...next, afterUpcomingMeters: offsets[index + 1]! - offsets[index]!, afterUpcomingSeconds: (offsets[index + 1]! - offsets[index]!) / Math.max(0.5, speed), + } : undefined; + return { upcoming, following, distanceToManeuverMeters: Math.max(0, offsets[index]! - traveled) }; +} + +export interface TrajectoryOptions { + mode: CameraMode; speed: number; seconds: number; startOffset?: number; lateralMeters?: number; + accuracy?: number; course?: (t: number, routeBearing: number) => number | undefined; speedAt?: (t: number) => number; + alignment?: CameraInput['alignment']; usable?: (t: number) => boolean; viewport?: GuidanceViewport; +} + +/** 1 Hz camera inputs along a fixture route. */ +export function trajectory(fixture: RouteFixture, options: TrajectoryOptions): CameraInput[] { + const inputs: CameraInput[] = []; + let traveled = options.startOffset ?? 0; + for (let t = 0; t < options.seconds; t += 1) { + const speed = options.speedAt ? options.speedAt(t) : options.speed; + const position = pointAt(fixture.route, traveled); + const ahead = pointAt(fixture.route, Math.min(fixture.route.length, traveled + 3)); + const routeBearing = bearingDegrees(position, ahead); + const raw = options.lateralMeters ? offsetCoordinate(position, routeBearing + 90, options.lateralMeters) : position; + const course = options.course ? options.course(t, routeBearing) : speed >= 1 ? routeBearing : undefined; + const fix: NavigationFix = { + ...raw, accuracyMeters: options.accuracy ?? 5, timestamp: 1_800_000_000_000 + t * 1000, elapsedMs: 10_000 + t * 1000, speedMps: speed, + ...(course !== undefined ? { course: (course + 360) % 360, courseAccuracyDegrees: 8 } : {}), + }; + inputs.push({ + mode: options.mode, fix, usable: options.usable ? options.usable(t) : true, route: fixture.route, routeRevision: 1, + progress: { traveledMeters: traveled, routeLengthMeters: fixture.route.length, segmentIndex: 0, stepIndex: 0 }, + alignment: options.alignment ?? 'aligned', snapped: position, viewport: options.viewport ?? PHONE, + ...guidanceAt(fixture, traveled, speed), + }); + traveled = Math.min(fixture.route.length, traveled + speed); + } + return inputs; +} diff --git a/src/features/navigation/guidance-layout.test.ts b/src/features/navigation/guidance-layout.test.ts new file mode 100644 index 0000000..4b52715 --- /dev/null +++ b/src/features/navigation/guidance-layout.test.ts @@ -0,0 +1,22 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { bannerMetrics, MAX_FONT_SCALE, stripLayout } from './guidance-layout'; + +test('banner reserves cover the tallest text state at every font scale up to the cap', () => { + for (const scale of [1, 1.15, 1.3, 1.5, 1.8, 2, 2.5]) { + const effective = Math.min(scale, MAX_FONT_SCALE); + const metrics = bannerMetrics(scale); + assert.ok(metrics.lines >= (2 * 28) * effective, 'two street lines'); + assert.ok(metrics.lines >= (28 + 24) * effective, 'one street line plus the action'); + assert.ok(metrics.firstRow >= 42 * 1.15 * effective, 'the distance line'); + assert.ok(metrics.thenRow >= 22, 'the Poi glyph fits'); + } + assert.deepEqual(bannerMetrics(2.5), bannerMetrics(2), 'text is capped, so are the reserves'); +}); + +test('the strip stacks on narrow screens and with large text', () => { + assert.equal(stripLayout(412, 1), 'row'); + assert.equal(stripLayout(360, 1), 'stacked'); + assert.equal(stripLayout(412, 1.3), 'stacked'); + assert.equal(stripLayout(915, 1.3), 'row'); +}); diff --git a/src/features/navigation/guidance-layout.ts b/src/features/navigation/guidance-layout.ts new file mode 100644 index 0000000..99fb5e4 --- /dev/null +++ b/src/features/navigation/guidance-layout.ts @@ -0,0 +1,39 @@ +/** + * Fixed guidance chrome geometry. Every banner row has a height that depends only on the font + * scale, so no instruction, status or pause changes the banner height (and with it the camera + * anchor). Text in the banner is capped at `MAX_FONT_SCALE`. These linear reserves are an upper + * bound used until `BannerReserveProbe` measures the real heights (Android scales large text + * non-linearly, so measured rows are usually smaller). + */ +export const MAX_FONT_SCALE = 2; + +export interface BannerMetrics { + /** Glyph box (dp). */ + glyph: number; + /** Distance line: 42 sp heavy, line height 1.15. */ + firstRow: number; + /** Street (28 dp lines) and action (24 dp): two street lines, or one street line plus the action. */ + lines: number; + /** The "Poi …" row. */ + thenRow: number; +} + +export function bannerMetrics(fontScale: number): BannerMetrics { + const scale = Math.max(1, Math.min(MAX_FONT_SCALE, Number.isFinite(fontScale) ? fontScale : 1)); + return { + glyph: Math.round(44 * Math.min(scale, 1.3)), + firstRow: Math.ceil(42 * 1.15 * scale), + lines: Math.ceil(Math.max(2 * 28, 28 + 24, 2 * 24) * scale), + thenRow: Math.ceil(26 * scale), + }; +} + +/** + * Bottom strip: one row (summary, voice, overview, Interrompi) when the summary has room for + * "arrivo stimato / senza traffico" and the remaining time and distance; otherwise the summary + * takes a full row above the controls, so no label or number is truncated. + */ +export function stripLayout(width: number, fontScale: number): 'row' | 'stacked' { + const scale = Math.max(1, Number.isFinite(fontScale) ? fontScale : 1); + return width >= 400 * scale ? 'row' : 'stacked'; +} diff --git a/src/features/navigation/guidance-route.test.ts b/src/features/navigation/guidance-route.test.ts new file mode 100644 index 0000000..d78c9c2 --- /dev/null +++ b/src/features/navigation/guidance-route.test.ts @@ -0,0 +1,39 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { maneuverArrow, remainingGradient, traveledFraction } from './guidance-route'; +import { routeFixture } from './guidance-fixtures'; +import { angleDelta, bearingDegrees, distanceMeters } from './route-measure'; + +const fixture = routeFixture([{ bearing: 0, meters: 200 }, { bearing: 90, meters: 150, modifier: 'right' }, { bearing: 0, meters: 100, modifier: 'left' }]); + +test('travelled fraction uses the native progress on the same geometry, clamped', () => { + const at = (traveledMeters: number) => traveledFraction(fixture.route, { traveledMeters, routeLengthMeters: 450, segmentIndex: 0, stepIndex: 0 }); + assert.ok(Math.abs(at(225) - 0.5) < 0.002); + assert.equal(at(-3), 0); + assert.equal(at(9999), 1); + assert.equal(traveledFraction(null, undefined), 0); +}); + +test('the remaining gradient is transparent before the cut and the route colour after it', () => { + assert.deepEqual(remainingGradient('#000', 0), ['interpolate', ['linear'], ['line-progress'], 0, '#000', 1, '#000']); + const cut = remainingGradient('#000', 0.25); + assert.deepEqual(cut.slice(3), [0, 'rgba(0,0,0,0)', 0.25, 'rgba(0,0,0,0)', 0.250001, '#000', 1, '#000']); + const stops = cut.slice(3).filter((_, i) => i % 2 === 0) as number[]; + assert.ok(stops.every((stop, i) => i === 0 || stop > stops[i - 1]!), 'stops strictly increase'); +}); + +test('one arrow through the junction: real incoming and outgoing geometry, head along the exit', () => { + const turn = fixture.maneuvers[1]!; + for (const mode of ['walk', 'bicycle', 'car'] as const) { + const arrow = maneuverArrow(fixture.route, turn, mode, 100)!; + const corner = { latitude: turn.latitude!, longitude: turn.longitude! }; + assert.ok(arrow.shaft.some(([longitude, latitude]) => distanceMeters({ latitude, longitude }, corner) < 0.5), `${mode} passes the corner`); + assert.ok(Math.abs(angleDelta(arrow.head.bearing, 90)) < 1, `${mode} head points along the exit`); + } + // Close to the turn the shaft never extends behind the current position. + const near = maneuverArrow(fixture.route, turn, 'car', 195)!; + const [lon, lat] = near.shaft[0]!; + assert.ok(Math.abs(bearingDegrees({ latitude: lat, longitude: lon }, { latitude: turn.latitude!, longitude: turn.longitude! })) < 1, 'starts on the incoming leg'); + assert.ok(distanceMeters({ latitude: lat, longitude: lon }, { latitude: turn.latitude!, longitude: turn.longitude! }) < 5.5); + assert.equal(maneuverArrow(fixture.route, fixture.maneuvers[3], 'car', 440), null, 'no arrow for arrival'); +}); diff --git a/src/features/navigation/guidance-route.ts b/src/features/navigation/guidance-route.ts new file mode 100644 index 0000000..77996e4 --- /dev/null +++ b/src/features/navigation/guidance-route.ts @@ -0,0 +1,51 @@ +import type { GuidanceManeuver, RouteProgress } from '../../domain/navigation'; +import { framesManeuver, type CameraMode } from './guidance-camera'; +import { bearingDegrees, offsetOfIndex, sliceRoute, type RouteMeasure } from './route-measure'; + +/** + * Fraction of the rendered route already travelled. The native offset is measured with the same + * haversine metric on the same geometry; MapLibre's `line-progress` uses projected length, which + * differs by well under 0.1% across a city. + */ +export function traveledFraction(route: RouteMeasure | null, progress: RouteProgress | undefined): number { + if (!route || route.length <= 0 || !progress || !Number.isFinite(progress.traveledMeters)) return 0; + return Math.min(1, Math.max(0, progress.traveledMeters / route.length)); +} + +/** `line-gradient` hiding the travelled part of the active route (a muted full route shows beneath). */ +export function remainingGradient(color: string, fraction: number): unknown[] { + const cut = Math.min(0.999998, Math.max(0, fraction)); + if (cut <= 0) return ['interpolate', ['linear'], ['line-progress'], 0, color, 1, color]; + return ['interpolate', ['linear'], ['line-progress'], 0, 'rgba(0,0,0,0)', cut, 'rgba(0,0,0,0)', cut + 0.000001, color, 1, color]; +} + +const ARROW: Record = { + walk: { before: 12, after: 10 }, bicycle: { before: 20, after: 16 }, car: { before: 35, after: 26 }, +}; +export interface ManeuverArrow { + /** Shaft through the junction: incoming geometry, the maneuver point, outgoing geometry. */ + shaft: [number, number][]; + /** Arrowhead at the shaft end, rotated to the last outgoing segment. */ + head: { coordinate: [number, number]; bearing: number }; +} + +/** + * One cased arrow through the upcoming junction, from the real incoming/outgoing route geometry. + * Never drawn behind the current progress, for arrival/departure or a straight continuation. + */ +export function maneuverArrow(route: RouteMeasure | null, maneuver: GuidanceManeuver | undefined, mode: CameraMode, traveled: number): ManeuverArrow | null { + if (!route || !maneuver || !framesManeuver(maneuver)) return null; + const at = offsetOfIndex(route, maneuver.geometryIndex); + const { before, after } = ARROW[mode]; + const start = Math.max(traveled, at - before); + const end = Math.min(route.length, at + after); + if (end - start < 4 || end <= at) return null; + const points = sliceRoute(route, start, end); + if (points.length < 2) return null; + const last = points[points.length - 1]!; + const previous = sliceRoute(route, Math.max(at, end - 4), end)[0]!; + return { + shaft: points.map(point => [point.longitude, point.latitude]), + head: { coordinate: [last.longitude, last.latitude], bearing: bearingDegrees(previous, last) }, + }; +} diff --git a/src/features/navigation/maneuver-presentation.test.ts b/src/features/navigation/maneuver-presentation.test.ts new file mode 100644 index 0000000..fa371ab --- /dev/null +++ b/src/features/navigation/maneuver-presentation.test.ts @@ -0,0 +1,69 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import type { GuidanceManeuver, NavigationSnapshot } from '../../domain/navigation'; +import { idleNavigation } from '../../domain/navigation'; +import { bannerDistance, maneuverGlyph, maneuverLines, thenManeuver } from './maneuver-presentation'; + +const m = (type: string, more: Partial = {}): GuidanceManeuver => ({ id: '1:1', stepIndex: 1, geometryIndex: 3, type, instruction: 'x', ...more }); + +test('glyphs come from OSRM type and modifier; right turns mirror the left artwork', () => { + assert.deepEqual(maneuverGlyph(m('turn', { modifier: 'right' })), { name: 'left', mirror: true, label: 'Svolta a destra' }); + assert.deepEqual(maneuverGlyph(m('turn', { modifier: 'slight left' })), { name: 'slight-left', mirror: false, label: 'Svolta leggermente a sinistra' }); + assert.equal(maneuverGlyph(m('end of road', { modifier: 'sharp right' })).name, 'sharp-left'); + assert.equal(maneuverGlyph(m('new name', { modifier: 'straight' })).name, 'straight'); + assert.deepEqual(maneuverGlyph(m('continue', { modifier: 'uturn', drivingSide: 'right' })), { name: 'uturn-left', mirror: false, label: 'Inversione di marcia' }); + assert.equal(maneuverGlyph(m('continue', { modifier: 'uturn', drivingSide: 'left' })).mirror, true); + assert.equal(maneuverGlyph(m('fork', { modifier: 'slight right' })).name, 'fork-left'); + assert.equal(maneuverGlyph(m('merge', { modifier: 'slight left' })).name, 'merge-left'); + assert.equal(maneuverGlyph(m('off ramp', { modifier: 'right' })).mirror, true); + assert.deepEqual(maneuverGlyph(m('arrive', { modifier: 'right' })), { name: 'arrive-left', mirror: true, label: 'Destinazione a destra' }); + assert.equal(maneuverGlyph(m('arrive')).name, 'arrive'); +}); + +test('roundabouts show exit number and circulation; left-hand traffic mirrors', () => { + assert.deepEqual(maneuverGlyph(m('roundabout', { modifier: 'right', exit: 2, drivingSide: 'right' })), + { name: 'roundabout-right', mirror: false, exit: 2, label: 'Rotatoria, uscita 2' }); + assert.equal(maneuverGlyph(m('rotary', { modifier: 'left', exit: 4 })).name, 'roundabout-left'); + assert.equal(maneuverGlyph(m('roundabout', { modifier: 'straight', exit: 3 })).name, 'roundabout-straight'); + const clockwise = maneuverGlyph(m('roundabout', { modifier: 'right', exit: 1, drivingSide: 'left' })); + assert.deepEqual([clockwise.name, clockwise.mirror], ['roundabout-left', true], 'mirrored left exit = clockwise right exit'); +}); + +test('unknown types or missing modifiers never become guessed turns', () => { + for (const maneuver of [m('future maneuver', { modifier: 'left' }), m('turn'), m('fork'), m('roundabout', { exit: 2 }), undefined]) { + assert.equal(maneuverGlyph(maneuver).name, 'unknown'); + } + assert.equal(maneuverGlyph(m('roundabout', { exit: 2 })).exit, 2, 'the supplied exit number is still shown'); +}); + +test('banner distance: coarse steps, subordinate unit, Italian decimal comma', () => { + assert.deepEqual(bannerDistance(42), { value: '40', unit: 'm', label: '40 metri' }); + assert.deepEqual(bannerDistance(2), { value: '0', unit: 'm', label: '0 metri' }); + assert.deepEqual(bannerDistance(347), { value: '350', unit: 'm', label: '350 metri' }); + assert.deepEqual(bannerDistance(998), { value: '1', unit: 'km', label: '1 chilometro' }); + assert.deepEqual(bannerDistance(1020), { value: '1', unit: 'km', label: '1 chilometro' }); + assert.deepEqual(bannerDistance(1260), { value: '1,3', unit: 'km', label: '1,3 chilometri' }); + assert.deepEqual(bannerDistance(2000), { value: '2', unit: 'km', label: '2 chilometri' }); + assert.equal(bannerDistance(Number.NaN).value, '–'); +}); + +test('street and action lines split only the supplied street suffix', () => { + assert.deepEqual(maneuverLines(m('turn', { name: 'Via Roma', instruction: 'Svolta a destra su Via Roma' }), undefined), { primary: 'Via Roma', secondary: 'Svolta a destra' }); + assert.deepEqual(maneuverLines(m('turn', { instruction: 'Svolta a destra' }), undefined), { primary: 'Svolta a destra', secondary: null }); + assert.deepEqual(maneuverLines(undefined, 'Stai arrivando a destinazione'), { primary: 'Stai arrivando a destinazione', secondary: null }); +}); + +test('"Poi" uses the gap between maneuvers, not proximity', () => { + const base: NavigationSnapshot = { ...idleNavigation, status: 'navigating', mode: 'car', upcomingManeuver: m('turn', { modifier: 'right' }) }; + const following = { ...m('turn', { id: '1:2', modifier: 'left' }), afterUpcomingMeters: 40, afterUpcomingSeconds: 6 }; + assert.equal(thenManeuver({ ...base, followingManeuver: following })?.id, '1:2'); + assert.equal(thenManeuver({ ...base, followingManeuver: { ...following, afterUpcomingMeters: 600, afterUpcomingSeconds: 45 } }), null); + assert.equal(thenManeuver({ ...base, distanceToManeuverMeters: 5, followingManeuver: { ...following, afterUpcomingMeters: 600, afterUpcomingSeconds: 45 } }), null, 'being close to the first turn is irrelevant'); +}); + +test('the roundabout exit number scales with its glyph and stays legible', async () => { + const { exitNumberSize } = await import('./exit-number'); + assert.equal(exitNumberSize(44), 16); + assert.equal(exitNumberSize(22), 11); + assert.ok(exitNumberSize(57) > exitNumberSize(44)); +}); diff --git a/src/features/navigation/maneuver-presentation.ts b/src/features/navigation/maneuver-presentation.ts new file mode 100644 index 0000000..67cf8e2 --- /dev/null +++ b/src/features/navigation/maneuver-presentation.ts @@ -0,0 +1,102 @@ +import type { GuidanceManeuver, ManeuverModifier, NavigationSnapshot } from '../../domain/navigation'; +import { CAMERA_PROFILES, followsClosely, type CameraMode } from './guidance-camera'; + +/** Glyph names rendered by scripts/render-navigation-assets.mjs (drawn for left turns, right-hand traffic). */ +export type GlyphName = 'straight' | 'slight-left' | 'left' | 'sharp-left' | 'uturn-left' | 'fork-left' | 'merge-left' | 'ramp-left' + | 'roundabout-right' | 'roundabout-slight-right' | 'roundabout-straight' | 'roundabout-slight-left' | 'roundabout-left' + | 'roundabout-sharp-left' | 'roundabout-uturn' | 'arrive' | 'arrive-left' | 'unknown'; +export interface ManeuverGlyph { + name: GlyphName; + /** Mirror horizontally: right turns, or clockwise circulation in left-hand traffic. */ + mirror: boolean; + /** Roundabout exit number shown beside the glyph. */ + exit?: number; + /** Spoken description of the glyph for TalkBack. */ + label: string; +} + +const side = (modifier: ManeuverModifier | undefined): 'left' | 'right' | null => + modifier === 'left' || modifier === 'slight left' || modifier === 'sharp left' ? 'left' + : modifier === 'right' || modifier === 'slight right' || modifier === 'sharp right' ? 'right' : null; +const flip = (modifier: ManeuverModifier): ManeuverModifier => modifier.includes('left') + ? modifier.replace('left', 'right') as ManeuverModifier : modifier.includes('right') ? modifier.replace('right', 'left') as ManeuverModifier : modifier; + +const TURN_TYPES = new Set(['turn', 'continue', 'end of road', 'new name', 'notification', 'use lane', 'exit roundabout', 'exit rotary', 'depart']); +const ROUNDABOUT_TYPES = new Set(['roundabout', 'rotary', 'roundabout turn']); +const unknownGlyph: ManeuverGlyph = { name: 'unknown', mirror: false, label: 'Manovra' }; + +/** + * The banner glyph from raw OSRM facts. A missing or unfamiliar type or modifier gives the neutral + * glyph with the supplied text; a turn direction is never guessed. + */ +export function maneuverGlyph(maneuver: GuidanceManeuver | undefined): ManeuverGlyph { + if (!maneuver) return unknownGlyph; + const { type, modifier } = maneuver; + const leftHand = maneuver.drivingSide === 'left'; + if (type === 'arrive') { + const where = side(modifier); + return where ? { name: 'arrive-left', mirror: where === 'right', label: `Destinazione a ${where === 'left' ? 'sinistra' : 'destra'}` } + : { name: 'arrive', mirror: false, label: 'Destinazione' }; + } + if (ROUNDABOUT_TYPES.has(type)) { + if (!modifier) return { ...unknownGlyph, ...(maneuver.exit ? { exit: maneuver.exit } : {}), label: 'Rotatoria' }; + // Left-hand traffic circulates clockwise: the mirrored glyph of the mirrored exit direction. + const seen = leftHand ? flip(modifier) : modifier; + const name: GlyphName = seen === 'uturn' ? 'roundabout-uturn' : seen === 'straight' ? 'roundabout-straight' + : (`roundabout-${seen.replace(' ', '-')}` as GlyphName); + const known: GlyphName[] = ['roundabout-right', 'roundabout-slight-right', 'roundabout-straight', 'roundabout-slight-left', 'roundabout-left', 'roundabout-sharp-left', 'roundabout-uturn']; + const resolved = known.includes(name) ? name : seen === 'sharp right' ? 'roundabout-right' : 'roundabout-straight'; + return { name: resolved, mirror: leftHand, ...(maneuver.exit ? { exit: maneuver.exit } : {}), label: `Rotatoria${maneuver.exit ? `, uscita ${maneuver.exit}` : ''}` }; + } + const where = side(modifier); + const mirror = where === 'right'; + if (type === 'fork') return where ? { name: 'fork-left', mirror, label: `Bivio, tieni la ${where === 'left' ? 'sinistra' : 'destra'}` } : unknownGlyph; + if (type === 'merge') return where ? { name: 'merge-left', mirror, label: `Immettiti a ${where === 'left' ? 'sinistra' : 'destra'}` } : { name: 'straight', mirror: false, label: 'Immettiti' }; + if (type === 'on ramp' || type === 'off ramp') return where ? { name: 'ramp-left', mirror, label: `Rampa a ${where === 'left' ? 'sinistra' : 'destra'}` } : unknownGlyph; + if (!TURN_TYPES.has(type) || !modifier) return unknownGlyph; + if (modifier === 'straight') return { name: 'straight', mirror: false, label: 'Dritto' }; + if (modifier === 'uturn') return { name: 'uturn-left', mirror: leftHand, label: 'Inversione di marcia' }; + const degree = modifier.startsWith('slight') ? 'slight-left' : modifier.startsWith('sharp') ? 'sharp-left' : 'left'; + const words = { 'slight-left': 'leggermente ', 'sharp-left': 'nettamente ', left: '' }[degree]; + return { name: degree, mirror, label: `Svolta ${words}a ${where === 'left' ? 'sinistra' : 'destra'}` }; +} + +/** + * Banner distance: a number and a subordinate unit. Steps of 5 m below 100 m, 10 m below 1 km, + * then tenths of a kilometre; never more precise than guidance can be. + */ +export function bannerDistance(meters: number): { value: string; unit: string; label: string } { + if (!Number.isFinite(meters) || meters < 0) return { value: '–', unit: '', label: '' }; + if (meters < 1000) { + const step = meters < 100 ? 5 : 10; + const value = Math.max(0, Math.round(meters / step) * step); + if (value >= 1000) return { value: '1', unit: 'km', label: '1 chilometro' }; + return { value: String(value), unit: 'm', label: `${value} metri` }; + } + const km = (Math.round(meters / 100) / 10).toFixed(1).replace('.', ',').replace(/,0$/, ''); + return { value: km, unit: 'km', label: km === '1' ? '1 chilometro' : `${km} chilometri` }; +} + +/** + * Street (primary) and action (secondary) lines. The street is the supplied OSRM name; the action is + * the native Italian instruction with that name's " su " suffix removed, never re-derived. + */ +export function maneuverLines(maneuver: GuidanceManeuver | undefined, instruction: string | undefined): { primary: string; secondary: string | null } { + const text = maneuver?.instruction ?? instruction ?? ''; + const name = maneuver?.name ?? (maneuver?.ref ?? undefined); + if (name) { + const suffix = ` su ${name}`; + const action = text.endsWith(suffix) ? text.slice(0, -suffix.length) : text; + return { primary: name, secondary: action && action !== name ? action : null }; + } + return { primary: text, secondary: null }; +} + +/** "Poi …" only when the following maneuver comes within about ten seconds of travel. */ +export function thenManeuver(snapshot: NavigationSnapshot): GuidanceManeuver | null { + const mode = snapshot.mode === 'walk' || snapshot.mode === 'bicycle' || snapshot.mode === 'car' ? snapshot.mode as CameraMode : null; + const following = snapshot.followingManeuver; + if (!mode || !following || !snapshot.upcomingManeuver) return null; + const speed = Math.max(CAMERA_PROFILES[mode].typicalSpeed, snapshot.location?.speedMps ?? 0); + return followsClosely(following, speed) ? following : null; +} diff --git a/src/features/navigation/map-projection.ts b/src/features/navigation/map-projection.ts new file mode 100644 index 0000000..5dce0fc --- /dev/null +++ b/src/features/navigation/map-projection.ts @@ -0,0 +1,68 @@ +import type { Coordinate } from '../../domain/types'; + +/** + * Screen projection matching MapLibre's transform (512 px tiles, vertical field of view 36.87°, + * camera distance from the full viewport height, padding as a principal-point offset). The camera + * planner uses it to place the puck and to check that a junction is framed before issuing a move; + * device runs compare it with `MapRef.project`. + */ +export interface ScreenSize { width: number; height: number } +export interface Padding { top: number; right: number; bottom: number; left: number } +export interface CameraPose { center: Coordinate; zoom: number; bearing: number; pitch: number; padding: Padding } +export interface ScreenPoint { x: number; y: number } + +const FIELD_OF_VIEW = 0.6435011087932844; +const TILE = 512; +const rad = (degrees: number) => degrees * Math.PI / 180; + +function world(point: Coordinate, zoom: number) { + const size = TILE * 2 ** zoom; + const latitude = Math.max(-85.051129, Math.min(85.051129, point.latitude)); + return { + x: ((point.longitude + 180) / 360) * size, + y: ((1 - Math.log(Math.tan(Math.PI / 4 + rad(latitude) / 2)) / Math.PI) / 2) * size, + }; +} + +/** Screen point of the padded centre: where the camera's `center` coordinate is drawn. */ +export function principalPoint(size: ScreenSize, padding: Padding): ScreenPoint { + return { x: size.width / 2 + (padding.left - padding.right) / 2, y: size.height / 2 + (padding.top - padding.bottom) / 2 }; +} + +/** Projects a ground coordinate; `null` behind the camera or beyond the horizon. */ +export function project(pose: CameraPose, size: ScreenSize, point: Coordinate): ScreenPoint | null { + const c = world(pose.center, pose.zoom); + const p = world(point, pose.zoom); + const dx = p.x - c.x; const dy = p.y - c.y; + const b = rad(pose.bearing); const pitch = rad(pose.pitch); + const right = dx * Math.cos(b) + dy * Math.sin(b); + const forward = dx * Math.sin(b) - dy * Math.cos(b); + const distance = 0.5 * size.height / Math.tan(FIELD_OF_VIEW / 2); + const depth = distance + forward * Math.sin(pitch); + if (depth <= distance * 0.05) return null; + const principal = principalPoint(size, pose.padding); + return { x: principal.x + right * distance / depth, y: principal.y - forward * Math.cos(pitch) * distance / depth }; +} + +/** + * Padding that draws the camera centre at (`anchorX`, `anchorY`), e.g. low in the map and, in + * landscape, in the middle of the map left of the side panel. MapLibre centres the padded + * rectangle, so a LOW anchor needs TOP padding: bottom padding alone moves the centre up. + */ +export function paddingForAnchor(size: ScreenSize, anchorY: number, anchorX = size.width / 2): Padding { + const y = Math.max(0, Math.min(size.height, anchorY)); + const x = Math.max(0, Math.min(size.width, anchorX)); + return { + top: Math.max(0, 2 * y - size.height), right: Math.max(0, size.width - 2 * x), + bottom: Math.max(0, size.height - 2 * y), left: Math.max(0, 2 * x - size.width), + }; +} + +export interface VisibleRect { left: number; top: number; right: number; bottom: number } +export const inside = (point: ScreenPoint | null, rect: VisibleRect) => point !== null + && point.x >= rect.left && point.x <= rect.right && point.y >= rect.top && point.y <= rect.bottom; + +/** Metres per screen point at the centre (MapLibre logical points). */ +export function metersPerPoint(latitude: number, zoom: number): number { + return 40_075_016.686 * Math.cos(rad(latitude)) / (TILE * 2 ** zoom); +} diff --git a/src/features/navigation/motion-estimator.test.ts b/src/features/navigation/motion-estimator.test.ts new file mode 100644 index 0000000..3fa5840 --- /dev/null +++ b/src/features/navigation/motion-estimator.test.ts @@ -0,0 +1,49 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { MotionEstimator } from './motion-estimator'; +import { offsetCoordinate } from './route-measure'; +import { TURIN } from './guidance-fixtures'; + +test('stationary jitter (2 m east/west at ±5 m) never becomes motion, speed or course', () => { + const estimator = new MotionEstimator(); + for (let t = 0; t < 60; t += 1) { + const motion = estimator.update(offsetCoordinate(TURIN, t % 2 ? 90 : 270, 2), 1000 * t, 5); + assert.deepEqual(motion, { speedMps: 0, moving: false }, `t=${t}`); + } +}); + +test('jitter larger than the reported accuracy flips direction and never passes the consistency hysteresis', () => { + const estimator = new MotionEstimator(); + for (let t = 0; t < 40; t += 1) assert.equal(estimator.update(offsetCoordinate(TURIN, t % 2 ? 90 : 270, 4), 1000 * t, 3).moving, false); +}); + +test('driving at 10 m/s: motion after two consistent estimates, honest course accuracy', () => { + const estimator = new MotionEstimator(); + const results = Array.from({ length: 8 }, (_, t) => estimator.update(offsetCoordinate(TURIN, 300, 10 * t), 1000 * t, 5)); + assert.equal(results[1]!.moving, false, 'one estimate is not enough'); + assert.equal(results[2]!.moving, true); + for (const motion of results.slice(3)) { + assert.ok(Math.abs(motion.speedMps - 10) < 0.2); + assert.ok(Math.abs(motion.course! - 300) < 0.5); + assert.ok(motion.courseAccuracyDegrees! <= 27, `${motion.courseAccuracyDegrees}`); + } +}); + +test('walking at 1.4 m/s with ±5 m fixes waits for a baseline above the noise; ±25 m fixes stay unproven', () => { + const precise = new MotionEstimator(); + const walk = Array.from({ length: 12 }, (_, t) => precise.update(offsetCoordinate(TURIN, 45, 1.4 * t), 1000 * t, 5)); + assert.equal(walk[4]!.moving, false, '5.6 m < 7.1 m combined accuracy'); + assert.equal(walk[11]!.moving, true); + assert.ok(Math.abs(walk[11]!.speedMps - 1.4) < 0.1); + const coarse = new MotionEstimator(); + for (let t = 0; t < 20; t += 1) assert.equal(coarse.update(offsetCoordinate(TURIN, 45, 1.4 * t), 1000 * t, 25).moving, false); +}); + +test('stopping returns to stationary at once; duplicate sample times are ignored', () => { + const estimator = new MotionEstimator(); + for (let t = 0; t < 5; t += 1) estimator.update(offsetCoordinate(TURIN, 0, 10 * t), 1000 * t, 5); + assert.equal(estimator.current.moving, true); + assert.equal(estimator.update(offsetCoordinate(TURIN, 0, 99), 4000, 5).moving, true, 'same time: unchanged'); + for (let t = 5; t < 16; t += 1) estimator.update(offsetCoordinate(TURIN, 0, 40), 1000 * t, 5); + assert.deepEqual(estimator.current, { speedMps: 0, moving: false }); +}); diff --git a/src/features/navigation/motion-estimator.ts b/src/features/navigation/motion-estimator.ts new file mode 100644 index 0000000..6090fb7 --- /dev/null +++ b/src/features/navigation/motion-estimator.ts @@ -0,0 +1,69 @@ +import type { Coordinate } from '../../domain/types'; +import { angleDelta, bearingDegrees, distanceMeters } from './route-measure'; + +/** + * Presentation-only motion for providers that omit speed or course (some platforms, test + * providers). A displacement counts only when it exceeds the combined horizontal accuracy of the + * two fixes (and at least `minimumMeters`), measured against the most recent earlier fix that it + * clears within `windowMs`; entering "moving" needs two consecutive consistent estimates, while one + * inconclusive fix returns to stationary. Stationary jitter therefore yields no speed and no course, + * and the course accuracy reports the real geometric uncertainty instead of a fixed guess. + */ +export interface EstimatedMotion { + /** 0 while stationary or unproven. */ + speedMps: number; + course?: number; + courseAccuracyDegrees?: number; + moving: boolean; +} + +interface Sample { coordinate: Coordinate; ms: number; accuracy: number } + +export class MotionEstimator { + private samples: Sample[] = []; + private streak = 0; + private lastCourse: number | null = null; + private result: EstimatedMotion = { speedMps: 0, moving: false }; + + constructor(private readonly windowMs = 10_000, private readonly minimumMeters = 3, private readonly consistencyDegrees = 60) {} + + get current(): EstimatedMotion { return this.result; } + + /** One distinct fix (a repeated sample time returns the previous estimate). */ + update(coordinate: Coordinate, ms: number, accuracyMeters: number): EstimatedMotion { + const last = this.samples[this.samples.length - 1]; + if (last && ms <= last.ms) return this.result; + const accuracy = Number.isFinite(accuracyMeters) && accuracyMeters > 0 ? accuracyMeters : 50; + this.samples.push({ coordinate, ms, accuracy }); + while (this.samples.length > 1 && ms - this.samples[0]!.ms > this.windowMs) this.samples.shift(); + // Speed: the most recent earlier fix the displacement clears. Course: prefer a baseline twice + // the uncertainty (about 27° at worst), falling back to the clearing fix with its honest error. + let found: { distance: number; seconds: number; course: number; uncertainty: number } | null = null; + let heading: { course: number; distance: number; uncertainty: number } | null = null; + for (let i = this.samples.length - 2; i >= 0; i -= 1) { + const earlier = this.samples[i]!; + const uncertainty = Math.max(this.minimumMeters, Math.hypot(earlier.accuracy, accuracy)); + const distance = distanceMeters(earlier.coordinate, coordinate); + if (!found && distance > uncertainty) { + found = { distance, seconds: (ms - earlier.ms) / 1000, course: bearingDegrees(earlier.coordinate, coordinate), uncertainty }; + } + if (found && distance >= 2 * uncertainty) { heading = { course: bearingDegrees(earlier.coordinate, coordinate), distance, uncertainty }; break; } + } + if (found && heading) found = { ...found, course: heading.course }; + if (!found || found.seconds <= 0) { + this.streak = 0; this.lastCourse = null; + this.result = { speedMps: 0, moving: false }; + return this.result; + } + const consistent = this.lastCourse !== null && Math.abs(angleDelta(this.lastCourse, found.course)) <= this.consistencyDegrees; + this.streak = consistent ? this.streak + 1 : 1; + this.lastCourse = found.course; + if (this.streak < 2) { this.result = { speedMps: 0, moving: false }; return this.result; } + const baseline = heading ?? found; + this.result = { + speedMps: found.distance / found.seconds, course: found.course, moving: true, + courseAccuracyDegrees: Math.min(90, Math.atan2(baseline.uncertainty, baseline.distance) * 180 / Math.PI), + }; + return this.result; + } +} diff --git a/src/features/navigation/route-measure.test.ts b/src/features/navigation/route-measure.test.ts new file mode 100644 index 0000000..89687cd --- /dev/null +++ b/src/features/navigation/route-measure.test.ts @@ -0,0 +1,28 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { angleDelta, bearingDegrees, distanceMeters, measureRoute, offsetCoordinate, offsetOfIndex, pointAt, routeBearingAt, segmentAt, sliceRoute } from './route-measure'; +import { maneuverPoint, routeFixture, TURIN } from './guidance-fixtures'; + +test('route offsets use the native haversine metric on the bridged geometry', () => { + const { route, maneuvers } = routeFixture([{ bearing: 0, meters: 200 }, { bearing: 90, meters: 150, modifier: 'right' }, { bearing: 0, meters: 100, modifier: 'left' }]); + assert.ok(Math.abs(route.length - 450) < 0.5); + assert.ok(Math.abs(offsetOfIndex(route, maneuvers[1]!.geometryIndex) - 200) < 0.5); + assert.ok(Math.abs(offsetOfIndex(route, maneuvers[2]!.geometryIndex) - 350) < 0.5); + assert.ok(distanceMeters(pointAt(route, 200), maneuverPoint(maneuvers[1]!)) < 0.01); + assert.equal(segmentAt(route, -5), 0); + assert.equal(segmentAt(route, 1e9), route.points.length - 2); + const slice = sliceRoute(route, 190, 230); + assert.ok(Math.abs(slice.slice(1).reduce((sum, point, i) => sum + distanceMeters(slice[i]!, point), 0) - 40) < 0.5, 'slice keeps the corner'); +}); + +test('bearings wrap across north and the route bearing stops at the next maneuver', () => { + assert.equal(angleDelta(359, 1), 2); + assert.equal(angleDelta(1, 359), -2); + assert.equal(angleDelta(10, 190), 180); + assert.ok(Math.abs(bearingDegrees(TURIN, offsetCoordinate(TURIN, 359, 50)) - 359) < 0.05); + const { route } = routeFixture([{ bearing: 0, meters: 200 }, { bearing: 90, meters: 150, modifier: 'right' }]); + // 10 m before a right turn with a 30 m look-ahead limited to the turn: still north. + assert.ok(Math.abs(angleDelta(routeBearingAt(route, 190, 30, 200)!, 0)) < 0.5); + assert.ok(Math.abs(angleDelta(routeBearingAt(route, 190, 30)!, 0)) > 20, 'unlimited look-ahead cuts the corner'); + assert.equal(routeBearingAt(measureRoute([TURIN]), 0, 10), null); +}); diff --git a/src/features/navigation/route-measure.ts b/src/features/navigation/route-measure.ts new file mode 100644 index 0000000..b5f85d9 --- /dev/null +++ b/src/features/navigation/route-measure.ts @@ -0,0 +1,104 @@ +import type { Coordinate } from '../../domain/types'; + +/** Mean Earth radius used by the native haversine (NavigationGeometry), so offsets agree. */ +const EARTH_RADIUS = 6_371_000; +const rad = (degrees: number) => degrees * Math.PI / 180; +const deg = (radians: number) => radians * 180 / Math.PI; + +export function distanceMeters(a: Coordinate, b: Coordinate): number { + const dLat = rad(b.latitude - a.latitude); + const dLon = rad(b.longitude - a.longitude); + const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(a.latitude)) * Math.cos(rad(b.latitude)) * Math.sin(dLon / 2) ** 2; + return 2 * EARTH_RADIUS * Math.asin(Math.sqrt(Math.min(1, Math.max(0, h)))); +} + +/** Initial compass bearing from a to b in [0, 360). */ +export function bearingDegrees(a: Coordinate, b: Coordinate): number { + const phi1 = rad(a.latitude); const phi2 = rad(b.latitude); const dLambda = rad(b.longitude - a.longitude); + const y = Math.sin(dLambda) * Math.cos(phi2); + const x = Math.cos(phi1) * Math.sin(phi2) - Math.sin(phi1) * Math.cos(phi2) * Math.cos(dLambda); + return (deg(Math.atan2(y, x)) + 360) % 360; +} + +/** Point reached from `from` after `meters` along compass `bearing` (local flat approximation). */ +export function offsetCoordinate(from: Coordinate, bearing: number, meters: number): Coordinate { + const b = rad(bearing); + return { + latitude: from.latitude + (meters * Math.cos(b)) / (EARTH_RADIUS * Math.PI / 180), + longitude: from.longitude + (meters * Math.sin(b)) / (EARTH_RADIUS * Math.PI / 180 * Math.cos(rad(from.latitude))), + }; +} + +/** Signed shortest angular difference `to - from` in (-180, 180]. */ +export function angleDelta(from: number, to: number): number { + const d = ((to - from) % 360 + 540) % 360 - 180; + return d === -180 ? 180 : d; +} +export const normalizeBearing = (value: number) => ((value % 360) + 360) % 360; + +/** + * Immutable measure over one route revision's geometry: cumulative haversine distance (the metric + * the native progress offset uses), interpolation and slices by route offset. + */ +export interface RouteMeasure { + readonly points: readonly Coordinate[]; + readonly cumulative: Float64Array; + readonly length: number; +} + +export function measureRoute(points: readonly Coordinate[]): RouteMeasure { + const cumulative = new Float64Array(points.length); + for (let i = 1; i < points.length; i += 1) cumulative[i] = cumulative[i - 1]! + distanceMeters(points[i - 1]!, points[i]!); + return { points, cumulative, length: points.length ? cumulative[points.length - 1]! : 0 }; +} + +/** Index i such that cumulative[i] <= offset < cumulative[i + 1] (clamped to the last segment). */ +export function segmentAt(route: RouteMeasure, offset: number): number { + const { cumulative, points } = route; + if (points.length < 2) return 0; + let lo = 0; let hi = points.length - 1; + if (offset <= 0) return 0; + if (offset >= route.length) return points.length - 2; + while (hi - lo > 1) { + const mid = (lo + hi) >> 1; + if (cumulative[mid]! <= offset) lo = mid; else hi = mid; + } + return lo; +} + +export function pointAt(route: RouteMeasure, offset: number): Coordinate { + const { points, cumulative } = route; + if (points.length === 0) return { latitude: 0, longitude: 0 }; + if (points.length === 1) return points[0]!; + const clamped = Math.min(route.length, Math.max(0, offset)); + const i = segmentAt(route, clamped); + const a = points[i]!; const b = points[i + 1]!; + const span = cumulative[i + 1]! - cumulative[i]!; + const t = span > 0 ? (clamped - cumulative[i]!) / span : 0; + return { latitude: a.latitude + (b.latitude - a.latitude) * t, longitude: a.longitude + (b.longitude - a.longitude) * t }; +} + +/** Points of the route between two offsets, both ends interpolated. */ +export function sliceRoute(route: RouteMeasure, from: number, to: number): Coordinate[] { + if (route.points.length < 2) return [...route.points]; + const start = Math.max(0, Math.min(from, to)); const end = Math.min(route.length, Math.max(from, to)); + const result = [pointAt(route, start)]; + for (let i = segmentAt(route, start) + 1; i < route.points.length && route.cumulative[i]! < end; i += 1) result.push(route.points[i]!); + result.push(pointAt(route, end)); + return result; +} + +/** + * Bearing of the route ahead of `offset`: from the point at `offset` to the point `lookAhead` metres + * further, never beyond `limit` (the next maneuver), so the camera does not rotate before a turn. + */ +export function routeBearingAt(route: RouteMeasure, offset: number, lookAhead: number, limit = Infinity): number | null { + if (route.points.length < 2) return null; + const end = Math.min(route.length, offset + lookAhead, Math.max(offset + 2, limit)); + const start = Math.max(0, Math.min(offset, end - 2)); + const a = pointAt(route, start); const b = pointAt(route, end); + return distanceMeters(a, b) < 0.5 ? null : bearingDegrees(a, b); +} + +/** Route offset of a geometry index. */ +export const offsetOfIndex = (route: RouteMeasure, index: number) => route.cumulative[Math.max(0, Math.min(route.points.length - 1, Math.round(index)))] ?? 0; diff --git a/src/features/navigation/useGuidanceCamera.ts b/src/features/navigation/useGuidanceCamera.ts new file mode 100644 index 0000000..13be08c --- /dev/null +++ b/src/features/navigation/useGuidanceCamera.ts @@ -0,0 +1,115 @@ +import { useMemo, useRef } from 'react'; +import type { NavigationSnapshot } from '../../domain/navigation'; +import type { Coordinate, RoutePlan } from '../../domain/types'; +import type { MapCamera } from '../map/useMapCamera'; +import { GuidanceCamera, overviewBounds, type CameraFrame, type CameraIntent, type CameraMode, type GuidanceViewport, type PuckKind } from './guidance-camera'; +import { maneuverArrow, traveledFraction, type ManeuverArrow } from './guidance-route'; +import { measureRoute, type RouteMeasure } from './route-measure'; +import { sessionPlan } from './transit-follow'; +import { legFitKey, type GuidanceFit } from './guidance-commands'; +export type { GuidanceFit } from './guidance-commands'; + +/** What the map needs during guidance: camera intent and frames, the puck and the route styling. */ +export interface GuidanceMapState { + intent: CameraIntent; + /** Road and transit walking modes; null while the camera only frames (transit without a fix). */ + mode: CameraMode | null; + frame: CameraFrame | null; + /** Overview of the remaining route, framed once per explicit request. */ + overview: GuidanceFit | null; + /** Transit without a usable fix: the current leg and its stop, framed once per leg. */ + fit: GuidanceFit | null; + puck: { coordinate: Coordinate; heading: number | null; kind: PuckKind } | null; + /** Road route styling: travelled fraction and the arrow through the next junction. */ + route: { fraction: number; arrow: ManeuverArrow | null } | null; + /** Called at gesture start: enters free immediately, before the region settles. */ + onUserGesture(): void; +} + +const ROAD_MODES = new Set(['walk', 'bicycle', 'car']); +/** Location states in which the accepted fix is current; anything else holds the camera. */ +const LIVE_STATUSES = new Set(['navigating', 'off-route', 'rerouting', 'routing']); +const FIX_FRESH_MS = 15_000; + +function boundsOf(points: Coordinate[], pad = 0.0004): [number, number, number, number] | null { + if (!points.length) return null; + let [west, south, east, north] = [Infinity, Infinity, -Infinity, -Infinity]; + for (const point of points) { + west = Math.min(west, point.longitude); east = Math.max(east, point.longitude); + south = Math.min(south, point.latitude); north = Math.max(north, point.latitude); + } + return [west - pad, south - pad, east + pad, north + pad]; +} + +/** + * First-person guidance camera, driven only by accepted native navigation state (no second + * location stream, no MapLibre auto-tracking). One planner per session; one frame per distinct fix. + * Transit access, transfer and final walks use the walking camera on the supplied trace when a + * usable fix exists (still without turn instructions); otherwise the current leg and stop are framed. + */ +export function useGuidanceCamera({ snapshot, camera, viewport, active, transitPlan }: { + snapshot: NavigationSnapshot; camera: MapCamera; viewport: GuidanceViewport; active: boolean; transitPlan?: RoutePlan | null; +}): GuidanceMapState | null { + const planner = useRef<{ session: string | null; camera: GuidanceCamera; recenter: number } | null>(null); + if (!planner.current || planner.current.session !== snapshot.sessionId) { + planner.current = { session: snapshot.sessionId, camera: new GuidanceCamera(), recenter: camera.guidanceRecenter }; + } + const transit = snapshot.mode === 'transit' ? snapshot.transit : undefined; + const plan = transit ? sessionPlan(snapshot, transitPlan ?? null) : null; + const legIndices = transit ? (transit.sourceLegIndices?.length ? transit.sourceLegIndices : [transit.legIndex]) : null; + const legKey = legIndices?.join(',') ?? ''; + const legGeometry = useMemo(() => plan && legIndices ? legIndices.flatMap(index => plan.legs[index]?.geometry ?? []) : null, + // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed by the leg indices + [plan, legKey]); + const walkingLeg = transit && (transit.phase === 'walk' || transit.phase === 'transfer'); + const geometry = transit ? (walkingLeg ? legGeometry : null) : snapshot.route?.geometry; + const route = useMemo(() => geometry && geometry.length > 1 ? measureRoute(geometry) : null, [geometry]); + const location = snapshot.location; + const fresh = location !== undefined && Date.now() - location.timestamp <= FIX_FRESH_MS; + const usable = snapshot.locationUsable === true && LIVE_STATUSES.has(snapshot.status) && (!transit || fresh); + const mode: CameraMode | null = snapshot.mode && ROAD_MODES.has(snapshot.mode) ? snapshot.mode as CameraMode + : walkingLeg && usable ? 'walk' : null; + const state = planner.current; + let frame: CameraFrame | null = null; + if (active && mode && location) { + frame = state.camera.update(transit ? { mode, fix: location, usable, route, viewport, traceOnly: true } : { + mode, fix: location, usable, route, routeRevision: snapshot.routeRevision, + progress: snapshot.routeProgress, alignment: snapshot.alignment, snapped: snapshot.snappedLocation, + upcoming: snapshot.upcomingManeuver, following: snapshot.followingManeuver, + distanceToManeuverMeters: snapshot.distanceToManeuverMeters, viewport, + }); + if (camera.guidanceRecenter !== state.recenter) { state.recenter = camera.guidanceRecenter; frame = state.camera.recenter() ?? frame; } + } + // Fits keep clear of every side: the banner, the strip and, in landscape, the side panel. + const padding = useMemo(() => ({ top: viewport.top + 24, right: viewport.width - viewport.right + 32, bottom: viewport.height - viewport.bottom + 24, left: viewport.left + 32 }), [viewport]); + const overviewKey = camera.guidanceOverview; + const traveled = snapshot.routeProgress?.traveledMeters ?? 0; + // Framed once per explicit request: later progress or a reroute never refits it. + const planRoute = useMemo(() => plan?.geometry.length ? measureRoute(plan.geometry) : null, [plan]); + const overviewRoute = transit ? planRoute : route; + const overview = useMemo(() => { + if (!overviewRoute || overviewKey === 0) return null; + const bounds = overviewBounds(overviewRoute, transit ? 0 : traveled, location ? { latitude: location.latitude, longitude: location.longitude } : undefined); + return bounds ? { key: `overview:${overviewKey}`, bounds, padding } : null; + // eslint-disable-next-line react-hooks/exhaustive-deps -- deliberately frozen until the next request + }, [overviewKey, overviewRoute !== null]); + const fit = useMemo(() => { + if (!transit || mode || !legGeometry?.length) return null; + const bounds = boundsOf(legGeometry); + // A new key per leg and per explicit Ricentra, so a recenter during a ride always reframes. + return bounds ? { key: legFitKey(snapshot.sessionId, legKey, camera.guidanceRecenter), bounds, padding } : null; + // eslint-disable-next-line react-hooks/exhaustive-deps -- one frame per leg and recenter request + }, [transit !== undefined, mode, legKey, legGeometry !== null, camera.guidanceRecenter]); + const fraction = traveledFraction(route, snapshot.routeProgress); + const upcoming = snapshot.upcomingManeuver; + const arrow = useMemo(() => !transit && mode ? maneuverArrow(route, upcoming, mode, traveled) : null, + // eslint-disable-next-line react-hooks/exhaustive-deps -- the arrow follows the maneuver id and coarse progress + [route, upcoming?.id, mode, transit !== undefined, Math.round(traveled / 2)]); + const { stopFollowing } = camera; + if (!active || (!mode && !transit)) return null; + const puck = frame?.puck ?? (location ? { coordinate: { latitude: location.latitude, longitude: location.longitude }, heading: null, kind: (usable ? 'dot' : 'retained') as PuckKind } : null); + return { + intent: camera.guidanceIntent, mode, frame, overview, fit, puck, + route: !transit && route ? { fraction, arrow } : null, onUserGesture: stopFollowing, + }; +} diff --git a/src/theme/brand-assets.test.ts b/src/theme/brand-assets.test.ts index ba5a727..2cd69d9 100644 --- a/src/theme/brand-assets.test.ts +++ b/src/theme/brand-assets.test.ts @@ -39,3 +39,9 @@ test('icon, adaptive, themed, splash and favicon PNGs match a fresh render of as const result = spawnSync(process.execPath.endsWith('bun') ? 'node' : process.execPath, ['scripts/render-brand-assets.mjs', '--check'], { cwd: fileURLToPath(root), encoding: 'utf8' }); assert.equal(result.status, 0, result.stderr || result.stdout); }); + +test('navigation puck, maneuver glyph and map symbol PNGs match a fresh render', async () => { + const { spawnSync } = await import('node:child_process'); + const result = spawnSync(process.execPath.endsWith('bun') ? 'node' : process.execPath, ['scripts/render-navigation-assets.mjs', '--check'], { cwd: fileURLToPath(root), encoding: 'utf8' }); + assert.equal(result.status, 0, result.stderr || result.stdout); +}); diff --git a/src/theme/brand-basemap.ts b/src/theme/brand-basemap.ts index fe63e41..dacf8f0 100644 --- a/src/theme/brand-basemap.ts +++ b/src/theme/brand-basemap.ts @@ -246,6 +246,19 @@ export function brandRecipe(scheme: ColorScheme): StyleRecipe { ], keep: [], insert: [ + { + // Driving guidance shows one-way chevrons (app image `oneway-`); hidden otherwise. + before: 'highway-name-path', + layer: { + id: 'avoid_oneway', type: 'symbol', source: 'openmaptiles', 'source-layer': 'transportation', minzoom: 15, + // `oneway` 1 runs with the line geometry, -1 against it: the chevron turns round. + filter: ['all', ['match', ['get', 'oneway'], [1, -1], true, false], ['match', ['get', 'class'], ['motorway', 'trunk', 'primary', 'secondary', 'tertiary', 'minor', 'service'], true, false]], + layout: { + visibility: 'none', 'symbol-placement': 'line', 'symbol-spacing': 90, 'icon-image': `oneway-${scheme}`, 'icon-rotate': ['match', ['get', 'oneway'], -1, 270, 90], + 'icon-rotation-alignment': 'map', 'icon-allow-overlap': true, 'icon-ignore-placement': true, + }, + }, + }, { before: 'poi_r20', layer: dot([1, 7], 15) }, { before: 'poi_r20', layer: dot([7, 20], 16) }, { before: 'poi_r20', layer: dot([20], 17) }, diff --git a/src/theme/map-style.test.ts b/src/theme/map-style.test.ts index 0f4efc6..d32e597 100644 --- a/src/theme/map-style.test.ts +++ b/src/theme/map-style.test.ts @@ -50,6 +50,8 @@ for (const scheme of schemes) { walk(layer.paint, layer.id); walk(layer.layout, layer.id); for (const property of ['icon-image', 'fill-pattern', 'line-pattern']) { + // The one exception is the app's own greyscale one-way chevron (assets/navigation, not the sprite). + if (layer.id === 'avoid_oneway' && property === 'icon-image') { assert.equal(layer.layout?.[property], `oneway-${scheme}`); continue; } assert.ok(!(property in (layer.layout ?? {})) && !(property in (layer.paint ?? {})), `${layer.id} uses sprite ${property}`); } } @@ -124,7 +126,7 @@ for (const scheme of schemes) { test(`avoid-${scheme}: labels meet AA on their halos and on the surfaces beneath them`, () => { const style = mapStyleFor(scheme); const ink = basemapInks[scheme]; - const labels = (style.layers as StyleLayer[]).filter(layer => layer.type === 'symbol'); + const labels = (style.layers as StyleLayer[]).filter(layer => layer.type === 'symbol' && layer.layout?.['text-field'] !== undefined); for (const layer of labels) { const color = String(layer.paint?.['text-color']); const halo = String(layer.paint?.['text-halo-color']); @@ -215,3 +217,20 @@ test('POI labels name key amenities by OSM subclass, not by the broader class', assert.equal(shown({ class: 'waste_basket', subclass: 'waste_basket', rank: 1 }), false, 'unnamed bins stay hidden'); assert.equal(shown({ class: 'railway', subclass: 'tram_stop', rank: 1, name: 'Castello' }), false, 'stops use the transit rings'); }); + +test('one-way chevrons cover both directions: oneway 1 along the line, -1 turned round', () => { + for (const scheme of ['light', 'dark'] as const) { + const layer = layerOf(mapStyleFor(scheme), 'avoid_oneway'); + assert.equal(layer?.layout?.visibility, 'none', 'hidden until driving guidance shows it'); + const filter = createExpression(layer?.filter, { type: 'boolean' } as never); + const rotate = createExpression(layer?.layout?.['icon-rotate'], latest.layout_symbol['icon-rotate'] as never); + assert.equal(filter.result, 'success'); assert.equal(rotate.result, 'success'); + if (filter.result !== 'success' || rotate.result !== 'success') return; + const feature = (oneway: number) => ({ type: 'LineString', properties: { oneway, class: 'minor' } }) as never; + assert.equal(filter.value.evaluate({ zoom: 16 }, feature(1)), true); + assert.equal(filter.value.evaluate({ zoom: 16 }, feature(-1)), true); + assert.equal(filter.value.evaluate({ zoom: 16 }, feature(0)), false); + assert.equal(rotate.value.evaluate({ zoom: 16 }, feature(1)), 90); + assert.equal(rotate.value.evaluate({ zoom: 16 }, feature(-1)), 270); + } +}); diff --git a/src/theme/palette.ts b/src/theme/palette.ts index d06d57a..5e51b7d 100644 --- a/src/theme/palette.ts +++ b/src/theme/palette.ts @@ -51,6 +51,8 @@ export interface MapColors { background: string; routeLine: string; routeCasing: string; + /** The part of a guidance route already travelled: thinner and muted beneath the active line. */ + routeTraveled: string; placeMarker: string; stopMarker: string; markerStroke: string; @@ -132,6 +134,7 @@ export const palettes: Record = { background: basemapInks.light.land, routeLine: '#09090B', routeCasing: '#FFFFFF', + routeTraveled: '#A1A1AA', placeMarker: '#09090B', stopMarker: '#71717A', markerStroke: '#FFFFFF', @@ -152,6 +155,7 @@ export const palettes: Record = { background: basemapInks.dark.land, routeLine: '#FFFFFF', routeCasing: '#000000', + routeTraveled: '#52525B', placeMarker: '#FFFFFF', stopMarker: '#A1A1AA', markerStroke: '#000000',