Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniapps/navigation/.claude/scheduled_tasks.lock +1 -0
- miniapps/navigation/miniapp.json +160 -0
- miniapps/navigation/package.json +33 -0
- miniapps/navigation/public/assets/Mentra-Navigation.png +0 -0
- miniapps/navigation/public/assets/dest.svg +4 -0
- miniapps/navigation/src/background/NavigationController.ts +0 -0
- miniapps/navigation/src/background/actions/savedAddressActions.ts +68 -0
- miniapps/navigation/src/background/index.ts +16 -0
- miniapps/navigation/src/background/lib/ArrowRenderer.ts +94 -0
- miniapps/navigation/src/background/lib/MinimapRenderer.ts +254 -0
- miniapps/navigation/src/background/lib/OsmLineMapRenderer.ts +407 -0
- miniapps/navigation/src/background/lib/bmp.ts +242 -0
- miniapps/navigation/src/background/lib/capabilities.ts +25 -0
- miniapps/navigation/src/background/lib/formatDistance.ts +40 -0
- miniapps/navigation/src/background/lib/geometry.ts +297 -0
- miniapps/navigation/src/background/lib/places.ts +103 -0
- miniapps/navigation/src/background/lib/rdpSmooth.ts +65 -0
- miniapps/navigation/src/background/lib/testBitmap.ts +0 -0
- miniapps/navigation/src/background/managers/AudioGuidanceManager.ts +565 -0
- miniapps/navigation/src/background/managers/CompassManager.ts +21 -0
- miniapps/navigation/src/background/managers/DisplayManager.ts +372 -0
- miniapps/navigation/src/background/managers/LocationManager.ts +29 -0
- miniapps/navigation/src/background/managers/ManeuverFormatter.ts +192 -0
- miniapps/navigation/src/background/managers/NavigationManager.ts +131 -0
- miniapps/navigation/src/background/managers/PlacesManager.ts +42 -0
- miniapps/navigation/src/background/managers/SimpleStorageManager.ts +133 -0
- miniapps/navigation/src/shared/channels.ts +111 -0
- miniapps/navigation/src/shared/maneuverDisplay.ts +240 -0
- miniapps/navigation/src/shared/types.ts +146 -0
- miniapps/navigation/src/test/audio-guidance.test.ts +421 -0
- miniapps/navigation/src/test/bitmaps/fetch-static-maps.ts +88 -0
- miniapps/navigation/src/test/bitmaps/png-to-bmp.ts +105 -0
- miniapps/navigation/src/test/bitmaps/preview-osm-map.ts +56 -0
- miniapps/navigation/src/test/bitmaps/preview-osm.bmp +0 -0
- miniapps/navigation/src/test/bitmaps/preview-osm.png +0 -0
- miniapps/navigation/src/test/bitmaps/z12-400x400.png +0 -0
- miniapps/navigation/src/test/bitmaps/z14-200x100.png +0 -0
- miniapps/navigation/src/test/bitmaps/z14-200x88.png +0 -0
- miniapps/navigation/src/test/bitmaps/z14-400x400.png +0 -0
- miniapps/navigation/src/test/bitmaps/z14-88x88-scale2.bmp.ts +4 -0
- miniapps/navigation/src/test/bitmaps/z14-88x88-scale2.png +0 -0
- miniapps/navigation/src/test/bitmaps/z14-roadmap.png +0 -0
- miniapps/navigation/src/test/bitmaps/z14-terrain.png +0 -0
- miniapps/navigation/src/test/bitmaps/z16-400x400.png +0 -0
- miniapps/navigation/src/test/buildConfig.test.ts +41 -0
- miniapps/navigation/src/test/capabilities.test.ts +49 -0
- miniapps/navigation/src/test/display-manager.test.ts +216 -0
- miniapps/navigation/src/test/early-arrival.test.ts +107 -0
- miniapps/navigation/src/test/navigation/computeRoute/computeRoute.test.ts +53 -0
- miniapps/navigation/src/test/navigation/computeRoute/fixtures/defaults.expected.json +5 -0
miniapps/navigation/.claude/scheduled_tasks.lock
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"sessionId":"cef166da-ea55-4acc-b4b6-cb18eb598d4c","pid":58408,"procStart":"Fri May 29 19:01:33 2026","acquiredAt":1780092380153}
|
miniapps/navigation/miniapp.json
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"$schema": "./node_modules/@mentra/miniapp-cli/schema/miniapp.schema.json",
|
| 3 |
+
"packageName": "com.mentra.navigation",
|
| 4 |
+
"version": "1.1.37",
|
| 5 |
+
"name": "Mentra Maps",
|
| 6 |
+
"description": "Turn-by-turn navigation with visual or spoken directions.",
|
| 7 |
+
"icon": "icon.png",
|
| 8 |
+
"type": "standard",
|
| 9 |
+
"sdkVersion": "0.3.0",
|
| 10 |
+
"minHostVersion": "1.42.0",
|
| 11 |
+
"entry": {
|
| 12 |
+
"background": "background/index.js",
|
| 13 |
+
"ui": "ui/index.html"
|
| 14 |
+
},
|
| 15 |
+
"permissions": [
|
| 16 |
+
{
|
| 17 |
+
"type": "LOCATION",
|
| 18 |
+
"description": "Used for live position, compass heading, and turn-by-turn directions"
|
| 19 |
+
},
|
| 20 |
+
{
|
| 21 |
+
"type": "BACKGROUND_LOCATION",
|
| 22 |
+
"description": "Used for live position, compass heading, and turn-by-turn directions"
|
| 23 |
+
}
|
| 24 |
+
],
|
| 25 |
+
"hardwareRequirements": [
|
| 26 |
+
{
|
| 27 |
+
"type": "DISPLAY",
|
| 28 |
+
"level": "OPTIONAL",
|
| 29 |
+
"description": "Shows next maneuver and distance on glasses"
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"type": "SPEAKER",
|
| 33 |
+
"level": "OPTIONAL",
|
| 34 |
+
"description": "Speaks turn-by-turn directions on audio glasses"
|
| 35 |
+
}
|
| 36 |
+
],
|
| 37 |
+
"actions": [
|
| 38 |
+
{
|
| 39 |
+
"id": "start_navigation",
|
| 40 |
+
"description": "Start turn-by-turn navigation to a destination and provide visual or spoken directions on the glasses. Use when the user wants to go somewhere \u2014 e.g. 'navigate to Blue Bottle Coffee', 'directions to the airport', 'take me home'. Give the destination as a place name or address in `query` (it gets looked up near the user's current location); only pass latitude/longitude instead if you already have exact coordinates. Defaults to walking directions.",
|
| 41 |
+
"parameters": {
|
| 42 |
+
"type": "object",
|
| 43 |
+
"properties": {
|
| 44 |
+
"query": {
|
| 45 |
+
"type": "string",
|
| 46 |
+
"description": "The destination as a place name or address (e.g. 'Blue Bottle Coffee', '369 Hayes St, San Francisco'). Resolved via place search biased to the user's current location. Provide this OR latitude+longitude."
|
| 47 |
+
},
|
| 48 |
+
"latitude": {
|
| 49 |
+
"type": "number",
|
| 50 |
+
"description": "Destination latitude. Provide latitude+longitude together as an alternative to query, when exact coordinates are known."
|
| 51 |
+
},
|
| 52 |
+
"longitude": {
|
| 53 |
+
"type": "number",
|
| 54 |
+
"description": "Destination longitude. Provide latitude+longitude together as an alternative to query."
|
| 55 |
+
},
|
| 56 |
+
"destination_name": {
|
| 57 |
+
"type": "string",
|
| 58 |
+
"description": "Optional friendly label for the destination, shown in the UI (e.g. 'Home', 'Blue Bottle')."
|
| 59 |
+
},
|
| 60 |
+
"travel_mode": {
|
| 61 |
+
"type": "string",
|
| 62 |
+
"enum": [
|
| 63 |
+
"walking",
|
| 64 |
+
"driving",
|
| 65 |
+
"cycling",
|
| 66 |
+
"two_wheeler"
|
| 67 |
+
],
|
| 68 |
+
"description": "How the user is traveling. Defaults to 'walking'."
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
},
|
| 72 |
+
"outputSchema": {
|
| 73 |
+
"type": "object",
|
| 74 |
+
"properties": {
|
| 75 |
+
"ok": {"type": "boolean"},
|
| 76 |
+
"error": {"type": "string"},
|
| 77 |
+
"destination": {
|
| 78 |
+
"type": "object",
|
| 79 |
+
"properties": {
|
| 80 |
+
"lat": {"type": "number"},
|
| 81 |
+
"lng": {"type": "number"},
|
| 82 |
+
"name": {"type": "string"},
|
| 83 |
+
"address": {"type": "string"},
|
| 84 |
+
"placeId": {"type": "string"}
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
},
|
| 88 |
+
"required": ["ok"]
|
| 89 |
+
}
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
"id": "get_saved_addresses",
|
| 93 |
+
"description": "Get the user's saved Home and Work addresses. Use before starting navigation when the user refers to Home or Work without giving an address. Returns the configured slots only; missing slots are omitted.",
|
| 94 |
+
"parameters": {
|
| 95 |
+
"type": "object",
|
| 96 |
+
"properties": {}
|
| 97 |
+
},
|
| 98 |
+
"outputSchema": {
|
| 99 |
+
"type": "object",
|
| 100 |
+
"properties": {
|
| 101 |
+
"addresses": {
|
| 102 |
+
"type": "array",
|
| 103 |
+
"items": {
|
| 104 |
+
"type": "object",
|
| 105 |
+
"properties": {
|
| 106 |
+
"type": {"type": "string"},
|
| 107 |
+
"name": {"type": "string"},
|
| 108 |
+
"address": {"type": "string"},
|
| 109 |
+
"latitude": {"type": "number"},
|
| 110 |
+
"longitude": {"type": "number"}
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
},
|
| 115 |
+
"required": ["addresses"]
|
| 116 |
+
}
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"id": "set_saved_address",
|
| 120 |
+
"description": "Save or replace the user's Home or Work address. Use when the user asks to remember, set, or update where Home or Work is. The address is resolved with place search near the user's current location.",
|
| 121 |
+
"parameters": {
|
| 122 |
+
"type": "object",
|
| 123 |
+
"properties": {
|
| 124 |
+
"type": {
|
| 125 |
+
"type": "string",
|
| 126 |
+
"enum": [
|
| 127 |
+
"home",
|
| 128 |
+
"work"
|
| 129 |
+
],
|
| 130 |
+
"description": "Which saved-address slot to set. Only Home and Work are supported."
|
| 131 |
+
},
|
| 132 |
+
"address": {
|
| 133 |
+
"type": "string",
|
| 134 |
+
"description": "The place name or street address to save (e.g. '369 Hayes St, San Francisco')."
|
| 135 |
+
}
|
| 136 |
+
},
|
| 137 |
+
"required": [
|
| 138 |
+
"type",
|
| 139 |
+
"address"
|
| 140 |
+
]
|
| 141 |
+
},
|
| 142 |
+
"outputSchema": {
|
| 143 |
+
"type": "object",
|
| 144 |
+
"properties": {
|
| 145 |
+
"address": {
|
| 146 |
+
"type": "object",
|
| 147 |
+
"properties": {
|
| 148 |
+
"type": {"type": "string"},
|
| 149 |
+
"name": {"type": "string"},
|
| 150 |
+
"address": {"type": "string"},
|
| 151 |
+
"latitude": {"type": "number"},
|
| 152 |
+
"longitude": {"type": "number"}
|
| 153 |
+
}
|
| 154 |
+
}
|
| 155 |
+
},
|
| 156 |
+
"required": ["address"]
|
| 157 |
+
}
|
| 158 |
+
}
|
| 159 |
+
]
|
| 160 |
+
}
|
miniapps/navigation/package.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "navigation-miniapp",
|
| 3 |
+
"private": true,
|
| 4 |
+
"version": "1.0.6",
|
| 5 |
+
"scripts": {
|
| 6 |
+
"dev": "mentra-miniapp dev",
|
| 7 |
+
"build": "bun run build.ts",
|
| 8 |
+
"release": "mentra-miniapp release",
|
| 9 |
+
"pack": "mentra-miniapp pack",
|
| 10 |
+
"test": "bun test ./src",
|
| 11 |
+
"typecheck": "tsc --noEmit -p tsconfig.json"
|
| 12 |
+
},
|
| 13 |
+
"dependencies": {
|
| 14 |
+
"@mentra/miniapp": "workspace:*",
|
| 15 |
+
"@turf/turf": "^7.3.5",
|
| 16 |
+
"liquid-glass-react": "^1.1.1",
|
| 17 |
+
"lucide-react": "^0.511.0",
|
| 18 |
+
"mapbox-gl": "^3.25.0",
|
| 19 |
+
"motion": "^12.38.0",
|
| 20 |
+
"react": "^19.0.0",
|
| 21 |
+
"react-dom": "^19.0.0",
|
| 22 |
+
"zustand": "^5.0.13"
|
| 23 |
+
},
|
| 24 |
+
"devDependencies": {
|
| 25 |
+
"@mentra/miniapp-cli": "workspace:*",
|
| 26 |
+
"@types/node": "^25.8.0",
|
| 27 |
+
"@types/react": "^19",
|
| 28 |
+
"@types/react-dom": "^19",
|
| 29 |
+
"bun-plugin-tailwind": "^0.1.2",
|
| 30 |
+
"bun-types": "^1.3.14",
|
| 31 |
+
"tailwindcss": "^4.2.4"
|
| 32 |
+
}
|
| 33 |
+
}
|
miniapps/navigation/public/assets/Mentra-Navigation.png
ADDED
|
miniapps/navigation/public/assets/dest.svg
ADDED
|
|
miniapps/navigation/src/background/NavigationController.ts
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniapps/navigation/src/background/actions/savedAddressActions.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type {PlaceDetails, SavedPlace, SavedPlaceType} from "../lib/places"
|
| 2 |
+
|
| 3 |
+
const SAVED_ADDRESS_TYPES = ["home", "work"] as const
|
| 4 |
+
|
| 5 |
+
type SavedAddressStorage = {
|
| 6 |
+
getAllSavedPlaces(): Promise<SavedPlace[]>
|
| 7 |
+
addSavedPlace(place: SavedPlace): Promise<void>
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
export type SavedAddress = {
|
| 11 |
+
type: SavedPlaceType
|
| 12 |
+
name: string
|
| 13 |
+
address: string
|
| 14 |
+
latitude: number
|
| 15 |
+
longitude: number
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
export type ResolveSavedAddress = (query: string) => Promise<PlaceDetails | null>
|
| 19 |
+
|
| 20 |
+
/** Return only the fixed Home/Work slots, in a stable order for action callers. */
|
| 21 |
+
export async function getSavedAddresses(storage: SavedAddressStorage): Promise<{addresses: SavedAddress[]}> {
|
| 22 |
+
const savedPlaces = await storage.getAllSavedPlaces()
|
| 23 |
+
const addresses = SAVED_ADDRESS_TYPES.flatMap((type) => {
|
| 24 |
+
const place = savedPlaces.find((candidate) => candidate.type === type)
|
| 25 |
+
return place ? [toSavedAddress(place, type)] : []
|
| 26 |
+
})
|
| 27 |
+
return {addresses}
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
/** Resolve and replace one fixed saved-address slot. */
|
| 31 |
+
export async function setSavedAddress(
|
| 32 |
+
params: Record<string, unknown>,
|
| 33 |
+
storage: SavedAddressStorage,
|
| 34 |
+
resolveAddress: ResolveSavedAddress,
|
| 35 |
+
): Promise<{address: SavedAddress}> {
|
| 36 |
+
const type = params.type
|
| 37 |
+
if (type !== "home" && type !== "work") {
|
| 38 |
+
throw new Error("set_saved_address: 'type' must be 'home' or 'work'")
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
if (typeof params.address !== "string" || !params.address.trim()) {
|
| 42 |
+
throw new Error("set_saved_address: 'address' is required and must be a non-empty string")
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
const query = params.address.trim()
|
| 46 |
+
const place = await resolveAddress(query)
|
| 47 |
+
if (!place) {
|
| 48 |
+
throw new Error(`set_saved_address: couldn't find a place matching "${query}"`)
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
const savedPlace: SavedPlace = {
|
| 52 |
+
...place,
|
| 53 |
+
type,
|
| 54 |
+
savedName: type === "home" ? "Home" : "Work",
|
| 55 |
+
}
|
| 56 |
+
await storage.addSavedPlace(savedPlace)
|
| 57 |
+
return {address: toSavedAddress(savedPlace, type)}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
function toSavedAddress(place: SavedPlace, type: SavedPlaceType): SavedAddress {
|
| 61 |
+
return {
|
| 62 |
+
type,
|
| 63 |
+
name: place.name,
|
| 64 |
+
address: place.address,
|
| 65 |
+
latitude: place.lat,
|
| 66 |
+
longitude: place.lng,
|
| 67 |
+
}
|
| 68 |
+
}
|
miniapps/navigation/src/background/index.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Background JSContext entry point — Mentra Map miniapp.
|
| 3 |
+
*
|
| 4 |
+
* Constructed once by the MentraOS host inside the per-miniapp JSContext.
|
| 5 |
+
* `registerMiniapp(...)` wires the handler to fire after CONNECT lands;
|
| 6 |
+
* the NavigationController instantiated here lives for the entire
|
| 7 |
+
* session, surviving WebView open/close cycles.
|
| 8 |
+
*/
|
| 9 |
+
|
| 10 |
+
import {registerMiniapp} from "@mentra/miniapp/background"
|
| 11 |
+
|
| 12 |
+
import {NavigationController} from "./NavigationController"
|
| 13 |
+
|
| 14 |
+
registerMiniapp((session) => {
|
| 15 |
+
new NavigationController(session).start()
|
| 16 |
+
})
|
miniapps/navigation/src/background/lib/ArrowRenderer.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* ArrowRenderer — rasterizes a turn-direction arrow into a 1-bit BMP for the
|
| 3 |
+
* glasses HUD's left "arrow" slot.
|
| 4 |
+
*
|
| 5 |
+
* Dependency-free (runs in the background JSContext). Draws a canonical
|
| 6 |
+
* up-pointing arrow (filled shaft + head) and rotates it to the maneuver
|
| 7 |
+
* direction by sampling each output pixel in arrow-local space. Polarity
|
| 8 |
+
* matches MinimapRenderer: feature = 255 (BOLD), background = 0, so it survives
|
| 9 |
+
* the phone's invert + dither the same way the minimap does.
|
| 10 |
+
*/
|
| 11 |
+
|
| 12 |
+
import {encodeBmpBase64} from "./bmp"
|
| 13 |
+
|
| 14 |
+
const BG = 0
|
| 15 |
+
const INK = 255
|
| 16 |
+
|
| 17 |
+
/**
|
| 18 |
+
* Clockwise angle (radians, 0 = up) for a maneuver. Accepts either the arrow
|
| 19 |
+
* glyph the HUD already computes (↑ ↗ → …) or a Mapbox-style maneuver string
|
| 20 |
+
* ("turn-left", "TURN_RIGHT", "uturn", "slight left", …). Unknown → straight up.
|
| 21 |
+
*/
|
| 22 |
+
export function maneuverAngleRad(maneuver: string | null | undefined): number {
|
| 23 |
+
const deg = maneuverAngleDeg(maneuver)
|
| 24 |
+
return (deg * Math.PI) / 180
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
function maneuverAngleDeg(maneuver: string | null | undefined): number {
|
| 28 |
+
if (!maneuver) return 0
|
| 29 |
+
const m = maneuver.toLowerCase()
|
| 30 |
+
|
| 31 |
+
// Arrow glyphs the HUD already uses.
|
| 32 |
+
if (maneuver.includes("↑")) return 0
|
| 33 |
+
if (maneuver.includes("↗")) return 45
|
| 34 |
+
if (maneuver.includes("→")) return 90
|
| 35 |
+
if (maneuver.includes("↘")) return 135
|
| 36 |
+
if (maneuver.includes("↓")) return 180
|
| 37 |
+
if (maneuver.includes("↙")) return 225
|
| 38 |
+
if (maneuver.includes("←")) return 270
|
| 39 |
+
if (maneuver.includes("↖")) return 315
|
| 40 |
+
if (maneuver.includes("↩") || maneuver.includes("⤵")) return 180 // u-turn
|
| 41 |
+
|
| 42 |
+
// Text maneuver descriptors.
|
| 43 |
+
if (m.includes("uturn") || m.includes("u-turn")) return 180
|
| 44 |
+
const slight = m.includes("slight")
|
| 45 |
+
const sharp = m.includes("sharp")
|
| 46 |
+
if (m.includes("left")) return slight ? 315 : sharp ? 225 : 270
|
| 47 |
+
if (m.includes("right")) return slight ? 45 : sharp ? 135 : 90
|
| 48 |
+
return 0 // straight / depart / continue / arrive
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
/** Is (lx, ly) inside the canonical up-pointing arrow drawn in an S×S box? */
|
| 52 |
+
function insideUpArrow(lx: number, ly: number, s: number): boolean {
|
| 53 |
+
const tipY = -0.42 * s // arrowhead tip (up)
|
| 54 |
+
const headBaseY = -0.04 * s // where the head meets the shaft
|
| 55 |
+
const headHalf = 0.3 * s // half-width of the head at its base
|
| 56 |
+
const shaftHalf = 0.11 * s
|
| 57 |
+
const shaftTopY = -0.12 * s
|
| 58 |
+
const shaftBotY = 0.42 * s
|
| 59 |
+
|
| 60 |
+
// Head: triangle tapering from the base up to the tip.
|
| 61 |
+
if (ly >= tipY && ly <= headBaseY) {
|
| 62 |
+
const t = (ly - tipY) / (headBaseY - tipY) // 0 at tip → 1 at base
|
| 63 |
+
if (Math.abs(lx) <= headHalf * t) return true
|
| 64 |
+
}
|
| 65 |
+
// Shaft: rectangle.
|
| 66 |
+
if (ly >= shaftTopY && ly <= shaftBotY && Math.abs(lx) <= shaftHalf) return true
|
| 67 |
+
return false
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
/**
|
| 71 |
+
* Render a `size`×`size` arrow BMP pointing in the maneuver's direction.
|
| 72 |
+
* Returns a base64 BMP for a `session.display.render()` image element.
|
| 73 |
+
*/
|
| 74 |
+
export function renderManeuverArrowBmp(maneuver: string | null | undefined, size = 40): string {
|
| 75 |
+
const s = Math.max(8, Math.round(size))
|
| 76 |
+
const gray = new Uint8Array(s * s).fill(BG)
|
| 77 |
+
const c = (s - 1) / 2
|
| 78 |
+
const theta = maneuverAngleRad(maneuver)
|
| 79 |
+
const cosT = Math.cos(theta)
|
| 80 |
+
const sinT = Math.sin(theta)
|
| 81 |
+
|
| 82 |
+
for (let py = 0; py < s; py++) {
|
| 83 |
+
for (let px = 0; px < s; px++) {
|
| 84 |
+
const dx = px - c
|
| 85 |
+
const dy = py - c
|
| 86 |
+
// Rotate the sample point by -theta into arrow-local space (y-down screen
|
| 87 |
+
// coords): theta measured clockwise from up, so theta=90 points right.
|
| 88 |
+
const lx = dx * cosT + dy * sinT
|
| 89 |
+
const ly = -dx * sinT + dy * cosT
|
| 90 |
+
if (insideUpArrow(lx, ly, s)) gray[py * s + px] = INK
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
return encodeBmpBase64(gray, s, s)
|
| 94 |
+
}
|
miniapps/navigation/src/background/lib/MinimapRenderer.ts
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* MinimapRenderer — rasterizes a small heading-up minimap into an 8-bit
|
| 3 |
+
* grayscale BMP for the glasses HUD. Pure JS (no DOM/canvas): we draw into a
|
| 4 |
+
* raw 1-byte-per-pixel buffer and hand it to the BMP encoder.
|
| 5 |
+
*
|
| 6 |
+
* We have no street/tile data in the background JSContext, so the minimap is
|
| 7 |
+
* built entirely from what the trip already gives us — the user's position +
|
| 8 |
+
* heading, the route polyline, and the upcoming turn. To make that read like
|
| 9 |
+
* a map rather than a bare squiggle we add:
|
| 10 |
+
* - heading-up orientation (the device-forward axis always points up),
|
| 11 |
+
* - concentric distance rings (25 m / 50 m) for a sense of scale,
|
| 12 |
+
* - a rotating "N" tick so north is still findable,
|
| 13 |
+
* - the route split into traveled (dim) vs. remaining (bold),
|
| 14 |
+
* - crosswalk ticks where the route briefly leaves the sidewalk,
|
| 15 |
+
* - the upcoming-turn marker and the centered user arrow.
|
| 16 |
+
*
|
| 17 |
+
* Grays: the encoder is 8-bit, so we use a few levels — BOLD for the live
|
| 18 |
+
* route/arrow, DIM for the traveled trail, FAINT for rings/north furniture.
|
| 19 |
+
*/
|
| 20 |
+
|
| 21 |
+
import {encodeBmpBase64} from "./bmp"
|
| 22 |
+
import {detectCrossings, haversineMeters, perpDistanceMeters, type LatLng} from "./geometry"
|
| 23 |
+
|
| 24 |
+
export type MinimapInput = {
|
| 25 |
+
coords: LatLng | null
|
| 26 |
+
heading: number | null // degrees, 0 = North
|
| 27 |
+
routePoints: LatLng[] | null
|
| 28 |
+
upcomingPivot: LatLng | null
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
// How many meters from the user the minimap edge represents. The user
|
| 32 |
+
// is centered, so the visible square is ~2 * VIEW_RADIUS_M on a side.
|
| 33 |
+
export const VIEW_RADIUS_M = 80
|
| 34 |
+
|
| 35 |
+
// Grayscale levels (0 = black background ... 255 = white-hot).
|
| 36 |
+
const WHITE = 0 // background
|
| 37 |
+
const FAINT = 90 // rings, north furniture
|
| 38 |
+
const DIM = 150 // already-traveled route
|
| 39 |
+
const BOLD = 255 // live route, arrow, markers
|
| 40 |
+
|
| 41 |
+
// Distance rings drawn for scale (meters from the user).
|
| 42 |
+
const RING_RADII_M = [25, 50]
|
| 43 |
+
|
| 44 |
+
/** Equirectangular projection to local meters, user at origin. */
|
| 45 |
+
function toLocalMeters(p: LatLng, origin: LatLng): {x: number; y: number} {
|
| 46 |
+
const mPerDegLat = 111_320
|
| 47 |
+
const mPerDegLng = 111_320 * Math.cos((origin.lat * Math.PI) / 180)
|
| 48 |
+
return {
|
| 49 |
+
x: (p.lng - origin.lng) * mPerDegLng, // east+
|
| 50 |
+
y: (p.lat - origin.lat) * mPerDegLat, // north+
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
class Raster {
|
| 55 |
+
readonly buf: Uint8Array
|
| 56 |
+
constructor(readonly size: number) {
|
| 57 |
+
this.buf = new Uint8Array(size * size) // 8-bit grayscale, 1 byte/px
|
| 58 |
+
this.buf.fill(WHITE)
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
set(x: number, y: number, v: number): void {
|
| 62 |
+
if (x < 0 || y < 0 || x >= this.size || y >= this.size) return
|
| 63 |
+
this.buf[y * this.size + x] = v
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
/** Filled disc — used as a brush so lines/markers have thickness. */
|
| 67 |
+
disc(cx: number, cy: number, r: number, v: number): void {
|
| 68 |
+
const r2 = r * r
|
| 69 |
+
for (let dy = -r; dy <= r; dy++) {
|
| 70 |
+
for (let dx = -r; dx <= r; dx++) {
|
| 71 |
+
if (dx * dx + dy * dy <= r2) this.set(cx + dx, cy + dy, v)
|
| 72 |
+
}
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
/** Thick line via a disc brush stepped along the segment (Bresenham). */
|
| 77 |
+
line(x0: number, y0: number, x1: number, y1: number, v: number, thickness: number): void {
|
| 78 |
+
x0 = Math.round(x0)
|
| 79 |
+
y0 = Math.round(y0)
|
| 80 |
+
x1 = Math.round(x1)
|
| 81 |
+
y1 = Math.round(y1)
|
| 82 |
+
const r = Math.max(0, Math.floor(thickness / 2))
|
| 83 |
+
const dx = Math.abs(x1 - x0)
|
| 84 |
+
const dy = -Math.abs(y1 - y0)
|
| 85 |
+
const sx = x0 < x1 ? 1 : -1
|
| 86 |
+
const sy = y0 < y1 ? 1 : -1
|
| 87 |
+
let err = dx + dy
|
| 88 |
+
for (;;) {
|
| 89 |
+
this.disc(x0, y0, r, v)
|
| 90 |
+
if (x0 === x1 && y0 === y1) break
|
| 91 |
+
const e2 = 2 * err
|
| 92 |
+
if (e2 >= dy) {
|
| 93 |
+
err += dy
|
| 94 |
+
x0 += sx
|
| 95 |
+
}
|
| 96 |
+
if (e2 <= dx) {
|
| 97 |
+
err += dx
|
| 98 |
+
y0 += sy
|
| 99 |
+
}
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
/** 1px circle outline (midpoint algorithm) — used for the distance rings. */
|
| 104 |
+
circle(cx: number, cy: number, r: number, v: number): void {
|
| 105 |
+
if (r < 1) return
|
| 106 |
+
let x = r
|
| 107 |
+
let y = 0
|
| 108 |
+
let err = 1 - r
|
| 109 |
+
const plot8 = (px: number, py: number) => {
|
| 110 |
+
this.set(cx + px, cy + py, v)
|
| 111 |
+
this.set(cx - px, cy + py, v)
|
| 112 |
+
this.set(cx + px, cy - py, v)
|
| 113 |
+
this.set(cx - px, cy - py, v)
|
| 114 |
+
this.set(cx + py, cy + px, v)
|
| 115 |
+
this.set(cx - py, cy + px, v)
|
| 116 |
+
this.set(cx + py, cy - px, v)
|
| 117 |
+
this.set(cx - py, cy - px, v)
|
| 118 |
+
}
|
| 119 |
+
while (x >= y) {
|
| 120 |
+
plot8(x, y)
|
| 121 |
+
y++
|
| 122 |
+
if (err < 0) {
|
| 123 |
+
err += 2 * y + 1
|
| 124 |
+
} else {
|
| 125 |
+
x--
|
| 126 |
+
err += 2 * (y - x) + 1
|
| 127 |
+
}
|
| 128 |
+
}
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
/** Filled triangle (scanline fill) — the user arrow. */
|
| 132 |
+
triangle(
|
| 133 |
+
ax: number,
|
| 134 |
+
ay: number,
|
| 135 |
+
bx: number,
|
| 136 |
+
by: number,
|
| 137 |
+
cx: number,
|
| 138 |
+
cy: number,
|
| 139 |
+
v: number,
|
| 140 |
+
): void {
|
| 141 |
+
const minY = Math.floor(Math.min(ay, by, cy))
|
| 142 |
+
const maxY = Math.ceil(Math.max(ay, by, cy))
|
| 143 |
+
const area = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay)
|
| 144 |
+
if (area === 0) return
|
| 145 |
+
for (let y = minY; y <= maxY; y++) {
|
| 146 |
+
for (let x = Math.floor(Math.min(ax, bx, cx)); x <= Math.ceil(Math.max(ax, bx, cx)); x++) {
|
| 147 |
+
// Barycentric inside-test.
|
| 148 |
+
const w0 = (bx - ax) * (y - ay) - (by - ay) * (x - ax)
|
| 149 |
+
const w1 = (cx - bx) * (y - by) - (cy - by) * (x - bx)
|
| 150 |
+
const w2 = (ax - cx) * (y - cy) - (ay - cy) * (x - cx)
|
| 151 |
+
if ((w0 >= 0 && w1 >= 0 && w2 >= 0) || (w0 <= 0 && w1 <= 0 && w2 <= 0)) {
|
| 152 |
+
this.set(x, y, v)
|
| 153 |
+
}
|
| 154 |
+
}
|
| 155 |
+
}
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
/** Index of the route segment whose perpendicular distance to `me` is least. */
|
| 160 |
+
function nearestSegmentIndex(me: LatLng, route: LatLng[]): number {
|
| 161 |
+
let bestIdx = 0
|
| 162 |
+
let bestDist = Infinity
|
| 163 |
+
for (let i = 0; i < route.length - 1; i++) {
|
| 164 |
+
const d = perpDistanceMeters(me, route[i], route[i + 1])
|
| 165 |
+
if (d < bestDist) {
|
| 166 |
+
bestDist = d
|
| 167 |
+
bestIdx = i
|
| 168 |
+
}
|
| 169 |
+
}
|
| 170 |
+
return bestIdx
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
/**
|
| 174 |
+
* Render the minimap. Returns a base64 BMP, or null when there's no
|
| 175 |
+
* position fix yet (nothing meaningful to draw).
|
| 176 |
+
*/
|
| 177 |
+
export function renderMinimap(input: MinimapInput, size = 100): string | null {
|
| 178 |
+
const {coords, heading, routePoints, upcomingPivot} = input
|
| 179 |
+
if (!coords) return null
|
| 180 |
+
|
| 181 |
+
const r = new Raster(size)
|
| 182 |
+
const center = (size - 1) / 2
|
| 183 |
+
const metersPerPx = VIEW_RADIUS_M / center
|
| 184 |
+
|
| 185 |
+
// Heading-up: rotate local (east, north) by -heading so the device-forward
|
| 186 |
+
// axis maps to screen-up. Screen y grows downward, so forward maps to -y.
|
| 187 |
+
const h = ((heading ?? 0) * Math.PI) / 180
|
| 188 |
+
const sinH = Math.sin(h)
|
| 189 |
+
const cosH = Math.cos(h)
|
| 190 |
+
|
| 191 |
+
const project = (p: LatLng): {x: number; y: number} => {
|
| 192 |
+
const m = toLocalMeters(p, coords)
|
| 193 |
+
const east = m.x
|
| 194 |
+
const north = m.y
|
| 195 |
+
const rx = east * cosH - north * sinH
|
| 196 |
+
const ry = east * sinH + north * cosH
|
| 197 |
+
// rx = right of user, ry = forward of user. Map forward to up (-y).
|
| 198 |
+
return {
|
| 199 |
+
x: center + rx / metersPerPx,
|
| 200 |
+
y: center - ry / metersPerPx,
|
| 201 |
+
}
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
// Corner brackets instead of a full border — short dashes meeting at each
|
| 205 |
+
// corner (drawn before the route so the route renders on top). Inset by 1px.
|
| 206 |
+
const lo = 1
|
| 207 |
+
const hi = size - 2
|
| 208 |
+
const len = Math.max(4, Math.round(size * 0.18)) // dash length per arm
|
| 209 |
+
r.line(lo, lo, lo + len, lo, FAINT, 2)
|
| 210 |
+
r.line(lo, lo, lo, lo + len, FAINT, 2)
|
| 211 |
+
r.line(hi, lo, hi - len, lo, FAINT, 2)
|
| 212 |
+
r.line(hi, lo, hi, lo + len, FAINT, 2)
|
| 213 |
+
r.line(lo, hi, lo + len, hi, FAINT, 2)
|
| 214 |
+
r.line(lo, hi, lo, hi - len, FAINT, 2)
|
| 215 |
+
r.line(hi, hi, hi - len, hi, FAINT, 2)
|
| 216 |
+
r.line(hi, hi, hi, hi - len, FAINT, 2)
|
| 217 |
+
|
| 218 |
+
// Route polyline, split into traveled (dim) and remaining (bold) at the
|
| 219 |
+
// segment closest to the user, so the path ahead stands out.
|
| 220 |
+
if (routePoints && routePoints.length >= 2) {
|
| 221 |
+
const splitIdx = nearestSegmentIndex(coords, routePoints)
|
| 222 |
+
let prev = project(routePoints[0]!)
|
| 223 |
+
for (let i = 1; i < routePoints.length; i++) {
|
| 224 |
+
const cur = project(routePoints[i]!)
|
| 225 |
+
const traveled = i - 1 < splitIdx
|
| 226 |
+
r.line(prev.x, prev.y, cur.x, cur.y, traveled ? DIM : BOLD, traveled ? 2 : 3)
|
| 227 |
+
prev = cur
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
// Crosswalk ticks: small bold dots where the route crosses a road.
|
| 231 |
+
for (const c of detectCrossings(routePoints)) {
|
| 232 |
+
const mid = {lat: (c.start.lat + c.end.lat) / 2, lng: (c.start.lng + c.end.lng) / 2}
|
| 233 |
+
const p = project(mid)
|
| 234 |
+
r.disc(Math.round(p.x), Math.round(p.y), 1, BOLD)
|
| 235 |
+
}
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
// Upcoming-turn marker (filled disc), only when it's within view.
|
| 239 |
+
if (upcomingPivot && haversineMeters(coords, upcomingPivot) <= VIEW_RADIUS_M) {
|
| 240 |
+
const p = project(upcomingPivot)
|
| 241 |
+
r.disc(Math.round(p.x), Math.round(p.y), 3, BOLD)
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
// User arrow at center, pointing up (heading-up frame).
|
| 245 |
+
const ax = center
|
| 246 |
+
const ay = center - 9 // tip
|
| 247 |
+
const bx = center - 6
|
| 248 |
+
const by = center + 7 // bottom-left
|
| 249 |
+
const cx = center + 6
|
| 250 |
+
const cy = center + 7 // bottom-right
|
| 251 |
+
r.triangle(ax, ay, bx, by, cx, cy, BOLD)
|
| 252 |
+
|
| 253 |
+
return encodeBmpBase64(r.buf, size, size)
|
| 254 |
+
}
|
miniapps/navigation/src/background/lib/OsmLineMapRenderer.ts
ADDED
|
@@ -0,0 +1,407 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* OsmLineMapRenderer — PoC: draw the bare road network around a point as a
|
| 3 |
+
* two-tone line map for the glasses.
|
| 4 |
+
*
|
| 5 |
+
* Pipeline: Overpass (live, DEV ONLY) → highway ways as lat/lng polylines →
|
| 6 |
+
* equirectangular projection to pixels → thick Bresenham raster into an 8-bit
|
| 7 |
+
* buffer → encodeBmpBase64. Mirrors MinimapRenderer's Raster/projection so the
|
| 8 |
+
* two can converge later.
|
| 9 |
+
*
|
| 10 |
+
* ⚠️ Uses the public Overpass API directly — fine for a dev proof-of-concept,
|
| 11 |
+
* NOT for production (OSM fair-use). See issues/barebones-osm-line-map.md for
|
| 12 |
+
* the real offline-extract pipeline.
|
| 13 |
+
*/
|
| 14 |
+
|
| 15 |
+
import {encodeBmpBase64} from "./bmp"
|
| 16 |
+
import type {LatLng} from "./geometry"
|
| 17 |
+
|
| 18 |
+
const BLACK = 0 // background
|
| 19 |
+
const ROAD = 77 // road centerline (70% dimmer ≈ 30% brightness, barely visible so the route dominates)
|
| 20 |
+
const ROUTE = 255 // active route overlay (white-hot)
|
| 21 |
+
const MARKER = 255 // heading arrow fill (white-hot, drawn on top of everything)
|
| 22 |
+
const MARKER_OUTLINE = 0 // heading arrow outline (black halo so it reads over the white route)
|
| 23 |
+
const BORDER = 255 // corner-bracket edge marks (white, indicate the bitmap bounds)
|
| 24 |
+
|
| 25 |
+
/** Equirectangular projection to local meters, origin-centered. */
|
| 26 |
+
function toLocalMeters(p: LatLng, origin: LatLng): {x: number; y: number} {
|
| 27 |
+
const mPerDegLat = 111_320
|
| 28 |
+
const mPerDegLng = 111_320 * Math.cos((origin.lat * Math.PI) / 180)
|
| 29 |
+
return {
|
| 30 |
+
x: (p.lng - origin.lng) * mPerDegLng, // east+
|
| 31 |
+
y: (p.lat - origin.lat) * mPerDegLat, // north+
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
class Raster {
|
| 36 |
+
readonly buf: Uint8Array
|
| 37 |
+
constructor(
|
| 38 |
+
readonly w: number,
|
| 39 |
+
readonly h: number,
|
| 40 |
+
) {
|
| 41 |
+
this.buf = new Uint8Array(w * h)
|
| 42 |
+
this.buf.fill(BLACK)
|
| 43 |
+
}
|
| 44 |
+
private set(x: number, y: number, v: number): void {
|
| 45 |
+
if (x < 0 || y < 0 || x >= this.w || y >= this.h) return
|
| 46 |
+
this.buf[y * this.w + x] = v
|
| 47 |
+
}
|
| 48 |
+
private disc(cx: number, cy: number, r: number, v: number): void {
|
| 49 |
+
if (r <= 0) {
|
| 50 |
+
this.set(cx, cy, v)
|
| 51 |
+
return
|
| 52 |
+
}
|
| 53 |
+
const r2 = r * r
|
| 54 |
+
for (let dy = -r; dy <= r; dy++) {
|
| 55 |
+
for (let dx = -r; dx <= r; dx++) {
|
| 56 |
+
if (dx * dx + dy * dy <= r2) this.set(cx + dx, cy + dy, v)
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
/**
|
| 61 |
+
* Hollow circle outline of radius `r` and `thickness` px, centered at
|
| 62 |
+
* (cx, cy). Used for the destination marker on the route. A pixel is "on"
|
| 63 |
+
* when its distance from center falls within [r - thickness, r].
|
| 64 |
+
*/
|
| 65 |
+
ring(cx: number, cy: number, r: number, v: number, thickness: number): void {
|
| 66 |
+
cx = Math.round(cx)
|
| 67 |
+
cy = Math.round(cy)
|
| 68 |
+
const rOuter = Math.max(1, Math.round(r))
|
| 69 |
+
const rInner = Math.max(0, rOuter - Math.max(1, Math.round(thickness)))
|
| 70 |
+
const o2 = rOuter * rOuter
|
| 71 |
+
const i2 = rInner * rInner
|
| 72 |
+
for (let dy = -rOuter; dy <= rOuter; dy++) {
|
| 73 |
+
for (let dx = -rOuter; dx <= rOuter; dx++) {
|
| 74 |
+
const d2 = dx * dx + dy * dy
|
| 75 |
+
if (d2 <= o2 && d2 >= i2) this.set(cx + dx, cy + dy, v)
|
| 76 |
+
}
|
| 77 |
+
}
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
/** Filled triangle via barycentric coverage test (used for the heading arrow). */
|
| 81 |
+
triangle(
|
| 82 |
+
ax: number,
|
| 83 |
+
ay: number,
|
| 84 |
+
bx: number,
|
| 85 |
+
by: number,
|
| 86 |
+
cx: number,
|
| 87 |
+
cy: number,
|
| 88 |
+
v: number,
|
| 89 |
+
): void {
|
| 90 |
+
const minX = Math.max(0, Math.floor(Math.min(ax, bx, cx)))
|
| 91 |
+
const maxX = Math.min(this.w - 1, Math.ceil(Math.max(ax, bx, cx)))
|
| 92 |
+
const minY = Math.max(0, Math.floor(Math.min(ay, by, cy)))
|
| 93 |
+
const maxY = Math.min(this.h - 1, Math.ceil(Math.max(ay, by, cy)))
|
| 94 |
+
const area = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay)
|
| 95 |
+
if (area === 0) return // degenerate
|
| 96 |
+
for (let y = minY; y <= maxY; y++) {
|
| 97 |
+
for (let x = minX; x <= maxX; x++) {
|
| 98 |
+
const px = x + 0.5
|
| 99 |
+
const py = y + 0.5
|
| 100 |
+
const w0 = ((bx - px) * (cy - py) - (cx - px) * (by - py)) / area
|
| 101 |
+
const w1 = ((cx - px) * (ay - py) - (ax - px) * (cy - py)) / area
|
| 102 |
+
const w2 = 1 - w0 - w1
|
| 103 |
+
if (w0 >= 0 && w1 >= 0 && w2 >= 0) this.set(x, y, v)
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
/** Thick line via a disc brush stepped along the segment (Bresenham). */
|
| 109 |
+
line(x0: number, y0: number, x1: number, y1: number, v: number, thickness: number): void {
|
| 110 |
+
x0 = Math.round(x0)
|
| 111 |
+
y0 = Math.round(y0)
|
| 112 |
+
x1 = Math.round(x1)
|
| 113 |
+
y1 = Math.round(y1)
|
| 114 |
+
const r = Math.max(0, Math.floor(thickness / 2))
|
| 115 |
+
const dx = Math.abs(x1 - x0)
|
| 116 |
+
const dy = -Math.abs(y1 - y0)
|
| 117 |
+
const sx = x0 < x1 ? 1 : -1
|
| 118 |
+
const sy = y0 < y1 ? 1 : -1
|
| 119 |
+
let err = dx + dy
|
| 120 |
+
for (;;) {
|
| 121 |
+
this.disc(x0, y0, r, v)
|
| 122 |
+
if (x0 === x1 && y0 === y1) break
|
| 123 |
+
const e2 = 2 * err
|
| 124 |
+
if (e2 >= dy) {
|
| 125 |
+
err += dy
|
| 126 |
+
x0 += sx
|
| 127 |
+
}
|
| 128 |
+
if (e2 <= dx) {
|
| 129 |
+
err += dx
|
| 130 |
+
y0 += sy
|
| 131 |
+
}
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
export type OsmLineMapOptions = {
|
| 137 |
+
center: LatLng
|
| 138 |
+
width: number
|
| 139 |
+
height: number
|
| 140 |
+
/** Half-extent of the view in meters (visible area is ~2× this per axis). */
|
| 141 |
+
viewRadiusMeters?: number
|
| 142 |
+
lineWidthPx?: number
|
| 143 |
+
/** Anti-aliasing: render at this multiple of the target size, then average down. Default 3. */
|
| 144 |
+
supersample?: number
|
| 145 |
+
/** Active route polyline, drawn thicker on top of the road network. */
|
| 146 |
+
route?: LatLng[] | null
|
| 147 |
+
/** Width of the route overlay line (defaults to lineWidthPx + 2). */
|
| 148 |
+
routeWidthPx?: number
|
| 149 |
+
/**
|
| 150 |
+
* Destination point — drawn as a small hollow circle at the end of the
|
| 151 |
+
* route so the user can see where they're headed. Omit / null for none.
|
| 152 |
+
*/
|
| 153 |
+
destination?: LatLng | null
|
| 154 |
+
/**
|
| 155 |
+
* "You are here" heading marker, drawn last (on top) as a filled arrow.
|
| 156 |
+
* `at` is projected like any other point; `headingDeg` is a compass bearing
|
| 157 |
+
* (0 = north/up, 90 = east/right) — pass the route's forward direction to
|
| 158 |
+
* point the arrow the way the user should go next.
|
| 159 |
+
*/
|
| 160 |
+
marker?: {at: LatLng; headingDeg: number} | null
|
| 161 |
+
/** Arrow size in target pixels (tip-to-base length). Default 9. */
|
| 162 |
+
markerSizePx?: number
|
| 163 |
+
/**
|
| 164 |
+
* Heading-up rotation. When set, the whole map is rotated so this compass
|
| 165 |
+
* bearing (0 = north, 90 = east) points UP on the display — i.e. the map
|
| 166 |
+
* faces the user's direction of travel. Pass the route's forward bearing to
|
| 167 |
+
* keep "the way you're going" always at the top. When omitted/null the map
|
| 168 |
+
* is drawn north-up (legacy behaviour). The heading marker is drawn pointing
|
| 169 |
+
* straight up in this mode, since the rotation already aligns it with travel.
|
| 170 |
+
*/
|
| 171 |
+
rotationDeg?: number | null
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
/**
|
| 175 |
+
* Fetch highway geometry around `center` from Overpass (DEV ONLY) and return it
|
| 176 |
+
* as lat/lng polylines. One polyline per OSM way.
|
| 177 |
+
*/
|
| 178 |
+
export async function fetchOsmRoads(
|
| 179 |
+
center: LatLng,
|
| 180 |
+
viewRadiusMeters: number,
|
| 181 |
+
): Promise<LatLng[][]> {
|
| 182 |
+
// Keep only real drivable road classes — NOT footways/sidewalks/paths/
|
| 183 |
+
// cycleways/service lanes, which OSM stores as separate parallel ways and
|
| 184 |
+
// would draw as a mess of extra lines next to each street. This whitelist
|
| 185 |
+
// gives one centerline per street. `out geom` returns inline node geometry.
|
| 186 |
+
const ROAD_CLASSES =
|
| 187 |
+
"motorway|trunk|primary|secondary|tertiary|unclassified|residential|" +
|
| 188 |
+
"living_street|motorway_link|trunk_link|primary_link|secondary_link|tertiary_link"
|
| 189 |
+
const query =
|
| 190 |
+
`[out:json][timeout:25];` +
|
| 191 |
+
`way["highway"~"^(${ROAD_CLASSES})$"](around:${viewRadiusMeters},${center.lat},${center.lng});` +
|
| 192 |
+
`out geom;`
|
| 193 |
+
|
| 194 |
+
const res = await fetch("https://overpass-api.de/api/interpreter", {
|
| 195 |
+
method: "POST",
|
| 196 |
+
headers: {
|
| 197 |
+
"Content-Type": "application/x-www-form-urlencoded",
|
| 198 |
+
Accept: "application/json",
|
| 199 |
+
// Overpass rejects requests with no/blank UA (HTTP 406). Identify the app.
|
| 200 |
+
"User-Agent": "MentraOS-Navigation-PoC/0.1 (OSM line map dev test)",
|
| 201 |
+
},
|
| 202 |
+
body: `data=${encodeURIComponent(query)}`,
|
| 203 |
+
})
|
| 204 |
+
if (!res.ok) {
|
| 205 |
+
throw new Error(`Overpass HTTP ${res.status}`)
|
| 206 |
+
}
|
| 207 |
+
const json = (await res.json()) as {
|
| 208 |
+
elements?: Array<{type: string; geometry?: Array<{lat: number; lon: number}>}>
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
const polylines: LatLng[][] = []
|
| 212 |
+
for (const el of json.elements ?? []) {
|
| 213 |
+
if (el.type !== "way" || !el.geometry) continue
|
| 214 |
+
const pts = el.geometry.map((g) => ({lat: g.lat, lng: g.lon}))
|
| 215 |
+
if (pts.length >= 2) polylines.push(pts)
|
| 216 |
+
}
|
| 217 |
+
return polylines
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
/**
|
| 221 |
+
* Rasterize road polylines into a base64 grayscale BMP centered on `center`.
|
| 222 |
+
* Pure function — no network. North-up, aspect-ratio preserved, Y flipped.
|
| 223 |
+
*/
|
| 224 |
+
export function renderOsmLineMap(roads: LatLng[][], opts: OsmLineMapOptions): string {
|
| 225 |
+
const {center, width, height} = opts
|
| 226 |
+
const viewRadius = opts.viewRadiusMeters ?? 400
|
| 227 |
+
const lineWidth = opts.lineWidthPx ?? 1
|
| 228 |
+
// Supersample: draw at SS× resolution with hard pixels, then box-average down
|
| 229 |
+
// to the target size. The averaging turns staircased diagonal edges into gray
|
| 230 |
+
// pixels (anti-aliasing) — and the G2 keeps 16 gray levels, so the smoothing
|
| 231 |
+
// survives instead of being thresholded back to jaggies.
|
| 232 |
+
const ss = Math.max(1, Math.round(opts.supersample ?? 3))
|
| 233 |
+
|
| 234 |
+
const hiW = width * ss
|
| 235 |
+
const hiH = height * ss
|
| 236 |
+
const raster = new Raster(hiW, hiH)
|
| 237 |
+
|
| 238 |
+
// meters → pixels at the hi-res scale; fit 2×viewRadius into the smaller axis
|
| 239 |
+
// so aspect ratio is preserved (no stretching).
|
| 240 |
+
const pxPerMeter = Math.min(hiW, hiH) / (viewRadius * 2)
|
| 241 |
+
const cx = hiW / 2
|
| 242 |
+
const cy = hiH / 2
|
| 243 |
+
|
| 244 |
+
// Heading-up rotation. Rotate the local-meter frame so the given compass
|
| 245 |
+
// bearing points up. A bearing θ has world vector (sinθ, cosθ) in (east,
|
| 246 |
+
// north); to bring it onto +north we rotate every point by −θ. cos/sin are
|
| 247 |
+
// hoisted out of the per-point hot path. rot==null → identity (north-up).
|
| 248 |
+
const rotDeg = opts.rotationDeg ?? null
|
| 249 |
+
const rotRad = rotDeg != null ? (-rotDeg * Math.PI) / 180 : 0
|
| 250 |
+
const rCos = Math.cos(rotRad)
|
| 251 |
+
const rSin = Math.sin(rotRad)
|
| 252 |
+
|
| 253 |
+
const project = (p: LatLng): {x: number; y: number} => {
|
| 254 |
+
const m = toLocalMeters(p, center)
|
| 255 |
+
// Rotate the (east, north) meter vector before projecting to pixels so the
|
| 256 |
+
// chosen bearing ends up pointing up.
|
| 257 |
+
const ex = m.x * rCos - m.y * rSin
|
| 258 |
+
const ny = m.x * rSin + m.y * rCos
|
| 259 |
+
return {
|
| 260 |
+
x: cx + ex * pxPerMeter,
|
| 261 |
+
y: cy - ny * pxPerMeter, // Y flipped: north(-of-rotated-frame) is up
|
| 262 |
+
}
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
for (const way of roads) {
|
| 266 |
+
for (let i = 0; i < way.length - 1; i++) {
|
| 267 |
+
const a = project(way[i]!)
|
| 268 |
+
const b = project(way[i + 1]!)
|
| 269 |
+
raster.line(a.x, a.y, b.x, b.y, ROAD, lineWidth * ss)
|
| 270 |
+
}
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
// Route overlay: drawn on top, thicker, so it stands out over the network.
|
| 274 |
+
const route = opts.route
|
| 275 |
+
if (route && route.length >= 2) {
|
| 276 |
+
const routeWidth = opts.routeWidthPx ?? lineWidth + 2
|
| 277 |
+
for (let i = 0; i < route.length - 1; i++) {
|
| 278 |
+
const a = project(route[i]!)
|
| 279 |
+
const b = project(route[i + 1]!)
|
| 280 |
+
raster.line(a.x, a.y, b.x, b.y, ROUTE, routeWidth * ss)
|
| 281 |
+
}
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
// Destination: a small hollow circle at the route's end so the user can see
|
| 285 |
+
// where they're headed. Drawn after the route, before the heading marker.
|
| 286 |
+
// Kept small + thin so it's "barely visible" — just enough to read as a
|
| 287 |
+
// target without dominating the tiny minimap.
|
| 288 |
+
const destination = opts.destination
|
| 289 |
+
if (destination) {
|
| 290 |
+
const d = project(destination)
|
| 291 |
+
const ringR = 3.9 * ss // ~3.9px target radius (30% larger than the prior 3px)
|
| 292 |
+
const ringT = Math.max(1, Math.round(ss)) // ~1px stroke
|
| 293 |
+
raster.ring(d.x, d.y, ringR, ROUTE, ringT)
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
// Heading marker: a filled arrowhead at the user's position, rotated to the
|
| 297 |
+
// route's forward bearing. Drawn last so it sits on top of roads + route.
|
| 298 |
+
const marker = opts.marker
|
| 299 |
+
if (marker) {
|
| 300 |
+
const c = project(marker.at)
|
| 301 |
+
const size = (opts.markerSizePx ?? 14) * ss
|
| 302 |
+
// Bearing 0 = north = up (−y). Rotate the arrow's local geometry by it.
|
| 303 |
+
// In heading-up mode the map is already rotated to travel direction, so the
|
| 304 |
+
// arrow points straight up (effective bearing = headingDeg − rotationDeg,
|
| 305 |
+
// which is ~0 when the marker uses the same bearing the map is rotated to).
|
| 306 |
+
const effHeading = rotDeg != null ? marker.headingDeg - rotDeg : marker.headingDeg
|
| 307 |
+
const rad = (effHeading * Math.PI) / 180
|
| 308 |
+
const sin = Math.sin(rad)
|
| 309 |
+
const cos = Math.cos(rad)
|
| 310 |
+
// Local arrow (pointing up): tip ahead, two base corners behind.
|
| 311 |
+
const tip = {x: 0, y: -size * 0.6}
|
| 312 |
+
const left = {x: -size * 0.45, y: size * 0.4}
|
| 313 |
+
const right = {x: size * 0.45, y: size * 0.4}
|
| 314 |
+
const rot = (p: {x: number; y: number}) => ({
|
| 315 |
+
x: c.x + (p.x * cos - p.y * sin),
|
| 316 |
+
y: c.y + (p.x * sin + p.y * cos),
|
| 317 |
+
})
|
| 318 |
+
// Outline thickness in hi-res px (scales with supersample so it survives the
|
| 319 |
+
// downsample). Expand each vertex outward from the local centroid to grow the
|
| 320 |
+
// black halo triangle, then fill the white arrow inside it.
|
| 321 |
+
const outline = Math.max(1, Math.round(1.5 * ss))
|
| 322 |
+
const ctr = {x: 0, y: (tip.y + left.y + right.y) / 3}
|
| 323 |
+
const grow = (p: {x: number; y: number}) => {
|
| 324 |
+
const dx = p.x - ctr.x
|
| 325 |
+
const dy = p.y - ctr.y
|
| 326 |
+
const len = Math.hypot(dx, dy) || 1
|
| 327 |
+
return {x: p.x + (dx / len) * outline, y: p.y + (dy / len) * outline}
|
| 328 |
+
}
|
| 329 |
+
// Black outline first (enlarged), white fill on top.
|
| 330 |
+
const ot = rot(grow(tip))
|
| 331 |
+
const ol = rot(grow(left))
|
| 332 |
+
const or = rot(grow(right))
|
| 333 |
+
raster.triangle(ot.x, ot.y, ol.x, ol.y, or.x, or.y, MARKER_OUTLINE)
|
| 334 |
+
const t = rot(tip)
|
| 335 |
+
const l = rot(left)
|
| 336 |
+
const r = rot(right)
|
| 337 |
+
raster.triangle(t.x, t.y, l.x, l.y, r.x, r.y, MARKER)
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
// Corner brackets: short rounded L-shaped marks at each corner (not a full
|
| 341 |
+
// border). A small quarter-circle arc rounds the turn, with two straight arms
|
| 342 |
+
// running out along each edge. Drawn in hi-res so it survives the downsample.
|
| 343 |
+
{
|
| 344 |
+
const armLen = Math.round(width * 0.066) * ss // length of each bracket arm (70% shorter)
|
| 345 |
+
const r = Math.max(1, Math.round(2 * ss)) // corner radius (~2px)
|
| 346 |
+
const thick = Math.max(1, ss) // stroke thickness
|
| 347 |
+
const W = hiW - 1
|
| 348 |
+
const H = hiH - 1
|
| 349 |
+
const hLine = (x0: number, x1: number, y: number) => raster.line(x0, y, x1, y, BORDER, thick)
|
| 350 |
+
const vLine = (y0: number, y1: number, x: number) => raster.line(x, y0, x, y1, BORDER, thick)
|
| 351 |
+
// Quarter arc of radius r, centered (cx,cy), sweeping from a→b radians.
|
| 352 |
+
const arc = (cx: number, cy: number, a0: number, a1: number) => {
|
| 353 |
+
const steps = Math.max(4, Math.round(r * 2))
|
| 354 |
+
for (let i = 0; i <= steps; i++) {
|
| 355 |
+
const a = a0 + ((a1 - a0) * i) / steps
|
| 356 |
+
raster.line(cx + Math.cos(a) * r, cy + Math.sin(a) * r, cx + Math.cos(a) * r, cy + Math.sin(a) * r, BORDER, thick)
|
| 357 |
+
}
|
| 358 |
+
}
|
| 359 |
+
// Each corner: arc tangent to both edges (center r in from the corner),
|
| 360 |
+
// then straight arms from the arc's edge-tangent points outward.
|
| 361 |
+
// top-left — arc center (r,r), sweeps 180°→270°
|
| 362 |
+
arc(r, r, Math.PI, 1.5 * Math.PI)
|
| 363 |
+
hLine(r, r + armLen, 0)
|
| 364 |
+
vLine(r, r + armLen, 0)
|
| 365 |
+
// top-right — center (W-r,r), sweeps 270°→360°
|
| 366 |
+
arc(W - r, r, 1.5 * Math.PI, 2 * Math.PI)
|
| 367 |
+
hLine(W - r - armLen, W - r, 0)
|
| 368 |
+
vLine(r, r + armLen, W)
|
| 369 |
+
// bottom-left — center (r,H-r), sweeps 90°→180°
|
| 370 |
+
arc(r, H - r, 0.5 * Math.PI, Math.PI)
|
| 371 |
+
hLine(r, r + armLen, H)
|
| 372 |
+
vLine(H - r - armLen, H - r, 0)
|
| 373 |
+
// bottom-right — center (W-r,H-r), sweeps 0°→90°
|
| 374 |
+
arc(W - r, H - r, 0, 0.5 * Math.PI)
|
| 375 |
+
hLine(W - r - armLen, W - r, H)
|
| 376 |
+
vLine(H - r - armLen, H - r, W)
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
// Box-downsample hi-res → target: each output pixel is the average of its
|
| 380 |
+
// ss×ss source block, producing smooth grayscale edges.
|
| 381 |
+
const out = new Uint8Array(width * height)
|
| 382 |
+
if (ss === 1) {
|
| 383 |
+
out.set(raster.buf)
|
| 384 |
+
} else {
|
| 385 |
+
const area = ss * ss
|
| 386 |
+
for (let oy = 0; oy < height; oy++) {
|
| 387 |
+
for (let ox = 0; ox < width; ox++) {
|
| 388 |
+
let sum = 0
|
| 389 |
+
for (let sy = 0; sy < ss; sy++) {
|
| 390 |
+
const row = (oy * ss + sy) * hiW + ox * ss
|
| 391 |
+
for (let sx = 0; sx < ss; sx++) sum += raster.buf[row + sx]!
|
| 392 |
+
}
|
| 393 |
+
out[oy * width + ox] = Math.round(sum / area)
|
| 394 |
+
}
|
| 395 |
+
}
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
return encodeBmpBase64(out, width, height)
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
/** Convenience: fetch + render in one call. */
|
| 402 |
+
export async function buildOsmLineMap(opts: OsmLineMapOptions): Promise<string> {
|
| 403 |
+
const viewRadius = opts.viewRadiusMeters ?? 400
|
| 404 |
+
const roads = await fetchOsmRoads(opts.center, viewRadius)
|
| 405 |
+
console.log(`[OSM-MAP] fetched ${roads.length} road ways around ${opts.center.lat},${opts.center.lng}`)
|
| 406 |
+
return renderOsmLineMap(roads, opts)
|
| 407 |
+
}
|
miniapps/navigation/src/background/lib/bmp.ts
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
*
|
| 4 |
+
* The glasses render in 1-bit monochrome, and the phone decodes the
|
| 5 |
+
* bitmap via iOS `UIImage(data:)` / Android BitmapFactory. A hand-rolled
|
| 6 |
+
* stored-DEFLATE PNG is rejected by ImageIO ("could not decode image"),
|
| 7 |
+
* and 24-bit is wasteful, so we emit an uncompressed 1-bit BMP — the same
|
| 8 |
+
* shape the cloud SDK's bitmap-utils produces, which both platforms decode.
|
| 9 |
+
*
|
| 10 |
+
* BMP is bottom-up. 1-bit pixels are packed MSB-first, 8 px/byte, with a
|
| 11 |
+
* 2-entry color table (index 0 = black, index 1 = white) and each row
|
| 12 |
+
* padded to a 4-byte boundary.
|
| 13 |
+
*/
|
| 14 |
+
|
| 15 |
+
const FILE_HEADER = 14
|
| 16 |
+
const DIB_HEADER = 40
|
| 17 |
+
const COLOR_TABLE = 8 // 2 colors * 4 bytes
|
| 18 |
+
const PIXEL_OFFSET = FILE_HEADER + DIB_HEADER + COLOR_TABLE // 62
|
| 19 |
+
|
| 20 |
+
function setU16LE(buf: Uint8Array, off: number, v: number): void {
|
| 21 |
+
buf[off] = v & 0xff
|
| 22 |
+
buf[off + 1] = (v >>> 8) & 0xff
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
function setU32LE(buf: Uint8Array, off: number, v: number): void {
|
| 26 |
+
buf[off] = v & 0xff
|
| 27 |
+
buf[off + 1] = (v >>> 8) & 0xff
|
| 28 |
+
buf[off + 2] = (v >>> 16) & 0xff
|
| 29 |
+
buf[off + 3] = (v >>> 24) & 0xff
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
function base64(bytes: Uint8Array): string {
|
| 33 |
+
let binary = ""
|
| 34 |
+
const CHUNK = 0x8000
|
| 35 |
+
for (let i = 0; i < bytes.length; i += CHUNK) {
|
| 36 |
+
const slice = bytes.subarray(i, i + CHUNK)
|
| 37 |
+
binary += String.fromCharCode.apply(null, slice as unknown as number[])
|
| 38 |
+
}
|
| 39 |
+
return btoa(binary)
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
/**
|
| 43 |
+
* Encode an 8-bit grayscale pixel buffer (row-major, top-down, 1 byte/px)
|
| 44 |
+
* as a base64 8-bit BMP string. Uses a 256-entry grayscale palette so each
|
| 45 |
+
* pixel byte indexes its own gray level (0 = black, 255 = white).
|
| 46 |
+
*/
|
| 47 |
+
export function encodeBmpBase64(gray: Uint8Array, width: number, height: number): string {
|
| 48 |
+
if (gray.length !== width * height) {
|
| 49 |
+
throw new Error(`encodeBmpBase64: expected ${width * height} bytes, got ${gray.length}`)
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
const GRAY_COLOR_TABLE = 256 * 4 // 256 colors * 4 bytes
|
| 53 |
+
const grayPixelOffset = FILE_HEADER + DIB_HEADER + GRAY_COLOR_TABLE // 1078
|
| 54 |
+
const rowSize = Math.ceil(width / 4) * 4 // 1 byte/px, 4-byte aligned
|
| 55 |
+
const pixelDataSize = rowSize * height
|
| 56 |
+
const fileSize = grayPixelOffset + pixelDataSize
|
| 57 |
+
|
| 58 |
+
const buf = new Uint8Array(fileSize)
|
| 59 |
+
|
| 60 |
+
// BMP file header (14 bytes)
|
| 61 |
+
buf[0] = 0x42 // 'B'
|
| 62 |
+
buf[1] = 0x4d // 'M'
|
| 63 |
+
setU32LE(buf, 2, fileSize)
|
| 64 |
+
setU32LE(buf, 6, 0) // reserved
|
| 65 |
+
setU32LE(buf, 10, grayPixelOffset)
|
| 66 |
+
|
| 67 |
+
// DIB header (BITMAPINFOHEADER, 40 bytes)
|
| 68 |
+
setU32LE(buf, 14, DIB_HEADER)
|
| 69 |
+
setU32LE(buf, 18, width)
|
| 70 |
+
setU32LE(buf, 22, height) // positive = bottom-up
|
| 71 |
+
setU16LE(buf, 26, 1) // planes
|
| 72 |
+
setU16LE(buf, 28, 8) // bits per pixel
|
| 73 |
+
setU32LE(buf, 30, 0) // compression: BI_RGB (none)
|
| 74 |
+
setU32LE(buf, 34, pixelDataSize)
|
| 75 |
+
setU32LE(buf, 38, 2835) // X px/meter (~72 DPI)
|
| 76 |
+
setU32LE(buf, 42, 2835) // Y px/meter
|
| 77 |
+
setU32LE(buf, 46, 256) // colors used
|
| 78 |
+
setU32LE(buf, 50, 256) // important colors
|
| 79 |
+
|
| 80 |
+
// Grayscale palette (1024 bytes): entry i = gray level i (BGRA).
|
| 81 |
+
for (let i = 0; i < 256; i++) {
|
| 82 |
+
const off = FILE_HEADER + DIB_HEADER + i * 4
|
| 83 |
+
buf[off] = i // B
|
| 84 |
+
buf[off + 1] = i // G
|
| 85 |
+
buf[off + 2] = i // R
|
| 86 |
+
buf[off + 3] = 0x00 // reserved
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
// Pixel data — bottom-up rows, 1 byte/px.
|
| 90 |
+
for (let y = 0; y < height; y++) {
|
| 91 |
+
const srcRow = y * width // source is top-down
|
| 92 |
+
const destRow = grayPixelOffset + (height - 1 - y) * rowSize // write bottom-up
|
| 93 |
+
for (let x = 0; x < width; x++) {
|
| 94 |
+
buf[destRow + x] = gray[srcRow + x]!
|
| 95 |
+
}
|
| 96 |
+
}
|
| 97 |
+
return base64(buf)
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
/**
|
| 101 |
+
* Build an 8-bit grayscale gradient test image as a base64 BMP. The width is
|
| 102 |
+
* split into 17 equal vertical bars whose gray level steps 0 → 16 left to
|
| 103 |
+
* right — handy for verifying the glasses' grayscale rendering.
|
| 104 |
+
*/
|
| 105 |
+
export function gradientTestImageBase64(width: number, height: number): string {
|
| 106 |
+
const BARS = 255 // levels 0..16
|
| 107 |
+
const gray = new Uint8Array(width * height)
|
| 108 |
+
for (let x = 0; x < width; x++) {
|
| 109 |
+
const level = Math.min(BARS - 1, Math.floor((x / width) * BARS))
|
| 110 |
+
for (let y = 0; y < height; y++) {
|
| 111 |
+
gray[y * width + x] = level
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
return encodeBmpBase64(gray, width, height)
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
/**
|
| 118 |
+
* Build an 8-bit grayscale test image of just the rectangle BORDER (outline)
|
| 119 |
+
* as a base64 BMP — a white frame `thickness` px wide on a black background.
|
| 120 |
+
* Handy for seeing the exact bounds/size of a bitmap container on the glasses.
|
| 121 |
+
*/
|
| 122 |
+
export function borderTestImageBase64(width: number, height: number, thickness = 2): string {
|
| 123 |
+
const t = Math.max(1, Math.min(thickness, Math.floor(Math.min(width, height) / 2)))
|
| 124 |
+
const gray = new Uint8Array(width * height) // 0 = black fill
|
| 125 |
+
for (let y = 0; y < height; y++) {
|
| 126 |
+
for (let x = 0; x < width; x++) {
|
| 127 |
+
const onBorder = x < t || x >= width - t || y < t || y >= height - t
|
| 128 |
+
if (onBorder) gray[y * width + x] = 255 // white edge
|
| 129 |
+
}
|
| 130 |
+
}
|
| 131 |
+
return encodeBmpBase64(gray, width, height)
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
/* -------------------------------------------------------------------------- */
|
| 135 |
+
/* Minimal 5×7 bitmap font — enough to draw short uppercase test labels into a */
|
| 136 |
+
/* bitmap. Each glyph is 7 rows × 5 bits (MSB = leftmost column). */
|
| 137 |
+
|
| 138 |
+
const GLYPH_W = 5
|
| 139 |
+
const GLYPH_H = 7
|
| 140 |
+
const GLYPH_GAP = 1 // blank column between glyphs
|
| 141 |
+
|
| 142 |
+
// Bit rows per glyph, top→bottom. 1 = on (white). Only the chars we need.
|
| 143 |
+
const FONT: Record<string, number[]> = {
|
| 144 |
+
" ": [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
|
| 145 |
+
A: [0x0e, 0x11, 0x11, 0x1f, 0x11, 0x11, 0x11],
|
| 146 |
+
B: [0x1e, 0x11, 0x11, 0x1e, 0x11, 0x11, 0x1e],
|
| 147 |
+
C: [0x0e, 0x11, 0x10, 0x10, 0x10, 0x11, 0x0e],
|
| 148 |
+
D: [0x1e, 0x11, 0x11, 0x11, 0x11, 0x11, 0x1e],
|
| 149 |
+
E: [0x1f, 0x10, 0x10, 0x1e, 0x10, 0x10, 0x1f],
|
| 150 |
+
F: [0x1f, 0x10, 0x10, 0x1e, 0x10, 0x10, 0x10],
|
| 151 |
+
G: [0x0e, 0x11, 0x10, 0x17, 0x11, 0x11, 0x0e],
|
| 152 |
+
H: [0x11, 0x11, 0x11, 0x1f, 0x11, 0x11, 0x11],
|
| 153 |
+
I: [0x0e, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0e],
|
| 154 |
+
L: [0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1f],
|
| 155 |
+
M: [0x11, 0x1b, 0x15, 0x15, 0x11, 0x11, 0x11],
|
| 156 |
+
N: [0x11, 0x19, 0x15, 0x13, 0x11, 0x11, 0x11],
|
| 157 |
+
O: [0x0e, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e],
|
| 158 |
+
P: [0x1e, 0x11, 0x11, 0x1e, 0x10, 0x10, 0x10],
|
| 159 |
+
R: [0x1e, 0x11, 0x11, 0x1e, 0x14, 0x12, 0x11],
|
| 160 |
+
S: [0x0f, 0x10, 0x10, 0x0e, 0x01, 0x01, 0x1e],
|
| 161 |
+
T: [0x1f, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04],
|
| 162 |
+
U: [0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e],
|
| 163 |
+
W: [0x11, 0x11, 0x11, 0x15, 0x15, 0x1b, 0x11],
|
| 164 |
+
"0": [0x0e, 0x11, 0x13, 0x15, 0x19, 0x11, 0x0e],
|
| 165 |
+
"1": [0x04, 0x0c, 0x04, 0x04, 0x04, 0x04, 0x0e],
|
| 166 |
+
"2": [0x0e, 0x11, 0x01, 0x02, 0x04, 0x08, 0x1f],
|
| 167 |
+
"3": [0x1f, 0x02, 0x04, 0x02, 0x01, 0x11, 0x0e],
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
/** Width in px of a string rendered at `scale` (incl. inter-glyph gaps). */
|
| 171 |
+
function measureText(text: string, scale: number): number {
|
| 172 |
+
const n = text.length
|
| 173 |
+
if (n === 0) return 0
|
| 174 |
+
return (n * GLYPH_W + (n - 1) * GLYPH_GAP) * scale
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
/** Blit a string into `gray` (8-bit, row-major) at top-left (ox, oy), `scale`×. */
|
| 178 |
+
function drawText(
|
| 179 |
+
gray: Uint8Array,
|
| 180 |
+
imgW: number,
|
| 181 |
+
imgH: number,
|
| 182 |
+
text: string,
|
| 183 |
+
ox: number,
|
| 184 |
+
oy: number,
|
| 185 |
+
scale: number,
|
| 186 |
+
value = 255,
|
| 187 |
+
): void {
|
| 188 |
+
let penX = ox
|
| 189 |
+
for (const ch of text.toUpperCase()) {
|
| 190 |
+
const glyph = FONT[ch] ?? FONT[" "]!
|
| 191 |
+
for (let row = 0; row < GLYPH_H; row++) {
|
| 192 |
+
const bits = glyph[row]!
|
| 193 |
+
for (let col = 0; col < GLYPH_W; col++) {
|
| 194 |
+
if ((bits >> (GLYPH_W - 1 - col)) & 1) {
|
| 195 |
+
// Scale up each lit cell into a scale×scale block.
|
| 196 |
+
for (let dy = 0; dy < scale; dy++) {
|
| 197 |
+
for (let dx = 0; dx < scale; dx++) {
|
| 198 |
+
const px = penX + col * scale + dx
|
| 199 |
+
const py = oy + row * scale + dy
|
| 200 |
+
if (px >= 0 && px < imgW && py >= 0 && py < imgH) gray[py * imgW + px] = value
|
| 201 |
+
}
|
| 202 |
+
}
|
| 203 |
+
}
|
| 204 |
+
}
|
| 205 |
+
}
|
| 206 |
+
penX += (GLYPH_W + GLYPH_GAP) * scale
|
| 207 |
+
}
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
/**
|
| 211 |
+
* Bordered box with `text` drawn centered inside it, as a base64 BMP. Same
|
| 212 |
+
* white-frame-on-black look as [borderTestImageBase64], but with a label baked
|
| 213 |
+
* into the bitmap (no separate positioned-text layout needed).
|
| 214 |
+
*/
|
| 215 |
+
export function labeledBoxImageBase64(
|
| 216 |
+
width: number,
|
| 217 |
+
height: number,
|
| 218 |
+
text: string,
|
| 219 |
+
thickness = 2,
|
| 220 |
+
): string {
|
| 221 |
+
const t = Math.max(1, Math.min(thickness, Math.floor(Math.min(width, height) / 2)))
|
| 222 |
+
const gray = new Uint8Array(width * height) // 0 = black fill
|
| 223 |
+
for (let y = 0; y < height; y++) {
|
| 224 |
+
for (let x = 0; x < width; x++) {
|
| 225 |
+
const onBorder = x < t || x >= width - t || y < t || y >= height - t
|
| 226 |
+
if (onBorder) gray[y * width + x] = 255
|
| 227 |
+
}
|
| 228 |
+
}
|
| 229 |
+
// Pick the largest integer scale that fits the text inside the border padding.
|
| 230 |
+
const padX = t + 2
|
| 231 |
+
const padY = t + 2
|
| 232 |
+
const maxW = width - padX * 2
|
| 233 |
+
const maxH = height - padY * 2
|
| 234 |
+
let scale = Math.max(1, Math.floor(maxH / GLYPH_H))
|
| 235 |
+
while (scale > 1 && measureText(text, scale) > maxW) scale--
|
| 236 |
+
const tw = measureText(text, scale)
|
| 237 |
+
const th = GLYPH_H * scale
|
| 238 |
+
const ox = Math.round((width - tw) / 2)
|
| 239 |
+
const oy = Math.round((height - th) / 2)
|
| 240 |
+
drawText(gray, width, height, text, ox, oy, scale, 255)
|
| 241 |
+
return encodeBmpBase64(gray, width, height)
|
| 242 |
+
}
|
miniapps/navigation/src/background/lib/capabilities.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type {GlassesCapabilitySnapshot} from "../../shared/types"
|
| 2 |
+
|
| 3 |
+
/**
|
| 4 |
+
* Normalize the host's glasses capability payload for navigation.
|
| 5 |
+
*
|
| 6 |
+
* Display capability fields are optional because older hosts do not send all
|
| 7 |
+
* of them. Absence means "unknown", so preserve Navigation's established
|
| 8 |
+
* positioned HUD unless the host explicitly says positioning is unsupported.
|
| 9 |
+
* Current G1 and Z100 profiles send `canPosition: false` and take the compact
|
| 10 |
+
* text fallback; current G2 and Mentra Display profiles send `true`.
|
| 11 |
+
*/
|
| 12 |
+
export function readGlassesCapabilities(capabilities: unknown): GlassesCapabilitySnapshot {
|
| 13 |
+
const record = (capabilities ?? {}) as Record<string, unknown>
|
| 14 |
+
const display =
|
| 15 |
+
record.display && typeof record.display === "object" ? (record.display as Record<string, unknown>) : null
|
| 16 |
+
const modelName = typeof record.modelName === "string" ? record.modelName : null
|
| 17 |
+
|
| 18 |
+
return {
|
| 19 |
+
modelName,
|
| 20 |
+
hasDisplay: record.hasDisplay === true || !!display,
|
| 21 |
+
canPosition: display != null && display.canPosition !== false,
|
| 22 |
+
hasSpeaker: record.hasSpeaker === true,
|
| 23 |
+
hasButton: record.hasButton === true,
|
| 24 |
+
}
|
| 25 |
+
}
|
miniapps/navigation/src/background/lib/formatDistance.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type {UnitSystem} from "../../shared/types"
|
| 2 |
+
|
| 3 |
+
const FEET_PER_METER = 3.28084
|
| 4 |
+
const FEET_PER_MILE = 5280
|
| 5 |
+
|
| 6 |
+
/**
|
| 7 |
+
* Compact distance string in the requested unit system.
|
| 8 |
+
*
|
| 9 |
+
* metric → "750 m", "1.2 km" (m below 1000 m, then km)
|
| 10 |
+
* imperial → "820 ft", "0.8 mi" (ft below 0.1 mi ≈ 528 ft, then mi)
|
| 11 |
+
*
|
| 12 |
+
* "—" for unknown (negative) input. Clamps very-small values to the
|
| 13 |
+
* smallest whole unit ("1 m" / "1 ft") so we never display "0 m". The
|
| 14 |
+
* `unit` param defaults to "metric" so legacy call sites stay valid.
|
| 15 |
+
*/
|
| 16 |
+
export function formatDistance(meters: number, unit: UnitSystem = "metric"): string {
|
| 17 |
+
if (meters < 0) return "—"
|
| 18 |
+
if (unit === "imperial") {
|
| 19 |
+
const feet = meters * FEET_PER_METER
|
| 20 |
+
// Switch to miles once we're past ~0.1 mi so short distances stay
|
| 21 |
+
// legible in feet rather than rounding to "0.0 mi".
|
| 22 |
+
if (feet < FEET_PER_MILE * 0.1) return `${Math.max(1, Math.round(feet))} ft`
|
| 23 |
+
const miles = feet / FEET_PER_MILE
|
| 24 |
+
return `${miles.toFixed(miles < 10 ? 1 : 0)} mi`
|
| 25 |
+
}
|
| 26 |
+
if (meters < 1000) return `${Math.max(1, Math.round(meters))} m`
|
| 27 |
+
const km = meters / 1000
|
| 28 |
+
return `${km.toFixed(km < 10 ? 1 : 0)} km`
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
/** Compact duration string ("45 sec", "14 min", "1 h 5 min", "—" for unknown). */
|
| 32 |
+
export function formatDuration(seconds: number): string {
|
| 33 |
+
if (seconds < 0) return "—"
|
| 34 |
+
if (seconds < 60) return `${seconds} sec`
|
| 35 |
+
const minutes = Math.round(seconds / 60)
|
| 36 |
+
if (minutes < 60) return `${minutes} min`
|
| 37 |
+
const hours = Math.floor(minutes / 60)
|
| 38 |
+
const remMin = minutes % 60
|
| 39 |
+
return remMin === 0 ? `${hours} h` : `${hours} h ${remMin} min`
|
| 40 |
+
}
|
miniapps/navigation/src/background/lib/geometry.ts
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Lightweight geo helpers used by the map and orientation logic.
|
| 3 |
+
* Small-angle approximations are fine for the segment lengths we deal
|
| 4 |
+
* with (10s–100s of meters within a single trip).
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
export type LatLng = {lat: number; lng: number}
|
| 8 |
+
|
| 9 |
+
/** Great-circle distance in meters (haversine). */
|
| 10 |
+
export function haversineMeters(a: LatLng, b: LatLng): number {
|
| 11 |
+
const R = 6_371_000
|
| 12 |
+
const toRad = (d: number) => (d * Math.PI) / 180
|
| 13 |
+
const dLat = toRad(b.lat - a.lat)
|
| 14 |
+
const dLng = toRad(b.lng - a.lng)
|
| 15 |
+
const lat1 = toRad(a.lat)
|
| 16 |
+
const lat2 = toRad(b.lat)
|
| 17 |
+
const x = Math.sin(dLat / 2) ** 2 + Math.sin(dLng / 2) ** 2 * Math.cos(lat1) * Math.cos(lat2)
|
| 18 |
+
return 2 * R * Math.asin(Math.sqrt(x))
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
/** Compass bearing from `a` to `b`, in degrees [0, 360). */
|
| 22 |
+
export function bearingDeg(a: LatLng, b: LatLng): number {
|
| 23 |
+
const toRad = (d: number) => (d * Math.PI) / 180
|
| 24 |
+
const toDeg = (r: number) => (r * 180) / Math.PI
|
| 25 |
+
const lat1 = toRad(a.lat)
|
| 26 |
+
const lat2 = toRad(b.lat)
|
| 27 |
+
const dLng = toRad(b.lng - a.lng)
|
| 28 |
+
const y = Math.sin(dLng) * Math.cos(lat2)
|
| 29 |
+
const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLng)
|
| 30 |
+
return (toDeg(Math.atan2(y, x)) + 360) % 360
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
/** Smallest signed difference: target - actual, in [-180, 180]. */
|
| 34 |
+
export function signedAngleDiff(target: number, actual: number): number {
|
| 35 |
+
return ((target - actual + 540) % 360) - 180
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
/** Eight-point cardinal name from a degree heading. */
|
| 39 |
+
export function cardinal(deg: number): string {
|
| 40 |
+
const names = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
|
| 41 |
+
const idx = Math.round((((deg % 360) + 360) % 360) / 45) % 8
|
| 42 |
+
return names[idx]
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
/**
|
| 46 |
+
* Approximate perpendicular distance from `p` to segment `a→b`, in meters.
|
| 47 |
+
* Good enough for picking the closest segment of a polyline.
|
| 48 |
+
*/
|
| 49 |
+
export function perpDistanceMeters(p: LatLng, a: LatLng, b: LatLng): number {
|
| 50 |
+
const mPerDegLat = 111_320
|
| 51 |
+
const mPerDegLng = 111_320 * Math.cos((a.lat * Math.PI) / 180)
|
| 52 |
+
const ax = 0
|
| 53 |
+
const ay = 0
|
| 54 |
+
const bx = (b.lng - a.lng) * mPerDegLng
|
| 55 |
+
const by = (b.lat - a.lat) * mPerDegLat
|
| 56 |
+
const px = (p.lng - a.lng) * mPerDegLng
|
| 57 |
+
const py = (p.lat - a.lat) * mPerDegLat
|
| 58 |
+
const dx = bx - ax
|
| 59 |
+
const dy = by - ay
|
| 60 |
+
const len2 = dx * dx + dy * dy
|
| 61 |
+
if (len2 === 0) return Math.sqrt(px * px + py * py)
|
| 62 |
+
let t = (px * dx + py * dy) / len2
|
| 63 |
+
t = Math.max(0, Math.min(1, t))
|
| 64 |
+
const projx = ax + t * dx
|
| 65 |
+
const projy = ay + t * dy
|
| 66 |
+
return Math.sqrt((px - projx) * (px - projx) + (py - projy) * (py - projy))
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
/**
|
| 70 |
+
* Distance in meters from `p` to the nearest point on a polyline.
|
| 71 |
+
* Returns null for empty / single-point polylines. Walks every segment;
|
| 72 |
+
* fine for the segment counts we deal with (tens to low hundreds).
|
| 73 |
+
*/
|
| 74 |
+
export function distanceToPolylineMeters(p: LatLng, points: LatLng[] | null): number | null {
|
| 75 |
+
if (!points || points.length < 2) return null
|
| 76 |
+
let best = Infinity
|
| 77 |
+
for (let i = 0; i < points.length - 1; i++) {
|
| 78 |
+
const d = perpDistanceMeters(p, points[i], points[i + 1])
|
| 79 |
+
if (d < best) best = d
|
| 80 |
+
}
|
| 81 |
+
return best === Infinity ? null : best
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
/**
|
| 85 |
+
* Bearing of the route at the user's current position. We find the
|
| 86 |
+
* polyline segment closest to `me` and return its endpoint bearing —
|
| 87 |
+
* i.e. which way the route wants you to face right now.
|
| 88 |
+
*/
|
| 89 |
+
export function nextSegmentBearing(me: LatLng | null, route: LatLng[] | null): number | null {
|
| 90 |
+
if (!me || !route || route.length < 2) return null
|
| 91 |
+
let bestIdx = 0
|
| 92 |
+
let bestDist = Infinity
|
| 93 |
+
for (let i = 0; i < route.length - 1; i++) {
|
| 94 |
+
const d = perpDistanceMeters(me, route[i], route[i + 1])
|
| 95 |
+
if (d < bestDist) {
|
| 96 |
+
bestDist = d
|
| 97 |
+
bestIdx = i
|
| 98 |
+
}
|
| 99 |
+
}
|
| 100 |
+
return bearingDeg(route[bestIdx], route[bestIdx + 1])
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
/**
|
| 104 |
+
* Remaining route distance in meters: from the user's projection onto
|
| 105 |
+
* the route polyline to the route's endpoint. Walks the polyline from
|
| 106 |
+
* the closest segment forward, summing the rest of that segment plus
|
| 107 |
+
* every segment after it. Returns null for empty / single-point routes.
|
| 108 |
+
*
|
| 109 |
+
* Used to fire arrival when the user is within N meters of the route's
|
| 110 |
+
* end *along the route*, rather than straight-line to the destination
|
| 111 |
+
* pin (the pin can sit a few meters off the walkable polyline).
|
| 112 |
+
*/
|
| 113 |
+
/**
|
| 114 |
+
* The portion of the route the user has NOT walked yet: the user's projected
|
| 115 |
+
* point onto the closest segment, followed by every route point after it.
|
| 116 |
+
* Used to draw only the route AHEAD on the minimap (the part behind the user
|
| 117 |
+
* is trimmed as they pass it). Returns the full route if `me` is null, and
|
| 118 |
+
* null for empty / single-point routes.
|
| 119 |
+
*/
|
| 120 |
+
export function remainingRoutePoints(me: LatLng | null, route: LatLng[] | null): LatLng[] | null {
|
| 121 |
+
if (!route || route.length < 2) return route ?? null
|
| 122 |
+
if (!me) return route
|
| 123 |
+
// Closest segment (same scan as remainingRouteMeters / nextSegmentBearing).
|
| 124 |
+
let bestIdx = 0
|
| 125 |
+
let bestDist = Infinity
|
| 126 |
+
for (let i = 0; i < route.length - 1; i++) {
|
| 127 |
+
const d = perpDistanceMeters(me, route[i], route[i + 1])
|
| 128 |
+
if (d < bestDist) {
|
| 129 |
+
bestDist = d
|
| 130 |
+
bestIdx = i
|
| 131 |
+
}
|
| 132 |
+
}
|
| 133 |
+
// Project `me` onto that segment to get the exact "where I am on the route"
|
| 134 |
+
// point, so the trimmed line starts right at the user, not at the segment's
|
| 135 |
+
// start vertex (which could be several meters behind).
|
| 136 |
+
const seg = route[bestIdx]
|
| 137 |
+
const next = route[bestIdx + 1]
|
| 138 |
+
const mPerDegLat = 111_320
|
| 139 |
+
const mPerDegLng = 111_320 * Math.cos((seg.lat * Math.PI) / 180)
|
| 140 |
+
const bx = (next.lng - seg.lng) * mPerDegLng
|
| 141 |
+
const by = (next.lat - seg.lat) * mPerDegLat
|
| 142 |
+
const px = (me.lng - seg.lng) * mPerDegLng
|
| 143 |
+
const py = (me.lat - seg.lat) * mPerDegLat
|
| 144 |
+
const len2 = bx * bx + by * by
|
| 145 |
+
let t = len2 > 0 ? (px * bx + py * by) / len2 : 0
|
| 146 |
+
t = Math.max(0, Math.min(1, t))
|
| 147 |
+
const projected: LatLng = {
|
| 148 |
+
lat: seg.lat + (next.lat - seg.lat) * t,
|
| 149 |
+
lng: seg.lng + (next.lng - seg.lng) * t,
|
| 150 |
+
}
|
| 151 |
+
// projected point + the rest of the route ahead.
|
| 152 |
+
return [projected, ...route.slice(bestIdx + 1)]
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
export function remainingRouteMeters(me: LatLng | null, route: LatLng[] | null): number | null {
|
| 156 |
+
if (!me || !route || route.length < 2) return null
|
| 157 |
+
let bestIdx = 0
|
| 158 |
+
let bestDist = Infinity
|
| 159 |
+
for (let i = 0; i < route.length - 1; i++) {
|
| 160 |
+
const d = perpDistanceMeters(me, route[i], route[i + 1])
|
| 161 |
+
if (d < bestDist) {
|
| 162 |
+
bestDist = d
|
| 163 |
+
bestIdx = i
|
| 164 |
+
}
|
| 165 |
+
}
|
| 166 |
+
const mPerDegLat = 111_320
|
| 167 |
+
const seg = route[bestIdx]
|
| 168 |
+
const next = route[bestIdx + 1]
|
| 169 |
+
const mPerDegLng = 111_320 * Math.cos((seg.lat * Math.PI) / 180)
|
| 170 |
+
const ax = 0
|
| 171 |
+
const ay = 0
|
| 172 |
+
const bx = (next.lng - seg.lng) * mPerDegLng
|
| 173 |
+
const by = (next.lat - seg.lat) * mPerDegLat
|
| 174 |
+
const px = (me.lng - seg.lng) * mPerDegLng
|
| 175 |
+
const py = (me.lat - seg.lat) * mPerDegLat
|
| 176 |
+
const dx = bx - ax
|
| 177 |
+
const dy = by - ay
|
| 178 |
+
const len2 = dx * dx + dy * dy
|
| 179 |
+
let t = len2 > 0 ? (px * dx + py * dy) / len2 : 0
|
| 180 |
+
t = Math.max(0, Math.min(1, t))
|
| 181 |
+
const projx = ax + t * dx
|
| 182 |
+
const projy = ay + t * dy
|
| 183 |
+
let remaining = Math.sqrt((bx - projx) * (bx - projx) + (by - projy) * (by - projy))
|
| 184 |
+
for (let i = bestIdx + 1; i < route.length - 1; i++) {
|
| 185 |
+
remaining += haversineMeters(route[i], route[i + 1])
|
| 186 |
+
}
|
| 187 |
+
return remaining
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
/**
|
| 191 |
+
* "left" or "right": which side of the final route segment the
|
| 192 |
+
* destination pin sits on, from the perspective of a walker facing
|
| 193 |
+
* along that segment. Used at arrival to tell the user which way to
|
| 194 |
+
* turn their head to see the destination.
|
| 195 |
+
*
|
| 196 |
+
* Returns null when the route is too short or the pin sits exactly on
|
| 197 |
+
* the segment's bearing line (rare; cross-product is zero).
|
| 198 |
+
*/
|
| 199 |
+
export function sideOfFinalSegment(route: LatLng[] | null, pin: LatLng | null): "left" | "right" | null {
|
| 200 |
+
if (!route || route.length < 2 || !pin) return null
|
| 201 |
+
const b = route[route.length - 1]
|
| 202 |
+
// Find the last DISTINCT point before the endpoint. Mapbox routes often end
|
| 203 |
+
// with duplicate trailing coordinates (b === route[length-2]); using one of
|
| 204 |
+
// those would make `segBearing` a meaningless bearing-between-identical-
|
| 205 |
+
// points (≈0/North), which flips left/right at random. Walk back until we
|
| 206 |
+
// find a point at least ~0.5 m from b so the segment has a real direction.
|
| 207 |
+
let a: LatLng | null = null
|
| 208 |
+
for (let i = route.length - 2; i >= 0; i--) {
|
| 209 |
+
if (haversineMeters(route[i], b) > 0.5) {
|
| 210 |
+
a = route[i]
|
| 211 |
+
break
|
| 212 |
+
}
|
| 213 |
+
}
|
| 214 |
+
if (!a) return null // whole tail collapses onto b — no usable bearing
|
| 215 |
+
const segBearing = bearingDeg(a, b)
|
| 216 |
+
const pinBearing = bearingDeg(b, pin)
|
| 217 |
+
const diff = signedAngleDiff(pinBearing, segBearing)
|
| 218 |
+
if (diff === 0) return null
|
| 219 |
+
// Compass bearings increase CLOCKWISE, so a destination to the walker's
|
| 220 |
+
// RIGHT has a larger bearing than the travel direction → positive diff.
|
| 221 |
+
return diff > 0 ? "right" : "left"
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
export type Crossing = {
|
| 225 |
+
/** Start of the crossing leg (curb on the user's current sidewalk). */
|
| 226 |
+
start: LatLng
|
| 227 |
+
/** End of the crossing leg (curb on the other sidewalk). */
|
| 228 |
+
end: LatLng
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
/**
|
| 232 |
+
* Detect crossing micro-steps in a route polyline. A "crossing" is a
|
| 233 |
+
* short polyline leg (<maxLegMeters) that turns sharply (>minBendDeg)
|
| 234 |
+
* away from the previous leg and then turns sharply back to roughly
|
| 235 |
+
* the original direction on the leg after — characteristic of a
|
| 236 |
+
* crosswalk where the planned route briefly leaves the sidewalk to
|
| 237 |
+
* traverse the road, then resumes along the opposite curb.
|
| 238 |
+
*
|
| 239 |
+
* Heuristic-based; tweakable via `maxLegMeters` and `minBendDeg`.
|
| 240 |
+
* Mirrors the same algorithm as the Android NavigationManager's
|
| 241 |
+
* stripCrossings() so the dev-panel visualization and the simulator
|
| 242 |
+
* walker agree on what counts as a crossing.
|
| 243 |
+
*/
|
| 244 |
+
export function detectCrossings(
|
| 245 |
+
points: LatLng[],
|
| 246 |
+
opts: {maxLegMeters?: number; minBendDeg?: number; minSidewalkSwitchMeters?: number} = {},
|
| 247 |
+
): Crossing[] {
|
| 248 |
+
const maxLeg = opts.maxLegMeters ?? 25
|
| 249 |
+
const minBend = opts.minBendDeg ?? 60
|
| 250 |
+
// Reject pass-through crosswalk traces at intersections where the
|
| 251 |
+
// user stays on the same sidewalk. A real sidewalk-switch leaves the
|
| 252 |
+
// post-crossing polyline ≥4m perpendicular from the pre-crossing line.
|
| 253 |
+
const minSwitch = opts.minSidewalkSwitchMeters ?? 4
|
| 254 |
+
const sampleMeters = 10
|
| 255 |
+
const out: Crossing[] = []
|
| 256 |
+
if (points.length < 4) return out
|
| 257 |
+
for (let i = 1; i < points.length - 2; i++) {
|
| 258 |
+
const prev = points[i - 1]
|
| 259 |
+
const here = points[i]
|
| 260 |
+
const next = points[i + 1]
|
| 261 |
+
const afterNext = points[i + 2]
|
| 262 |
+
const legOut = haversineMeters(here, next)
|
| 263 |
+
if (legOut >= maxLeg) continue
|
| 264 |
+
const bearIn = bearingDeg(prev, here)
|
| 265 |
+
const bearOut = bearingDeg(here, next)
|
| 266 |
+
const bend = Math.abs(((bearIn - bearOut + 540) % 360) - 180)
|
| 267 |
+
if (bend <= minBend) continue
|
| 268 |
+
const bearAfter = bearingDeg(next, afterNext)
|
| 269 |
+
const bendBack = Math.abs(((bearOut - bearAfter + 540) % 360) - 180)
|
| 270 |
+
const inOutDelta = Math.abs(((bearIn - bearAfter + 540) % 360) - 180)
|
| 271 |
+
if (!(bendBack > minBend && inOutDelta < minBend)) continue
|
| 272 |
+
const sample = walkAlongPolyline(points, i + 1, sampleMeters)
|
| 273 |
+
if (!sample) continue
|
| 274 |
+
const displacement = perpDistanceMeters(sample, prev, here)
|
| 275 |
+
if (displacement < minSwitch) continue
|
| 276 |
+
out.push({start: here, end: next})
|
| 277 |
+
}
|
| 278 |
+
return out
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
function walkAlongPolyline(points: LatLng[], startIdx: number, meters: number): LatLng | null {
|
| 282 |
+
if (startIdx >= points.length - 1) return null
|
| 283 |
+
let remaining = meters
|
| 284 |
+
let idx = startIdx
|
| 285 |
+
while (idx < points.length - 1) {
|
| 286 |
+
const a = points[idx]
|
| 287 |
+
const b = points[idx + 1]
|
| 288 |
+
const segLen = haversineMeters(a, b)
|
| 289 |
+
if (remaining <= segLen) {
|
| 290 |
+
const t = segLen > 0 ? remaining / segLen : 0
|
| 291 |
+
return {lat: a.lat + (b.lat - a.lat) * t, lng: a.lng + (b.lng - a.lng) * t}
|
| 292 |
+
}
|
| 293 |
+
remaining -= segLen
|
| 294 |
+
idx++
|
| 295 |
+
}
|
| 296 |
+
return null
|
| 297 |
+
}
|
miniapps/navigation/src/background/lib/places.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Places client — type-ahead autocomplete + details for the search box.
|
| 3 |
+
*
|
| 4 |
+
* Routes entirely through the miniapp SDK (`session.navigation.place*`), which
|
| 5 |
+
* the host bridges to the v2 cloud maps service (Mapbox Search Box today). There
|
| 6 |
+
* is NO backend Worker and no provider key in this bundle — the cloud holds the
|
| 7 |
+
* token, caches, and bills. This replaced the old Google-Places secret-proxy
|
| 8 |
+
* Worker.
|
| 9 |
+
*
|
| 10 |
+
* One PlacesSession represents one autocomplete-then-details flow. The provider
|
| 11 |
+
* bills the autocomplete keystrokes + the final details call as a single search
|
| 12 |
+
* session when the same `sessionToken` is sent on all of them, so callers should
|
| 13 |
+
* create a session per "search box opening" and `reset()` it after the user
|
| 14 |
+
* picks a result.
|
| 15 |
+
*/
|
| 16 |
+
|
| 17 |
+
import type {MiniappSession} from "@mentra/miniapp"
|
| 18 |
+
|
| 19 |
+
export type PlaceSuggestion = {
|
| 20 |
+
placeId: string
|
| 21 |
+
mainText: string
|
| 22 |
+
secondaryText: string
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
export type PlaceDetails = {
|
| 26 |
+
placeId: string
|
| 27 |
+
lat: number
|
| 28 |
+
lng: number
|
| 29 |
+
name: string
|
| 30 |
+
address: string
|
| 31 |
+
/** User-defined label when saved as a favorite or custom place */
|
| 32 |
+
savedName?: string
|
| 33 |
+
/**
|
| 34 |
+
* True while a reverse-geocode is in flight for a dropped pin. The
|
| 35 |
+
* `name` / `address` fields are placeholders (raw lat/lng) until this
|
| 36 |
+
* flips back to false. UI consumers render a skeleton while this is
|
| 37 |
+
* true so the user doesn't see the bare coordinates flash on screen
|
| 38 |
+
* before the real address lands.
|
| 39 |
+
*/
|
| 40 |
+
isGeocoding?: boolean
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
/**
|
| 44 |
+
* A place saved by the user. Optionally tagged as `"home"` or `"work"`
|
| 45 |
+
* so the IdleDrawer can surface those two as fixed quick-access slots.
|
| 46 |
+
* Anything else is just an untagged saved place — there is no
|
| 47 |
+
* favorite/custom distinction anymore.
|
| 48 |
+
*/
|
| 49 |
+
export type SavedPlaceType = "home" | "work"
|
| 50 |
+
|
| 51 |
+
export type SavedPlace = PlaceDetails & {
|
| 52 |
+
type?: SavedPlaceType
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
export class PlacesSession {
|
| 56 |
+
private token: string
|
| 57 |
+
|
| 58 |
+
constructor(private readonly session: MiniappSession) {
|
| 59 |
+
this.token = newToken()
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
/**
|
| 63 |
+
* Type-ahead suggestions for `input`, optionally biased toward `near`. Goes
|
| 64 |
+
* through the SDK → host → v2 cloud maps (Mapbox Search Box). The same
|
| 65 |
+
* `token` is sent on every keystroke + the final `details()` so the cloud
|
| 66 |
+
* bills one search session.
|
| 67 |
+
*/
|
| 68 |
+
async autocomplete(input: string, near?: {lat: number; lng: number}): Promise<PlaceSuggestion[]> {
|
| 69 |
+
if (!input.trim()) return []
|
| 70 |
+
const res = await this.session.navigation.placeAutocomplete({
|
| 71 |
+
query: input,
|
| 72 |
+
near,
|
| 73 |
+
sessionToken: this.token,
|
| 74 |
+
})
|
| 75 |
+
if (!res.ok) throw new Error(res.error || "autocomplete failed")
|
| 76 |
+
return res.suggestions ?? []
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
/** Resolve a picked suggestion to coordinates. Uses the same session token. */
|
| 80 |
+
async details(placeId: string): Promise<PlaceDetails> {
|
| 81 |
+
const res = await this.session.navigation.placeDetails({
|
| 82 |
+
placeId,
|
| 83 |
+
sessionToken: this.token,
|
| 84 |
+
})
|
| 85 |
+
if (!res.ok || !res.place) throw new Error(res.error || "details failed")
|
| 86 |
+
const {placeId: id, name, address, lat, lng} = res.place
|
| 87 |
+
return {placeId: id, name, address, lat, lng}
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
/** Rotate the token after a completed pick so the next search is a new
|
| 91 |
+
* billing session. */
|
| 92 |
+
reset(): void {
|
| 93 |
+
this.token = newToken()
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
function newToken(): string {
|
| 98 |
+
if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
|
| 99 |
+
return crypto.randomUUID()
|
| 100 |
+
}
|
| 101 |
+
return Math.random().toString(36).slice(2) + Date.now().toString(36)
|
| 102 |
+
}
|
| 103 |
+
|
miniapps/navigation/src/background/lib/rdpSmooth.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Ramer-Douglas-Peucker polyline simplification for visual rendering.
|
| 3 |
+
*
|
| 4 |
+
* The pivot-detection variant of RDP moved into `@mentra/miniapp`'s
|
| 5 |
+
* internal geometry helpers when pivot tracking was lifted into the
|
| 6 |
+
* SDK. This file is the small leftover that NavMap uses to smooth
|
| 7 |
+
* the visible route polyline before drawing it on the map — pure
|
| 8 |
+
* presentation, no semantics.
|
| 9 |
+
*/
|
| 10 |
+
|
| 11 |
+
import type {LatLng} from "./geometry"
|
| 12 |
+
|
| 13 |
+
/**
|
| 14 |
+
* Return a simplified copy of `points` for rendering. Drops vertices
|
| 15 |
+
* whose perpendicular distance to the line through their neighbors
|
| 16 |
+
* is below `epsilonMeters`. Default 6m — slightly looser than the
|
| 17 |
+
* pivot extractor's 5m because the map only needs visual fidelity.
|
| 18 |
+
*/
|
| 19 |
+
export function rdpSmooth(points: LatLng[], epsilonMeters: number = 6): LatLng[] {
|
| 20 |
+
if (points.length < 3) return points.slice()
|
| 21 |
+
const kept = rdpSimplify(points, epsilonMeters)
|
| 22 |
+
return kept.map((i) => points[i])
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
function rdpSimplify(points: LatLng[], epsilonMeters: number): number[] {
|
| 26 |
+
if (points.length < 3) return points.map((_, i) => i)
|
| 27 |
+
|
| 28 |
+
const keep = new Array(points.length).fill(false)
|
| 29 |
+
keep[0] = true
|
| 30 |
+
keep[points.length - 1] = true
|
| 31 |
+
|
| 32 |
+
const stack: Array<[number, number]> = [[0, points.length - 1]]
|
| 33 |
+
while (stack.length) {
|
| 34 |
+
const [lo, hi] = stack.pop()!
|
| 35 |
+
let maxDist = 0
|
| 36 |
+
let maxIdx = -1
|
| 37 |
+
for (let i = lo + 1; i < hi; i++) {
|
| 38 |
+
const d = perpDistMeters(points[i], points[lo], points[hi])
|
| 39 |
+
if (d > maxDist) {
|
| 40 |
+
maxDist = d
|
| 41 |
+
maxIdx = i
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
if (maxIdx !== -1 && maxDist > epsilonMeters) {
|
| 45 |
+
keep[maxIdx] = true
|
| 46 |
+
stack.push([lo, maxIdx], [maxIdx, hi])
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
const out: number[] = []
|
| 51 |
+
for (let i = 0; i < keep.length; i++) if (keep[i]) out.push(i)
|
| 52 |
+
return out
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
function perpDistMeters(p: LatLng, a: LatLng, b: LatLng): number {
|
| 56 |
+
const mPerDegLat = 111_320
|
| 57 |
+
const mPerDegLng = 111_320 * Math.cos((a.lat * Math.PI) / 180)
|
| 58 |
+
const bx = (b.lng - a.lng) * mPerDegLng
|
| 59 |
+
const by = (b.lat - a.lat) * mPerDegLat
|
| 60 |
+
const px = (p.lng - a.lng) * mPerDegLng
|
| 61 |
+
const py = (p.lat - a.lat) * mPerDegLat
|
| 62 |
+
const len = Math.sqrt(bx * bx + by * by)
|
| 63 |
+
if (len === 0) return Math.sqrt(px * px + py * py)
|
| 64 |
+
return Math.abs(bx * -py - -px * by) / len
|
| 65 |
+
}
|
miniapps/navigation/src/background/lib/testBitmap.ts
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniapps/navigation/src/background/managers/AudioGuidanceManager.ts
ADDED
|
@@ -0,0 +1,565 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type {NavStatus, UnitSystem, VoiceGuidanceMode} from "../../shared/types"
|
| 2 |
+
|
| 3 |
+
export type AudioTravelMode = "walking" | "driving" | "cycling" | "two_wheeler"
|
| 4 |
+
|
| 5 |
+
type SpeakerPort = {
|
| 6 |
+
speak(
|
| 7 |
+
text: string,
|
| 8 |
+
options?: {stopOtherAudio?: boolean; voice_settings?: Record<string, unknown>},
|
| 9 |
+
): Promise<{completed: boolean}>
|
| 10 |
+
stop(): void
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
export type AudioGuidanceInput = {
|
| 14 |
+
status: NavStatus
|
| 15 |
+
running: boolean
|
| 16 |
+
routeRevision: number
|
| 17 |
+
pivotIndex: number | null
|
| 18 |
+
maneuverType: string | null
|
| 19 |
+
instruction: string | null
|
| 20 |
+
distanceMeters: number | null
|
| 21 |
+
offRoute: boolean
|
| 22 |
+
destinationName: string | null
|
| 23 |
+
arrivalSide: "left" | "right" | null
|
| 24 |
+
travelMode: AudioTravelMode
|
| 25 |
+
unitSystem: UnitSystem
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
type Prompt = {
|
| 29 |
+
text: string
|
| 30 |
+
priority: number
|
| 31 |
+
expiresAt: number
|
| 32 |
+
maneuverKey?: string
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
type Thresholds = {prepareMeters: number; nowMeters: number}
|
| 36 |
+
|
| 37 |
+
const THRESHOLDS: Record<AudioTravelMode, Thresholds> = {
|
| 38 |
+
walking: {prepareMeters: 60, nowMeters: 10},
|
| 39 |
+
cycling: {prepareMeters: 200, nowMeters: 25},
|
| 40 |
+
driving: {prepareMeters: 500, nowMeters: 60},
|
| 41 |
+
two_wheeler: {prepareMeters: 350, nowMeters: 50},
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
const MIN_AUTOMATIC_PROMPT_GAP_MS = 3_500
|
| 45 |
+
const STARTUP_OFF_ROUTE_GRACE_MS = 15_000
|
| 46 |
+
const TURN_TYPES = new Set([
|
| 47 |
+
"TURN_LEFT",
|
| 48 |
+
"TURN_RIGHT",
|
| 49 |
+
"SLIGHT_LEFT",
|
| 50 |
+
"SLIGHT_RIGHT",
|
| 51 |
+
"SHARP_LEFT",
|
| 52 |
+
"SHARP_RIGHT",
|
| 53 |
+
"U_TURN",
|
| 54 |
+
"CROSS_STREET",
|
| 55 |
+
])
|
| 56 |
+
|
| 57 |
+
/**
|
| 58 |
+
* Converts the navigation engine's ~1 Hz/per-metre progress stream into a
|
| 59 |
+
* deliberately sparse spoken experience: one preparation prompt and one
|
| 60 |
+
* action prompt per maneuver, plus deduplicated lifecycle alerts.
|
| 61 |
+
*/
|
| 62 |
+
export class AudioGuidanceManager {
|
| 63 |
+
private available = false
|
| 64 |
+
private mode: VoiceGuidanceMode = "off"
|
| 65 |
+
private tripActive = false
|
| 66 |
+
private tripConfirmed = false
|
| 67 |
+
private tripStartedAt: number | null = null
|
| 68 |
+
private startupOffRouteSuppressed = false
|
| 69 |
+
private startupRerouteSuppressed = false
|
| 70 |
+
private allowImplicitResume = true
|
| 71 |
+
private latestUnconfirmedInput: AudioGuidanceInput | null = null
|
| 72 |
+
private lastStatus: NavStatus = "idle"
|
| 73 |
+
private lastOffRoute = false
|
| 74 |
+
private currentManeuverKey: string | null = null
|
| 75 |
+
private currentPivotIndex: number | null = null
|
| 76 |
+
private currentRepeatPhrase: string | null = null
|
| 77 |
+
private lastSignature = ""
|
| 78 |
+
private lastDistance: number | null = null
|
| 79 |
+
private syntheticSequence = 0
|
| 80 |
+
private spokenStages = new Set<string>()
|
| 81 |
+
private speakingGeneration = 0
|
| 82 |
+
private speaking = false
|
| 83 |
+
private speakingPriority = 0
|
| 84 |
+
private speakingManeuverKey: string | null = null
|
| 85 |
+
private pending: Prompt | null = null
|
| 86 |
+
private pendingTimer: ReturnType<typeof setTimeout> | null = null
|
| 87 |
+
private lastPromptStartedAt = 0
|
| 88 |
+
private disposed = false
|
| 89 |
+
|
| 90 |
+
constructor(
|
| 91 |
+
private readonly speaker: SpeakerPort,
|
| 92 |
+
private readonly log: (message: string) => void = () => {},
|
| 93 |
+
) {}
|
| 94 |
+
|
| 95 |
+
setAvailable(available: boolean): void {
|
| 96 |
+
this.available = available
|
| 97 |
+
if (!available) this.stopSpeech()
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
setMode(mode: VoiceGuidanceMode): void {
|
| 101 |
+
this.mode = mode
|
| 102 |
+
if (mode === "off") this.stopSpeech()
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
beginTrip(): void {
|
| 106 |
+
this.stopSpeech()
|
| 107 |
+
this.tripActive = true
|
| 108 |
+
this.tripConfirmed = false
|
| 109 |
+
this.tripStartedAt = null
|
| 110 |
+
this.startupOffRouteSuppressed = false
|
| 111 |
+
this.startupRerouteSuppressed = false
|
| 112 |
+
this.allowImplicitResume = false
|
| 113 |
+
this.latestUnconfirmedInput = null
|
| 114 |
+
this.lastStatus = "navigating"
|
| 115 |
+
this.lastOffRoute = false
|
| 116 |
+
this.resetManeuverState()
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
confirmTripStarted(destinationName: string | null): void {
|
| 120 |
+
if (!this.tripActive) return
|
| 121 |
+
this.tripConfirmed = true
|
| 122 |
+
this.tripStartedAt = Date.now()
|
| 123 |
+
if (this.canSpeak()) {
|
| 124 |
+
const destination = cleanSpokenText(destinationName)
|
| 125 |
+
this.enqueue({
|
| 126 |
+
text: destination ? `Navigation started to ${destination}.` : "Navigation started.",
|
| 127 |
+
// Lead the first maneuver cue, but still allow arrival to interrupt.
|
| 128 |
+
priority: 100,
|
| 129 |
+
expiresAt: Date.now() + 12_000,
|
| 130 |
+
})
|
| 131 |
+
}
|
| 132 |
+
const latest = this.latestUnconfirmedInput
|
| 133 |
+
this.latestUnconfirmedInput = null
|
| 134 |
+
if (latest) this.observe(latest)
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
observe(input: AudioGuidanceInput): void {
|
| 138 |
+
if (this.disposed) return
|
| 139 |
+
|
| 140 |
+
if (!input.running && input.status === "idle") {
|
| 141 |
+
if (this.tripActive) this.endTrip()
|
| 142 |
+
this.lastStatus = input.status
|
| 143 |
+
return
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
// Keep the manager usable for an already-running session restored by the
|
| 147 |
+
// host, where beginTrip()/confirmTripStarted() did not occur in this JS
|
| 148 |
+
// lifetime. Explicit new trips still enter the unconfirmed path below.
|
| 149 |
+
if (this.allowImplicitResume && !this.tripActive && input.running && input.status === "navigating") {
|
| 150 |
+
this.tripActive = true
|
| 151 |
+
this.tripConfirmed = true
|
| 152 |
+
this.tripStartedAt = null
|
| 153 |
+
this.allowImplicitResume = false
|
| 154 |
+
}
|
| 155 |
+
if (!this.tripActive) {
|
| 156 |
+
this.lastStatus = input.status
|
| 157 |
+
return
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
// The native engine can emit its first maneuver before navigation.start()
|
| 161 |
+
// resolves. Keep only the freshest update and replay it after the start
|
| 162 |
+
// confirmation so spoken guidance never leads with a turn instruction.
|
| 163 |
+
if (this.tripActive && !this.tripConfirmed) {
|
| 164 |
+
this.latestUnconfirmedInput = input
|
| 165 |
+
return
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
const startupOffRouteGraceActive = this.isStartupOffRouteGraceActive()
|
| 169 |
+
const enteredRerouting = input.status === "rerouting" && this.lastStatus !== "rerouting"
|
| 170 |
+
const deferredStartupReroute =
|
| 171 |
+
input.status === "rerouting" && this.startupRerouteSuppressed && !startupOffRouteGraceActive
|
| 172 |
+
if (enteredRerouting || deferredStartupReroute) {
|
| 173 |
+
this.discardStaleManeuverPrompts()
|
| 174 |
+
this.currentManeuverKey = null
|
| 175 |
+
this.currentRepeatPhrase = "Rerouting."
|
| 176 |
+
if (startupOffRouteGraceActive) {
|
| 177 |
+
this.startupRerouteSuppressed = true
|
| 178 |
+
} else {
|
| 179 |
+
this.startupRerouteSuppressed = false
|
| 180 |
+
this.enqueue({text: "Off route. Rerouting.", priority: 100, expiresAt: Date.now() + 10_000})
|
| 181 |
+
}
|
| 182 |
+
} else if (input.status !== "rerouting") {
|
| 183 |
+
this.startupRerouteSuppressed = false
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
if (input.status === "arrived" && this.lastStatus !== "arrived") {
|
| 187 |
+
const destination = cleanSpokenText(input.destinationName)
|
| 188 |
+
const side = input.arrivalSide ? `, on your ${input.arrivalSide}` : ""
|
| 189 |
+
const phrase = destination ? `You have arrived at ${destination}${side}.` : `You have arrived${side}.`
|
| 190 |
+
this.currentManeuverKey = null
|
| 191 |
+
this.currentRepeatPhrase = phrase
|
| 192 |
+
this.enqueue({text: phrase, priority: 110, expiresAt: Date.now() + 20_000})
|
| 193 |
+
this.tripActive = false
|
| 194 |
+
this.allowImplicitResume = false
|
| 195 |
+
this.lastOffRoute = false
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
this.lastStatus = input.status
|
| 199 |
+
if (!input.running || input.status !== "navigating") return
|
| 200 |
+
this.tripActive = true
|
| 201 |
+
|
| 202 |
+
// A route can initially snap to a walkable road tens of metres from an
|
| 203 |
+
// indoor or noisy GPS fix. Keep real rerouting active, but do not speak
|
| 204 |
+
// either an off-route warning or maneuver guidance derived from that
|
| 205 |
+
// unstable fix. A stable on-route update resumes the current maneuver
|
| 206 |
+
// afresh; if the condition persists past the grace period, the normal
|
| 207 |
+
// one-shot warning becomes eligible.
|
| 208 |
+
if (input.offRoute && startupOffRouteGraceActive) {
|
| 209 |
+
if (!this.startupOffRouteSuppressed) {
|
| 210 |
+
this.discardStaleManeuverPrompts()
|
| 211 |
+
this.currentManeuverKey = null
|
| 212 |
+
this.currentPivotIndex = null
|
| 213 |
+
this.currentRepeatPhrase = null
|
| 214 |
+
}
|
| 215 |
+
this.startupOffRouteSuppressed = true
|
| 216 |
+
return
|
| 217 |
+
}
|
| 218 |
+
if (input.offRoute) {
|
| 219 |
+
this.startupOffRouteSuppressed = false
|
| 220 |
+
if (!this.lastOffRoute) {
|
| 221 |
+
const phrase = "You are off route. Go back to the route."
|
| 222 |
+
this.discardStaleManeuverPrompts()
|
| 223 |
+
this.currentManeuverKey = null
|
| 224 |
+
this.currentRepeatPhrase = phrase
|
| 225 |
+
this.enqueue({text: phrase, priority: 100, expiresAt: Date.now() + 12_000})
|
| 226 |
+
}
|
| 227 |
+
this.lastOffRoute = true
|
| 228 |
+
return
|
| 229 |
+
}
|
| 230 |
+
if (this.lastOffRoute || this.startupOffRouteSuppressed) {
|
| 231 |
+
// Returning to the route should evaluate the current maneuver afresh;
|
| 232 |
+
// stages spoken before the deviation no longer describe the live spot.
|
| 233 |
+
this.currentManeuverKey = null
|
| 234 |
+
this.currentPivotIndex = null
|
| 235 |
+
}
|
| 236 |
+
this.startupOffRouteSuppressed = false
|
| 237 |
+
this.lastOffRoute = false
|
| 238 |
+
|
| 239 |
+
const instruction = cleanSpokenText(input.instruction)
|
| 240 |
+
const maneuverType = input.maneuverType?.toUpperCase() ?? null
|
| 241 |
+
const distance = validDistance(input.distanceMeters)
|
| 242 |
+
if (!instruction || !maneuverType) return
|
| 243 |
+
|
| 244 |
+
const signature = `${input.routeRevision}|${maneuverType}|${instruction.toLowerCase()}`
|
| 245 |
+
const thresholds = THRESHOLDS[input.travelMode]
|
| 246 |
+
// Consecutive identical turns without pivot metadata advance by jumping
|
| 247 |
+
// from a near-zero distance to the next turn's much larger distance.
|
| 248 |
+
const previousNowSpoken =
|
| 249 |
+
this.currentManeuverKey != null && this.spokenStages.has(`${this.currentManeuverKey}|now`)
|
| 250 |
+
const distanceRebounded =
|
| 251 |
+
input.pivotIndex == null &&
|
| 252 |
+
signature === this.lastSignature &&
|
| 253 |
+
distance != null &&
|
| 254 |
+
this.lastDistance != null &&
|
| 255 |
+
(distance > this.lastDistance + Math.max(25, thresholds.prepareMeters / 2) ||
|
| 256 |
+
(previousNowSpoken &&
|
| 257 |
+
distance > thresholds.nowMeters &&
|
| 258 |
+
distance > this.lastDistance + Math.max(10, thresholds.nowMeters / 2)))
|
| 259 |
+
|
| 260 |
+
const pivotChanged =
|
| 261 |
+
this.currentPivotIndex != null && input.pivotIndex != null && input.pivotIndex !== this.currentPivotIndex
|
| 262 |
+
const newSemanticManeuver =
|
| 263 |
+
this.currentManeuverKey == null || signature !== this.lastSignature || pivotChanged || distanceRebounded
|
| 264 |
+
if (newSemanticManeuver) {
|
| 265 |
+
this.discardStaleManeuverPrompts()
|
| 266 |
+
this.syntheticSequence += 1
|
| 267 |
+
this.currentManeuverKey = `${signature}|semantic-${this.syntheticSequence}`
|
| 268 |
+
this.currentPivotIndex = input.pivotIndex
|
| 269 |
+
} else if (this.currentPivotIndex == null && input.pivotIndex != null) {
|
| 270 |
+
// The same maneuver first arrived before PivotEngine bound metadata.
|
| 271 |
+
// Attach the pivot without changing its identity or replaying stages.
|
| 272 |
+
this.currentPivotIndex = input.pivotIndex
|
| 273 |
+
}
|
| 274 |
+
this.lastSignature = signature
|
| 275 |
+
this.lastDistance = distance
|
| 276 |
+
const maneuverKey = this.currentManeuverKey
|
| 277 |
+
if (!maneuverKey) return
|
| 278 |
+
|
| 279 |
+
const preparePhrase = buildPreparationPhrase(instruction, distance, input.unitSystem)
|
| 280 |
+
const nowPhrase = buildNowPhrase(instruction, maneuverType)
|
| 281 |
+
|
| 282 |
+
if (maneuverType === "ARRIVE") {
|
| 283 |
+
const approachPhrase =
|
| 284 |
+
distance == null ? "Approaching your destination." : `Destination in ${formatSpokenDistance(distance, input.unitSystem)}.`
|
| 285 |
+
this.currentRepeatPhrase = approachPhrase
|
| 286 |
+
const approachStage = `${maneuverKey}|prepare`
|
| 287 |
+
if (
|
| 288 |
+
this.canSpeak() &&
|
| 289 |
+
this.mode === "full" &&
|
| 290 |
+
distance != null &&
|
| 291 |
+
distance <= thresholds.prepareMeters &&
|
| 292 |
+
!this.spokenStages.has(approachStage)
|
| 293 |
+
) {
|
| 294 |
+
this.spokenStages.add(approachStage)
|
| 295 |
+
this.enqueue({
|
| 296 |
+
text: approachPhrase,
|
| 297 |
+
priority: 30,
|
| 298 |
+
expiresAt: Date.now() + 15_000,
|
| 299 |
+
maneuverKey,
|
| 300 |
+
})
|
| 301 |
+
}
|
| 302 |
+
return
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
this.currentRepeatPhrase =
|
| 306 |
+
distance != null && distance <= thresholds.nowMeters && TURN_TYPES.has(maneuverType) ? nowPhrase : preparePhrase
|
| 307 |
+
|
| 308 |
+
if (!this.canSpeak()) return
|
| 309 |
+
|
| 310 |
+
const nowStage = `${maneuverKey}|now`
|
| 311 |
+
if (
|
| 312 |
+
TURN_TYPES.has(maneuverType) &&
|
| 313 |
+
distance != null &&
|
| 314 |
+
distance <= thresholds.nowMeters &&
|
| 315 |
+
!this.spokenStages.has(nowStage)
|
| 316 |
+
) {
|
| 317 |
+
this.spokenStages.add(nowStage)
|
| 318 |
+
this.enqueue({
|
| 319 |
+
text: nowPhrase,
|
| 320 |
+
priority: 90,
|
| 321 |
+
expiresAt: Date.now() + 7_000,
|
| 322 |
+
maneuverKey,
|
| 323 |
+
})
|
| 324 |
+
return
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
const prepareStage = `${maneuverKey}|prepare`
|
| 328 |
+
if (
|
| 329 |
+
this.mode === "full" &&
|
| 330 |
+
distance != null &&
|
| 331 |
+
distance <= thresholds.prepareMeters &&
|
| 332 |
+
distance > thresholds.nowMeters &&
|
| 333 |
+
!this.spokenStages.has(nowStage) &&
|
| 334 |
+
!this.spokenStages.has(prepareStage)
|
| 335 |
+
) {
|
| 336 |
+
this.spokenStages.add(prepareStage)
|
| 337 |
+
this.enqueue({
|
| 338 |
+
text: preparePhrase,
|
| 339 |
+
priority: 30,
|
| 340 |
+
expiresAt: Date.now() + 15_000,
|
| 341 |
+
maneuverKey,
|
| 342 |
+
})
|
| 343 |
+
}
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
repeatCurrent(): boolean {
|
| 347 |
+
if (!this.canSpeak() || !this.tripActive || !this.currentRepeatPhrase) return false
|
| 348 |
+
this.enqueue({
|
| 349 |
+
text: this.currentRepeatPhrase,
|
| 350 |
+
priority: 95,
|
| 351 |
+
expiresAt: Date.now() + 8_000,
|
| 352 |
+
maneuverKey: this.currentManeuverKey ?? undefined,
|
| 353 |
+
})
|
| 354 |
+
return true
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
endTrip(): void {
|
| 358 |
+
this.tripActive = false
|
| 359 |
+
this.tripConfirmed = false
|
| 360 |
+
this.tripStartedAt = null
|
| 361 |
+
this.startupOffRouteSuppressed = false
|
| 362 |
+
this.startupRerouteSuppressed = false
|
| 363 |
+
this.allowImplicitResume = false
|
| 364 |
+
this.latestUnconfirmedInput = null
|
| 365 |
+
this.lastStatus = "idle"
|
| 366 |
+
this.lastOffRoute = false
|
| 367 |
+
this.currentRepeatPhrase = null
|
| 368 |
+
this.resetManeuverState()
|
| 369 |
+
this.stopSpeech()
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
dispose(): void {
|
| 373 |
+
this.disposed = true
|
| 374 |
+
this.endTrip()
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
private canSpeak(): boolean {
|
| 378 |
+
return !this.disposed && this.available && this.mode !== "off"
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
private isStartupOffRouteGraceActive(): boolean {
|
| 382 |
+
return this.tripStartedAt != null && Date.now() - this.tripStartedAt < STARTUP_OFF_ROUTE_GRACE_MS
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
private resetManeuverState(): void {
|
| 386 |
+
this.currentManeuverKey = null
|
| 387 |
+
this.currentPivotIndex = null
|
| 388 |
+
this.currentRepeatPhrase = null
|
| 389 |
+
this.lastSignature = ""
|
| 390 |
+
this.lastDistance = null
|
| 391 |
+
this.syntheticSequence = 0
|
| 392 |
+
this.spokenStages.clear()
|
| 393 |
+
this.pending = null
|
| 394 |
+
this.clearPendingTimer()
|
| 395 |
+
}
|
| 396 |
+
|
| 397 |
+
private enqueue(prompt: Prompt): void {
|
| 398 |
+
if (!this.canSpeak() || !prompt.text) return
|
| 399 |
+
if (prompt.priority >= 90) {
|
| 400 |
+
// An action/repeat/lifecycle cue supersedes deferred advance notice.
|
| 401 |
+
// Otherwise a prepare prompt waiting out the automatic gap can fire
|
| 402 |
+
// after "turn now", when it is both stale and actively confusing.
|
| 403 |
+
this.pending = null
|
| 404 |
+
this.clearPendingTimer()
|
| 405 |
+
if (this.speaking && prompt.priority >= this.speakingPriority) {
|
| 406 |
+
this.speaker.stop()
|
| 407 |
+
this.startPrompt(prompt)
|
| 408 |
+
return
|
| 409 |
+
}
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
if (this.speaking) {
|
| 413 |
+
if (!this.pending || prompt.priority >= this.pending.priority) this.pending = prompt
|
| 414 |
+
return
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
const gap = prompt.priority >= 90 ? 0 : MIN_AUTOMATIC_PROMPT_GAP_MS
|
| 418 |
+
const wait = Math.max(0, this.lastPromptStartedAt + gap - Date.now())
|
| 419 |
+
if (wait > 0) {
|
| 420 |
+
if (!this.pending || prompt.priority >= this.pending.priority) this.pending = prompt
|
| 421 |
+
if (!this.pendingTimer) {
|
| 422 |
+
this.pendingTimer = setTimeout(() => {
|
| 423 |
+
this.pendingTimer = null
|
| 424 |
+
this.drainPending()
|
| 425 |
+
}, wait)
|
| 426 |
+
}
|
| 427 |
+
return
|
| 428 |
+
}
|
| 429 |
+
this.startPrompt(prompt)
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
private startPrompt(prompt: Prompt): void {
|
| 433 |
+
if (!this.isPromptValid(prompt)) return
|
| 434 |
+
const generation = ++this.speakingGeneration
|
| 435 |
+
this.speaking = true
|
| 436 |
+
this.speakingPriority = prompt.priority
|
| 437 |
+
this.speakingManeuverKey = prompt.maneuverKey ?? null
|
| 438 |
+
this.lastPromptStartedAt = Date.now()
|
| 439 |
+
this.log(`VOICE ${prompt.text}`)
|
| 440 |
+
void this.speaker
|
| 441 |
+
.speak(prompt.text, {
|
| 442 |
+
// The host's playback session ducks external media. Do not abort other
|
| 443 |
+
// miniapp streams merely to deliver a short navigation cue.
|
| 444 |
+
stopOtherAudio: false,
|
| 445 |
+
voice_settings: {speed: 1.05},
|
| 446 |
+
})
|
| 447 |
+
.catch((err) => {
|
| 448 |
+
this.log(`VOICE failed: ${err instanceof Error ? err.message : String(err)}`)
|
| 449 |
+
})
|
| 450 |
+
.finally(() => {
|
| 451 |
+
if (generation !== this.speakingGeneration) return
|
| 452 |
+
this.speaking = false
|
| 453 |
+
this.speakingPriority = 0
|
| 454 |
+
this.speakingManeuverKey = null
|
| 455 |
+
this.drainPending()
|
| 456 |
+
})
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
private drainPending(): void {
|
| 460 |
+
if (this.speaking) return
|
| 461 |
+
const next = this.pending
|
| 462 |
+
this.pending = null
|
| 463 |
+
if (!next || !this.isPromptValid(next)) return
|
| 464 |
+
this.enqueue(next)
|
| 465 |
+
}
|
| 466 |
+
|
| 467 |
+
private isPromptValid(prompt: Prompt): boolean {
|
| 468 |
+
if (!this.canSpeak() || Date.now() > prompt.expiresAt) return false
|
| 469 |
+
return !prompt.maneuverKey || prompt.maneuverKey === this.currentManeuverKey
|
| 470 |
+
}
|
| 471 |
+
|
| 472 |
+
private discardStaleManeuverPrompts(): void {
|
| 473 |
+
if (this.pending?.maneuverKey) {
|
| 474 |
+
this.pending = null
|
| 475 |
+
this.clearPendingTimer()
|
| 476 |
+
}
|
| 477 |
+
if (!this.speaking || !this.speakingManeuverKey) return
|
| 478 |
+
|
| 479 |
+
// A route/pivot change invalidates even an utterance that has already
|
| 480 |
+
// started. Interrupt only maneuver-bound speech; lifecycle cues such as
|
| 481 |
+
// "Navigation started" deliberately have no maneuver key and continue.
|
| 482 |
+
this.speakingGeneration += 1
|
| 483 |
+
this.speaker.stop()
|
| 484 |
+
this.speaking = false
|
| 485 |
+
this.speakingPriority = 0
|
| 486 |
+
this.speakingManeuverKey = null
|
| 487 |
+
}
|
| 488 |
+
|
| 489 |
+
private stopSpeech(): void {
|
| 490 |
+
this.pending = null
|
| 491 |
+
this.clearPendingTimer()
|
| 492 |
+
this.speakingGeneration += 1
|
| 493 |
+
if (this.speaking) this.speaker.stop()
|
| 494 |
+
this.speaking = false
|
| 495 |
+
this.speakingPriority = 0
|
| 496 |
+
this.speakingManeuverKey = null
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
private clearPendingTimer(): void {
|
| 500 |
+
if (!this.pendingTimer) return
|
| 501 |
+
clearTimeout(this.pendingTimer)
|
| 502 |
+
this.pendingTimer = null
|
| 503 |
+
}
|
| 504 |
+
}
|
| 505 |
+
|
| 506 |
+
/**
|
| 507 |
+
* Arrival guidance follows the live destination countdown, while turn cues
|
| 508 |
+
* stay paired with the native event that supplied their type and instruction.
|
| 509 |
+
*/
|
| 510 |
+
export function selectAudioGuidanceDistance(
|
| 511 |
+
maneuverType: string | null | undefined,
|
| 512 |
+
eventDistanceMeters: number | null | undefined,
|
| 513 |
+
liveDisplayDistanceMeters: number | null | undefined,
|
| 514 |
+
): number | null {
|
| 515 |
+
const eventDistance = validDistance(eventDistanceMeters ?? null)
|
| 516 |
+
if (maneuverType?.toUpperCase() !== "ARRIVE") return eventDistance
|
| 517 |
+
return validDistance(liveDisplayDistanceMeters ?? null) ?? eventDistance
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
+
function validDistance(value: number | null): number | null {
|
| 521 |
+
return value != null && Number.isFinite(value) && value >= 0 ? value : null
|
| 522 |
+
}
|
| 523 |
+
|
| 524 |
+
function cleanSpokenText(value: string | null | undefined): string {
|
| 525 |
+
return (value ?? "")
|
| 526 |
+
.replace(/[\n\r]+/g, " ")
|
| 527 |
+
.replace(/[←→↑↺↰↱↖↗⤴⤵●⇆]/g, "")
|
| 528 |
+
.replace(/\s+/g, " ")
|
| 529 |
+
.replace(/[.\s]+$/, "")
|
| 530 |
+
.trim()
|
| 531 |
+
}
|
| 532 |
+
|
| 533 |
+
function buildPreparationPhrase(instruction: string, distanceMeters: number | null, unit: UnitSystem): string {
|
| 534 |
+
if (distanceMeters == null) return `${capitalize(instruction)}.`
|
| 535 |
+
return `In ${formatSpokenDistance(distanceMeters, unit)}, ${lowercaseFirst(instruction)}.`
|
| 536 |
+
}
|
| 537 |
+
|
| 538 |
+
function buildNowPhrase(instruction: string, maneuverType: string): string {
|
| 539 |
+
if (maneuverType === "CROSS_STREET") return "Cross the street now."
|
| 540 |
+
if (maneuverType === "U_TURN") return "Turn around now."
|
| 541 |
+
return `${capitalize(instruction)} now.`
|
| 542 |
+
}
|
| 543 |
+
|
| 544 |
+
function formatSpokenDistance(meters: number, unit: UnitSystem): string {
|
| 545 |
+
if (unit === "imperial") {
|
| 546 |
+
const feet = meters * 3.28084
|
| 547 |
+
if (feet < 528) return `${Math.max(10, Math.round(feet / 10) * 10)} feet`
|
| 548 |
+
const miles = feet / 5280
|
| 549 |
+
return `${miles.toFixed(1)} ${miles >= 0.95 && miles < 1.05 ? "mile" : "miles"}`
|
| 550 |
+
}
|
| 551 |
+
if (meters < 1000) {
|
| 552 |
+
const rounded = meters < 100 ? Math.max(5, Math.round(meters / 5) * 5) : Math.round(meters / 10) * 10
|
| 553 |
+
return `${rounded} meters`
|
| 554 |
+
}
|
| 555 |
+
const kilometers = meters / 1000
|
| 556 |
+
return `${kilometers.toFixed(1)} ${kilometers >= 0.95 && kilometers < 1.05 ? "kilometer" : "kilometers"}`
|
| 557 |
+
}
|
| 558 |
+
|
| 559 |
+
function capitalize(value: string): string {
|
| 560 |
+
return value ? value.charAt(0).toUpperCase() + value.slice(1) : value
|
| 561 |
+
}
|
| 562 |
+
|
| 563 |
+
function lowercaseFirst(value: string): string {
|
| 564 |
+
return value ? value.charAt(0).toLowerCase() + value.slice(1) : value
|
| 565 |
+
}
|
miniapps/navigation/src/background/managers/CompassManager.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* CompassManager
|
| 3 |
+
*
|
| 4 |
+
* Thin wrapper over `session.heading.onUpdate`. Same shape as the SDK's
|
| 5 |
+
* heading module — callers do `user.compass.onUpdate(handler)` and own
|
| 6 |
+
* their state.
|
| 7 |
+
*/
|
| 8 |
+
|
| 9 |
+
import type {HeadingData, MiniappSession} from "@mentra/miniapp"
|
| 10 |
+
|
| 11 |
+
export type CompassListener = (data: HeadingData) => void
|
| 12 |
+
export type Unsubscribe = () => void
|
| 13 |
+
|
| 14 |
+
export class CompassManager {
|
| 15 |
+
constructor(private readonly session: MiniappSession) {}
|
| 16 |
+
|
| 17 |
+
/** Subscribe to continuous compass-heading updates. */
|
| 18 |
+
onUpdate(handler: CompassListener): Unsubscribe {
|
| 19 |
+
return this.session.heading.onUpdate(handler)
|
| 20 |
+
}
|
| 21 |
+
}
|
miniapps/navigation/src/background/managers/DisplayManager.ts
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* DisplayManager
|
| 3 |
+
*
|
| 4 |
+
* Thin imperative wrapper over `session.display.*`. Mirrors the SDK
|
| 5 |
+
* module shape — short verbs that delegate to the underlying
|
| 6 |
+
* DisplayManager. Callers decide when to push.
|
| 7 |
+
*/
|
| 8 |
+
|
| 9 |
+
import type {MiniappSession, RenderElement} from "@mentra/miniapp"
|
| 10 |
+
import {borderTestImageBase64} from "../lib/bmp"
|
| 11 |
+
import {readGlassesCapabilities} from "../lib/capabilities"
|
| 12 |
+
|
| 13 |
+
export class DisplayManager {
|
| 14 |
+
constructor(private readonly session: MiniappSession) {}
|
| 15 |
+
|
| 16 |
+
private get bitmapLimits() {
|
| 17 |
+
const display = this.session.capabilities?.display
|
| 18 |
+
const dimension = (value: unknown, fallback: number) =>
|
| 19 |
+
typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback
|
| 20 |
+
const width = dimension(display?.width, 576)
|
| 21 |
+
const height = dimension(display?.height, 288)
|
| 22 |
+
return {
|
| 23 |
+
width,
|
| 24 |
+
height,
|
| 25 |
+
maxWidth: display?.maxImageElements === 0 ? 0 : Math.min(width, dimension(display?.maxImagePx?.width, width)),
|
| 26 |
+
maxHeight: display?.maxImageElements === 0 ? 0 : Math.min(height, dimension(display?.maxImagePx?.height, height)),
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
/** Whether the selected display can show a positioned bitmap. */
|
| 31 |
+
get supportsBitmaps(): boolean {
|
| 32 |
+
const {maxWidth, maxHeight} = this.bitmapLimits
|
| 33 |
+
return this.session.capabilities?.display?.canPosition !== false && maxWidth > 0 && maxHeight > 0
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
/** Choose raster dimensions before encoding, using the same limits as placement. */
|
| 37 |
+
getBitmapSize(width = 288, height = 140): {w: number; h: number} {
|
| 38 |
+
const {maxWidth, maxHeight} = this.bitmapLimits
|
| 39 |
+
const w = Math.min(width, maxWidth)
|
| 40 |
+
const h = Math.min(height, maxHeight)
|
| 41 |
+
this.bitmapBox(w, h)
|
| 42 |
+
return {w, h}
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
private bitmapBox(w: number, h: number): {x: number; y: number; w: number; h: number} {
|
| 46 |
+
const {width, height, maxWidth, maxHeight} = this.bitmapLimits
|
| 47 |
+
if (!Number.isInteger(w) || !Number.isInteger(h) || w <= 0 || h <= 0 || w > maxWidth || h > maxHeight) {
|
| 48 |
+
throw new RangeError(`Bitmap ${w}x${h} is unsupported; maximum image size is ${maxWidth}x${maxHeight}`)
|
| 49 |
+
}
|
| 50 |
+
return {x: Math.round((width - w) / 2), y: Math.round((height - h) / 2), w, h}
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
// ── Navigation HUD layout ────────────────────────────────────────────
|
| 54 |
+
// Boxes on the 500×220 Mentra canvas, from the nav HUD mockup: a map bitmap
|
| 55 |
+
// on the right, a turn-arrow bitmap on the left, trip stats along the top,
|
| 56 |
+
// and the maneuver instruction below the arrow. The firmware draws the outer
|
| 57 |
+
// rounded frame itself, so we only send these content slots. `message` shares
|
| 58 |
+
// the arrow's left x and spans the content area (staying clear of the map).
|
| 59 |
+
static readonly HUD = {
|
| 60 |
+
// Keep the map below the two-line stats region. Both regions meet at y=80
|
| 61 |
+
// without overlapping and still fit the 220px-tall HUD canvas exactly.
|
| 62 |
+
map: {x: 340, y: 80, w: 140, h: 140},
|
| 63 |
+
arrow: {x: 0, y: 182, w: 38, h: 38},
|
| 64 |
+
// Wall-clock current time, top-LEFT (the phone's clock, sent each refresh).
|
| 65 |
+
// The widest 24-hour clock is 52px in the G2 font, and native adds 4px of
|
| 66 |
+
// padding on each side. Keep a little extra headroom so it never wraps into
|
| 67 |
+
// a clipped second line.
|
| 68 |
+
clock: {x: 0, y: 0, w: 64, h: 40},
|
| 69 |
+
// Long distance + ETA strings can wrap. Give the top-right stats region
|
| 70 |
+
// two full calibrated G2 lines instead of letting a second line overflow a
|
| 71 |
+
// 28px box. The wider box also keeps the common case on one line.
|
| 72 |
+
stats: {x: 280, y: 0, w: 200, h: 80},
|
| 73 |
+
// The body contains a distance line plus an instruction that may itself
|
| 74 |
+
// wrap (for example, "Turn right onto Gough Street"). G2 clips by
|
| 75 |
+
// floor(height / 40px), so reserve three complete lines; the old 52px box
|
| 76 |
+
// admitted only the distance and silently removed the instruction.
|
| 77 |
+
maneuver: {x: 40, y: 100, w: 270, h: 120},
|
| 78 |
+
message: {x: 12, y: 54, w: 310, h: 156},
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
// ── HUD frame state ──────────────────────────────────────────────────
|
| 82 |
+
// render() replaces the whole frame, so this class caches the CONTENT of
|
| 83 |
+
// each slot (the arrow/map bitmaps are expensive to produce, not to resend —
|
| 84 |
+
// the host diffs frames and unchanged elements never re-cross BLE) and
|
| 85 |
+
// composes the full scene on every push. No element lifecycle, no removes:
|
| 86 |
+
// what's on screen is exactly what buildFrame() returns.
|
| 87 |
+
private mode: "hud" | "message" | null = null
|
| 88 |
+
private arrowBmp: string | null = null
|
| 89 |
+
private mapBmp: string | null = null
|
| 90 |
+
private clock: string | null = null
|
| 91 |
+
private stats: string | null = null
|
| 92 |
+
private maneuver: string | null = null
|
| 93 |
+
private message: string | null = null
|
| 94 |
+
|
| 95 |
+
private buildFrame(): RenderElement[] {
|
| 96 |
+
const els: RenderElement[] = []
|
| 97 |
+
if (this.mode === "hud") {
|
| 98 |
+
if (this.arrowBmp) els.push({type: "image", id: "arrow", box: DisplayManager.HUD.arrow, data: this.arrowBmp})
|
| 99 |
+
if (this.maneuver != null)
|
| 100 |
+
els.push({type: "text", id: "maneuver", box: DisplayManager.HUD.maneuver, text: this.maneuver})
|
| 101 |
+
if (this.stats != null) els.push({type: "text", id: "stats", box: DisplayManager.HUD.stats, text: this.stats})
|
| 102 |
+
} else if (this.mode === "message" && this.message != null) {
|
| 103 |
+
els.push({
|
| 104 |
+
type: "text",
|
| 105 |
+
id: "message",
|
| 106 |
+
box: DisplayManager.HUD.message,
|
| 107 |
+
text: this.message,
|
| 108 |
+
...(readGlassesCapabilities(this.session.capabilities).canPosition
|
| 109 |
+
? {style: {breakMode: "word" as const}}
|
| 110 |
+
: {}),
|
| 111 |
+
})
|
| 112 |
+
}
|
| 113 |
+
// The clock (top-left) and minimap ride along in both modes.
|
| 114 |
+
if (this.clock != null) els.push({type: "text", id: "clock", box: DisplayManager.HUD.clock, text: this.clock})
|
| 115 |
+
if (this.mapBmp) els.push({type: "image", id: "map", box: DisplayManager.HUD.map, data: this.mapBmp})
|
| 116 |
+
return els
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
private pushFrame(): void {
|
| 120 |
+
this.safeCall(() => void this.session.display.render(this.buildFrame()))
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
/**
|
| 124 |
+
* Turn-by-turn HUD frame: arrow bitmap (left), maneuver text (bottom), trip
|
| 125 |
+
* stats (top) — plus the cached minimap. Fields set to a value (including
|
| 126 |
+
* null) overwrite that slot; omitted fields keep their cached content, so the
|
| 127 |
+
* caller only re-encodes the arrow BMP when the direction changes.
|
| 128 |
+
*/
|
| 129 |
+
showNavHud(frame: {arrowBmp?: string; stats?: string | null; maneuver?: string | null; clock?: string | null}): void {
|
| 130 |
+
this.mode = "hud"
|
| 131 |
+
if (frame.arrowBmp !== undefined) this.arrowBmp = frame.arrowBmp
|
| 132 |
+
if (frame.stats !== undefined) this.stats = frame.stats
|
| 133 |
+
if (frame.maneuver !== undefined) this.maneuver = frame.maneuver
|
| 134 |
+
if (frame.clock !== undefined) this.clock = frame.clock
|
| 135 |
+
this.pushFrame()
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
/**
|
| 139 |
+
* Single-message state (welcome / "Starting…" / rerouting / arrived): the
|
| 140 |
+
* whole frame becomes the message (plus minimap). Turn-by-turn slots simply
|
| 141 |
+
* stop being rendered — render() replaces the frame, nothing to remove.
|
| 142 |
+
*/
|
| 143 |
+
showNavMessage(text: string, clock?: string | null): void {
|
| 144 |
+
this.mode = "message"
|
| 145 |
+
this.message = text
|
| 146 |
+
if (clock !== undefined) this.clock = clock
|
| 147 |
+
this.pushFrame()
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
/**
|
| 151 |
+
* Navigation frame for non-positioning displays such as Even Realities G1.
|
| 152 |
+
* Keep the maneuver first and emit one text element: host-side scene
|
| 153 |
+
* degradation otherwise inserts blank lines between the positioned clock,
|
| 154 |
+
* stats, and maneuver elements, pushing the instruction past G1's five-line
|
| 155 |
+
* limit. Images and clock are deliberately cleared because these displays
|
| 156 |
+
* cannot render them through the scene API.
|
| 157 |
+
*/
|
| 158 |
+
showCompactNavHud(maneuver: string, stats: string | null): void {
|
| 159 |
+
this.mode = "message"
|
| 160 |
+
this.message = [maneuver, stats].filter(Boolean).join("\n\n")
|
| 161 |
+
this.clock = null
|
| 162 |
+
this.mapBmp = null
|
| 163 |
+
this.pushFrame()
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
// ── Display sends ────────────────────────────────────────────────────
|
| 167 |
+
// Sends are INSTANT — each show fires immediately, no spacing/throttle.
|
| 168 |
+
// (We previously serialized text through a 200ms queue, but that's removed:
|
| 169 |
+
// `enqueue` now just fires the thunk right away. The `box` key is kept in
|
| 170 |
+
// the signature only so call sites read clearly and so a future throttle
|
| 171 |
+
// could be reintroduced without touching them.)
|
| 172 |
+
private enqueue(_box: string, fn: () => void): void {
|
| 173 |
+
this.safeCall(fn)
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
/**
|
| 177 |
+
* Single line filling the glasses display.
|
| 178 |
+
* `durationMs` is forwarded to the SDK; if set, the message auto-clears
|
| 179 |
+
* after that long. Omit for a sticky message that persists until replaced.
|
| 180 |
+
*/
|
| 181 |
+
showText(text: string, durationMs?: number): void {
|
| 182 |
+
const {width: w, height: h} = this.bitmapLimits
|
| 183 |
+
this.enqueue(
|
| 184 |
+
"wall",
|
| 185 |
+
() =>
|
| 186 |
+
void this.session.display.render(
|
| 187 |
+
[{type: "text", id: "wall", box: {x: 0, y: 0, w, h}, text}],
|
| 188 |
+
durationMs != null ? {durationMs} : undefined,
|
| 189 |
+
),
|
| 190 |
+
)
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
showTextTest(): void {
|
| 194 |
+
this.showText(
|
| 195 |
+
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec venenatis vulputate lorem. Maecenas vestibulum mollis diam. Pellentesque ut neque. Sed lectus. Donec sodales sagittis magna.",
|
| 196 |
+
)
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
// showTwoLines(top: string, bottom: string): void {
|
| 200 |
+
// this.showText(`${top} / ${bottom}`)
|
| 201 |
+
// }
|
| 202 |
+
|
| 203 |
+
// /** Title + body card. */
|
| 204 |
+
// showCard(title: string, body: string): void {
|
| 205 |
+
// this.showText(`${title} — ${body}`)
|
| 206 |
+
// }
|
| 207 |
+
|
| 208 |
+
/**
|
| 209 |
+
* Show a bitmap on the glasses. `base64Bmp` is a base64-encoded 1-bit
|
| 210 |
+
* BMP (see MinimapRenderer/bmp.ts). `width`/`height` size the target
|
| 211 |
+
* container on the glasses canvas.
|
| 212 |
+
*/
|
| 213 |
+
showBitmap(base64Bmp: string): void {
|
| 214 |
+
// The minimap is the "map" slot of the HUD frame — refreshMinimap runs on
|
| 215 |
+
// its own async cadence, so it updates the cache and re-pushes whatever
|
| 216 |
+
// frame is current (host diff keeps unchanged slots off BLE).
|
| 217 |
+
this.mapBmp = base64Bmp
|
| 218 |
+
this.pushFrame()
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
/**
|
| 222 |
+
* Drop the minimap slot (e.g. when switching to the swipe-up large map, which
|
| 223 |
+
* renders at a different rect).
|
| 224 |
+
*/
|
| 225 |
+
clearMinimap(): void {
|
| 226 |
+
this.mapBmp = null
|
| 227 |
+
this.pushFrame()
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
/**
|
| 231 |
+
* Swipe test box centered on the advertised canvas. Reject unsupported
|
| 232 |
+
* sizes before clearing, so a diagnostic cannot silently blank the display.
|
| 233 |
+
*/
|
| 234 |
+
showTestBox(width: number, height: number): void {
|
| 235 |
+
const {w, h} = this.bitmapBox(width, height)
|
| 236 |
+
const base64Bmp = borderTestImageBase64(w, h)
|
| 237 |
+
// Clear first, wait 1s so old containers tear down, THEN draw the box.
|
| 238 |
+
this.safeCall(() => void this.session.display.render([]))
|
| 239 |
+
setTimeout(() => {
|
| 240 |
+
this.renderCenteredBitmap(base64Bmp, w, h)
|
| 241 |
+
}, 1000)
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
/** One centered image element as the whole frame (test/large-map paths). */
|
| 245 |
+
private renderCenteredBitmap(data: string, w: number, h: number): void {
|
| 246 |
+
const box = this.bitmapBox(w, h)
|
| 247 |
+
this.safeCall(() => void this.session.display.render([{type: "image", id: "bmp", box, data}]))
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
/**
|
| 251 |
+
* Large map shown on swipe-up. Call getBitmapSize before rasterizing;
|
| 252 |
+
* silently clamping only the box would disagree with the encoded image.
|
| 253 |
+
*/
|
| 254 |
+
showLargeBitmap(base64Bmp: string, width = 288, height = 140): void {
|
| 255 |
+
this.renderCenteredBitmap(base64Bmp, width, height)
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
// ── Two stacked text containers ──────────────────────────────────────
|
| 259 |
+
// The G2's single full-screen (576×288) text wall only fits ~5 lines. To get
|
| 260 |
+
// more usable vertical text we split into two stacked positioned-text
|
| 261 |
+
// containers: maneuver/directions on top, trip stats below.
|
| 262 |
+
// SINGLE-CONTAINER HUD: the whole frame (maneuver block + trip stats) is now
|
| 263 |
+
// crammed into THIS one container, spanning the full canvas so all the lines
|
| 264 |
+
// fit. There is no longer a separate stats box below it.
|
| 265 |
+
// Full 500×220 Mentra canvas — used by the single-container states
|
| 266 |
+
// (welcome / rerouting / arrived / off-route), which don't use the 4-slot split.
|
| 267 |
+
private static readonly MANEUVER_REGION = {x: 0, y: 0, width: 500, height: 220}
|
| 268 |
+
|
| 269 |
+
/**
|
| 270 |
+
* Single full-canvas message element shared by the single-container states
|
| 271 |
+
* (maneuver text, loading messages, trip stats). One stable id + one
|
| 272 |
+
* geometry means every push is a content-only update — the same last-wins
|
| 273 |
+
* behavior as the positioned_text sends it replaces. Replaces the whole
|
| 274 |
+
* frame; these states never coexist with the 4-slot HUD.
|
| 275 |
+
*/
|
| 276 |
+
private renderRegionText(text: string): void {
|
| 277 |
+
const r = DisplayManager.MANEUVER_REGION
|
| 278 |
+
void this.session.display.render([{type: "text", id: "msg", box: {x: r.x, y: r.y, w: r.width, h: r.height}, text}])
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
/**
|
| 282 |
+
* Maneuver / direction text in the TOP region of the canvas (its own G2 text
|
| 283 |
+
* container), leaving the bottom region free for the stats container.
|
| 284 |
+
*/
|
| 285 |
+
showManeuver(text: string): void {
|
| 286 |
+
// Queued under "maneuver" — drains after "minimap", before "stats".
|
| 287 |
+
this.enqueue("maneuver", () => this.renderRegionText(text))
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
/**
|
| 291 |
+
* Transition status text in the TOP-LEFT maneuver region, shown IMMEDIATELY
|
| 292 |
+
* (bypasses the 200ms text queue) — used for "Loading large map" / "Loading
|
| 293 |
+
* main menu" while a swipe transition settles, so the user sees feedback in
|
| 294 |
+
* the gap rather than a blank/stale screen. Bypasses the queue because it
|
| 295 |
+
* must appear right at the swipe, before any HUD text, and the transition
|
| 296 |
+
* clear() has just purged the queue anyway.
|
| 297 |
+
*/
|
| 298 |
+
showLoadingMessage(text: string): void {
|
| 299 |
+
this.safeCall(() => this.renderRegionText(text))
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
/** Blank the top-left loading message (overwrite its region with empty text). */
|
| 303 |
+
clearLoadingMessage(): void {
|
| 304 |
+
this.safeCall(() => this.renderRegionText(""))
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
/**
|
| 308 |
+
* Live trip-stats (distance + ETA) in the BOTTOM region, in its own G2 text
|
| 309 |
+
* container stacked under the maneuver box.
|
| 310 |
+
*/
|
| 311 |
+
showTripStats(text: string): void {
|
| 312 |
+
// Queued under "stats" — drains last, after "minimap" and "maneuver".
|
| 313 |
+
// STATS_REGION === MANEUVER_REGION (single-container HUD), so this rides
|
| 314 |
+
// the same shared message element.
|
| 315 |
+
this.enqueue("stats", () => this.renderRegionText(text))
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
/**
|
| 319 |
+
* Fixed 288x288 diagnostic asset. Reports an unsupported size on displays
|
| 320 |
+
* whose image or canvas limits cannot accommodate it; it is not resized.
|
| 321 |
+
*/
|
| 322 |
+
showBitmapTest(base64Bmp: string): void {
|
| 323 |
+
// render() replaces the whole frame — no separate clear needed.
|
| 324 |
+
this.renderCenteredBitmap(base64Bmp, 288, 288)
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
/**
|
| 328 |
+
* Test-only: render a bordered bitmap at the exact requested size, centered
|
| 329 |
+
* on the device canvas. Unsupported probes fail before clearing the frame.
|
| 330 |
+
*/
|
| 331 |
+
showBitmapSize(size: number, height?: number): void {
|
| 332 |
+
const {w, h} = this.bitmapBox(size, height ?? size)
|
| 333 |
+
const base64Bmp = borderTestImageBase64(w, h)
|
| 334 |
+
// Clear first, wait 3s so the old container fully tears down, THEN draw the
|
| 335 |
+
// new bitmap — avoids the G2 reusing/overlapping a stale image container.
|
| 336 |
+
this.safeCall(() => void this.session.display.render([]))
|
| 337 |
+
setTimeout(() => {
|
| 338 |
+
this.renderCenteredBitmap(base64Bmp, w, h)
|
| 339 |
+
}, 3000)
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
/**
|
| 343 |
+
* Test-only: show a pre-rendered base64 BMP at a given container size,
|
| 344 |
+
* centered within device limits. Used by the OSM line-map PoC.
|
| 345 |
+
*/
|
| 346 |
+
showRawBitmap(base64Bmp: string, width: number, height: number): void {
|
| 347 |
+
// Stable id + unchanged rect ⇒ the differ marks this a content-only update
|
| 348 |
+
// and the G2 swaps the bitmap into the existing container in place — the
|
| 349 |
+
// same no-flicker behavior the old rect-keyed container reuse gave.
|
| 350 |
+
this.renderCenteredBitmap(base64Bmp, width, height)
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
/** Wipe whatever's on the glasses (and forget the cached frame slots). */
|
| 354 |
+
clear(): void {
|
| 355 |
+
this.mode = null
|
| 356 |
+
this.arrowBmp = null
|
| 357 |
+
this.mapBmp = null
|
| 358 |
+
this.clock = null
|
| 359 |
+
this.stats = null
|
| 360 |
+
this.maneuver = null
|
| 361 |
+
this.message = null
|
| 362 |
+
this.safeCall(() => void this.session.display.render([]))
|
| 363 |
+
}
|
| 364 |
+
|
| 365 |
+
private safeCall(fn: () => void): void {
|
| 366 |
+
try {
|
| 367 |
+
fn()
|
| 368 |
+
} catch (err) {
|
| 369 |
+
console.log("[NAV-MINI] display call ignored:", err)
|
| 370 |
+
}
|
| 371 |
+
}
|
| 372 |
+
}
|
miniapps/navigation/src/background/managers/LocationManager.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* LocationManager
|
| 3 |
+
*
|
| 4 |
+
* Thin wrapper over `session.location.onUpdate`. Mirrors the shape of the
|
| 5 |
+
* SDK's `LocationModule` (sdk/miniapp/src/modules/location.ts) — the User
|
| 6 |
+
* holds an instance, callers do `user.location.onUpdate(handler)` and
|
| 7 |
+
* manage their own state.
|
| 8 |
+
*/
|
| 9 |
+
|
| 10 |
+
import type {LocationData, MiniappSession} from "@mentra/miniapp"
|
| 11 |
+
|
| 12 |
+
export type Coords = {lat: number; lng: number; accuracy?: number; ts: number}
|
| 13 |
+
|
| 14 |
+
export type LocationListener = (data: LocationData) => void
|
| 15 |
+
export type Unsubscribe = () => void
|
| 16 |
+
|
| 17 |
+
export class LocationManager {
|
| 18 |
+
constructor(private readonly session: MiniappSession) {}
|
| 19 |
+
|
| 20 |
+
/** Subscribe to continuous location updates. */
|
| 21 |
+
onUpdate(handler: LocationListener): Unsubscribe {
|
| 22 |
+
return this.session.location.onUpdate(handler)
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
/** Request a single location fix. Useful at app load to seed UI. */
|
| 26 |
+
getOnce(): Promise<LocationData> {
|
| 27 |
+
return this.session.location.getOnce()
|
| 28 |
+
}
|
| 29 |
+
}
|
miniapps/navigation/src/background/managers/ManeuverFormatter.ts
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* ManeuverFormatter
|
| 3 |
+
*
|
| 4 |
+
* Pure presentation helpers for `NavManeuver` data — glyphs, arrows,
|
| 5 |
+
* human verbs, headlines, and the glasses NOW/NEXT line pair. Lives
|
| 6 |
+
* under `user.navigation.format` so anything maneuver-related has a
|
| 7 |
+
* single entry point.
|
| 8 |
+
*
|
| 9 |
+
* Stateless: every method is a pure function of its inputs. The class
|
| 10 |
+
* shape exists only so callers can reach the helpers via the
|
| 11 |
+
* NavigationManager (`user.navigation.format.headline(m)`).
|
| 12 |
+
*/
|
| 13 |
+
|
| 14 |
+
import type {NavManeuver} from "@mentra/miniapp"
|
| 15 |
+
|
| 16 |
+
import type {UnitSystem} from "../../shared/types"
|
| 17 |
+
import {formatDistance, formatDuration} from "../lib/formatDistance"
|
| 18 |
+
|
| 19 |
+
/** Distance threshold below which a turn becomes the active instruction. */
|
| 20 |
+
const IMMINENT_M = 30
|
| 21 |
+
|
| 22 |
+
export class ManeuverFormatter {
|
| 23 |
+
/** A "go straight" continuation rather than a turn. */
|
| 24 |
+
isStraight(m: NavManeuver | null): boolean {
|
| 25 |
+
return !!m && (m.maneuverType === "STRAIGHT" || m.maneuverType === "CONTINUE")
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
/** Capitalize first letter. */
|
| 29 |
+
cap(s: string): string {
|
| 30 |
+
return s.charAt(0).toUpperCase() + s.slice(1)
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
/** Big glyph for the OrientationCard / pill. */
|
| 34 |
+
glyph(type: string): string {
|
| 35 |
+
switch (type.toUpperCase()) {
|
| 36 |
+
case "TURN_LEFT":
|
| 37 |
+
return "↰"
|
| 38 |
+
case "TURN_RIGHT":
|
| 39 |
+
return "↱"
|
| 40 |
+
case "SLIGHT_LEFT":
|
| 41 |
+
return "↖"
|
| 42 |
+
case "SLIGHT_RIGHT":
|
| 43 |
+
return "↗"
|
| 44 |
+
case "SHARP_LEFT":
|
| 45 |
+
return "⤴"
|
| 46 |
+
case "SHARP_RIGHT":
|
| 47 |
+
return "⤵"
|
| 48 |
+
case "U_TURN":
|
| 49 |
+
return "↶"
|
| 50 |
+
case "STRAIGHT":
|
| 51 |
+
case "CONTINUE":
|
| 52 |
+
return "↑"
|
| 53 |
+
case "ARRIVE":
|
| 54 |
+
return "●"
|
| 55 |
+
case "CROSS_STREET":
|
| 56 |
+
return "⇆"
|
| 57 |
+
default:
|
| 58 |
+
return "↑"
|
| 59 |
+
}
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
/** Compact arrow for short text lines (←/→/↑). */
|
| 63 |
+
arrow(type: string): string {
|
| 64 |
+
const t = type.toUpperCase()
|
| 65 |
+
if (t === "CROSS_STREET") return "⇆"
|
| 66 |
+
if (t.includes("LEFT")) return "←"
|
| 67 |
+
if (t.includes("RIGHT")) return "→"
|
| 68 |
+
if (t === "U_TURN") return "↺"
|
| 69 |
+
return "↑"
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
/** Human-readable verb. */
|
| 73 |
+
humanize(type: string): string {
|
| 74 |
+
switch (type.toUpperCase()) {
|
| 75 |
+
case "TURN_LEFT":
|
| 76 |
+
return "turn left"
|
| 77 |
+
case "TURN_RIGHT":
|
| 78 |
+
return "turn right"
|
| 79 |
+
case "SLIGHT_LEFT":
|
| 80 |
+
return "slight left"
|
| 81 |
+
case "SLIGHT_RIGHT":
|
| 82 |
+
return "slight right"
|
| 83 |
+
case "SHARP_LEFT":
|
| 84 |
+
return "sharp left"
|
| 85 |
+
case "SHARP_RIGHT":
|
| 86 |
+
return "sharp right"
|
| 87 |
+
case "U_TURN":
|
| 88 |
+
return "turn around"
|
| 89 |
+
case "STRAIGHT":
|
| 90 |
+
case "CONTINUE":
|
| 91 |
+
return "continue straight"
|
| 92 |
+
case "ARRIVE":
|
| 93 |
+
return "arrive"
|
| 94 |
+
case "CROSS_STREET":
|
| 95 |
+
return "cross the road"
|
| 96 |
+
default:
|
| 97 |
+
return type.toLowerCase().replace(/_/g, " ")
|
| 98 |
+
}
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
/**
|
| 102 |
+
* One-line headline for the maneuver pill. Built from the categorical
|
| 103 |
+
* type + distance — no road names.
|
| 104 |
+
*
|
| 105 |
+
* "In 200 m, turn right"
|
| 106 |
+
* "Continue straight"
|
| 107 |
+
* "Arriving in 35 m"
|
| 108 |
+
*/
|
| 109 |
+
headline(m: NavManeuver, unit: UnitSystem = "metric"): string {
|
| 110 |
+
const verb = this.humanize(m.maneuverType)
|
| 111 |
+
if (m.maneuverType === "ARRIVE") {
|
| 112 |
+
return m.distanceMeters > 0 ? `Arriving in ${formatDistance(m.distanceMeters, unit)}` : "Arriving"
|
| 113 |
+
}
|
| 114 |
+
if (m.maneuverType === "STRAIGHT") {
|
| 115 |
+
return "Continue straight"
|
| 116 |
+
}
|
| 117 |
+
if (m.distanceMeters > 0) {
|
| 118 |
+
return `In ${formatDistance(m.distanceMeters, unit)}, ${verb}`
|
| 119 |
+
}
|
| 120 |
+
return this.cap(verb)
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
/**
|
| 124 |
+
* Two short lines for the glasses HUD — NOW (top) + NEXT (bottom).
|
| 125 |
+
* Returns `next: null` when the imminent turn IS the active instruction
|
| 126 |
+
* (≤ IMMINENT_M), in which case the caller falls back to a single line.
|
| 127 |
+
*/
|
| 128 |
+
glassesLines(m: NavManeuver, unit: UnitSystem = "metric"): {now: string; next: string | null} {
|
| 129 |
+
const dist = m.distanceMeters
|
| 130 |
+
const isStraightT = this.isStraight(m)
|
| 131 |
+
const arrowed = (verb: string) => `${this.arrow(m.maneuverType)} ${verb}`
|
| 132 |
+
const toRoad = this.cleanRoad(m.toRoad, m.maneuverType)
|
| 133 |
+
|
| 134 |
+
if (!isStraightT && dist >= 0 && dist <= IMMINENT_M) {
|
| 135 |
+
const verb = this.humanize(m.maneuverType)
|
| 136 |
+
// CROSS_STREET keeps the same road on both sides — never append
|
| 137 |
+
// "onto X". The verb already reads as a complete instruction.
|
| 138 |
+
const onto = m.maneuverType === "CROSS_STREET" || !toRoad ? "" : ` onto ${toRoad}`
|
| 139 |
+
return {now: arrowed(`${this.cap(verb)}${onto}`), next: null}
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
const road = this.cleanRoad(m.fromRoad, m.maneuverType)
|
| 143 |
+
const distStr = dist > 0 ? formatDistance(dist, unit) : null
|
| 144 |
+
const nowLine =
|
| 145 |
+
road && distStr
|
| 146 |
+
? `↑ ${road} • ${distStr}`
|
| 147 |
+
: road
|
| 148 |
+
? `↑ ${road}`
|
| 149 |
+
: distStr
|
| 150 |
+
? `↑ Continue ${distStr}`
|
| 151 |
+
: "↑ Continue"
|
| 152 |
+
|
| 153 |
+
if (isStraightT) {
|
| 154 |
+
return {now: nowLine, next: null}
|
| 155 |
+
}
|
| 156 |
+
const verb = this.humanize(m.maneuverType)
|
| 157 |
+
const onto = m.maneuverType === "CROSS_STREET" || !toRoad ? "" : ` onto ${toRoad}`
|
| 158 |
+
return {now: nowLine, next: arrowed(`Then ${verb}${onto}`)}
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
/**
|
| 162 |
+
* Third HUD line: "1.2 km to destination · 14 min". Returns null when
|
| 163 |
+
* the engine hasn't supplied trip totals yet (-1 sentinels), so the UI
|
| 164 |
+
* can hide the line instead of rendering em-dashes.
|
| 165 |
+
*/
|
| 166 |
+
glassesProgressLine(m: NavManeuver, unit: UnitSystem = "metric"): string | null {
|
| 167 |
+
const dist = m.distanceToDestinationMeters
|
| 168 |
+
const time = m.timeToDestinationSeconds
|
| 169 |
+
const haveDist = typeof dist === "number" && dist >= 0
|
| 170 |
+
const haveTime = typeof time === "number" && time >= 0
|
| 171 |
+
if (!haveDist && !haveTime) return null
|
| 172 |
+
const distStr = haveDist ? `${formatDistance(dist!, unit)} to destination` : null
|
| 173 |
+
const timeStr = haveTime ? formatDuration(time!) : null
|
| 174 |
+
return [distStr, timeStr].filter(Boolean).join(" · ")
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
/**
|
| 178 |
+
* Drop a "road name" that's actually the maneuver instruction. The
|
| 179 |
+
* Google Nav SDK falls back to its instruction text (e.g. "Turn left")
|
| 180 |
+
* when the underlying road has no name, and that bubbles all the way
|
| 181 |
+
* here — concatenated naively, you'd render "Turn left onto Turn left".
|
| 182 |
+
* Returns null when the road string is empty or duplicates the verb.
|
| 183 |
+
*/
|
| 184 |
+
private cleanRoad(road: string | null | undefined, maneuverType: string): string | null {
|
| 185 |
+
const trimmed = road?.trim()
|
| 186 |
+
if (!trimmed) return null
|
| 187 |
+
const verb = this.humanize(maneuverType).toLowerCase()
|
| 188 |
+
const lower = trimmed.toLowerCase()
|
| 189 |
+
if (lower === verb || lower.startsWith(verb)) return null
|
| 190 |
+
return trimmed
|
| 191 |
+
}
|
| 192 |
+
}
|
miniapps/navigation/src/background/managers/NavigationManager.ts
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* NavigationManager
|
| 3 |
+
*
|
| 4 |
+
* Thin wrapper over `session.navigation.*`. Mirrors the SDK module shape:
|
| 5 |
+
* imperative methods (start/stop/deviate) and subscribe-style listeners
|
| 6 |
+
* (onUpdate/onRoute). Callers manage their own state.
|
| 7 |
+
*/
|
| 8 |
+
|
| 9 |
+
import type {
|
| 10 |
+
ComputeRouteOptions,
|
| 11 |
+
ComputeRouteResult,
|
| 12 |
+
MiniappSession,
|
| 13 |
+
NavigationDev,
|
| 14 |
+
NavRoute,
|
| 15 |
+
NavState,
|
| 16 |
+
NavUpdate,
|
| 17 |
+
Pivot,
|
| 18 |
+
PivotEvent,
|
| 19 |
+
StartNavigationOptions,
|
| 20 |
+
} from "@mentra/miniapp/background"
|
| 21 |
+
|
| 22 |
+
import {ManeuverFormatter} from "./ManeuverFormatter"
|
| 23 |
+
|
| 24 |
+
export type NavUpdateListener = (update: NavUpdate) => void
|
| 25 |
+
export type NavRouteListener = (route: NavRoute) => void
|
| 26 |
+
export type PivotListener = (event: PivotEvent) => void
|
| 27 |
+
export type Unsubscribe = () => void
|
| 28 |
+
|
| 29 |
+
export class NavigationManager {
|
| 30 |
+
/**
|
| 31 |
+
* Presentation helpers for `NavManeuver` data — glyphs, arrows, human
|
| 32 |
+
* verbs, headlines, glasses lines. Lives here so all maneuver-related
|
| 33 |
+
* stuff is reachable via `user.navigation.format.*`.
|
| 34 |
+
*/
|
| 35 |
+
readonly format = new ManeuverFormatter()
|
| 36 |
+
|
| 37 |
+
constructor(private readonly session: MiniappSession) {}
|
| 38 |
+
|
| 39 |
+
/** True iff `LOCATION` is declared in the miniapp's manifest. */
|
| 40 |
+
get hasPermission(): boolean {
|
| 41 |
+
return this.session.navigation.hasPermission
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
/**
|
| 45 |
+
* Trigger the Google Nav SDK Terms & Conditions dialog. Idempotent and
|
| 46 |
+
* intended to be called eagerly on mount so `start()` is friction-free.
|
| 47 |
+
*/
|
| 48 |
+
requestPermission(): Promise<{ok: boolean; accepted: boolean; error?: string}> {
|
| 49 |
+
return this.session.navigation.requestPermission()
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
/** Begin a turn-by-turn trip. */
|
| 53 |
+
start(opts: StartNavigationOptions): Promise<{ok: boolean; error?: string}> {
|
| 54 |
+
return this.session.navigation.start(opts)
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
/** Stop the active trip (if any). Fire-and-forget. */
|
| 58 |
+
stop(): void {
|
| 59 |
+
this.session.navigation.stop()
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
/**
|
| 63 |
+
* Dev-only helpers (simulator deviation, wrong-sidewalk lock,
|
| 64 |
+
* skip-crossings). Throws in production builds — gate all calls
|
| 65 |
+
* behind `if (process.env.NODE_ENV !== "production")`. See
|
| 66 |
+
* `NavigationModule.dev` for the underlying API.
|
| 67 |
+
*/
|
| 68 |
+
get dev(): NavigationDev {
|
| 69 |
+
return this.session.navigation.dev
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
/** Subscribe to maneuver / rerouting / arrived / error events. */
|
| 73 |
+
onUpdate(handler: NavUpdateListener): Unsubscribe {
|
| 74 |
+
return this.session.navigation.onUpdate(handler)
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
/** Subscribe to the route polyline (full path each time it's rebuilt). */
|
| 78 |
+
onRoute(handler: NavRouteListener): Unsubscribe {
|
| 79 |
+
return this.session.navigation.onRoute(handler)
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
/**
|
| 83 |
+
* Snapshot of the active trip; null when no trip is running. Use on
|
| 84 |
+
* mount to hydrate state for a miniapp opening mid-trip.
|
| 85 |
+
*/
|
| 86 |
+
getState(): Promise<NavState | null> {
|
| 87 |
+
return this.session.navigation.getState()
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
/** Compute one or more routes without starting a trip. */
|
| 91 |
+
computeRoute(opts: ComputeRouteOptions): Promise<ComputeRouteResult> {
|
| 92 |
+
return this.session.navigation.computeRoute(opts)
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
/**
|
| 96 |
+
* Reverse-geocode a coordinate to a road name + full address via the SDK,
|
| 97 |
+
* which routes through the v2 cloud maps service (the WebView never calls a
|
| 98 |
+
* maps provider directly). Normalizes the SDK's `{ok, road?, address?}` into a
|
| 99 |
+
* plain `{road, address}` for the RPC channel — a failed lookup surfaces as
|
| 100 |
+
* `{road: null, address: null}` rather than throwing, so dropped-pin / POI UI
|
| 101 |
+
* just falls back to coordinates.
|
| 102 |
+
*/
|
| 103 |
+
async reverseGeocode(coord: {lat: number; lng: number}): Promise<{
|
| 104 |
+
road: string | null
|
| 105 |
+
address: string | null
|
| 106 |
+
}> {
|
| 107 |
+
const result = await this.session.navigation.reverseGeocodeRoad(coord)
|
| 108 |
+
if (!result.ok) return {road: null, address: null}
|
| 109 |
+
return {road: result.road ?? null, address: result.address ?? null}
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
/** Subscribe to pivot events (approaching / entered / exited). */
|
| 113 |
+
onPivot(handler: PivotListener): Unsubscribe {
|
| 114 |
+
return this.session.navigation.onPivot(handler)
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
/** Full pivot list for the active route. */
|
| 118 |
+
getPivots(): Pivot[] {
|
| 119 |
+
return this.session.navigation.getPivots()
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
/** Pivot the user is currently inside the radius of, or null. */
|
| 123 |
+
getActivePivot(): Pivot | null {
|
| 124 |
+
return this.session.navigation.getActivePivot()
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
/** Next pivot ahead, or null when past the final pivot. */
|
| 128 |
+
getUpcomingPivot(): Pivot | null {
|
| 129 |
+
return this.session.navigation.getUpcomingPivot()
|
| 130 |
+
}
|
| 131 |
+
}
|
miniapps/navigation/src/background/managers/PlacesManager.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* PlacesManager
|
| 3 |
+
*
|
| 4 |
+
* Background-side Places facade. Wraps `PlacesSession` so the
|
| 5 |
+
* `NavigationController` can expose `places:autocomplete` and
|
| 6 |
+
* `places:details` as RPC channels. The underlying session token is
|
| 7 |
+
* reset after every successful `details()` so the next autocomplete
|
| 8 |
+
* begins a fresh billing session.
|
| 9 |
+
*
|
| 10 |
+
* Place search goes through the miniapp SDK → host → v2 cloud maps service
|
| 11 |
+
* (Mapbox Search Box). There is no backend Worker. The request/response SDK
|
| 12 |
+
* bridge has no mid-flight cancellation, so a superseded keystroke can't abort
|
| 13 |
+
* an in-flight call — the UI's debounce limits wasted calls and the cloud
|
| 14 |
+
* coalesces identical prefixes, so this is fine.
|
| 15 |
+
*/
|
| 16 |
+
|
| 17 |
+
import {PlacesSession} from "../lib/places"
|
| 18 |
+
import type {PlaceDetails, PlaceSuggestion} from "../lib/places"
|
| 19 |
+
import type {MiniappSession} from "@mentra/miniapp"
|
| 20 |
+
|
| 21 |
+
export class PlacesManager {
|
| 22 |
+
private session: PlacesSession
|
| 23 |
+
|
| 24 |
+
constructor(session: MiniappSession) {
|
| 25 |
+
this.session = new PlacesSession(session)
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
autocomplete(
|
| 29 |
+
query: string,
|
| 30 |
+
near: {lat: number; lng: number} | undefined,
|
| 31 |
+
): Promise<PlaceSuggestion[]> {
|
| 32 |
+
return this.session.autocomplete(query, near)
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
async details(placeId: string): Promise<PlaceDetails> {
|
| 36 |
+
const result = await this.session.details(placeId)
|
| 37 |
+
// Rotate the session token after a successful pick so the next
|
| 38 |
+
// autocomplete is billed as a new session.
|
| 39 |
+
this.session.reset()
|
| 40 |
+
return result
|
| 41 |
+
}
|
| 42 |
+
}
|
miniapps/navigation/src/background/managers/SimpleStorageManager.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* SimpleStorageManager
|
| 3 |
+
*
|
| 4 |
+
* Thin wrapper over `session.storage` for persistent phone-local key-value
|
| 5 |
+
* storage scoped to this miniapp. Values are always strings — callers
|
| 6 |
+
* JSON.stringify / JSON.parse structured data themselves.
|
| 7 |
+
*
|
| 8 |
+
* const storage = new SimpleStorageManager(session)
|
| 9 |
+
* await storage.set("recentDestinations", JSON.stringify([...]))
|
| 10 |
+
* const raw = await storage.get("recentDestinations")
|
| 11 |
+
*/
|
| 12 |
+
|
| 13 |
+
import type {MiniappSession} from "@mentra/miniapp"
|
| 14 |
+
import type {PlaceDetails, SavedPlace} from "../lib/places"
|
| 15 |
+
import type {UnitSystem, VoiceGuidanceMode} from "../../shared/types"
|
| 16 |
+
|
| 17 |
+
export class SimpleStorageManager {
|
| 18 |
+
constructor(private readonly session: MiniappSession) {}
|
| 19 |
+
|
| 20 |
+
/** Retrieve a value by key. Returns null if the key does not exist. */
|
| 21 |
+
get(key: string): Promise<string | null> {
|
| 22 |
+
return this.session.storage.get(key)
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
/** Store a string value. Overwrites any existing value for the key. */
|
| 26 |
+
set(key: string, value: string): Promise<void> {
|
| 27 |
+
return this.session.storage.set(key, value)
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
/** Remove a key. No-op if the key does not exist. */
|
| 31 |
+
delete(key: string): Promise<void> {
|
| 32 |
+
return this.session.storage.delete(key)
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
/** List all keys currently stored for this miniapp. */
|
| 36 |
+
list(): Promise<string[]> {
|
| 37 |
+
return this.session.storage.list()
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
/** Convenience: get and JSON.parse in one call. Returns null on miss or parse error. */
|
| 41 |
+
async getJSON<T>(key: string): Promise<T | null> {
|
| 42 |
+
const raw = await this.session.storage.get(key)
|
| 43 |
+
if (raw === null) return null
|
| 44 |
+
try {
|
| 45 |
+
return JSON.parse(raw) as T
|
| 46 |
+
} catch {
|
| 47 |
+
return null
|
| 48 |
+
}
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
/** Convenience: JSON.stringify and set in one call. */
|
| 52 |
+
setJSON<T>(key: string, value: T): Promise<void> {
|
| 53 |
+
return this.session.storage.set(key, JSON.stringify(value))
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
private static readonly RECENT_SEARCHES_KEY = "recentSearches"
|
| 57 |
+
private static readonly RECENT_SEARCHES_MAX = 10
|
| 58 |
+
|
| 59 |
+
/** Returns the saved list of recent searches, most recent first. */
|
| 60 |
+
async getRecentSearches(): Promise<PlaceDetails[]> {
|
| 61 |
+
return (await this.getJSON<PlaceDetails[]>(SimpleStorageManager.RECENT_SEARCHES_KEY)) ?? []
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
/** Prepends a place to the recent searches list, deduplicates by placeId, and caps at 10. */
|
| 65 |
+
async addRecentSearch(place: PlaceDetails): Promise<void> {
|
| 66 |
+
const current = await this.getRecentSearches()
|
| 67 |
+
const next = [place, ...current.filter((p) => p.placeId !== place.placeId)].slice(0, SimpleStorageManager.RECENT_SEARCHES_MAX)
|
| 68 |
+
await this.setJSON(SimpleStorageManager.RECENT_SEARCHES_KEY, next)
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
private static readonly SAVED_PLACES_KEY = "savedPlaces"
|
| 72 |
+
private static readonly SAVED_MAX = 20
|
| 73 |
+
|
| 74 |
+
/** Returns all saved places, most recently added first. */
|
| 75 |
+
async getAllSavedPlaces(): Promise<SavedPlace[]> {
|
| 76 |
+
return (await this.getJSON<SavedPlace[]>(SimpleStorageManager.SAVED_PLACES_KEY)) ?? []
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
/**
|
| 80 |
+
* Adds or replaces a saved place (caps at 20).
|
| 81 |
+
*
|
| 82 |
+
* Dedup rules:
|
| 83 |
+
* - If the incoming place has `type: "home"` or `"work"`, any existing
|
| 84 |
+
* entry with the same type is replaced (a user only ever has one
|
| 85 |
+
* Home and one Work).
|
| 86 |
+
* - Otherwise dedup by `placeId` so re-saving the same untagged place
|
| 87 |
+
* moves it to the top instead of duplicating it.
|
| 88 |
+
*/
|
| 89 |
+
async addSavedPlace(place: SavedPlace): Promise<void> {
|
| 90 |
+
const current = await this.getAllSavedPlaces()
|
| 91 |
+
const filtered = current.filter((p) => {
|
| 92 |
+
if (place.type && p.type === place.type) return false
|
| 93 |
+
if (p.placeId === place.placeId) return false
|
| 94 |
+
return true
|
| 95 |
+
})
|
| 96 |
+
const next = [place, ...filtered].slice(0, SimpleStorageManager.SAVED_MAX)
|
| 97 |
+
await this.setJSON(SimpleStorageManager.SAVED_PLACES_KEY, next)
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
/** Removes a saved place by placeId. No-op if it isn't saved. */
|
| 101 |
+
async removeSavedPlace(placeId: string): Promise<void> {
|
| 102 |
+
const current = await this.getAllSavedPlaces()
|
| 103 |
+
const next = current.filter((p) => p.placeId !== placeId)
|
| 104 |
+
if (next.length !== current.length) {
|
| 105 |
+
await this.setJSON(SimpleStorageManager.SAVED_PLACES_KEY, next)
|
| 106 |
+
}
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
private static readonly UNIT_SYSTEM_KEY = "unitSystem"
|
| 110 |
+
|
| 111 |
+
/** Returns the saved distance-unit preference, defaulting to "metric". */
|
| 112 |
+
async getUnitSystem(): Promise<UnitSystem> {
|
| 113 |
+
const raw = await this.get(SimpleStorageManager.UNIT_SYSTEM_KEY)
|
| 114 |
+
return raw === "imperial" ? "imperial" : "metric"
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
/** Persists the distance-unit preference. */
|
| 118 |
+
async setUnitSystem(unit: UnitSystem): Promise<void> {
|
| 119 |
+
await this.set(SimpleStorageManager.UNIT_SYSTEM_KEY, unit)
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
private static readonly VOICE_GUIDANCE_MODE_KEY = "voiceGuidanceMode"
|
| 123 |
+
|
| 124 |
+
/** Null means the user has never chosen, so hardware-aware defaults may apply. */
|
| 125 |
+
async getVoiceGuidanceMode(): Promise<VoiceGuidanceMode | null> {
|
| 126 |
+
const raw = await this.get(SimpleStorageManager.VOICE_GUIDANCE_MODE_KEY)
|
| 127 |
+
return raw === "off" || raw === "essential" || raw === "full" ? raw : null
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
async setVoiceGuidanceMode(mode: VoiceGuidanceMode): Promise<void> {
|
| 131 |
+
await this.set(SimpleStorageManager.VOICE_GUIDANCE_MODE_KEY, mode)
|
| 132 |
+
}
|
| 133 |
+
}
|
miniapps/navigation/src/shared/channels.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Typed channel registry — the single source of truth for every name
|
| 3 |
+
* that flows between this miniapp's background JSContext and its UI
|
| 4 |
+
* WebView. Both halves import this file at build time; the bundler
|
| 5 |
+
* inlines the declarations so there's no runtime cross-boundary I/O.
|
| 6 |
+
*
|
| 7 |
+
* Channels wrapped in `Rpc<Req, Res>` are RPC (call via mentra.request /
|
| 8 |
+
* session.ui.handle). Everything else is broadcast (mentra.send /
|
| 9 |
+
* session.ui.on / session.ui.send).
|
| 10 |
+
*/
|
| 11 |
+
|
| 12 |
+
import type {Rpc} from "@mentra/miniapp/ui"
|
| 13 |
+
import type {
|
| 14 |
+
ComputeRouteOptions,
|
| 15 |
+
ComputeRouteResult,
|
| 16 |
+
NavPermissionResult,
|
| 17 |
+
Pivot,
|
| 18 |
+
StartNavigationOptions,
|
| 19 |
+
} from "@mentra/miniapp"
|
| 20 |
+
|
| 21 |
+
import type {
|
| 22 |
+
Coords,
|
| 23 |
+
DevSettings,
|
| 24 |
+
LogEntry,
|
| 25 |
+
NavRouteStep,
|
| 26 |
+
NavSnapshot,
|
| 27 |
+
PlaceDetails,
|
| 28 |
+
PlaceSuggestion,
|
| 29 |
+
SavedPlace,
|
| 30 |
+
TripState,
|
| 31 |
+
UnitSystem,
|
| 32 |
+
VoiceGuidanceMode,
|
| 33 |
+
} from "./types"
|
| 34 |
+
|
| 35 |
+
export interface Channels {
|
| 36 |
+
// ── background → UI broadcasts ─────────────────────────────────────────
|
| 37 |
+
"nav:snapshot": NavSnapshot // on ui.onOpen
|
| 38 |
+
"nav:coords": Coords // hot
|
| 39 |
+
"nav:heading": {degrees: number} // hot, 10Hz throttled
|
| 40 |
+
"nav:trip-state": TripState // on transitions
|
| 41 |
+
"nav:route": {points: {lat: number; lng: number}[]; steps: NavRouteStep[] | null} // on onRoute
|
| 42 |
+
"nav:pivots": {active: Pivot | null; upcoming: Pivot | null}
|
| 43 |
+
"nav:log-append": LogEntry
|
| 44 |
+
"nav:log-clear": Record<string, never>
|
| 45 |
+
"nav:dev-settings-update": DevSettings
|
| 46 |
+
"nav:units-update": {unitSystem: UnitSystem}
|
| 47 |
+
"nav:voice-guidance-update": Pick<NavSnapshot, "voiceGuidanceMode" | "capabilities">
|
| 48 |
+
|
| 49 |
+
// ── UI → background broadcasts (fire-and-forget) ───────────────────────
|
| 50 |
+
"nav:start": StartNavigationOptions & {destinationName?: string}
|
| 51 |
+
"nav:stop": Record<string, never>
|
| 52 |
+
"nav:deviate": Record<string, never>
|
| 53 |
+
/** Dev: stop any active trip/sim and snap the map back to the device's
|
| 54 |
+
* real current location (forces a fresh one-shot fix). */
|
| 55 |
+
"nav:reset-location": Record<string, never>
|
| 56 |
+
"nav:set-destination": PlaceDetails | null
|
| 57 |
+
"nav:set-dev-settings": Partial<DevSettings>
|
| 58 |
+
"nav:set-show-minimap": boolean
|
| 59 |
+
"nav:set-units": {unitSystem: UnitSystem}
|
| 60 |
+
"nav:set-voice-guidance": {mode: VoiceGuidanceMode}
|
| 61 |
+
"nav:repeat-direction": Record<string, never>
|
| 62 |
+
|
| 63 |
+
// ── UI → background RPC ────────────────────────────────────────────────
|
| 64 |
+
"nav:compute-route": Rpc<ComputeRouteOptions, ComputeRouteResult>
|
| 65 |
+
"nav:request-permission": Rpc<void, NavPermissionResult>
|
| 66 |
+
"nav:get-snapshot": Rpc<void, NavSnapshot>
|
| 67 |
+
"nav:get-pivots": Rpc<void, Pivot[]> // full turn list for dev debug dots
|
| 68 |
+
|
| 69 |
+
"places:autocomplete": Rpc<{query: string; near?: {lat: number; lng: number}}, PlaceSuggestion[]>
|
| 70 |
+
"places:details": Rpc<{placeId: string}, PlaceDetails>
|
| 71 |
+
/**
|
| 72 |
+
* Reverse-geocode a coordinate to a road name + full address. Proxies through
|
| 73 |
+
* the background's SDK session into the v2 cloud maps service (auth + cache +
|
| 74 |
+
* rate-limit point) — the WebView never calls a maps provider directly. Each
|
| 75 |
+
* field is null when none of that kind is found near the coordinate.
|
| 76 |
+
*/
|
| 77 |
+
"places:reverse-geocode": Rpc<{lat: number; lng: number}, {road: string | null; address: string | null}>
|
| 78 |
+
|
| 79 |
+
"storage:list-saved": Rpc<void, SavedPlace[]>
|
| 80 |
+
"storage:add-saved": Rpc<SavedPlace, void>
|
| 81 |
+
"storage:remove-saved": Rpc<{placeId: string}, void>
|
| 82 |
+
"storage:list-recent": Rpc<void, PlaceDetails[]>
|
| 83 |
+
"storage:add-recent": Rpc<PlaceDetails, void>
|
| 84 |
+
|
| 85 |
+
// test channels
|
| 86 |
+
"test:show-text-test": Rpc<{text: string; durationMs?: number}, void>
|
| 87 |
+
"test:show-bitmap-test": Rpc<void, void>
|
| 88 |
+
/** Render a gradient test bitmap. `size` is the width; `height` defaults to `size` (square). */
|
| 89 |
+
"test:show-bitmap-size": Rpc<{size: number; height?: number}, void>
|
| 90 |
+
/** PoC: fetch OSM roads around the test center and draw the bare network on the glasses. */
|
| 91 |
+
"test:show-osm-map": Rpc<void, {ok: boolean; error?: string}>
|
| 92 |
+
/** PoC: pan the OSM map view by a small nudge in a direction, then redraw. */
|
| 93 |
+
"test:pan-osm-map": Rpc<{dir: "up" | "down" | "left" | "right"}, {ok: boolean; error?: string}>
|
| 94 |
+
"test:count-1-to-10": Rpc<void, void>
|
| 95 |
+
/**
|
| 96 |
+
* Delay-probe: show the minimap bitmap top-right, then count BOTH text
|
| 97 |
+
* containers (top-left maneuver + bottom-left stats) down from 100 to 0 on
|
| 98 |
+
* the same tick, through the real showManeuver/showTripStats queue. Lets
|
| 99 |
+
* you eyeball whether the two boxes stay in sync or one lags.
|
| 100 |
+
*/
|
| 101 |
+
"test:count-both-boxes": Rpc<void, void>
|
| 102 |
+
"test:reset-nav-permission": Rpc<void, {ok: boolean; error?: string}>
|
| 103 |
+
/** Test: render the large centered map bitmap at a given size on demand. */
|
| 104 |
+
"test:show-large-map": Rpc<{size?: number}, {ok: boolean; error?: string}>
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
// Convenience: the typed shape of `window.mentra` for this miniapp.
|
| 108 |
+
declare global {
|
| 109 |
+
// eslint-disable-next-line no-var
|
| 110 |
+
var mentra: import("@mentra/miniapp/ui").MentraTyped<Channels>
|
| 111 |
+
}
|
miniapps/navigation/src/shared/maneuverDisplay.ts
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Shared maneuver → display derivation.
|
| 3 |
+
*
|
| 4 |
+
* SINGLE SOURCE OF TRUTH for what the next-turn UI says. Both the phone
|
| 5 |
+
* OrientationCard and the glasses HUD consume this so they can never drift
|
| 6 |
+
* apart on instruction text, distance, or turn direction — they read the
|
| 7 |
+
* exact same Mapbox `maneuver` event through the exact same logic.
|
| 8 |
+
*
|
| 9 |
+
* It returns the raw PIECES (instruction string, distance in meters, arrow
|
| 10 |
+
* glyph, an "at turn / arriving" mode) rather than a finished string, so
|
| 11 |
+
* each surface can lay them out its own way (the card is two lines; the
|
| 12 |
+
* glasses HUD prepends a directional arrow) while still agreeing on every
|
| 13 |
+
* value. Distance formatting is left to the caller so each side applies its
|
| 14 |
+
* own unit system.
|
| 15 |
+
*/
|
| 16 |
+
|
| 17 |
+
import type {NavManeuver} from "@mentra/miniapp"
|
| 18 |
+
import type {NavStatus} from "./types"
|
| 19 |
+
|
| 20 |
+
/** Distance (m) at/under which we say "Now" instead of "In X m". */
|
| 21 |
+
const AT_TURN_M = 10
|
| 22 |
+
|
| 23 |
+
export type ManeuverDisplay = {
|
| 24 |
+
/** Big instruction line — Mapbox's verbatim text, or a reconstructed verb+road. */
|
| 25 |
+
instruction: string
|
| 26 |
+
/** Maneuver kind (drives icon on the card, arrow glyph on the HUD). */
|
| 27 |
+
kind: string
|
| 28 |
+
/** Directional arrow glyph for the glasses HUD (←/→/↑). */
|
| 29 |
+
arrow: string
|
| 30 |
+
/**
|
| 31 |
+
* Distance to the maneuver in meters, or null when unknown. Callers
|
| 32 |
+
* format this with their own unit system (e.g. `In ${formatDistance(...)}`).
|
| 33 |
+
*/
|
| 34 |
+
distanceMeters: number | null
|
| 35 |
+
/** True within AT_TURN_M of the maneuver — show "Now" instead of distance. */
|
| 36 |
+
atTurn: boolean
|
| 37 |
+
/** Final-leg arrival mode: show "Arriving in <distanceMeters>" not "In X m, <turn>". */
|
| 38 |
+
arriving: boolean
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
/**
|
| 42 |
+
* Derive the shared display fields from the live `maneuver` event (Mapbox's
|
| 43 |
+
* own current-step tracking, delivered natively from RouteProgress).
|
| 44 |
+
* Returns null when there's nothing to show (no maneuver / arrived) — the
|
| 45 |
+
* caller decides the empty/arrival framing.
|
| 46 |
+
*
|
| 47 |
+
* `liveDistanceMeters` (optional): a freshly-computed distance to the next
|
| 48 |
+
* maneuver, derived from the user's LIVE position against the route polyline by
|
| 49 |
+
* the caller (see liveDistanceToNextTurn). When provided it OVERRIDES the
|
| 50 |
+
* maneuver event's own `distanceMeters`, so the "In X m" / "Arriving in X m"
|
| 51 |
+
* line ticks down on every location update instead of only when a new native
|
| 52 |
+
* RouteProgress maneuver event arrives. Both the phone card and the glasses HUD
|
| 53 |
+
* pass it, so they recompute identically and stay in lockstep — without waiting
|
| 54 |
+
* on a background→UI re-broadcast. Omit it to use the event's own distance.
|
| 55 |
+
*/
|
| 56 |
+
export function deriveManeuverDisplay(
|
| 57 |
+
maneuver: NavManeuver | null,
|
| 58 |
+
status: NavStatus | undefined,
|
| 59 |
+
liveDistanceMeters?: number | null,
|
| 60 |
+
): ManeuverDisplay | null {
|
| 61 |
+
if (status === "arrived" || !maneuver) return null
|
| 62 |
+
|
| 63 |
+
const kind = maneuver.maneuverType
|
| 64 |
+
const instructionRaw = maneuver.instruction?.trim() || null
|
| 65 |
+
|
| 66 |
+
// Prefer the live position-derived distance when the caller supplies one;
|
| 67 |
+
// fall back to the maneuver event's own (slower-updating) distance.
|
| 68 |
+
const liveDist =
|
| 69 |
+
liveDistanceMeters != null && liveDistanceMeters >= 0 ? liveDistanceMeters : null
|
| 70 |
+
const eventDist =
|
| 71 |
+
maneuver.distanceMeters != null && maneuver.distanceMeters >= 0 ? maneuver.distanceMeters : null
|
| 72 |
+
// DISPLAYED distance: live (smooth) when available, else the event's.
|
| 73 |
+
const distanceMeters = liveDist ?? eventDist
|
| 74 |
+
|
| 75 |
+
// "At turn" (and therefore whether to show a DIRECTIONAL arrow) must be gated
|
| 76 |
+
// on the EVENT's own distance — NOT the live distance. Reason: `kind` (the
|
| 77 |
+
// turn direction) comes from the maneuver EVENT, while `liveDist` is derived
|
| 78 |
+
// from the live position against the route STEPS and can already be measuring
|
| 79 |
+
// the turn AFTER the one `kind` describes. If we let liveDist decide atTurn,
|
| 80 |
+
// there's a brief window right as you pass a turn where liveDist says "now"
|
| 81 |
+
// but `kind` still points at the wrong/next turn — that's the flash of the
|
| 82 |
+
// wrong arrow (right turn shows, then a left arrow blips before it settles).
|
| 83 |
+
// Gating atTurn on eventDist keeps the arrow and its direction from the SAME
|
| 84 |
+
// turn, so the glyph can never disagree with the distance that triggered it.
|
| 85 |
+
const atTurn = eventDist != null && eventDist <= AT_TURN_M
|
| 86 |
+
|
| 87 |
+
// Arrival leg (the LAST step) — show ONLY the destination countdown
|
| 88 |
+
// ("Arriving in X m") and drop the turn instruction entirely: there are no
|
| 89 |
+
// more turns, just the destination ahead. Fires for ANY ARRIVE maneuver,
|
| 90 |
+
// even when Mapbox supplies an instruction string ("Your destination is on
|
| 91 |
+
// the right.") — we deliberately replace that with the clean countdown.
|
| 92 |
+
if (kind === "ARRIVE") {
|
| 93 |
+
// On the arrival leg the relevant distance is to the destination. Prefer
|
| 94 |
+
// the live distance (caller passes distance-to-destination here), else the
|
| 95 |
+
// event's own toDest.
|
| 96 |
+
const toDest = liveDist ?? maneuver.distanceToDestinationMeters
|
| 97 |
+
return {
|
| 98 |
+
instruction: "Arriving",
|
| 99 |
+
kind: "ARRIVE",
|
| 100 |
+
arrow: "↑",
|
| 101 |
+
distanceMeters: toDest != null && toDest >= 0 ? toDest : null,
|
| 102 |
+
atTurn: false,
|
| 103 |
+
arriving: true,
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
// Bottom/instruction line: Mapbox's verbatim instruction, falling back to
|
| 108 |
+
// a reconstructed "<verb> onto <road>" only when none is present.
|
| 109 |
+
let instruction = instructionRaw
|
| 110 |
+
if (!instruction) {
|
| 111 |
+
const verb = verbForManeuver(kind)
|
| 112 |
+
const onto = realRoadName(maneuver.nextStepRoad)
|
| 113 |
+
instruction = onto ? `${verb} onto ${onto}` : verb
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
return {
|
| 117 |
+
instruction,
|
| 118 |
+
kind,
|
| 119 |
+
// Directional arrow (←/→) ONLY once we're AT the turn (atTurn / "Now").
|
| 120 |
+
// While still approaching ("In 90 m, turn left") the arrow stays ↑ —
|
| 121 |
+
// straight ahead — so it doesn't claim "turn now" the whole walk in.
|
| 122 |
+
// Applies to both the glasses HUD and the phone card (shared source).
|
| 123 |
+
arrow: atTurn ? arrowForKind(kind) : "↑",
|
| 124 |
+
distanceMeters,
|
| 125 |
+
atTurn,
|
| 126 |
+
arriving: false,
|
| 127 |
+
}
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
/**
|
| 131 |
+
* Live distance (m) from the user's current position to the NEXT maneuver,
|
| 132 |
+
* measured ALONG the route — the value that should drive the "In X m" line so
|
| 133 |
+
* it ticks down on every location update (not only when a native maneuver event
|
| 134 |
+
* fires). SHARED by the phone card and the glasses HUD so both recompute the
|
| 135 |
+
* same number from the same live coords.
|
| 136 |
+
*
|
| 137 |
+
* `remaining` is the caller's `remainingRouteMeters(point, route)` implementation
|
| 138 |
+
* (injected so this shared module stays free of a geometry import / cross-layer
|
| 139 |
+
* dependency). Returns null when it can't be computed — caller then falls back
|
| 140 |
+
* to the maneuver event's own distance.
|
| 141 |
+
*
|
| 142 |
+
* Algorithm: the next turn is the closest route step still AHEAD of the user.
|
| 143 |
+
* Each step's remaining-along-route distance is measured the same way as the
|
| 144 |
+
* user's, so `userRemaining - stepRemaining` is the live gap to that step.
|
| 145 |
+
*
|
| 146 |
+
* Robustness: some routes (e.g. a ferry leg) contain a huge coordinate
|
| 147 |
+
* discontinuity that corrupts the along-route arithmetic, making every gap
|
| 148 |
+
* negative or null. In that case we fall back to the STRAIGHT-LINE (haversine)
|
| 149 |
+
* distance to the nearest step ahead, so the line never freezes. `straightLine`
|
| 150 |
+
* is injected (like `remaining`) to keep this module dependency-free.
|
| 151 |
+
*/
|
| 152 |
+
export function liveDistanceToNextTurn(
|
| 153 |
+
me: {lat: number; lng: number} | null,
|
| 154 |
+
route: Array<{lat: number; lng: number}> | null,
|
| 155 |
+
steps: Array<{lat: number; lng: number}> | null,
|
| 156 |
+
remaining: (
|
| 157 |
+
p: {lat: number; lng: number} | null,
|
| 158 |
+
r: Array<{lat: number; lng: number}> | null,
|
| 159 |
+
) => number | null,
|
| 160 |
+
straightLine?: (a: {lat: number; lng: number}, b: {lat: number; lng: number}) => number,
|
| 161 |
+
): number | null {
|
| 162 |
+
if (!me || !route || route.length < 2 || !steps || steps.length === 0) return null
|
| 163 |
+
|
| 164 |
+
// Primary: along-route gap to the closest step ahead of the user.
|
| 165 |
+
const meRemaining = remaining(me, route)
|
| 166 |
+
if (meRemaining != null) {
|
| 167 |
+
let bestGap: number | null = null
|
| 168 |
+
for (const s of steps) {
|
| 169 |
+
const stepRemaining = remaining({lat: s.lat, lng: s.lng}, route)
|
| 170 |
+
if (stepRemaining == null) continue
|
| 171 |
+
const gap = meRemaining - stepRemaining
|
| 172 |
+
if (gap <= 1) continue // behind us or essentially here — skip
|
| 173 |
+
if (bestGap == null || gap < bestGap) bestGap = gap
|
| 174 |
+
}
|
| 175 |
+
if (bestGap != null) return bestGap
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
// Fallback: straight-line distance to the nearest step (when the along-route
|
| 179 |
+
// math degenerates). Better a slightly-off live number than a frozen one.
|
| 180 |
+
if (straightLine) {
|
| 181 |
+
let best: number | null = null
|
| 182 |
+
for (const s of steps) {
|
| 183 |
+
const d = straightLine(me, {lat: s.lat, lng: s.lng})
|
| 184 |
+
if (d <= 1) continue
|
| 185 |
+
if (best == null || d < best) best = d
|
| 186 |
+
}
|
| 187 |
+
if (best != null) return best
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
return null
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
/** Plain arrow glyph for the glasses HUD (corner-curve variants don't render). */
|
| 194 |
+
export function arrowForKind(kind: string | null | undefined): string {
|
| 195 |
+
const m = (kind ?? "").toUpperCase()
|
| 196 |
+
if (m.includes("LEFT")) return "←"
|
| 197 |
+
if (m.includes("RIGHT")) return "→"
|
| 198 |
+
return "↑"
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
/** Map a ManeuverKind to a verb (fallback when no verbatim instruction). */
|
| 202 |
+
export function verbForManeuver(kind: string): string {
|
| 203 |
+
switch (kind) {
|
| 204 |
+
case "TURN_LEFT":
|
| 205 |
+
case "SLIGHT_LEFT":
|
| 206 |
+
case "SHARP_LEFT":
|
| 207 |
+
return kind === "SLIGHT_LEFT" ? "Slight left" : kind === "SHARP_LEFT" ? "Sharp left" : "Turn left"
|
| 208 |
+
case "TURN_RIGHT":
|
| 209 |
+
case "SLIGHT_RIGHT":
|
| 210 |
+
case "SHARP_RIGHT":
|
| 211 |
+
return kind === "SLIGHT_RIGHT" ? "Slight right" : kind === "SHARP_RIGHT" ? "Sharp right" : "Turn right"
|
| 212 |
+
case "U_TURN":
|
| 213 |
+
return "Turn around"
|
| 214 |
+
case "CONTINUE":
|
| 215 |
+
case "STRAIGHT":
|
| 216 |
+
return "Continue"
|
| 217 |
+
case "NAME_CHANGE":
|
| 218 |
+
return "Continue"
|
| 219 |
+
case "DEPART":
|
| 220 |
+
return "Head out"
|
| 221 |
+
case "CROSS_STREET":
|
| 222 |
+
return "Cross the street"
|
| 223 |
+
default:
|
| 224 |
+
return "Continue"
|
| 225 |
+
}
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
/** Drop instruction-like strings masquerading as road names; trim the rest. */
|
| 229 |
+
export function realRoadName(raw: string | null | undefined): string | null {
|
| 230 |
+
if (!raw) return null
|
| 231 |
+
const trimmed = raw.trim()
|
| 232 |
+
if (trimmed.length === 0) return null
|
| 233 |
+
if (
|
| 234 |
+
/^(toward|turn|continue|destination|head|cross|slight|sharp|keep|merge|fork|exit|take|roundabout|u[\s-]?turn|arrive|arriving|depart|enter|leave|stay)\b/i.test(
|
| 235 |
+
trimmed,
|
| 236 |
+
)
|
| 237 |
+
)
|
| 238 |
+
return null
|
| 239 |
+
return trimmed
|
| 240 |
+
}
|
miniapps/navigation/src/shared/types.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Shared domain types referenced by both the background JSContext and
|
| 3 |
+
* the UI WebView. Both bundlers inline this file at build time, so
|
| 4 |
+
* there's no runtime resolution across the boundary.
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import type {NavManeuver, Pivot} from "@mentra/miniapp"
|
| 8 |
+
|
| 9 |
+
export type Coords = {lat: number; lng: number; accuracy?: number; ts: number}
|
| 10 |
+
export type LatLng = {lat: number; lng: number}
|
| 11 |
+
export type NavStatus = "idle" | "navigating" | "rerouting" | "arrived"
|
| 12 |
+
|
| 13 |
+
/**
|
| 14 |
+
* Distance unit preference. "metric" → m / km, "imperial" → ft / mi.
|
| 15 |
+
* A real user preference (not a dev toggle): persisted in background
|
| 16 |
+
* storage and mirrored to the UI via the snapshot so every distance
|
| 17 |
+
* string — on the map, in drawers, and on the glasses HUD — renders in
|
| 18 |
+
* the chosen system. Defaults to "metric".
|
| 19 |
+
*/
|
| 20 |
+
export type UnitSystem = "metric" | "imperial"
|
| 21 |
+
export type VoiceGuidanceMode = "off" | "essential" | "full"
|
| 22 |
+
export type GlassesCapabilitySnapshot = {
|
| 23 |
+
modelName: string | null
|
| 24 |
+
hasDisplay: boolean
|
| 25 |
+
/** True when the glasses can render positioned scene elements. */
|
| 26 |
+
canPosition: boolean
|
| 27 |
+
hasSpeaker: boolean
|
| 28 |
+
hasButton: boolean
|
| 29 |
+
}
|
| 30 |
+
export type LogEntry = {id: number; ts: number; line: string}
|
| 31 |
+
|
| 32 |
+
export type PlaceSuggestion = {placeId: string; mainText: string; secondaryText?: string}
|
| 33 |
+
export type PlaceDetails = {
|
| 34 |
+
placeId: string
|
| 35 |
+
name: string
|
| 36 |
+
address: string
|
| 37 |
+
lat: number
|
| 38 |
+
lng: number
|
| 39 |
+
/** User-defined label when saved as a favorite or custom place */
|
| 40 |
+
savedName?: string
|
| 41 |
+
/**
|
| 42 |
+
* True while a reverse-geocode is in flight for a dropped pin. The
|
| 43 |
+
* `name` / `address` fields are placeholders (raw lat/lng) until this
|
| 44 |
+
* flips back to false. UI consumers render a skeleton while this is
|
| 45 |
+
* true so the user doesn't see the bare coordinates flash on screen
|
| 46 |
+
* before the real address lands.
|
| 47 |
+
*/
|
| 48 |
+
isGeocoding?: boolean
|
| 49 |
+
}
|
| 50 |
+
export type SavedPlace = PlaceDetails & {
|
| 51 |
+
type?: "home" | "work"
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
/**
|
| 55 |
+
* Trip state mirrored from background to UI. Kept dual `status` +
|
| 56 |
+
* `running` for parity with the existing NavigationPage state machine —
|
| 57 |
+
* `running` is true while `status` ∈ {"navigating","rerouting"}, false
|
| 58 |
+
* otherwise. Collapsing into a single field is a separate refactor.
|
| 59 |
+
*/
|
| 60 |
+
/**
|
| 61 |
+
* One step in the active trip's route, mirrored from the SDK's
|
| 62 |
+
* `NavStep` minus internal fields the UI doesn't need (`routeIndex`).
|
| 63 |
+
* Carries the resolved road name (host-side hybrid resolver) so the
|
| 64 |
+
* UI can build live turn dots from road→road transitions, matching
|
| 65 |
+
* the preview path. `maneuver` is the SDK's `ManeuverKind` string —
|
| 66 |
+
* widened to `string` here to avoid pulling the union into the
|
| 67 |
+
* shared types boundary (the channel layer doesn't gain anything
|
| 68 |
+
* from the narrower type).
|
| 69 |
+
*/
|
| 70 |
+
export type NavRouteStep = {
|
| 71 |
+
lat: number
|
| 72 |
+
lng: number
|
| 73 |
+
road: string | null
|
| 74 |
+
maneuver: string
|
| 75 |
+
distanceMeters: number
|
| 76 |
+
/**
|
| 77 |
+
* Google's verbatim turn-by-turn text for this step (e.g. "Head west
|
| 78 |
+
* on Hayes St toward Gough St"). Populated from the preview-time
|
| 79 |
+
* Routes API response and refetched on reroute. Null when no cached
|
| 80 |
+
* preview is available — consumers fall back to the constructed
|
| 81 |
+
* "Turn left onto Octavia St" rendering.
|
| 82 |
+
*/
|
| 83 |
+
instruction: string | null
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
export type TripState = {
|
| 87 |
+
status: NavStatus
|
| 88 |
+
running: boolean
|
| 89 |
+
maneuver: NavManeuver | null
|
| 90 |
+
activeDestination: LatLng | null
|
| 91 |
+
activeDestinationName: string | null
|
| 92 |
+
routePoints: LatLng[] | null
|
| 93 |
+
/**
|
| 94 |
+
* Step list for the active route, populated alongside `routePoints`
|
| 95 |
+
* from the SDK's onRoute event. Null until the first route lands.
|
| 96 |
+
* Used by NavigationPage to build live turn dots that mirror the
|
| 97 |
+
* preview from→to/direction labels — preview reads steps directly
|
| 98 |
+
* from `computeRoute`, live reads them from here.
|
| 99 |
+
*/
|
| 100 |
+
routeSteps: NavRouteStep[] | null
|
| 101 |
+
offRouteAt: number | null
|
| 102 |
+
/**
|
| 103 |
+
* Side of the final route segment the destination pin sits on, from
|
| 104 |
+
* the walker's perspective. Captured at the moment we fire arrival
|
| 105 |
+
* (either from the early ≤7m-remaining trigger or the SDK's own
|
| 106 |
+
* arrived event) and held alongside `status === "arrived"` so the
|
| 107 |
+
* HUD can render "You have arrived at X, on your left|right".
|
| 108 |
+
* Null while not arrived, or when the route was too short to derive
|
| 109 |
+
* a side.
|
| 110 |
+
*/
|
| 111 |
+
arrivalSide: "left" | "right" | null
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
export type DevSettings = {
|
| 115 |
+
simulate: boolean
|
| 116 |
+
speedMultiplier: number
|
| 117 |
+
wrongSidewalk: boolean
|
| 118 |
+
skipCrossings: boolean
|
| 119 |
+
/**
|
| 120 |
+
* Debug toggle. When on, the maneuver card and glasses HUD swap their
|
| 121 |
+
* constructed "Turn right onto Octavia St" phrasing for Google's raw
|
| 122 |
+
* navigationInstruction string (e.g. "Head west on Hayes St toward
|
| 123 |
+
* Gough St"). The distance suffix ("in 198 m") is preserved.
|
| 124 |
+
*/
|
| 125 |
+
useRawInstructions: boolean
|
| 126 |
+
/**
|
| 127 |
+
* Dev toggle for the swipe-up large map (WIP). When OFF (default), swipe
|
| 128 |
+
* gestures do nothing — the large map feature is disabled. When ON, swiping
|
| 129 |
+
* toggles the full-screen route map on/off as usual.
|
| 130 |
+
*/
|
| 131 |
+
largeMapEnabled: boolean
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
export type NavSnapshot = {
|
| 135 |
+
coords: Coords | null
|
| 136 |
+
heading: number | null
|
| 137 |
+
trip: TripState
|
| 138 |
+
activePivot: Pivot | null
|
| 139 |
+
upcomingPivot: Pivot | null
|
| 140 |
+
log: LogEntry[]
|
| 141 |
+
devSettings: DevSettings
|
| 142 |
+
/** User's distance-unit preference. Defaults to "metric". */
|
| 143 |
+
unitSystem: UnitSystem
|
| 144 |
+
voiceGuidanceMode: VoiceGuidanceMode
|
| 145 |
+
capabilities: GlassesCapabilitySnapshot
|
| 146 |
+
}
|
miniapps/navigation/src/test/audio-guidance.test.ts
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/// <reference types="bun-types" />
|
| 2 |
+
|
| 3 |
+
import {afterEach, describe, expect, jest, test} from "bun:test"
|
| 4 |
+
|
| 5 |
+
import {
|
| 6 |
+
AudioGuidanceManager,
|
| 7 |
+
selectAudioGuidanceDistance,
|
| 8 |
+
type AudioGuidanceInput,
|
| 9 |
+
} from "../background/managers/AudioGuidanceManager"
|
| 10 |
+
|
| 11 |
+
function createHarness() {
|
| 12 |
+
const spoken: string[] = []
|
| 13 |
+
let stops = 0
|
| 14 |
+
const manager = new AudioGuidanceManager({
|
| 15 |
+
speak: async (text) => {
|
| 16 |
+
spoken.push(text)
|
| 17 |
+
return {completed: true}
|
| 18 |
+
},
|
| 19 |
+
stop: () => {
|
| 20 |
+
stops += 1
|
| 21 |
+
},
|
| 22 |
+
})
|
| 23 |
+
manager.setAvailable(true)
|
| 24 |
+
return {
|
| 25 |
+
manager,
|
| 26 |
+
spoken,
|
| 27 |
+
get stops() {
|
| 28 |
+
return stops
|
| 29 |
+
},
|
| 30 |
+
}
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
function input(partial: Partial<AudioGuidanceInput> = {}): AudioGuidanceInput {
|
| 34 |
+
return {
|
| 35 |
+
status: "navigating",
|
| 36 |
+
running: true,
|
| 37 |
+
routeRevision: 1,
|
| 38 |
+
pivotIndex: 0,
|
| 39 |
+
maneuverType: "TURN_LEFT",
|
| 40 |
+
instruction: "Turn left onto Market Street",
|
| 41 |
+
distanceMeters: 100,
|
| 42 |
+
offRoute: false,
|
| 43 |
+
destinationName: "Blue Bottle",
|
| 44 |
+
arrivalSide: null,
|
| 45 |
+
travelMode: "walking",
|
| 46 |
+
unitSystem: "metric",
|
| 47 |
+
...partial,
|
| 48 |
+
}
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
async function settleSpeech(): Promise<void> {
|
| 52 |
+
for (let i = 0; i < 6; i += 1) await Promise.resolve()
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
afterEach(() => {
|
| 56 |
+
if (jest.isFakeTimers()) jest.useRealTimers()
|
| 57 |
+
})
|
| 58 |
+
|
| 59 |
+
describe("AudioGuidanceManager", () => {
|
| 60 |
+
test("full guidance speaks at most one preparation and one now prompt per turn", async () => {
|
| 61 |
+
const {manager, spoken} = createHarness()
|
| 62 |
+
manager.setMode("full")
|
| 63 |
+
|
| 64 |
+
manager.observe(input({distanceMeters: 59}))
|
| 65 |
+
await settleSpeech()
|
| 66 |
+
manager.observe(input({distanceMeters: 48}))
|
| 67 |
+
await settleSpeech()
|
| 68 |
+
manager.observe(input({distanceMeters: 9}))
|
| 69 |
+
await settleSpeech()
|
| 70 |
+
manager.observe(input({distanceMeters: 4}))
|
| 71 |
+
await settleSpeech()
|
| 72 |
+
|
| 73 |
+
expect(spoken).toEqual(["In 60 meters, turn left onto Market Street.", "Turn left onto Market Street now."])
|
| 74 |
+
})
|
| 75 |
+
|
| 76 |
+
test("essential guidance skips advance notice but still announces the turn", async () => {
|
| 77 |
+
const {manager, spoken} = createHarness()
|
| 78 |
+
manager.setMode("essential")
|
| 79 |
+
|
| 80 |
+
manager.observe(input({distanceMeters: 55}))
|
| 81 |
+
await settleSpeech()
|
| 82 |
+
manager.observe(input({distanceMeters: 10}))
|
| 83 |
+
await settleSpeech()
|
| 84 |
+
|
| 85 |
+
expect(spoken).toEqual(["Turn left onto Market Street now."])
|
| 86 |
+
})
|
| 87 |
+
|
| 88 |
+
test("route revision and pivot index create fresh maneuver identities", async () => {
|
| 89 |
+
const {manager, spoken} = createHarness()
|
| 90 |
+
manager.setMode("full")
|
| 91 |
+
|
| 92 |
+
manager.observe(input({distanceMeters: 9, pivotIndex: 0}))
|
| 93 |
+
await settleSpeech()
|
| 94 |
+
manager.observe(input({distanceMeters: 9, pivotIndex: 1}))
|
| 95 |
+
await settleSpeech()
|
| 96 |
+
manager.observe(input({distanceMeters: 9, pivotIndex: 1, routeRevision: 2}))
|
| 97 |
+
await settleSpeech()
|
| 98 |
+
|
| 99 |
+
expect(spoken).toHaveLength(3)
|
| 100 |
+
})
|
| 101 |
+
|
| 102 |
+
test("binding a late pivot does not replay the same maneuver", async () => {
|
| 103 |
+
const {manager, spoken} = createHarness()
|
| 104 |
+
manager.setMode("full")
|
| 105 |
+
|
| 106 |
+
manager.observe(input({distanceMeters: 50, pivotIndex: null}))
|
| 107 |
+
await settleSpeech()
|
| 108 |
+
manager.observe(input({distanceMeters: 48, pivotIndex: 0}))
|
| 109 |
+
await settleSpeech()
|
| 110 |
+
|
| 111 |
+
expect(spoken).toEqual(["In 50 meters, turn left onto Market Street."])
|
| 112 |
+
})
|
| 113 |
+
|
| 114 |
+
test("pivotless identical short turns receive distinct action cues", async () => {
|
| 115 |
+
const {manager, spoken} = createHarness()
|
| 116 |
+
manager.setMode("essential")
|
| 117 |
+
|
| 118 |
+
manager.observe(input({distanceMeters: 9, pivotIndex: null}))
|
| 119 |
+
await settleSpeech()
|
| 120 |
+
manager.observe(input({distanceMeters: 20, pivotIndex: null}))
|
| 121 |
+
await settleSpeech()
|
| 122 |
+
manager.observe(input({distanceMeters: 9, pivotIndex: null}))
|
| 123 |
+
await settleSpeech()
|
| 124 |
+
|
| 125 |
+
expect(spoken).toEqual(["Turn left onto Market Street now.", "Turn left onto Market Street now."])
|
| 126 |
+
})
|
| 127 |
+
|
| 128 |
+
test("full guidance announces the final approach once", async () => {
|
| 129 |
+
const {manager, spoken} = createHarness()
|
| 130 |
+
manager.setMode("full")
|
| 131 |
+
|
| 132 |
+
manager.observe(
|
| 133 |
+
input({maneuverType: "ARRIVE", instruction: "Arriving", distanceMeters: 50, pivotIndex: null}),
|
| 134 |
+
)
|
| 135 |
+
await settleSpeech()
|
| 136 |
+
manager.observe(
|
| 137 |
+
input({maneuverType: "ARRIVE", instruction: "Arriving", distanceMeters: 30, pivotIndex: null}),
|
| 138 |
+
)
|
| 139 |
+
await settleSpeech()
|
| 140 |
+
|
| 141 |
+
expect(spoken).toEqual(["Destination in 50 meters."])
|
| 142 |
+
})
|
| 143 |
+
|
| 144 |
+
test("arrival guidance uses live distance without detaching turn cues from their event", () => {
|
| 145 |
+
expect(selectAudioGuidanceDistance("ARRIVE", 120, 35)).toBe(35)
|
| 146 |
+
expect(selectAudioGuidanceDistance("ARRIVE", 120, null)).toBe(120)
|
| 147 |
+
expect(selectAudioGuidanceDistance("TURN_LEFT", 12, 80)).toBe(12)
|
| 148 |
+
})
|
| 149 |
+
|
| 150 |
+
test("a new semantic maneuver stops an in-progress maneuver prompt", async () => {
|
| 151 |
+
const spoken: string[] = []
|
| 152 |
+
let stops = 0
|
| 153 |
+
const manager = new AudioGuidanceManager({
|
| 154 |
+
speak: (text) => {
|
| 155 |
+
spoken.push(text)
|
| 156 |
+
return new Promise(() => {})
|
| 157 |
+
},
|
| 158 |
+
stop: () => {
|
| 159 |
+
stops += 1
|
| 160 |
+
},
|
| 161 |
+
})
|
| 162 |
+
manager.setAvailable(true)
|
| 163 |
+
manager.setMode("full")
|
| 164 |
+
|
| 165 |
+
manager.observe(input({distanceMeters: 50, pivotIndex: 0}))
|
| 166 |
+
manager.observe(
|
| 167 |
+
input({
|
| 168 |
+
maneuverType: "TURN_RIGHT",
|
| 169 |
+
instruction: "Turn right onto Valencia Street",
|
| 170 |
+
distanceMeters: 45,
|
| 171 |
+
pivotIndex: 1,
|
| 172 |
+
}),
|
| 173 |
+
)
|
| 174 |
+
await settleSpeech()
|
| 175 |
+
|
| 176 |
+
expect(spoken).toEqual(["In 50 meters, turn left onto Market Street."])
|
| 177 |
+
expect(stops).toBe(1)
|
| 178 |
+
})
|
| 179 |
+
|
| 180 |
+
test("off-route guidance replaces stale turn cues until the route is regained", async () => {
|
| 181 |
+
const {manager, spoken} = createHarness()
|
| 182 |
+
manager.setMode("essential")
|
| 183 |
+
|
| 184 |
+
manager.observe(input({distanceMeters: 9, offRoute: true}))
|
| 185 |
+
await settleSpeech()
|
| 186 |
+
manager.observe(input({distanceMeters: 7, offRoute: true}))
|
| 187 |
+
await settleSpeech()
|
| 188 |
+
manager.observe(input({distanceMeters: 7, offRoute: false}))
|
| 189 |
+
await settleSpeech()
|
| 190 |
+
|
| 191 |
+
expect(spoken).toEqual(["You are off route. Go back to the route.", "Turn left onto Market Street now."])
|
| 192 |
+
})
|
| 193 |
+
|
| 194 |
+
test("startup grace resumes maneuver guidance when an off-route fix stabilizes", async () => {
|
| 195 |
+
jest.useFakeTimers({now: 100_000})
|
| 196 |
+
const {manager, spoken} = createHarness()
|
| 197 |
+
manager.setMode("essential")
|
| 198 |
+
manager.beginTrip()
|
| 199 |
+
manager.confirmTripStarted("Blue Bottle")
|
| 200 |
+
await settleSpeech()
|
| 201 |
+
|
| 202 |
+
manager.observe(input({distanceMeters: 9, offRoute: true}))
|
| 203 |
+
await settleSpeech()
|
| 204 |
+
|
| 205 |
+
expect(spoken).toEqual(["Navigation started to Blue Bottle."])
|
| 206 |
+
|
| 207 |
+
manager.observe(input({distanceMeters: 9, offRoute: false}))
|
| 208 |
+
await settleSpeech()
|
| 209 |
+
|
| 210 |
+
expect(spoken).toEqual(["Navigation started to Blue Bottle.", "Turn left onto Market Street now."])
|
| 211 |
+
})
|
| 212 |
+
|
| 213 |
+
test("startup off-route warning becomes eligible if the condition outlasts the grace period", async () => {
|
| 214 |
+
jest.useFakeTimers({now: 100_000})
|
| 215 |
+
const {manager, spoken} = createHarness()
|
| 216 |
+
manager.setMode("essential")
|
| 217 |
+
manager.beginTrip()
|
| 218 |
+
manager.confirmTripStarted("Blue Bottle")
|
| 219 |
+
await settleSpeech()
|
| 220 |
+
|
| 221 |
+
manager.observe(input({distanceMeters: 9, offRoute: true}))
|
| 222 |
+
await settleSpeech()
|
| 223 |
+
jest.advanceTimersByTime(15_000)
|
| 224 |
+
manager.observe(input({distanceMeters: 7, offRoute: true}))
|
| 225 |
+
await settleSpeech()
|
| 226 |
+
|
| 227 |
+
expect(spoken).toEqual(["Navigation started to Blue Bottle.", "You are off route. Go back to the route."])
|
| 228 |
+
})
|
| 229 |
+
|
| 230 |
+
test("startup reroute becomes eligible if it is still active after the grace period", async () => {
|
| 231 |
+
jest.useFakeTimers({now: 100_000})
|
| 232 |
+
const {manager, spoken} = createHarness()
|
| 233 |
+
manager.setMode("essential")
|
| 234 |
+
manager.beginTrip()
|
| 235 |
+
manager.confirmTripStarted("Blue Bottle")
|
| 236 |
+
await settleSpeech()
|
| 237 |
+
|
| 238 |
+
manager.observe(input({status: "rerouting", maneuverType: null, instruction: null, distanceMeters: null}))
|
| 239 |
+
await settleSpeech()
|
| 240 |
+
jest.advanceTimersByTime(14_999)
|
| 241 |
+
manager.observe(input({status: "rerouting", maneuverType: null, instruction: null, distanceMeters: null}))
|
| 242 |
+
await settleSpeech()
|
| 243 |
+
|
| 244 |
+
expect(spoken).toEqual(["Navigation started to Blue Bottle."])
|
| 245 |
+
|
| 246 |
+
jest.advanceTimersByTime(1)
|
| 247 |
+
manager.observe(input({status: "rerouting", maneuverType: null, instruction: null, distanceMeters: null}))
|
| 248 |
+
await settleSpeech()
|
| 249 |
+
manager.observe(input({status: "rerouting", maneuverType: null, instruction: null, distanceMeters: null}))
|
| 250 |
+
await settleSpeech()
|
| 251 |
+
|
| 252 |
+
expect(spoken).toEqual(["Navigation started to Blue Bottle.", "Off route. Rerouting."])
|
| 253 |
+
})
|
| 254 |
+
|
| 255 |
+
test("a suppressed startup reroute cancels stale maneuver speech", async () => {
|
| 256 |
+
jest.useFakeTimers({now: 100_000})
|
| 257 |
+
const spoken: string[] = []
|
| 258 |
+
let stops = 0
|
| 259 |
+
const manager = new AudioGuidanceManager({
|
| 260 |
+
speak: (text) => {
|
| 261 |
+
spoken.push(text)
|
| 262 |
+
if (text.startsWith("Turn left")) return new Promise(() => {})
|
| 263 |
+
return Promise.resolve({completed: true})
|
| 264 |
+
},
|
| 265 |
+
stop: () => {
|
| 266 |
+
stops += 1
|
| 267 |
+
},
|
| 268 |
+
})
|
| 269 |
+
manager.setAvailable(true)
|
| 270 |
+
manager.setMode("essential")
|
| 271 |
+
manager.beginTrip()
|
| 272 |
+
manager.confirmTripStarted("Blue Bottle")
|
| 273 |
+
await settleSpeech()
|
| 274 |
+
manager.observe(input({distanceMeters: 9}))
|
| 275 |
+
await settleSpeech()
|
| 276 |
+
|
| 277 |
+
manager.observe(input({status: "rerouting", maneuverType: null, instruction: null, distanceMeters: null}))
|
| 278 |
+
await settleSpeech()
|
| 279 |
+
|
| 280 |
+
expect(spoken).toEqual(["Navigation started to Blue Bottle.", "Turn left onto Market Street now."])
|
| 281 |
+
expect(stops).toBe(1)
|
| 282 |
+
})
|
| 283 |
+
|
| 284 |
+
test("late navigation updates cannot revive guidance after stop or arrival", async () => {
|
| 285 |
+
const stopped = createHarness()
|
| 286 |
+
stopped.manager.setMode("essential")
|
| 287 |
+
stopped.manager.beginTrip()
|
| 288 |
+
stopped.manager.endTrip()
|
| 289 |
+
stopped.manager.observe(input({distanceMeters: 9}))
|
| 290 |
+
await settleSpeech()
|
| 291 |
+
expect(stopped.spoken).toEqual([])
|
| 292 |
+
|
| 293 |
+
const arrived = createHarness()
|
| 294 |
+
arrived.manager.setMode("essential")
|
| 295 |
+
arrived.manager.beginTrip()
|
| 296 |
+
arrived.manager.confirmTripStarted("Blue Bottle")
|
| 297 |
+
await settleSpeech()
|
| 298 |
+
arrived.manager.observe(
|
| 299 |
+
input({status: "arrived", running: false, maneuverType: null, instruction: null, distanceMeters: null}),
|
| 300 |
+
)
|
| 301 |
+
await settleSpeech()
|
| 302 |
+
arrived.manager.observe(input({distanceMeters: 9}))
|
| 303 |
+
await settleSpeech()
|
| 304 |
+
expect(arrived.spoken).toEqual(["Navigation started to Blue Bottle.", "You have arrived at Blue Bottle."])
|
| 305 |
+
})
|
| 306 |
+
|
| 307 |
+
test("distance jitter after a now cue cannot backtrack into preparation", async () => {
|
| 308 |
+
const {manager, spoken} = createHarness()
|
| 309 |
+
manager.setMode("full")
|
| 310 |
+
|
| 311 |
+
manager.observe(input({distanceMeters: 9, pivotIndex: null}))
|
| 312 |
+
await settleSpeech()
|
| 313 |
+
manager.observe(input({distanceMeters: 16, pivotIndex: null}))
|
| 314 |
+
await settleSpeech()
|
| 315 |
+
|
| 316 |
+
expect(spoken).toEqual(["Turn left onto Market Street now."])
|
| 317 |
+
})
|
| 318 |
+
|
| 319 |
+
test("start confirmation leads a maneuver received during startup", async () => {
|
| 320 |
+
jest.useFakeTimers({now: 100_000})
|
| 321 |
+
const {manager, spoken} = createHarness()
|
| 322 |
+
manager.setMode("full")
|
| 323 |
+
manager.beginTrip()
|
| 324 |
+
|
| 325 |
+
manager.observe(input({distanceMeters: 50}))
|
| 326 |
+
expect(spoken).toEqual([])
|
| 327 |
+
manager.confirmTripStarted(null)
|
| 328 |
+
await settleSpeech()
|
| 329 |
+
jest.advanceTimersByTime(4_000)
|
| 330 |
+
await settleSpeech()
|
| 331 |
+
|
| 332 |
+
expect(spoken).toEqual(["Navigation started.", "In 50 meters, turn left onto Market Street."])
|
| 333 |
+
})
|
| 334 |
+
|
| 335 |
+
test("rerouting and arrival are each announced once", async () => {
|
| 336 |
+
jest.useFakeTimers({now: 100_000})
|
| 337 |
+
const {manager, spoken} = createHarness()
|
| 338 |
+
manager.setMode("essential")
|
| 339 |
+
manager.beginTrip()
|
| 340 |
+
manager.confirmTripStarted("Blue Bottle")
|
| 341 |
+
await settleSpeech()
|
| 342 |
+
jest.advanceTimersByTime(15_000)
|
| 343 |
+
|
| 344 |
+
manager.observe(input({status: "rerouting", maneuverType: null, instruction: null, distanceMeters: null}))
|
| 345 |
+
await settleSpeech()
|
| 346 |
+
manager.observe(input({status: "rerouting", maneuverType: null, instruction: null, distanceMeters: null}))
|
| 347 |
+
await settleSpeech()
|
| 348 |
+
manager.observe(
|
| 349 |
+
input({
|
| 350 |
+
status: "arrived",
|
| 351 |
+
running: false,
|
| 352 |
+
maneuverType: null,
|
| 353 |
+
instruction: null,
|
| 354 |
+
distanceMeters: null,
|
| 355 |
+
arrivalSide: "right",
|
| 356 |
+
}),
|
| 357 |
+
)
|
| 358 |
+
await settleSpeech()
|
| 359 |
+
|
| 360 |
+
expect(spoken).toEqual([
|
| 361 |
+
"Navigation started to Blue Bottle.",
|
| 362 |
+
"Off route. Rerouting.",
|
| 363 |
+
"You have arrived at Blue Bottle, on your right.",
|
| 364 |
+
])
|
| 365 |
+
})
|
| 366 |
+
|
| 367 |
+
test("repeat speaks the latest live instruction and off stops all speech", async () => {
|
| 368 |
+
const harness = createHarness()
|
| 369 |
+
harness.manager.setMode("full")
|
| 370 |
+
harness.manager.beginTrip()
|
| 371 |
+
harness.manager.confirmTripStarted(null)
|
| 372 |
+
await settleSpeech()
|
| 373 |
+
harness.manager.observe(input({distanceMeters: 42}))
|
| 374 |
+
await settleSpeech()
|
| 375 |
+
|
| 376 |
+
expect(harness.manager.repeatCurrent()).toBe(true)
|
| 377 |
+
await settleSpeech()
|
| 378 |
+
harness.manager.setMode("off")
|
| 379 |
+
expect(harness.manager.repeatCurrent()).toBe(false)
|
| 380 |
+
expect(harness.spoken.at(-1)).toBe("In 40 meters, turn left onto Market Street.")
|
| 381 |
+
})
|
| 382 |
+
|
| 383 |
+
test("urgent turn cue cancels deferred advance notice", async () => {
|
| 384 |
+
jest.useFakeTimers({now: 100_000})
|
| 385 |
+
const {manager, spoken} = createHarness()
|
| 386 |
+
manager.setMode("full")
|
| 387 |
+
manager.beginTrip()
|
| 388 |
+
manager.confirmTripStarted(null)
|
| 389 |
+
await settleSpeech()
|
| 390 |
+
|
| 391 |
+
// This preparation prompt waits for the automatic gap after the start
|
| 392 |
+
// announcement. The urgent action cue must supersede it completely.
|
| 393 |
+
manager.observe(input({distanceMeters: 50}))
|
| 394 |
+
manager.observe(input({distanceMeters: 9}))
|
| 395 |
+
await settleSpeech()
|
| 396 |
+
jest.advanceTimersByTime(4_000)
|
| 397 |
+
await settleSpeech()
|
| 398 |
+
|
| 399 |
+
expect(spoken).toEqual(["Navigation started.", "Turn left onto Market Street now."])
|
| 400 |
+
})
|
| 401 |
+
|
| 402 |
+
test("new trip clears the previous arrival repeat phrase", async () => {
|
| 403 |
+
const {manager} = createHarness()
|
| 404 |
+
manager.setMode("essential")
|
| 405 |
+
manager.beginTrip()
|
| 406 |
+
manager.observe(
|
| 407 |
+
input({
|
| 408 |
+
status: "arrived",
|
| 409 |
+
running: false,
|
| 410 |
+
maneuverType: null,
|
| 411 |
+
instruction: null,
|
| 412 |
+
distanceMeters: null,
|
| 413 |
+
}),
|
| 414 |
+
)
|
| 415 |
+
await settleSpeech()
|
| 416 |
+
|
| 417 |
+
manager.beginTrip()
|
| 418 |
+
|
| 419 |
+
expect(manager.repeatCurrent()).toBe(false)
|
| 420 |
+
})
|
| 421 |
+
})
|
miniapps/navigation/src/test/bitmaps/fetch-static-maps.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Fetch Google Static Maps images and save them next to this file, so we can
|
| 3 |
+
* eyeball what kind of picture the glasses bitmap pipeline could render from a
|
| 4 |
+
* real map tile (different zooms / sizes / map types).
|
| 5 |
+
*
|
| 6 |
+
* The API key is read from PUBLIC_MAP_NAV_VIEWER (the navigation miniapp's
|
| 7 |
+
* map key — Bun auto-loads it from .env). NOTE: that key is normally restricted
|
| 8 |
+
* to the Maps JavaScript API + an HTTP-referrer; the Static Maps API is a
|
| 9 |
+
* different endpoint, so if it's restricted you'll get a 403 / "API key not
|
| 10 |
+
* authorized" PNG back. In that case enable "Maps Static API" for the key
|
| 11 |
+
* (or use an unrestricted key) — see the console URL in .env.example.
|
| 12 |
+
*
|
| 13 |
+
* Run: bun run src/test/bitmaps/fetch-static-maps.ts
|
| 14 |
+
*/
|
| 15 |
+
|
| 16 |
+
const API_KEY = process.env.PUBLIC_MAP_NAV_VIEWER
|
| 17 |
+
|
| 18 |
+
if (!API_KEY || API_KEY.startsWith("your_") || API_KEY.startsWith("YOUR_")) {
|
| 19 |
+
console.error(
|
| 20 |
+
"✗ PUBLIC_MAP_NAV_VIEWER is not set (or is a placeholder). Add it to .env.",
|
| 21 |
+
)
|
| 22 |
+
process.exit(1)
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
const BASE = "https://maps.googleapis.com/maps/api/staticmap"
|
| 26 |
+
|
| 27 |
+
// Center used in the examples (Lower Manhattan).
|
| 28 |
+
const CENTER = "40.714728,-73.998672"
|
| 29 |
+
|
| 30 |
+
// A spread of variations so we can compare what reads well on a 1-bit-ish
|
| 31 |
+
// glasses display: zoom levels, output sizes, and map types.
|
| 32 |
+
type MapRequest = {name: string; params: Record<string, string>}
|
| 33 |
+
|
| 34 |
+
const REQUESTS: MapRequest[] = [
|
| 35 |
+
{name: "z12-400x400", params: {center: CENTER, zoom: "12", size: "400x400"}},
|
| 36 |
+
{name: "z14-400x400", params: {center: CENTER, zoom: "14", size: "400x400"}},
|
| 37 |
+
{name: "z16-400x400", params: {center: CENTER, zoom: "16", size: "400x400"}},
|
| 38 |
+
// Match the glasses container shapes we've been testing.
|
| 39 |
+
{name: "z14-200x88", params: {center: CENTER, zoom: "14", size: "200x88"}},
|
| 40 |
+
{name: "z14-200x100", params: {center: CENTER, zoom: "14", size: "200x100"}},
|
| 41 |
+
// Map type variations — roadmap vs high-contrast options.
|
| 42 |
+
{name: "z14-roadmap", params: {center: CENTER, zoom: "14", size: "400x400", maptype: "roadmap"}},
|
| 43 |
+
{name: "z14-terrain", params: {center: CENTER, zoom: "14", size: "400x400", maptype: "terrain"}},
|
| 44 |
+
{name: "z14-satellite", params: {center: CENTER, zoom: "14", size: "400x400", maptype: "satellite"}},
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
function buildUrl(params: Record<string, string>): string {
|
| 48 |
+
const q = new URLSearchParams({...params, key: API_KEY!})
|
| 49 |
+
return `${BASE}?${q.toString()}`
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
// The key is HTTP-referrer-restricted, but a CLI fetch sends no referrer and
|
| 53 |
+
// gets rejected. We forge a Referer header matching one of the key's allowed
|
| 54 |
+
// referrer patterns so the request is accepted WITHOUT loosening the key.
|
| 55 |
+
// Override via STATIC_MAPS_REFERER if the key allows a different domain.
|
| 56 |
+
const REFERER = process.env.STATIC_MAPS_REFERER ?? "https://console.mentra.glass/"
|
| 57 |
+
|
| 58 |
+
const outDir = new URL(".", import.meta.url).pathname
|
| 59 |
+
|
| 60 |
+
async function fetchOne(req: MapRequest): Promise<void> {
|
| 61 |
+
const url = buildUrl(req.params)
|
| 62 |
+
// Log the URL with the key redacted so it's safe to paste.
|
| 63 |
+
console.log(`→ ${req.name}: ${url.replace(API_KEY!, "***")}`)
|
| 64 |
+
|
| 65 |
+
const res = await fetch(url, {headers: {Referer: REFERER}})
|
| 66 |
+
const buf = new Uint8Array(await res.arrayBuffer())
|
| 67 |
+
|
| 68 |
+
if (!res.ok) {
|
| 69 |
+
console.error(` ✗ HTTP ${res.status} — saving body for inspection`)
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
const file = `${outDir}${req.name}.png`
|
| 73 |
+
await Bun.write(file, buf)
|
| 74 |
+
console.log(` ✓ saved ${file} (${(buf.length / 1024).toFixed(1)} KB)`)
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
export {}
|
| 78 |
+
|
| 79 |
+
console.log(`Fetching ${REQUESTS.length} static maps → ${outDir}`)
|
| 80 |
+
console.log(`Referer: ${REFERER}\n`)
|
| 81 |
+
for (const req of REQUESTS) {
|
| 82 |
+
try {
|
| 83 |
+
await fetchOne(req)
|
| 84 |
+
} catch (err) {
|
| 85 |
+
console.error(` ✗ ${req.name} failed:`, err)
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
console.log("\nDone.")
|
miniapps/navigation/src/test/bitmaps/png-to-bmp.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* PNG → glasses-BMP converter (build-time util).
|
| 3 |
+
*
|
| 4 |
+
* Pipeline: PNG --sips--> 88×88 24-bit BMP --> 8-bit grayscale pixels
|
| 5 |
+
* --> encodeBmpBase64() --> base64 BMP string the glasses display.
|
| 6 |
+
*
|
| 7 |
+
* PNG is the right SOURCE: it's lossless, so downscaling + graying doesn't
|
| 8 |
+
* fight JPEG artifacts. BMP is the right TARGET: it's what the phone SGC /
|
| 9 |
+
* G2 native side decode (see bmp.ts / convertToG2Bmp).
|
| 10 |
+
*
|
| 11 |
+
* We shell out to macOS `sips` for decode+resize (no npm image deps). It
|
| 12 |
+
* emits a 24-bit, top-down (negative-height) uncompressed BMP with a 54-byte
|
| 13 |
+
* header — easy to parse by hand.
|
| 14 |
+
*
|
| 15 |
+
* Usage:
|
| 16 |
+
* bun run src/test/bitmaps/png-to-bmp.ts <input.png> [size]
|
| 17 |
+
* # → writes <input>.bmp.ts exporting the base64 BMP string + dims.
|
| 18 |
+
*
|
| 19 |
+
* Default size is 88 (→ 88×88).
|
| 20 |
+
*/
|
| 21 |
+
|
| 22 |
+
import {$} from "bun"
|
| 23 |
+
import {encodeBmpBase64} from "../../background/lib/bmp"
|
| 24 |
+
|
| 25 |
+
const DEFAULT_SIZE = 88
|
| 26 |
+
|
| 27 |
+
/**
|
| 28 |
+
* Convert a PNG file to a base64 grayscale BMP at `size`×`size`, ready for
|
| 29 |
+
* a `session.display.render()` image element. Returns the base64 string.
|
| 30 |
+
*/
|
| 31 |
+
export async function pngToGlassesBmp(pngPath: string, size = DEFAULT_SIZE): Promise<string> {
|
| 32 |
+
const tmpBmp = `/tmp/png-to-bmp-${size}.bmp`
|
| 33 |
+
|
| 34 |
+
// Resize to size×size and emit a 24-bit BMP. `-z H W` forces exact dims
|
| 35 |
+
// (not aspect-preserving) — caller asked for a fixed square.
|
| 36 |
+
await $`sips -z ${size} ${size} -s format bmp ${pngPath} --out ${tmpBmp}`.quiet()
|
| 37 |
+
|
| 38 |
+
const bmp = new Uint8Array(await Bun.file(tmpBmp).arrayBuffer())
|
| 39 |
+
|
| 40 |
+
// --- Parse the BMP sips produced (BITMAPINFOHEADER, 24-bit, uncompressed) ---
|
| 41 |
+
const readU32 = (o: number) => bmp[o] | (bmp[o + 1] << 8) | (bmp[o + 2] << 16) | (bmp[o + 3] << 24)
|
| 42 |
+
const readI32 = (o: number) => readU32(o) | 0
|
| 43 |
+
|
| 44 |
+
const pixelOffset = readU32(10)
|
| 45 |
+
const width = readI32(18)
|
| 46 |
+
const rawHeight = readI32(22)
|
| 47 |
+
const topDown = rawHeight < 0
|
| 48 |
+
const height = Math.abs(rawHeight)
|
| 49 |
+
const bpp = bmp[28] | (bmp[29] << 8)
|
| 50 |
+
|
| 51 |
+
if (bpp !== 24) throw new Error(`expected 24-bit BMP from sips, got ${bpp}-bit`)
|
| 52 |
+
|
| 53 |
+
// 24-bit rows are padded to a 4-byte boundary; pixels are stored B,G,R.
|
| 54 |
+
const rowSize = ((width * 3 + 3) >> 2) << 2
|
| 55 |
+
|
| 56 |
+
// Build the 8-bit grayscale buffer encodeBmpBase64 wants: row-major, TOP-DOWN.
|
| 57 |
+
const gray = new Uint8Array(width * height)
|
| 58 |
+
for (let y = 0; y < height; y++) {
|
| 59 |
+
// Map our top-down output row `y` to the source row in the BMP.
|
| 60 |
+
const srcRow = topDown ? y : height - 1 - y
|
| 61 |
+
const rowStart = pixelOffset + srcRow * rowSize
|
| 62 |
+
for (let x = 0; x < width; x++) {
|
| 63 |
+
const p = rowStart + x * 3
|
| 64 |
+
const b = bmp[p]!
|
| 65 |
+
const g = bmp[p + 1]!
|
| 66 |
+
const r = bmp[p + 2]!
|
| 67 |
+
// ITU-R 601 luma — same weights the G2 native converter uses.
|
| 68 |
+
gray[y * width + x] = (r * 299 + g * 587 + b * 114) / 1000
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
return encodeBmpBase64(gray, width, height)
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
// ── CLI ──────────────────────────────────────────────────────────────────
|
| 76 |
+
if (import.meta.main) {
|
| 77 |
+
const input = process.argv[2]
|
| 78 |
+
const size = process.argv[3] ? parseInt(process.argv[3], 10) : DEFAULT_SIZE
|
| 79 |
+
if (!input) {
|
| 80 |
+
console.error("usage: bun run png-to-bmp.ts <input.png> [size]")
|
| 81 |
+
process.exit(1)
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
const base64 = await pngToGlassesBmp(input, size)
|
| 85 |
+
|
| 86 |
+
const outTs = input.replace(/\.png$/i, "") + `.bmp.ts`
|
| 87 |
+
const constName =
|
| 88 |
+
"MAP_BMP_" +
|
| 89 |
+
input
|
| 90 |
+
.split("/")
|
| 91 |
+
.pop()!
|
| 92 |
+
.replace(/\.png$/i, "")
|
| 93 |
+
.replace(/[^a-zA-Z0-9]/g, "_")
|
| 94 |
+
.toUpperCase()
|
| 95 |
+
|
| 96 |
+
const contents =
|
| 97 |
+
`// AUTO-GENERATED by png-to-bmp.ts from ${input} at ${size}×${size}.\n` +
|
| 98 |
+
`// Base64 8-bit grayscale BMP — data for a session.display.render() image element.\n` +
|
| 99 |
+
`export const ${constName} = "${base64}"\n` +
|
| 100 |
+
`export const ${constName}_SIZE = ${size}\n`
|
| 101 |
+
|
| 102 |
+
await Bun.write(outTs, contents)
|
| 103 |
+
console.log(`✓ ${input} → ${outTs}`)
|
| 104 |
+
console.log(` const: ${constName} (${size}×${size}, ${(base64.length / 1024).toFixed(1)} KB base64)`)
|
| 105 |
+
}
|
miniapps/navigation/src/test/bitmaps/preview-osm-map.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Desktop preview for the OSM line-map renderer — no glasses needed.
|
| 3 |
+
*
|
| 4 |
+
* Fetches roads, renders the exact same base64 BMP the glasses get, decodes it
|
| 5 |
+
* back to a PNG, upscales it so it's visible, saves to disk, and (on macOS)
|
| 6 |
+
* opens it. Use this to iterate on zoom / line width / center quickly.
|
| 7 |
+
*
|
| 8 |
+
* Usage:
|
| 9 |
+
* bun run src/test/bitmaps/preview-osm-map.ts # defaults
|
| 10 |
+
* bun run src/test/bitmaps/preview-osm-map.ts <lat> <lng> <radiusM> <size> <lineW> <upscale>
|
| 11 |
+
*
|
| 12 |
+
* Example (zoomed in on Manhattan, 8× upscale):
|
| 13 |
+
* bun run src/test/bitmaps/preview-osm-map.ts 40.714728 -73.998672 133 88 1 8
|
| 14 |
+
*/
|
| 15 |
+
|
| 16 |
+
import {$} from "bun"
|
| 17 |
+
import {buildOsmLineMap} from "../../background/lib/OsmLineMapRenderer"
|
| 18 |
+
|
| 19 |
+
const lat = Number(process.argv[2] ?? 40.714728)
|
| 20 |
+
const lng = Number(process.argv[3] ?? -73.998672)
|
| 21 |
+
const radius = Number(process.argv[4] ?? 133)
|
| 22 |
+
const size = Number(process.argv[5] ?? 88)
|
| 23 |
+
const lineW = Number(process.argv[6] ?? 1)
|
| 24 |
+
const upscale = Number(process.argv[7] ?? 4)
|
| 25 |
+
|
| 26 |
+
console.log(`Rendering OSM map: center=${lat},${lng} radius=${radius}m size=${size}×${size} lineW=${lineW}`)
|
| 27 |
+
|
| 28 |
+
const base64 = await buildOsmLineMap({
|
| 29 |
+
center: {lat, lng},
|
| 30 |
+
width: size,
|
| 31 |
+
height: size,
|
| 32 |
+
viewRadiusMeters: radius,
|
| 33 |
+
lineWidthPx: lineW,
|
| 34 |
+
})
|
| 35 |
+
|
| 36 |
+
// Decode the base64 BMP (exactly what the glasses receive) and save it.
|
| 37 |
+
const bmpBytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0))
|
| 38 |
+
const outDir = new URL(".", import.meta.url).pathname
|
| 39 |
+
const bmpPath = `${outDir}preview-osm.bmp`
|
| 40 |
+
const pngPath = `${outDir}preview-osm.png`
|
| 41 |
+
await Bun.write(bmpPath, bmpBytes)
|
| 42 |
+
|
| 43 |
+
// Convert BMP → PNG and upscale (nearest-neighbour stays crisp for line art)
|
| 44 |
+
// so the tiny 88px image is actually viewable on a desktop monitor.
|
| 45 |
+
const upPx = size * upscale
|
| 46 |
+
await $`sips -s format png ${bmpPath} -z ${upPx} ${upPx} --out ${pngPath}`.quiet()
|
| 47 |
+
|
| 48 |
+
console.log(`✓ saved ${pngPath} (${size}×${size} upscaled ${upscale}× → ${upPx}px)`)
|
| 49 |
+
|
| 50 |
+
// Open it on macOS so you see it immediately.
|
| 51 |
+
try {
|
| 52 |
+
await $`open ${pngPath}`.quiet()
|
| 53 |
+
console.log("→ opened in Preview")
|
| 54 |
+
} catch {
|
| 55 |
+
console.log("(could not auto-open; open the PNG manually)")
|
| 56 |
+
}
|
miniapps/navigation/src/test/bitmaps/preview-osm.bmp
ADDED
|
miniapps/navigation/src/test/bitmaps/preview-osm.png
ADDED
|
miniapps/navigation/src/test/bitmaps/z12-400x400.png
ADDED
|
miniapps/navigation/src/test/bitmaps/z14-200x100.png
ADDED
|
miniapps/navigation/src/test/bitmaps/z14-200x88.png
ADDED
|
miniapps/navigation/src/test/bitmaps/z14-400x400.png
ADDED
|
miniapps/navigation/src/test/bitmaps/z14-88x88-scale2.bmp.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// AUTO-GENERATED by png-to-bmp.ts from src/test/bitmaps/z14-88x88-scale2.png at 88×88.
|
| 2 |
+
// Base64 8-bit grayscale BMP — data for a session.display.render() image element.
|
| 3 |
+
export const MAP_BMP_Z14_88X88_SCALE2 = "Qk12IgAAAAAAADYEAAAoAAAAWAAAAFgAAAABAAgAAAAAAEAeAAATCwAAEwsAAAABAAAAAQAAAA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2t7d3Nnd3t7d2ODu6OPz8/Pz8/Pz8/P05eb08/Pz8/Pz8/Pk5/Tz8/Pz8/Lw4N3e3t7d3PDx8/Pz8/Pz8/Lq3t3e3tri9PPz8/P05tne3tvi9PTz6d3Z293b3NLa3t7d2Of09PLh6/Tz8/Pz8/Pz8+/g7/Pz8/Pz8/Pz7uHx8/Pz9PLr4N/c3t7e3tjq8fHz8/Pz9O7j4uza3d7e2On08/Pz8/Pd3N7e2ezo3Nnc3dnb5t7c3t7d2Oj08/P06uPz8/Pz8/Pz8/P05ef08/Pz8/Pz8/Pk6PT08erh4ujv39ve3t7b4fHw8/Pz8ujg6PL06tje3tza8PPz8/P069ne3tzX2d3d2N3p8eDb3t7d2Oj08/Pz8/Hg7PTz8/Pz8/Pz8+7g8fPz8/Pz8/P07OHw6uHi6/Ly8enY3t7e3tnu8PPz8ePf7fPz8/Tg297e2eH08/Pz8/Pd3d7e3t7Z2erz9OHY3t7e1+b08/Pz8/P05+Tz8/Pz8/Pz8/Pz4+r08/Pz8/Pz8/Li3+Dr8/Tz8/Hw2t3e3t7Y5/E="
|
| 4 |
+
export const MAP_BMP_Z14_88X88_SCALE2_SIZE = 88
|
miniapps/navigation/src/test/bitmaps/z14-88x88-scale2.png
ADDED
|
miniapps/navigation/src/test/bitmaps/z14-roadmap.png
ADDED
|
miniapps/navigation/src/test/bitmaps/z14-terrain.png
ADDED
|
miniapps/navigation/src/test/bitmaps/z16-400x400.png
ADDED
|
miniapps/navigation/src/test/buildConfig.test.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import {describe, expect, test} from "bun:test"
|
| 2 |
+
|
| 3 |
+
import {resolveMapboxBuildToken} from "../../buildConfig"
|
| 4 |
+
|
| 5 |
+
describe("navigation build configuration", () => {
|
| 6 |
+
test("uses the standalone miniapp token when configured", () => {
|
| 7 |
+
expect(
|
| 8 |
+
resolveMapboxBuildToken({
|
| 9 |
+
NODE_ENV: "production",
|
| 10 |
+
PUBLIC_MAPBOX_TOKEN: "pk.miniapp-token",
|
| 11 |
+
EXPO_PUBLIC_MAPBOX_ACCESS_TOKEN: "pk.mobile-token",
|
| 12 |
+
}),
|
| 13 |
+
).toBe("pk.miniapp-token")
|
| 14 |
+
})
|
| 15 |
+
|
| 16 |
+
test("falls back to the Mentra App token for bundled builds", () => {
|
| 17 |
+
expect(
|
| 18 |
+
resolveMapboxBuildToken({
|
| 19 |
+
NODE_ENV: "production",
|
| 20 |
+
PUBLIC_MAPBOX_TOKEN: " ",
|
| 21 |
+
EXPO_PUBLIC_MAPBOX_ACCESS_TOKEN: "pk.mobile-token",
|
| 22 |
+
}),
|
| 23 |
+
).toBe("pk.mobile-token")
|
| 24 |
+
})
|
| 25 |
+
|
| 26 |
+
test.each([undefined, "", "ci-dummy-mapbox-pk-token"])(
|
| 27 |
+
"rejects a missing or invalid token in production (%s)",
|
| 28 |
+
(token) => {
|
| 29 |
+
expect(() =>
|
| 30 |
+
resolveMapboxBuildToken({
|
| 31 |
+
NODE_ENV: "production",
|
| 32 |
+
PUBLIC_MAPBOX_TOKEN: token,
|
| 33 |
+
}),
|
| 34 |
+
).toThrow("A valid public Mapbox token is required")
|
| 35 |
+
},
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
test("allows the dev server to provide the token at runtime", () => {
|
| 39 |
+
expect(resolveMapboxBuildToken({NODE_ENV: "development"})).toBe("")
|
| 40 |
+
})
|
| 41 |
+
})
|
miniapps/navigation/src/test/capabilities.test.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import {describe, expect, test} from "bun:test"
|
| 2 |
+
|
| 3 |
+
import {readGlassesCapabilities} from "../background/lib/capabilities"
|
| 4 |
+
|
| 5 |
+
describe("navigation glasses capabilities", () => {
|
| 6 |
+
test("preserves the positioned HUD when the host omits canPosition", () => {
|
| 7 |
+
expect(
|
| 8 |
+
readGlassesCapabilities({
|
| 9 |
+
modelName: "Even Realities G2",
|
| 10 |
+
hasDisplay: true,
|
| 11 |
+
display: {canDisplayBitmap: true},
|
| 12 |
+
}).canPosition,
|
| 13 |
+
).toBe(true)
|
| 14 |
+
})
|
| 15 |
+
|
| 16 |
+
test("does not infer positioning support from a device model", () => {
|
| 17 |
+
expect(
|
| 18 |
+
readGlassesCapabilities({
|
| 19 |
+
modelName: "Even Realities G2",
|
| 20 |
+
hasDisplay: true,
|
| 21 |
+
display: {canPosition: false},
|
| 22 |
+
}).canPosition,
|
| 23 |
+
).toBe(false)
|
| 24 |
+
})
|
| 25 |
+
|
| 26 |
+
test("uses the compact text HUD only when positioning is explicitly unsupported", () => {
|
| 27 |
+
expect(
|
| 28 |
+
readGlassesCapabilities({
|
| 29 |
+
modelName: "Even Realities G1",
|
| 30 |
+
hasDisplay: true,
|
| 31 |
+
display: {canPosition: false},
|
| 32 |
+
}).canPosition,
|
| 33 |
+
).toBe(false)
|
| 34 |
+
})
|
| 35 |
+
|
| 36 |
+
test("honors explicit positioned-scene support", () => {
|
| 37 |
+
expect(
|
| 38 |
+
readGlassesCapabilities({
|
| 39 |
+
modelName: "Mentra Display",
|
| 40 |
+
hasDisplay: true,
|
| 41 |
+
display: {canPosition: true},
|
| 42 |
+
}).canPosition,
|
| 43 |
+
).toBe(true)
|
| 44 |
+
})
|
| 45 |
+
|
| 46 |
+
test("does not claim positioning support without a display", () => {
|
| 47 |
+
expect(readGlassesCapabilities({modelName: "Mentra Live", hasDisplay: false}).canPosition).toBe(false)
|
| 48 |
+
})
|
| 49 |
+
})
|
miniapps/navigation/src/test/display-manager.test.ts
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import {afterEach, describe, expect, test} from "bun:test"
|
| 2 |
+
import type {MiniappSession, RenderElement} from "@mentra/miniapp"
|
| 3 |
+
|
| 4 |
+
import {DisplayManager} from "../background/managers/DisplayManager"
|
| 5 |
+
import {NavigationController} from "../background/NavigationController"
|
| 6 |
+
import {borderTestImageBase64} from "../background/lib/bmp"
|
| 7 |
+
|
| 8 |
+
// Rendered widths from the calibrated G2 font profile. All digits except 1
|
| 9 |
+
// occupy 12px; 1 occupies 8px; the colon occupies 4px.
|
| 10 |
+
const G2_DIGIT_WIDTH_PX = 12
|
| 11 |
+
const G2_COLON_WIDTH_PX = 4
|
| 12 |
+
const G2_NATIVE_HORIZONTAL_PADDING_PX = 8
|
| 13 |
+
const G2_LINE_HEIGHT_PX = 40
|
| 14 |
+
|
| 15 |
+
function makeNimoDisplay() {
|
| 16 |
+
const frames: RenderElement[][] = []
|
| 17 |
+
const session = {
|
| 18 |
+
capabilities: {
|
| 19 |
+
modelName: "NIMO",
|
| 20 |
+
display: {width: 500, height: 220, canPosition: true, maxImagePx: {width: 200, height: 200}},
|
| 21 |
+
},
|
| 22 |
+
display: {render: (elements: RenderElement[]) => frames.push(elements)},
|
| 23 |
+
} as unknown as MiniappSession
|
| 24 |
+
return {frames, session, display: new DisplayManager(session)}
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
describe("navigation capability-bounded bitmaps", () => {
|
| 28 |
+
const setTimeoutOriginal = globalThis.setTimeout
|
| 29 |
+
afterEach(() => {
|
| 30 |
+
globalThis.setTimeout = setTimeoutOriginal
|
| 31 |
+
})
|
| 32 |
+
|
| 33 |
+
test("ignores large-map requests on text-only displays without taking over the HUD", () => {
|
| 34 |
+
const {frames, session} = makeNimoDisplay()
|
| 35 |
+
session.capabilities = {display: {width: 576, height: 288, canPosition: false, maxImageElements: 0}}
|
| 36 |
+
const controller = new NavigationController(session) as unknown as {
|
| 37 |
+
showLargeMap(): void
|
| 38 |
+
renderLargeMap(position: {lat: number; lng: number}): void
|
| 39 |
+
largeMapShown: boolean
|
| 40 |
+
largeMapTransitioning: boolean
|
| 41 |
+
}
|
| 42 |
+
expect(() => controller.showLargeMap()).not.toThrow()
|
| 43 |
+
expect(() => controller.renderLargeMap({lat: 37.77, lng: -122.42})).not.toThrow()
|
| 44 |
+
expect(controller.largeMapShown).toBe(false)
|
| 45 |
+
expect(controller.largeMapTransitioning).toBe(false)
|
| 46 |
+
expect(frames).toEqual([])
|
| 47 |
+
})
|
| 48 |
+
|
| 49 |
+
test("repaints the HUD when only bitmap capability disappears", () => {
|
| 50 |
+
const {frames, session} = makeNimoDisplay()
|
| 51 |
+
const controller = new NavigationController(session) as unknown as {
|
| 52 |
+
applyCapabilities(raw: MiniappSession["capabilities"]): void
|
| 53 |
+
largeMapShown: boolean
|
| 54 |
+
broadcastVoiceGuidanceState(): void
|
| 55 |
+
}
|
| 56 |
+
controller.broadcastVoiceGuidanceState = () => {}
|
| 57 |
+
session.capabilities = {...session.capabilities, hasDisplay: true}
|
| 58 |
+
controller.applyCapabilities(session.capabilities)
|
| 59 |
+
controller.largeMapShown = true
|
| 60 |
+
session.capabilities = {...session.capabilities, display: {...session.capabilities?.display, maxImageElements: 0}}
|
| 61 |
+
controller.applyCapabilities(session.capabilities)
|
| 62 |
+
expect(controller.largeMapShown).toBe(false)
|
| 63 |
+
expect(frames.at(-1)?.some((el) => el.type === "text" && el.text.includes("Welcome to Mentra Maps"))).toBe(true)
|
| 64 |
+
})
|
| 65 |
+
|
| 66 |
+
test("renders the real large-map raster and matching placement inside NIMO limits", () => {
|
| 67 |
+
const {frames, session} = makeNimoDisplay()
|
| 68 |
+
const controller = new NavigationController(session) as unknown as {
|
| 69 |
+
renderLargeMap: (position: {lat: number; lng: number}) => void
|
| 70 |
+
}
|
| 71 |
+
controller.renderLargeMap({lat: 37.77, lng: -122.42})
|
| 72 |
+
const image = frames.at(-1)?.[0]
|
| 73 |
+
expect(image?.type).toBe("image")
|
| 74 |
+
if (image?.type !== "image") throw new Error("large map did not render an image")
|
| 75 |
+
expect(image.box).toEqual({x: 150, y: 40, w: 200, h: 140})
|
| 76 |
+
const bmp = Buffer.from(image.data, "base64")
|
| 77 |
+
expect(bmp.readUInt32LE(18)).toBe(image.box.w)
|
| 78 |
+
expect(bmp.readUInt32LE(22)).toBe(image.box.h)
|
| 79 |
+
})
|
| 80 |
+
|
| 81 |
+
test("centers existing raw images without changing their declared raster size", () => {
|
| 82 |
+
const {frames, display} = makeNimoDisplay()
|
| 83 |
+
display.showRawBitmap(borderTestImageBase64(100, 80), 100, 80)
|
| 84 |
+
expect(frames.at(-1)?.[0]?.box).toEqual({x: 200, y: 70, w: 100, h: 80})
|
| 85 |
+
})
|
| 86 |
+
|
| 87 |
+
test("generates diagnostics at the same dimensions as their device-centered box", () => {
|
| 88 |
+
const callbacks: Array<() => void> = []
|
| 89 |
+
globalThis.setTimeout = ((cb: () => void) => {
|
| 90 |
+
callbacks.push(cb)
|
| 91 |
+
return 1
|
| 92 |
+
}) as unknown as typeof setTimeout
|
| 93 |
+
const {frames, display} = makeNimoDisplay()
|
| 94 |
+
for (const render of [() => display.showTestBox(200, 100), () => display.showBitmapSize(200, 100)]) {
|
| 95 |
+
render()
|
| 96 |
+
callbacks.shift()?.()
|
| 97 |
+
const image = frames.at(-1)?.[0]
|
| 98 |
+
expect(image?.type).toBe("image")
|
| 99 |
+
if (image?.type !== "image") throw new Error("diagnostic did not render an image")
|
| 100 |
+
expect(image.box).toEqual({x: 150, y: 60, w: 200, h: 100})
|
| 101 |
+
const bmp = Buffer.from(image.data, "base64")
|
| 102 |
+
expect(bmp.readUInt32LE(18)).toBe(200)
|
| 103 |
+
expect(bmp.readUInt32LE(22)).toBe(100)
|
| 104 |
+
}
|
| 105 |
+
})
|
| 106 |
+
|
| 107 |
+
test("rejects invalid and oversized diagnostics before clearing or sending a frame", () => {
|
| 108 |
+
globalThis.setTimeout = (() => 1) as unknown as typeof setTimeout
|
| 109 |
+
const {frames, display} = makeNimoDisplay()
|
| 110 |
+
for (const [w, h] of [
|
| 111 |
+
[288, 140],
|
| 112 |
+
[100, 221],
|
| 113 |
+
[NaN, 100],
|
| 114 |
+
[100, Infinity],
|
| 115 |
+
[0, 100],
|
| 116 |
+
[-1, 100],
|
| 117 |
+
[8.5, 100],
|
| 118 |
+
]) {
|
| 119 |
+
expect(() => display.showLargeBitmap("bmp", w, h)).toThrow()
|
| 120 |
+
expect(() => display.showRawBitmap("bmp", w, h)).toThrow()
|
| 121 |
+
expect(() => display.showTestBox(w, h)).toThrow()
|
| 122 |
+
expect(() => display.showBitmapSize(w, h)).toThrow()
|
| 123 |
+
}
|
| 124 |
+
expect(() => display.showBitmapTest("288-square-bmp")).toThrow()
|
| 125 |
+
expect(frames).toEqual([])
|
| 126 |
+
})
|
| 127 |
+
|
| 128 |
+
test("uses live capabilities and preserves the older-host canvas fallback", () => {
|
| 129 |
+
const {frames, session, display} = makeNimoDisplay()
|
| 130 |
+
display.showText("NIMO")
|
| 131 |
+
expect(frames.at(-1)?.[0]?.box).toEqual({x: 0, y: 0, w: 500, h: 220})
|
| 132 |
+
session.capabilities = {display: {width: 576, height: 288}}
|
| 133 |
+
display.showLargeBitmap("bmp", 288, 140)
|
| 134 |
+
expect(frames.at(-1)?.[0]?.box).toEqual({x: 144, y: 74, w: 288, h: 140})
|
| 135 |
+
session.capabilities = null
|
| 136 |
+
display.showLargeBitmap("bmp", 288, 140)
|
| 137 |
+
expect(frames.at(-1)?.[0]?.box).toEqual({x: 144, y: 74, w: 288, h: 140})
|
| 138 |
+
})
|
| 139 |
+
})
|
| 140 |
+
|
| 141 |
+
describe("navigation display layout", () => {
|
| 142 |
+
test("keeps arrival words intact in the positioned message box", () => {
|
| 143 |
+
const {frames, display} = makeNimoDisplay()
|
| 144 |
+
|
| 145 |
+
display.showNavMessage("You have arrived at Union Square, on your left", "15:55")
|
| 146 |
+
|
| 147 |
+
expect(frames.at(-1)?.find((element) => element.id === "message")).toEqual({
|
| 148 |
+
type: "text",
|
| 149 |
+
id: "message",
|
| 150 |
+
box: DisplayManager.HUD.message,
|
| 151 |
+
text: "You have arrived at Union Square, on your left",
|
| 152 |
+
style: {breakMode: "word"},
|
| 153 |
+
})
|
| 154 |
+
})
|
| 155 |
+
|
| 156 |
+
test("uses word wrapping for older positioned hosts that omit canPosition", () => {
|
| 157 |
+
const {frames, session, display} = makeNimoDisplay()
|
| 158 |
+
session.capabilities = {display: {width: 500, height: 220}}
|
| 159 |
+
|
| 160 |
+
display.showNavMessage("You have arrived at Union Square, on your left")
|
| 161 |
+
|
| 162 |
+
expect(frames.at(-1)?.find((element) => element.id === "message")).toMatchObject({
|
| 163 |
+
style: {breakMode: "word"},
|
| 164 |
+
})
|
| 165 |
+
})
|
| 166 |
+
|
| 167 |
+
test("keeps every 24-hour clock value on one G2 text line", () => {
|
| 168 |
+
const widestClockWidth = G2_DIGIT_WIDTH_PX * 4 + G2_COLON_WIDTH_PX
|
| 169 |
+
const availableTextWidth = DisplayManager.HUD.clock.w - G2_NATIVE_HORIZONTAL_PADDING_PX
|
| 170 |
+
|
| 171 |
+
expect(availableTextWidth).toBeGreaterThanOrEqual(widestClockWidth)
|
| 172 |
+
expect(DisplayManager.HUD.clock.h).toBeGreaterThanOrEqual(G2_LINE_HEIGHT_PX)
|
| 173 |
+
})
|
| 174 |
+
|
| 175 |
+
test("reserves complete G2 lines for wrapped stats and maneuver instructions", () => {
|
| 176 |
+
const {maneuver, map, stats} = DisplayManager.HUD
|
| 177 |
+
|
| 178 |
+
expect(stats.w).toBeGreaterThanOrEqual(200)
|
| 179 |
+
expect(stats.h).toBeGreaterThanOrEqual(G2_LINE_HEIGHT_PX * 2)
|
| 180 |
+
expect(stats.y + stats.h).toBeLessThanOrEqual(map.y)
|
| 181 |
+
|
| 182 |
+
// One distance line plus up to two wrapped instruction lines.
|
| 183 |
+
expect(maneuver.h).toBeGreaterThanOrEqual(G2_LINE_HEIGHT_PX * 3)
|
| 184 |
+
expect(maneuver.y + maneuver.h).toBeLessThanOrEqual(220)
|
| 185 |
+
expect(maneuver.x + maneuver.w).toBeLessThanOrEqual(map.x)
|
| 186 |
+
})
|
| 187 |
+
|
| 188 |
+
test("keeps the maneuver instruction inside G1's five-line text budget", () => {
|
| 189 |
+
const frames: RenderElement[][] = []
|
| 190 |
+
const session = {
|
| 191 |
+
capabilities: {display: {canPosition: false}},
|
| 192 |
+
display: {
|
| 193 |
+
render: (elements: RenderElement[]) => {
|
| 194 |
+
frames.push(elements)
|
| 195 |
+
},
|
| 196 |
+
},
|
| 197 |
+
} as unknown as MiniappSession
|
| 198 |
+
const display = new DisplayManager(session)
|
| 199 |
+
|
| 200 |
+
// Prime the positioning-only slots. The compact frame must drop them so
|
| 201 |
+
// scene degradation cannot consume G1's line budget before the instruction.
|
| 202 |
+
display.showBitmap("map-bitmap")
|
| 203 |
+
display.showNavMessage("Starting…", "10:51")
|
| 204 |
+
display.showCompactNavHud("→\n56 m\nTurn right onto Gough Street", "1.2 km · 14 min")
|
| 205 |
+
|
| 206 |
+
expect(frames.at(-1)).toEqual([
|
| 207 |
+
{
|
| 208 |
+
type: "text",
|
| 209 |
+
id: "message",
|
| 210 |
+
box: DisplayManager.HUD.message,
|
| 211 |
+
text: "→\n56 m\nTurn right onto Gough Street\n\n1.2 km · 14 min",
|
| 212 |
+
},
|
| 213 |
+
])
|
| 214 |
+
expect((frames.at(-1)?.[0] as {text: string}).text.split("\n")).toHaveLength(5)
|
| 215 |
+
})
|
| 216 |
+
})
|
miniapps/navigation/src/test/early-arrival.test.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import {describe, expect, mock, test} from "bun:test"
|
| 2 |
+
|
| 3 |
+
import {NavigationController} from "../background/NavigationController"
|
| 4 |
+
import type {LatLng} from "../background/lib/geometry"
|
| 5 |
+
import type {Coords, TripState} from "../shared/types"
|
| 6 |
+
|
| 7 |
+
// Exercise the controller's arrival transition without constructing device,
|
| 8 |
+
// network, UI, or timer-owning managers.
|
| 9 |
+
type ArrivalHarness = {
|
| 10 |
+
coords: Coords | null
|
| 11 |
+
trip: TripState
|
| 12 |
+
maybeFireEarlyArrival(): void
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
const point = (eastMeters: number, northMeters = 0): LatLng => ({
|
| 16 |
+
lat: northMeters / 111_320,
|
| 17 |
+
lng: eastMeters / 111_320,
|
| 18 |
+
})
|
| 19 |
+
const route = [point(0), point(372)]
|
| 20 |
+
|
| 21 |
+
function checkArrival(me: LatLng, points: LatLng[] | null = route, destination: LatLng = point(372)) {
|
| 22 |
+
const stop = mock(() => {})
|
| 23 |
+
const controller: ArrivalHarness = Object.create(NavigationController.prototype)
|
| 24 |
+
Object.assign(controller, {
|
| 25 |
+
coords: {...me, ts: 0},
|
| 26 |
+
trip: {
|
| 27 |
+
status: "navigating",
|
| 28 |
+
running: true,
|
| 29 |
+
maneuver: null,
|
| 30 |
+
activeDestination: destination,
|
| 31 |
+
activeDestinationName: null,
|
| 32 |
+
routePoints: points,
|
| 33 |
+
routeSteps: null,
|
| 34 |
+
offRouteAt: null,
|
| 35 |
+
arrivalSide: null,
|
| 36 |
+
} satisfies TripState,
|
| 37 |
+
appendLog: () => {},
|
| 38 |
+
cancelPendingRebuild: () => {},
|
| 39 |
+
exitLargeMap: () => {},
|
| 40 |
+
navigation: {stop},
|
| 41 |
+
ui: {send: () => {}},
|
| 42 |
+
})
|
| 43 |
+
controller.maybeFireEarlyArrival()
|
| 44 |
+
return {controller, stop}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
describe("early arrival requires actual proximity", () => {
|
| 48 |
+
test("does not stop a trip when a fix projects beyond the route tail from 64.4m away", () => {
|
| 49 |
+
const {controller, stop} = checkArrival(point(436.4))
|
| 50 |
+
expect(controller.trip.status).toBe("navigating")
|
| 51 |
+
expect(stop).not.toHaveBeenCalled()
|
| 52 |
+
})
|
| 53 |
+
|
| 54 |
+
test("does not arrive 64.4m lateral to the endpoint despite zero projected distance", () => {
|
| 55 |
+
const {controller, stop} = checkArrival(point(372, 64.4))
|
| 56 |
+
expect(controller.trip.status).toBe("navigating")
|
| 57 |
+
expect(stop).not.toHaveBeenCalled()
|
| 58 |
+
})
|
| 59 |
+
|
| 60 |
+
test("still arrives five meters before the route endpoint", () => {
|
| 61 |
+
const {controller, stop} = checkArrival(point(367))
|
| 62 |
+
expect(controller.trip.status).toBe("arrived")
|
| 63 |
+
expect(stop).toHaveBeenCalledTimes(1)
|
| 64 |
+
})
|
| 65 |
+
|
| 66 |
+
test("still arrives at the walkable route endpoint when the destination pin is set back", () => {
|
| 67 |
+
const {controller, stop} = checkArrival(point(372), route, point(372, 30))
|
| 68 |
+
expect(controller.trip.status).toBe("arrived")
|
| 69 |
+
expect(stop).toHaveBeenCalledTimes(1)
|
| 70 |
+
})
|
| 71 |
+
|
| 72 |
+
test("preserves near-pin arrival within the last forty meters", () => {
|
| 73 |
+
const {controller, stop} = checkArrival(point(350), route, point(350, 10))
|
| 74 |
+
expect(controller.trip.status).toBe("arrived")
|
| 75 |
+
expect(stop).toHaveBeenCalledTimes(1)
|
| 76 |
+
})
|
| 77 |
+
|
| 78 |
+
test("does not arrive at the beginning of a 372m route", () => {
|
| 79 |
+
const {controller, stop} = checkArrival(point(0))
|
| 80 |
+
expect(controller.trip.status).toBe("navigating")
|
| 81 |
+
expect(stop).not.toHaveBeenCalled()
|
| 82 |
+
})
|
| 83 |
+
|
| 84 |
+
test("leaves arrival to the native stream when route geometry is unavailable", () => {
|
| 85 |
+
for (const points of [null, [], [point(372)]]) {
|
| 86 |
+
const {controller, stop} = checkArrival(point(372), points)
|
| 87 |
+
expect(controller.trip.status).toBe("navigating")
|
| 88 |
+
expect(stop).not.toHaveBeenCalled()
|
| 89 |
+
}
|
| 90 |
+
})
|
| 91 |
+
|
| 92 |
+
test("does not infer arrival from a route containing nonfinite points", () => {
|
| 93 |
+
for (const invalid of [NaN, Infinity, -Infinity]) {
|
| 94 |
+
const {controller, stop} = checkArrival(point(372), [{lat: invalid, lng: 0}, ...route])
|
| 95 |
+
expect(controller.trip.status).toBe("navigating")
|
| 96 |
+
expect(stop).not.toHaveBeenCalled()
|
| 97 |
+
}
|
| 98 |
+
})
|
| 99 |
+
|
| 100 |
+
test("does not infer arrival from a nonfinite location fix", () => {
|
| 101 |
+
for (const invalid of [NaN, Infinity, -Infinity]) {
|
| 102 |
+
const {controller, stop} = checkArrival({lat: invalid, lng: route[1].lng})
|
| 103 |
+
expect(controller.trip.status).toBe("navigating")
|
| 104 |
+
expect(stop).not.toHaveBeenCalled()
|
| 105 |
+
}
|
| 106 |
+
})
|
| 107 |
+
})
|
miniapps/navigation/src/test/navigation/computeRoute/computeRoute.test.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/// <reference types="bun-types" />
|
| 2 |
+
import {describe, expect, test} from "bun:test"
|
| 3 |
+
|
| 4 |
+
import {ackLatest, connectedSession, lastOutbound} from "../helpers"
|
| 5 |
+
|
| 6 |
+
import defaultsInput from "./fixtures/defaults.input.json"
|
| 7 |
+
import defaultsExpected from "./fixtures/defaults.expected.json"
|
| 8 |
+
import passthroughInput from "./fixtures/passthrough.input.json"
|
| 9 |
+
import passthroughExpected from "./fixtures/passthrough.expected.json"
|
| 10 |
+
import primaryPlusAlts from "./fixtures/primary-plus-alternates.response.json"
|
| 11 |
+
import engineFailure from "./fixtures/engine-failure.response.json"
|
| 12 |
+
|
| 13 |
+
describe("navigation.computeRoute", () => {
|
| 14 |
+
test("resolves with {ok: false, error: ...} when LOCATION not declared", async () => {
|
| 15 |
+
const {session} = await connectedSession({location: false})
|
| 16 |
+
const result = await session.navigation.computeRoute({origin: {lat: 0, lng: 0}, stops: [{lat: 1, lng: 1}]})
|
| 17 |
+
expect(result.ok).toBe(false)
|
| 18 |
+
expect((result as {error?: string}).error).toMatch(/LOCATION permission not declared/)
|
| 19 |
+
})
|
| 20 |
+
|
| 21 |
+
test("defaults mode to driving and alternatives to 1", async () => {
|
| 22 |
+
const {session, transport} = await connectedSession({location: true})
|
| 23 |
+
void session.navigation.computeRoute(defaultsInput as never)
|
| 24 |
+
expect(lastOutbound(transport)).toMatchObject(defaultsExpected)
|
| 25 |
+
})
|
| 26 |
+
|
| 27 |
+
test("origin / stops / alternatives / mode pass through verbatim", async () => {
|
| 28 |
+
const {session, transport} = await connectedSession({location: true})
|
| 29 |
+
void session.navigation.computeRoute(passthroughInput as never)
|
| 30 |
+
expect(lastOutbound(transport)).toMatchObject(passthroughExpected)
|
| 31 |
+
})
|
| 32 |
+
|
| 33 |
+
test("resolves with primary + alternates", async () => {
|
| 34 |
+
const {session, transport} = await connectedSession({location: true})
|
| 35 |
+
const promise = session.navigation.computeRoute({
|
| 36 |
+
origin: {lat: 0, lng: 0},
|
| 37 |
+
stops: [{lat: 1, lng: 1}],
|
| 38 |
+
alternatives: 2,
|
| 39 |
+
})
|
| 40 |
+
ackLatest(transport, primaryPlusAlts)
|
| 41 |
+
await expect(promise).resolves.toEqual(primaryPlusAlts)
|
| 42 |
+
})
|
| 43 |
+
|
| 44 |
+
test("forwards engine failure as ComputeRouteResult.ok=false", async () => {
|
| 45 |
+
const {session, transport} = await connectedSession({location: true})
|
| 46 |
+
const promise = session.navigation.computeRoute({
|
| 47 |
+
origin: {lat: 0, lng: 0},
|
| 48 |
+
stops: [{lat: 1, lng: 1}],
|
| 49 |
+
})
|
| 50 |
+
ackLatest(transport, engineFailure)
|
| 51 |
+
await expect(promise).resolves.toEqual(engineFailure)
|
| 52 |
+
})
|
| 53 |
+
})
|
miniapps/navigation/src/test/navigation/computeRoute/fixtures/defaults.expected.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"type": "miniapp_navigation_compute_route",
|
| 3 |
+
"mode": "driving",
|
| 4 |
+
"alternatives": 1
|
| 5 |
+
}
|