diff --git a/TODO.adoc b/TODO.adoc index 871da5c..9dc0edb 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -228,8 +228,14 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho by km along the route, `legs_km`), at most every 15 s and only moving *** [ ] Step advance like Ferrostar's DistanceEntryExit (30 m to the step's end, 5 m past it) instead of "the first maneuver ahead by km"; arrival at 30 m -** [ ] Turn-by-turn: the next maneuver big (arrow, distance, street), voice - (`speechSynthesis`), the route ahead highlighted / the driven part greyed +** [x] The navigation banner across the top (Dashboard widget, on by default): the next + maneuver's arrow (Valhalla's maneuver type), distance and street, "then …" when the next one + follows within 300 m, its lanes from 1 km, the street being driven; `/api/route` maneuvers + gain `type`, `street`, `exit` +** [x] The driving view decluttered: tilted to 3D (≥ 30°), route numbers and minor roads' / + paths' names hidden; road labels 1.5× further apart, past z15 the same ground distance +** [ ] Turn-by-turn voice (`speechSynthesis`), the route ahead highlighted / the driven part + greyed ** [x] Lanes as SVG arrows, one per direction bit, the lanes to take (Valhalla's `active`) blue with that direction bold *** [ ] Lane guidance before motorway exits (lanes several maneuvers ahead), bigger on the diff --git a/lib/maptool/routing.rb b/lib/maptool/routing.rb index d5a320f..b35c416 100644 --- a/lib/maptool/routing.rb +++ b/lib/maptool/routing.rb @@ -256,11 +256,18 @@ module Maptool speed_limits: along[:speed_limits], signals: along[:signals], legs_km: legs.map { |leg| leg.dig("summary", "length") }, # to each via point, for rerouting # lanes: Valhalla's [{directions:, valid:, active:}] bitmasks, at junctions that have them - maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| { text: m["instruction"], km: m["length"], lanes: m["lanes"] }.compact } } } } + # type: Valhalla's maneuver type (the arrow), street: the road it leads onto + maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| maneuver(m) } } } } rescue ArgumentError, TypeError raise RouteError, "invalid coordinates" end + def self.maneuver(m) + { text: m["instruction"], km: m["length"], type: m["type"], street: (m["begin_street_names"] || m["street_names"])&.first, + exit: m["roundabout_exit_count"], lanes: m["lanes"] }.compact + end + private_class_method :maneuver + # From Valhalla's per-edge attributes along the route: # countries: [{ code: "AT", km:, motorway_km:, toll_km: }, ...] in route # order (vignettes, tolls); diff --git a/public/css/style.css b/public/css/style.css index 39984d8..6bf2222 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -3457,3 +3457,32 @@ html.night .maplibregl-marker { /* The GNSS position once it has a course: an arrow, not the dot. */ .gnss-marker--arrow { width: 26px; height: 26px; border: none; border-radius: 0; background: none; box-shadow: none; filter: drop-shadow(0 1px 2px rgb(0 0 0 / 0.5)); } .gnss-marker--arrow svg { display: block; } + +/* The navigation banner across the top (dashboard.js): the next turn. */ +.dash-banner { + position: absolute; + top: 10px; + left: 50%; + transform: translateX(-50%); + z-index: 3; + min-width: 260px; + max-width: calc(100% - 140px); + padding: 8px 14px; + border-radius: 12px; + background: rgb(var(--inst-bezel) / var(--dash-alpha, 0.9)); + box-shadow: 0 1px 6px rgb(0 0 0 / 0.3); + color: var(--inst-text); + font-family: system-ui, sans-serif; + pointer-events: none; + text-shadow: 0 0 3px var(--inst-halo); +} +.dash-banner[hidden] { display: none; } +.dash-banner__main { display: flex; align-items: center; gap: 12px; } +.dash-banner__icon { width: 44px; height: 58px; flex: none; } +.dash-banner__arrow { fill: none; stroke: var(--inst-active); stroke-width: 3.5; stroke-linecap: round; stroke-linejoin: round; } +.dash-banner__distance { font-size: 30px; font-weight: 700; font-variant-numeric: tabular-nums; line-height: 1.1; } +.dash-banner__street { font-size: 18px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.dash-banner__lanes { margin-top: 6px; justify-content: center; } +.dash-banner__then { margin-top: 4px; font-size: 13px; color: var(--inst-muted); display: flex; align-items: center; gap: 4px; } +.dash-banner__then .dash-banner__icon { width: 14px; height: 18px; } +.dash-banner__on { margin-top: 4px; font-size: 12px; color: var(--inst-muted); text-transform: uppercase; letter-spacing: 0.04em; } diff --git a/public/js/dashboard.js b/public/js/dashboard.js index aca429e..e486a14 100644 --- a/public/js/dashboard.js +++ b/public/js/dashboard.js @@ -31,7 +31,8 @@ const REROUTE_EVERY_MS = 15000; const ROAD_EVERY_MS = 4000; // /api/road at most this often, only while moving const TRACE_STEP_M = 10; // fixes kept for /api/road at least this far apart const LANES_AHEAD_M = 1000; // the next maneuver's lanes from this close -const DEFAULT_WIDGETS = { inclinometer: true, speed: true, navigation: true }; +const DEFAULT_WIDGETS = { inclinometer: true, speed: true, navigation: true, banner: true }; +const THEN_M = 300; // the maneuver after the next one shown with it when it follows this closely const DEFAULT_OPACITY = 0.45; // the card's background, the map shows through const load = () => { @@ -43,6 +44,31 @@ const RAD = Math.PI / 180; // meters between two [lon, lat] (equirectangular: fine at these distances) const meters = ([lon1, lat1], [lon2, lat2]) => Math.hypot((lon2 - lon1) * Math.cos(((lat1 + lat2) / 2) * RAD), lat2 - lat1) * 111320; const distance = (m) => (m >= 1000 ? `${(m / 1000).toFixed(1)} km` : `${Math.round(m / 10) * 10} m`); +const esc = (text) => String(text ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); + +// An arrow from the bottom center turning by `angle` (° from straight on), +// in a 24 × 32 box: a lane's, and the banner's maneuver. +function arrowPath(angle, cls) { + const a = (angle * Math.PI) / 180; + const [x, y] = [12 + 9 * Math.sin(a), 15 - 9 * Math.cos(a)]; + const back = (side) => `${(x - 5 * Math.sin(a + side)).toFixed(1)} ${(y + 5 * Math.cos(a + side)).toFixed(1)}`; + return ``; +} +const uturnPath = (cls) => ``; + +// Valhalla's maneuver types (its API docs) → the banner's arrow angle; +// "uturn", "arrive", "roundabout" drawn their own way. +const MANEUVER_ANGLES = { 1: 0, 2: 45, 3: -45, 7: 0, 8: 0, 9: 45, 10: 90, 11: 135, 14: -135, 15: -90, 16: -45, 17: 0, 18: 45, 19: -45, + 20: 45, 21: -45, 22: 0, 23: 30, 24: -30, 25: 0, 37: 30, 38: -30 }; +function maneuverSvg(type) { + let body; + if (type === 12 || type === 13) body = uturnPath("dash-banner__arrow"); + else if (type >= 4 && type <= 6) body = ``; // a flag: arriving + else if (type === 26 || type === 27) body = ``; + else body = arrowPath(MANEUVER_ANGLES[type] ?? 0, "dash-banner__arrow"); + return `${body}`; +} + // Valhalla's lane direction bits → the arrow's angle (° from straight on) const LANE_ANGLES = { 2: 0, 16: -45, 8: -90, 4: -135, 32: 45, 64: 90, 128: 135, 512: -25, 1024: 25 }; const LANE_REVERSE = 256; @@ -50,12 +76,8 @@ const LANE_REVERSE = 256; // directions to take, a bitmask too) drawn bold. function laneSvg({ directions, active = 0 }) { const arrow = (bit) => { - const bold = active & bit ? " dash-lane__take" : ""; - if (bit === LANE_REVERSE) return ``; - const a = (LANE_ANGLES[bit] * Math.PI) / 180; - const [x, y] = [12 + 9 * Math.sin(a), 15 - 9 * Math.cos(a)]; - const head = (side) => `L${(x - 5 * Math.sin(a + side)).toFixed(1)} ${(y + 5 * Math.cos(a + side)).toFixed(1)}`; - return ``; + const cls = `dash-lane__arrow${active & bit ? " dash-lane__take" : ""}`; + return bit === LANE_REVERSE ? uturnPath(cls) : arrowPath(LANE_ANGLES[bit], cls); }; const bits = [2, 16, 8, 4, 32, 64, 128, 512, 1024, LANE_REVERSE].filter((bit) => directions & bit); return `${(bits.length ? bits : [2]).map(arrow).join("")}`; @@ -159,17 +181,22 @@ export class DashboardControl { const current = limits.findLast(([km]) => km <= at); const next = limits.find(([km, limit]) => km > at && limit !== current?.[1]); const signal = signals.find(([, , km]) => km > at); - const maneuver = maneuvers.find((m) => m.at > at + 0.005); + const index = maneuvers.findIndex((m) => m.at > at + 0.005); + const maneuver = maneuvers[index]; + const then = maneuvers[index + 1]; + const onStreet = maneuvers[index - 1]?.street; // the one being driven: the last maneuver's if (off <= ON_ROUTE_M) this._lastAt = at; this._nav = { limit: current?.[1] ?? null, next: next && { limit: next[1], m: (next[0] - at) * 1000 }, signal: signal && (signal[2] - at) * 1000, - maneuver: maneuver && { text: maneuver.text, m: (maneuver.at - at) * 1000, lanes: maneuver.lanes }, + maneuver: maneuver && { ...maneuver, m: (maneuver.at - at) * 1000 }, + then: maneuver && then && then.at - maneuver.at <= THEN_M / 1000 ? then : null, + street: onStreet, }; return; } - this._nav = { limit: this._road?.speed_limit ?? null, offRoute: !!this._route }; + this._nav = { limit: this._road?.speed_limit ?? null, offRoute: !!this._route, street: this._road?.name }; if (this._route && (speed ?? 0) >= MOVING_MS && Date.now() - this._rerouteAt >= REROUTE_EVERY_MS) { this._rerouteAt = Date.now(); requestReroute(position, this._route.viaKm.filter((km) => km <= this._lastAt).length); @@ -211,6 +238,7 @@ export class DashboardControl { + @@ -281,6 +309,11 @@ export class DashboardControl { this._card.style.setProperty("--dash-alpha", this._settings.opacity ?? DEFAULT_OPACITY); this._card.innerHTML = `
${INCLINOMETER}
km/h
`; this._map.getContainer().appendChild(this._card); + // the next turn across the top, as in a car navigation + this._banner = document.createElement("div"); + this._banner.className = "dash-banner"; + this._banner.hidden = true; + this._map.getContainer().appendChild(this._banner); this._status.hidden = false; this._status.textContent = "Connecting…"; this._poll(); @@ -291,6 +324,8 @@ export class DashboardControl { this._timer = null; this._card?.remove(); this._card = null; + this._banner?.remove(); + this._banner = null; this._status.hidden = true; } @@ -330,6 +365,7 @@ export class DashboardControl { nav.style.display = widgets.navigation ? "" : "none"; this._card.hidden = !widgets.inclinometer && !widgets.speed && !widgets.navigation; this._renderNav(nav); + this._renderBanner(); const severity = (key, value) => (value == null ? "" : Math.abs(value) >= WARN[key] * 1.5 ? "dash-bad" : Math.abs(value) >= WARN[key] ? "dash-warn" : ""); for (const key of ["roll", "pitch"]) { @@ -363,13 +399,31 @@ export class DashboardControl { if (n?.offRoute) rows.push(`
Off the route — rerouting
`); if (n?.next) rows.push(`
${typeof n.next.limit === "number" ? n.next.limit : n.next.limit ? "" : "?"} in ${distance(n.next.m)}
`); if (n?.signal != null) rows.push(`
${distance(n.signal)}
`); - if (n?.maneuver) { + if (n?.maneuver && !this._settings.widgets.banner) { const { text, m, lanes } = n.maneuver; - rows.push(`
${distance(m)} · ${text.replace(/[&<>]/g, (c) => ({ "&": "&", "<": "<", ">": ">" })[c])}
`); + rows.push(`
${distance(m)} · ${esc(text)}
`); if (lanes && m <= LANES_AHEAD_M) { rows.push(`
${lanes.map(laneSvg).join("")}
`); } } nav.querySelector(".dash-ahead").innerHTML = rows.join(""); } + + // Across the top: the next maneuver's arrow, distance and street (its + // instruction when it has no street), "then …" when the one after follows + // closely, its lanes from LANES_AHEAD_M, and the street being driven. + _renderBanner() { + const n = this._nav; + const show = this._settings.widgets.banner && !!n?.maneuver; + this._banner.hidden = !show; + if (!show) return; + this._banner.style.setProperty("--dash-alpha", Math.max(0.8, this._settings.opacity ?? DEFAULT_OPACITY)); + const { m, type, street, text, exit, lanes } = n.maneuver; + const what = street ? `${exit ? `${exit}. exit · ` : ""}${esc(street)}` : esc(text); + const then = n.then ? `
then ${maneuverSvg(n.then.type)} ${esc(n.then.street || n.then.text)}
` : ""; + const lanesRow = lanes && m <= LANES_AHEAD_M ? `
${lanes.map(laneSvg).join("")}
` : ""; + const onStreet = n.street ? `
on ${esc(n.street)}
` : ""; + this._banner.innerHTML = `
${maneuverSvg(type)}
${distance(m)}
` + + `
${what}
${lanesRow}${then}${onStreet}`; + } } diff --git a/public/js/map.js b/public/js/map.js index 41e3404..1cdb43e 100644 --- a/public/js/map.js +++ b/public/js/map.js @@ -24,7 +24,7 @@ import { notifySidePanelOpen, onlyOneSidePanelOpen, setupSidePanelModes } from " import { isLoggedIn } from "/js/auth.js"; import { DebugControl } from "/js/debug.js"; import { setupUpdate } from "/js/update.js"; -import { patchOnlineStyle, patternImage, PATTERN_IDS, NightMap } from "/js/map_themes.js"; +import { patchOnlineStyle, patternImage, PATTERN_IDS, NightMap, declutterWhenDriving } from "/js/map_themes.js"; import { offerSharedFiles } from "/js/share_import.js"; import HomeButton from "/vendor/npmap-home-button/home-button.esm.js"; import OverviewMap from "/vendor/npmap-overview/overview.esm.js"; @@ -485,6 +485,7 @@ const addPatterns = () => { } }; map.on("style.load", addPatterns); +declutterWhenDriving(map); if (map.isStyleLoaded()) addPatterns(); // Still the fallback for one asked for before that. map.on("styleimagemissing", ({ id }) => { diff --git a/public/js/map_themes.js b/public/js/map_themes.js index 9bdc6d0..716143b 100644 --- a/public/js/map_themes.js +++ b/public/js/map_themes.js @@ -8,19 +8,43 @@ // map.js styles the map with it and /symbols.html draws its legend from the // same patched style, so the two can't drift apart. +// The driving view (the map tilted to 3D, as following does): route +// numbers and minor roads' / paths' names hidden, the main roads' names +// left — what's needed at a glance. Back as soon as the map is flat. +const DRIVE_HIDDEN_LABELS = /^(highway-shield|road_shield|highway-name-(minor|path))/; +const DRIVE_PITCH = 30; + +export function declutterWhenDriving(map) { + let hidden = null; + const apply = () => { + const hide = map.getPitch() >= DRIVE_PITCH; + if (hide === hidden) return; + hidden = hide; + for (const layer of map.getStyle().layers) { + if (DRIVE_HIDDEN_LABELS.test(layer.id)) map.setLayoutProperty(layer.id, "visibility", hide ? "none" : "visible"); + } + }; + map.on("pitchend", apply); + map.on("style.load", () => { + hidden = null; + apply(); + }); +} + export function patchOnlineStyle(style) { return insertTrackOnlyLayer(protectedAreasAndTextures(roadLabelSpacing(parkTilesStyle(style)))); } // Road names and route numbers repeat every symbol-spacing *pixels*, so -// zoomed in close (z22) a street got its name every few meters. Past -// z16 the spacing grows with the zoom: the same distance on the ground -// (~400 m here) at every zoom. -const ROAD_LABEL_FIXED_ZOOM = 16; +// zoomed in close (z22) a street got its name every few meters. 1.5× +// Liberty's spacing, and past z15 it grows with the zoom: the same +// distance on the ground (~900 m) at every zoom. +const ROAD_LABEL_FIXED_ZOOM = 15; +const ROAD_LABEL_SPACING = 1.5; function roadLabelSpacing(style) { for (const layer of style.layers) { if (layer.type !== "symbol" || layer["source-layer"] !== "transportation_name") continue; - const spacing = layer.layout?.["symbol-spacing"] ?? 250; // the style spec's default + const spacing = (layer.layout?.["symbol-spacing"] ?? 250) * ROAD_LABEL_SPACING; // 250: the style spec's default layer.layout = { ...layer.layout, "symbol-spacing": ["interpolate", ["exponential", 2], ["zoom"], ROAD_LABEL_FIXED_ZOOM, spacing, 22, spacing * 64] }; } return style; diff --git a/test/test_routing.rb b/test/test_routing.rb index 4e7e604..5c514ec 100644 --- a/test/test_routing.rb +++ b/test/test_routing.rb @@ -126,11 +126,12 @@ class RoutingTest < Minitest::Test def test_route_picks_the_costing_by_weight_and_returns_a_line shape = "wdg|xA{ubdQc@w@" reply = JSON.generate(trip: { summary: { length: 1.5, time: 90 }, - legs: [{ shape: shape, maneuvers: [{ instruction: "Drive north.", length: 1.5 }] }] }) + legs: [{ shape: shape, maneuvers: [{ instruction: "Drive north.", length: 1.5, type: 2, street_names: ["Main"] }] }] }) # The per-country lookup failing (400) leaves the route as it is. request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}", "HTTP/1.1 400 Bad Request\r\nContent-Length: 2\r\n\r\n{}") do |url| route = Maptool::Routing.route(url, [[9.52, 47.14], [9.53, 47.15]], Maptool::Routing::DEFAULT_VEHICLES[1]) assert_equal [2, "auto", "Drive north."], [route[:geometry][:coordinates].size, route[:properties][:costing], route[:properties][:maneuvers][0][:text]] + assert_equal({ text: "Drive north.", km: 1.5, type: 2, street: "Main" }, route[:properties][:maneuvers][0]) end assert_includes request, %("costing_options":{"auto":{"height":3.0,"width":2.3}})