Merge branch 'main' into perf/imagery-stale-thumbnail-cancellation-20260929

# Conflicts:
#	docs/CURRENT-STATE.md
This commit is contained in:
German Khokhlov committed 2026-11-18 16:35:39 +04:00
commit 3348e3517e
2055 files changed
+320058 -46434

No files matched your search

+33 -34
View File
@@ -20,7 +20,7 @@ import {
PRODUCTS,
boxCentre,
boxFromPin,
boxFromRectangle,
boxFromDegrees,
boxSideKm,
dequantizeBox,
fitViewHeightM,
@@ -33,7 +33,14 @@ import {
viewTooLargeMessage,
} from './model.js';
import { msg, t } from '../../i18n/index.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import { READOUT_WORDS, displayDay, displayMetres } from './display.js';
import {
canvasOf,
findCamera,
findGlobe,
findQuery,
} from '../../render/rendererOf.js';
/**
* Quiet time after the last arrow key before the focused day previews, so a
@@ -66,10 +73,6 @@ const clampUnit = (value, fallback) => {
const boxSignature = (box) =>
box ? BOX_EDGES.map((edge) => Number(box[edge]).toFixed(6)).join(',') : '';
const sourceOf = (product) => PRODUCTS[product]?.source || null;
const toDegrees = (radians) => (radians * 180) / Math.PI;
const toRadians = (degrees) => (degrees * Math.PI) / 180;
const ellipsoidOf = (viewer) =>
viewer?.scene?.ellipsoid || viewer?.scene?.globe?.ellipsoid || null;
/**
* The ground under the canvas centre, in degrees; null when the centre is
@@ -78,20 +81,14 @@ const ellipsoidOf = (viewer) =>
* @returns {{ lon: number, lat: number } | null}
*/
function viewCentre(viewer) {
const ellipsoid = ellipsoidOf(viewer);
const canvas = viewer?.scene?.canvas;
const query = findQuery(viewer);
const canvas = canvasOf(viewer);
const width = Number(canvas?.clientWidth);
const height = Number(canvas?.clientHeight);
if (!ellipsoid?.cartesianToCartographic || !(width > 0) || !(height > 0))
return null;
const hit = viewer.camera?.pickEllipsoid?.(
{ x: width / 2, y: height / 2 },
ellipsoid,
);
const ground = hit ? ellipsoid.cartesianToCartographic(hit) : null;
return ground
? { lon: toDegrees(ground.longitude), lat: toDegrees(ground.latitude) }
: null;
if (!query || !(width > 0) || !(height > 0)) return null;
const hit = query.pickEllipsoid(width / 2, height / 2);
const ground = hit ? toLonLatH(hit) : null;
return ground ? { lon: ground.lon, lat: ground.lat } : null;
}
const modeFrom = (value) =>
MODES.includes(value)
@@ -102,13 +99,14 @@ const modeFrom = (value) =>
/**
* Create the layer.
* @param {{ catalog?: { searchHls: Function }, renderer: object, thumbnails: object, host?: Function, now?: () => Date, days?: number, setTimeoutImpl?: Function, clearTimeoutImpl?: Function }} options
* @param {{ catalog?: { searchHls: Function }, renderer: object, thumbnails: object, host?: Function, globeOf?: Function, now?: () => Date, days?: number, setTimeoutImpl?: Function, clearTimeoutImpl?: Function }} options
*/
export function createRecentImageryLayer({
catalog = { searchHls },
renderer,
thumbnails,
host = resolveImageryHost,
globeOf = findGlobe,
now = () => new Date(),
days = CATALOG_DAYS,
setTimeoutImpl = (fn, ms) => globalThis.setTimeout(fn, ms),
@@ -379,7 +377,13 @@ export function createRecentImageryLayer({
const changed =
next.collection !== _hostInfo.collection || next.kind !== _hostInfo.kind;
_hostInfo = next;
renderer.rebind(next);
// The layers drape through the viewer's globe port, on the tileset too
// when that is the host.
renderer.rebind({
...next,
globe: next.kind === 'none' ? null : globeOf(_viewer),
tileset: next.kind === 'tileset' ? _tileset : null,
});
return changed;
}
@@ -970,10 +974,10 @@ export function createRecentImageryLayer({
* @returns {boolean}
*/
useCurrentView(viewer = _viewer) {
const rectangle = viewer?.camera?.computeViewRectangle?.();
const rectangle = findCamera(viewer)?.viewRectangle();
if (!rectangle)
return refuseBox('Point the camera at the ground to use the view');
const box = boxFromRectangle(rectangle);
const box = boxFromDegrees(rectangle);
if (validateBox(box).reason === 'too-large') {
const { width, height } = boxSideKm(box);
return refuseBox(
@@ -992,24 +996,19 @@ export function createRecentImageryLayer({
*/
zoomToFit() {
const target = _boxError ? _refusalTarget : null;
const camera = _viewer?.camera;
const ellipsoid = ellipsoidOf(_viewer);
if (!target || !camera?.flyTo || !ellipsoid?.cartographicToCartesian)
return null;
const canvas = _viewer.scene?.canvas;
// No camera port: a viewer of the caller's own whose renderer did not
// bring the camera factory (GEV's own imagery renderer does).
const port = findCamera(_viewer);
if (!target || !port) return null;
const canvas = canvasOf(_viewer);
const height = fitViewHeightM({
width: canvas?.clientWidth,
height: canvas?.clientHeight,
fovy: camera.frustum?.fovy,
fovy: port.pose().fovy,
});
camera.flyTo({
destination: ellipsoid.cartographicToCartesian({
longitude: toRadians(target.lon),
latitude: toRadians(target.lat),
height,
}),
port.flyTo(fromDegrees(target.lon, target.lat, height), {
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
duration: ZOOM_FIT_SECONDS,
durationS: ZOOM_FIT_SECONDS,
});
return height;
},
+63 -18
View File
@@ -1,8 +1,10 @@
import test from 'node:test';
import * as Cesium from 'cesium';
import assert from 'node:assert/strict';
import { NO_IMAGERY_HOST } from '../../maps/imageryHost.js';
import { acquireImageryComparison } from '../../maps/imageryComparison.js';
import { MapSourceController } from '../../maps/controller.js';
import '../../render/cesium/mapEngine.js';
import { createDefaultMapSources } from '../../maps/defaultSources.js';
import { resetPointerOwnership } from '../../data/inputOwnership.js';
import { initImageryBoxTool } from '../../ui/imageryBoxTool.js';
@@ -12,6 +14,8 @@ import {
SPLIT_PUBLISH_MS,
createRecentImageryLayer,
} from './index.js';
import { createImageryBoxPreview } from './rendering.js';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import {
BOX,
CANDIDATES,
@@ -24,6 +28,8 @@ import {
manualTimers,
settle,
} from './testDoubles.mjs';
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
import { fakeSceneQuery } from '../../testSupport/fakeCesiumScene.mjs';
const NOW = new Date('2026-09-21T15:00:00Z');
const LINK_BOX = {
@@ -112,6 +118,8 @@ function fixture({
hostKind = 'globe',
controller = fakeController(),
viirs = true,
globeOf,
ports = () => ({}),
} = {}) {
const renderer = fakeRenderer();
const thumbnails = fakeThumbnails();
@@ -127,12 +135,14 @@ function fixture({
collection: collections[hostState.kind],
kind: hostState.kind,
}),
...(globeOf && { globeOf }),
now: () => NOW,
setTimeoutImpl: timers.setTimeoutImpl,
clearTimeoutImpl: timers.clearTimeoutImpl,
});
if (viirs) layer.setSources({ viirs: true });
const viewer = { camera: {} };
bindFakeCesiumCamera(viewer, ports(viewer));
const reasons = [];
layer.subscribe((snapshot, reason) => reasons.push(reason));
layer.init(viewer);
@@ -826,6 +836,32 @@ test('without a host the drapes hide and say so; the stats poll rebinds when no
assert.equal(f.owned().a.kind, 'tileset');
});
test("the renderer is bound with the viewer's globe port, and the attached tileset while that is the host", async () => {
const globe = { name: 'globe port' };
const asked = [];
const f = fixture({
globeOf: (viewer) => {
asked.push(viewer);
return globe;
},
});
await f.ready();
const last = () => f.renderer.hosts.at(-1);
assert.equal(last().globe, globe);
assert.equal(last().tileset, null, 'a globe host carries no tileset');
assert.ok(asked.every((viewer) => viewer === f.viewer));
const tileset = { name: 'photoreal' };
f.hostState.kind = 'tileset';
f.layer.attachTileset(tileset);
assert.equal(last().kind, 'tileset');
assert.equal(last().globe, globe);
assert.equal(last().tileset, tileset);
f.hostState.kind = 'none';
f.layer.getStats();
assert.equal(last().globe, null, 'no host, no port');
f.layer.destroy();
});
test('a controller subscription moves the drape to the new host on every settled switch', async () => {
const listeners = new Set();
const controller = {
@@ -964,8 +1000,11 @@ test('USE VIEW takes the camera rectangle and refuses a view over the cap instea
});
test('ZOOM IN: an oversized box or view flies top-down to its centre at the height whose view is 400 km wide', () => {
const f = fixture();
// The renderer's query port picks the ellipsoid through the camera's own.
const f = fixture({ ports: (viewer) => ({ query: fakeSceneQuery(viewer) }) });
const flights = [];
const landing = (i) =>
Cesium.Ellipsoid.WGS84.cartesianToCartographic(flights[i].destination);
const deg = (rad) => (rad * 180) / Math.PI;
const rad = (value) => (value * Math.PI) / 180;
// A 1000 × 500 canvas with a 60° horizontal FOV.
@@ -973,20 +1012,25 @@ test('ZOOM IN: an oversized box or view flies top-down to its centre at the heig
const expected = 400_000 / (2 * Math.tan(Math.PI / 6));
let centreHit = null;
Object.assign(f.viewer, {
scene: {
canvas: { clientWidth: 1000, clientHeight: 500 },
ellipsoid: {
cartographicToCartesian: (c) => ({ ...c, cartesian: true }),
cartesianToCartographic: (c) => c && { ...c },
},
},
canvas: { clientWidth: 1000, clientHeight: 500 },
});
Object.assign(f.viewer.camera, {
frustum: { fovy },
flyTo: (options) => flights.push(options),
pickEllipsoid: (position) => {
assert.deepEqual(position, { x: 500, y: 250 }, 'the canvas centre');
return centreHit;
assert.deepEqual(
[position.x, position.y],
[500, 250],
'the canvas centre',
);
return (
centreHit &&
Cesium.Cartesian3.fromRadians(
centreHit.longitude,
centreHit.latitude,
centreHit.height,
)
);
},
});
f.layer.enable();
@@ -999,9 +1043,9 @@ test('ZOOM IN: an oversized box or view flies top-down to its centre at the heig
assert.ok(Math.abs(height - expected) < 1e-6, String(height));
assert.equal(flights.length, 1);
const [flight] = flights;
assert.ok(Math.abs(deg(flight.destination.longitude) - 10) < 1e-9);
assert.ok(Math.abs(deg(flight.destination.latitude) - 10) < 1e-9);
assert.equal(flight.destination.height, height);
assert.ok(Math.abs(deg(landing(0).longitude) - 10) < 1e-9);
assert.ok(Math.abs(deg(landing(0).latitude) - 10) < 1e-9);
assert.ok(Math.abs(landing(0).height - height) < 1e-6);
assert.deepEqual(flight.orientation, {
heading: 0,
pitch: -Math.PI / 2,
@@ -1019,14 +1063,14 @@ test('ZOOM IN: an oversized box or view flies top-down to its centre at the heig
assert.equal(f.layer.useCurrentView(), false);
assert.equal(f.snap().zoomToFit, true);
f.layer.zoomToFit();
assert.ok(Math.abs(deg(flights[1].destination.longitude) + 97) < 1e-9);
assert.ok(Math.abs(deg(flights[1].destination.latitude) - 31) < 1e-9);
assert.ok(Math.abs(deg(landing(1).longitude) + 97) < 1e-9);
assert.ok(Math.abs(deg(landing(1).latitude) - 31) < 1e-9);
// Sky at the centre: the view rectangle's centre instead.
centreHit = null;
f.layer.useCurrentView();
f.layer.zoomToFit();
assert.ok(Math.abs(deg(flights[2].destination.longitude) + 98) < 1e-9);
assert.ok(Math.abs(deg(flights[2].destination.latitude) - 30) < 1e-9);
assert.ok(Math.abs(deg(landing(2).longitude) + 98) < 1e-9);
assert.ok(Math.abs(deg(landing(2).latitude) - 30) < 1e-9);
// The box tool's own oversized drag carries its box.
f.layer.reportBoxRefusal('Box is 2,226 km wide · limit 1,000 km', {
west: 0,
@@ -1411,7 +1455,8 @@ test('with SELECT BOX armed, Escape clears the preview first and the next Escape
const cancels = [];
const tool = initImageryBoxTool({
viewer: fakes.viewer,
cesium: fakes.cesium,
createPreview: (viewer, dragBox) =>
createImageryBoxPreview(viewer, dragBox, { draw: fakeDrawPort() }),
pickWorld: fakes.pickWorld,
documentRef: fakes.documentRef,
onBox: (box) => f.layer.setBox(box),
+5
View File
@@ -237,6 +237,11 @@ function mapBox(box, fn) {
});
}
/** Degrees box from a degrees rectangle (the camera port's `viewRectangle`). */
export function boxFromDegrees(rectangle) {
return mapBox(rectangle, (degrees) => degrees);
}
/** Degrees box from a radians rectangle (Cesium `Rectangle` shape). */
export function boxFromRectangle(rectangle) {
return mapBox(rectangle, (radians) => (Number(radians) * 180) / Math.PI);
+189 -92
View File
@@ -1,22 +1,28 @@
/**
* Draped-imagery renderer for the Recent Imagery layer: at most two GIBS
* imagery layers (slot `a`, left of a swipe; slot `b`, right) on whichever
* host the map stack offers. Against the basemap slot `a` splits left and
* slot `b` stays empty. Every layer is removed from the collection that owns it, so a
* host switch or a replaced image never strands one. Tile requests pass a
* small semaphore of our own; Cesium's global request limits stay untouched.
* imagery layers (slot `a`, left of a swipe; slot `b`, right) through the
* renderer's globe port, draped on whichever surface the map stack draws.
* Against the basemap slot `a` splits left and slot `b` stays empty. Tile
* requests pass a small semaphore of our own, shared by both slots, through
* each layer's admission hook; the renderer's own request limits stay
* untouched.
*/
import * as Cesium from 'cesium';
// The imagery drapes through the globe port and the box preview draws
// through `drawOf`, both on the renderer's ports: a viewer with no renderer
// bound gets them once its owner has loaded the package's
// `./render/cesium/unbound` export. A tileset host is marked as a base the
// globe port drapes on (`markBaseTileset`).
import { fromDegrees } from '../../geo/ellipsoid.js';
import { markBaseTileset } from '../../render/baseTilesets.js';
import { drawOf } from '../../render/rendererOf.js';
import { PRODUCTS, gibsTemplate } from './model.js';
const SLOT_IDS = ['a', 'b'];
const SPLIT_ENUM = { left: 'LEFT', right: 'RIGHT', none: 'NONE' };
const NO_HOST = Object.freeze({ collection: null, kind: 'none' });
const SPLITS = new Set(['left', 'right', 'none']);
const NO_HOST = Object.freeze({ collection: null, kind: 'none', globe: null });
/** Render reason for a deferred or settled tile request. */
/** Render reason for a settled tile request. */
export const TILE_RENDER_REASON = 'recent-imagery-tiles';
/** Delay before the one frame that retries tiles Cesium itself deferred. */
export const TILE_RETRY_DELAY_MS = 250;
function clampAlpha(value) {
const alpha = Number(value);
@@ -27,18 +33,13 @@ const boxKey = (box) =>
[box.west, box.south, box.east, box.north].map(Number).join(',');
/**
* Gate a provider's `requestImage` through the semaphore. Returning
* `undefined` tells Cesium to retry on a later frame, but under
* `requestRenderMode` there is no later frame unless something asks — and a
* deferral must never ask for one itself: the retried tile would defer again
* and ask again, keeping the scene rendering every frame. So a request that
* finds our semaphore full asks for nothing (the request holding the slot
* asks for one frame when it settles), and a request the provider itself
* deferred goes through the one coalesced delayed retry.
* Admit a tile request while the semaphore has room. A request that finds
* it full is deferred and asks for no frame itself: the request holding the
* slot asks for one as it settles. One the renderer itself defers frees its
* slot at once, and the renderer asks again on a later frame.
*/
function admitTileRequests(provider, admission, requestRender, retry) {
const original = provider.requestImage.bind(provider);
provider.requestImage = (x, y, level, request) => {
function admitTileRequests(admission, requestRender) {
return (_tile, issue) => {
if (admission.inFlight >= admission.limit) return undefined;
admission.inFlight += 1;
const release = () => {
@@ -46,14 +47,13 @@ function admitTileRequests(provider, admission, requestRender, retry) {
};
let promise;
try {
promise = original(x, y, level, request);
promise = issue();
} catch (error) {
release();
throw error;
}
if (!promise) {
release();
retry.schedule();
return undefined;
}
return Promise.resolve(promise).finally(() => {
@@ -61,95 +61,62 @@ function admitTileRequests(provider, admission, requestRender, retry) {
requestRender(TILE_RENDER_REASON);
});
};
return provider;
}
/**
* Create the renderer.
* @param {{ cesium?: object, maxTileRequests?: number, requestRender?: (reason: string) => void, setTimeoutImpl?: Function, clearTimeoutImpl?: Function }} [options]
* Create the renderer. The host it is bound to (`rebind`) carries the
* viewer's globe port.
* @param {{ tileTemplate?: Function, credit?: string, maxTileRequests?: number, requestRender?: (reason: string) => void }} [options]
*/
export function createRecentImageryRenderer({
cesium = Cesium,
tileTemplate = gibsTemplate,
credit = 'NASA GIBS',
maxTileRequests = 6,
requestRender = () => {},
setTimeoutImpl = (fn, ms) => globalThis.setTimeout(fn, ms),
clearTimeoutImpl = (id) => globalThis.clearTimeout(id),
} = {}) {
let host = NO_HOST;
let destroyed = false;
const admission = { limit: maxTileRequests, inFlight: 0 };
/** @type {Record<'a'|'b', null | { layer: object, collection: object, candidate: object, box: object, alpha: number, split: string }>} */
/** @type {Record<'a'|'b', null | { layer: object, globe: object, candidate: object, box: object, alpha: number, split: string }>} */
const owned = { a: null, b: null };
const admit = admitTileRequests(admission, requestRender);
// One timer for both slots: any number of upstream deferrals while it is
// armed share the same single retry frame.
let retryTimer = null;
const retry = {
schedule() {
if (retryTimer !== null) return;
retryTimer = setTimeoutImpl(() => {
retryTimer = null;
if (!destroyed) requestRender(TILE_RENDER_REASON);
}, TILE_RETRY_DELAY_MS);
},
cancel() {
if (retryTimer !== null) clearTimeoutImpl(retryTimer);
retryTimer = null;
},
};
function createProvider(candidate, box) {
const spec = PRODUCTS[candidate.product];
const provider = new cesium.UrlTemplateImageryProvider({
function specFor(candidate, box) {
const product = PRODUCTS[candidate.product];
return {
kind: 'xyz',
url: tileTemplate(candidate.product, candidate.day),
subdomains: ['a', 'b', 'c'],
minimumLevel: 0,
maximumLevel: spec.maxLevel,
tilingScheme: new cesium.WebMercatorTilingScheme(),
rectangle: cesium.Rectangle.fromDegrees(
box.west,
box.south,
box.east,
box.north,
),
credit,
hasAlphaChannel: spec.format === 'png',
});
return admitTileRequests(provider, admission, requestRender, retry);
tiling: 'webMercator',
minLevel: 0,
maxLevel: product.maxLevel,
rectangle: {
west: box.west,
south: box.south,
east: box.east,
north: box.north,
},
credit: { text: credit },
admit,
};
}
function removeOwned(slotId) {
const record = owned[slotId];
if (!record) return false;
owned[slotId] = null;
try {
record.collection.remove(record.layer, true);
} catch {
/* the collection is already gone */
}
record.layer.remove();
return true;
}
function applyLook(record) {
record.layer.alpha = record.alpha;
record.layer.splitDirection =
cesium.SplitDirection?.[SPLIT_ENUM[record.split] || 'NONE'] ?? 0;
record.layer.split = SPLITS.has(record.split) ? record.split : 'none';
}
function mount(slotId, { candidate, box, alpha, split }) {
const layer = host.collection.addImageryProvider(
createProvider(candidate, box),
);
owned[slotId] = {
layer,
collection: host.collection,
candidate,
box,
alpha,
split,
};
const layer = host.globe.imagery.add(specFor(candidate, box));
owned[slotId] = { layer, globe: host.globe, candidate, box, alpha, split };
applyLook(owned[slotId]);
}
@@ -170,7 +137,7 @@ export function createRecentImageryRenderer({
{ alpha = 1, splitDirection = 'none' } = {},
) {
if (destroyed || !candidate?.key || !box) return false;
if (!host.collection) {
if (!host.globe) {
removeOwned(slotId);
return false;
}
@@ -178,7 +145,7 @@ export function createRecentImageryRenderer({
const look = { alpha: clampAlpha(alpha), split: splitDirection };
if (
current &&
current.collection === host.collection &&
current.globe === host.globe &&
current.candidate.key === candidate.key &&
boxKey(current.box) === boxKey(box)
) {
@@ -214,19 +181,25 @@ export function createRecentImageryRenderer({
},
/**
* Move every owned layer to a new host. Layers are rebuilt there, never
* re-parented, so the old collection is left as it was found.
* @param {{ collection: object | null, kind: string }} nextHost
* Follow the map stack's host. The globe port moves the owned layers
* between the globe and the 3D tiles itself; without a host they go,
* and a new globe port gets them rebuilt.
* @param {{ collection: object | null, kind: string, globe?: object | null, tileset?: object | null }} nextHost
*/
rebind(nextHost) {
host = nextHost || NO_HOST;
let changed = false;
const previous = host;
host =
nextHost && nextHost.kind !== 'none' && nextHost.globe
? nextHost
: NO_HOST;
if (host.kind === 'tileset') markBaseTileset(host.tileset);
let changed = host.kind !== previous.kind && Boolean(owned.a || owned.b);
for (const slotId of SLOT_IDS) {
const record = owned[slotId];
if (!record || record.collection === host.collection) continue;
if (!record || record.globe === host.globe) continue;
removeOwned(slotId);
changed = true;
if (host.collection && !destroyed) mount(slotId, record);
if (host.globe && !destroyed) mount(slotId, record);
}
if (changed) requestRender('recent-imagery-rebind');
},
@@ -257,7 +230,6 @@ export function createRecentImageryRenderer({
destroy() {
if (destroyed) return;
destroyed = true;
retry.cancel();
let changed = false;
for (const slotId of SLOT_IDS) changed = removeOwned(slotId) || changed;
host = NO_HOST;
@@ -265,3 +237,128 @@ export function createRecentImageryRenderer({
},
};
}
const PREVIEW_STROKE = Object.freeze([139 / 255, 233 / 255, 1]);
/** Fill alpha and outline alpha of the box being dragged. */
const PREVIEW_FILL_ALPHA = 0.12;
const PREVIEW_LINE_ALPHA = 0.95;
/** Each preview's draw sets have ids of their own. */
let previewSeq = 0;
/** A box with no area has no fill: a press, or a drag along one axis. */
const hasArea = (box) =>
Boolean(box) && box.east > box.west && box.north > box.south;
/** A box with no extent draws nothing: a press that has not moved yet. */
const hasExtent = (box) =>
Boolean(box) && (box.east > box.west || box.north > box.south);
/**
* The box tool's preview: the box being dragged, a translucent fill and a
* dashed outline on the ground, drawn through the draw port. Each change
* moves them where they are (the port draws a moved ground fill and a moved
* draped line in the frame they move), so the box shows every frame of a
* drag.
* @param {object} viewer
* @param {() => ({west: number, south: number, east: number, north: number}|null)} dragBox
* Degrees, or null while no drag is live.
* @param {{draw?: import('../../render/contract/draw').DrawPort}} [options]
* The draw port (tests pass a double); the viewer's by default.
* @returns {{setVisible: (visible: boolean) => void, changed: () => void, destroy: () => Promise<void>}}
*/
export function createImageryBoxPreview(
viewer,
dragBox,
{ draw = drawOf(viewer) } = {},
) {
previewSeq += 1;
const fills = draw.shapes({
id: `recent-imagery-box:${previewSeq}:fill`,
pickable: false,
});
const outlines = draw.lines({
id: `recent-imagery-box:${previewSeq}:outline`,
pickable: false,
});
let visible = false;
let destroyed = false;
// The sets go at once; every caller gets the same settled promise.
const gone = Promise.resolve();
// The last box drawn, and the last with an area: a box without one keeps
// it, hidden, so the next one moves it rather than draw it anew.
let drawn = null;
let filled = null;
function drawFill(box, show) {
const { west, south, east, north } = box;
fills.upsert([
{
id: 'box',
geometry: { kind: 'rectangle', rect: { west, south, east, north } },
fill: [...PREVIEW_STROKE, PREVIEW_FILL_ALPHA],
height: 'clampGround',
clampTo: 'both',
show,
},
]);
}
function drawEdge(box, show) {
const { west, south, east, north } = box;
// A rectangle has no dashed edge on the ground, so the outline is a
// draped line traced round the same corners; a drag along one axis
// draws it as a line along the drag, as the fill has no area.
outlines.upsert([
{
id: 'edge',
positions: [
fromDegrees(west, south),
fromDegrees(east, south),
fromDegrees(east, north),
fromDegrees(west, north),
fromDegrees(west, south),
],
widthPx: 2,
mode: 'draped',
clampTo: 'both',
style: {
kind: 'dash',
color: [...PREVIEW_STROKE, PREVIEW_LINE_ALPHA],
length: 12,
},
show,
},
]);
}
function update() {
if (destroyed) return;
const box = visible ? dragBox() : null;
if (hasArea(box)) {
filled = { ...box };
drawFill(filled, true);
} else if (filled) drawFill(filled, false);
if (hasExtent(box)) {
drawn = { ...box };
drawEdge(drawn, true);
} else if (drawn) drawEdge(drawn, false);
}
return {
setVisible(on) {
visible = Boolean(on);
update();
},
/** The box moved: draw it again. */
changed: update,
/** Take the preview away; resolves once it is gone. */
destroy() {
if (!destroyed) {
destroyed = true;
fills.dispose();
outlines.dispose();
}
return gone;
},
};
}
+173 -129
View File
@@ -2,86 +2,53 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import {
TILE_RENDER_REASON,
TILE_RETRY_DELAY_MS,
createImageryBoxPreview,
createRecentImageryRenderer,
} from './rendering.js';
import { BOX, manualTimers } from './testDoubles.mjs';
/** A provider whose tile requests stay pending until the test settles them. */
class UrlTemplateImageryProvider {
constructor(options) {
this.options = options;
this.calls = [];
this.pending = [];
}
requestImage(x, y, level) {
this.calls.push([x, y, level]);
return new Promise((resolve) => this.pending.push(resolve));
}
}
function fakeCesium(requestImage) {
class Provider extends UrlTemplateImageryProvider {}
if (requestImage) Provider.prototype.requestImage = requestImage;
return {
UrlTemplateImageryProvider: Provider,
WebMercatorTilingScheme: class {},
Rectangle: {
fromDegrees: (west, south, east, north) => ({ west, south, east, north }),
},
SplitDirection: { LEFT: -1, NONE: 0, RIGHT: 1 },
};
}
function fakeCollection() {
const layers = [];
return {
layers,
addImageryProvider(provider) {
const layer = { provider, alpha: 1, splitDirection: 0 };
layers.push(layer);
return layer;
},
remove(layer, destroy) {
layers.splice(layers.indexOf(layer), 1);
layer.destroyed = destroy;
},
};
}
import { BOX } from './testDoubles.mjs';
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
const S30 = { key: 'S30:2026-09-18', product: 'S30', day: '2026-09-18' };
const L30 = { key: 'L30:2026-09-16', product: 'L30', day: '2026-09-16' };
const VIIRS = { key: 'VIIRS:2026-09-20', product: 'VIIRS', day: '2026-09-20' };
function fixture({ requestImage, maxTileRequests, ...options } = {}) {
const renders = [];
const timers = manualTimers();
const renderer = createRecentImageryRenderer({
...options,
cesium: fakeCesium(requestImage),
maxTileRequests,
requestRender: (reason) => renders.push(reason),
setTimeoutImpl: timers.setTimeoutImpl,
clearTimeoutImpl: timers.clearTimeoutImpl,
});
const globe = fakeCollection();
renderer.rebind({ collection: globe, kind: 'globe' });
const tileFrames = () =>
renders.filter((reason) => reason === TILE_RENDER_REASON).length;
return { renderer, globe, renders, timers, tileFrames };
/** A tile fetch that stays pending until the test settles it. */
function pendingFetches() {
const pending = [];
const fetch = () => new Promise((resolve) => pending.push(resolve));
return { pending, fetch };
}
test('a slot drapes one GIBS provider bounded to the box; the same day only restyles it', () => {
function fixture({ maxTileRequests, ...options } = {}) {
const renders = [];
const renderer = createRecentImageryRenderer({
...options,
maxTileRequests,
requestRender: (reason) => renders.push(reason),
});
const globe = fakeGlobePort();
renderer.rebind({ collection: {}, kind: 'globe', globe });
const tileFrames = () =>
renders.filter((reason) => reason === TILE_RENDER_REASON).length;
return { renderer, globe, renders, tileFrames };
}
const tile = (x, level = 1) => ({ x, y: 0, level });
test('a slot drapes one GIBS layer bounded to the box; the same day only restyles it', () => {
const { renderer, globe, renders } = fixture();
assert.equal(renderer.showSlot('a', S30, BOX, { alpha: 0.8 }), true);
const [layer] = globe.layers;
assert.match(
layer.provider.options.url,
layer.spec.url,
/^https:\/\/gibs-\{s\}\.earthdata\.nasa\.gov\/.*HLS_S30.*\/2026-09-18\/GoogleMapsCompatible_Level12\/\{z\}\/\{y\}\/\{x\}\.png$/,
);
assert.deepEqual(layer.provider.options.subdomains, ['a', 'b', 'c']);
assert.equal(layer.provider.options.credit, 'NASA GIBS');
assert.deepEqual(layer.provider.options.rectangle, BOX);
assert.equal(layer.spec.kind, 'xyz');
assert.equal(layer.spec.tiling, 'webMercator');
assert.deepEqual(layer.spec.subdomains, ['a', 'b', 'c']);
assert.deepEqual(layer.spec.credit, { text: 'NASA GIBS' });
assert.deepEqual(layer.spec.rectangle, BOX);
assert.equal(layer.alpha, 0.8);
assert.deepEqual(renders, ['recent-imagery-show']);
assert.deepEqual(renderer.getOwned().a, {
@@ -92,16 +59,15 @@ test('a slot drapes one GIBS provider bounded to the box; the same day only rest
});
renderer.showSlot('a', S30, BOX, { alpha: 0.5, splitDirection: 'left' });
assert.deepEqual(globe.layers, [layer], 'the layer is reused');
assert.equal(layer.splitDirection, -1);
// A different day replaces the layer in its own collection.
assert.equal(layer.split, 'left');
// A different day replaces the layer.
renderer.showSlot('a', L30, BOX);
assert.equal(layer.destroyed, true);
assert.equal(layer.removed, true);
assert.equal(globe.layers.length, 1);
// VIIRS is a level-9 JPEG overview with no alpha channel.
// VIIRS is a level-9 overview.
renderer.showSlot('b', VIIRS, BOX, { splitDirection: 'right' });
assert.equal(globe.layers[1].provider.options.maximumLevel, 9);
assert.equal(globe.layers[1].provider.options.hasAlphaChannel, false);
assert.equal(globe.layers[1].splitDirection, 1);
assert.equal(globe.layers[1].spec.maxLevel, 9);
assert.equal(globe.layers[1].split, 'right');
renderer.setAlpha('b', 7);
assert.equal(globe.layers[1].alpha, 1, 'alpha clamps to 0–1');
});
@@ -120,80 +86,92 @@ test('rapid replacement never owns more than two layers', () => {
assert.equal(globe.layers.length, 0);
});
test('rebind rebuilds the owned layers on the new host and leaves the old one empty', () => {
const { renderer, globe } = fixture();
test('the renderer leaves the surface to the globe port; no host removes the layers; a new port rebuilds them', () => {
const { renderer, globe, renders } = fixture();
renderer.showSlot('a', S30, BOX, { alpha: 0.6, splitDirection: 'left' });
renderer.showSlot('b', L30, BOX, { splitDirection: 'right' });
const tileset = fakeCollection();
renderer.rebind({ collection: tileset, kind: 'tileset' });
assert.equal(globe.layers.length, 0);
assert.deepEqual(
tileset.layers.map((layer) => [layer.alpha, layer.splitDirection]),
[
[0.6, -1],
[1, 1],
],
const layers = [...globe.layers];
renders.length = 0;
renderer.rebind({ collection: {}, kind: 'tileset', globe, tileset: {} });
assert.deepEqual(globe.layers, layers, 'the port drapes them on the tiles');
assert.ok(
layers.every((layer) => layer.drapeOn === 'all'),
'the renderer never narrows where they drape',
);
assert.equal(renderer.getOwned().a.kind, 'tileset');
renderer.rebind({ collection: null, kind: 'none' });
assert.equal(tileset.layers.length, 0);
assert.deepEqual(renders, ['recent-imagery-rebind'], 'the move gets a frame');
renderer.rebind({ collection: {}, kind: 'globe', globe: null });
assert.equal(
globe.layers.length,
0,
'a host with no globe port drapes nothing',
);
assert.equal(renderer.showSlot('a', S30, BOX), false);
renderer.rebind({ collection: globe, kind: 'globe' });
renderer.showSlot('a', S30, BOX);
renderer.destroy();
renderer.rebind({ collection: {}, kind: 'globe', globe });
renderer.rebind({ collection: null, kind: 'none', globe });
assert.equal(globe.layers.length, 0);
assert.equal(renderer.showSlot('a', S30, BOX), false);
const other = fakeGlobePort();
renderer.rebind({ collection: {}, kind: 'globe', globe });
renderer.showSlot('a', S30, BOX, { alpha: 0.6, splitDirection: 'left' });
renderer.showSlot('b', L30, BOX, { splitDirection: 'right' });
renderer.rebind({ collection: {}, kind: 'globe', globe: other });
assert.equal(globe.layers.length, 0);
assert.deepEqual(
other.layers.map((layer) => [layer.alpha, layer.split]),
[
[0.6, 'left'],
[1, 'right'],
],
);
renderer.destroy();
assert.equal(other.layers.length, 0);
assert.equal(renderer.showSlot('a', S30, BOX), false, 'destroyed');
});
test('above the tile limit a request defers silently; its settlement asks for exactly one frame', async () => {
const { renderer, globe, timers, tileFrames } = fixture({
maxTileRequests: 1,
});
const { renderer, globe, tileFrames } = fixture({ maxTileRequests: 1 });
renderer.showSlot('a', S30, BOX);
const { provider } = globe.layers[0];
const first = provider.requestImage(0, 0, 1);
const [layer] = globe.layers;
const { pending, fetch } = pendingFetches();
const first = layer.request(tile(0), fetch);
assert.ok(first instanceof Promise);
for (let i = 1; i <= 120; i += 1)
assert.equal(provider.requestImage(i, 0, 1), undefined);
assert.equal(provider.calls.length, 1, 'deferred requests never go out');
assert.equal(layer.request(tile(i), fetch), undefined);
assert.equal(pending.length, 1, 'deferred requests never go out');
assert.equal(tileFrames(), 0, 'a deferral asks for no frame');
assert.equal(timers.armed(), 0);
provider.pending[0]('tile');
pending[0]('tile');
await first;
assert.equal(tileFrames(), 1, 'the settlement asks for the retry frame');
assert.ok(provider.requestImage(200, 0, 1) instanceof Promise);
assert.ok(layer.request(tile(200), fetch) instanceof Promise);
});
test('upstream deferrals from both slots share one delayed retry frame; destroy disarms it', () => {
let throwNext = false;
const { renderer, globe, timers, tileFrames } = fixture({
maxTileRequests: 1,
requestImage() {
if (throwNext) throw new Error('boom');
return undefined;
},
});
test('both slots share the budget; a renderer deferral or throw frees its slot', async () => {
const { renderer, globe, tileFrames } = fixture({ maxTileRequests: 1 });
renderer.showSlot('a', S30, BOX);
renderer.showSlot('b', L30, BOX);
for (const { provider } of globe.layers)
for (let i = 0; i < 40; i += 1)
assert.equal(provider.requestImage(i, 0, 0), undefined);
// Every deferral released its slot (the limit is one), and none asked
// for a frame of its own: one timer holds the single retry.
assert.equal(tileFrames(), 0);
assert.equal(timers.armed(), 1);
assert.equal([...timers.pending.values()][0].ms, TILE_RETRY_DELAY_MS);
timers.flush();
const [a, b] = globe.layers;
const { pending, fetch } = pendingFetches();
const held = a.request(tile(0), fetch);
assert.equal(b.request(tile(0), fetch), undefined, 'the other slot waits');
pending[0]('tile');
await held;
// The renderer itself defers: the slot is free at once.
for (let i = 0; i < 40; i += 1)
assert.equal(
b.request(tile(i), () => undefined),
undefined,
);
assert.throws(
() =>
a.request(tile(0), () => {
throw new Error('boom');
}),
/boom/,
);
assert.ok(b.request(tile(1), fetch) instanceof Promise, 'still room');
assert.equal(tileFrames(), 1);
// A throwing provider releases its slot too.
throwNext = true;
assert.throws(() => globe.layers[0].provider.requestImage(0, 0, 0), /boom/);
throwNext = false;
globe.layers[0].provider.requestImage(0, 0, 0);
assert.equal(timers.armed(), 1, 'the next deferral arms a fresh timer');
renderer.destroy();
assert.equal(timers.armed(), 0, 'destroy disarms the retry');
assert.equal(tileFrames(), 1);
});
test('against the basemap slot a splits left with no second layer, and leaving the swipe only restyles it', () => {
@@ -201,12 +179,12 @@ test('against the basemap slot a splits left with no second layer, and leaving t
renderer.showSlot('a', S30, BOX, { splitDirection: 'left' });
renderer.hideSlot('b');
assert.equal(globe.layers.length, 1, 'the basemap is the right side');
assert.equal(globe.layers[0].splitDirection, -1);
assert.equal(globe.layers[0].split, 'left');
assert.equal(renderer.getOwned().b, null);
const [layer] = globe.layers;
renderer.showSlot('a', S30, BOX, { splitDirection: 'none' });
assert.deepEqual(globe.layers, [layer], 'no rebuild for a new look');
assert.equal(layer.splitDirection, 0);
assert.equal(layer.split, 'none');
assert.deepEqual(renders, ['recent-imagery-show', 'recent-imagery-look']);
});
@@ -219,11 +197,77 @@ test('replacement imagery uses source-owned tile URLs and credit and tears down
assert.equal(renderer.showSlot('a', S30, BOX), true);
const layer = globe.layers[0];
assert.equal(
layer.provider.options.url,
layer.spec.url,
'https://tiles.example/S30/2026-09-18/{z}/{x}/{y}',
);
assert.equal(layer.provider.options.credit, 'Example imagery');
assert.deepEqual(layer.spec.credit, { text: 'Example imagery' });
renderer.destroy();
assert.equal(globe.layers.length, 0);
assert.equal(layer.destroyed, true);
assert.equal(layer.removed, true);
});
test('the box preview draws a ground fill and a draped dashed edge, hidden rather than dropped between drags', async () => {
const draw = fakeDrawPort();
let box = null;
const preview = createImageryBoxPreview({}, () => box, { draw });
const sets = [...draw.sets.values()];
assert.deepEqual(
sets.map((r) => [r.kind, r.spec.pickable]),
[
['shapes', false],
['lines', false],
],
);
const [fills, lines] = sets;
preview.setVisible(true);
assert.equal(fills.items.size, 0, 'no box yet');
box = { west: -98, south: 30, east: -98, north: 30 };
preview.changed();
assert.equal(fills.items.size, 0, 'a press draws nothing');
assert.equal(lines.items.size, 0);
// Dragged along one axis: the edge draws as a line, the fill has no area.
box = { west: -98, south: 30, east: -97.9, north: 30 };
preview.changed();
assert.equal(fills.items.size, 0, 'no fill without an area');
assert.equal(lines.items.get('edge').show, true, 'the edge along the drag');
box = { west: -98, south: 30, east: -97.9, north: 30.1 };
preview.changed();
const fill = fills.items.get('box');
assert.deepEqual(fill.geometry.rect, box);
assert.equal(fill.height, 'clampGround');
assert.equal(fill.clampTo, 'both');
assert.deepEqual(fill.fill, [139 / 255, 233 / 255, 1, 0.12]);
assert.equal(fill.show, true);
const edge = lines.items.get('edge');
assert.equal(edge.mode, 'draped');
assert.equal(edge.clampTo, 'both');
assert.equal(edge.widthPx, 2);
assert.deepEqual(edge.style, {
kind: 'dash',
color: [139 / 255, 233 / 255, 1, 0.95],
length: 12,
});
assert.equal(edge.positions.length, 5, 'round the corners and back');
assert.deepEqual(edge.positions[0], edge.positions[4]);
preview.setVisible(false);
assert.equal(fills.items.get('box').show, false, 'hidden, kept to move');
assert.equal(lines.items.get('edge').show, false);
// The next drag moves it and shows it again.
box = { west: -97, south: 31, east: -96.5, north: 31.5 };
preview.setVisible(true);
assert.deepEqual(fills.items.get('box').geometry.rect, box);
assert.equal(fills.items.get('box').show, true);
assert.equal(lines.items.get('edge').show, true);
// A press with no extent hides the last box.
box = { west: -97, south: 31, east: -97, north: 31 };
preview.changed();
assert.equal(fills.items.get('box').show, false);
assert.equal(lines.items.get('edge').show, false);
const gone = preview.destroy();
assert.equal(preview.destroy(), gone, 'the same promise every time');
await gone;
assert.ok(fills.disposed && lines.disposed);
// Gone: changes after do nothing.
box = { west: -96, south: 32, east: -95, north: 33 };
assert.doesNotThrow(() => preview.changed());
});
+21 -38
View File
@@ -3,6 +3,11 @@
* responses, and the Cesium/viewer/document fakes the box tool needs.
*/
import { thumbnailOrder } from './model.js';
import {
FAKE_EVENT_TYPES as EVENT_TYPES,
FakeScreenSpaceEventHandler,
fakeInput,
} from '../../input/testDoubles.mjs';
export const BOX = Object.freeze({
west: -97.8,
@@ -60,40 +65,11 @@ export function response({
};
}
const EVENT_TYPES = {
LEFT_DOWN: 'down',
MOUSE_MOVE: 'move',
LEFT_UP: 'up',
LEFT_CLICK: 'click',
LEFT_DOUBLE_CLICK: 'dblclick',
};
/**
* Cesium, viewer and document fakes for `initImageryBoxTool`. The canvas is
* 1000 × 500 px mapped linearly onto 0.2° near Austin; y < 40 px is sky.
*/
export function boxToolFakes() {
const handlers = [];
class ScreenSpaceEventHandler {
constructor(canvas) {
this.canvas = canvas;
this.actions = new Map();
this.destroyed = false;
handlers.push(this);
}
setInputAction(fn, type) {
this.actions.set(type, fn);
}
getInputAction(type) {
return this.actions.get(type);
}
removeInputAction(type) {
this.actions.delete(type);
}
destroy() {
this.destroyed = true;
}
}
class CustomDataSource {
constructor(name) {
this.name = name;
@@ -107,8 +83,6 @@ export function boxToolFakes() {
}
const color = { withAlpha: (alpha) => ({ alpha }) };
const cesium = {
ScreenSpaceEventHandler,
ScreenSpaceEventType: EVENT_TYPES,
CustomDataSource,
CallbackProperty: class {},
PolylineDashMaterialProperty: class {},
@@ -118,7 +92,7 @@ export function boxToolFakes() {
Cartesian3: { fromDegreesArray: (values) => values },
};
const stock = new ScreenSpaceEventHandler('stock');
const stock = new FakeScreenSpaceEventHandler();
const originalClick = () => 'select';
const originalDouble = () => 'track';
stock.setInputAction(originalClick, EVENT_TYPES.LEFT_CLICK);
@@ -126,6 +100,9 @@ export function boxToolFakes() {
const sources = [];
const viewer = {
renders: 0,
get canvas() {
return this.scene.canvas;
},
scene: {
canvas: { clientWidth: 1000, clientHeight: 500 },
screenSpaceCameraController: { enableInputs: true },
@@ -159,13 +136,13 @@ export function boxToolFakes() {
},
};
const input = fakeInput(viewer);
const pickWorld = (_viewer, nx, ny) =>
ny * 500 < 40 ? null : { lon: -97.9 + nx * 0.2, lat: 30.4 - ny * 0.2 };
/** The live (non-stock) canvas handler, if the tool has one bound. */
const handler = () =>
handlers.find((h) => h.canvas !== 'stock' && !h.destroyed) || null;
const fire = (type, event) =>
handler()?.actions.get(EVENT_TYPES[type])?.(event);
/** Whether the tool has pointer input bound on the scene's dispatcher. */
const bound = () => input.input.subscriberCount() > 0;
const fire = (type, event) => input.handler.fire(EVENT_TYPES[type], event);
/** Dispatch a keydown to the tool's document listener. */
const key = (name) => {
const event = {
@@ -187,7 +164,9 @@ export function boxToolFakes() {
viewer,
documentRef,
pickWorld,
handler,
input: input.input,
stockEnabled: input.stockEnabled,
bound,
fire,
key,
types: EVENT_TYPES,
@@ -238,10 +217,14 @@ export function fakeRenderer() {
const owned = { a: null, b: null };
let host = { kind: 'none' };
let peak = 0;
/** Every host the renderer was bound to, as given. */
const hosts = [];
return {
calls,
hosts,
rebind(next) {
calls.push(['rebind', next.kind]);
hosts.push(next);
host = next;
for (const slot of ['a', 'b'])
if (owned[slot]) owned[slot] = { ...owned[slot], kind: next.kind };