mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 16:22:20 +00:00
Merge origin/main: street-level links, embed terrain waits, Swedish, and host-supplied weather frames on the renderer's ports
A weather frame source's regional tiles reach the renderer through the imagery layer's fetchTile, drawn and handed over as PNG bytes, a null tile one shared transparent tile; the camera-owner watch listens on the renderer's canvas.
This commit is contained in:
commit
c57e535275
110 files changed
+12262
-168
No files matched your search
+23
-11
@@ -502,14 +502,26 @@ export function createModel({
|
||||
return `${isolate(latPart)} ${isolate(lonPart)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Millisecond delta → `{ unit: '<1h' | 'h' | 'd', count }`, or null for
|
||||
* invalid input. Both age formatters read it, so they pick the same unit.
|
||||
*/
|
||||
|
||||
function ageParts(deltaMs) {
|
||||
if (!Number.isFinite(deltaMs) || deltaMs < 0) return null;
|
||||
const hours = deltaMs / 3600000;
|
||||
if (hours < 1) return { unit: '<1h', count: 0 };
|
||||
const wholeHours = Math.round(hours);
|
||||
if (wholeHours < 48) return { unit: 'h', count: wholeHours };
|
||||
return { unit: 'd', count: Math.round(hours / 24) };
|
||||
}
|
||||
|
||||
/** Millisecond delta → "<1h" / "Xh" / "Xd", or '' for invalid input. */
|
||||
|
||||
function formatAge(deltaMs) {
|
||||
if (!Number.isFinite(deltaMs) || deltaMs < 0) return '';
|
||||
const hours = deltaMs / 3600000;
|
||||
if (hours < 1) return '<1h';
|
||||
if (hours < 48) return `${Math.round(hours)}h`;
|
||||
return `${Math.round(hours / 24)}d`;
|
||||
const age = ageParts(deltaMs);
|
||||
if (!age) return '';
|
||||
return age.unit === '<1h' ? '<1h' : `${age.count}${age.unit}`;
|
||||
}
|
||||
|
||||
/** Millisecond delta → "<1m ago" / "Xm ago" / "Xh ago" (fresh-feed readout). */
|
||||
@@ -540,12 +552,12 @@ export function createModel({
|
||||
/** formatAge for a card: "<1h", "24h", "3d" in the UI language ("24 ч"). */
|
||||
|
||||
function formatAgeLabel(deltaMs) {
|
||||
if (!Number.isFinite(deltaMs) || deltaMs < 0) return '';
|
||||
const hours = deltaMs / 3600000;
|
||||
if (hours < 1) return t('<1h', { context: 'age' });
|
||||
if (hours < 48)
|
||||
return t('{count}h', { context: 'age', count: Math.round(hours) });
|
||||
return t('{count}d', { context: 'age', count: Math.round(hours / 24) });
|
||||
const age = ageParts(deltaMs);
|
||||
if (!age) return '';
|
||||
if (age.unit === '<1h') return t('<1h', { context: 'age' });
|
||||
return age.unit === 'h'
|
||||
? t('{count}h', { context: 'age', count: age.count })
|
||||
: t('{count}d', { context: 'age', count: age.count });
|
||||
}
|
||||
|
||||
/** Normalized 0..1 confidence → low/nominal/high display bucket. */
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { getLocale, setLocale } from '../../i18n/index.js';
|
||||
import { createModel } from './model.js';
|
||||
|
||||
const HOUR_MS = 3600000;
|
||||
|
||||
test('a fire age that rounds to 48 hours reads in days, as 48 hours does', () => {
|
||||
const previousLocale = getLocale();
|
||||
const { formatAge, formatAgeLabel } = createModel({
|
||||
services: { anchors: {} },
|
||||
});
|
||||
try {
|
||||
setLocale('en');
|
||||
assert.equal(formatAge(47.4 * HOUR_MS), '47h');
|
||||
assert.equal(formatAge(47.5 * HOUR_MS), '2d');
|
||||
assert.equal(formatAge(47.6 * HOUR_MS), '2d');
|
||||
assert.equal(formatAge(48 * HOUR_MS), '2d');
|
||||
assert.equal(formatAgeLabel(47.4 * HOUR_MS), '47h');
|
||||
assert.equal(formatAgeLabel(47.5 * HOUR_MS), '2d');
|
||||
assert.equal(formatAgeLabel(47.6 * HOUR_MS), formatAgeLabel(48 * HOUR_MS));
|
||||
assert.equal(formatAgeLabel(48 * HOUR_MS), '2d');
|
||||
} finally {
|
||||
setLocale(previousLocale);
|
||||
}
|
||||
});
|
||||
|
||||
test('both fire age formatters agree on invalid, sub-hour and multi-day ages', () => {
|
||||
const previousLocale = getLocale();
|
||||
const { formatAge, formatAgeLabel } = createModel({
|
||||
services: { anchors: {} },
|
||||
});
|
||||
try {
|
||||
setLocale('en');
|
||||
for (const format of [formatAge, formatAgeLabel]) {
|
||||
assert.equal(format(-1), '');
|
||||
assert.equal(format(Number.NaN), '');
|
||||
assert.equal(format(0.5 * HOUR_MS), '<1h');
|
||||
assert.equal(format(1 * HOUR_MS), '1h');
|
||||
assert.equal(format(72 * HOUR_MS), '3d');
|
||||
}
|
||||
} finally {
|
||||
setLocale(previousLocale);
|
||||
}
|
||||
});
|
||||
+200
-18
@@ -14,7 +14,12 @@ import {
|
||||
keyAlternatives,
|
||||
summarizeCoverage,
|
||||
} from './uiState.js';
|
||||
import { canvasSize, groundUnderCamera, viewCentre } from './view.js';
|
||||
import {
|
||||
canvasSize,
|
||||
groundUnderCamera,
|
||||
metresBetween,
|
||||
viewCentre,
|
||||
} from './view.js';
|
||||
import { toLonLatH } from '../../geo/index.js';
|
||||
import { findCamera, findQuery } from '../../render/rendererOf.js';
|
||||
import { isPickedWorldPosition } from '../../data/scenePick.js';
|
||||
@@ -24,6 +29,7 @@ import {
|
||||
AIM_AT_GROUND_MESSAGE,
|
||||
keyStatusLabel,
|
||||
NEAREST_RADIUS_M,
|
||||
NEAREST_RADIUS_MAX_M,
|
||||
POSITION_PICK_ID,
|
||||
STREET_LEVEL_LAYER_ID,
|
||||
} from './policy.js';
|
||||
@@ -35,6 +41,11 @@ const KEY_STATUS_TIMEOUT_MS = 10_000;
|
||||
/** Re-measures of a ground not loaded yet (Google 3D), a second apart. */
|
||||
const GROUND_RETRY_LIMIT = 5;
|
||||
const GROUND_RETRY_MS = 1000;
|
||||
/**
|
||||
* An armed point stays the OPEN button's target while the view centre is
|
||||
* this close to it (m); a user who moved on opens what the view shows now.
|
||||
*/
|
||||
const ARMED_REACH_M = 1000;
|
||||
|
||||
/**
|
||||
* The Street Level layer over imagery providers (contract in registry.js).
|
||||
@@ -174,6 +185,12 @@ export function createStreetLevelLayer({
|
||||
const owner = state.providers.get(state.street.providerId);
|
||||
if (state.street.open && owner && !providerAvailable(owner))
|
||||
layer.closeViewer();
|
||||
// An armed lookup for a source whose map left dies too.
|
||||
const armedFor = state.street.armed?.providerIds?.map((id) =>
|
||||
state.providers.get(id),
|
||||
);
|
||||
if (armedFor?.some((entry) => entry && !providerAvailable(entry)))
|
||||
state.street.armed = null;
|
||||
for (const entry of state.providers.values()) {
|
||||
if (!entry.def.requiresMapStack) continue;
|
||||
if (state.enabled && entry.on && providerAvailable(entry))
|
||||
@@ -258,8 +275,11 @@ export function createStreetLevelLayer({
|
||||
if (providerAvailable(entry)) parts.credits.show(state.viewer, entry.def);
|
||||
}
|
||||
|
||||
/** Sources whose open photo a replacing request keeps up while it switches them off. */
|
||||
const heldViewers = new Map();
|
||||
|
||||
function deactivate(entry) {
|
||||
parts.viewerHost.unmount(entry.def.id);
|
||||
if (!heldViewers.has(entry.def.id)) parts.viewerHost.unmount(entry.def.id);
|
||||
entry.instance.deactivate();
|
||||
parts.credits.hide(state.viewer, entry.def);
|
||||
}
|
||||
@@ -272,6 +292,13 @@ export function createStreetLevelLayer({
|
||||
nearestLookup = null;
|
||||
}
|
||||
|
||||
/** Close the image and deselect its sequence on the map. */
|
||||
function closeViewer() {
|
||||
abortNearest();
|
||||
parts.viewerHost.close();
|
||||
parts.clearSequences();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ground under the screen centre: the drawn surface, else the ellipsoid;
|
||||
* null for sky, undefined when it cannot aim.
|
||||
@@ -298,8 +325,14 @@ export function createStreetLevelLayer({
|
||||
}
|
||||
|
||||
/** `frame: false` keeps the camera where it is (the user picked the spot). */
|
||||
function openImage(providerId, imageId, { frame = true } = {}) {
|
||||
function openImage(
|
||||
providerId,
|
||||
imageId,
|
||||
{ frame = true, signal = null } = {},
|
||||
) {
|
||||
if (signal?.aborted) return Promise.resolve(false);
|
||||
abortNearest();
|
||||
state.street.armed = null;
|
||||
const entry = state.providers.get(providerId);
|
||||
if (entry && !providerAvailable(entry)) {
|
||||
state.street.loading = false;
|
||||
@@ -307,7 +340,7 @@ export function createStreetLevelLayer({
|
||||
notify();
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
return parts.viewerHost.open(providerId, imageId, { frame });
|
||||
return parts.viewerHost.open(providerId, imageId, { frame, signal });
|
||||
}
|
||||
|
||||
function unavailableReason(entry) {
|
||||
@@ -353,6 +386,9 @@ export function createStreetLevelLayer({
|
||||
function switchProvider(entry, on) {
|
||||
if (entry.on === on) return;
|
||||
entry.on = on;
|
||||
// A lookup armed for this source dies with it.
|
||||
if (!on && state.street.armed?.providerIds?.includes(entry.def.id))
|
||||
state.street.armed = null;
|
||||
if (!state.enabled) return;
|
||||
if (on) activate(entry);
|
||||
else deactivate(entry);
|
||||
@@ -489,6 +525,33 @@ export function createStreetLevelLayer({
|
||||
},
|
||||
/** Registered providers, in chip order. */
|
||||
providerIds: defs.map((def) => def.id),
|
||||
/** The map stack a provider needs (`requiresMapStack`), or null for any. */
|
||||
requiredMapStack(providerId) {
|
||||
const def = defs.find((entry) => entry.id === providerId);
|
||||
return def?.requiresMapStack || null;
|
||||
},
|
||||
/**
|
||||
* A provider's name and key state on any map (the panel lists a provider
|
||||
* only on the map it needs). `configured` is null until its status call
|
||||
* answers; `keyRequired` covers a missing or refused key.
|
||||
*/
|
||||
providerStatus(providerId) {
|
||||
const entry = state.providers.get(providerId);
|
||||
if (!entry) return null;
|
||||
const stats = entry.instance.coverageStats();
|
||||
return {
|
||||
id: entry.def.id,
|
||||
name: entry.def.name,
|
||||
on: entry.on,
|
||||
configured: entry.status ? entry.status.configured === true : null,
|
||||
keyRequired: stats.keyRequired === true || stats.keyRejected === true,
|
||||
keyRejected: stats.keyRejected === true,
|
||||
groundClick: entry.def.groundClick === true,
|
||||
billed: entry.def.billedPerImage === true,
|
||||
available: providerAvailable(entry),
|
||||
error: stats.error || null,
|
||||
};
|
||||
},
|
||||
getSourceAvailability() {
|
||||
const available = defs.length > 0;
|
||||
return {
|
||||
@@ -646,19 +709,66 @@ export function createStreetLevelLayer({
|
||||
* Open the nearest image of the active providers (or `providerIds`) near
|
||||
* a point, else the view centre, or with `aim: 'screen-centre'` the ground
|
||||
* under the screen centre (sky: nothing). Providers without
|
||||
* `nearestImage` are skipped.
|
||||
* `nearestImage` are skipped. Options:
|
||||
* - `radiusM` widens the search where a provider can (a geocoded landmark
|
||||
* is rarely within 50 m of a street);
|
||||
* - `signal` retires the lookup: nothing opens after it fires;
|
||||
* - `armed: false` (the assistant's own request) ignores a link's armed
|
||||
* point and keeps it until a photo opens;
|
||||
* - `replace: true` keeps an open photo (and EXPAND) up while it looks and
|
||||
* closes it if nothing opens;
|
||||
* - `proceed()` is asked before a found photo loads or an empty lookup
|
||||
* reports; false retires the request and leaves the panel as it was.
|
||||
* Why nothing opened is in `street.nearestOutcome`: 'empty', 'sky' or
|
||||
* null (an error).
|
||||
*/
|
||||
async openNearest(
|
||||
point,
|
||||
{ providerIds = null, frame = true, aim = 'view' } = {},
|
||||
{
|
||||
providerIds = null,
|
||||
frame = true,
|
||||
aim = 'view',
|
||||
radiusM = null,
|
||||
signal: callerSignal = null,
|
||||
armed: useArmed = true,
|
||||
replace = false,
|
||||
proceed = null,
|
||||
} = {},
|
||||
) {
|
||||
if (callerSignal?.aborted) return false;
|
||||
state.street.nearestOutcome = null;
|
||||
// An OPEN press after a link armed a lookup opens what the link asked;
|
||||
// any other lookup is a new request and drops the armed one.
|
||||
const armed = useArmed ? state.street.armed : null;
|
||||
if (useArmed) state.street.armed = null;
|
||||
const closeReplaced = () => {
|
||||
if (replace && state.street.open) closeViewer();
|
||||
};
|
||||
if (!point && aim === 'screen-centre' && armed) {
|
||||
// OPEN promises the view centre: the link's spot only while the view
|
||||
// still shows it, or when the view cannot be picked.
|
||||
const centre = armed.point ? screenCentreGround() : null;
|
||||
if (!armed.point) radiusM ??= armed.radiusM;
|
||||
else if (
|
||||
centre === undefined ||
|
||||
(centre && metresBetween(centre, armed.point) <= ARMED_REACH_M)
|
||||
) {
|
||||
point = armed.point;
|
||||
radiusM ??= armed.radiusM;
|
||||
}
|
||||
}
|
||||
const radius = Number.isFinite(radiusM)
|
||||
? Math.min(NEAREST_RADIUS_MAX_M, Math.max(1, radiusM))
|
||||
: NEAREST_RADIUS_M;
|
||||
let view = point;
|
||||
if (!view && aim === 'screen-centre') {
|
||||
view = screenCentreGround();
|
||||
if (view === null) {
|
||||
abortNearest();
|
||||
closeReplaced();
|
||||
state.street.loading = false;
|
||||
state.street.error = AIM_AT_GROUND_MESSAGE;
|
||||
state.street.nearestOutcome = 'sky';
|
||||
notify();
|
||||
return false;
|
||||
}
|
||||
@@ -670,6 +780,19 @@ export function createStreetLevelLayer({
|
||||
const lookup = new AbortController();
|
||||
nearestLookup = lookup;
|
||||
const { signal } = lookup;
|
||||
const onCallerAbort = () => lookup.abort();
|
||||
callerSignal?.addEventListener('abort', onCallerAbort, { once: true });
|
||||
const retired = () => {
|
||||
callerSignal?.removeEventListener('abort', onCallerAbort);
|
||||
// A newer lookup owns the panel, its spinner and its error.
|
||||
if (nearestLookup !== lookup) return false;
|
||||
nearestLookup = null;
|
||||
if (state.street.loading) {
|
||||
state.street.loading = false;
|
||||
notify();
|
||||
}
|
||||
return false;
|
||||
};
|
||||
state.street.loading = true;
|
||||
state.street.error = null;
|
||||
notify();
|
||||
@@ -684,49 +807,108 @@ export function createStreetLevelLayer({
|
||||
try {
|
||||
imageId = await entry.instance.nearestImage(
|
||||
{ lat: view.lat, lon: view.lon },
|
||||
{ signal },
|
||||
radius === NEAREST_RADIUS_M
|
||||
? { signal }
|
||||
: { signal, radiusM: radius },
|
||||
);
|
||||
} catch (error) {
|
||||
if (callerSignal?.aborted) return retired();
|
||||
// Overtaken: whatever replaced it owns the panel, errors included.
|
||||
if (signal.aborted) return false;
|
||||
if (signal.aborted) return retired();
|
||||
// One provider failing (no key, offline) must not hide the others.
|
||||
lastError = error;
|
||||
continue;
|
||||
}
|
||||
if (signal.aborted) return false;
|
||||
if (callerSignal?.aborted) return retired();
|
||||
if (signal.aborted) return retired();
|
||||
if (!state.enabled) break;
|
||||
// Switched off, or its map left, while it looked: try the next.
|
||||
if (!imageId || !entry.on || !providerAvailable(entry)) continue;
|
||||
if (proceed && proceed() !== true) return retired();
|
||||
nearestLookup = null;
|
||||
return openImage(entry.def.id, imageId, { frame });
|
||||
callerSignal?.removeEventListener('abort', onCallerAbort);
|
||||
// A sequence playing in the replaced photo would step past this one.
|
||||
if (replace && state.street.open) parts.viewerHost.stopPlayback();
|
||||
// The caller's signal still counts while the viewer mounts and loads.
|
||||
return openImage(entry.def.id, imageId, {
|
||||
frame,
|
||||
signal: callerSignal,
|
||||
});
|
||||
}
|
||||
if (nearestLookup === lookup) nearestLookup = null;
|
||||
callerSignal?.removeEventListener('abort', onCallerAbort);
|
||||
// Replaced while it looked: the panel is the newer lookup's.
|
||||
if (nearestLookup !== lookup) return false;
|
||||
// Given up by its caller: the panel stays as it was.
|
||||
if (proceed && proceed() !== true) return retired();
|
||||
nearestLookup = null;
|
||||
closeReplaced();
|
||||
// Switched off while it looked: nothing to open, nothing to report.
|
||||
const stillOn = entries.some(
|
||||
(entry) => entry.on && providerAvailable(entry),
|
||||
);
|
||||
// A provider's own refusal is English data that the panel translates;
|
||||
// the core's refusal is built here, for the panel only, in the language.
|
||||
if (state.enabled && stillOn && !lastError)
|
||||
state.street.nearestOutcome = 'empty';
|
||||
if (state.enabled && stillOn)
|
||||
state.street.error =
|
||||
lastError?.message ||
|
||||
(point
|
||||
? t('No street-level imagery within {radius} m of that point', {
|
||||
radius: NEAREST_RADIUS_M,
|
||||
radius,
|
||||
})
|
||||
: t(
|
||||
'No street-level imagery within {radius} m of the view centre',
|
||||
{ radius: NEAREST_RADIUS_M },
|
||||
{
|
||||
radius,
|
||||
},
|
||||
));
|
||||
state.street.loading = false;
|
||||
notify();
|
||||
return false;
|
||||
},
|
||||
/** Close the image and deselect its sequence on the map. */
|
||||
closeViewer() {
|
||||
abortNearest();
|
||||
parts.viewerHost.close();
|
||||
parts.clearSequences();
|
||||
closeViewer,
|
||||
/**
|
||||
* Keep the open photo up while a request that replaces it switches its
|
||||
* source off, so EXPAND stays; only that source's own switch-off is held,
|
||||
* a source switched by hand meanwhile still stops a load. Release frees
|
||||
* the old viewer.
|
||||
*/
|
||||
holdViewer() {
|
||||
const id = state.street.open ? state.street.providerId : null;
|
||||
if (!id) return () => {};
|
||||
heldViewers.set(id, (heldViewers.get(id) || 0) + 1);
|
||||
let held = true;
|
||||
return () => {
|
||||
if (!held) return;
|
||||
held = false;
|
||||
const left = heldViewers.get(id) - 1;
|
||||
if (left > 0) return void heldViewers.set(id, left);
|
||||
heldViewers.delete(id);
|
||||
if (state.providers.get(id)?.on !== false) return;
|
||||
// Its photo still up (the request gave up) closes with its source;
|
||||
// otherwise the request replaced or closed it, and the panel keeps
|
||||
// what that request left (an error, an armed OPEN).
|
||||
if (state.street.open && state.street.providerId === id)
|
||||
parts.viewerHost.unmount(id);
|
||||
else parts.viewerHost.release(id);
|
||||
};
|
||||
},
|
||||
/**
|
||||
* Arm a nearest lookup for the next OPEN press without running it (a link
|
||||
* to a source that bills every load). Any other lookup, open or close, the
|
||||
* source switched off or its map leaving clears it.
|
||||
*/
|
||||
armNearest(point, { providerIds = null, radiusM = null } = {}) {
|
||||
state.street.armed = {
|
||||
point:
|
||||
Number.isFinite(point?.lat) && Number.isFinite(point?.lon)
|
||||
? { lat: point.lat, lon: point.lon }
|
||||
: null,
|
||||
providerIds: Array.isArray(providerIds) ? [...providerIds] : null,
|
||||
radiusM: Number.isFinite(radiusM) ? radiusM : null,
|
||||
};
|
||||
notify();
|
||||
},
|
||||
setViewerRenderMode: (mode) => parts.viewerHost.setRenderMode(mode),
|
||||
resizeViewer: () => parts.viewerHost.resize(),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { getEventListeners } from 'node:events';
|
||||
import * as Cesium from 'cesium';
|
||||
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
|
||||
import { createStreetLevelLayer } from './index.js';
|
||||
@@ -15,6 +16,9 @@ import {
|
||||
streetPorts,
|
||||
} from '../../testSupport/streetLevelFakes.mjs';
|
||||
import { setLocale } from '../../i18n/index.js';
|
||||
// Loaded up front: it brings Vue, which reads `document` once when it loads,
|
||||
// and several tests here stand a bare fake document in for the page.
|
||||
import { createGevActionRunner } from '../../voice/gevActions.js';
|
||||
|
||||
/**
|
||||
* A layer over `source` and `photoViewer`, initialised on a stand-in viewer
|
||||
@@ -364,7 +368,11 @@ function fakeViewer() {
|
||||
}
|
||||
|
||||
/** A layer over `providers`, initialised and enabled on a stand-in viewer. */
|
||||
async function enabledLayer(t, providers = [fakeProvider()]) {
|
||||
async function enabledLayer(
|
||||
t,
|
||||
providers = [fakeProvider()],
|
||||
{ services, setup } = {},
|
||||
) {
|
||||
const saved = globalThis.document;
|
||||
// A pose moves the position marker, whose glyph is drawn on a canvas.
|
||||
const drawing = new Proxy({}, { get: () => () => ({ addColorStop() {} }) });
|
||||
@@ -372,7 +380,11 @@ async function enabledLayer(t, providers = [fakeProvider()]) {
|
||||
createElement: () => ({ getContext: () => drawing }),
|
||||
});
|
||||
const viewer = fakeViewer();
|
||||
const layer = createStreetLevelLayer({ providers });
|
||||
setup?.(viewer);
|
||||
const layer = createStreetLevelLayer({
|
||||
providers,
|
||||
...(services ? { services } : {}),
|
||||
});
|
||||
layer.init(viewer);
|
||||
layer.enable(viewer);
|
||||
t.after(() => {
|
||||
@@ -990,6 +1002,54 @@ test('a pick that fails at the screen centre counts as a miss, and the ellipsoid
|
||||
assert.ok(Math.abs(lookups[0].lat - 38.5799) < 1e-9);
|
||||
});
|
||||
|
||||
test('OPEN after a link armed opens at its point only while the view centre is still near it', async (t) => {
|
||||
const { createStreetLevelLayer: create } = await import('./index.js');
|
||||
const scenePick = await import('../../data/scenePick.js');
|
||||
const lookups = [];
|
||||
const provider = fakeProvider({
|
||||
nearestImage: async (point, options) => {
|
||||
lookups.push({ point, radiusM: options?.radiusM ?? null });
|
||||
return null;
|
||||
},
|
||||
});
|
||||
const saved = globalThis.document;
|
||||
const drawing = new Proxy({}, { get: () => () => ({ addColorStop() {} }) });
|
||||
globalThis.document = Object.assign(new EventTarget(), {
|
||||
createElement: () => ({ getContext: () => drawing }),
|
||||
});
|
||||
const viewer = fakeViewer();
|
||||
const centre = Cesium.Cartesian3.fromDegrees(-121.4937, 38.5799, 0);
|
||||
Object.assign(viewer.scene, {
|
||||
pickPositionSupported: true,
|
||||
pickPosition: (at) => (at.x === 500 && at.y === 300 ? centre : undefined),
|
||||
});
|
||||
viewer.scene.canvas.clientWidth = 1000;
|
||||
viewer.scene.canvas.clientHeight = 600;
|
||||
const layer = create({ providers: [provider], services: { scenePick } });
|
||||
layer.init(viewer);
|
||||
layer.enable(viewer);
|
||||
t.after(() => {
|
||||
layer.destroy();
|
||||
globalThis.document = saved;
|
||||
});
|
||||
// About 120 m from the view centre: the link's spot is still in view.
|
||||
layer.armNearest({ lat: 38.5808, lon: -121.494 }, { radiusM: 250 });
|
||||
await layer.openNearest(undefined, { aim: 'screen-centre' });
|
||||
assert.deepEqual(lookups.at(-1), {
|
||||
point: { lat: 38.5808, lon: -121.494 },
|
||||
radiusM: 250,
|
||||
});
|
||||
// The user flew to Paris after the link armed in Sacramento: OPEN looks
|
||||
// under the view centre, and the link's radius goes with its point.
|
||||
layer.armNearest({ lat: 48.8584, lon: 2.2945 }, { radiusM: 250 });
|
||||
await layer.openNearest(undefined, { aim: 'screen-centre' });
|
||||
const press = lookups.at(-1);
|
||||
assert.ok(Math.abs(press.point.lat - 38.5799) < 1e-9, 'the view centre');
|
||||
assert.ok(Math.abs(press.point.lon - -121.4937) < 1e-9);
|
||||
assert.equal(press.radiusM, null, 'the default radius');
|
||||
assert.equal(layer.getUIState().street.armed, null, 'dropped');
|
||||
});
|
||||
|
||||
test('the button aimed at the sky opens nothing, and says to aim at a street', async (t) => {
|
||||
const { createStreetLevelLayer: create } = await import('./index.js');
|
||||
const lookups = [];
|
||||
@@ -1163,6 +1223,732 @@ test('switching source by params clears a failed lookup’s error; reapplying th
|
||||
assert.equal(second.getUIState().street.error, kept);
|
||||
});
|
||||
|
||||
test('openNearest searches wider on request, never past the cap, and says how far it looked', async (t) => {
|
||||
const { layer, fake } = await withStreetView(t, { nearest: () => null });
|
||||
layer.setProviderEnabled('google', true);
|
||||
await settle();
|
||||
await layer.openNearest(
|
||||
{ lat: 38.58, lon: -121.49 },
|
||||
{ providerIds: ['google'], frame: false, radiusM: 250 },
|
||||
);
|
||||
assert.equal(fake.lookups.at(-1).radius, 250);
|
||||
assert.equal(
|
||||
layer.getUIState().street.error,
|
||||
'No street-level imagery within 250 m of that point',
|
||||
);
|
||||
await layer.openNearest(
|
||||
{ lat: 38.58, lon: -121.49 },
|
||||
{ providerIds: ['google'], frame: false, radiusM: 5000 },
|
||||
);
|
||||
assert.equal(fake.lookups.at(-1).radius, 250, 'capped');
|
||||
await layer.openNearest(
|
||||
{ lat: 38.58, lon: -121.49 },
|
||||
{ providerIds: ['google'], frame: false },
|
||||
);
|
||||
assert.equal(fake.lookups.at(-1).radius, 50, 'a click keeps the default');
|
||||
});
|
||||
|
||||
test('a caller’s signal retires a nearest lookup: nothing opens after it fires', async (t) => {
|
||||
let answer = null;
|
||||
const { layer, fake } = await withStreetView(t, {
|
||||
nearest: () => 'pano-a',
|
||||
});
|
||||
const lib = fake.library;
|
||||
const service = lib.StreetViewService.prototype.getPanorama;
|
||||
lib.StreetViewService.prototype.getPanorama = function (request) {
|
||||
return new Promise((resolve, reject) => {
|
||||
answer = () => service.call(this, request).then(resolve, reject);
|
||||
});
|
||||
};
|
||||
layer.setProviderEnabled('google', true);
|
||||
await settle();
|
||||
const controller = new AbortController();
|
||||
const pending = layer.openNearest(
|
||||
{ lat: 38.58, lon: -121.49 },
|
||||
{ providerIds: ['google'], frame: false, signal: controller.signal },
|
||||
);
|
||||
await settle();
|
||||
controller.abort();
|
||||
answer?.();
|
||||
assert.equal(await pending, false);
|
||||
const street = layer.getUIState().street;
|
||||
assert.equal(street.open, false, 'the retired lookup opened nothing');
|
||||
assert.equal(street.loading, false, 'no stuck spinner');
|
||||
assert.equal(street.error, null, 'and reports no missing imagery');
|
||||
const refused = await layer.openNearest(
|
||||
{ lat: 38.58, lon: -121.49 },
|
||||
{ providerIds: ['google'], frame: false, signal: controller.signal },
|
||||
);
|
||||
assert.equal(refused, false, 'an already-aborted signal asks nothing');
|
||||
});
|
||||
|
||||
test('providerStatus reports name, key state and billing on any map', async (t) => {
|
||||
const { layer } = await withStreetView(t, { mapStack: 'osm' });
|
||||
const google = layer.providerStatus('google');
|
||||
assert.equal(google.name, 'Google Street View');
|
||||
assert.equal(google.billed, true, 'every Street View load is billed');
|
||||
assert.equal(google.available, false, 'not on this map');
|
||||
assert.equal(google.keyRequired, false);
|
||||
assert.equal(layer.providerStatus('mapillary').billed, false);
|
||||
assert.equal(layer.providerStatus('nope'), null);
|
||||
assert.equal(layer.requiredMapStack('google'), 'photoreal');
|
||||
assert.equal(layer.requiredMapStack('mapillary'), null);
|
||||
});
|
||||
|
||||
test('an armed lookup asks nothing until the OPEN press, then opens at its point and radius once', async (t) => {
|
||||
const { layer, fake, mapillaryLookups } = await withStreetView(t);
|
||||
layer.setProviderEnabled('google', true);
|
||||
await settle();
|
||||
const before = fake.lookups.length;
|
||||
layer.armNearest(
|
||||
{ lat: 38.57986, lon: -121.49372 },
|
||||
{ providerIds: ['google'], radiusM: 250 },
|
||||
);
|
||||
await settle();
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
// The click gate: arming is free. No provider was asked, nothing opened.
|
||||
assert.equal(
|
||||
fake.lookups.length,
|
||||
before,
|
||||
'no Google lookup before the press',
|
||||
);
|
||||
assert.deepEqual(mapillaryLookups, [], 'no Mapillary lookup either');
|
||||
assert.equal(layer.getUIState().street.open, false);
|
||||
assert.equal(layer.getUIState().street.loading, false);
|
||||
assert.deepEqual(layer.getUIState().street.armed, {
|
||||
point: { lat: 38.57986, lon: -121.49372 },
|
||||
providerIds: ['google'],
|
||||
radiusM: 250,
|
||||
});
|
||||
// The OPEN button: no point, aimed at the screen centre.
|
||||
const opened = await layer.openNearest(undefined, {
|
||||
providerIds: ['google'],
|
||||
frame: false,
|
||||
aim: 'screen-centre',
|
||||
});
|
||||
assert.equal(opened, true);
|
||||
assert.equal(
|
||||
fake.lookups.length,
|
||||
before + 1,
|
||||
'exactly one lookup for the press',
|
||||
);
|
||||
const request = fake.lookups.at(-1);
|
||||
assert.deepEqual(
|
||||
request.location,
|
||||
{ lat: 38.57986, lng: -121.49372 },
|
||||
'the armed point, not the screen centre',
|
||||
);
|
||||
assert.equal(request.radius, 250);
|
||||
assert.equal(layer.getUIState().street.armed, null, 'used once');
|
||||
layer.armNearest({ lat: 1, lon: 2 }, { providerIds: ['google'] });
|
||||
layer.closeViewer();
|
||||
assert.equal(layer.getUIState().street.armed, null, 'closing clears it');
|
||||
layer.armNearest({ lat: 1, lon: 2 }, { providerIds: ['google'] });
|
||||
await layer.openNearest(
|
||||
{ lat: 38.58, lon: -121.49 },
|
||||
{ providerIds: ['google'], frame: false },
|
||||
);
|
||||
assert.deepEqual(
|
||||
fake.lookups.at(-1).location,
|
||||
{ lat: 38.58, lng: -121.49 },
|
||||
'an explicit point wins',
|
||||
);
|
||||
assert.equal(layer.getUIState().street.armed, null);
|
||||
// Only the OPEN press consumes the armed point: "street view here" after a
|
||||
// pan is a new request at the view centre, and it drops the armed one.
|
||||
layer.closeViewer();
|
||||
layer.armNearest(
|
||||
{ lat: 10, lon: 20 },
|
||||
{ providerIds: ['google'], radiusM: 250 },
|
||||
);
|
||||
await layer.openNearest(null, { providerIds: ['google'], frame: false });
|
||||
const centre = fake.lookups.at(-1);
|
||||
assert.notDeepEqual(
|
||||
centre.location,
|
||||
{ lat: 10, lng: 20 },
|
||||
'the view centre, not the armed point',
|
||||
);
|
||||
assert.equal(centre.radius, 50, 'and the default radius');
|
||||
assert.equal(layer.getUIState().street.armed, null, 'dropped');
|
||||
// Opening any image, or switching the layer off, clears it too.
|
||||
layer.armNearest({ lat: 10, lon: 20 }, { providerIds: ['google'] });
|
||||
await layer.openImage('google', 'pano-a');
|
||||
assert.equal(layer.getUIState().street.armed, null, 'cleared by an open');
|
||||
layer.armNearest({ lat: 10, lon: 20 }, { providerIds: ['google'] });
|
||||
layer.disable();
|
||||
assert.equal(layer.getUIState().street.armed, null, 'cleared by disable');
|
||||
});
|
||||
|
||||
test('a caller’s signal: an aborted one asks nothing, and a provider that ignores the abort still opens nothing', async (t) => {
|
||||
const { layer, fake } = await withStreetView(t);
|
||||
layer.setProviderEnabled('google', true);
|
||||
await settle();
|
||||
const before = fake.lookups.length;
|
||||
const done = new AbortController();
|
||||
done.abort();
|
||||
assert.equal(
|
||||
await layer.openNearest(
|
||||
{ lat: 38.58, lon: -121.49 },
|
||||
{ providerIds: ['google'], frame: false, signal: done.signal },
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
fake.lookups.length,
|
||||
before,
|
||||
'an already-aborted signal asks nothing',
|
||||
);
|
||||
});
|
||||
|
||||
test('a provider that ignores the abort and answers late still opens nothing', async (t) => {
|
||||
let seen = null;
|
||||
let release = null;
|
||||
const slow = fakeProvider({
|
||||
nearestImage: async (_point, { signal } = {}) => {
|
||||
seen = signal;
|
||||
await new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
return 'late-image';
|
||||
},
|
||||
});
|
||||
const { layer: ignoring } = await enabledLayer(t, [slow]);
|
||||
const { fakeHost } =
|
||||
await import('../../testSupport/googleStreetViewFakes.mjs');
|
||||
ignoring.attachViewerHost(fakeHost());
|
||||
const controller = new AbortController();
|
||||
const pending = ignoring.openNearest(
|
||||
{ lat: 1, lon: 2 },
|
||||
{ frame: false, signal: controller.signal },
|
||||
);
|
||||
await settle();
|
||||
controller.abort();
|
||||
assert.equal(seen?.aborted, true, 'the provider sees the abort');
|
||||
release();
|
||||
assert.equal(await pending, false);
|
||||
const street = ignoring.getUIState().street;
|
||||
assert.equal(street.open, false, 'the late answer opened nothing');
|
||||
assert.equal(street.loading, false, 'no stuck spinner');
|
||||
assert.equal(street.error, null);
|
||||
});
|
||||
|
||||
test('providerStatus reports a keyless source on any map', async (t) => {
|
||||
const keyless = await withStreetView(t, {
|
||||
mapStack: 'osm',
|
||||
mapillaryKeyless: true,
|
||||
});
|
||||
await settle();
|
||||
const mapillary = keyless.layer.providerStatus('mapillary');
|
||||
assert.equal(mapillary.configured, false);
|
||||
assert.equal(mapillary.keyRequired, true);
|
||||
assert.equal(mapillary.keyRejected, false);
|
||||
});
|
||||
|
||||
test('providerStatus reports the key state as unknown until the status call answers', async (t) => {
|
||||
// A freshly loaded sl= link meets its source in this state: unknown is not
|
||||
// "needs its key", or the link would fail on a cold load.
|
||||
const pending = fakeProvider();
|
||||
pending.requiresKeyId = 'mapillary';
|
||||
const create = pending.create;
|
||||
pending.create = (context) => ({
|
||||
...create(context),
|
||||
status: () => new Promise(() => {}),
|
||||
});
|
||||
const { layer } = await enabledLayer(t, [pending]);
|
||||
const status = layer.providerStatus(pending.id);
|
||||
assert.equal(status.configured, null);
|
||||
assert.equal(status.keyRequired, false);
|
||||
});
|
||||
|
||||
test('providerStatus reports a refused key on any map', async (t) => {
|
||||
const refused = await withStreetView(t, { mapStack: 'osm' });
|
||||
refused.loader.refuseKey();
|
||||
await settle();
|
||||
const google = refused.layer.providerStatus('google');
|
||||
assert.equal(
|
||||
google.keyRequired,
|
||||
true,
|
||||
'a refused key gates like a missing one',
|
||||
);
|
||||
assert.equal(google.keyRejected, true);
|
||||
assert.equal(google.available, false, 'still not on this map');
|
||||
});
|
||||
|
||||
test('an armed lookup dies with its source: switched off, or its map gone', async (t) => {
|
||||
const { layer, stack } = await withStreetView(t);
|
||||
layer.setProviderEnabled('google', true);
|
||||
await settle();
|
||||
layer.armNearest(
|
||||
{ lat: 1, lon: 2 },
|
||||
{ providerIds: ['google'], radiusM: 250 },
|
||||
);
|
||||
layer.setProviderEnabled('google', false);
|
||||
assert.equal(
|
||||
layer.getUIState().street.armed,
|
||||
null,
|
||||
'switching the source off clears it',
|
||||
);
|
||||
layer.setProviderEnabled('google', true);
|
||||
layer.armNearest(
|
||||
{ lat: 1, lon: 2 },
|
||||
{ providerIds: ['google'], radiusM: 250 },
|
||||
);
|
||||
// Lighting Mapillary instead (one source at a time) turns Google off too.
|
||||
layer.setProviderEnabled('mapillary', true);
|
||||
assert.equal(
|
||||
layer.getUIState().street.armed,
|
||||
null,
|
||||
'another source lit clears it',
|
||||
);
|
||||
layer.setProviderEnabled('google', true);
|
||||
layer.armNearest(
|
||||
{ lat: 1, lon: 2 },
|
||||
{ providerIds: ['google'], radiusM: 250 },
|
||||
);
|
||||
// A map-stack notify that keeps Google 3D (a silent re-settle) keeps it.
|
||||
stack.switchTo('photoreal');
|
||||
assert.notEqual(
|
||||
layer.getUIState().street.armed,
|
||||
null,
|
||||
'a notify on the same map keeps it',
|
||||
);
|
||||
stack.switchTo('osm');
|
||||
assert.equal(
|
||||
layer.getUIState().street.armed,
|
||||
null,
|
||||
'leaving Google 3D clears it',
|
||||
);
|
||||
// Arming notifies, so a panel can show the state.
|
||||
let notified = 0;
|
||||
const unsubscribe = layer.subscribe(() => notified++);
|
||||
stack.switchTo('photoreal');
|
||||
await settle();
|
||||
const before = notified;
|
||||
layer.armNearest({ lat: 1, lon: 2 }, { providerIds: ['google'] });
|
||||
await settle();
|
||||
assert.ok(notified > before, 'subscribers hear about the armed lookup');
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test('a lookup armed with no point opens under the middle of the screen on the press', async (t) => {
|
||||
const { createStreetLevelLayer: create } = await import('./index.js');
|
||||
const scenePick = await import('../../data/scenePick.js');
|
||||
const lookups = [];
|
||||
const provider = fakeProvider({
|
||||
nearestImage: async (point, options) => {
|
||||
lookups.push({ ...point, radiusM: options?.radiusM ?? null });
|
||||
return null;
|
||||
},
|
||||
});
|
||||
const saved = globalThis.document;
|
||||
const drawing = new Proxy({}, { get: () => () => ({ addColorStop() {} }) });
|
||||
globalThis.document = Object.assign(new EventTarget(), {
|
||||
createElement: () => ({ getContext: () => drawing }),
|
||||
});
|
||||
const viewer = fakeViewer();
|
||||
const centre = Cesium.Cartesian3.fromDegrees(-121.4937, 38.5799, 0);
|
||||
Object.assign(viewer.scene, {
|
||||
pickPositionSupported: true,
|
||||
pickPosition: (at) => (at.x === 500 && at.y === 300 ? centre : undefined),
|
||||
});
|
||||
viewer.scene.canvas.clientWidth = 1000;
|
||||
viewer.scene.canvas.clientHeight = 600;
|
||||
// Registered before the layer exists, so a throwing create() still
|
||||
// restores the document; destroy() runs first, while the stub is in place.
|
||||
let layer = null;
|
||||
t.after(() => {
|
||||
layer?.destroy();
|
||||
globalThis.document = saved;
|
||||
});
|
||||
layer = create({ providers: [provider], services: { scenePick } });
|
||||
layer.init(viewer);
|
||||
layer.enable(viewer);
|
||||
layer.armNearest(null, { providerIds: [provider.id], radiusM: 250 });
|
||||
assert.equal(
|
||||
layer.getUIState().street.armed.point,
|
||||
null,
|
||||
'no point stored, not 0,0',
|
||||
);
|
||||
await layer.openNearest(undefined, { aim: 'screen-centre' });
|
||||
assert.equal(lookups.length, 1);
|
||||
assert.ok(
|
||||
Math.abs(lookups[0].lat - 38.5799) < 1e-9,
|
||||
'the screen centre, not Null Island',
|
||||
);
|
||||
assert.ok(Math.abs(lookups[0].lon - -121.4937) < 1e-9);
|
||||
assert.equal(lookups[0].radiusM, 250, 'with the armed radius');
|
||||
});
|
||||
|
||||
test('the action over the real layer: a billed link arms without a lookup, and one press makes exactly one at the point', async (t) => {
|
||||
const { layer, fake, viewer } = await withStreetView(t);
|
||||
// The runner wires pointer tracking to the clock and camera.
|
||||
viewer.clock ??= { onTick: { addEventListener: () => () => {} } };
|
||||
viewer.camera.moveEnd ??= { addEventListener() {} };
|
||||
const dataManager = {
|
||||
layers: new Map([['street-level', { module: layer }]]),
|
||||
isEnabled: () => true,
|
||||
getLayerParams: () => layer.getParams(),
|
||||
setLayerParams: (_id, params) => {
|
||||
layer.setParams(params);
|
||||
return true;
|
||||
},
|
||||
getAll: () => [{ id: 'street-level', name: 'Street Level', enabled: true }],
|
||||
};
|
||||
const styleManager = {
|
||||
mapStackController: { getActiveId: () => 'photoreal' },
|
||||
setMapStack: async () => ({ ok: true, activeStack: 'photoreal' }),
|
||||
};
|
||||
const runner = createGevActionRunner({ viewer, styleManager, dataManager });
|
||||
const before = fake.lookups.length;
|
||||
const armed = await runner('show_street_level', {
|
||||
latitude: 38.57986,
|
||||
longitude: -121.49372,
|
||||
provider: 'google',
|
||||
fly: false,
|
||||
autoOpen: false,
|
||||
});
|
||||
assert.equal(armed.ok, true, armed.error);
|
||||
assert.equal(armed.armed, true);
|
||||
assert.equal(armed.providerName, 'Google Street View');
|
||||
await settle();
|
||||
assert.equal(fake.lookups.length, before, 'arming made no Google request');
|
||||
assert.deepEqual(
|
||||
layer
|
||||
.getUIState()
|
||||
.providers.filter((p) => p.on)
|
||||
.map((p) => p.id),
|
||||
['google'],
|
||||
);
|
||||
assert.equal(layer.getUIState().street.open, false);
|
||||
// The OPEN button.
|
||||
assert.equal(
|
||||
await layer.openNearest(undefined, {
|
||||
providerIds: ['google'],
|
||||
frame: false,
|
||||
aim: 'screen-centre',
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(fake.lookups.length, before + 1, 'one request for the press');
|
||||
assert.deepEqual(fake.lookups.at(-1).location, {
|
||||
lat: 38.57986,
|
||||
lng: -121.49372,
|
||||
});
|
||||
assert.equal(fake.lookups.at(-1).radius, 250);
|
||||
assert.equal(layer.getUIState().street.imageId, 'pano-a');
|
||||
// The same call without the gate opens at once, with one request.
|
||||
layer.closeViewer();
|
||||
const opened = await runner('show_street_level', {
|
||||
latitude: 38.57986,
|
||||
longitude: -121.49372,
|
||||
provider: 'google',
|
||||
fly: false,
|
||||
});
|
||||
assert.equal(opened.ok, true, opened.error);
|
||||
assert.equal(opened.imageId, 'pano-a');
|
||||
assert.equal(fake.lookups.length, before + 2);
|
||||
});
|
||||
|
||||
test('openNearest keeps honouring the caller after the lookup: an abort while the viewer loads opens nothing', async (t) => {
|
||||
let releaseMount = null;
|
||||
const provider = fakeProvider({ nearestImage: async () => 'img-1' });
|
||||
const create = provider.create;
|
||||
provider.create = (context) => {
|
||||
const instance = create(context);
|
||||
const mount = instance.viewer.mount;
|
||||
instance.viewer.mount = async (...args) => {
|
||||
await new Promise((resolve) => {
|
||||
releaseMount = resolve;
|
||||
});
|
||||
return mount(...args);
|
||||
};
|
||||
return instance;
|
||||
};
|
||||
const { layer } = await enabledLayer(t, [provider]);
|
||||
const { fakeHost } =
|
||||
await import('../../testSupport/googleStreetViewFakes.mjs');
|
||||
layer.attachViewerHost(fakeHost());
|
||||
const controller = new AbortController();
|
||||
const pending = layer.openNearest(
|
||||
{ lat: 1, lon: 2 },
|
||||
{ frame: false, signal: controller.signal },
|
||||
);
|
||||
for (let i = 0; i < 20 && !releaseMount; i++) await settle();
|
||||
assert.ok(releaseMount, 'the lookup answered and the viewer is mounting');
|
||||
controller.abort();
|
||||
releaseMount();
|
||||
assert.equal(await pending, false);
|
||||
assert.deepEqual(provider.calls.open, [], 'the photo was never opened');
|
||||
assert.equal(layer.getUIState().street.open, false);
|
||||
assert.equal(layer.getUIState().street.loading, false);
|
||||
});
|
||||
|
||||
for (const rejectsOnAbort of [true, false]) {
|
||||
test(`cancelling a lookup over an open photo clears its spinner (provider rejects: ${rejectsOnAbort})`, async (t) => {
|
||||
const answer = deferred();
|
||||
const provider = fakeProvider({
|
||||
nearestImage: (_point, { signal }) => {
|
||||
if (rejectsOnAbort)
|
||||
signal.addEventListener('abort', () => answer.reject(signal.reason), {
|
||||
once: true,
|
||||
});
|
||||
return answer.promise;
|
||||
},
|
||||
});
|
||||
const { layer } = await enabledLayer(t, [provider]);
|
||||
const { fakeHost } =
|
||||
await import('../../testSupport/googleStreetViewFakes.mjs');
|
||||
layer.attachViewerHost(fakeHost());
|
||||
assert.equal(
|
||||
await layer.openImage('mapillary', 'existing', { frame: false }),
|
||||
true,
|
||||
);
|
||||
const controller = new AbortController();
|
||||
const pending = layer.openNearest(
|
||||
{ lat: 1, lon: 2 },
|
||||
{ frame: false, signal: controller.signal },
|
||||
);
|
||||
assert.equal(layer.getUIState().street.loading, true);
|
||||
controller.abort();
|
||||
if (!rejectsOnAbort) answer.resolve('late-image');
|
||||
assert.equal(await pending, false);
|
||||
const street = layer.getUIState().street;
|
||||
assert.equal(
|
||||
street.loading,
|
||||
false,
|
||||
'the cancelled lookup owns and clears the spinner',
|
||||
);
|
||||
assert.equal(street.open, true, 'the existing photo remains open');
|
||||
assert.equal(street.error, null);
|
||||
assert.deepEqual(
|
||||
provider.calls.open,
|
||||
['existing'],
|
||||
'no replacement photo opens',
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
for (const rejectsOnAbort of [true, false]) {
|
||||
test(`retired lookups release the caller listener (provider rejects: ${rejectsOnAbort})`, async (t) => {
|
||||
let answer;
|
||||
const provider = fakeProvider({
|
||||
nearestImage: (_point, { signal }) => {
|
||||
answer = deferred();
|
||||
if (rejectsOnAbort)
|
||||
signal.addEventListener('abort', () => answer.reject(signal.reason), {
|
||||
once: true,
|
||||
});
|
||||
return answer.promise;
|
||||
},
|
||||
});
|
||||
const { layer } = await enabledLayer(t, [provider]);
|
||||
const lifetime = new AbortController();
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const pending = layer.openNearest(
|
||||
{ lat: 1, lon: 2 },
|
||||
{ frame: false, signal: lifetime.signal },
|
||||
);
|
||||
assert.equal(getEventListeners(lifetime.signal, 'abort').length, 1);
|
||||
layer.closeViewer();
|
||||
if (!rejectsOnAbort) answer.resolve('late-image');
|
||||
assert.equal(await pending, false);
|
||||
assert.equal(
|
||||
getEventListeners(lifetime.signal, 'abort').length,
|
||||
0,
|
||||
'closing the lookup releases its listener on the application lifetime',
|
||||
);
|
||||
}
|
||||
assert.equal(lifetime.signal.aborted, false);
|
||||
});
|
||||
}
|
||||
|
||||
test('an aborted older lookup leaves its replacement’s spinner alone', async (t) => {
|
||||
const answers = [];
|
||||
const provider = fakeProvider({
|
||||
nearestImage: (_point, { signal } = {}) =>
|
||||
new Promise((resolve, reject) => {
|
||||
answers.push(resolve);
|
||||
signal?.addEventListener('abort', () =>
|
||||
reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
|
||||
);
|
||||
}),
|
||||
});
|
||||
const { layer } = await enabledLayer(t, [provider]);
|
||||
const { fakeHost } =
|
||||
await import('../../testSupport/googleStreetViewFakes.mjs');
|
||||
layer.attachViewerHost(fakeHost());
|
||||
const older = new AbortController();
|
||||
const first = layer.openNearest(
|
||||
{ lat: 1, lon: 2 },
|
||||
{ frame: false, signal: older.signal },
|
||||
);
|
||||
await settle();
|
||||
// A newer request replaces it, and its caller withdraws the old one too.
|
||||
const second = layer.openNearest({ lat: 3, lon: 4 }, { frame: false });
|
||||
older.abort();
|
||||
assert.equal(await first, false);
|
||||
assert.equal(
|
||||
layer.getUIState().street.loading,
|
||||
true,
|
||||
'the newer lookup is still loading',
|
||||
);
|
||||
answers.at(-1)(null);
|
||||
assert.equal(await second, false);
|
||||
assert.equal(layer.getUIState().street.loading, false);
|
||||
assert.match(
|
||||
layer.getUIState().street.error,
|
||||
/No street-level imagery/,
|
||||
'the newer lookup reports its own result',
|
||||
);
|
||||
});
|
||||
|
||||
test('show_street_level opens a KartaView photo, and a plain link opens it at once since it is not billed', async (t) => {
|
||||
const mapillary = fakeProvider();
|
||||
let nearest = 'kv-1';
|
||||
const kartaview = fakeProvider({
|
||||
id: 'kartaview',
|
||||
pickPrefix: 'kv:',
|
||||
nearestImage: async () => nearest,
|
||||
});
|
||||
kartaview.name = 'KartaView';
|
||||
kartaview.label = 'KARTAVIEW';
|
||||
kartaview.defaultOn = false;
|
||||
// As the real provider: 360° / flat and SINCE (the setFilter log stays in
|
||||
// the fake's closure).
|
||||
kartaview.filters = Object.freeze(['pano', 'since']);
|
||||
const { layer, viewer } = await enabledLayer(t, [mapillary, kartaview]);
|
||||
const { fakeHost } =
|
||||
await import('../../testSupport/googleStreetViewFakes.mjs');
|
||||
layer.attachViewerHost(fakeHost());
|
||||
viewer.clock ??= { onTick: { addEventListener: () => () => {} } };
|
||||
viewer.camera.moveEnd ??= { addEventListener() {} };
|
||||
const dataManager = {
|
||||
layers: new Map([['street-level', { module: layer }]]),
|
||||
isEnabled: () => true,
|
||||
getLayerParams: () => layer.getParams(),
|
||||
setLayerParams: (_id, params) => {
|
||||
layer.setParams(params);
|
||||
return true;
|
||||
},
|
||||
getAll: () => [{ id: 'street-level', name: 'Street Level', enabled: true }],
|
||||
};
|
||||
const styleManager = {
|
||||
mapStackController: { getActiveId: () => 'osm' },
|
||||
setMapStack: async () => ({ ok: false, error: 'no map switch expected' }),
|
||||
};
|
||||
const runner = createGevActionRunner({ viewer, styleManager, dataManager });
|
||||
// The way a plain sl=kartaview link calls it: autoOpen false.
|
||||
const result = await runner('show_street_level', {
|
||||
latitude: 52.52,
|
||||
longitude: 13.405,
|
||||
provider: 'kartaview',
|
||||
fly: false,
|
||||
autoOpen: false,
|
||||
});
|
||||
assert.equal(result.ok, true, result.error);
|
||||
assert.equal(result.armed, undefined, 'not armed: KartaView bills nothing');
|
||||
assert.equal(result.provider, 'kartaview');
|
||||
assert.equal(result.providerName, 'KartaView');
|
||||
assert.deepEqual(
|
||||
layer
|
||||
.getUIState()
|
||||
.providers.filter((p) => p.on)
|
||||
.map((p) => p.id),
|
||||
['kartaview'],
|
||||
);
|
||||
assert.deepEqual(kartaview.calls.open, ['kv-1']);
|
||||
assert.equal(layer.providerStatus('kartaview').billed, false);
|
||||
assert.equal(layer.requiredMapStack('kartaview'), null);
|
||||
|
||||
// With 360° only on, an empty search names the filter, not just "no imagery".
|
||||
layer.closeViewer?.();
|
||||
layer.setParams({ pano: 'pano' });
|
||||
nearest = null;
|
||||
const empty = await runner('show_street_level', {
|
||||
latitude: 52.52,
|
||||
longitude: 13.405,
|
||||
provider: 'kartaview',
|
||||
fly: false,
|
||||
});
|
||||
assert.deepEqual([empty.ok, empty.stage], [false, 'imagery']);
|
||||
assert.equal(empty.filter?.pano, 'pano');
|
||||
assert.match(empty.error, /with the 360° filter on$/);
|
||||
layer.setParams({ pano: 'all' });
|
||||
const plain = await runner('show_street_level', {
|
||||
latitude: 52.52,
|
||||
longitude: 13.405,
|
||||
provider: 'kartaview',
|
||||
fly: false,
|
||||
});
|
||||
assert.equal(plain.ok, false);
|
||||
assert.equal(plain.filter, undefined, 'no filter, no hint');
|
||||
assert.doesNotMatch(plain.error, /filter/);
|
||||
});
|
||||
|
||||
test('show_street_level switches from KartaView to Panoramax and opens its photo at once, unbilled', async (t) => {
|
||||
const mapillary = fakeProvider();
|
||||
const kartaview = fakeProvider({ id: 'kartaview', pickPrefix: 'kv:' });
|
||||
kartaview.name = 'KartaView';
|
||||
kartaview.defaultOn = false;
|
||||
const panoramax = fakeProvider({
|
||||
id: 'panoramax',
|
||||
pickPrefix: 'px:',
|
||||
nearestImage: async () => 'px-1',
|
||||
});
|
||||
panoramax.name = 'Panoramax';
|
||||
panoramax.label = 'PANORAMAX';
|
||||
panoramax.defaultOn = false;
|
||||
const { layer, viewer } = await enabledLayer(t, [
|
||||
mapillary,
|
||||
kartaview,
|
||||
panoramax,
|
||||
]);
|
||||
const { fakeHost } =
|
||||
await import('../../testSupport/googleStreetViewFakes.mjs');
|
||||
layer.attachViewerHost(fakeHost());
|
||||
viewer.clock ??= { onTick: { addEventListener: () => () => {} } };
|
||||
viewer.camera.moveEnd ??= { addEventListener() {} };
|
||||
layer.setParams({ mapillary: false, kartaview: true, panoramax: false });
|
||||
const dataManager = {
|
||||
layers: new Map([['street-level', { module: layer }]]),
|
||||
isEnabled: () => true,
|
||||
getLayerParams: () => layer.getParams(),
|
||||
setLayerParams: (_id, params) => {
|
||||
layer.setParams(params);
|
||||
return true;
|
||||
},
|
||||
getAll: () => [{ id: 'street-level', name: 'Street Level', enabled: true }],
|
||||
};
|
||||
const styleManager = {
|
||||
mapStackController: { getActiveId: () => 'osm' },
|
||||
setMapStack: async () => ({ ok: false, error: 'no map switch expected' }),
|
||||
};
|
||||
const runner = createGevActionRunner({ viewer, styleManager, dataManager });
|
||||
// The way a plain sl=panoramax link calls it: autoOpen false.
|
||||
const result = await runner('show_street_level', {
|
||||
latitude: 48.8874,
|
||||
longitude: 2.3495,
|
||||
provider: 'panoramax',
|
||||
fly: false,
|
||||
autoOpen: false,
|
||||
});
|
||||
assert.equal(result.ok, true, result.error);
|
||||
assert.equal(result.armed, undefined, 'not armed: Panoramax bills nothing');
|
||||
assert.equal(result.providerName, 'Panoramax');
|
||||
assert.deepEqual(
|
||||
layer
|
||||
.getUIState()
|
||||
.providers.filter((p) => p.on)
|
||||
.map((p) => p.id),
|
||||
['panoramax'],
|
||||
'KartaView switched off',
|
||||
);
|
||||
assert.deepEqual(panoramax.calls.open, ['px-1']);
|
||||
assert.deepEqual(kartaview.calls.open, [], 'nothing asked of KartaView');
|
||||
assert.equal(layer.providerStatus('panoramax').billed, false);
|
||||
assert.equal(layer.requiredMapStack('panoramax'), null);
|
||||
});
|
||||
|
||||
test('the panel says why a lit Street View draws nothing off Google 3D', async (t) => {
|
||||
const { presentStreetLevelPanel } =
|
||||
await import('../../ui/streetLevelPresentation.js');
|
||||
@@ -1173,6 +1959,88 @@ test('the panel says why a lit Street View draws nothing off Google 3D', async (
|
||||
assert.match(view.meta, /Google Street View needs the Google 3D map/);
|
||||
});
|
||||
|
||||
test('OPEN aimed at the sky after a link armed opens nothing: never the far link point', async (t) => {
|
||||
const scenePick = await import('../../data/scenePick.js');
|
||||
const lookups = [];
|
||||
const provider = fakeProvider({
|
||||
nearestImage: async (point) => {
|
||||
lookups.push(point);
|
||||
return null;
|
||||
},
|
||||
});
|
||||
const { layer } = await enabledLayer(t, [provider], {
|
||||
services: { scenePick },
|
||||
setup: (viewer) => {
|
||||
// Every pick misses the ground: the screen centre is sky.
|
||||
Object.assign(viewer.scene, {
|
||||
pickPositionSupported: true,
|
||||
pickPosition: () => undefined,
|
||||
});
|
||||
viewer.globe = { pick: () => undefined };
|
||||
viewer.scene.canvas.clientWidth = 1000;
|
||||
viewer.scene.canvas.clientHeight = 600;
|
||||
},
|
||||
});
|
||||
layer.armNearest({ lat: 48.8584, lon: 2.2945 }, { radiusM: 250 });
|
||||
assert.equal(
|
||||
await layer.openNearest(undefined, { aim: 'screen-centre' }),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(lookups, [], 'no paid Paris lookup from another city’s sky');
|
||||
const street = layer.getUIState().street;
|
||||
assert.equal(street.nearestOutcome, 'sky');
|
||||
assert.match(street.error, /Aim the middle of the view/);
|
||||
});
|
||||
|
||||
test('a request of its own (armed: false) neither uses nor drops the link’s armed point', async (t) => {
|
||||
const scenePick = await import('../../data/scenePick.js');
|
||||
const lookups = [];
|
||||
const provider = fakeProvider({
|
||||
nearestImage: async (point, options) => {
|
||||
lookups.push({ point, radiusM: options?.radiusM ?? null });
|
||||
return null;
|
||||
},
|
||||
});
|
||||
const centre = Cesium.Cartesian3.fromDegrees(-121.4937, 38.5799, 0);
|
||||
const { layer } = await enabledLayer(t, [provider], {
|
||||
services: { scenePick },
|
||||
setup: (viewer) => {
|
||||
Object.assign(viewer.scene, {
|
||||
pickPositionSupported: true,
|
||||
pickPosition: (at) =>
|
||||
at.x === 500 && at.y === 300 ? centre : undefined,
|
||||
});
|
||||
viewer.scene.canvas.clientWidth = 1000;
|
||||
viewer.scene.canvas.clientHeight = 600;
|
||||
},
|
||||
});
|
||||
// About 120 m away: an OPEN press would take the link's spot.
|
||||
layer.armNearest({ lat: 38.5808, lon: -121.494 }, { radiusM: 250 });
|
||||
await layer.openNearest(undefined, { aim: 'screen-centre', armed: false });
|
||||
const asked = lookups.at(-1);
|
||||
assert.ok(Math.abs(asked.point.lat - 38.5799) < 1e-9, 'the screen centre');
|
||||
assert.equal(asked.radiusM, null, 'its own radius');
|
||||
assert.equal(layer.getUIState().street.nearestOutcome, 'empty');
|
||||
assert.deepEqual(
|
||||
layer.getUIState().street.armed?.point,
|
||||
{ lat: 38.5808, lon: -121.494 },
|
||||
'still armed for the OPEN press',
|
||||
);
|
||||
});
|
||||
|
||||
test('a failing source is not reported as missing imagery', async (t) => {
|
||||
const provider = fakeProvider({
|
||||
nearestImage: async () => {
|
||||
throw new Error('Mapillary graph HTTP 500');
|
||||
},
|
||||
});
|
||||
const { layer } = await enabledLayer(t, [provider]);
|
||||
assert.equal(await layer.openNearest({ lat: 1, lon: 2 }), false);
|
||||
const street = layer.getUIState().street;
|
||||
assert.equal(street.nearestOutcome, null);
|
||||
assert.equal(street.error, 'Mapillary graph HTTP 500');
|
||||
});
|
||||
|
||||
/** Mapillary (keyless unless `mapillary` says otherwise) plus KartaView. */
|
||||
function keylessLayer(t, mapillary = { hasToken: () => false }) {
|
||||
const layer = createStreetLevelLayer({
|
||||
@@ -1228,3 +2096,83 @@ test('filter-only updates keep the lit source, even a chosen keyless Mapillary',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('a replacing lookup keeps the viewer open while it looks, so EXPAND stays with the new photo', async (t) => {
|
||||
const answers = ['img-1', 'img-2'];
|
||||
const provider = posingProvider({
|
||||
nearestImage: async () => answers.shift(),
|
||||
});
|
||||
const { layer } = await enabledLayer(t, [provider]);
|
||||
layer.attachViewerHost({});
|
||||
assert.equal(await layer.openNearest({ lat: 1, lon: 2 }), true);
|
||||
const seen = [];
|
||||
const unsubscribe = layer.subscribe(() =>
|
||||
seen.push(layer.getUIState().street.open),
|
||||
);
|
||||
t.after(unsubscribe);
|
||||
assert.equal(
|
||||
await layer.openNearest({ lat: 3, lon: 4 }, { replace: true }),
|
||||
true,
|
||||
);
|
||||
assert.ok(seen.length > 0);
|
||||
assert.ok(!seen.includes(false), 'never published closed on the way');
|
||||
assert.deepEqual(provider.calls.open, ['img-1', 'img-2']);
|
||||
});
|
||||
|
||||
test('a replacing lookup that finds nothing closes the old photo and keeps its own message', async (t) => {
|
||||
const answers = ['img-1', null];
|
||||
const provider = posingProvider({
|
||||
nearestImage: async () => answers.shift(),
|
||||
});
|
||||
const { layer } = await enabledLayer(t, [provider]);
|
||||
layer.attachViewerHost({});
|
||||
await layer.openNearest({ lat: 1, lon: 2 });
|
||||
assert.equal(
|
||||
await layer.openNearest({ lat: 3, lon: 4 }, { replace: true }),
|
||||
false,
|
||||
);
|
||||
const street = layer.getUIState().street;
|
||||
assert.equal(street.open, false, 'no photo of another place');
|
||||
assert.equal(street.nearestOutcome, 'empty');
|
||||
assert.match(street.error, /No street-level imagery within 50 m/);
|
||||
});
|
||||
|
||||
test('a found photo the viewer cannot load keeps its error on the open viewer', async (t) => {
|
||||
const provider = posingProvider({ nearestImage: async () => 'img-1' });
|
||||
const create = provider.create;
|
||||
provider.create = (context) => {
|
||||
const instance = create(context);
|
||||
instance.viewer.open = async () => {
|
||||
throw new Error('Image could not be opened');
|
||||
};
|
||||
return instance;
|
||||
};
|
||||
const { layer } = await enabledLayer(t, [provider]);
|
||||
layer.attachViewerHost({});
|
||||
assert.equal(
|
||||
await layer.openNearest({ lat: 1, lon: 2 }, { replace: true }),
|
||||
false,
|
||||
);
|
||||
const street = layer.getUIState().street;
|
||||
assert.equal(street.open, true);
|
||||
assert.equal(street.error, 'Image could not be opened');
|
||||
});
|
||||
|
||||
test('proceed() is asked after the lookup: false loads nothing and clears the spinner', async (t) => {
|
||||
const provider = posingProvider({ nearestImage: async () => 'img-1' });
|
||||
const { layer } = await enabledLayer(t, [provider]);
|
||||
layer.attachViewerHost({});
|
||||
let asked = 0;
|
||||
const opened = await layer.openNearest(
|
||||
{ lat: 1, lon: 2 },
|
||||
{ proceed: () => (asked++, false) },
|
||||
);
|
||||
assert.equal(opened, false);
|
||||
assert.equal(asked, 1);
|
||||
assert.deepEqual(provider.calls.open, [], 'the viewer never loads it');
|
||||
assert.equal(layer.getUIState().street.loading, false);
|
||||
assert.equal(
|
||||
await layer.openNearest({ lat: 1, lon: 2 }, { proceed: () => true }),
|
||||
true,
|
||||
);
|
||||
});
|
||||
@@ -43,6 +43,14 @@ export const FILTER_DEFAULT = Object.freeze({ pano: 'all', sinceDays: 0 });
|
||||
/** Nearest-image search radius in metres. */
|
||||
export const NEAREST_RADIUS_M = 50;
|
||||
|
||||
/**
|
||||
* Widest nearest-image radius a caller may ask for, in metres. A geocoded
|
||||
* landmark sits at its centroid, often further than 50 m from the nearest
|
||||
* street; providers that can search wider (Google) honour it, the rest keep
|
||||
* their own cap.
|
||||
*/
|
||||
export const NEAREST_RADIUS_MAX_M = 250;
|
||||
|
||||
/** The Google 3D map stack: Street View may be shown only on it. */
|
||||
export const GOOGLE_3D_MAP_STACK_ID = 'photoreal';
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
GROUND_CLICK_HINT,
|
||||
KEY_REJECTED_MESSAGE,
|
||||
NEAREST_RADIUS_M,
|
||||
NEAREST_RADIUS_MAX_M,
|
||||
NEAREST_TIMEOUT_MS,
|
||||
NO_ANSWER_MESSAGE,
|
||||
PICK_PREFIX,
|
||||
@@ -67,6 +68,7 @@ export function createGoogleProvider({
|
||||
requiresMapStack: GOOGLE_3D_MAP_STACK_ID,
|
||||
// Every panorama is billed to the Maps key.
|
||||
defaultOn: false,
|
||||
billedPerImage: true,
|
||||
// All 360°, and no coverage for a date filter to thin.
|
||||
filters: [],
|
||||
marker: Object.freeze({ kind: 'view-cone', color: COLORS.coverage }),
|
||||
@@ -136,8 +138,12 @@ export function createGoogleProvider({
|
||||
* Nearest Google-collected outdoor panorama, or null. The imagery
|
||||
* filters do not apply (see `filters`).
|
||||
*/
|
||||
async nearestImage({ lat, lon }, { signal } = {}) {
|
||||
async nearestImage({ lat, lon }, { signal, radiusM } = {}) {
|
||||
if (loader.authFailed()) throw new Error(KEY_REJECTED_MESSAGE);
|
||||
// Wider than the shared default only on request, never past the cap.
|
||||
const radius = Number.isFinite(radiusM)
|
||||
? Math.min(NEAREST_RADIUS_MAX_M, Math.max(1, radiusM))
|
||||
: NEAREST_RADIUS_M;
|
||||
signal?.throwIfAborted();
|
||||
// Set once the caller has its answer (aborted, timed out, refused):
|
||||
// a lookup still waiting on Google's script then asks nothing.
|
||||
@@ -150,7 +156,7 @@ export function createGoogleProvider({
|
||||
try {
|
||||
const { data } = await service.getPanorama({
|
||||
location: { lat, lng: lon },
|
||||
radius: NEAREST_RADIUS_M,
|
||||
radius,
|
||||
// Both: Google's own imagery, outdoors (sources intersect).
|
||||
sources: [GOOGLE, OUTDOOR],
|
||||
preference: lib.StreetViewPreference.NEAREST,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { COLORS as SHARED_COLORS, PROVIDER_COLORS } from '../../policy.js';
|
||||
import { msg } from '../../../../i18n/index.js';
|
||||
|
||||
export { NEAREST_RADIUS_M } from '../../policy.js';
|
||||
export { NEAREST_RADIUS_M, NEAREST_RADIUS_MAX_M } from '../../policy.js';
|
||||
|
||||
export const GOOGLE_PROVIDER_ID = 'google';
|
||||
export const GOOGLE_NAME = msg('Google Street View');
|
||||
|
||||
@@ -291,3 +291,13 @@ test('the panorama a lookup found is dated without a second lookup', async () =>
|
||||
'no getPanorama({pano}) for a panorama the lookup already described',
|
||||
);
|
||||
});
|
||||
|
||||
test('a wider lookup radius is honoured up to the cap', async () => {
|
||||
const { instance, fake } = setup();
|
||||
await instance.nearestImage({ lat: 38.58, lon: -121.49 }, { radiusM: 250 });
|
||||
assert.equal(fake.lookups.at(-1).radius, 250);
|
||||
await instance.nearestImage({ lat: 38.58, lon: -121.49 }, { radiusM: 9999 });
|
||||
assert.equal(fake.lookups.at(-1).radius, 250);
|
||||
await instance.nearestImage({ lat: 38.58, lon: -121.49 }, { radiusM: NaN });
|
||||
assert.equal(fake.lookups.at(-1).radius, 50);
|
||||
});
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
} from '../../lineCoverage.js';
|
||||
import { createSequenceCones, thinImages } from '../../sequenceCones.js';
|
||||
import { coverageZoomForHeight } from '../../tileMath.js';
|
||||
import { passesImageryFilter } from '../../filter.js';
|
||||
import { metresBetween } from '../../view.js';
|
||||
import { decodeCoverageTile } from './decode.js';
|
||||
import { createMapillaryViewer } from './viewer.js';
|
||||
import {
|
||||
@@ -195,6 +197,35 @@ export function createMapillaryProvider({ source, photoViewer = null }) {
|
||||
error: state.sequence.error,
|
||||
}),
|
||||
|
||||
/**
|
||||
* The nearest image that passes the imagery filter, or null: what
|
||||
* show_street_level and sl= links open (clicks open a line, then a
|
||||
* cone). The core aborts `signal` once a newer request overtakes it.
|
||||
*/
|
||||
async nearestImage({ lat, lon }, { signal } = {}) {
|
||||
const images = await source.nearestImages({ lat, lon }, { signal });
|
||||
// The API returns the images in the radius in no particular order.
|
||||
const metres = (record) => {
|
||||
const [lon2, lat2] = (record.computed_geometry || record.geometry)
|
||||
?.coordinates || [NaN, NaN];
|
||||
const d = metresBetween({ lon, lat }, { lon: lon2, lat: lat2 });
|
||||
return Number.isFinite(d) ? d : Infinity;
|
||||
};
|
||||
const filter = context.getFilter();
|
||||
const hit = [...images]
|
||||
.sort((a, b) => metres(a) - metres(b))
|
||||
.find((record) =>
|
||||
passesImageryFilter(
|
||||
{
|
||||
isPano: record.is_pano === true,
|
||||
capturedAt: Number(record.captured_at) || 0,
|
||||
},
|
||||
filter,
|
||||
),
|
||||
);
|
||||
return hit ? String(hit.id) : null;
|
||||
},
|
||||
|
||||
viewer:
|
||||
photoViewer ||
|
||||
createMapillaryViewer({ source, render: context.services?.render }),
|
||||
|
||||
@@ -16,6 +16,7 @@ export const MAPILLARY_SOURCE_METHODS = Object.freeze([
|
||||
'getStatus',
|
||||
'getTile',
|
||||
'getSequenceImages',
|
||||
'nearestImages',
|
||||
]);
|
||||
|
||||
/** Stable id prefixes for picked primitives; every one starts with `mly:`. */
|
||||
@@ -72,3 +73,18 @@ export function mapillaryImageUrl(imageId) {
|
||||
/** Fields requested for a sequence's images. */
|
||||
export const SEQUENCE_IMAGE_FIELDS =
|
||||
'id,captured_at,compass_angle,geometry,is_pano';
|
||||
|
||||
/**
|
||||
* Images asked for in a nearest-image search: the API cuts at the limit
|
||||
* before any order, so this is its most; the distance sort and the imagery
|
||||
* filter choose among the photos this one request returns.
|
||||
*/
|
||||
export const NEAREST_LIMIT = 100;
|
||||
/**
|
||||
* A nearest-image search not answered in full (body included) by then is
|
||||
* given up: a link or posted view, and every view queued behind it, waits.
|
||||
*/
|
||||
export const NEAREST_TIMEOUT_MS = 12_000;
|
||||
/** Fields a nearest-image search needs: where each is, and the filter's. */
|
||||
export const NEAREST_IMAGE_FIELDS =
|
||||
'id,captured_at,geometry,computed_geometry,is_pano';
|
||||
@@ -158,3 +158,41 @@ test('a status the server never answers falls back to the bundled token once the
|
||||
assert.deepEqual(await status, { configured: false });
|
||||
assert.equal(instance.coverageStats().keyRequired, true);
|
||||
});
|
||||
|
||||
/** A graph image record at a point. */
|
||||
const imageAt = (id, lon, lat, extra = {}) => ({
|
||||
id,
|
||||
is_pano: false,
|
||||
captured_at: 10,
|
||||
geometry: { type: 'Point', coordinates: [lon, lat] },
|
||||
...extra,
|
||||
});
|
||||
|
||||
test('nearestImage opens the closest image that passes the filter, not the first the API returned', async () => {
|
||||
const requests = [];
|
||||
const answer = [
|
||||
imageAt('far', 2.0004, 1), // ~45 m east
|
||||
imageAt('near-pano', 2.00002, 1, { is_pano: true }), // ~2 m, a panorama
|
||||
imageAt('near', 2.00005, 1), // ~5 m east
|
||||
imageAt('mid', 2, 1.0002), // ~22 m north
|
||||
];
|
||||
const source = fakeMapillarySource({
|
||||
nearestImages: async (query, options) => {
|
||||
requests.push({ query, options });
|
||||
return answer;
|
||||
},
|
||||
});
|
||||
const { signal } = new AbortController();
|
||||
const flat = createMapillaryProvider({ source }).create(
|
||||
fakeContext({ pano: 'flat', sinceMs: null }),
|
||||
);
|
||||
assert.equal(await flat.nearestImage({ lat: 1, lon: 2 }, { signal }), 'near');
|
||||
assert.equal(requests[0].options.signal, signal, 'the core can abort it');
|
||||
assert.deepEqual(requests[0].query, { lat: 1, lon: 2 });
|
||||
const any = createMapillaryProvider({ source }).create(fakeContext());
|
||||
assert.equal(await any.nearestImage({ lat: 1, lon: 2 }), 'near-pano');
|
||||
const tooOld = createMapillaryProvider({ source }).create(
|
||||
fakeContext({ pano: 'all', sinceMs: 100 }),
|
||||
);
|
||||
assert.equal(await tooOld.nearestImage({ lat: 1, lon: 2 }), null);
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import '../../../../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { registerHooks } from 'node:module';
|
||||
import { createStreetLevelLayer } from '../../index.js';
|
||||
import { fakeStreetLevelProvider, fakeCesiumViewer } from '../../../../testSupport/streetLevelFakes.mjs';
|
||||
import { createMapillaryViewer } from './viewer.js';
|
||||
import { showStreetLevel } from '../../../../voice/gevActions.js';
|
||||
|
||||
// Library boundary fixture: moveTo changes the image without stopping PLAY,
|
||||
// matching installed MapillaryJS Viewer.moveTo / Navigator.moveTo$.
|
||||
const fakeLibrary = `export class Viewer {
|
||||
constructor() { globalThis.__replacePlayViewer = this; this.playing = false; this.id = null; this.stops = 0; }
|
||||
on() {} remove() {} resize() {} setRenderMode() {}
|
||||
getComponent() { return { play: () => {this.playing = true;}, stop: () => {this.playing = false; this.stops++;} }; }
|
||||
async moveTo(id) { this.id = id; return { id, sequenceId: 'fixture-sequence', cameraType: 'perspective' }; }
|
||||
async getPosition() { return { lng: 2, lat: 48 }; }
|
||||
async getPointOfView() { return { bearing: 0 }; }
|
||||
}
|
||||
export class GraphDataProvider {}
|
||||
export const RenderMode = { Fill: 1, Letterbox: 0 };`;
|
||||
const hooks = registerHooks({
|
||||
resolve(specifier, context, next) {
|
||||
if (specifier === 'mapillary-js') return { url: 'data:text/javascript,' + encodeURIComponent(fakeLibrary), shortCircuit: true };
|
||||
if (specifier.endsWith('mapillary.css')) return { url: 'data:text/javascript,export default {}', shortCircuit: true };
|
||||
return next(specifier, context);
|
||||
},
|
||||
});
|
||||
globalThis.fetch = async () => { throw new Error('Unexpected network use in offline test'); };
|
||||
test('a photo the action asks for stops sequence PLAY', async t => {
|
||||
const provider = fakeStreetLevelProvider({ nearestImage: async () => 'B' });
|
||||
const create = provider.create;
|
||||
provider.create = context => ({ ...create(context), viewer: createMapillaryViewer({ source: { token: '' } }) });
|
||||
const viewer = fakeCesiumViewer(); viewer.canvas = viewer.scene.canvas;
|
||||
const layer = createStreetLevelLayer({ providers: [provider] });
|
||||
layer.init(viewer); layer.enable(viewer);
|
||||
layer.attachViewerHost(document.body.appendChild(document.createElement('div')));
|
||||
t.after(() => { layer.destroy(); hooks.deregister(); delete globalThis.__replacePlayViewer; document.body.replaceChildren(); });
|
||||
await Promise.resolve();
|
||||
await layer.openImage('mapillary', 'A', { frame: false });
|
||||
const libraryViewer = globalThis.__replacePlayViewer;
|
||||
libraryViewer.getComponent('sequence').play();
|
||||
assert.equal(libraryViewer.playing, true);
|
||||
const manager = {
|
||||
layers: new Map([['street-level', { module: layer }]]), isEnabled: () => true,
|
||||
getLayerParams: () => layer.getParams(), setLayerParams: (_id, params) => layer.setParams(params),
|
||||
};
|
||||
const result = await showStreetLevel({ provider: 'mapillary', latitude: 48, longitude: 2 }, {
|
||||
viewer, dataManager: manager, styleManager: { _navigationGeneration: 1 },
|
||||
runGevAction: async () => ({ ok: true, latitude: 48, longitude: 2, label: 'fixture destination' }),
|
||||
});
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(libraryViewer.id, 'B');
|
||||
assert.equal(layer.getUIState().street.open, true);
|
||||
assert.equal(libraryViewer.playing, false, 'requested image must stay selected rather than continue sequence PLAY');
|
||||
});
|
||||
@@ -1,9 +1,17 @@
|
||||
import { msg } from '../../../../i18n/marker.js';
|
||||
import { NEAREST_RADIUS_M } from '../../policy.js';
|
||||
import {
|
||||
MAPILLARY_GRAPH_HOST,
|
||||
NEAREST_IMAGE_FIELDS,
|
||||
NEAREST_LIMIT,
|
||||
NEAREST_TIMEOUT_MS,
|
||||
SEQUENCE_IMAGE_FIELDS,
|
||||
SEQUENCE_IMAGES_LIMIT,
|
||||
} from './policy.js';
|
||||
|
||||
/** English data: the Street Level panel translates it. */
|
||||
const NO_ANSWER = msg('Mapillary did not answer in time — try again');
|
||||
|
||||
/** HTTP error flagged `keyRequired`, `keyRejected` or `retryAfterSec` (429). */
|
||||
export class MapillarySourceError extends Error {
|
||||
constructor(message, { status = 0, payload = null, retryAfterSec } = {}) {
|
||||
@@ -66,7 +74,47 @@ export function createMapillarySource({
|
||||
...endpoints,
|
||||
};
|
||||
|
||||
async function graph(path, params = {}, { signal } = {}) {
|
||||
async function graph(path, params = {}, { signal, timeoutMs = 0 } = {}) {
|
||||
if (!timeoutMs) return graphOnce(path, params, { signal });
|
||||
// The whole answer, body included, within `timeoutMs`; the caller's
|
||||
// abort still wins.
|
||||
if (signal?.aborted) throw signal.reason;
|
||||
const controller = new AbortController();
|
||||
const onAbort = () => controller.abort(signal.reason);
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
const timer = setTimeout(
|
||||
() =>
|
||||
controller.abort(
|
||||
new MapillarySourceError(NO_ANSWER, {
|
||||
status: 504,
|
||||
}),
|
||||
),
|
||||
timeoutMs,
|
||||
);
|
||||
try {
|
||||
// A body that never ends is given up too, whatever the fetch does.
|
||||
const gaveUp = new Promise((_, reject) =>
|
||||
controller.signal.addEventListener(
|
||||
'abort',
|
||||
() => reject(controller.signal.reason),
|
||||
{ once: true },
|
||||
),
|
||||
);
|
||||
return await Promise.race([
|
||||
graphOnce(path, params, { signal: controller.signal }),
|
||||
gaveUp,
|
||||
]);
|
||||
} catch (error) {
|
||||
if (signal?.aborted) throw signal.reason;
|
||||
if (controller.signal.aborted) throw controller.signal.reason;
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
}
|
||||
}
|
||||
|
||||
async function graphOnce(path, params, { signal }) {
|
||||
if (graphBase) {
|
||||
const search = new URLSearchParams(params);
|
||||
const response = await fetchImpl(`${graphBase}${path}?${search}`, {
|
||||
@@ -147,5 +195,21 @@ export function createMapillarySource({
|
||||
);
|
||||
return Array.isArray(payload?.data) ? payload.data : [];
|
||||
},
|
||||
|
||||
/** Images within `NEAREST_RADIUS_M` of a point, in no particular order. */
|
||||
async nearestImages({ lat, lon }, { signal } = {}) {
|
||||
const payload = await graph(
|
||||
'images',
|
||||
{
|
||||
lat: String(lat),
|
||||
lng: String(lon),
|
||||
radius: String(NEAREST_RADIUS_M),
|
||||
limit: String(NEAREST_LIMIT),
|
||||
fields: NEAREST_IMAGE_FIELDS,
|
||||
},
|
||||
{ signal, timeoutMs: NEAREST_TIMEOUT_MS },
|
||||
);
|
||||
return Array.isArray(payload?.data) ? payload.data : [];
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -126,6 +126,25 @@ test('a rejected key and a rate limit are told apart from other tile errors', as
|
||||
);
|
||||
});
|
||||
|
||||
test('nearestImages asks the graph API around a point, within 50 m, for at most 100 images', async () => {
|
||||
const { calls, fetchImpl } = fakeFetch(() =>
|
||||
jsonResponse({ data: [{ id: '1', geometry: { coordinates: [1, 2] } }] }),
|
||||
);
|
||||
const source = createMapillarySource({ token: 'MLY|1|abc', fetchImpl });
|
||||
const images = await source.nearestImages({ lat: 38.5, lon: -121.5 });
|
||||
assert.equal(images.length, 1);
|
||||
const url = new URL(calls[0].url);
|
||||
assert.equal(url.pathname, '/images');
|
||||
assert.equal(url.searchParams.get('lat'), '38.5');
|
||||
assert.equal(url.searchParams.get('lng'), '-121.5');
|
||||
assert.equal(url.searchParams.get('radius'), '50');
|
||||
// The API cuts at the limit before any order: a small one would sort and
|
||||
// filter a handful of arbitrary photos (a 360° filter could find none).
|
||||
assert.equal(url.searchParams.get('limit'), '100', "the API's most");
|
||||
assert.match(url.searchParams.get('fields'), /computed_geometry/);
|
||||
assert.match(url.searchParams.get('fields'), /is_pano/);
|
||||
});
|
||||
|
||||
test('with a Graph endpoint, sequence lookups go there without a token', async () => {
|
||||
const { calls, fetchImpl } = fakeFetch(() =>
|
||||
jsonResponse({ data: [{ id: '1', geometry: { coordinates: [1, 2] } }] }),
|
||||
@@ -157,3 +176,63 @@ test('Graph endpoint errors keep their status', async () => {
|
||||
(error) => error.status === 503 && error.keyRequired === true,
|
||||
);
|
||||
});
|
||||
|
||||
test('a nearest-image search that never answers is given up, body included', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const { NEAREST_TIMEOUT_MS } = await import('./policy.js');
|
||||
// Headers arrive; the body never ends, and the fetch ignores its signal.
|
||||
const { fetchImpl } = fakeFetch(() => ({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: () => new Promise(() => {}),
|
||||
}));
|
||||
const source = createMapillarySource({ token: 'MLY|1|abc', fetchImpl });
|
||||
const pending = source.nearestImages({ lat: 1, lon: 2 });
|
||||
const outcome = pending.then(
|
||||
() => 'answered',
|
||||
(error) => error,
|
||||
);
|
||||
await Promise.resolve();
|
||||
t.mock.timers.tick(NEAREST_TIMEOUT_MS);
|
||||
const error = await outcome;
|
||||
assert.ok(error instanceof MapillarySourceError, String(error));
|
||||
assert.equal(error.status, 504);
|
||||
assert.equal(error.keyRequired, false, 'not a key problem');
|
||||
// English data, shown in the interface language like the other sources'.
|
||||
const { setLocale } = await import('../../../../i18n/index.js');
|
||||
const { translateStreetLevelError } =
|
||||
await import('../../../../ui/streetLevelPresentation.js');
|
||||
assert.equal(
|
||||
translateStreetLevelError(error.message),
|
||||
'Mapillary did not answer in time — try again',
|
||||
);
|
||||
for (const [locale, expected] of [
|
||||
['de', /nicht rechtzeitig/],
|
||||
['ja', /時間内に応答/],
|
||||
]) {
|
||||
setLocale(locale);
|
||||
try {
|
||||
assert.match(translateStreetLevelError(error.message), expected, locale);
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('the caller’s abort still ends a nearest-image search before its deadline', async () => {
|
||||
const { fetchImpl } = fakeFetch(
|
||||
(_url, init) =>
|
||||
new Promise((_, reject) =>
|
||||
init.signal.addEventListener('abort', () => reject(init.signal.reason)),
|
||||
),
|
||||
);
|
||||
const source = createMapillarySource({ token: 'MLY|1|abc', fetchImpl });
|
||||
const controller = new AbortController();
|
||||
const pending = source.nearestImages(
|
||||
{ lat: 1, lon: 2 },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
const reason = new Error('the turn moved on');
|
||||
controller.abort(reason);
|
||||
await assert.rejects(pending, (error) => error === reason);
|
||||
});
|
||||
@@ -174,6 +174,15 @@ export function createMapillaryViewer({ source, render } = {}) {
|
||||
current = null;
|
||||
}
|
||||
|
||||
/** A playing sequence keeps stepping through (and downloading) images. */
|
||||
function stopPlayback() {
|
||||
try {
|
||||
viewer?.getComponent('sequence')?.stop();
|
||||
} catch {
|
||||
/* sequence component not available */
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
async mount(host) {
|
||||
if (!host) throw new Error('Street Level viewer has no host element');
|
||||
@@ -195,15 +204,12 @@ export function createMapillaryViewer({ source, render } = {}) {
|
||||
close() {
|
||||
pendingOpen = null;
|
||||
current = null;
|
||||
// A playing sequence would keep stepping through (and downloading)
|
||||
// images in the hidden viewer.
|
||||
try {
|
||||
viewer?.getComponent('sequence')?.stop();
|
||||
} catch {
|
||||
/* sequence component not available */
|
||||
}
|
||||
// Hidden, the viewer must not keep playing.
|
||||
stopPlayback();
|
||||
},
|
||||
|
||||
stopPlayback,
|
||||
|
||||
unmount() {
|
||||
pendingOpen = null;
|
||||
// A build still waiting for the library gives up when it arrives.
|
||||
|
||||
@@ -20,6 +20,7 @@ export function filtersOf(provider) {
|
||||
* @property {boolean} [groundClick] No coverage: a ground click at street zoom opens its nearest image.
|
||||
* @property {string} [requiresMapStack] Usable only on this map stack.
|
||||
* @property {boolean} [defaultOn] Default true; the first that defaults on is lit.
|
||||
* @property {boolean} [billedPerImage] Every image load costs the key's owner: a link never opens one without a click.
|
||||
* @property {() => boolean} [keyReady] False when its key is missing now; the
|
||||
* first keyless provider is lit instead of a default that cannot draw.
|
||||
* @property {{kind: 'view-cone', color: string}} [marker] Default: GEV's pin.
|
||||
@@ -50,7 +51,7 @@ export function filtersOf(provider) {
|
||||
* @property {(sequenceId: string) => Promise<void>} [selectSequence]
|
||||
* @property {() => void} [clearSequence]
|
||||
* @property {() => {selectedId: string|null, images: number, loading: boolean, error?: string|null}} [sequenceStats]
|
||||
* @property {(point: {lat: number, lon: number}, options?: {signal?: AbortSignal}) => Promise<string|null>} [nearestImage] For ground clicks and `openNearest`; an aborted lookup gives up (it may reject with an AbortError).
|
||||
* @property {(point: {lat: number, lon: number}, options?: {signal?: AbortSignal, radiusM?: number}) => Promise<string|null>} [nearestImage] For ground clicks and `openNearest`; an aborted lookup gives up (it may reject with an AbortError). `radiusM` asks for a wider search than NEAREST_RADIUS_M; a provider that cannot search wider ignores it.
|
||||
* @property {ViewerAdapter} viewer
|
||||
*
|
||||
* @typedef {object} ViewerAdapter
|
||||
|
||||
@@ -19,6 +19,8 @@ export function freshStreet() {
|
||||
capturedAt: null,
|
||||
/** 'day', or 'month' for providers that date images by month (Google). */
|
||||
capturedAtPrecision: 'day',
|
||||
/** Why the last nearest lookup opened nothing: 'empty', 'sky' or null. */
|
||||
nearestOutcome: null,
|
||||
/** A place name for the caption (Google's address), or null. */
|
||||
title: null,
|
||||
/** Whether the open viewer has FIT/FILL render modes. */
|
||||
@@ -29,6 +31,8 @@ export function freshStreet() {
|
||||
externalUrl: null,
|
||||
loading: false,
|
||||
error: null,
|
||||
// A lookup a link prepared but left to a click: {point, providerIds, radiusM}.
|
||||
armed: null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -73,6 +73,19 @@ export function createViewerHost({ state, parts }) {
|
||||
active.unsubscribe();
|
||||
active.adapter.unmount();
|
||||
active = null;
|
||||
// The photo being replaced belonged to that source: none of its details
|
||||
// (id, place, author, link) describe the one loading now.
|
||||
const { open, loading, error, providerId, providerName, providerLabel } =
|
||||
state.street;
|
||||
Object.assign(state.street, freshStreet(), {
|
||||
open,
|
||||
loading,
|
||||
error,
|
||||
providerId,
|
||||
providerName,
|
||||
providerLabel,
|
||||
});
|
||||
parts.marker.clear();
|
||||
}
|
||||
const adapter = entry.instance.viewer;
|
||||
const promise = (async () => {
|
||||
@@ -99,12 +112,17 @@ export function createViewerHost({ state, parts }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Open an image: true once its first pose is in, false if it failed or was
|
||||
* overtaken. `frame: false` leaves the camera where it is.
|
||||
* Open an image: true once its first pose is in, false if it failed, was
|
||||
* overtaken, or `signal` fired first. An abort while the viewer mounts or
|
||||
* loads closes the photo: nothing opens for a request that was withdrawn.
|
||||
*/
|
||||
async function open(providerId, imageId, { frame = true } = {}) {
|
||||
async function open(
|
||||
providerId,
|
||||
imageId,
|
||||
{ frame = true, signal = null } = {},
|
||||
) {
|
||||
const entry = state.providers.get(providerId);
|
||||
if (!entry || !imageId) return false;
|
||||
if (!entry || !imageId || signal?.aborted) return false;
|
||||
if (!state.street.host) {
|
||||
// A nearest-image lookup may have set it; nothing is loading now.
|
||||
state.street.loading = false;
|
||||
@@ -115,6 +133,10 @@ export function createViewerHost({ state, parts }) {
|
||||
}
|
||||
const seq = ++openSeq;
|
||||
const current = () => seq === openSeq;
|
||||
const onAbort = () => {
|
||||
if (current()) close();
|
||||
};
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
// Claimed now, honoured after loading only if nothing newer took the camera.
|
||||
const ticket = frame ? parts.framing.begin() : null;
|
||||
Object.assign(state.street, {
|
||||
@@ -138,6 +160,7 @@ export function createViewerHost({ state, parts }) {
|
||||
if (current())
|
||||
state.street.error = error?.message || msg('Image could not be opened');
|
||||
} finally {
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
if (current()) state.street.loading = false;
|
||||
notify();
|
||||
}
|
||||
@@ -165,6 +188,11 @@ export function createViewerHost({ state, parts }) {
|
||||
active?.adapter.resize();
|
||||
}
|
||||
|
||||
/** Stop a sequence playing in the open photo (adapters that play). */
|
||||
function stopPlayback() {
|
||||
active?.adapter.stopPlayback?.();
|
||||
}
|
||||
|
||||
function setRenderMode(mode) {
|
||||
state.street.renderMode = mode === 'fill' ? 'fill' : 'letterbox';
|
||||
active?.adapter.setRenderMode?.(state.street.renderMode);
|
||||
@@ -187,5 +215,27 @@ export function createViewerHost({ state, parts }) {
|
||||
active = null;
|
||||
}
|
||||
|
||||
return { attach, open, close, resize, setRenderMode, unmount };
|
||||
/**
|
||||
* Destroy `providerId`'s viewer and leave the panel's state alone: what a
|
||||
* request leaves behind once it replaced or closed that source's photo.
|
||||
*/
|
||||
function release(providerId) {
|
||||
if (active?.id !== providerId && mounting?.id !== providerId) return;
|
||||
const pending = mounting;
|
||||
mounting = null;
|
||||
active?.unsubscribe();
|
||||
(active?.adapter ?? pending?.adapter)?.unmount();
|
||||
active = null;
|
||||
}
|
||||
|
||||
return {
|
||||
attach,
|
||||
open,
|
||||
close,
|
||||
resize,
|
||||
setRenderMode,
|
||||
stopPlayback,
|
||||
unmount,
|
||||
release,
|
||||
};
|
||||
}
|
||||
@@ -557,6 +557,51 @@ test('an adapter that can frame but says this image has no frame offers no FIT /
|
||||
assert.equal(state.street.renderModes, true, 'a flat image can be framed');
|
||||
});
|
||||
|
||||
test('a caller that withdraws while the viewer is still mounting gets no photo', async () => {
|
||||
const gate = deferred();
|
||||
const adapter = fakeAdapter({ gate });
|
||||
const { state, host } = harness(adapter);
|
||||
const controller = new AbortController();
|
||||
const pending = host.open('mapillary', 'a', { signal: controller.signal });
|
||||
assert.equal(state.street.open, true, 'opening');
|
||||
controller.abort(); // the library is still loading
|
||||
gate.resolve();
|
||||
assert.equal(await pending, false);
|
||||
assert.deepEqual(adapter.calls.open, [], 'the image was never opened');
|
||||
assert.equal(state.street.open, false, 'the photo is closed');
|
||||
assert.equal(state.street.loading, false, 'no stuck spinner');
|
||||
assert.equal(state.street.imageId, null);
|
||||
});
|
||||
|
||||
test('a caller that withdraws while the photo is loading gets it closed', async () => {
|
||||
const openGate = deferred();
|
||||
const adapter = fakeAdapter({ openGate });
|
||||
const { state, host } = harness(adapter);
|
||||
const controller = new AbortController();
|
||||
const pending = host.open('mapillary', 'a', { signal: controller.signal });
|
||||
await settle();
|
||||
assert.deepEqual(adapter.calls.open, ['a'], 'loading');
|
||||
controller.abort();
|
||||
openGate.resolve();
|
||||
assert.equal(await pending, false);
|
||||
assert.equal(state.street.open, false, 'the withdrawn photo is closed');
|
||||
assert.equal(state.street.imageId, null);
|
||||
// An already-withdrawn request asks nothing at all.
|
||||
const done = new AbortController();
|
||||
done.abort();
|
||||
assert.equal(
|
||||
await host.open('mapillary', 'b', { signal: done.signal }),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(adapter.calls.open, ['a']);
|
||||
// A signal that never fires changes nothing.
|
||||
assert.equal(
|
||||
await host.open('mapillary', 'c', { signal: new AbortController().signal }),
|
||||
true,
|
||||
);
|
||||
assert.equal(state.street.imageId, 'c');
|
||||
});
|
||||
|
||||
test('a pose’s licence reaches the caption state, and a closed viewer forgets it', async () => {
|
||||
const { state, host, google } = twoProviders();
|
||||
await host.open('google', 'g-1');
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createWeatherRendering } from './rendering.js';
|
||||
import { createWeatherShell, globeImageryHost } from './shellRendering.js';
|
||||
import { weatherFrameSource } from './source.js';
|
||||
import { imageryHostStatus } from './imageryHost.js';
|
||||
import { weatherDisplay, insideExtent } from './display.js';
|
||||
import {
|
||||
@@ -72,6 +73,7 @@ export function createWeatherLayer({
|
||||
} = {}) {
|
||||
if (typeof feed?.getSnapshot !== 'function')
|
||||
throw new TypeError('Weather requires a snapshot source');
|
||||
// A feed may also supply decoded frames; see weatherFrameSource.
|
||||
const radar = id === 'weather-radar';
|
||||
const lightning = id === 'weather-lightning';
|
||||
const satellite = !radar && !lightning;
|
||||
@@ -293,6 +295,7 @@ export function createWeatherLayer({
|
||||
createShell: createWeatherShell,
|
||||
getHost,
|
||||
onChange: notify,
|
||||
frameSource: weatherFrameSource(feed),
|
||||
});
|
||||
checkHost(false);
|
||||
eventTarget?.addEventListener?.(
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { readResponseBytesCapped } from '../../sources/httpBody.js';
|
||||
import { msg } from '../../i18n/index.js';
|
||||
import { weatherImageUrl } from './source.js';
|
||||
import {
|
||||
weatherImageUrl,
|
||||
weatherPixelSize,
|
||||
drawWeatherPixels,
|
||||
closeWeatherPixels,
|
||||
} from './source.js';
|
||||
import { infraredAlpha } from './infraredAlpha.js';
|
||||
|
||||
export const MAX_MOSAIC_BYTES = 4 * 1024 * 1024;
|
||||
@@ -20,10 +25,35 @@ export function processInfraredImage(
|
||||
if (flipY) context.setTransform(1, 0, 0, -1, 0, image.height);
|
||||
context.drawImage(image, 0, 0);
|
||||
if (flipY) context.setTransform(1, 0, 0, 1, 0, 0);
|
||||
applyInfraredTransfer(context, canvas, mode);
|
||||
return canvas;
|
||||
}
|
||||
|
||||
function applyInfraredTransfer(context, canvas, mode) {
|
||||
const pixels = context.getImageData(0, 0, canvas.width, canvas.height);
|
||||
pixels.data.set(infraredAlpha(pixels.data, mode));
|
||||
context.putImageData(pixels, 0, 0);
|
||||
return canvas;
|
||||
}
|
||||
|
||||
/** Draw pixels a frame source supplied into a new canvas, with the display
|
||||
* transfer for infrared products, and release them. They must be `size`. */
|
||||
function drawSuppliedImage(pixels, product, mode, size, signal, createCanvas) {
|
||||
try {
|
||||
signal.throwIfAborted();
|
||||
const { width, height } = weatherPixelSize(pixels);
|
||||
if (width !== size.width || height !== size.height)
|
||||
throw new Error('Invalid weather image dimensions');
|
||||
const texture = createCanvas();
|
||||
texture.width = width;
|
||||
texture.height = height;
|
||||
const context = texture.getContext('2d');
|
||||
drawWeatherPixels(context, pixels);
|
||||
if (product === 'clouds' || product === 'clouds-regional')
|
||||
applyInfraredTransfer(context, texture, mode);
|
||||
return texture;
|
||||
} finally {
|
||||
closeWeatherPixels(pixels);
|
||||
}
|
||||
}
|
||||
|
||||
/** Decode locally, releasing the object URL on success, failure or cancellation. */
|
||||
@@ -60,7 +90,8 @@ export function decodeInfraredImage(blob, signal) {
|
||||
/** Fetch one capped whole-extent frame, or a `bbox` detail window of it, and draw
|
||||
* it into a canvas. Infrared frames get the display transfer; a canvas also keeps
|
||||
* Cesium's texture row order, which an ImageBitmap upload would not. The decoded
|
||||
* image is always released. */
|
||||
* image is always released. With a `frameSource` that has `getImage`, the host
|
||||
* supplies the decoded pixels instead and nothing is fetched or decoded here. */
|
||||
export async function acquireWeatherImage(
|
||||
product,
|
||||
time,
|
||||
@@ -75,8 +106,30 @@ export async function acquireWeatherImage(
|
||||
decodeImage = decodeInfraredImage,
|
||||
now = () => performance.now(),
|
||||
onFetched = () => {},
|
||||
frameSource = null,
|
||||
},
|
||||
) {
|
||||
if (frameSource?.getImage) {
|
||||
signal.throwIfAborted();
|
||||
const started = now();
|
||||
const pixels = await frameSource.getImage({
|
||||
product,
|
||||
time,
|
||||
size,
|
||||
bbox,
|
||||
signal,
|
||||
});
|
||||
onFetched();
|
||||
const texture = drawSuppliedImage(
|
||||
pixels,
|
||||
product,
|
||||
mode,
|
||||
size,
|
||||
signal,
|
||||
createCanvas,
|
||||
);
|
||||
return { texture, decodeMs: now() - started };
|
||||
}
|
||||
const response = await fetchImpl(weatherImageUrl(product, time, size, bbox), {
|
||||
signal,
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
acquireInfraredMosaic,
|
||||
acquireWeatherImage,
|
||||
decodeInfraredImage,
|
||||
processInfraredImage,
|
||||
MAX_MOSAIC_BYTES,
|
||||
@@ -183,3 +184,154 @@ test('bitmap decoding and Image fallback release resources on success, error and
|
||||
}
|
||||
assert.deepEqual(revoked, ['blob:test', 'blob:test', 'blob:test']);
|
||||
});
|
||||
|
||||
const pixels = (width, height) => ({
|
||||
width,
|
||||
height,
|
||||
closes: 0,
|
||||
close() {
|
||||
this.closes++;
|
||||
},
|
||||
});
|
||||
|
||||
test('a frame source supplies the image: nothing is fetched or decoded and the pixels are released', async () => {
|
||||
const controller = new AbortController();
|
||||
const requests = [];
|
||||
const bitmap = pixels(2048, 1024);
|
||||
let clock = 5,
|
||||
fetched = false;
|
||||
const result = await acquireInfraredMosaic('2026-09-15T20:00:00.000Z', {
|
||||
signal: controller.signal,
|
||||
mode: 'filtered',
|
||||
createCanvas: canvas,
|
||||
now: () => clock,
|
||||
onFetched: () => {
|
||||
fetched = true;
|
||||
},
|
||||
fetchImpl: () => assert.fail('a supplied frame is not fetched'),
|
||||
decodeImage: () => assert.fail('a supplied frame is not decoded'),
|
||||
frameSource: {
|
||||
getImage: async (request) => {
|
||||
requests.push(request);
|
||||
clock = 12;
|
||||
return bitmap;
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.deepEqual(requests, [
|
||||
{
|
||||
product: 'clouds',
|
||||
time: '2026-09-15T20:00:00.000Z',
|
||||
size: { width: 2048, height: 1024 },
|
||||
bbox: null,
|
||||
signal: controller.signal,
|
||||
},
|
||||
]);
|
||||
assert.equal(fetched, true);
|
||||
assert.equal(result.decodeMs, 7);
|
||||
assert.equal(result.texture.width, 2048);
|
||||
assert.equal(result.texture.height, 1024);
|
||||
assert.equal(result.texture.image, bitmap);
|
||||
assert.deepEqual(
|
||||
[...result.texture.pixels],
|
||||
[194, 0, 0, 98],
|
||||
'infrared frames get the display transfer',
|
||||
);
|
||||
assert.equal(bitmap.closes, 1);
|
||||
});
|
||||
|
||||
test('supplied detail windows carry their bbox; ImageData is put, radar keeps its pixels', async (t) => {
|
||||
const had = Object.hasOwn(globalThis, 'ImageData');
|
||||
const previous = globalThis.ImageData;
|
||||
globalThis.ImageData = class ImageData {
|
||||
width = 4096;
|
||||
height = 2048;
|
||||
data = new Uint8ClampedArray([1, 2, 3, 4]);
|
||||
};
|
||||
t.after(() => {
|
||||
if (had) globalThis.ImageData = previous;
|
||||
else delete globalThis.ImageData;
|
||||
});
|
||||
const data = new globalThis.ImageData();
|
||||
const bbox = { west: -102, south: 34, east: -96, north: 37 };
|
||||
let request;
|
||||
const { texture } = await acquireWeatherImage('radar', 't', {
|
||||
signal: new AbortController().signal,
|
||||
size: { width: 4096, height: 2048 },
|
||||
bbox,
|
||||
createCanvas: canvas,
|
||||
fetchImpl: () => assert.fail('no fetch'),
|
||||
frameSource: {
|
||||
getImage: async (value) => {
|
||||
request = value;
|
||||
return data;
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.equal(request.bbox, bbox);
|
||||
assert.equal(
|
||||
texture.pixels,
|
||||
data.data,
|
||||
'ImageData is put as it is; radar has no transfer',
|
||||
);
|
||||
assert.equal(texture.image, undefined, 'ImageData is not drawn as an image');
|
||||
assert.equal(texture.width, 4096);
|
||||
});
|
||||
|
||||
test('a supplied frame of the wrong size is refused and still released', async () => {
|
||||
const wrong = pixels(1024, 512);
|
||||
await assert.rejects(
|
||||
acquireInfraredMosaic('t', {
|
||||
signal: new AbortController().signal,
|
||||
mode: 'filtered',
|
||||
createCanvas: canvas,
|
||||
frameSource: { getImage: async () => wrong },
|
||||
}),
|
||||
/Invalid weather image dimensions/,
|
||||
);
|
||||
assert.equal(wrong.closes, 1);
|
||||
await assert.rejects(
|
||||
acquireInfraredMosaic('t', {
|
||||
signal: new AbortController().signal,
|
||||
mode: 'filtered',
|
||||
createCanvas: canvas,
|
||||
frameSource: { getImage: async () => undefined },
|
||||
}),
|
||||
/Invalid weather image dimensions/,
|
||||
);
|
||||
});
|
||||
|
||||
test('cancellation reaches the frame source, and a frame that arrives after it is released', async () => {
|
||||
const controller = new AbortController();
|
||||
const late = pixels(2048, 1024);
|
||||
let seen;
|
||||
const pending = acquireInfraredMosaic('t', {
|
||||
signal: controller.signal,
|
||||
mode: 'filtered',
|
||||
createCanvas: () => assert.fail('a cancelled frame is not drawn'),
|
||||
frameSource: {
|
||||
getImage: async ({ signal }) => {
|
||||
seen = signal;
|
||||
await flushMicrotasks();
|
||||
return late;
|
||||
},
|
||||
},
|
||||
});
|
||||
controller.abort();
|
||||
await assert.rejects(pending, { name: 'AbortError' });
|
||||
assert.equal(seen, controller.signal);
|
||||
assert.equal(late.closes, 1);
|
||||
const aborted = new AbortController();
|
||||
aborted.abort();
|
||||
await assert.rejects(
|
||||
acquireInfraredMosaic('t', {
|
||||
signal: aborted.signal,
|
||||
frameSource: { getImage: () => assert.fail('already cancelled') },
|
||||
}),
|
||||
{ name: 'AbortError' },
|
||||
);
|
||||
});
|
||||
|
||||
async function flushMicrotasks() {
|
||||
for (let i = 0; i < 5; i++) await Promise.resolve();
|
||||
}
|
||||
@@ -1,3 +1,9 @@
|
||||
import {
|
||||
weatherPixelSize,
|
||||
drawWeatherPixels,
|
||||
closeWeatherPixels,
|
||||
} from './source.js';
|
||||
|
||||
/**
|
||||
* Draw one tile of the geographic scheme (two level-zero tiles) from a
|
||||
* decoded mosaic covering `bounds` (degrees), without network requests or
|
||||
@@ -27,3 +33,73 @@ export function drawMosaicTile(texture, bounds, { x, y, level }, canvas) {
|
||||
canvas.height,
|
||||
);
|
||||
}
|
||||
|
||||
/** A canvas's pixels as PNG bytes. */
|
||||
async function canvasBytes(canvas) {
|
||||
const blob =
|
||||
typeof canvas.convertToBlob === 'function'
|
||||
? await canvas.convertToBlob({ type: 'image/png' })
|
||||
: await new Promise((resolve, reject) =>
|
||||
canvas.toBlob(
|
||||
(made) =>
|
||||
made ? resolve(made) : reject(new Error('Tile not encoded')),
|
||||
'image/png',
|
||||
),
|
||||
);
|
||||
return blob.arrayBuffer();
|
||||
}
|
||||
|
||||
/**
|
||||
* An imagery layer's `fetchTile` for one product time of a host frame source.
|
||||
* Supplied pixels are drawn into a new canvas and released, and handed to the
|
||||
* renderer as PNG bytes; a null tile is one shared transparent tile, drawn,
|
||||
* not missing, so no coarser tile shows through it. Aborting `signal` (or the
|
||||
* renderer's own) cancels the tile at the source, and a failed tile rejects,
|
||||
* which the renderer reports as its `tileError`.
|
||||
*/
|
||||
export function createFrameTileFetch({
|
||||
frameSource,
|
||||
product,
|
||||
time,
|
||||
createCanvas,
|
||||
tileSize = 256,
|
||||
signal,
|
||||
}) {
|
||||
let empty = null;
|
||||
const canvas = () => {
|
||||
const tile = createCanvas();
|
||||
tile.width = tile.height = tileSize;
|
||||
return tile;
|
||||
};
|
||||
return async ({ tile: { x, y, level }, signal: tileSignal }) => {
|
||||
const signals = [signal, tileSignal].filter(Boolean);
|
||||
const both = signals.length > 1 ? AbortSignal.any(signals) : signals[0];
|
||||
both?.throwIfAborted();
|
||||
const pixels = await frameSource.getTile({
|
||||
product,
|
||||
time,
|
||||
z: level,
|
||||
x,
|
||||
y,
|
||||
size: tileSize,
|
||||
signal: both ?? new AbortController().signal,
|
||||
});
|
||||
if (pixels === null) {
|
||||
both?.throwIfAborted();
|
||||
empty ??= canvasBytes(canvas());
|
||||
return { bytes: (await empty).slice(0), contentType: 'image/png' };
|
||||
}
|
||||
let tileCanvas;
|
||||
try {
|
||||
both?.throwIfAborted();
|
||||
const { width, height } = weatherPixelSize(pixels);
|
||||
if (width !== tileSize || height !== tileSize)
|
||||
throw new Error('Invalid weather tile dimensions');
|
||||
tileCanvas = canvas();
|
||||
drawWeatherPixels(tileCanvas.getContext('2d'), pixels);
|
||||
} finally {
|
||||
closeWeatherPixels(pixels);
|
||||
}
|
||||
return { bytes: await canvasBytes(tileCanvas), contentType: 'image/png' };
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { drawMosaicTile } from './rasterTiles.js';
|
||||
import { drawMosaicTile, createFrameTileFetch } from './rasterTiles.js';
|
||||
import { createFieldRaster } from '../wind/fields.js';
|
||||
|
||||
// A small canvas double exposes the uploaded raster and exact drawImage crop.
|
||||
@@ -108,3 +108,138 @@ test('512-pixel tiles preserve the source extent at every level', () => {
|
||||
assert.deepEqual(tile.crop, crop);
|
||||
}
|
||||
});
|
||||
|
||||
const time = '2026-09-15T20:00:00.000Z';
|
||||
// A tile canvas double that records what is drawn on it and encodes to bytes
|
||||
// naming its draws.
|
||||
function tileCanvas() {
|
||||
const canvas = { width: 0, height: 0, drawn: [], encoded: 0 };
|
||||
canvas.getContext = () => ({
|
||||
drawImage: (source, ...args) => canvas.drawn.push([source, ...args]),
|
||||
putImageData: (source, ...args) => canvas.drawn.push([source, ...args]),
|
||||
});
|
||||
canvas.convertToBlob = async ({ type }) => {
|
||||
canvas.encoded++;
|
||||
assert.equal(type, 'image/png');
|
||||
return new Blob([`tile:${canvas.drawn.length}`]);
|
||||
};
|
||||
return canvas;
|
||||
}
|
||||
const tilePixels = (size = 256) => ({
|
||||
width: size,
|
||||
height: size,
|
||||
closes: 0,
|
||||
close() {
|
||||
this.closes++;
|
||||
},
|
||||
});
|
||||
const deferredTile = () => {
|
||||
let resolve, reject;
|
||||
const promise = new Promise((yes, no) => {
|
||||
resolve = yes;
|
||||
reject = no;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
};
|
||||
const text = (bytes) => new TextDecoder().decode(bytes);
|
||||
function frameFetch(getTile, options = {}) {
|
||||
const canvases = [];
|
||||
const fetchTile = createFrameTileFetch({
|
||||
frameSource: { getTile },
|
||||
product: 'radar',
|
||||
time,
|
||||
createCanvas: () => {
|
||||
const canvas = tileCanvas();
|
||||
canvases.push(canvas);
|
||||
return canvas;
|
||||
},
|
||||
...options,
|
||||
});
|
||||
const ask = (x, y, level, signal = new AbortController().signal) =>
|
||||
fetchTile({ tile: { x, y, level }, url: 'unused', signal });
|
||||
return { ask, canvases };
|
||||
}
|
||||
|
||||
test('a frame tile fetch draws each supplied tile into its own canvas, releases it, and answers PNG bytes', async () => {
|
||||
const requests = [];
|
||||
const supplied = tilePixels();
|
||||
const { ask, canvases } = frameFetch(async (request) => {
|
||||
requests.push(request);
|
||||
return supplied;
|
||||
});
|
||||
const answer = await ask(3, 1, 2);
|
||||
assert.equal(answer.contentType, 'image/png');
|
||||
assert.equal(text(answer.bytes), 'tile:1');
|
||||
assert.equal(canvases.length, 1);
|
||||
assert.equal(canvases[0].width, 256);
|
||||
assert.deepEqual(canvases[0].drawn, [[supplied, 0, 0]]);
|
||||
assert.equal(supplied.closes, 1);
|
||||
assert.equal(requests.length, 1);
|
||||
const { signal, ...rest } = requests[0];
|
||||
assert.deepEqual(rest, {
|
||||
product: 'radar',
|
||||
time,
|
||||
z: 2,
|
||||
x: 3,
|
||||
y: 1,
|
||||
size: 256,
|
||||
});
|
||||
assert.ok(signal instanceof AbortSignal);
|
||||
});
|
||||
|
||||
test('a null tile is one shared transparent tile, drawn rather than missing', async () => {
|
||||
const { ask, canvases } = frameFetch(async () => null);
|
||||
const first = await ask(0, 0, 0);
|
||||
const second = await ask(1, 0, 0);
|
||||
assert.equal(text(first.bytes), 'tile:0', 'nothing is drawn on it');
|
||||
assert.equal(text(second.bytes), 'tile:0');
|
||||
assert.notEqual(first.bytes, second.bytes, 'each answer has its own bytes');
|
||||
assert.equal(canvases.length, 1, 'made and encoded once');
|
||||
assert.equal(canvases[0].encoded, 1);
|
||||
});
|
||||
|
||||
test('a failed tile rejects, which the renderer reports as a tile error', async () => {
|
||||
const { ask } = frameFetch(async () => {
|
||||
throw new Error('frame unavailable');
|
||||
});
|
||||
await assert.rejects(ask(0, 0, 0), /frame unavailable/);
|
||||
const wrong = tilePixels(512);
|
||||
const sized = frameFetch(async () => wrong);
|
||||
await assert.rejects(sized.ask(0, 0, 0), /Invalid weather tile dimensions/);
|
||||
assert.equal(wrong.closes, 1, 'a refused tile is still released');
|
||||
});
|
||||
|
||||
test('aborting the frame or the tile cancels it at the source and releases late pixels', async () => {
|
||||
const controller = new AbortController();
|
||||
const gate = deferredTile();
|
||||
let seen;
|
||||
const { ask } = frameFetch(
|
||||
({ signal }) => {
|
||||
seen = signal;
|
||||
return gate.promise;
|
||||
},
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
const pending = ask(0, 0, 0);
|
||||
assert.equal(seen.aborted, false);
|
||||
controller.abort();
|
||||
assert.equal(seen.aborted, true, 'the abort reaches the frame source');
|
||||
const late = tilePixels();
|
||||
gate.resolve(late);
|
||||
await assert.rejects(pending, { name: 'AbortError' });
|
||||
assert.equal(late.closes, 1);
|
||||
await assert.rejects(
|
||||
ask(1, 0, 0),
|
||||
{ name: 'AbortError' },
|
||||
'a closed frame asks the source for nothing more',
|
||||
);
|
||||
// The renderer's own abort of one tile reaches the source too.
|
||||
const own = frameFetch(({ signal }) => {
|
||||
seen = signal;
|
||||
return new Promise(() => {});
|
||||
});
|
||||
const tile = new AbortController();
|
||||
void own.ask(0, 0, 0, tile.signal).catch(() => {});
|
||||
tile.abort();
|
||||
assert.equal(seen.aborted, true);
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
import { weatherTileUrl } from './source.js';
|
||||
import { weatherTileUrl, closeWeatherPixels } from './source.js';
|
||||
import { WEATHER_IMAGERY_Z } from './imageryOrder.js';
|
||||
import { imageryHostStatus } from './imageryHost.js';
|
||||
import { globeImageryHost } from './shellRendering.js';
|
||||
import { drawMosaicTile } from './rasterTiles.js';
|
||||
import { drawMosaicTile, createFrameTileFetch } from './rasterTiles.js';
|
||||
import { weatherDisplay } from './display.js';
|
||||
import { msg } from '../../i18n/index.js';
|
||||
import {
|
||||
@@ -75,6 +75,7 @@ function createGlobeRendering({
|
||||
fetchImpl,
|
||||
decodeImage,
|
||||
createCanvas,
|
||||
frameSource,
|
||||
}) {
|
||||
const requestRender = () => frameOf(viewer)?.requestRender('weather');
|
||||
const onPostRender = (cb) => frameOf(viewer).on('postRender', cb);
|
||||
@@ -119,6 +120,7 @@ function createGlobeRendering({
|
||||
decodeImage,
|
||||
now,
|
||||
onFetched,
|
||||
frameSource,
|
||||
});
|
||||
// An aborted decode may still finish; never repopulate a cleared instance.
|
||||
signal.throwIfAborted();
|
||||
@@ -129,27 +131,50 @@ function createGlobeRendering({
|
||||
return { ...result, cached: false };
|
||||
}
|
||||
|
||||
function prefetchTiles(snapshot, time) {
|
||||
/** Level 0–1 tiles of the visible product bounds, at most eight. */
|
||||
function prefetchTiles(snapshot) {
|
||||
const bounds = snapshot.bounds;
|
||||
const view = cameraOf(viewer)?.viewRectangle?.();
|
||||
const coverage = view ? rectangleOverlap(bounds, view) : bounds;
|
||||
if (!coverage) return [];
|
||||
const template = weatherTileUrl(snapshot.product, time, {
|
||||
size: profile(snapshot.product).tileSize,
|
||||
});
|
||||
const urls = [];
|
||||
const tiles = [];
|
||||
for (let z = 0; z <= 1; z++) {
|
||||
for (let y = 0; y < 2 ** z; y++) {
|
||||
for (let x = 0; x < 2 ** (z + 1); x++) {
|
||||
if (!rectangleOverlap(coverage, geographicTile(x, y, z))) continue;
|
||||
urls.push(
|
||||
template.replace('{z}', z).replace('{x}', x).replace('{y}', y),
|
||||
);
|
||||
if (urls.length === MAX_PREFETCH_TILES) return urls;
|
||||
tiles.push({ z, x, y });
|
||||
if (tiles.length === MAX_PREFETCH_TILES) return tiles;
|
||||
}
|
||||
}
|
||||
}
|
||||
return urls;
|
||||
return tiles;
|
||||
}
|
||||
function tileUrls(snapshot, time, tiles) {
|
||||
const template = weatherTileUrl(snapshot.product, time, {
|
||||
size: profile(snapshot.product).tileSize,
|
||||
});
|
||||
return tiles.map(({ z, x, y }) =>
|
||||
template.replace('{z}', z).replace('{x}', x).replace('{y}', y),
|
||||
);
|
||||
}
|
||||
/** Warm tiles through the frame source; the pixels themselves are released. */
|
||||
function prefetchFrameTiles(snapshot, time, tiles, signal) {
|
||||
const size = profile(snapshot.product).tileSize;
|
||||
return Promise.all(
|
||||
tiles.map(async ({ z, x, y }) =>
|
||||
closeWeatherPixels(
|
||||
await frameSource.getTile({
|
||||
product: snapshot.product,
|
||||
time,
|
||||
z,
|
||||
x,
|
||||
y,
|
||||
size,
|
||||
signal,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function creditText(snapshot) {
|
||||
@@ -263,8 +288,14 @@ function createGlobeRendering({
|
||||
)
|
||||
return false;
|
||||
const global = snapshot.product === 'clouds';
|
||||
const urls = global ? [] : prefetchTiles(snapshot, time);
|
||||
const key = global ? `${time}|${infrared}` : urls.join('|');
|
||||
const tiles = global ? [] : prefetchTiles(snapshot);
|
||||
const supplied = !global && Boolean(frameSource?.getTile);
|
||||
const urls = global || supplied ? [] : tileUrls(snapshot, time, tiles);
|
||||
const key = global
|
||||
? `${time}|${infrared}`
|
||||
: supplied
|
||||
? `${snapshot.product}|${time}|${tiles.map(({ z, x, y }) => `${z}/${x}/${y}`).join('|')}`
|
||||
: urls.join('|');
|
||||
if (prefetchJob?.key === key || prefetchedKey === key) return false;
|
||||
cancelPrefetch();
|
||||
job = { key, controller: new AbortController() };
|
||||
@@ -272,6 +303,8 @@ function createGlobeRendering({
|
||||
const { signal } = job.controller;
|
||||
job.timeout = setTimeout(() => job.controller.abort(), timeoutMs);
|
||||
if (global) await mosaic(time, infrared, signal);
|
||||
else if (supplied)
|
||||
await prefetchFrameTiles(snapshot, time, tiles, signal);
|
||||
else
|
||||
await Promise.all(
|
||||
urls.map(async (url) => {
|
||||
@@ -452,6 +485,21 @@ function createGlobeRendering({
|
||||
maxLevel: nextProfile.maximumLevel,
|
||||
retryStatuses: RETRY_STATUSES,
|
||||
admit,
|
||||
// A host's frame source supplies the tiles in place of the
|
||||
// route, at most six at once.
|
||||
...(frameSource?.getTile
|
||||
? {
|
||||
fetchTile: createFrameTileFetch({
|
||||
frameSource,
|
||||
product: snapshot.product,
|
||||
time,
|
||||
createCanvas,
|
||||
tileSize,
|
||||
signal: frame.controller.signal,
|
||||
}),
|
||||
maxConcurrentRequests: 6,
|
||||
}
|
||||
: {}),
|
||||
...(snapshot.product === 'clouds-regional'
|
||||
? {
|
||||
// The transfer runs on the upright tile the renderer
|
||||
@@ -608,6 +656,7 @@ export function createWeatherRendering({
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
decodeImage,
|
||||
createCanvas = () => document.createElement('canvas'),
|
||||
frameSource = null,
|
||||
}) {
|
||||
const shared = {
|
||||
viewer,
|
||||
@@ -618,6 +667,7 @@ export function createWeatherRendering({
|
||||
fetchImpl,
|
||||
decodeImage,
|
||||
createCanvas,
|
||||
frameSource,
|
||||
};
|
||||
const globe = createGlobeRendering({
|
||||
...shared,
|
||||
|
||||
@@ -160,7 +160,8 @@ let weatherShells = 0;
|
||||
/** Observed weather on 3D Tiles: one raised shell per product and one
|
||||
* full-extent image per frame. The previous image stays until the next is ready.
|
||||
* Inside a window around the view the same surface samples a sharper image of
|
||||
* that area, so the two images share one mesh and never blend. */
|
||||
* that area, so the two images share one mesh and never blend. A `frameSource`
|
||||
* with `getImage` supplies both images, the detail window through its `bbox`. */
|
||||
export function createWeatherShell({
|
||||
viewer,
|
||||
product,
|
||||
@@ -177,6 +178,7 @@ export function createWeatherShell({
|
||||
cameraOf = findCamera,
|
||||
frameOf = findFrame,
|
||||
maxTextureSize = rendererOf(viewer)?.quality?.device?.().maxTextureSize ?? 0,
|
||||
frameSource = null,
|
||||
}) {
|
||||
if (!Object.hasOwn(WEATHER_IMAGE_SIZES, product))
|
||||
throw new TypeError('Unknown weather product');
|
||||
@@ -327,6 +329,7 @@ export function createWeatherShell({
|
||||
decodeImage,
|
||||
now,
|
||||
onFetched,
|
||||
frameSource,
|
||||
});
|
||||
// An aborted decode may still finish; never repopulate a cleared instance.
|
||||
signal.throwIfAborted();
|
||||
|
||||
@@ -1189,3 +1189,101 @@ test('global infrared keeps one full-extent image; detail images halve for small
|
||||
});
|
||||
small.shell.clear();
|
||||
});
|
||||
|
||||
test('a frame source supplies the full-extent and detail images, the detail through its bbox', async () => {
|
||||
const view = camera(-100, 35, -98, 36);
|
||||
const requests = [];
|
||||
const supplied = [];
|
||||
const h = harness({
|
||||
camera: view,
|
||||
fetchImpl: () => assert.fail('supplied images are not fetched'),
|
||||
decodeImage: () => assert.fail('supplied images are not decoded'),
|
||||
frameSource: {
|
||||
getImage: async (request) => {
|
||||
requests.push(request);
|
||||
const image = {
|
||||
...request.size,
|
||||
closed: 0,
|
||||
close() {
|
||||
this.closed++;
|
||||
},
|
||||
};
|
||||
supplied.push(image);
|
||||
return image;
|
||||
},
|
||||
},
|
||||
});
|
||||
const pending = h.shell.setFrame(snapshot(), times[0]);
|
||||
await flush();
|
||||
h.render();
|
||||
assert.equal(await pending, true);
|
||||
await flush();
|
||||
assert.deepEqual(
|
||||
requests.map(({ product, time, size, bbox }) => ({
|
||||
product,
|
||||
time,
|
||||
size,
|
||||
bbox,
|
||||
})),
|
||||
[
|
||||
{
|
||||
product: 'radar',
|
||||
time: times[0],
|
||||
size: { width: 4096, height: 2048 },
|
||||
bbox: null,
|
||||
},
|
||||
{
|
||||
product: 'radar',
|
||||
time: times[0],
|
||||
size: { width: 4096, height: 2048 },
|
||||
bbox: box(-102, 34, -96, 37),
|
||||
},
|
||||
],
|
||||
);
|
||||
assert.ok(supplied.every(({ closed }) => closed === 1));
|
||||
const [shell] = h.primitives();
|
||||
const { uniforms } = shell.appearance.material;
|
||||
assert.equal(uniforms.image.source, supplied[0]);
|
||||
assert.equal(uniforms.detail.source, supplied[1]);
|
||||
h.render();
|
||||
assert.deepEqual(windowOf(shell), windowFor(box(-102, 34, -96, 37)));
|
||||
h.shell.clear();
|
||||
});
|
||||
|
||||
test('cancelling a supplied frame aborts the frame source request', async () => {
|
||||
const gate = deferred();
|
||||
let signal;
|
||||
const h = harness({
|
||||
frameSource: {
|
||||
getImage: (request) => {
|
||||
signal = request.signal;
|
||||
return gate.promise;
|
||||
},
|
||||
},
|
||||
});
|
||||
const abort = new AbortController();
|
||||
const pending = h.shell.setFrame(snapshot(), times[0], {
|
||||
signal: abort.signal,
|
||||
});
|
||||
await flush();
|
||||
abort.abort();
|
||||
assert.equal(signal.aborted, true);
|
||||
assert.equal(await pending, false);
|
||||
const late = {
|
||||
width: 4096,
|
||||
height: 2048,
|
||||
closed: 0,
|
||||
close() {
|
||||
this.closed++;
|
||||
},
|
||||
};
|
||||
gate.resolve(late);
|
||||
await flush();
|
||||
assert.equal(
|
||||
late.closed,
|
||||
1,
|
||||
'a frame arriving after cancellation is released',
|
||||
);
|
||||
assert.equal(h.primitives().length, 0);
|
||||
h.shell.clear();
|
||||
});
|
||||
@@ -104,6 +104,75 @@ export function weatherTileUrl(product, time, { size } = {}) {
|
||||
return `/api/weather/tile?product=${product}&time=${encodeURIComponent(time)}&z={z}&x={x}&y={y}${size === undefined ? '' : `&size=${size}`}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decoded pixels a host hands the weather layer. The layer takes ownership:
|
||||
* it draws them once and closes a VideoFrame or ImageBitmap afterwards, so a
|
||||
* host returns a fresh object for every call.
|
||||
* @typedef {ImageBitmap|ImageData|HTMLCanvasElement|OffscreenCanvas|VideoFrame} WeatherPixels
|
||||
*/
|
||||
|
||||
/**
|
||||
* A weather feed may also be a frame source: a host can supply decoded frames
|
||||
* in place of the bounded image and tile routes. Both methods are optional and
|
||||
* independent; a product or path without one keeps the routes.
|
||||
*
|
||||
* `getFrameImage` returns one image exactly `size` pixels, covering the
|
||||
* product's whole extent, or with `bbox` ({ west, south, east, north }
|
||||
* degrees) a detail window of it. `getFrameTile` returns one `size`-pixel tile
|
||||
* of the geographic tiling scheme, or null for a transparent tile. Rows run
|
||||
* top-down (north first), as an image does. Both honour `signal`.
|
||||
* @typedef {object} WeatherFrameFeed
|
||||
* @property {(request: { product: string, time: string,
|
||||
* size: { width: number, height: number },
|
||||
* bbox: { west: number, south: number, east: number, north: number } | null,
|
||||
* signal: AbortSignal }) => Promise<WeatherPixels>} [getFrameImage]
|
||||
* @property {(request: { product: string, time: string, z: number, x: number,
|
||||
* y: number, size: number, signal: AbortSignal })
|
||||
* => Promise<WeatherPixels | null>} [getFrameTile]
|
||||
*/
|
||||
|
||||
/**
|
||||
* The frame source a feed provides, or null when it has neither method. A
|
||||
* missing method is left undefined, so that path keeps the routes.
|
||||
* @param {WeatherFrameFeed | undefined} feed
|
||||
* @returns {{ getImage?: Function, getTile?: Function } | null}
|
||||
*/
|
||||
export function weatherFrameSource(feed) {
|
||||
const image = typeof feed?.getFrameImage === 'function';
|
||||
const tile = typeof feed?.getFrameTile === 'function';
|
||||
if (!image && !tile) return null;
|
||||
return {
|
||||
getImage: image
|
||||
? ({ product, time, size, bbox = null, signal }) =>
|
||||
feed.getFrameImage({ product, time, size, bbox, signal })
|
||||
: undefined,
|
||||
getTile: tile
|
||||
? ({ product, time, z, x, y, size, signal }) =>
|
||||
feed.getFrameTile({ product, time, z, x, y, size, signal })
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/** Width and height of supplied pixels; a VideoFrame draws at its display size. */
|
||||
export function weatherPixelSize(pixels) {
|
||||
return {
|
||||
width: pixels?.displayWidth ?? pixels?.width,
|
||||
height: pixels?.displayHeight ?? pixels?.height,
|
||||
};
|
||||
}
|
||||
|
||||
/** Draw supplied pixels at the canvas origin, at their own size. */
|
||||
export function drawWeatherPixels(context, pixels) {
|
||||
if (typeof ImageData !== 'undefined' && pixels instanceof ImageData)
|
||||
context.putImageData(pixels, 0, 0);
|
||||
else context.drawImage(pixels, 0, 0);
|
||||
}
|
||||
|
||||
/** Release supplied pixels that hold decoder or GPU memory. */
|
||||
export function closeWeatherPixels(pixels) {
|
||||
if (typeof pixels?.close === 'function') pixels.close();
|
||||
}
|
||||
|
||||
/** Acquisition is lazy and shares the application's existing source contract. */
|
||||
export function createWeatherSource({
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
|
||||
@@ -5,6 +5,10 @@ import {
|
||||
validateWeatherSnapshot,
|
||||
weatherImageUrl,
|
||||
weatherTileUrl,
|
||||
weatherFrameSource,
|
||||
weatherPixelSize,
|
||||
drawWeatherPixels,
|
||||
closeWeatherPixels,
|
||||
WEATHER_DETAIL_SIZE,
|
||||
WEATHER_IMAGE_SIZES,
|
||||
} from './source.js';
|
||||
@@ -199,3 +203,103 @@ test('image frames are read through the bounded image route', async () => {
|
||||
/Weather image HTTP 409/,
|
||||
);
|
||||
});
|
||||
|
||||
test('a feed without frame methods is no frame source', () => {
|
||||
assert.equal(weatherFrameSource(undefined), null);
|
||||
assert.equal(weatherFrameSource({ getSnapshot: async () => ({}) }), null);
|
||||
assert.equal(weatherFrameSource({ getFrameImage: 'no' }), null);
|
||||
});
|
||||
|
||||
test('a frame source forwards exactly the documented requests to its feed', async () => {
|
||||
const calls = [];
|
||||
const signal = new AbortController().signal;
|
||||
const feed = {
|
||||
getFrameImage: async (request) => {
|
||||
calls.push(['image', request]);
|
||||
return 'image';
|
||||
},
|
||||
getFrameTile: async (request) => {
|
||||
calls.push(['tile', request]);
|
||||
return null;
|
||||
},
|
||||
};
|
||||
const source = weatherFrameSource(feed);
|
||||
const size = { width: 4096, height: 2048 };
|
||||
assert.equal(
|
||||
await source.getImage({ product: 'radar', time: 't', size, signal }),
|
||||
'image',
|
||||
);
|
||||
const bbox = { west: -102, south: 34, east: -96, north: 37 };
|
||||
await source.getImage({ product: 'radar', time: 't', size, bbox, signal });
|
||||
assert.equal(
|
||||
await source.getTile({
|
||||
product: 'lightning',
|
||||
time: 't',
|
||||
z: 1,
|
||||
x: 2,
|
||||
y: 0,
|
||||
size: 256,
|
||||
signal,
|
||||
extra: true,
|
||||
}),
|
||||
null,
|
||||
);
|
||||
assert.deepEqual(calls, [
|
||||
['image', { product: 'radar', time: 't', size, bbox: null, signal }],
|
||||
['image', { product: 'radar', time: 't', size, bbox, signal }],
|
||||
[
|
||||
'tile',
|
||||
{ product: 'lightning', time: 't', z: 1, x: 2, y: 0, size: 256, signal },
|
||||
],
|
||||
]);
|
||||
const imagesOnly = weatherFrameSource({ getFrameImage: feed.getFrameImage });
|
||||
assert.equal(typeof imagesOnly.getImage, 'function');
|
||||
assert.equal(imagesOnly.getTile, undefined, 'tiles keep the tile route');
|
||||
const tilesOnly = weatherFrameSource({ getFrameTile: feed.getFrameTile });
|
||||
assert.equal(tilesOnly.getImage, undefined, 'images keep the image route');
|
||||
});
|
||||
|
||||
test('supplied pixels report their drawn size, draw at the origin and close once', (t) => {
|
||||
assert.deepEqual(weatherPixelSize({ width: 4, height: 2 }), {
|
||||
width: 4,
|
||||
height: 2,
|
||||
});
|
||||
assert.deepEqual(
|
||||
weatherPixelSize({
|
||||
codedWidth: 8,
|
||||
codedHeight: 8,
|
||||
displayWidth: 4,
|
||||
displayHeight: 2,
|
||||
}),
|
||||
{ width: 4, height: 2 },
|
||||
'a VideoFrame draws at its display size',
|
||||
);
|
||||
const had = Object.hasOwn(globalThis, 'ImageData');
|
||||
const previous = globalThis.ImageData;
|
||||
globalThis.ImageData = class ImageData {
|
||||
width = 1;
|
||||
height = 1;
|
||||
};
|
||||
t.after(() => {
|
||||
if (had) globalThis.ImageData = previous;
|
||||
else delete globalThis.ImageData;
|
||||
});
|
||||
const calls = [];
|
||||
const context = {
|
||||
drawImage: (...args) => calls.push(['drawImage', ...args]),
|
||||
putImageData: (...args) => calls.push(['putImageData', ...args]),
|
||||
};
|
||||
const bitmap = { width: 1, height: 1 };
|
||||
const data = new globalThis.ImageData();
|
||||
drawWeatherPixels(context, bitmap);
|
||||
drawWeatherPixels(context, data);
|
||||
assert.deepEqual(calls, [
|
||||
['drawImage', bitmap, 0, 0],
|
||||
['putImageData', data, 0, 0],
|
||||
]);
|
||||
let closes = 0;
|
||||
closeWeatherPixels({ close: () => closes++ });
|
||||
closeWeatherPixels(data);
|
||||
closeWeatherPixels(null);
|
||||
assert.equal(closes, 1);
|
||||
});
|
||||
@@ -78,8 +78,16 @@ function target(extra = {}) {
|
||||
},
|
||||
};
|
||||
}
|
||||
// What a canvas double encoded, by its bytes' text: a fetched tile's bytes
|
||||
// are "decoded" back to the canvas that made them.
|
||||
const encodedCanvases = new Map();
|
||||
function mockCanvas() {
|
||||
const canvas = { width: 0, height: 0 };
|
||||
canvas.convertToBlob = async () => {
|
||||
const id = `canvas:${encodedCanvases.size}`;
|
||||
encodedCanvases.set(id, canvas);
|
||||
return new Blob([id]);
|
||||
};
|
||||
canvas.getContext = () => ({
|
||||
setTransform(...matrix) {
|
||||
canvas.transforms = [...(canvas.transforms ?? []), matrix];
|
||||
@@ -169,6 +177,16 @@ function layerDriver(layer, createCanvas) {
|
||||
layer.spec.drawTile(tile, canvas);
|
||||
return Promise.resolve(canvas);
|
||||
}
|
||||
if (layer.spec.fetchTile) {
|
||||
// The renderer fetches through the hook, then decodes the bytes.
|
||||
const controller = new AbortController();
|
||||
box.abort = (reason) => controller.abort(reason);
|
||||
return layer.spec
|
||||
.fetchTile({ tile, url: layer.spec.url, signal: controller.signal })
|
||||
.then((answer) =>
|
||||
encodedCanvases.get(new TextDecoder().decode(answer.bytes)),
|
||||
);
|
||||
}
|
||||
return box.response?.promise;
|
||||
});
|
||||
},
|
||||
@@ -2420,3 +2438,246 @@ test('disabled weather releases its camera listener and re-enabling binds only o
|
||||
h.layer.destroy();
|
||||
assert.equal(h.moveEnd.size, 0);
|
||||
});
|
||||
|
||||
const suppliedTile = (size = 256) => ({
|
||||
width: size,
|
||||
height: size,
|
||||
closes: 0,
|
||||
close() {
|
||||
this.closes++;
|
||||
},
|
||||
});
|
||||
|
||||
test('a frame source supplies regional tiles in place of the tile route, through the readiness wrapper', async () => {
|
||||
let now = 0;
|
||||
const requests = [];
|
||||
const supplied = [];
|
||||
const h = renderingHarness({
|
||||
now: () => now,
|
||||
fetchImpl: () => assert.fail('supplied tiles are not fetched'),
|
||||
frameSource: {
|
||||
getTile: async (request) => {
|
||||
requests.push(request);
|
||||
const tile = suppliedTile();
|
||||
supplied.push(tile);
|
||||
return tile;
|
||||
},
|
||||
},
|
||||
});
|
||||
h.viewer.scene.globe.tilesLoaded = false;
|
||||
const loaded = h.rendering.setFrame(snapshot, times[0]);
|
||||
assert.equal(h.providers.length, 1);
|
||||
const [provider] = h.providers;
|
||||
assert.equal(typeof provider.spec.fetchTile, 'function', 'not the route');
|
||||
assert.equal(provider.spec.maxLevel, 6);
|
||||
assert.equal(provider.spec.maxConcurrentRequests, 6);
|
||||
const tile = await provider.requestImage(1, 0, 1, {});
|
||||
assert.equal(tile.width, 256);
|
||||
assert.equal(tile.source, supplied[0]);
|
||||
assert.equal(supplied[0].closes, 1);
|
||||
assert.equal(requests[0].product, 'radar');
|
||||
assert.equal(requests[0].time, times[0]);
|
||||
assert.deepEqual(
|
||||
[requests[0].z, requests[0].x, requests[0].y, requests[0].size],
|
||||
[1, 1, 0, 256],
|
||||
);
|
||||
assert.equal(h.rendering.getDiagnostics().loadedTiles, 1);
|
||||
now = 500;
|
||||
h.settle();
|
||||
assert.equal(await loaded, true);
|
||||
|
||||
const gate = deferred();
|
||||
let signal;
|
||||
const next = renderingHarness({
|
||||
frameSource: {
|
||||
getTile: (request) => {
|
||||
signal = request.signal;
|
||||
return gate.promise;
|
||||
},
|
||||
},
|
||||
});
|
||||
const staged = next.rendering.setFrame(snapshot, times[1]);
|
||||
const pending = next.providers[0].requestImage(0, 0, 0, {});
|
||||
next.rendering.clear();
|
||||
assert.equal(signal.aborted, true, 'clearing a frame aborts its tiles');
|
||||
const late = suppliedTile();
|
||||
gate.resolve(late);
|
||||
await assert.rejects(pending, { name: 'AbortError' });
|
||||
assert.equal(late.closes, 1);
|
||||
assert.equal(await staged, false);
|
||||
h.rendering.clear();
|
||||
});
|
||||
|
||||
test('a failed supplied tile fails the staged frame through the tile error', async () => {
|
||||
const h = renderingHarness({
|
||||
frameSource: {
|
||||
getTile: async () => {
|
||||
throw new Error('frame unavailable');
|
||||
},
|
||||
},
|
||||
});
|
||||
const staged = h.rendering.setFrame(snapshot, times[0]);
|
||||
const [provider] = h.providers;
|
||||
await assert.rejects(provider.requestImage(0, 0, 0, {}));
|
||||
provider.errorEvent.emit({ x: 0, y: 0, level: 0, error: {} });
|
||||
h.settle();
|
||||
assert.equal(await staged, false);
|
||||
assert.match(h.rendering.getDiagnostics().error, /Weather tiles unavailable/);
|
||||
h.rendering.clear();
|
||||
});
|
||||
|
||||
test("supplied regional infrared tiles get the transfer upright, as the route's do", async () => {
|
||||
const hadBitmap = Object.hasOwn(globalThis, 'ImageBitmap');
|
||||
const previous = globalThis.ImageBitmap;
|
||||
globalThis.ImageBitmap = class ImageBitmap {
|
||||
width = 256;
|
||||
height = 256;
|
||||
close() {}
|
||||
};
|
||||
try {
|
||||
const h = renderingHarness({
|
||||
frameSource: { getTile: async () => new globalThis.ImageBitmap() },
|
||||
});
|
||||
void h.rendering.setFrame(
|
||||
{ ...snapshot, product: 'clouds-regional' },
|
||||
times[0],
|
||||
);
|
||||
const [provider] = h.providers;
|
||||
const decoded = await provider.requestImage(0, 0, 0, {});
|
||||
const tile = await provider.spec.tileTransform(
|
||||
{ x: 0, y: 0, level: 0 },
|
||||
decoded,
|
||||
);
|
||||
assert.equal(tile.drawnWith, null, 'drawn upright, not flipped');
|
||||
assert.ok(tile.pixels, 'the infrared transfer ran');
|
||||
const empty = renderingHarness({
|
||||
frameSource: { getTile: async () => null },
|
||||
});
|
||||
void empty.rendering.setFrame(
|
||||
{ ...snapshot, product: 'clouds-regional' },
|
||||
times[0],
|
||||
);
|
||||
const transparent = await empty.providers[0].requestImage(0, 0, 0, {});
|
||||
assert.equal(transparent.width, 256, 'a null tile is still a drawn tile');
|
||||
h.rendering.clear();
|
||||
empty.rendering.clear();
|
||||
} finally {
|
||||
if (hadBitmap) globalThis.ImageBitmap = previous;
|
||||
else delete globalThis.ImageBitmap;
|
||||
}
|
||||
});
|
||||
|
||||
test('tiled prefetch asks the frame source for the same level 0/1 tiles and releases them', async (t) => {
|
||||
const requests = [];
|
||||
const supplied = [];
|
||||
const h = renderingHarness({
|
||||
fetchImpl: () => assert.fail('supplied tiles are not fetched'),
|
||||
frameSource: {
|
||||
getTile: async (request) => {
|
||||
requests.push(request);
|
||||
if (request.z === 0) return null;
|
||||
const tile = suppliedTile();
|
||||
supplied.push(tile);
|
||||
return tile;
|
||||
},
|
||||
},
|
||||
});
|
||||
t.after(() => h.rendering.clear());
|
||||
h.viewer.camera = {
|
||||
computeViewRectangle: () =>
|
||||
Cesium.Rectangle.fromDegrees(-120, 25, -100, 50),
|
||||
};
|
||||
assert.equal(await h.rendering.prefetch(snapshot, times[1]), true);
|
||||
assert.deepEqual(
|
||||
requests.map(({ product, time, z, x, y, size }) => [
|
||||
product,
|
||||
time,
|
||||
z,
|
||||
x,
|
||||
y,
|
||||
size,
|
||||
]),
|
||||
[
|
||||
['radar', times[1], 0, 0, 0, 256],
|
||||
['radar', times[1], 1, 0, 0, 256],
|
||||
],
|
||||
);
|
||||
assert.ok(requests.every(({ signal }) => signal instanceof AbortSignal));
|
||||
assert.equal(supplied[0].closes, 1);
|
||||
assert.equal(
|
||||
await h.rendering.prefetch(snapshot, times[1]),
|
||||
false,
|
||||
'same completed work is not repeated',
|
||||
);
|
||||
assert.equal(requests.length, 2);
|
||||
|
||||
const gate = deferred();
|
||||
let signal;
|
||||
const slow = renderingHarness({
|
||||
frameSource: {
|
||||
getTile: ({ signal: value }) => {
|
||||
signal = value;
|
||||
return gate.promise;
|
||||
},
|
||||
},
|
||||
});
|
||||
t.after(() => slow.rendering.clear());
|
||||
slow.viewer.camera = h.viewer.camera;
|
||||
const warm = slow.rendering.prefetch(snapshot, times[1]);
|
||||
slow.rendering.cancelPrefetch();
|
||||
assert.equal(signal.aborted, true, 'cancelling a prefetch aborts its tiles');
|
||||
gate.resolve(null);
|
||||
assert.equal(await warm, false);
|
||||
});
|
||||
|
||||
test('the global mosaic comes from the frame source image when present', async (t) => {
|
||||
const requests = [];
|
||||
const h = renderingHarness({
|
||||
fetchImpl: () => assert.fail('a supplied mosaic is not fetched'),
|
||||
decodeImage: () => assert.fail('a supplied mosaic is not decoded'),
|
||||
frameSource: {
|
||||
getImage: async (request) => {
|
||||
requests.push(request);
|
||||
return { width: 2048, height: 1024, close() {} };
|
||||
},
|
||||
},
|
||||
});
|
||||
t.after(() => h.rendering.clear());
|
||||
await showMosaic(h, times[0]);
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(requests[0].product, 'clouds');
|
||||
assert.deepEqual(requests[0].size, { width: 2048, height: 1024 });
|
||||
assert.equal(requests[0].bbox, null);
|
||||
assert.equal(h.rendering.getDiagnostics().mosaic.fetched, true);
|
||||
});
|
||||
|
||||
test('the layer hands rendering a frame source only when its feed is one', () => {
|
||||
const seen = [];
|
||||
const createRendering = (args) => {
|
||||
seen.push(args.frameSource);
|
||||
return {
|
||||
setAlpha() {},
|
||||
rehome() {},
|
||||
clear() {},
|
||||
getDiagnostics: () => ({}),
|
||||
};
|
||||
};
|
||||
const options = {
|
||||
documentRef: target({ hidden: false }),
|
||||
eventTarget: target(),
|
||||
matchMedia: () => target({ matches: false }),
|
||||
createRendering,
|
||||
};
|
||||
createWeatherLayer({
|
||||
...options,
|
||||
feed: { getSnapshot: async () => snapshot },
|
||||
}).init({});
|
||||
const getFrameTile = async () => null;
|
||||
createWeatherLayer({
|
||||
...options,
|
||||
feed: { getSnapshot: async () => snapshot, getFrameTile },
|
||||
}).init({});
|
||||
assert.equal(seen[0], null);
|
||||
assert.equal(typeof seen[1].getTile, 'function');
|
||||
assert.equal(seen[1].getImage, undefined);
|
||||
});
|
||||
Reference in new issue
Block a user