Fix the review findings across the engines, layers, data and QA

Navara now matches Cesium where the review found it diverging: a flight
holds the camera inputs, camera.changed counts turns as Cesium does,
render requests made during a frame survive it, follow pinches zoom,
ground widths follow the pixel ratio and Cyber sonar reaches glyph caches
and models. On Cesium, a staged imagery swap keeps loading tiles, setView
replaces a running flight, and a cleared weather detail goes away.

The contract gains MoverSet.failed, maps.terrainRevision,
render.maxTextureSize and surface.sampleTerrainMostDetailed on every
engine, so layers retry failed models, key road heights by terrain,
size weather textures to the GPU and place Bhote Koshi cards on detailed
terrain.

Engine switches keep the live view, follows, focus, layer options and
cards: a pick hands over the exact pose, applies no address options and
pans no carried-over card; a history visit still applies its entry.

Layers put GhostMaps pins, cable landings, OSM Places and directions on
the measured surface without per-frame sampling, draw the Cockpit contact
dot, hide disabled CCTV on attach, and keep ALPR running outside secure
contexts. KML imports draw raised polygon fills, rotated and coloured
ground overlays and north-referenced icon headings, and report files
with nothing to draw.

QA scripts read the contract instead of Cesium internals (test:track is
109/109 again), wait for the camera to rest before clicking, and give
cold switches and parked engines realistic time. Docs follow the code.
This commit is contained in:
German Khokhlov committed 2026-11-09 21:34:42 +04:00
1 parent 69fbf5b38d
commit 0ef29781e5
276 files changed
+7217 -1517

No files matched your search

