forked from Blendman974/faceclaw
Navigate app: Location indicator rotates based on the compass; darken the map background color
This commit is contained in:
1 parent
9234458dd6
commit
00dd546b1c
6 files changed
+246
-42
No files matched your search
@@ -60,7 +60,18 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
private volatile FaceclawBleCommunicatorListener listener;
|
private volatile FaceclawBleCommunicatorListener listener;
|
||||||
private final java.util.List<FaceclawImuListener> imuListeners =
|
private final java.util.List<FaceclawImuListener> imuListeners =
|
||||||
new java.util.concurrent.CopyOnWriteArrayList<>();
|
new java.util.concurrent.CopyOnWriteArrayList<>();
|
||||||
private final java.util.List<FaceclawCompassListener> compassListeners =
|
/** A compass subscriber plus the Looper it registered from (see addCompassListener). */
|
||||||
|
private static final class CompassSubscription {
|
||||||
|
final FaceclawCompassListener listener;
|
||||||
|
final Handler handler;
|
||||||
|
|
||||||
|
CompassSubscription(FaceclawCompassListener listener, Handler handler) {
|
||||||
|
this.listener = listener;
|
||||||
|
this.handler = handler;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private final java.util.List<CompassSubscription> compassSubscriptions =
|
||||||
new java.util.concurrent.CopyOnWriteArrayList<>();
|
new java.util.concurrent.CopyOnWriteArrayList<>();
|
||||||
private final java.util.List<FaceclawMicStatusListener> micStatusListeners =
|
private final java.util.List<FaceclawMicStatusListener> micStatusListeners =
|
||||||
new java.util.concurrent.CopyOnWriteArrayList<>();
|
new java.util.concurrent.CopyOnWriteArrayList<>();
|
||||||
@@ -90,7 +101,13 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
private int firmwareDebugFlagsLastSent = -1;
|
private int firmwareDebugFlagsLastSent = -1;
|
||||||
// Desired CFW mode-10 compass state. It survives reconnects; lastSent is
|
// Desired CFW mode-10 compass state. It survives reconnects; lastSent is
|
||||||
// reset with each session so an open Compass window is re-asserted.
|
// reset with each session so an open Compass window is re-asserted.
|
||||||
private boolean compassEnabled;
|
/**
|
||||||
|
* Who currently wants the stock compass running (the Compass window, the
|
||||||
|
* Navigate worker, ...). The magnetometer is one shared resource, so it
|
||||||
|
* stays on while any owner holds it and is released when the last lets go;
|
||||||
|
* this keeps one app's release from silently switching off another's feed.
|
||||||
|
*/
|
||||||
|
private final java.util.Set<String> compassOwners = new java.util.HashSet<>();
|
||||||
private int compassControlLastSent = -1;
|
private int compassControlLastSent = -1;
|
||||||
// Whether the glasses-side compass may still be running: set when an enable
|
// Whether the glasses-side compass may still be running: set when an enable
|
||||||
// is enqueued, cleared only when a disable is acked. Drives the forced
|
// is enqueued, cleared only when a disable is acked. Drives the forced
|
||||||
@@ -481,12 +498,32 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
* stock sid-0x08 navigation notifications and FaceclawCompassListeners.
|
* stock sid-0x08 navigation notifications and FaceclawCompassListeners.
|
||||||
*/
|
*/
|
||||||
public void setCompassEnabled(boolean enable) {
|
public void setCompassEnabled(boolean enable) {
|
||||||
|
setCompassEnabled("compass", enable);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* As above, on behalf of a named owner. The compass runs while at least
|
||||||
|
* one owner has enabled it; an owner disabling it only takes effect once
|
||||||
|
* no other owner still wants it.
|
||||||
|
*/
|
||||||
|
public void setCompassEnabled(String owner, boolean enable) {
|
||||||
synchronized (lock) {
|
synchronized (lock) {
|
||||||
compassEnabled = enable;
|
boolean before = !compassOwners.isEmpty();
|
||||||
|
if (enable) {
|
||||||
|
compassOwners.add(owner);
|
||||||
|
} else {
|
||||||
|
compassOwners.remove(owner);
|
||||||
|
}
|
||||||
|
boolean wanted = !compassOwners.isEmpty();
|
||||||
|
if (wanted == before && compassControlLastSent == (wanted ? 1 : 0)) {
|
||||||
|
logLine("compass " + (enable ? "enable" : "disable") + " by " + owner
|
||||||
|
+ "; state unchanged (owners=" + compassOwners + ")");
|
||||||
|
return;
|
||||||
|
}
|
||||||
compassControlLastSent = -1;
|
compassControlLastSent = -1;
|
||||||
clearMessagesOfKindLocked("compass-control");
|
clearMessagesOfKindLocked("compass-control");
|
||||||
if (running && sessionReady && !shutdownRequested && fixedLayoutCreated) {
|
if (running && sessionReady && !shutdownRequested && fixedLayoutCreated) {
|
||||||
enqueueCompassControlLocked(true, compassEnabled);
|
enqueueCompassControlLocked(true, wanted);
|
||||||
} else {
|
} else {
|
||||||
logLine("defer compass " + (enable ? "enable" : "disable") + "; display path not ready");
|
logLine("defer compass " + (enable ? "enable" : "disable") + "; display path not ready");
|
||||||
}
|
}
|
||||||
@@ -645,15 +682,28 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Subscribe to compass events. Callbacks are delivered on the Looper of
|
||||||
|
* the thread that registered (falling back to the main thread), so app
|
||||||
|
* worker isolates can listen without a cross-thread hop into their JS.
|
||||||
|
*/
|
||||||
public void addCompassListener(FaceclawCompassListener listener) {
|
public void addCompassListener(FaceclawCompassListener listener) {
|
||||||
if (listener != null) {
|
if (listener == null) {
|
||||||
compassListeners.add(listener);
|
return;
|
||||||
}
|
}
|
||||||
|
Looper looper = Looper.myLooper();
|
||||||
|
Handler handler = looper != null ? new Handler(looper) : mainHandler;
|
||||||
|
compassSubscriptions.add(new CompassSubscription(listener, handler));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void removeCompassListener(FaceclawCompassListener listener) {
|
public void removeCompassListener(FaceclawCompassListener listener) {
|
||||||
if (listener != null) {
|
if (listener == null) {
|
||||||
compassListeners.remove(listener);
|
return;
|
||||||
|
}
|
||||||
|
for (CompassSubscription subscription : compassSubscriptions) {
|
||||||
|
if (subscription.listener == listener) {
|
||||||
|
compassSubscriptions.remove(subscription);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1897,10 +1947,11 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (messageToPrewrite == null && !shutdownRequested && fixedLayoutCreated
|
if (messageToPrewrite == null && !shutdownRequested && fixedLayoutCreated
|
||||||
&& (compassEnabled ? 1 : 0) != compassControlLastSent
|
&& (compassOwners.isEmpty() ? 0 : 1) != compassControlLastSent
|
||||||
&& pendingMessages.isEmpty() && inFlightMessages.isEmpty()) {
|
&& pendingMessages.isEmpty() && inFlightMessages.isEmpty()) {
|
||||||
Log.i(TAG, "enqueueing compass " + (compassEnabled ? "enable" : "disable"));
|
boolean wanted = !compassOwners.isEmpty();
|
||||||
enqueueCompassControlLocked(false, compassEnabled);
|
Log.i(TAG, "enqueueing compass " + (wanted ? "enable" : "disable"));
|
||||||
|
enqueueCompassControlLocked(false, wanted);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Up to WINDOW_SIZE messages may be in flight at once (full
|
// Up to WINDOW_SIZE messages may be in flight at once (full
|
||||||
@@ -3310,18 +3361,15 @@ public class FaceclawBleCommunicator implements FaceclawBleListener, Runnable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void emitCompassEvent(int command, int headingDegrees) {
|
private void emitCompassEvent(int command, int headingDegrees) {
|
||||||
if (compassListeners.isEmpty()) {
|
for (CompassSubscription subscription : compassSubscriptions) {
|
||||||
return;
|
subscription.handler.post(() -> {
|
||||||
}
|
|
||||||
mainHandler.post(() -> {
|
|
||||||
for (FaceclawCompassListener compassListener : compassListeners) {
|
|
||||||
try {
|
try {
|
||||||
compassListener.onCompassEvent(command, headingDegrees);
|
subscription.listener.onCompassEvent(command, headingDegrees);
|
||||||
} catch (Throwable t) {
|
} catch (Throwable t) {
|
||||||
Log.w(TAG, "listener onCompassEvent failed", t);
|
Log.w(TAG, "listener onCompassEvent failed", t);
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
});
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void emitSilentMode(boolean silent) {
|
private void emitSilentMode(boolean silent) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package com.faceclaw.app;
|
package com.faceclaw.app;
|
||||||
|
|
||||||
/** Receives stock compass heading and calibration notifications on the main thread. */
|
/** Receives stock compass heading and calibration notifications on the thread that subscribed. */
|
||||||
public interface FaceclawCompassListener {
|
public interface FaceclawCompassListener {
|
||||||
void onCompassEvent(int command, int headingDegrees);
|
void onCompassEvent(int command, int headingDegrees);
|
||||||
}
|
}
|
||||||
@@ -6,6 +6,8 @@
|
|||||||
* Move some items from app context menus to the system context menu
|
* Move some items from app context menus to the system context menu
|
||||||
* Long-press now opens the system context menu and tap-then-hold the app context menu (games keep long-press as a move while playing)
|
* Long-press now opens the system context menu and tap-then-hold the app context menu (games keep long-press as a move while playing)
|
||||||
* Content beneath an open context menu is dimmed
|
* Content beneath an open context menu is dimmed
|
||||||
|
* Navigate app: Location indicator rotates based on the compass
|
||||||
|
* Navigate app: Darken the map background color
|
||||||
|
|
||||||
## 0.6.4 - 2026-09-02
|
## 0.6.4 - 2026-09-02
|
||||||
* Context menus are centered and include window title
|
* Context menus are centered and include window title
|
||||||
|
|||||||
@@ -30,6 +30,9 @@ import {
|
|||||||
type RouteProfile,
|
type RouteProfile,
|
||||||
type StaticMapCamera,
|
type StaticMapCamera,
|
||||||
} from "../../native/mapbox";
|
} from "../../native/mapbox";
|
||||||
|
import { addCompassListener, COMPASS_CHANGED, setCompassEnabled, type CompassEvent } from "../../native/compass";
|
||||||
|
import { magneticDeclinationDegrees } from "../../native/geomagnetic";
|
||||||
|
import { calibrateHeading, normalizeHeading } from "../compass/calibration";
|
||||||
import { bearingDegrees, haversineMeters, RouteFollower, type RouteProgress } from "./route-follower";
|
import { bearingDegrees, haversineMeters, RouteFollower, type RouteProgress } from "./route-follower";
|
||||||
import { drawManeuverGlyph } from "./maneuver-icons";
|
import { drawManeuverGlyph } from "./maneuver-icons";
|
||||||
|
|
||||||
@@ -49,6 +52,10 @@ const FIRST_FIX_TIMEOUT_MS = 10_000;
|
|||||||
const LOCATION_INTERVAL_MS = 1_000;
|
const LOCATION_INTERVAL_MS = 1_000;
|
||||||
/** Above this speed a GPS bearing is trustworthy for heading-up. */
|
/** Above this speed a GPS bearing is trustworthy for heading-up. */
|
||||||
const BEARING_MIN_SPEED_MPS = 2.5;
|
const BEARING_MIN_SPEED_MPS = 2.5;
|
||||||
|
/** The head-direction chevron only redraws once the wearer has turned this far. */
|
||||||
|
const HEADING_STEP_DEG = 4;
|
||||||
|
/** Our claim on the shared glasses magnetometer (see setCompassEnabled). */
|
||||||
|
const COMPASS_OWNER = "navigate";
|
||||||
|
|
||||||
const largeFont = getFont("terminus32");
|
const largeFont = getFont("terminus32");
|
||||||
const mediumFont = getFont("terminus24");
|
const mediumFont = getFont("terminus24");
|
||||||
@@ -134,6 +141,17 @@ let mapLastFetchAtMs = 0;
|
|||||||
let mapLastFetchCenter: [number, number] | null = null;
|
let mapLastFetchCenter: [number, number] | null = null;
|
||||||
let mapNextRetryAtMs = 0;
|
let mapNextRetryAtMs = 0;
|
||||||
let mapLastError = "";
|
let mapLastError = "";
|
||||||
|
/** Bearing the current map image was rendered with (its "up"), for follow mode. */
|
||||||
|
let mapFetchedBearingDeg = 0;
|
||||||
|
|
||||||
|
// Glasses compass: the same firmware feed and wearer calibration as the
|
||||||
|
// Compass app, so the position chevron shows where the wearer is looking
|
||||||
|
// relative to the map rather than always pointing up the direction of travel.
|
||||||
|
let compassActive = false;
|
||||||
|
let unsubscribeCompass: (() => void) | null = null;
|
||||||
|
/** Wearer's true heading (degrees clockwise from north) as last drawn, or null before compass data arrives. */
|
||||||
|
let headHeadingDeg: number | null = null;
|
||||||
|
let declinationCache: { latitude: number; longitude: number; degrees: number | null } | null = null;
|
||||||
|
|
||||||
let tickTimer: ReturnType<typeof setInterval> | null = null;
|
let tickTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
let firstFixWaiters: Array<(fix: TrackedLocation) => void> = [];
|
let firstFixWaiters: Array<(fix: TrackedLocation) => void> = [];
|
||||||
@@ -177,6 +195,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
|
|||||||
case "close-window":
|
case "close-window":
|
||||||
stopNavigation("");
|
stopNavigation("");
|
||||||
window = null;
|
window = null;
|
||||||
|
reconcileCompass();
|
||||||
break;
|
break;
|
||||||
case "input":
|
case "input":
|
||||||
if (!window || window.windowId !== message.windowId) {
|
if (!window || window.windowId !== message.windowId) {
|
||||||
@@ -204,6 +223,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
|
|||||||
if (!window) break;
|
if (!window) break;
|
||||||
window.foreground = message.foreground;
|
window.foreground = message.foreground;
|
||||||
window.focused = message.focused;
|
window.focused = message.focused;
|
||||||
|
reconcileCompass();
|
||||||
if (window.foreground) {
|
if (window.foreground) {
|
||||||
maybeRefreshMap();
|
maybeRefreshMap();
|
||||||
render();
|
render();
|
||||||
@@ -211,6 +231,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
|
|||||||
break;
|
break;
|
||||||
case "screen":
|
case "screen":
|
||||||
screenOn = message.on;
|
screenOn = message.on;
|
||||||
|
reconcileCompass();
|
||||||
if (screenOn && window?.foreground) {
|
if (screenOn && window?.foreground) {
|
||||||
maybeRefreshMap();
|
maybeRefreshMap();
|
||||||
render();
|
render();
|
||||||
@@ -397,6 +418,59 @@ function waitForFix(): Promise<TrackedLocation> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Head heading (glasses compass)
|
||||||
|
|
||||||
|
/** Hold the magnetometer only while its reading is actually on screen. */
|
||||||
|
function reconcileCompass(): void {
|
||||||
|
const wanted =
|
||||||
|
window !== null && window.foreground && screenOn && phase === "navigating" && mapMode === "follow";
|
||||||
|
if (wanted === compassActive) return;
|
||||||
|
compassActive = wanted;
|
||||||
|
if (wanted) {
|
||||||
|
unsubscribeCompass = addCompassListener(handleCompassEvent);
|
||||||
|
setCompassEnabled(true, COMPASS_OWNER);
|
||||||
|
} else {
|
||||||
|
setCompassEnabled(false, COMPASS_OWNER);
|
||||||
|
unsubscribeCompass?.();
|
||||||
|
unsubscribeCompass = null;
|
||||||
|
headHeadingDeg = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleCompassEvent(event: CompassEvent): void {
|
||||||
|
if (!compassActive || event.command !== COMPASS_CHANGED || event.headingDegrees < 0) return;
|
||||||
|
// Wearer-fit offset from the Compass app's calibration, then declination
|
||||||
|
// from our own GPS fix: the map is always true-north referenced.
|
||||||
|
const magnetic = calibrateHeading(event.headingDegrees);
|
||||||
|
const heading = normalizeHeading(magnetic + (currentDeclination() ?? 0));
|
||||||
|
if (headHeadingDeg !== null && angularDistance(heading, headHeadingDeg) < HEADING_STEP_DEG) return;
|
||||||
|
headHeadingDeg = heading;
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Declination at the last fix; it only varies over tens of kilometres, so cache per coarse position. */
|
||||||
|
function currentDeclination(): number | null {
|
||||||
|
if (!lastFix) return null;
|
||||||
|
if (
|
||||||
|
!declinationCache ||
|
||||||
|
Math.abs(declinationCache.latitude - lastFix.latitude) > 0.5 ||
|
||||||
|
Math.abs(declinationCache.longitude - lastFix.longitude) > 0.5
|
||||||
|
) {
|
||||||
|
declinationCache = {
|
||||||
|
latitude: lastFix.latitude,
|
||||||
|
longitude: lastFix.longitude,
|
||||||
|
degrees: magneticDeclinationDegrees(lastFix.latitude, lastFix.longitude),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return declinationCache.degrees;
|
||||||
|
}
|
||||||
|
|
||||||
|
function angularDistance(a: number, b: number): number {
|
||||||
|
const delta = Math.abs(normalizeHeading(a) - normalizeHeading(b));
|
||||||
|
return Math.min(delta, 360 - delta);
|
||||||
|
}
|
||||||
|
|
||||||
function ensureTickTimer(): void {
|
function ensureTickTimer(): void {
|
||||||
const shouldRun = phase === "navigating";
|
const shouldRun = phase === "navigating";
|
||||||
if (shouldRun && tickTimer === null) {
|
if (shouldRun && tickTimer === null) {
|
||||||
@@ -515,9 +589,10 @@ function maybeRefreshMap(): void {
|
|||||||
.then((image) => {
|
.then((image) => {
|
||||||
mapInFlight = false;
|
mapInFlight = false;
|
||||||
if (generation !== routeGeneration) return; // Route/mode changed mid-fetch.
|
if (generation !== routeGeneration) return; // Route/mode changed mid-fetch.
|
||||||
boostContrast(image);
|
levelMap(image);
|
||||||
mapImage = image;
|
mapImage = image;
|
||||||
mapFetchedKey = view.key;
|
mapFetchedKey = view.key;
|
||||||
|
mapFetchedBearingDeg = view.camera.kind === "center" ? view.camera.bearingDeg : 0;
|
||||||
mapLastFetchAtMs = Date.now();
|
mapLastFetchAtMs = Date.now();
|
||||||
mapLastFetchCenter = view.camera.kind === "center" ? [view.camera.longitude, view.camera.latitude] : null;
|
mapLastFetchCenter = view.camera.kind === "center" ? [view.camera.longitude, view.camera.latitude] : null;
|
||||||
mapLastError = "";
|
mapLastError = "";
|
||||||
@@ -542,11 +617,25 @@ function simplifyPath(path: Array<[number, number]>, maxPoints: number): Array<[
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Stretch the dark-style render so roads survive 4bpp quantization. */
|
/**
|
||||||
function boostContrast(image: GrayImage): void {
|
* Level the render for the lens. The dominant tone is the land fill: black
|
||||||
|
* when the style override took, dark gray otherwise. Either way it becomes
|
||||||
|
* the black point, and everything above it is stretched so roads survive
|
||||||
|
* 4bpp quantization.
|
||||||
|
*/
|
||||||
|
function levelMap(image: GrayImage): void {
|
||||||
|
const histogram = new Uint32Array(256);
|
||||||
|
for (let i = 0; i < image.pixels.length; i++) histogram[image.pixels[i]!]++;
|
||||||
|
let black = 0;
|
||||||
|
for (let value = 1; value < 256; value++) {
|
||||||
|
if (histogram[value]! > histogram[black]!) black = value;
|
||||||
|
}
|
||||||
|
// A bright dominant tone isn't a floor (a large plaza, a fetch that came
|
||||||
|
// back mostly label); flattening it would eat the roads.
|
||||||
|
if (black > 64) black = 0;
|
||||||
for (let i = 0; i < image.pixels.length; i++) {
|
for (let i = 0; i < image.pixels.length; i++) {
|
||||||
const value = image.pixels[i]!;
|
const value = image.pixels[i]!;
|
||||||
image.pixels[i] = Math.max(0, Math.min(255, Math.round((value - 12) * 1.7)));
|
image.pixels[i] = value <= black ? 0 : Math.min(255, Math.round((value - black) * 1.7));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -728,7 +817,12 @@ function paintNavigating(image: GrayImage, win: NavWindow): void {
|
|||||||
// Map pane (left).
|
// Map pane (left).
|
||||||
if (mapImage) {
|
if (mapImage) {
|
||||||
image.bitBlt(mapImage, 0, 0);
|
image.bitBlt(mapImage, 0, 0);
|
||||||
if (mapMode === "follow") drawChevron(image, MAP_SIZE / 2, MAP_SIZE / 2);
|
if (mapMode === "follow") {
|
||||||
|
// Head heading relative to the map's up (its render bearing); no
|
||||||
|
// compass reading yet means "up", i.e. the direction of travel.
|
||||||
|
const angle = headHeadingDeg === null ? 0 : headHeadingDeg - mapFetchedBearingDeg;
|
||||||
|
drawChevron(image, MAP_SIZE / 2, MAP_SIZE / 2, angle);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
image.drawRect(0, 0, MAP_SIZE, MAP_SIZE, 60);
|
image.drawRect(0, 0, MAP_SIZE, MAP_SIZE, 60);
|
||||||
const text = mapLastError ? "Map unavailable" : "Loading map...";
|
const text = mapLastError ? "Map unavailable" : "Loading map...";
|
||||||
@@ -788,11 +882,21 @@ function paintNavigating(image: GrayImage, win: NavWindow): void {
|
|||||||
drawFooter(image, `${GESTURE_SCROLL} zoom ${GESTURE_CLICK} ${modeHint} ${GESTURE_DOUBLE_CLICK} back`, PANEL_X + 8);
|
drawFooter(image, `${GESTURE_SCROLL} zoom ${GESTURE_CLICK} ${modeHint} ${GESTURE_DOUBLE_CLICK} back`, PANEL_X + 8);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Position chevron, fixed at the map center (heading-up: it always points up). */
|
/**
|
||||||
function drawChevron(image: GrayImage, cx: number, cy: number): void {
|
* Position chevron, fixed at the map center and rotated `angleDeg` clockwise
|
||||||
|
* from straight up (the map's render bearing) to the wearer's head heading.
|
||||||
|
*/
|
||||||
|
function drawChevron(image: GrayImage, cx: number, cy: number, angleDeg: number): void {
|
||||||
|
const radians = (angleDeg * Math.PI) / 180;
|
||||||
|
const cos = Math.cos(radians);
|
||||||
|
const sin = Math.sin(radians);
|
||||||
|
const triangle = (points: Array<[number, number]>, value: number): void => {
|
||||||
|
const [a, b, c] = points.map(([x, y]): [number, number] => [cx + x * cos - y * sin, cy + x * sin + y * cos]);
|
||||||
|
fillTriangle(image, a![0], a![1], b![0], b![1], c![0], c![1], value);
|
||||||
|
};
|
||||||
// Black halo first so it reads over bright roads.
|
// Black halo first so it reads over bright roads.
|
||||||
fillTriangle(image, cx, cy - 11, cx - 9, cy + 9, cx + 9, cy + 9, 0);
|
triangle([[0, -11], [-9, 9], [9, 9]], 0);
|
||||||
fillTriangle(image, cx, cy - 8, cx - 6, cy + 6, cx + 6, cy + 6, 255);
|
triangle([[0, -8], [-6, 6], [6, 6]], 255);
|
||||||
}
|
}
|
||||||
|
|
||||||
function fillTriangle(image: GrayImage, x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, value: number): void {
|
function fillTriangle(image: GrayImage, x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, value: number): void {
|
||||||
@@ -876,6 +980,9 @@ function render(): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function renderAndSubmit(win: NavWindow, inputFrameId: number): void {
|
function renderAndSubmit(win: NavWindow, inputFrameId: number): void {
|
||||||
|
// Every state change funnels through here, so it doubles as the point where
|
||||||
|
// the compass claim tracks foreground/phase/mode.
|
||||||
|
reconcileCompass();
|
||||||
if (!win.foreground && inputFrameId === 0) return;
|
if (!win.foreground && inputFrameId === 0) return;
|
||||||
const frameId = inputFrameId > 0 ? inputFrameId : frameTimings.startFrame(`render:${win.windowId}`);
|
const frameId = inputFrameId > 0 ? inputFrameId : frameTimings.startFrame(`render:${win.windowId}`);
|
||||||
try {
|
try {
|
||||||
|
|||||||
+11
-4
@@ -20,16 +20,23 @@ function activeCommunicator(): any {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Request CFW mode 10 to start/stop the stock firmware compass. */
|
/**
|
||||||
export function setCompassEnabled(enabled: boolean): void {
|
* Request CFW mode 10 to start/stop the stock firmware compass on behalf of
|
||||||
|
* `owner`. The magnetometer is shared: it runs while any owner wants it and
|
||||||
|
* stops once the last one releases it, so apps can't switch each other off.
|
||||||
|
*/
|
||||||
|
export function setCompassEnabled(enabled: boolean, owner = "compass"): void {
|
||||||
try {
|
try {
|
||||||
activeCommunicator()?.setCompassEnabled(enabled);
|
activeCommunicator()?.setCompassEnabled(owner, enabled);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn(`setCompassEnabled failed: ${error}`);
|
console.warn(`setCompassEnabled failed: ${error}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Subscribe to stock compass heading/calibration notifications. */
|
/**
|
||||||
|
* Subscribe to stock compass heading/calibration notifications. Events are
|
||||||
|
* delivered on the calling thread's Looper, so this works from app workers.
|
||||||
|
*/
|
||||||
export function addCompassListener(listener: (event: CompassEvent) => void): () => void {
|
export function addCompassListener(listener: (event: CompassEvent) => void): () => void {
|
||||||
const active = activeCommunicator();
|
const active = activeCommunicator();
|
||||||
if (!active) return () => {};
|
if (!active) return () => {};
|
||||||
|
|||||||
+49
-9
@@ -18,6 +18,23 @@ const DIRECTIONS_ROOT = "https://api.mapbox.com/directions/v5";
|
|||||||
const STATIC_ROOT = "https://api.mapbox.com/styles/v1";
|
const STATIC_ROOT = "https://api.mapbox.com/styles/v1";
|
||||||
/** Classic dark style; readable after gray conversion. Swappable for a custom Studio style later. */
|
/** Classic dark style; readable after gray conversion. Swappable for a custom Studio style later. */
|
||||||
const MAP_STYLE = "mapbox/dark-v11";
|
const MAP_STYLE = "mapbox/dark-v11";
|
||||||
|
/**
|
||||||
|
* Render-time style override: a black background inserted beneath the road
|
||||||
|
* stack so land, landuse, water, and building fills all come out black on the
|
||||||
|
* lens (dark-v11's own fills are dark gray, which the lens shows as a lit
|
||||||
|
* haze). Static Images allows one added layer per request; `before_layer`
|
||||||
|
* must name a layer in the style, so candidates are tried in order and a
|
||||||
|
* rejected one is skipped for the rest of the session, ending with the plain
|
||||||
|
* style (the worker's levelling pass then does what it can client-side).
|
||||||
|
*/
|
||||||
|
const STYLE_OVERRIDE_LAYER = JSON.stringify({
|
||||||
|
id: "faceclaw-blackout",
|
||||||
|
type: "background",
|
||||||
|
paint: { "background-color": "#000000" },
|
||||||
|
});
|
||||||
|
/** First road layer of dark-v11, then a layer common to every Streets-based style. */
|
||||||
|
const STYLE_OVERRIDE_BEFORE_LAYERS = ["tunnel-path-trail", "building"];
|
||||||
|
let styleOverrideIndex = 0;
|
||||||
const FETCH_TIMEOUT_MS = 15_000;
|
const FETCH_TIMEOUT_MS = 15_000;
|
||||||
|
|
||||||
export type RouteProfile = "driving" | "walking" | "cycling";
|
export type RouteProfile = "driving" | "walking" | "cycling";
|
||||||
@@ -188,18 +205,32 @@ export async function fetchStaticMapGray(options: {
|
|||||||
: `${round6(options.camera.longitude)},${round6(options.camera.latitude)},` +
|
: `${round6(options.camera.longitude)},${round6(options.camera.latitude)},` +
|
||||||
`${options.camera.zoom.toFixed(2)},${Math.round(normalizeBearing(options.camera.bearingDeg))}`;
|
`${options.camera.zoom.toFixed(2)},${Math.round(normalizeBearing(options.camera.bearingDeg))}`;
|
||||||
const size = `${Math.round(options.width)}x${Math.round(options.height)}`;
|
const size = `${Math.round(options.width)}x${Math.round(options.height)}`;
|
||||||
const params = queryString({
|
let bytes: ArrayBuffer;
|
||||||
access_token: requireToken(),
|
for (;;) {
|
||||||
logo: "false",
|
const beforeLayer = STYLE_OVERRIDE_BEFORE_LAYERS[styleOverrideIndex];
|
||||||
attribution: "false",
|
const params: Record<string, string> = {
|
||||||
});
|
access_token: requireToken(),
|
||||||
const url = `${STATIC_ROOT}/${MAP_STYLE}/static/${overlay}${camera}/${size}?${params}`;
|
logo: "false",
|
||||||
|
attribution: "false",
|
||||||
|
};
|
||||||
|
if (beforeLayer !== undefined) {
|
||||||
|
params.addlayer = STYLE_OVERRIDE_LAYER;
|
||||||
|
params.before_layer = beforeLayer;
|
||||||
|
}
|
||||||
|
const url = `${STATIC_ROOT}/${MAP_STYLE}/static/${overlay}${camera}/${size}?${queryString(params)}`;
|
||||||
|
|
||||||
const response = await fetchWithTimeout(url, "Mapbox static map");
|
const response = await fetchWithTimeout(url, "Mapbox static map");
|
||||||
if (!response.ok) {
|
if (response.ok) {
|
||||||
|
bytes = await response.arrayBuffer();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (beforeLayer !== undefined && isStyleOverrideRejection(response.status)) {
|
||||||
|
console.warn(`Mapbox rejected the map style override (before_layer=${beforeLayer}, HTTP ${response.status}); falling back`);
|
||||||
|
styleOverrideIndex++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
throw new Error(`Mapbox static map failed (HTTP ${response.status}).`);
|
throw new Error(`Mapbox static map failed (HTTP ${response.status}).`);
|
||||||
}
|
}
|
||||||
const bytes = await response.arrayBuffer();
|
|
||||||
if (!global.isAndroid) throw new Error("Map decoding is only available on Android.");
|
if (!global.isAndroid) throw new Error("Map decoding is only available on Android.");
|
||||||
const image = grayImageFromPacket(
|
const image = grayImageFromPacket(
|
||||||
com.faceclaw.app.ImageFileLoader.loadGrayFromBytes(bytes, Math.round(options.width), Math.round(options.height)),
|
com.faceclaw.app.ImageFileLoader.loadGrayFromBytes(bytes, Math.round(options.width), Math.round(options.height)),
|
||||||
@@ -281,6 +312,15 @@ async function fetchWithTimeout(url: string, label: string): Promise<Response> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A client error that plausibly blames the added layer (an unknown
|
||||||
|
* before_layer, or a style without it), as opposed to token or quota trouble
|
||||||
|
* that the plain request would hit just the same.
|
||||||
|
*/
|
||||||
|
function isStyleOverrideRejection(status: number): boolean {
|
||||||
|
return status >= 400 && status < 500 && status !== 401 && status !== 403 && status !== 429;
|
||||||
|
}
|
||||||
|
|
||||||
function normalizeBearing(bearingDeg: number): number {
|
function normalizeBearing(bearingDeg: number): number {
|
||||||
return ((bearingDeg % 360) + 360) % 360;
|
return ((bearingDeg % 360) + 360) % 360;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user