+48 -12
View File
@@ -44,6 +44,8 @@ const SCENE_REVEAL_RENDER_HOLD = 'bhote-koshi-scene-beat-reveal';
const SCENE_PATH_RENDER_HOLD = 'bhote-koshi-scene-path-travel';
const SCENE_MEDIA_MIN_PLAYBACK_SECONDS = 6;
const SCENE_MEDIA_EXIT_SECONDS = 0.65;
// A camera this near an evidence anchor has the valley's terrain loaded.
const EVIDENCE_REFINE_M = 25_000;
const BHOTE_EVENT_ACCENT = WORLD_OVERLAY_STYLE.accent;
const FLOOD_COLOR = () =>
Cesium.Color.fromCssColorString('#d8954e').withAlpha(0.68);
@@ -1050,6 +1052,9 @@ export function createBhoteKoshiEventLayer({
let _evidenceTimeline = [];
let _evidenceAnchors = [];
let _evidenceFrameSlots = [];
let _evidenceEntries = [];
// Evidence anchors at the pack's elevations (no terrain sample).
const _fallbackAnchors = new WeakSet();
let _evidenceVideo = null;
let _evidenceVideoIndex = -1;
let _evidenceVideoReady = false;
@@ -1198,14 +1203,17 @@ export function createBhoteKoshiEventLayer({
: [];
let sampled = null;
try {
sampled =
_engine && !_viewer
? observations.map(({ lon, lat }) => ({
height: _engine.surface.terrainHeight(
Cesium.Cartographic.fromDegrees(lon, lat),
),
}))
: await terrainSampler(_viewer, observations, { signal });
if (_engine && !_viewer) {
const revision = _engine.maps.terrainRevision();
const heights = await _engine.surface.sampleTerrainMostDetailed(
observations.map(({ lon, lat }) =>
Cesium.Cartographic.fromDegrees(lon, lat),
),
);
// Heights of a terrain replaced meanwhile are not the one shown.
if (_engine.maps.terrainRevision() === revision)
sampled = heights.map((height) => ({ height }));
} else sampled = await terrainSampler(_viewer, observations, { signal });
} catch (error) {
if (error?.name === 'AbortError') throw error;
console.warn(
@@ -1217,14 +1225,35 @@ export function createBhoteKoshiEventLayer({
return observations.map((observation, index) => {
const sampledHeight = Number(sampled?.[index]?.height);
const fallbackHeight = Number(observation.fallbackElevationM) || 0;
return Cesium.Cartesian3.fromDegrees(
const anchor = Cesium.Cartesian3.fromDegrees(
observation.lon,
observation.lat,
(Number.isFinite(sampledHeight) ? sampledHeight : fallbackHeight) + 18,
);
if (!Number.isFinite(sampledHeight)) _fallbackAnchors.add(anchor);
return anchor;
});
}
// An anchor at the pack's elevation, on Navara, moves onto the terrain
// loaded under a near camera (the valley's, not an overview tile's), in
// place, so the card's cull position follows.
function refineEvidenceAnchor(index) {
const anchor = _evidenceAnchors[index];
if (!anchor || _viewer || !_engine || !_fallbackAnchors.has(anchor))
return anchor || null;
const live = _engine.camera.livePosition;
if (!live || Cesium.Cartesian3.distance(live, anchor) > EVIDENCE_REFINE_M)
return anchor;
const { lon, lat } = _evidenceTimeline[index]?.observation ?? {};
const height = Number.isFinite(lon)
? _engine.surface.terrainHeight(Cesium.Cartographic.fromDegrees(lon, lat))
: undefined;
if (Number.isFinite(height))
Cesium.Cartesian3.fromDegrees(lon, lat, height + 18, undefined, anchor);
return anchor;
}
function evidencePositionGetter(index, breadcrumb = false) {
return () => {
if (!_enabled) return null;
@@ -1245,13 +1274,13 @@ export function createBhoteKoshiEventLayer({
_sceneMediaPlaybackCompletedBeatId
)
return null;
return _evidenceAnchors[index] || null;
return refineEvidenceAnchor(index);
}
const activeIndex = activeEvidenceIndex(_progress, _evidenceTimeline);
if (breadcrumb ? index >= activeIndex : index !== activeIndex)
return null;
if (!breadcrumb && index === _embeddedEvidenceIndex) return null;
return _evidenceAnchors[index] || null;
return refineEvidenceAnchor(index);
};
}
@@ -2448,7 +2477,12 @@ export function createBhoteKoshiEventLayer({
placement: 'above',
});
}
overlayHost.setEntries(BHOTE_KOSHI_OVERLAY_SOURCE_ID, entries, {
_evidenceEntries = entries;
restoreEvidenceEntries();
}
function restoreEvidenceEntries() {
overlayHost.setEntries(BHOTE_KOSHI_OVERLAY_SOURCE_ID, _evidenceEntries, {
cohortLimit: 16,
collisionCapacity: 12,
moving: false,
@@ -3557,6 +3591,7 @@ export function createBhoteKoshiEventLayer({
return;
}
createSplitControl(_event);
restoreEvidenceEntries();
syncPresentationMode();
attachCameraInputRelease();
attachEvidenceCardActivation();
@@ -3739,6 +3774,7 @@ export function createBhoteKoshiEventLayer({
_corridorPositionCache = { visibleCount: -1, positions: [] };
_evidenceTimeline = [];
_evidenceAnchors = [];
_evidenceEntries = [];
_cinematicKeyframes = [];
for (const slot of _evidenceFrameSlots) {
closeFrame(slot.frame);
+179
View File
@@ -3133,3 +3133,182 @@ test('Bhote Koshi stops waiting for a stalled map switch when its scene is relea
globalThis.window = originalWindow;
}
});
test('Bhote Koshi republishes its evidence cards to the incoming engine overlay', async () => {
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
const originalDocument = globalThis.document;
const originalWindow = globalThis.window;
installEventDom();
globalThis.window = { setTimeout: () => 1, clearTimeout() {} };
const first = eventViewer();
const second = eventViewer();
const engineB = {
id: 'B',
host: { canvas: second.scene.canvas },
camera: second.camera,
};
const hosts = new Map();
const hostFor = (engine) => {
const key = engine ?? 'A';
if (!hosts.has(key))
hosts.set(key, {
entries: new Map(),
setEntries(id, e) {
this.entries.set(id, e);
},
setVisible() {},
clearSource(id) {
this.entries.delete(id);
},
hitTest() {
return null;
},
});
return hosts.get(key);
};
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageLoader: async (url) => ({ url }),
embeddedMediaFactory: () => ({
show() {},
hide() {},
pause() {},
destroy() {},
}),
overlayHost: hostFor,
renderHost: { request() {}, hold() {}, release() {} },
});
layer.attachMapStackController({
getActiveId: () => 'esri-imagery',
getSwitchGeneration: () => 1,
async setStack() {},
});
const manager = new LayerLifecycle(first);
manager.register(layer);
try {
assert.equal(
await manager.setEnabled(layer.id, true, { origin: 'local-restore' }),
true,
);
const a = hostFor(null);
assert.ok(
[...a.entries.values()].some((e) => e.length > 0),
'first engine got the cards',
);
await layer.detachRenderer();
await layer.attachRenderer(second, { engine: engineB });
const b = hostFor(engineB);
assert.ok(
[...b.entries.values()].some((e) => e.length > 0),
'incoming engine overlay should get the cards',
);
} finally {
await manager.destroyLayer(layer.id);
globalThis.document = originalDocument;
globalThis.window = originalWindow;
}
});
// The event on a Navara engine double: its surface samples the terrain at
// its finest level (or fails to), and its loaded terrain answers `terrain`.
async function navaraEvidenceCard({ sample }) {
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
installEventDom();
globalThis.window = { setTimeout: () => 1, clearTimeout() {} };
const entries = [];
const engine = {
terrain: 3500,
host: { canvas: eventViewer().scene.canvas },
surface: {
terrainHeight: () => engine.terrain,
sampleTerrainMostDetailed: sample,
},
maps: { terrainRevision: () => 1 },
camera: { livePosition: Cesium.Cartesian3.fromDegrees(0, 0, 1e7) },
};
const layer = buildEventLayer({
eventLoader: async () => event,
imageLoader: async (url) => ({ url }),
createNativeRenderer: () => ({
loadImages: async () => {},
draw: () => ({ destroy() {} }),
setVisible() {},
setSplit() {},
clear() {},
destroy() {},
}),
embeddedMediaFactory: () => ({
show() {},
hide() {},
pause() {},
destroy() {},
}),
overlayHost: {
setEntries: (_id, value) => entries.push(...value),
setVisible() {},
clearSource() {},
},
renderHost: { request() {}, hold() {}, release() {} },
});
await layer.init(null, { engine });
await layer.enable(null, { origin: 'local-restore' });
const [first] = event.evidenceSpine;
const card = entries.find(
(entry) => entry.id === `evidence-card-${first.id}`,
);
return {
engine,
layer,
card,
first,
height: () => Cesium.Cartographic.fromCartesian(card.cullPosition).height,
};
}
test('Navara evidence anchors stand on the most detailed terrain', async () => {
const originalDocument = globalThis.document;
const originalWindow = globalThis.window;
const { layer, height } = await navaraEvidenceCard({
sample: async (places) => places.map(() => 1234),
});
try {
assert.ok(Math.abs(height() - 1252) < 0.01, `${height()}`);
} finally {
await layer.disable();
await layer.destroy();
globalThis.document = originalDocument;
globalThis.window = originalWindow;
}
});
test('Navara evidence anchors without a terrain sample follow the terrain near the camera', async () => {
const originalDocument = globalThis.document;
const originalWindow = globalThis.window;
const { engine, layer, card, first, height } = await navaraEvidenceCard({
sample: async () => {
throw new Error('no terrain');
},
});
try {
const pack = first.fallbackElevationM + 18;
assert.ok(Math.abs(height() - pack) < 0.01, 'the pack elevation');
card.position();
assert.ok(Math.abs(height() - pack) < 0.01, 'a far camera keeps it');
engine.camera.livePosition = Cesium.Cartesian3.fromDegrees(
first.lon,
first.lat,
6000,
);
engine.terrain = 2000;
assert.ok(card.position(), 'the first card is shown');
assert.ok(
Math.abs(height() - 2018) < 0.01,
'a near camera reads the terrain',
);
} finally {
await layer.disable();
await layer.destroy();
globalThis.document = originalDocument;
globalThis.window = originalWindow;
}
});
+27
View File
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createFakeEngine } from '../globe/testing/fakeEngine.js';
import { LayerLifecycle } from './lifecycle.js';
import { cancelCameraArrival, ownCameraArrival } from './cameraArrival.js';
test('an arrival owned on the engine yields to a cancel on the engine', () => {
@@ -33,3 +34,29 @@ test('a newer arrival replaces the older one and release is idempotent', () => {
cancelCameraArrival(null);
assert.deepEqual(seen, ['old', 'new']);
});
test('disabling a layer cancels an engine arrival without a native viewer', async () => {
const engine = createFakeEngine();
const manager = new LayerLifecycle(null, { engine });
manager.register({
id: 'arrival',
name: 'Arrival',
init() {},
enable() {},
disable() {},
update() {},
updateInterval: -1,
});
let cancelled = 0;
const release = ownCameraArrival(engine, () => {
cancelled++;
});
try {
await manager.setEnabled('arrival', false);
assert.equal(cancelled, 1);
} finally {
release();
await manager.destroyLayer('arrival');
engine.destroy();
}
});
+35
View File
@@ -0,0 +1,35 @@
// A file whose only geometry is degenerate (a one-point line, a two-point
// ring) draws nothing; main refused it with "That file has nothing to draw.".
import test from 'node:test';
import assert from 'node:assert/strict';
import { loadGeoFile, GeoImportError } from './geoFileImport.js';
const geojson = (geometry) => {
const blob = new Blob([
JSON.stringify({ type: 'Feature', properties: {}, geometry }),
]);
blob.name = 'degenerate.geojson';
return blob;
};
for (const geometry of [
{ type: 'LineString', coordinates: [[1, 2]] },
{
type: 'Polygon',
coordinates: [
[
[1, 2],
[2, 3],
],
],
},
]) {
test(`a ${geometry.type} with nothing to draw is refused`, async () => {
await assert.rejects(
loadGeoFile(geojson(geometry)),
(error) =>
error instanceof GeoImportError &&
/nothing to draw/.test(error.message),
);
});
}
+234 -45
View File
@@ -1,9 +1,7 @@
// One imported file (UTILITIES ▸ Import) drawn on the globe contract, the
// same on every engine, from its plain records (src/data/geoImportRecords.js),
// with Cesium's look as the reference:
// - polygons: one ground 'polygon' set of their fills; a raised polygon
// (KML absolute or relative) also gets its outline as lines at its
// heights, as Cesium drew it (its fill drapes: the ground has no heights);
// - polygons: ground fills, or meshes and outlines at the vertices' heights;
// - ground lines: one ground 'corridor' set in pixels, over the fills;
// - lines in the air: one engine line each;
// - points: one sprite set per look, each sprite a square centred on its
@@ -11,13 +9,16 @@
// geoImportPins.js); points on the ground draw over the scene and are
// hidden beyond the horizon instead, as Cesium's clamped billboards
// ignored the depth test;
// - ground overlays: one image imagery layer each over its rectangle.
// - ground overlays: one image imagery layer each over its rectangle, its
// image tinted and turned on a canvas when the KML says so, an absolute
// one raised to its altitude; a plain colour is a ground fill.
// Nothing is pickable: an imported file has no card. Ground heights under
// the points come from engine.surface, sampled again by refreshGround():
// the terrain where the globe is drawn, else (3D tiles) the scene drawn
// under a low camera, never an imported point (as Cesium's import kept its
// pins out of height queries).
import earcut from 'earcut';
import * as geo from '../geo/index.js';
import { normalizeGroundItem } from '../globe/ground.js';
import { composeIcon } from './geoImportPins.js';
@@ -34,6 +35,10 @@ const HORIZON_LIFT_M = 2000;
// drawn now; higher up the terrain answers (Cesium's 250 km).
const CLAMP_TILES_BELOW_M = 250_000;
const BATCH = 256;
// Canvas pixels every imported icon look shares (64 MiB of RGBA).
const ICON_PIXEL_BUDGET = 16 * 1024 * 1024;
// The longest side of a tinted or turned ground overlay's canvas.
const MAX_OVERLAY_SIDE = 4096;
let serial = 0;
// Each engine's imported point sets, left out of each other's ground.
const pointSets = new WeakMap();
@@ -60,6 +65,103 @@ function checked(kind, item) {
}
}
// A ground overlay's box with east past west across 180°, and how a corner
// turns by its rotation: KML's degrees counter-clockwise about the centre,
// in longitude and latitude (Cesium's rectangle rotation).
function overlayBox({ rectangle, rotation = 0 }) {
const { west, south, north } = rectangle;
const east = rectangle.east < west ? rectangle.east + 360 : rectangle.east;
const box = { west, south, east, north };
const center = [(west + east) / 2, (south + north) / 2];
const angle = (rotation * Math.PI) / 180;
const [cos, sin] = [Math.cos(angle), Math.sin(angle)];
const turn = ([lon, lat]) => {
const [x, y] = [lon - center[0], lat - center[1]];
return [center[0] + x * cos - y * sin, center[1] + x * sin + y * cos];
};
return { box, center, angle, turn };
}
// What a ground overlay's image layer draws: its image tinted by the
// overlay's colour and turned by its rotation onto the box around the
// turned image (transparent outside it). Null when that box passes a pole.
async function overlayImage(overlay, loadImage, createCanvas) {
const tint = overlay.color.slice(0, 3);
const { box, center, angle } = overlayBox(overlay);
if (tint.every((value) => value === 1) && !angle)
return { url: overlay.url, rectangle: overlay.rectangle };
const [width, height] = [box.east - box.west, box.north - box.south];
const [cos, sin] = [Math.abs(Math.cos(angle)), Math.abs(Math.sin(angle))];
const [spanX, spanY] = [
width * cos + height * sin,
width * sin + height * cos,
];
const rectangle = {
west: center[0] - spanX / 2,
south: center[1] - spanY / 2,
east: center[0] + spanX / 2,
north: center[1] + spanY / 2,
};
if (rectangle.south < -90 || rectangle.north > 90 || spanX >= 360)
return null;
let image;
try {
image = await loadImage(overlay.url);
} catch {
// An image that does not decode draws nothing, as on the plain path.
return { url: overlay.url, rectangle: overlay.rectangle };
}
const natural = [
image.naturalWidth || image.width,
image.naturalHeight || image.height,
];
// Pixels per degree: one scale on both axes when turned, so the image
// turns in degrees as Cesium's does.
let [scaleX, scaleY] = [natural[0] / width, natural[1] / height];
if (angle) scaleX = scaleY = Math.max(scaleX, scaleY);
const fit = Math.min(
1,
MAX_OVERLAY_SIDE / (spanX * scaleX),
MAX_OVERLAY_SIDE / (spanY * scaleY),
);
[scaleX, scaleY] = [scaleX * fit, scaleY * fit];
const canvas = createCanvas();
canvas.width = Math.max(1, Math.round(spanX * scaleX));
canvas.height = Math.max(1, Math.round(spanY * scaleY));
const context = canvas.getContext('2d');
context.translate(canvas.width / 2, canvas.height / 2);
// The canvas's y runs south: a counter-clockwise turn is a negative one.
context.rotate(-angle);
context.drawImage(
image,
(-width * scaleX) / 2,
(-height * scaleY) / 2,
width * scaleX,
height * scaleY,
);
if (tint.some((value) => value !== 1)) {
const pixels = context.getImageData(0, 0, canvas.width, canvas.height);
for (let i = 0; i < pixels.data.length; i += 4)
for (let channel = 0; channel < 3; channel++)
pixels.data[i + channel] *= tint[channel];
context.putImageData(pixels, 0, 0);
}
const wrap = (lon) => (lon > 180 ? lon - 360 : lon < -180 ? lon + 360 : lon);
return {
image: canvas,
rectangle: {
...rectangle,
west: wrap(rectangle.west),
east: wrap(rectangle.east),
},
};
}
// KML headings are from north (Cesium's billboard on the Earth's axis):
// the sprite turns on screen with the camera's heading.
const turnsWithCamera = (look) => look.pins.some((pin) => pin.rotation);
const onScreen = (pin, heading) => (pin.rotation ? pin.rotation + heading : 0);
const flat = (positions) => positions.map(([lon, lat]) => [lon, lat]);
const cartesian = ([lon, lat, height = 0]) =>
geo.cartesian3.fromDegrees(lon, lat, height);
@@ -110,6 +212,9 @@ export async function drawImportedFile(
let removeCull = null;
const groundSets = [];
const lines = [];
const meshes = [];
const pins = [];
const kinds = { ...records.undrawn };
const layers = [];
const looks = new Map();
let drawn = 0;
@@ -120,12 +225,14 @@ export async function drawImportedFile(
removeCull = null;
for (const set of groundSets.splice(0)) set.destroy();
for (const line of lines.splice(0)) line.destroy();
for (const mesh of meshes.splice(0)) mesh.destroy();
for (const layer of layers.splice(0)) layer.destroy();
for (const look of looks.values()) {
pointSetsOf(engine).delete(look.set);
look.set?.destroy();
}
looks.clear();
pins.length = 0;
}
try {
@@ -133,7 +240,34 @@ export async function drawImportedFile(
const fills = [];
for (const polygon of records.polygons) {
let any = false;
if (polygon.fill) {
if (polygon.fill && polygon.raised) {
const vertices = polygon.rings.flat();
const origin = vertices[0]?.[0] ?? 0;
const xy = vertices.flatMap(([lon, lat]) => [
origin + ((((lon - origin + 180) % 360) + 360) % 360) - 180,
lat,
]);
let count = 0;
const holes = polygon.rings
.slice(0, -1)
.map((ring) => (count += ring.length));
const indices = earcut(xy, holes);
if (indices.length) {
meshes.push(
engine.meshes.createMesh({
id: `${prefix}-fill-${meshes.length}`,
positions: vertices.flatMap((vertex) => {
const { x, y, z } = cartesian(vertex);
return [x, y, z];
}),
indices,
color: polygon.fill,
show: shown,
}),
);
any = true;
}
} else if (polygon.fill) {
const item = checked('polygon', {
rings: polygon.rings.map(flat),
fill: polygon.fill,
@@ -160,34 +294,47 @@ export async function drawImportedFile(
if (any) drawn++;
}
for (const overlay of records.overlays) {
// Cesium raises only an absolute overlay, to its altitude.
const raise =
overlay.altitudeMode === 'absolute' && overlay.altitude > 0
? overlay.altitude
: undefined;
if (overlay.url) {
const prepared = await overlayImage(overlay, loadImage, createCanvas);
if (!prepared) {
kinds.rotatedOverlay = (kinds.rotatedOverlay ?? 0) + 1;
continue;
}
layers.push(
engine.imagery.createLayer({
id: `${prefix}-overlay-${layers.length}`,
source: {
kind: 'image',
url: overlay.url,
rectangle: overlay.rectangle,
},
source: { kind: 'image', ...prepared },
// Cesium's transparent image material: at most 0.99.
alpha: Math.min(0.99, overlay.color[3]),
show: shown,
order: OVERLAY_ORDER,
...(raise ? { raise } : {}),
}),
);
drawn++;
continue;
}
// A plain colour draws as a ground fill.
if (raise) {
kinds.raisedOverlay = (kinds.raisedOverlay ?? 0) + 1;
continue;
}
const { west, south, east, north } = overlay.rectangle;
const item = checked('cell', { west, south, east, north });
if (!item) continue;
const { box, turn } = overlayBox(overlay);
const rings = [
[
[west, south],
[east < west ? east + 360 : east, south],
[east < west ? east + 360 : east, north],
[west, north],
],
[box.west, box.south],
[box.east, box.south],
[box.east, box.north],
[box.west, box.north],
].map(turn),
];
fills.push({ rings, fill: overlay.color });
drawn++;
@@ -261,6 +408,11 @@ export async function drawImportedFile(
rotation: point.icon.rotation ?? 0,
});
}
pins.push(...[...looks.values()].flatMap((look) => look.pins));
const maxSide = Math.min(
512,
Math.floor(Math.sqrt(ICON_PIXEL_BUDGET / Math.max(1, looks.size))),
);
await Promise.all(
[...looks.values()].map(async (look) => {
const url = look.icon.image?.url;
@@ -279,6 +431,7 @@ export async function drawImportedFile(
image,
createCanvas,
ratio: pixelRatio,
maxSide,
});
look.set = engine.movers.createSet({
id: `${prefix}-pins-${look.depth}-${looks.size}-${++serial}`,
@@ -299,7 +452,11 @@ export async function drawImportedFile(
}),
);
if (destroyed) throw new Error('The imported file was removed');
settle(heightContext());
for (let from = 0; from < pins.length; from += BATCH) {
settle(heightContext(), from, from + BATCH);
if (from + BATCH < pins.length)
await new Promise((resolve) => setTimeout(resolve, 0));
}
for (const look of looks.values()) writePins(look);
syncCull();
} catch (error) {
@@ -316,11 +473,30 @@ export async function drawImportedFile(
(engine.imagery?.surface?.() ?? 'globe') !== 'globe' &&
surface.clampToHeightSupported &&
engine.camera.height() < CLAMP_TILES_BELOW_M;
return { surface, tiles, exclude: [...pointSetsOf(engine)] };
return {
surface,
tiles,
exclude: [...pointSetsOf(engine)],
size: tiles ? engine.host.size() : null,
};
}
// Whether a position is in the window now: clamping to 3D tiles reads
// the tiles drawn, and a point elsewhere would only cost the query.
function inWindow(position, { width, height }) {
if (!engine.projector.horizonVisible(position)) return false;
const screen = engine.projector.worldToWindow(position);
return (
Boolean(screen) &&
screen.x >= 0 &&
screen.y >= 0 &&
screen.x <= width &&
screen.y <= height
);
}
// The ground under a pin, falling back to the last known one.
function groundUnder(pin, { surface, tiles, exclude }) {
function groundUnder(pin, { surface, tiles, exclude, size }) {
const at = geo.cartographic.fromDegrees(pin.lon, pin.lat, 0);
const terrain = surface.terrainHeightSupported
? surface.terrainHeight(at)
@@ -331,7 +507,10 @@ export async function drawImportedFile(
? Math.max(0, terrain)
: terrain
: (pin.ground ?? 0);
if (tiles) {
if (
tiles &&
inWindow(geo.cartesian3.fromDegrees(pin.lon, pin.lat, ground), size)
) {
const top = surface.clampToHeight(
geo.cartesian3.fromDegrees(pin.lon, pin.lat, Math.max(0, ground)),
exclude,
@@ -342,33 +521,33 @@ export async function drawImportedFile(
return ground;
}
function settle(context, from = 0, to = Infinity) {
let at = 0;
for (const look of looks.values())
for (const pin of look.pins) {
if (at++ < from || at > to) continue;
if (pin.height === null) pin.ground = groundUnder(pin, context);
const height = pin.height ?? pin.ground + pin.offset;
pin.position = geo.cartesian3.fromDegrees(pin.lon, pin.lat, height);
pin.horizon = geo.cartesian3.fromDegrees(
pin.lon,
pin.lat,
height + HORIZON_LIFT_M,
);
}
function settle(context, from = 0, to = pins.length) {
for (let i = from; i < Math.min(to, pins.length); i++) {
const pin = pins[i];
if (pin.height === null) pin.ground = groundUnder(pin, context);
const height = pin.height ?? pin.ground + pin.offset;
pin.position = geo.cartesian3.fromDegrees(pin.lon, pin.lat, height);
pin.horizon = geo.cartesian3.fromDegrees(
pin.lon,
pin.lat,
height + HORIZON_LIFT_M,
);
}
}
function writePins(look) {
const { set, pins } = look;
if (!set) return;
const culled = look.depth === 'always';
const heading = turnsWithCamera(look) ? engine.camera.pose().heading : 0;
pins.forEach((pin, index) => {
if (culled) pin.show = engine.projector.horizonVisible(pin.horizon);
pin.drawnRotation = onScreen(pin, heading);
set.set(index, {
position: pin.position,
cell: 'icon',
color: pin.color,
rotation: pin.rotation,
rotation: pin.drawnRotation,
show: pin.show,
});
});
@@ -377,14 +556,18 @@ export async function drawImportedFile(
set.commit();
}
// Hides the ground points beyond the horizon; true when any show changed.
function cull(look) {
// Hides the ground points beyond the horizon and turns the headed ones
// with the camera; true when any changed.
function cull(look, heading) {
let changed = false;
look.pins.forEach((pin, index) => {
const show = engine.projector.horizonVisible(pin.horizon);
if (show === pin.show) return;
const show =
look.depth !== 'always' || engine.projector.horizonVisible(pin.horizon);
const rotation = onScreen(pin, heading);
if (show === pin.show && rotation === pin.drawnRotation) return;
pin.show = show;
look.set.set(index, { show });
pin.drawnRotation = rotation;
look.set.set(index, { show, rotation });
changed = true;
});
if (changed) look.set.commit();
@@ -392,33 +575,39 @@ export async function drawImportedFile(
}
function syncCull() {
const culled = [...looks.values()].filter(
(look) => look.set && look.depth === 'always',
(look) => look.set && (look.depth === 'always' || turnsWithCamera(look)),
);
if (!culled.length || !shown) {
removeCull?.();
removeCull = null;
return;
}
const turning = culled.some(turnsWithCamera);
const lastCamera = geo.cartesian3.create(Number.NaN, 0, 0);
let lastHeading = Number.NaN;
removeCull ??= engine.frames.preRender.addEventListener(() => {
const live = engine.camera.livePosition;
if (geo.cartesian3.equals(live, lastCamera)) return;
const heading = turning ? engine.camera.pose().heading : 0;
if (geo.cartesian3.equals(live, lastCamera) && heading === lastHeading)
return;
lastHeading = heading;
geo.cartesian3.clone(live, lastCamera);
let changed = false;
for (const look of culled) changed = cull(look) || changed;
for (const look of culled) changed = cull(look, heading) || changed;
if (changed) request();
});
}
const undrawn = Object.values(records.undrawn).reduce((n, c) => n + c, 0);
const undrawn = Object.values(kinds).reduce((n, c) => n + c, 0);
return {
report: { drawn, undrawn, kinds: { ...records.undrawn } },
report: { drawn, undrawn, kinds },
setShow(visibleNow) {
visibleNow = Boolean(visibleNow);
if (destroyed || visibleNow === shown) return;
shown = visibleNow;
for (const set of groundSets) set.show(shown);
for (const line of lines) line.show(shown);
for (const mesh of meshes) mesh.show(shown);
for (const layer of layers) layer.show(shown);
for (const look of looks.values()) {
look.set?.setCount(shown ? look.count : 0);
@@ -444,7 +633,7 @@ export async function drawImportedFile(
},
/** Sample the ground under the points again (a map or the terrain changed). */
async refreshGround(signal) {
const total = [...looks.values()].reduce((n, l) => n + l.pins.length, 0);
const total = pins.length;
for (let from = 0; from < total; from += BATCH) {
signal?.throwIfAborted();
if (destroyed) return;
+222 -3
View File
@@ -4,7 +4,7 @@ import * as Cesium from 'cesium';
import * as geo from '../geo/index.js';
import { GROUND_HARNESSES } from '../testSupport/groundDisplayEngines.mjs';
import { drawImportedFile } from './geoImportDisplay.js';
import { geoJsonRecords } from './geoImportRecords.js';
import { emptyRecords, geoJsonRecords } from './geoImportRecords.js';
// A 2D context that only records what draws.
const createCanvas = () => ({
@@ -191,6 +191,8 @@ for (const make of GROUND_HARNESSES) {
viewer.scene.clampToHeightSupported = true;
} else engine.imagery.surface = () => 'tiles';
engine.camera.height = () => 1000;
engine.projector.worldToWindow = () => ({ x: 1, y: 1 });
engine.projector.horizonVisible = () => true;
const excluded = [];
engine.surface.clampToHeight = (position, exclude) => {
excluded.push(exclude);
@@ -270,8 +272,9 @@ for (const make of GROUND_HARNESSES) {
visible: false,
});
const fill = set(engine.ground.list()[0].id);
assert.equal(fill.items.length, 2);
assert.equal(fill.items[0].rings.length, 2);
assert.equal(fill.items.length, 1);
assert.equal(engine.meshes.list().length, 1);
assert.equal(fill.items[0].rings.length, 1);
assert.ok(fill.items[0].rings.flat().every((p) => p.length === 2));
assert.equal(fill.shown, false);
assert.equal(engine.lines.list().length, 2);
@@ -339,6 +342,222 @@ for (const make of GROUND_HARNESSES) {
},
);
displayTest(
'KML headings follow north as the camera rotates',
async ({ engine, pins }) => {
let heading = 0;
engine.camera.pose = () => ({ heading });
const records = geoJsonRecords(
{ type: 'Point', coordinates: [1, 2] },
'#39d0ff',
);
records.points[0].icon.rotation = -Math.PI / 4;
const drawing = await drawImportedFile(engine, records, { createCanvas });
assert.equal(pins[0].items[0].rotation, -Math.PI / 4);
heading = Math.PI / 2;
engine.frames.preRender.raiseEvent();
assert.equal(pins[0].items[0].rotation, Math.PI / 4);
drawing.destroy();
},
);
// A canvas whose context records the transform and holds one pixel.
const recordingCanvas = () => {
const calls = [];
const pixels = { data: new Uint8ClampedArray([128, 64, 32, 128]) };
const context = {
translate: (...args) => calls.push(['translate', ...args]),
rotate: (angle) => calls.push(['rotate', angle]),
drawImage: (_image, ...args) => calls.push(['drawImage', ...args]),
getImageData: () => pixels,
putImageData: (value) => calls.push(['putImageData', value]),
};
return { calls, pixels, canvas: { getContext: () => context } };
};
const overlayLayer = (engine) => {
const layers = [];
const create = engine.imagery.createLayer;
engine.imagery.createLayer = (options) => {
layers.push(options);
return create(options);
};
return layers;
};
displayTest(
'colored overlays multiply image RGB and retain layer alpha',
async ({ engine }) => {
const { calls, pixels, canvas } = recordingCanvas();
const layers = overlayLayer(engine);
const records = emptyRecords();
records.overlays.push({
url: 'blob:overlay',
color: [1, 0, 0, 0.5],
rectangle: { west: 0, south: 0, east: 1, north: 1 },
rotation: 0,
});
const drawing = await drawImportedFile(engine, records, {
createCanvas: () => canvas,
loadImage: async () => ({ width: 32, height: 16 }),
});
assert.equal(layers[0].source.image, canvas);
assert.deepEqual(
{ ...layers[0].source.rectangle },
{ west: 0, south: 0, east: 1, north: 1 },
);
assert.equal(layers[0].alpha, 0.5);
assert.deepEqual([canvas.width, canvas.height], [32, 16]);
assert.ok(
calls.some(
([name, value]) => name === 'putImageData' && value === pixels,
),
);
assert.deepEqual([...pixels.data], [128, 0, 0, 128]);
drawing.destroy();
},
);
displayTest(
'a rotated overlay turns its image counter-clockwise onto the box around it',
async ({ engine }) => {
const { calls, canvas } = recordingCanvas();
const layers = overlayLayer(engine);
const records = emptyRecords();
records.overlays.push({
url: 'blob:overlay',
color: [1, 1, 1, 1],
// Two degrees by one, across 180°, turned a quarter.
rectangle: { west: 179, south: 10, east: -179, north: 11 },
rotation: 90,
});
const drawing = await drawImportedFile(engine, records, {
createCanvas: () => canvas,
loadImage: async () => ({ width: 200, height: 100 }),
});
assert.equal(drawing.report.drawn, 1);
assert.equal(drawing.report.undrawn, 0);
const { rectangle } = layers[0].source;
assert.ok(Math.abs(rectangle.west - 179.5) < 1e-9);
assert.ok(Math.abs(rectangle.east + 179.5) < 1e-9);
assert.ok(Math.abs(rectangle.south - 9.5) < 1e-9);
assert.ok(Math.abs(rectangle.north - 11.5) < 1e-9);
// 100 pixels a degree on both axes: the turned box is 1° by 2°.
assert.deepEqual([canvas.width, canvas.height], [100, 200]);
assert.deepEqual(
calls.find(([name]) => name === 'rotate'),
['rotate', -Math.PI / 2],
);
assert.deepEqual(
calls.find(([name]) => name === 'drawImage'),
['drawImage', -100, -50, 200, 100],
);
assert.equal(
calls.some(([name]) => name === 'putImageData'),
false,
);
drawing.destroy();
},
);
displayTest(
'a rotated overlay whose box passes a pole is reported undrawn',
async ({ engine }) => {
const records = emptyRecords();
records.overlays.push({
url: 'blob:overlay',
color: [1, 1, 1, 1],
rectangle: { west: 0, south: 80, east: 30, north: 89 },
rotation: 45,
});
const drawing = await drawImportedFile(engine, records, { createCanvas });
assert.deepEqual(drawing.report, {
drawn: 0,
undrawn: 1,
kinds: { rotatedOverlay: 1 },
});
assert.equal(engine.imagery.list().length, 0);
drawing.destroy();
},
);
displayTest(
'a rotated plain-colour overlay fills its turned corners',
async ({ engine, set }) => {
const records = emptyRecords();
records.overlays.push({
url: null,
color: [0, 1, 0, 0.5],
rectangle: { west: 0, south: 0, east: 2, north: 2 },
rotation: 90,
});
const drawing = await drawImportedFile(engine, records, { createCanvas });
const fill = set(engine.ground.list()[0].id);
const [ring] = fill.items[0].rings;
const near = (a, b) => a.every((v, i) => Math.abs(v - b[i]) < 1e-9);
assert.ok(near(ring[0], [2, 0]), JSON.stringify(ring));
assert.ok(near(ring[1], [2, 2]), JSON.stringify(ring));
assert.ok(near(ring[2], [0, 2]), JSON.stringify(ring));
drawing.destroy();
},
);
displayTest(
'an absolute overlay is raised to its altitude, a relative one drapes',
async ({ engine }) => {
const layers = overlayLayer(engine);
const records = emptyRecords();
for (const altitudeMode of ['absolute', 'relative'])
records.overlays.push({
url: 'blob:overlay',
altitudeMode,
altitude: 1000,
color: [1, 1, 1, 1],
rectangle: { west: 0, south: 0, east: 1, north: 1 },
rotation: 0,
});
const drawing = await drawImportedFile(engine, records, { createCanvas });
assert.deepEqual(drawing.report, { drawn: 2, undrawn: 0, kinds: {} });
assert.equal(layers[0].raise, 1000);
assert.equal(layers[1].raise, undefined);
drawing.destroy();
},
);
displayTest(
'tile clamps only sample visible pins and yield between batches',
async ({ engine }) => {
engine.imagery.surface = () => 'tiles';
engine.camera.height = () => 1000;
engine.projector.horizonVisible = () => true;
let visible = false;
engine.projector.worldToWindow = () => (visible ? { x: 1, y: 1 } : null);
let clamps = 0;
engine.surface.clampToHeight = (position) => {
clamps++;
return position;
};
const records = geoJsonRecords(
{
type: 'MultiPoint',
coordinates: Array.from({ length: 600 }, () => [1, 2]),
},
'#39d0ff',
);
const drawing = await drawImportedFile(engine, records, { createCanvas });
assert.equal(clamps, 0);
visible = true;
let beforeYield;
const heartbeat = setTimeout(() => {
beforeYield = clamps;
}, 0);
await drawing.refreshGround();
clearTimeout(heartbeat);
assert.equal(beforeYield, 256);
assert.equal(clamps, 600);
drawing.destroy();
},
);
displayTest(
'an aborted ground refresh leaves the existing drawing owned',
async ({ engine }) => {
+97
View File
@@ -0,0 +1,97 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { drawImportedFile } from './geoImportDisplay.js';
import { emptyRecords } from './geoImportRecords.js';
// A globe engine double that records what drawImportedFile asks of it.
function recordingEngine() {
const calls = { groundSets: [], lines: [], layers: [], moverSets: [] };
const handle = (extra = {}) => ({
destroy() {},
show() {},
commit() {},
...extra,
});
const engine = {
calls,
render: { request() {} },
ground: {
createSet(options) {
const rec = { options, items: [] };
calls.groundSets.push(rec);
return handle({ replace: (items) => (rec.items = items) });
},
},
lines: {
createLine(options) {
const rec = { options, positions: null };
calls.lines.push(rec);
return handle({ setPositions: (p) => (rec.positions = p) });
},
},
imagery: {
surface: () => 'globe',
createLayer(options) {
calls.layers.push(options);
return handle();
},
},
movers: {
createSet(options) {
const rec = { options, items: [] };
calls.moverSets.push(rec);
return handle({
set: (i, f) => (rec.items[i] = { ...rec.items[i], ...f }),
setCount() {},
});
},
},
surface: { terrainHeightSupported: false, clampToHeightSupported: false },
camera: { height: () => 1e7, livePosition: { x: 1, y: 0, z: 0 } },
projector: { horizonVisible: () => true },
frames: { preRender: { addEventListener: () => () => {} } },
};
return engine;
}
const createCanvas = () => ({
width: 0,
height: 0,
getContext: () =>
new Proxy({}, { get: (_, key) => (key in {} ? undefined : () => {}) }),
});
const draw = (engine, records, extra = {}) =>
drawImportedFile(engine, records, {
createCanvas,
loadImage: async () => ({ width: 32, height: 32 }),
pixelRatio: 2,
...extra,
});
const box = { west: 10, south: 10, east: 11, north: 11 };
test('icon variants of one file stay within a canvas budget', async () => {
const engine = recordingEngine();
const points = [];
for (let i = 0; i < 2000; i++)
points.push({
position: [1, 2, 0],
altitude: 'ground',
icon: { image: { url: 'blob:icon' }, scale: 10 + i / 1000 },
});
let bytes = 0;
await draw(
engine,
{ ...emptyRecords(), points },
{
createCanvas: () => {
const c = createCanvas();
return new Proxy(c, {
set(target, key, value) {
if (key === 'height') bytes += target.width * value * 4;
target[key] = value;
return true;
},
});
},
},
);
assert.ok(bytes <= 256 * 2 ** 20, `canvas bytes ${bytes / 2 ** 20} MiB`);
});
+2
View File
@@ -380,6 +380,8 @@ function readGroundOverlay(el, records) {
rectangle,
color,
rotation: numberOf(box, 'rotation') ?? 0,
altitude: numberOf(el, 'altitude') ?? 0,
altitudeMode: altitudeOf(el),
});
}
+12
View File
@@ -400,3 +400,15 @@ test('a KML file loads to records with its name, count and outside content remov
assert.equal(loaded.records.points[0].name, 'QA KML pin');
loaded.revoke();
});
test('GroundOverlay retains altitude and altitude mode for drawing diagnostics', () => {
const records = readKmlRecords(
parseXml(
kml(
`<GroundOverlay><altitude>1000</altitude><altitudeMode>absolute</altitudeMode><LatLonBox><west>0</west><east>1</east><south>0</south><north>1</north></LatLonBox></GroundOverlay>`,
),
),
);
assert.equal(records.overlays[0].altitude, 1000);
assert.equal(records.overlays[0].altitudeMode, 'absolute');
});
+5 -2
View File
@@ -87,7 +87,10 @@ export function iconBox(icon, natural) {
* `ratio` canvas pixels per CSS pixel. Returns the canvas and the sprite's
* side in CSS pixels.
*/
export function composeIcon(icon, { image, createCanvas, ratio = 1 } = {}) {
export function composeIcon(
icon,
{ image, createCanvas, ratio = 1, maxSide = 512 } = {},
) {
const natural = image
? {
width: image.naturalWidth || image.width,
@@ -96,7 +99,7 @@ export function composeIcon(icon, { image, createCanvas, ratio = 1 } = {}) {
: undefined;
const box = iconBox(icon, natural);
// At least one canvas pixel per icon pixel, at most 512 a side.
const k = Math.min(ratio, 512 / box.side);
const k = Math.min(ratio, maxSide / box.side);
const canvas = createCanvas();
canvas.width = Math.max(1, Math.ceil(box.side * k));
canvas.height = canvas.width;
+112
View File
@@ -0,0 +1,112 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { drawImportedFile } from './geoImportDisplay.js';
import { emptyRecords } from './geoImportRecords.js';
// A globe engine double that records what drawImportedFile asks of it.
function recordingEngine() {
const calls = {
meshes: [],
groundSets: [],
lines: [],
layers: [],
moverSets: [],
};
const handle = (extra = {}) => ({
destroy() {},
show() {},
commit() {},
...extra,
});
const engine = {
calls,
render: { request() {} },
meshes: {
createMesh(options) {
calls.meshes.push(options);
return handle();
},
},
ground: {
createSet(options) {
const rec = { options, items: [] };
calls.groundSets.push(rec);
return handle({ replace: (items) => (rec.items = items) });
},
},
lines: {
createLine(options) {
const rec = { options, positions: null };
calls.lines.push(rec);
return handle({ setPositions: (p) => (rec.positions = p) });
},
},
imagery: {
surface: () => 'globe',
createLayer(options) {
calls.layers.push(options);
return handle();
},
},
movers: {
createSet(options) {
const rec = { options, items: [] };
calls.moverSets.push(rec);
return handle({
set: (i, f) => (rec.items[i] = { ...rec.items[i], ...f }),
setCount() {},
});
},
},
surface: { terrainHeightSupported: false, clampToHeightSupported: false },
camera: { height: () => 1e7, livePosition: { x: 1, y: 0, z: 0 } },
projector: { horizonVisible: () => true },
frames: { preRender: { addEventListener: () => () => {} } },
};
return engine;
}
const createCanvas = () => ({
width: 0,
height: 0,
getContext: () =>
new Proxy({}, { get: (_, key) => (key in {} ? undefined : () => {}) }),
});
const draw = (engine, records, extra = {}) =>
drawImportedFile(engine, records, {
createCanvas,
loadImage: async () => ({ width: 32, height: 32 }),
pixelRatio: 2,
...extra,
});
const box = { west: 10, south: 10, east: 11, north: 11 };
test('a raised polygon fill keeps its heights (not a ground fill)', async () => {
const engine = recordingEngine();
await draw(engine, {
...emptyRecords(),
polygons: [
{
rings: [
[
[0, 0, 1000],
[1, 0, 1000],
[1, 1, 1000],
],
],
raised: true,
fill: [1, 0, 0, 1],
outline: { color: [1, 1, 1, 1], widthPx: 1 },
},
],
});
const groundFills = engine.calls.groundSets
.filter((s) => s.options.kind === 'polygon')
.flatMap((s) => s.items);
assert.equal(
groundFills.length,
0,
'the 1000 m fill is draped on the ground',
);
assert.equal(engine.calls.meshes.length, 1);
assert.equal(engine.calls.meshes[0].positions[0], 6379137);
assert.equal(engine.calls.meshes[0].indices.length, 3);
});
+11 -3
View File
@@ -16,7 +16,9 @@
// @property {ImportedPolygon[]} polygons
// @property {ImportedOverlay[]} overlays
// @property {Object<string, number>} undrawn What the file has that no
// engine draws, by kind (`wall`, `extruded`, `latLonQuad`), counted.
// engine draws, by kind (`wall`, `extruded`, `latLonQuad`), counted;
// the display adds the overlays it cannot draw (`rotatedOverlay`,
// `raisedOverlay`).
//
// @typedef {object} ImportedPoint
// @property {number[]} position
@@ -62,6 +64,9 @@
// @property {{ west: number, south: number, east: number, north: number }} rectangle
// @property {number[]} color Multiplies the image; its alpha fades it.
// @property {number} rotation Degrees counter-clockwise (KML LatLonBox).
// @property {number} altitude Metres (KML altitude); Cesium raises an
// absolute overlay to it.
// @property {'ground'|'relative'|'absolute'} altitudeMode
/** Longest plain-text name kept from a file's features. */
const MAX_IMPORT_NAME_LENGTH = 120;
@@ -162,7 +167,7 @@ export function geoJsonRecords(geojson, color) {
origin: 'bottom',
},
});
else if (kind === 'LineString')
else if (kind === 'LineString' && part.length >= 2)
records.lines.push({
name,
positions: part.map(position),
@@ -170,7 +175,10 @@ export function geoJsonRecords(geojson, color) {
color: stroke,
widthPx: GEOJSON_STROKE_PX,
});
else if (kind === 'Polygon' && part[0]?.length)
else if (
kind === 'Polygon' &&
new Set(part[0]?.map(([lon, lat]) => `${lon},${lat}`)).size >= 3
)
records.polygons.push({
name,
rings: part.map((ring) => ring.map(position)),
+31 -19
View File
@@ -404,25 +404,6 @@ export class LayerStateCoordinator {
live,
enabled.has(entry.id),
);
// A same-document engine choice retains operational layer intents.
// The share still owns durable preferences and later history visits.
if (
live &&
this.dataManager.layers.get(entry.id) === live.entry &&
!live.entry.lifecycleUncertain &&
live.entry.enabled === targetEnabled
) {
return {
layerId: entry.id,
targetEnabled,
origin,
phase: 'retained',
...currentLayerOutcome(this.dataManager, entry.id),
appliedOptions: {},
persistenceWrite: false,
succeeded: true,
};
}
const options = layerOptionsForRestore(this._durableState, entry.id);
if (origin === LAYER_RESTORE_ORIGINS.share && options) {
for (const trackingKey of Object.values(
@@ -445,6 +426,37 @@ export class LayerStateCoordinator {
succeeded: false,
};
}
// A same-document engine choice retains operational layer intents.
// The share still owns durable preferences and later history visits:
// on a visit, the entry's options that differ from the live layer
// apply; a pick keeps the live layer as it is.
if (
live &&
this.dataManager.layers.get(entry.id) === live.entry &&
!live.entry.lifecycleUncertain &&
live.entry.enabled === targetEnabled
) {
const current = this.dataManager.getLayerParams(entry.id);
const changed =
live.visit === true &&
options &&
Object.entries(options).some(
([key, value]) => !Object.is(current?.[key], value),
);
const succeeded =
!changed ||
this.dataManager.setLayerParams(entry.id, options, { origin });
return {
layerId: entry.id,
targetEnabled,
origin,
phase: 'retained',
...currentLayerOutcome(this.dataManager, entry.id),
appliedOptions: changed && succeeded ? options : {},
persistenceWrite: false,
succeeded,
};
}
// Reserve passive option state before any asynchronous lifecycle work.
// A later explicit params intent then wins on its own lane without
// cancelling or being overwritten by the visibility restore.
+130
View File
@@ -0,0 +1,130 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { DataLayerManager } from './manager.js';
import { LAYER_STATE_REGISTRY, REGISTERED_LAYER_IDS } from './layerState.js';
import { LayerStateCoordinator } from './layerStateCoordinator.js';
let windParamWrites = 0;
function layer(id) {
let params =
id === 'wind'
? { model: 'gfs', overlay: 'none', units: 'km/h', paused: false }
: null;
return {
id,
name: id,
icon: '',
source: 'test',
async init() {
return true;
},
async enable() {
return true;
},
async update() {
return true;
},
async disable() {
return true;
},
attachRenderer() {},
...(params
? {
setParams(next = {}) {
windParamWrites++;
params = { ...params, ...next };
return true;
},
getParams() {
return { ...params };
},
}
: {}),
};
}
function manager() {
const m = new DataLayerManager({});
for (const id of REGISTERED_LAYER_IDS) m.register(layer(id));
m.finalizeRegistrations(LAYER_STATE_REGISTRY);
return m;
}
const storage = () => {
const v = new Map();
return { getItem: (k) => v.get(k) ?? null, setItem: (k, x) => v.set(k, x) };
};
const sink = () => ({ setLayerStateProvider() {}, onLayerStateChange() {} });
const cesiumEntry = {
enabledLayerIds: ['wind'],
options: { wind: { model: 'gfs' } },
};
test('same-engine Back to a gfs entry restores gfs (reference)', async () => {
const m = manager();
const c = new LayerStateCoordinator(m, sink(), { storage: storage() });
await m.setEnabled('wind', true, { origin: 'user' });
m.setLayerParams('wind', { model: 'ifs' }, { origin: 'user' });
assert.equal(m.getLayerParams('wind').model, 'ifs');
await c.applyShareLayerState({ shareLayerState: cesiumEntry });
assert.equal(m.getLayerParams('wind').model, 'gfs');
});
const handoffOf = (m) =>
new Map(
[...m.layers].map(([id, entry]) => [
id,
{ entry, enabled: m.isEffectivelyEnabled(id), durable: id === 'wind' },
]),
);
test('cross-engine Back to a gfs entry restores gfs', async () => {
const m = manager();
await m.setEnabled('wind', true, { origin: 'user' });
m.setLayerParams('wind', { model: 'ifs' }, { origin: 'user' });
const handoffLayers = new Map(
[...m.layers].map(([id, entry]) => [
id,
{
entry,
enabled: m.isEffectivelyEnabled(id),
durable: id === 'wind',
visit: true,
},
]),
);
const c = new LayerStateCoordinator(m, sink(), { storage: storage() });
await c.start({ shareLayerState: cesiumEntry, handoffLayers });
assert.equal(c.getDurableState().options.wind.model, 'gfs');
assert.equal(
m.getLayerParams('wind').model,
'gfs',
'live wind should follow the visited entry',
);
});
test('a picked engine keeps the live layer options, not the address', async () => {
const m = manager();
await m.setEnabled('wind', true, { origin: 'user' });
m.setLayerParams('wind', { model: 'ifs' }, { origin: 'user' });
const writes = windParamWrites;
const c = new LayerStateCoordinator(m, sink(), { storage: storage() });
await c.start({ shareLayerState: cesiumEntry, handoffLayers: handoffOf(m) });
assert.equal(windParamWrites, writes, 'a pick writes no params');
assert.equal(m.getLayerParams('wind').model, 'ifs');
});
test('an engine switch leaves a retained layer whose options match alone', async () => {
const m = manager();
await m.setEnabled('wind', true, { origin: 'user' });
m.setLayerParams('wind', { model: 'gfs' }, { origin: 'user' });
const writes = windParamWrites;
const c = new LayerStateCoordinator(m, sink(), { storage: storage() });
const results = await c.start({
shareLayerState: cesiumEntry,
handoffLayers: handoffOf(m),
});
assert.equal(windParamWrites, writes, 'no params write for equal options');
const wind = results.find((result) => result.layerId === 'wind');
assert.equal(wind.phase, 'retained');
assert.equal(wind.succeeded, true);
assert.deepEqual(wind.appliedOptions, {});
});
+2 -3
View File
@@ -1207,9 +1207,8 @@ export class LayerLifecycle extends LayerSceneBinding {
const entry = this.layers.get(layerId);
if (!entry) return { intentEpoch: null, promise: Promise.resolve() };
const desiredState = Boolean(shouldEnable);
// A layer leaving ends the camera arrival correction on a globe with a
// viewer (Cesium).
if (!desiredState && this.viewer) cancelCameraArrival(this.engine);
// A layer leaving ends its camera arrival correction.
if (!desiredState) cancelCameraArrival(this.engine);
if (entry.destroying) {
return {
intentEpoch: null,
+15 -3
View File
@@ -169,10 +169,17 @@ for (const makeHarness of [fakeHarness, createCesiumMoversEngine]) {
height(native.gevDisplayPosition()) < 100,
'a ready tracked model releases the billboard floor',
);
// While the model owns the visual the card sits on it, not on the
// released billboard floor below it.
const card = { ...publications.at(-1).position() };
assert.deepEqual(
publications.at(-1).position(),
follow.label.position(),
'the card uses the follow label cache',
card,
{ ...native.gevVisualPosition() },
'the card anchors on the tracked model',
);
assert.ok(
height(card) >= 204.5 && height(card) < 217,
'the card stands with the model on the sampled ground',
);
const cached = { ...native.gevDisplayPosition() };
publications.at(-1).position();
@@ -185,6 +192,11 @@ for (const makeHarness of [fakeHarness, createCesiumMoversEngine]) {
await frames();
const zoomedOut = layer.qaDrawn().find((row) => row.trackedModel)?.model;
assert.ok(!zoomedOut?.show, 'zooming out releases the tracked model');
assert.deepEqual(
{ ...publications.at(-1).position() },
{ ...follow.label.position() },
'without a model the card uses the follow label cache',
);
if (layerId === 'flights')
assert.ok(
height(native.gevDisplayPosition()) >= 205.5,
+1
View File
@@ -191,6 +191,7 @@ export function createTrackedReadout(
return typeof model === 'function' ? model() : model;
},
gevDisplayPosition: () => (handle.label ?? label).position(),
gevVisualPosition: () => handle.native?.gevVisualPosition?.(),
};
_labelSubjects.set(handle, subject);
}
@@ -0,0 +1,52 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createTrackedReadout } from './trackedReadout.js';
test('followed aircraft card anchors to the model the person sees (gevVisualPosition)', () => {
const display = { x: 1, y: 0, z: 0 };
const visual = { x: 1, y: 0, z: 100 };
const native = {
gevTrackedId: 'flight:abc',
gevLabelModel: { title: 'ABC123' },
gevDisplayPosition: () => display,
gevVisualPosition: () => visual,
};
const handle = {
native,
label: {
id: 'flight:abc',
model: () => native.gevLabelModel,
position: () => native.gevDisplayPosition(),
},
};
const listeners = [];
const engine = {
camera: {
following: () => handle,
followChanged: {
addEventListener: (f) => {
listeners.push(f);
return () => {};
},
},
},
};
let entries = null;
const overlay = {
setEntries(_id, e) {
entries = e;
},
setVisible() {},
clearSource() {
entries = null;
},
};
const readout = createTrackedReadout(engine, {
overlay,
events: new EventTarget(),
selectedContext: () => null,
});
readout.init();
assert.ok(entries?.length === 1, 'card published');
assert.deepEqual(entries[0].position(), visual);
});
-24
View File
@@ -51,30 +51,6 @@ export const VESSEL_TYPE_CSS_COLORS = Object.freeze([
...new Set([...TYPE_STYLES, DEFAULT_STYLE].map(({ css }) => css)),
]);
const NUMERIC_TYPE_SPECIALS = {
30: 'FISHING',
31: 'TOWING',
32: 'TOWING',
33: 'DREDGER',
34: 'DIVE OPS',
35: 'MILITARY',
36: 'SAILING',
37: 'PLEASURE',
50: 'PILOT',
51: 'SAR',
52: 'TUG',
53: 'PORT TENDER',
54: 'ANTI-POLLUTION',
55: 'LAW ENFORCE',
58: 'MEDICAL',
};
const NUMERIC_TYPE_FAMILIES = {
4: 'HIGH-SPEED',
6: 'PASSENGER',
7: 'CARGO',
8: 'TANKER',
9: 'OTHER',
};
// Card text for the type tokens above. The tokens stay English: TYPE_STYLES
// and tests match on them.
const TYPE_DISPLAY_KEYS = Object.freeze({