Remove the weather and wind imagery fallbacks

Require engine.imagery for weather and wind and load the wind flow backend
from the layer manifest. Preserve Cesium's staging, frame retention, shell
ordering, wind fade and streamlines; Navara follows the same display policy.
Remove obsolete rendering modules and their three translated status keys.
Run every weather and wind display case on both the fake engine and the
headless Cesium engine, keeping the existing behavioural assertions.

Coupling: Cesium import files fall from 27 to 25, viewer lines from 1232 to
1177 and engine-name lines from 63 to 62. The explicit Cesium wind flow
backend deliberately raises renderer lines from 330 to 344 and extension
reads from 8 to 9; every other count stays unchanged.

Browser checks to run
GOOGLE_MAPS_API_KEY= CESIUM_ION_TOKEN= npm run dev -- --port 4291
node scripts/qa-contract-suite.mjs http://localhost:4291
node scripts/qa-weather-compare.mjs shoot http://localhost:4291 --out=qa-shots/weather-after

Compare weather and wind against the previous capture on both engines.
This commit is contained in:
German Khokhlov committed 2026-11-07 12:16:27 +04:00
1 parent c73c5382d4
commit c079b329d0
44 files changed
+1983 -4858

No files matched your search

@@ -4,7 +4,7 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { setLocale, t } from '../../i18n/index.js';
import { SCALAR_UNAVAILABLE, WIND_FIELDS } from './fields.js';
import { fieldUnavailableText } from './rendering.js';
import { fieldUnavailableText } from './fields.js';
for (const locale of ['es', 'ru']) {
test(`${locale}: every field's unavailable status has a translation`, () => {
+14
View File
@@ -11,6 +11,20 @@ export const SCALAR_UNAVAILABLE = Object.freeze({
pressure: msg('Mean sea level pressure field unavailable'),
});
// English for diagnostics; the row status shows it translated (index.js). The
// scalar texts are the source's own.
const FIELD_UNAVAILABLE = Object.freeze({
speed: msg('Wind speed field unavailable'),
...SCALAR_UNAVAILABLE,
});
/** English status for a scalar overlay with no drawable field. */
export function fieldUnavailableText(overlay) {
return Object.hasOwn(FIELD_UNAVAILABLE, overlay)
? FIELD_UNAVAILABLE[overlay]
: null;
}
/** Fixed physical scales shared by imagery and the field legend. */
export const WIND_FIELDS = Object.freeze({
speed: Object.freeze({
+16 -47
View File
@@ -1,5 +1,4 @@
import * as Cesium from 'cesium';
import { createWindRendering } from './rendering.js';
import { createWindDisplay } from './render/display.js';
import { WIND_FIELDS } from './fields.js';
import {
formatWindReading,
@@ -50,14 +49,15 @@ export function windStats(manifest) {
};
}
/** Construct one wind layer with an explicit source and owned animation. */
/** Construct one wind layer with an explicit source and owned animation. It
* draws through its display (render/display.js) on the engine it is attached
* to: `createNativeRendering(engine, options)`, the application's, which
* passes each engine's streamlines in, or the display made here, which draws
* the colour field alone. */
export function createWindLayer({
feed,
clock,
cesium = null,
container,
createRendering = createWindRendering,
createNativeRendering,
createNativeRendering = createWindDisplay,
} = {}) {
if (typeof feed?.getSnapshot !== 'function')
throw new TypeError('Wind requires a snapshot source');
@@ -66,7 +66,6 @@ export function createWindLayer({
let request = null;
let enabled = false;
let rendering = null;
let imageryHost = null;
let manifest = null;
let error = null;
let loading = false;
@@ -125,44 +124,18 @@ export function createWindLayer({
attachRenderer(nextViewer, { engine: nextEngine = null } = {}) {
viewer = nextViewer;
engine = nextEngine;
const cesiumRendering = (options) =>
createRendering({
// Read on Cesium only: the production build's Cesium global
// loads with the first Cesium globe.
cesium: cesium ?? Cesium,
container: container ?? nextViewer.container,
getViewer: () => viewer,
getHost: () =>
imageryHost?.() ?? {
collection: viewer.imageryLayers ?? viewer.scene?.imageryLayers,
kind: 'globe',
},
onStatusChange: notify,
...options,
});
// The engine's display (render/display.js) when the layer has one,
// with Cesium's flow (no field) on Cesium; an engine's own flow
// backend takes its place. Else the Cesium renderer draws it all.
rendering =
(engine
? createNativeRendering?.(engine, {
flow: nextViewer ? () => cesiumRendering({ field: false }) : null,
onStatusChange: notify,
})
: null) ?? cesiumRendering();
rendering.attach();
rendering.setOptions?.({ overlay, paused });
const target =
container ?? nextViewer?.container ?? engine?.host.container;
if (!engine) return;
rendering = createNativeRendering(engine, { onStatusChange: notify });
rendering?.attach();
rendering?.setOptions?.({ overlay, paused });
inspectionMarker = createWindInspectionMarker({
container: target,
container: engine.host.container,
viewer,
cesium: engine ? null : (cesium ?? Cesium),
engine,
});
if (enabled && manifest && !manifest.unavailable) {
rendering.setField(manifest);
rendering.start();
rendering?.setField(manifest);
rendering?.start();
}
if (sampledPosition) inspectionMarker.show(sampledPosition);
},
@@ -170,13 +143,9 @@ export function createWindLayer({
inspectionMarker?.destroy();
inspectionMarker = null;
rendering?.destroy();
rendering = imageryHost = viewer = engine = null;
rendering = viewer = engine = null;
},
attachShellServices(services) {
imageryHost =
typeof services?.imageryHost === 'function'
? services.imageryHost
: null;
attachShellServices() {
rendering?.rehome?.();
},
enable() {
+166 -43
View File
@@ -4,6 +4,7 @@ import { createWindLayer, formatWindValidTime, windStats } from './index.js';
import { useWindInspectionStore } from '../../ui/stores/windInspection.js';
import { applicationPinia } from '../../ui/vueRuntime.js';
import * as geo from '../../geo/index.js';
import { createFakeEngine } from '../../globe/testing/fakeEngine.js';
const snapshot = (model) => ({
model,
@@ -19,8 +20,11 @@ function harness(feed, diagnostics = {}) {
]),
);
rendering.getDiagnostics = () => diagnostics;
const layer = createWindLayer({ feed, createRendering: () => rendering });
layer.init({ container: {} });
const layer = createWindLayer({
feed,
createNativeRendering: () => rendering,
});
layer.init(null, { engine: createFakeEngine() });
layer.enable();
return { layer, calls };
}
@@ -261,12 +265,12 @@ test('renderer readiness pushes fresh loading stats and controls to the displaye
};
const layer = createWindLayer({
feed: { getSnapshot: async () => snapshot('gfs') },
createRendering(options) {
createNativeRendering(engine, options) {
statusChanged = options.onStatusChange;
return rendering;
},
});
layer.init({ container: {} });
layer.init(null, { engine: createFakeEngine() });
layer.enable();
let displayed;
layer.setRowControlsListener(() => {
@@ -281,12 +285,18 @@ test('renderer readiness pushes fresh loading stats and controls to the displaye
await update;
assert.equal(displayed.loading, true);
assert.match(displayed.info, /Valid: [^\n]+ · preparing/);
assert.equal(displayed.info.split('\n').length, loadingInfo.split('\n').length);
assert.equal(
displayed.info.split('\n').length,
loadingInfo.split('\n').length,
);
ready = true;
statusChanged();
assert.equal(displayed.loading, false);
assert.doesNotMatch(displayed.info, / · preparing| · loading/);
assert.equal(displayed.info.split('\n').length, loadingInfo.split('\n').length);
assert.equal(
displayed.info.split('\n').length,
loadingInfo.split('\n').length,
);
layer.destroy();
});
@@ -300,7 +310,11 @@ test('weather summary describes the selected forecast and count remains numeric'
assert.equal(summary.units, 'km/h');
assert.match(summary.detail, /GFS forecast.*UTC/);
assert.equal((summary.detail.match(/UTC/g) || []).length, 1);
assert.equal(layer.getRowControls().chips.find(c => c.id === 'overlay-temperature').label, 'Temperature');
assert.equal(
layer.getRowControls().chips.find((c) => c.id === 'overlay-temperature')
.label,
'Temperature',
);
layer.destroy();
});
@@ -315,27 +329,44 @@ test('sample stays fixed across model, field and unit changes; dismissal and dis
};
const viewer = {
container,
camera: { positionWC: {}, pickEllipsoid: () => { samples++; return geo.cartesian3.fromDegrees(0, 0); } },
camera: {
positionWC: {},
pickEllipsoid: () => {
samples++;
return geo.cartesian3.fromDegrees(0, 0);
},
},
scene: {
mode: 3,
canvas: { clientWidth: 800, clientHeight: 600, getBoundingClientRect: () => ({ left: 0, top: 0 }) },
canvas: {
clientWidth: 800,
clientHeight: 600,
getBoundingClientRect: () => ({ left: 0, top: 0 }),
},
cartesianToCanvasCoordinates: () => ({ x: 400, y: 300 }),
postRender: { addEventListener(fn) { listener = fn; return () => { listener = null; }; } },
postRender: {
addEventListener(fn) {
listener = fn;
return () => {
listener = null;
};
},
},
requestRender() {},
},
};
const rendering = Object.fromEntries(['attach', 'start', 'stop', 'clear', 'destroy', 'setField'].map(name => [name, () => {}]));
const rendering = Object.fromEntries(
['attach', 'start', 'stop', 'clear', 'destroy', 'setField'].map((name) => [
name,
() => {},
]),
);
const layer = createWindLayer({
feed: { getSnapshot: async ({ model }) => complete(model) },
cesium: {
Cartesian2: class {}, Ellipsoid: { WGS84: {} }, SceneMode: { SCENE3D: 3 },
Cartographic: { fromCartesian: point => point }, Math: { toDegrees: value => value },
EllipsoidalOccluder: class { isPointVisible() { return true; } },
},
createRendering: () => rendering,
createNativeRendering: () => rendering,
});
layer.init(viewer);
// A Cesium page: the viewer samples, the engine projects the marker.
layer.init(viewer, { engine: createFakeEngine({ container }) });
layer.enable();
await layer.update();
layer.setParams({ inspect: true });
@@ -350,26 +381,52 @@ test('sample stays fixed across model, field and unit changes; dismissal and dis
assert.match(changed.wind, /mph/);
assert.equal(samples, 1, 'units do not resample');
assert.equal(layer.getRowControls().summary.result.id, 'reading');
assert.deepEqual(layer.getRowControls().summary.settings.map(({ label }) => label), ['MODEL', 'FIELD', 'UNITS', 'MOTION']);
assert.deepEqual(
layer.getRowControls().summary.settings.map(({ label }) => label),
['MODEL', 'FIELD', 'UNITS', 'MOTION'],
);
assert.ok(marker());
assert.equal(typeof listener, 'function');
viewer.camera.pickEllipsoid = () => { samples++; return geo.cartesian3.fromDegrees(70, 20); };
viewer.camera.pickEllipsoid = () => {
samples++;
return geo.cartesian3.fromDegrees(70, 20);
};
layer.setParams({ overlay: 'speed' });
assert.equal(layer.getRowControls().summary.reading.coordinates, captured.coordinates);
assert.equal(
layer.getRowControls().summary.reading.coordinates,
captured.coordinates,
);
layer.setParams({ model: 'ifs' });
await new Promise(resolve => setImmediate(resolve));
await new Promise((resolve) => setImmediate(resolve));
const resampled = layer.getRowControls().summary.reading;
assert.equal(resampled.coordinates, captured.coordinates);
assert.equal(resampled.model, 'ECMWF');
assert.equal(resampled.position, captured.position);
assert.equal(samples, 1, 'model and field changes never sample the moved camera');
assert.match(layer.getRowControls().summary.result.lines.find(({ id }) => id === 'meta').text, /ECMWF · valid/);
assert.equal(
samples,
1,
'model and field changes never sample the moved camera',
);
assert.match(
layer.getRowControls().summary.result.lines.find(({ id }) => id === 'meta')
.text,
/ECMWF · valid/,
);
await layer.update();
assert.equal(layer.getRowControls().summary.reading.coordinates, captured.coordinates);
assert.equal(
layer.getRowControls().summary.reading.coordinates,
captured.coordinates,
);
layer.setParams({ inspect: true });
assert.equal(layer.getRowControls().summary.reading.coordinates, '20.00°N · 70.00°E');
assert.equal(
layer.getRowControls().summary.reading.coordinates,
'20.00°N · 70.00°E',
);
assert.equal(samples, 2, 'the next explicit read samples the new center');
for (const change of [() => layer.setParams({ inspect: false }), () => layer.disable()]) {
for (const change of [
() => layer.setParams({ inspect: false }),
() => layer.disable(),
]) {
layer.setParams({ inspect: true });
assert.ok(marker());
change();
@@ -384,14 +441,24 @@ test('sample stays fixed across model, field and unit changes; dismissal and dis
test('observed history labels wind as a forecast without changing its data or parameters', async () => {
const { createWeatherClock } = await import('../weather/clock.js');
const clock = createWeatherClock();
const layer = createWindLayer({ feed: { getSnapshot: async () => snapshot('gfs') }, clock });
const layer = createWindLayer({
feed: { getSnapshot: async () => snapshot('gfs') },
clock,
});
let changes = 0;
layer.setRowControlsListener(() => changes++);
const params = layer.getParams();
await clock.setTarget('2026-09-14T12:00:00.000Z');
assert.equal(layer.getRowControls().summary.status, null, 'history does not mask source status');
assert.equal(
layer.getRowControls().summary.status,
null,
'history does not mask source status',
);
assert.ok(changes > 0);
assert.match(layer.getRowControls().info, /Forecast · does not follow history/);
assert.match(
layer.getRowControls().info,
/Forecast · does not follow history/,
);
assert.deepEqual(layer.getParams(), params);
await clock.latest();
assert.equal(layer.getRowControls().summary.status, null);
@@ -403,16 +470,43 @@ test('observed history labels wind as a forecast without changing its data or pa
});
test('wind unit chips appear only alongside a speed legend, including canvas trails', async () => {
let renderMode = 'gpu-streamlines'; let imageryError = null;
const layer = createWindLayer({ feed: { getSnapshot: async () => complete('gfs') }, createRendering: () => ({ attach() {}, start() {}, clear() {}, setField() {}, setOptions() {}, getDiagnostics: () => ({ renderMode, imageryError }), stop() {}, destroy() {} }) });
layer.init({ container: {} }); layer.enable(); await layer.update();
const unitChips = () => layer.getRowControls().chips.filter(({ id }) => id.startsWith('units-'));
assert.equal(layer.getRowControls().readout, true); assert.equal(layer.getRowControls().summary.coverage, 'Global · 1° grid');
assert.deepEqual(unitChips(), []); assert.deepEqual(layer.getRowControls().legend, []);
renderMode = 'canvas-fallback'; assert.equal(unitChips().length, 3); assert.ok(layer.getRowControls().legend.length);
renderMode = 'gpu-streamlines'; layer.setParams({ overlay: 'speed' }); assert.equal(unitChips().length, 3);
imageryError = 'Unavailable'; assert.deepEqual(unitChips(), []); imageryError = null;
for (const overlay of ['pressure', 'temperature', 'none']) { layer.setParams({ overlay }); assert.deepEqual(unitChips(), []); }
let renderMode = 'gpu-streamlines';
let imageryError = null;
const layer = createWindLayer({
feed: { getSnapshot: async () => complete('gfs') },
createNativeRendering: () => ({
attach() {},
start() {},
clear() {},
setField() {},
setOptions() {},
getDiagnostics: () => ({ renderMode, imageryError }),
stop() {},
destroy() {},
}),
});
layer.init(null, { engine: createFakeEngine() });
layer.enable();
await layer.update();
const unitChips = () =>
layer.getRowControls().chips.filter(({ id }) => id.startsWith('units-'));
assert.equal(layer.getRowControls().readout, true);
assert.equal(layer.getRowControls().summary.coverage, 'Global · 1° grid');
assert.deepEqual(unitChips(), []);
assert.deepEqual(layer.getRowControls().legend, []);
renderMode = 'canvas-fallback';
assert.equal(unitChips().length, 3);
assert.ok(layer.getRowControls().legend.length);
renderMode = 'gpu-streamlines';
layer.setParams({ overlay: 'speed' });
assert.equal(unitChips().length, 3);
imageryError = 'Unavailable';
assert.deepEqual(unitChips(), []);
imageryError = null;
for (const overlay of ['pressure', 'temperature', 'none']) {
layer.setParams({ overlay });
assert.deepEqual(unitChips(), []);
}
layer.destroy();
});
@@ -430,9 +524,9 @@ test('a parameter replacement during manager enable does not roll the layer back
getSnapshot: (args) =>
new Promise((resolve) => pending.push({ ...args, resolve })),
},
createRendering: () => rendering,
createNativeRendering: () => rendering,
});
const manager = new LayerLifecycle({ container: {} });
const manager = new LayerLifecycle(null, { engine: createFakeEngine() });
manager.register(layer);
const enabled = manager.setEnabled('wind', true);
for (let i = 0; i < 20 && !pending.length; i++) await Promise.resolve();
@@ -448,3 +542,32 @@ test('a parameter replacement during manager enable does not roll the layer back
assert.equal(layer.getStats().count, 4);
await manager.destroyAll();
});
test('without a renderer of the application the layer draws its display on the engine; without an engine nothing', async () => {
const feed = { getSnapshot: async () => complete('gfs') };
const engine = createFakeEngine();
const layer = createWindLayer({ feed });
layer.init(null, { engine });
assert.equal(engine.frames.preRender.numberOfListeners, 1);
layer.enable();
await layer.update();
// The display's own diagnostics: the field, and no streamlines.
assert.deepEqual(layer.getDiagnostics(), {
overlay: 'none',
paused: false,
imageryActive: false,
host: null,
field: null,
imageryError: null,
});
layer.destroy();
assert.equal(engine.frames.preRender.numberOfListeners, 0);
const bare = createWindLayer({ feed });
bare.init(null);
bare.enable();
assert.equal(await bare.update(), true);
assert.equal(bare.getStats().count, 4);
assert.deepEqual(bare.getDiagnostics(), {});
bare.destroy();
});
+22
View File
@@ -87,3 +87,25 @@ export function advectParticle(
);
return particle;
}
// Snapshots own immutable decoded arrays. Compare their contents, not grid URLs
// (which include the scalar overlay) or only cycle IDs (which can be revised).
// This bounded scan runs on acquisition, never in the animation loop.
export function sameWind(previous, next, previousField, nextField) {
if (!previous || !next || !previousField || !nextField) return false;
for (const key of ['model', 'level', 'units'])
if (previous[key] !== next[key]) return false;
for (const key of ['runIso', 'validIso', 'forecastHour', 'date', 'hour'])
if (previous.cycle?.[key] !== next.cycle?.[key]) return false;
for (const key of ['nx', 'ny', 'lo1', 'la1', 'dx', 'dy'])
if (previousField[key] !== nextField[key]) return false;
for (const key of ['u', 'v']) {
const before = previousField[key];
const after = nextField[key];
if (!before || !after || before.length !== after.length) return false;
if (before === after) continue;
for (let i = 0; i < before.length; i++)
if (before[i] !== after[i]) return false;
}
return true;
}
+13
View File
@@ -0,0 +1,13 @@
// Cesium's backend of the wind display: the wind renderer's streamlines
// (../rendering.js) over the viewer, read only once a Cesium globe draws.
import * as Cesium from 'cesium';
import { createWindRendering } from '../rendering.js';
export function createWindCesiumFlow(engine, { onStatusChange } = {}) {
return createWindRendering({
cesium: Cesium,
container: engine.host.container,
getViewer: () => engine.extensions.cesium.viewer,
onStatusChange,
});
}
+12 -11
View File
@@ -3,12 +3,12 @@
// imagery drapes on the globe and raised at the wind's shell height on 3D
// tiles, faded out as the camera comes down while streamlines draw (they
// carry the wind near the ground). The streamlines are the engine's own,
// behind one seam: the `flow` backend each engine passes in (Cesium's
// wind renderer without its field, rendering.js; Navara's flow mesh,
// render/navaraFlow.js). Without one the field draws alone.
// behind one seam: the `flow` backend the application passes in for each
// engine (Cesium's wind renderer, rendering.js, on the page's SDK;
// Navara's flow mesh, render/navaraFlow.js). Without one the field draws
// alone.
import { createFieldRaster } from '../fields.js';
import { fieldUnavailableText } from '../rendering.js';
import { createFieldRaster, fieldUnavailableText } from '../fields.js';
import { NO_IMAGERY_HOST } from '../../weather/imageryHost.js';
import { WEATHER_SHELL_HEIGHTS } from '../../weather/shellRendering.js';
import { WEATHER_IMAGERY_ORDER } from '../../weather/render/display.js';
@@ -48,11 +48,12 @@ function rasterCanvas(raster) {
/**
* The wind layer's renderer on any engine (index.js).
* @param {import('../../../globe/contract.js').GlobeEngine} engine
* @param {{ flow?: (engine: object) => object, onStatusChange?: () => void,
* @param {{ flow?: (engine: object, options: object) => object,
* onStatusChange?: () => void,
* createCanvas?: (raster: object) => object }} [options]
* `flow` makes the engine's streamlines (rendering.js's interface:
* attach, setField, setOptions, start, stop, clear, destroy,
* getParticleCount, getDiagnostics).
* `flow(engine, { onStatusChange })` makes the engine's streamlines
* (rendering.js's interface: attach, setField, setOptions, start, stop,
* clear, destroy, getParticleCount, getDiagnostics).
*/
export function createWindDisplay(
engine,
@@ -64,7 +65,7 @@ export function createWindDisplay(
) {
if (!engine?.imagery)
throw new TypeError('The wind display needs a globe engine');
const flow = makeFlow?.(engine) ?? null;
const flow = makeFlow?.(engine, { onStatusChange }) ?? null;
const id = `wind-field-${++fields}`;
let snapshot = null;
let overlay = 'none';
@@ -209,7 +210,7 @@ export function createWindDisplay(
ready: layer.ready(),
}
: null,
imageryError: imageryError ?? drawn.imageryError ?? null,
imageryError,
};
},
};
+188 -5
View File
@@ -1,10 +1,10 @@
// The wind display on the fake engine: its field as one imagery image,
// The wind display on the fake and headless Cesium engines: its field as one imagery image,
// faded with the camera while streamlines draw, raised on 3D tiles; the
// flow is the backend's.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as geo from '../../../geo/index.js';
import { createFakeEngine } from '../../../globe/testing/fakeEngine.js';
import { imageryDisplayTests } from '../../../testSupport/imageryDisplayEngines.mjs';
const { test, createEngine } = imageryDisplayTests();
import { WEATHER_SHELL_HEIGHTS } from '../../weather/shellRendering.js';
import { createWindDisplay, windFieldAlpha } from './display.js';
@@ -55,7 +55,7 @@ test('the field fades below 1200 km while streamlines draw', () => {
});
test('the field is one image layer over the globe, faded by height; the flow draws the paths', () => {
const engine = createFakeEngine();
const engine = createEngine();
const flow = flowStub();
const display = createWindDisplay(engine, {
flow: () => flow,
@@ -94,7 +94,7 @@ test('the field is one image layer over the globe, faded by height; the flow dra
});
test('on 3D tiles the field is raised at the wind’s shell height; none: a status', () => {
const engine = createFakeEngine();
const engine = createEngine();
let surface = 'tiles';
engine.imagery.surface = () => surface;
let changes = 0;
@@ -119,3 +119,186 @@ test('on 3D tiles the field is raised at the wind’s shell height; none: a stat
assert.equal(display.getDiagnostics().host, 'globe');
assert.equal(display.getDiagnostics().imageryError, null);
});
// A display whose field layer counts its alpha writes, over a flow stub that
// draws streamlines (`flowing`) or the canvas fallback.
function fieldHarness({ flowing = true, surface = null } = {}) {
const engine = createEngine();
if (surface) engine.imagery.surface = () => surface.value;
const create = engine.imagery.createLayer.bind(engine.imagery);
const counts = { writes: 0, canvases: 0 };
engine.imagery.createLayer = (options) => {
const layer = create(options);
return {
...layer,
setAlpha(value) {
counts.writes++;
layer.setAlpha(value);
},
};
};
const flow = flowStub();
flow.getDiagnostics = () => ({
renderMode: flowing ? 'gpu-streamlines' : 'canvas-fallback',
});
const display = createWindDisplay(engine, {
flow: () => flow,
createCanvas: (raster) => {
counts.canvases++;
return canvasOf(raster);
},
});
const field = () => {
const [id] = engine.fake.imageryLayers();
return id ? engine.fake.imageryLayer(id) : undefined;
};
return { engine, display, flow, counts, field };
}
const withScalar = (kind, value) => ({
...snapshot(),
scalar: {
kind,
units: kind === 'pressure' ? 'hPa' : '°C',
values: new Float32Array(40).fill(value),
},
});
const MIDPOINT = Math.sqrt(200_000 * 1_200_000);
test('the field builds once, survives frames and pause, replaces cleanly and releases on clear', () => {
const { engine, display, counts, field } = fieldHarness();
display.attach();
display.setOptions({ overlay: 'speed' });
display.setField(snapshot());
display.start();
assert.equal(engine.fake.imageryLayers().length, 1);
assert.equal(counts.canvases, 1);
assert.equal(field().source.image.width, 360);
assert.equal(field().source.image.height, 181);
engine.fake.frames(3);
assert.equal(counts.canvases, 1, 'no texture generation from frames');
display.setOptions({ paused: true });
assert.equal(engine.fake.imageryLayers().length, 1);
display.setOptions({ overlay: 'temperature' });
assert.deepEqual(
engine.fake.imageryLayers(),
[],
'unavailable scalar cannot display the previous field',
);
assert.match(display.getDiagnostics().imageryError, /unavailable/);
display.setField(withScalar('temperature', 20));
assert.equal(engine.fake.imageryLayers().length, 1);
assert.equal(display.getDiagnostics().imageryError, null);
display.clear();
assert.deepEqual(engine.fake.imageryLayers(), []);
display.destroy();
});
for (const overlay of ['speed', 'pressure', 'temperature']) {
test(`${overlay} field fades with log camera height, skips small changes and follows height while paused`, () => {
const { engine, display, counts, field } = fieldHarness();
const base = overlay === 'temperature' ? 1 : 0.85;
display.attach();
display.setOptions({ overlay });
display.setField(
overlay === 'speed'
? snapshot()
: withScalar(overlay, overlay === 'pressure' ? 1013 : 20),
);
display.start();
at(engine, 17_368_000);
assert.equal(field().alpha, base);
assert.equal(field().shown, true);
const writes = counts.writes;
at(engine, 17_368_000);
assert.equal(counts.writes, writes, 'unchanged height never writes alpha');
at(engine, MIDPOINT);
assert.ok(Math.abs(field().alpha - base / 2) < 1e-6, 'log midpoint');
const midpoint = counts.writes;
at(engine, MIDPOINT * 1.001);
assert.equal(counts.writes, midpoint, 'sub-0.005 changes are skipped');
at(engine, MIDPOINT * 1.03);
assert.equal(counts.writes, midpoint + 1, 'larger changes write alpha');
at(engine, 100_000);
assert.equal(field().alpha, 0);
assert.equal(field().shown, false);
display.setOptions({ paused: true });
at(engine, 1_200_000);
assert.equal(field().alpha, base, 'a paused field still follows height');
assert.equal(field().shown, true);
assert.equal(counts.canvases, 1, 'height changes never rebuild it');
display.destroy();
});
}
test('without streamlines the field keeps its base alpha low down', () => {
const { engine, display, field } = fieldHarness({ flowing: false });
display.attach();
display.setOptions({ overlay: 'speed' });
display.setField(snapshot());
at(engine, 1_200);
assert.equal(field().alpha, 0.85);
assert.equal(field().shown, true);
display.destroy();
});
for (const overlay of ['speed', 'temperature']) {
test(`${overlay} raised field fades in 0.1 steps; without streamlines it shows at street level`, () => {
const surface = { value: 'tiles' };
const base = overlay === 'temperature' ? 1 : 0.85;
const field = overlay === 'speed' ? snapshot() : withScalar(overlay, 20);
const h = fieldHarness({ surface });
h.display.attach();
h.display.setOptions({ overlay });
h.display.setField(field);
at(h.engine, MIDPOINT);
assert.equal(h.field().raise, WEATHER_SHELL_HEIGHTS.wind);
assert.equal(h.field().alpha, overlay === 'temperature' ? 0.5 : 0.4);
const writes = h.counts.writes;
at(h.engine, MIDPOINT * 1.01);
assert.equal(h.counts.writes, writes, 'the same step writes nothing');
at(h.engine, 100_000);
assert.equal(h.field().alpha, 0);
assert.equal(h.field().shown, false);
at(h.engine, 1_200_000);
assert.equal(h.field().alpha, overlay === 'temperature' ? 1 : 0.9);
// Back on the globe: the smooth fade.
surface.value = 'globe';
at(h.engine, 1_200_000);
assert.equal(h.field().raise, null);
assert.equal(h.field().alpha, base);
h.display.destroy();
const fallback = fieldHarness({
flowing: false,
surface: { value: 'tiles' },
});
fallback.display.attach();
fallback.display.setOptions({ overlay });
fallback.display.setField(field);
at(fallback.engine, 1_200);
assert.equal(fallback.field().shown, true, 'no height gate on 3D tiles');
assert.equal(fallback.field().alpha, Math.round(base * 10) / 10);
at(fallback.engine, 1_500);
assert.equal(fallback.counts.canvases, 1, 'camera changes keep the field');
fallback.display.destroy();
});
}
test('a field installed with no imagery surface reports hidden and installs on restore', () => {
const surface = { value: 'none' };
const { engine, display, counts } = fieldHarness({ surface });
display.attach();
display.setOptions({ overlay: 'speed' });
display.setField(snapshot());
assert.deepEqual(engine.fake.imageryLayers(), []);
assert.equal(counts.canvases, 0);
assert.equal(
display.getDiagnostics().imageryError,
'Hidden by this map source · choose a globe map',
);
surface.value = 'globe';
display.rehome();
assert.equal(engine.fake.imageryLayers().length, 1);
assert.equal(display.getDiagnostics().imageryError, null);
display.destroy();
});
+1 -1
View File
@@ -3,7 +3,7 @@ import {
WIND_NARROW_PATH_LIMIT,
WIND_PATH_LIMIT,
} from '../streamlines.js';
import { sameWind } from '../rendering.js';
import { sameWind } from '../model.js';
import { createWindFlowMesh } from './flowMesh.js';
const clamp = (n) => Math.max(0, Math.min(1, n));
+9 -238
View File
@@ -1,78 +1,19 @@
import {
createShellSurface,
WEATHER_SHELL_HEIGHTS,
} from '../weather/shellRendering.js';
import { createWindRelief } from './relief.js';
import { orderWeatherImagery } from '../weather/imageryOrder.js';
import { NO_IMAGERY_HOST } from '../weather/imageryHost.js';
import { msg } from '../../i18n/index.js';
import { createWindGpuRendering } from './gpuRendering.js';
import { advectParticle, sampleWind } from './model.js';
import {
createFieldRaster,
SCALAR_UNAVAILABLE,
trailEraseAlpha,
windTrailColor,
} from './fields.js';
import { advectParticle, sampleWind, sameWind } from './model.js';
import { trailEraseAlpha, windTrailColor } from './fields.js';
// English for diagnostics; the row status shows it translated (index.js). The
// scalar texts are the source's own; setOptions accepts only these overlays.
const FIELD_UNAVAILABLE = Object.freeze({
speed: msg('Wind speed field unavailable'),
...SCALAR_UNAVAILABLE,
});
/** English status for a scalar overlay with no drawable field. */
export function fieldUnavailableText(overlay) {
return Object.hasOwn(FIELD_UNAVAILABLE, overlay)
? FIELD_UNAVAILABLE[overlay]
: null;
}
const WIND_FIELD_FADE_HIGH_METERS = 1_200_000;
const WIND_FIELD_FADE_LOW_METERS = 200_000;
const WIND_FIELD_LOG_RANGE = Math.log(
WIND_FIELD_FADE_HIGH_METERS / WIND_FIELD_FADE_LOW_METERS,
);
// Snapshots own immutable decoded arrays. Compare their contents, not grid URLs
// (which include the scalar overlay) or only cycle IDs (which can be revised).
// This bounded scan runs on acquisition, never in the animation loop.
export function sameWind(previous, next, previousField, nextField) {
if (!previous || !next || !previousField || !nextField) return false;
for (const key of ['model', 'level', 'units'])
if (previous[key] !== next[key]) return false;
for (const key of ['runIso', 'validIso', 'forecastHour', 'date', 'hour'])
if (previous.cycle?.[key] !== next.cycle?.[key]) return false;
for (const key of ['nx', 'ny', 'lo1', 'la1', 'dx', 'dy'])
if (previousField[key] !== nextField[key]) return false;
for (const key of ['u', 'v']) {
const before = previousField[key];
const after = nextField[key];
if (!before || !after || before.length !== after.length) return false;
if (before === after) continue;
for (let i = 0; i < before.length; i++)
if (before[i] !== after[i]) return false;
}
return true;
}
/** Globe-projected surface flow plus one owned, static colour field: globe
* imagery on the globe host, a raised shell on the 3D Tiles host. With
* `field: false` it draws the flow alone: the wind display draws the field
* through the globe contract (render/display.js). */
/** The wind's streamlines on Cesium (the wind display's flow backend,
* render/display.js, which draws the colour field): globe-projected surface
* flow over the viewer's scene, GPU streamlines where the context has them,
* else canvas particles in `container`. The Cesium SDK is the page's,
* passed in. */
export function createWindRendering({
cesium,
container,
getViewer,
getHost = () => ({
collection:
getViewer?.()?.imageryLayers ?? getViewer?.()?.scene?.imageryLayers,
kind: 'globe',
}),
eventTarget = globalThis.window,
createGpuRendering = createWindGpuRendering,
onStatusChange,
field: drawsField = true,
} = {}) {
let canvas = null;
let context = null;
@@ -88,12 +29,6 @@ export function createWindRendering({
let overlay = 'none';
let paused = false;
let reducedMotion = false;
let imagery = null;
let shell = null;
let imageryCollection = null;
let imageryKind = null;
let imageryError = null;
let imageryErrorRemove = null;
let media = null;
let removers = [];
let bounds = null;
@@ -297,155 +232,10 @@ export function createWindRendering({
for (const particle of particles) spawn(particle, scene, occluder);
}
function removeImagery() {
imageryErrorRemove?.();
imageryErrorRemove = null;
if (imagery && imageryCollection && !imageryCollection.isDestroyed?.())
imageryCollection.remove(imagery, true);
else if (imagery && !imagery.isDestroyed?.()) imagery.destroy?.();
imagery = null;
shell?.destroy();
shell = null;
imageryCollection = null;
imageryKind = null;
}
function updateImageryFade(camera, settled = false) {
// The tileset shell keeps the quantised move-end fade; globe imagery keeps
// its smooth per-frame fade.
if (
(!imagery && !shell) ||
!camera?.positionCartographic ||
(imageryKind === 'tileset' && !settled)
)
return;
const height = camera.positionCartographic.height;
const fade = !gpuActive
? 1
: height <= WIND_FIELD_FADE_LOW_METERS
? 0
: height >= WIND_FIELD_FADE_HIGH_METERS
? 1
: Math.log(height / WIND_FIELD_FADE_LOW_METERS) /
WIND_FIELD_LOG_RANGE;
const baseAlpha = overlay === 'temperature' ? 1 : 0.85;
const smoothAlpha = baseAlpha * fade;
const alpha =
gpuActive && imageryKind === 'tileset'
? Math.round(smoothAlpha * 10) / 10
: smoothAlpha;
if (shell) {
shell.setAlpha(alpha);
shell.setShow(alpha > 0 && getHost().kind !== 'none');
return;
}
if (Math.abs(imagery.alpha - alpha) > 0.005) imagery.alpha = alpha;
const show = alpha > 0;
if (imagery.show !== show) imagery.show = show;
}
function installImagery() {
removeImagery();
imageryError = null;
const viewer = viewerReady();
if (!drawsField || !snapshot || overlay === 'none' || !viewer) return;
const { collection, kind } = getHost();
if (kind === 'none') {
imageryError = NO_IMAGERY_HOST;
return;
}
const raster = createFieldRaster(snapshot, overlay);
if (!raster) {
imageryError = fieldUnavailableText(overlay);
return;
}
if (
kind === 'tileset'
? !cesium.Primitive
: !collection || !cesium.SingleTileImageryProvider
) {
imageryError = msg('Globe imagery unavailable');
return;
}
try {
const texture = document.createElement('canvas');
texture.width = raster.width;
texture.height = raster.height;
const ctx = texture.getContext('2d');
const pixels = ctx.createImageData(raster.width, raster.height);
pixels.data.set(raster.rgba);
ctx.putImageData(pixels, 0, 0);
if (kind === 'tileset') {
shell = createShellSurface({
viewer,
cesium,
rectangle: cesium.Rectangle.MAX_VALUE,
height: WEATHER_SHELL_HEIGHTS.wind,
});
shell.setImage(texture);
imageryKind = kind;
shell.setAlpha(overlay === 'temperature' ? 1 : 0.85);
updateImageryFade(viewer.scene.camera, true);
viewer.scene?.requestRender?.();
return;
}
const provider = new cesium.SingleTileImageryProvider({
url: texture.toDataURL('image/png'),
tileWidth: raster.width,
tileHeight: raster.height,
rectangle: cesium.Rectangle.MAX_VALUE,
});
imagery = collection.addImageryProvider(provider);
orderWeatherImagery(collection, imagery, 0);
imageryCollection = collection;
imageryKind = kind;
// Temperature colors carry quantitative meaning; double transparency
// blends orange heat into blue ocean and obscures useful gradients.
imagery.alpha = overlay === 'temperature' ? 1 : 0.85;
if (gpuActive) updateImageryFade(viewer.scene.camera, true);
imageryErrorRemove = provider.errorEvent?.addEventListener(() => {
imageryError = msg('Globe field image unavailable');
});
viewer.scene?.requestRender?.();
} catch {
removeImagery();
imageryError = msg('Globe field image unavailable');
}
}
function rehome() {
if (!drawsField || !snapshot || overlay === 'none') return;
const { collection, kind } = getHost();
const wasHidden = imageryError === NO_IMAGERY_HOST;
if ((imagery || shell) && kind !== 'none' && kind !== imageryKind) {
installImagery();
onStatusChange?.();
return;
}
// A host without imagery hides the retained shell until a host returns.
if (shell && kind === 'none') shell.setShow(false);
if (imagery && collection !== imageryCollection) {
imageryCollection?.remove(imagery, false);
imageryCollection = collection;
if (collection) {
collection.add(imagery);
orderWeatherImagery(collection, imagery, 0);
}
viewerReady()?.scene?.requestRender?.();
}
if ((gpuActive || kind === 'tileset') && kind !== 'none')
updateImageryFade(viewerReady()?.scene?.camera, true);
if (kind === 'none') imageryError = NO_IMAGERY_HOST;
else if (wasHidden) {
imageryError = null;
if (!imagery && !shell) installImagery();
}
if (wasHidden !== (imageryError === NO_IMAGERY_HOST)) onStatusChange?.();
}
/** No idle animation for pause/reduced motion; scene events repaint only changed views. */
function viewChanged() {
if (gpuActive) {
const viewer = viewerReady();
if (viewer) updateImageryFade(viewer.scene.camera);
const narrow = (viewer?.scene?.canvas?.clientWidth || 800) < 700;
let visibilityUpdated = false;
if (running && field && !hidden() && narrow !== gpuNarrow) {
@@ -492,7 +282,6 @@ export function createWindRendering({
if (!running || !field || hidden()) return;
const viewer = viewerReady();
if (gpuActive) {
if (viewer) updateImageryFade(viewer.scene.camera);
gpuVisible = viewer ? gpu.updateVisibility(viewer.scene.camera) : false;
if (gpuVisible) {
gpu.tick(flowTime);
@@ -509,11 +298,6 @@ export function createWindRendering({
target.addEventListener(event, callback);
removers.push(() => target.removeEventListener(event, callback));
}
function cameraSettled() {
if (gpuActive || imageryKind === 'tileset')
updateImageryFade(viewerReady()?.scene?.camera, true);
cameraMoved();
}
function cameraMoved() {
viewChanged();
// A parked request-render scene may never run preRender until we wake it.
@@ -536,11 +320,10 @@ export function createWindRendering({
listen(media, 'change', motionChanged);
listen(globalThis.document, 'visibilitychange', motionChanged);
listen(globalThis, 'resize', cameraMoved);
listen(eventTarget, 'gev:map-stack-changed', rehome);
const viewer = viewerReady();
const camera = viewer?.scene?.camera;
listenScene(viewer?.scene?.preRender, viewChanged);
listenScene(camera?.moveEnd, cameraSettled);
listenScene(camera?.moveEnd, cameraMoved);
}
function detachListeners() {
for (const remove of removers) remove();
@@ -688,7 +471,6 @@ export function createWindRendering({
}
return {
rehome,
attach() {
if (canvas) return;
canvas = document.createElement('canvas');
@@ -732,7 +514,6 @@ export function createWindRendering({
resize(viewer);
seed(viewer.scene, makeOccluder(viewer.scene));
}
installImagery();
relief.attach();
motionChanged();
}
@@ -749,17 +530,13 @@ export function createWindRendering({
const changedPause = newPaused !== paused;
overlay = nextOverlay;
paused = newPaused;
if (changedOverlay) {
installImagery();
clearPixels();
}
if (changedOverlay) clearPixels();
if (changedOverlay || changedPause) motionChanged();
},
start() {
if (running || !canvas) return;
running = true;
attachListeners();
rehome();
motionChanged();
},
stop() {
@@ -781,8 +558,6 @@ export function createWindRendering({
gpuVisible = false;
reportedGpuReady = null;
flowTime = 0;
removeImagery();
imageryError = null;
clearPixels();
},
destroy() {
@@ -809,10 +584,6 @@ export function createWindRendering({
relief: relief.getDiagnostics(),
painted,
framePending: frame !== null,
imageryActive: imagery !== null || shell !== null,
host: shell ? 'shell' : imagery ? 'globe' : null,
shell: shell?.getDiagnostics() ?? null,
imageryError,
};
},
};
+4 -442
View File
@@ -1,13 +1,10 @@
// The wind's streamlines on Cesium (rendering.js, the wind display's flow
// backend) over a stub viewer and SDK. The colour field is the display's
// (render/display.test.mjs).
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createWindRendering } from './rendering.js';
import { NO_IMAGERY_HOST } from '../weather/imageryHost.js';
import {
createShellCesium,
createShellScene,
} from '../weather/shellFixture.mjs';
function event() {
const listeners = new Set();
@@ -32,14 +29,9 @@ function harness({
projected = null,
createGpuRendering,
onStatusChange,
getHost,
eventTarget,
shell = false,
} = {}) {
const shellScene = shell ? createShellScene() : null;
const strokes = [];
const clears = [];
const textures = [];
const erasures = [];
let path = [];
const context = {
@@ -76,13 +68,11 @@ function harness({
clientWidth: 800,
clientHeight: 600,
getContext: () => context,
toDataURL: () => 'data:image/png;base64,test',
remove() {
this.removed = true;
},
});
const canvas = makeCanvas();
let created = 0;
const container = {
clientWidth: 800,
clientHeight: 600,
@@ -115,12 +105,7 @@ function harness({
};
globalThis.document = {
hidden: false,
createElement() {
if (!created++) return canvas;
const item = makeCanvas();
textures.push(item);
return item;
},
createElement: () => canvas,
addEventListener(type, cb) {
this.removeVisibility = visibility.addEventListener(cb);
},
@@ -138,35 +123,8 @@ function harness({
globalThis.cancelled = true;
pending.delete(id);
};
const imagery = [];
const removed = [];
const imageryLayers = {
addImageryProvider(provider) {
let alpha = 1;
const layer = {
provider,
show: true,
alphaWrites: 0,
get alpha() {
return alpha;
},
set alpha(value) {
alpha = value;
this.alphaWrites++;
},
};
imagery.push(layer);
return layer;
},
remove(layer, destroy) {
const i = imagery.indexOf(layer);
if (i >= 0) imagery.splice(i, 1);
removed.push({ layer, destroy });
},
};
const viewer = {
container,
imageryLayers,
scene: {
canvas,
camera: {
@@ -178,23 +136,12 @@ function harness({
},
preRender,
requestRender() {},
...(shellScene
? {
primitives: shellScene.primitives,
postRender: shellScene.postRender,
}
: {}),
},
isDestroyed: () => false,
};
const cesium = {
...(shell ? createShellCesium() : {}),
GeographicTilingScheme: Cesium.GeographicTilingScheme,
Credit: Cesium.Credit,
Event: Cesium.Event,
Cartesian3: { fromDegrees: (lon, lat) => ({ lon, lat }) },
Ellipsoid: { WGS84: {} },
Rectangle: { MAX_VALUE: {} },
EllipsoidalOccluder: class {
isPointVisible() {
return !occluded;
@@ -203,12 +150,6 @@ function harness({
SceneTransforms: {
worldToWindowCoordinates: projected ?? (() => ({ x: 100, y: 100 })),
},
SingleTileImageryProvider: class {
constructor(options) {
this.options = options;
this.errorEvent = event();
}
},
};
const rendering = createWindRendering({
cesium,
@@ -216,8 +157,6 @@ function harness({
getViewer: () => viewer,
createGpuRendering,
onStatusChange,
getHost,
eventTarget,
});
return {
rendering,
@@ -227,7 +166,6 @@ function harness({
pending,
strokes,
clears,
textures,
erasures,
visibility,
media,
@@ -235,9 +173,6 @@ function harness({
preRender,
viewer,
cesium,
imagery,
removed,
primitives: () => shellScene?.primitives.items ?? [],
};
}
@@ -389,169 +324,6 @@ test('reduced motion and hidden documents never retain an animation callback', (
h.rendering.destroy();
});
test('scalar imagery builds once, survives pause, replaces cleanly, and releases on clear', () => {
const h = harness();
h.rendering.attach();
h.rendering.setOptions({ overlay: 'speed' });
h.rendering.setField({ grid: FIELD, u: FIELD.u, v: FIELD.v });
h.rendering.start();
assert.equal(h.imagery.length, 1);
assert.equal(h.textures.length, 1);
assert.equal(h.imagery[0].provider.options.tileWidth, 360);
h.callbacks.shift()(16);
h.callbacks.shift()(50);
h.callbacks.shift()(85);
assert.equal(h.textures.length, 1, 'no texture generation from frames');
h.rendering.setOptions({ paused: true });
assert.equal(h.imagery.length, 1);
h.rendering.setOptions({ overlay: 'temperature' });
assert.equal(
h.imagery.length,
0,
'unavailable scalar cannot display the previous field',
);
assert.match(h.rendering.getDiagnostics().imageryError, /unavailable/);
h.rendering.setField({
grid: FIELD,
u: FIELD.u,
v: FIELD.v,
scalar: {
kind: 'temperature',
units: '°C',
values: new Float32Array([20]),
},
});
assert.equal(h.imagery.length, 1);
assert.equal(h.pending.size, 0);
h.rendering.clear();
assert.equal(h.imagery.length, 0);
assert.ok(h.removed.every((item) => item.destroy));
h.rendering.destroy();
});
for (const overlay of ['speed', 'pressure', 'temperature']) {
test(`${overlay} imagery fades with log camera height and resumes from idle`, () => {
const gpu = {
supported: () => true,
setField: () => true,
updateVisibility: (camera) => camera.positionCartographic.height > 15000,
tick() {},
setOptions() {},
clear() {},
destroy() {},
getParticleCount: () => 1,
getDiagnostics: () => ({ ready: true }),
};
const h = harness({ createGpuRendering: () => gpu });
const camera = h.viewer.scene.camera;
const baseAlpha = overlay === 'temperature' ? 1 : 0.85;
const snapshot = {
grid: FIELD,
u: FIELD.u,
v: FIELD.v,
scalar: {
kind: overlay,
units: overlay === 'pressure' ? 'hPa' : '°C',
values: Float32Array.from([overlay === 'pressure' ? 1013 : 20]),
},
};
camera.positionCartographic.height = 17_368_000;
h.rendering.attach();
h.rendering.setOptions({ overlay });
h.rendering.setField(snapshot);
h.rendering.start();
let layer = h.imagery[0];
assert.equal(layer.alpha, baseAlpha);
assert.equal(layer.show, true);
const writes = layer.alphaWrites;
h.preRender.emit();
camera.changed.emit();
camera.moveEnd.emit();
assert.equal(
layer.alphaWrites,
writes,
'unchanged height never writes alpha',
);
camera.positionCartographic.height = Math.sqrt(200_000 * 1_200_000);
h.preRender.emit();
assert.ok(layer.alpha > 0 && layer.alpha < baseAlpha);
assert.ok(Math.abs(layer.alpha - baseAlpha / 2) < 1e-12, 'log midpoint');
const midpointWrites = layer.alphaWrites;
h.preRender.emit();
camera.positionCartographic.height *= 1.001;
h.preRender.emit();
assert.equal(
layer.alphaWrites,
midpointWrites,
'sub-0.005 changes are skipped',
);
camera.positionCartographic.height *= 1.02;
h.preRender.emit();
assert.equal(
layer.alphaWrites,
midpointWrites + 1,
'larger changes write alpha',
);
camera.positionCartographic.height = 100_000;
h.preRender.emit();
assert.equal(layer.alpha, 0);
assert.equal(layer.show, false);
h.rendering.setField({ ...snapshot });
assert.notEqual(h.imagery[0], layer, 'reinstall replaces the layer');
layer = h.imagery[0];
assert.equal(layer.alpha, 0, 'reinstall at low height starts transparent');
assert.equal(layer.show, false, 'reinstall at low height starts hidden');
for (const eventName of ['preRender', 'moveEnd']) {
camera.positionCartographic.height = 1200;
h.preRender.emit();
assert.equal(h.pending.size, 0, 'street-level flow is parked');
camera.positionCartographic.height = 1_200_000;
(eventName === 'preRender' ? h.preRender : camera.moveEnd).emit();
assert.equal(layer.alpha, baseAlpha, 'camera event restores full alpha');
assert.equal(
layer.show,
true,
'camera event unhides imagery without preRender',
);
camera.positionCartographic.height = 200_000;
(eventName === 'preRender' ? h.preRender : camera.moveEnd).emit();
assert.equal(layer.alpha, 0, 'lower bound is transparent');
assert.equal(layer.show, false);
}
h.rendering.setOptions({ paused: true });
camera.positionCartographic.height = 1_200_000;
h.preRender.emit();
assert.equal(
layer.alpha,
baseAlpha,
'paused imagery still follows camera height',
);
assert.equal(h.pending.size, 0);
assert.equal(
h.textures.length,
2,
'height changes never rebuild the texture',
);
h.rendering.destroy();
});
}
test('canvas fallback retains scalar base alpha at low camera height', () => {
const h = harness();
h.viewer.scene.camera.positionCartographic.height = 1200;
h.rendering.attach();
h.rendering.setOptions({ overlay: 'speed' });
h.rendering.setField({ grid: FIELD, u: FIELD.u, v: FIELD.v });
h.rendering.start();
h.preRender.emit();
assert.equal(h.imagery[0].alpha, 0.85);
assert.equal(h.imagery[0].show, true);
h.rendering.destroy();
});
test('projection discontinuities cannot produce long strokes across the viewport', () => {
let calls = 0;
const h = harness({
@@ -829,7 +601,6 @@ test('scalar snapshots retain identical GPU wind geometry and animation phase',
1,
'freshly decoded equal arrays reuse the worker-built primitive',
);
assert.equal(h.imagery.length, 1, 'new scalar field is still installed');
h.callbacks.shift()(1032);
assert.ok(
times.at(-1) >= phase,
@@ -845,11 +616,6 @@ test('scalar snapshots retain identical GPU wind geometry and animation phase',
}),
);
assert.equal(builds, 1, 'revised scalar alone does not rebuild flow');
assert.equal(
h.imagery.length,
1,
'scalar replacement releases the prior image',
);
h.rendering.clear();
h.rendering.setField(snapshot());
assert.equal(builds, 2, 'clear invalidates reuse');
@@ -989,207 +755,3 @@ for (const eventName of ['preRender', 'moveEnd']) {
assert.equal(camera.percentageChanged, 0.5);
});
}
test('scalar field becomes a raised shell on 3D Tiles and survives no-host events', () => {
const eventTarget = new EventTarget();
let host;
const h = harness({
eventTarget,
shell: true,
getHost: () =>
host ?? { collection: h.viewer.imageryLayers, kind: 'globe' },
});
h.rendering.attach();
h.rendering.setOptions({ overlay: 'speed' });
h.rendering.setField(FIELD);
h.rendering.start();
const original = h.imagery[0];
assert.ok(original);
assert.equal(h.rendering.getDiagnostics().host, 'globe');
const tiles = {
addImageryProvider() {
throw new Error('nothing drapes on 3D Tiles');
},
};
host = { collection: tiles, kind: 'tileset' };
eventTarget.dispatchEvent(new Event('gev:map-stack-changed'));
assert.equal(h.imagery.length, 0);
assert.equal(h.removed[0].destroy, true);
const [primitive] = h.primitives();
const geometry = primitive.options.geometryInstances.geometry.options;
assert.equal(geometry.height, 5_000);
assert.equal(geometry.rectangle, h.cesium.Rectangle.MAX_VALUE);
const material = primitive.appearance.material;
assert.equal(h.textures.length, 2);
assert.equal(material.uniforms.image, h.textures[1]);
assert.equal(h.textures[1].width, 360);
assert.equal(h.textures[1].height, 181);
assert.equal(material.uniforms.alpha, 0.85);
assert.equal(primitive.show, true);
const diagnostics = h.rendering.getDiagnostics();
assert.equal(diagnostics.host, 'shell');
assert.equal(diagnostics.imageryActive, true);
assert.equal(diagnostics.shell.height, 5_000);
host = { collection: null, kind: 'none' };
eventTarget.dispatchEvent(new Event('gev:map-stack-changed'));
assert.equal(primitive.show, false);
assert.equal(h.rendering.getDiagnostics().imageryError, NO_IMAGERY_HOST);
h.viewer.scene.camera.moveEnd.emit();
assert.equal(primitive.show, false, 'camera events keep it hidden');
host = { collection: tiles, kind: 'tileset' };
h.rendering.rehome();
assert.deepEqual(h.primitives(), [primitive]);
assert.equal(primitive.show, true);
assert.equal(h.textures.length, 2, 'the retained shell is reused');
assert.equal(h.rendering.getDiagnostics().imageryError, null);
host = null;
h.rendering.rehome();
assert.equal(primitive.destroyed, true);
assert.equal(material.destroyed, true);
assert.equal(h.primitives().length, 0);
assert.equal(h.imagery.length, 1);
assert.equal(h.rendering.getDiagnostics().host, 'globe');
h.rendering.destroy();
assert.equal(h.imagery.length, 0);
assert.equal(h.viewer.scene.postRender.size, 0);
eventTarget.dispatchEvent(new Event('gev:map-stack-changed'));
assert.equal(h.primitives().length, 0);
});
test('scalar installation with no host reports hidden and installs on restore', () => {
let host = { collection: null, kind: 'none' };
const h = harness({ getHost: () => host });
h.rendering.attach();
h.rendering.setOptions({ overlay: 'speed' });
h.rendering.setField(FIELD);
assert.equal(h.imagery.length, 0);
assert.equal(h.textures.length, 0);
assert.equal(
h.rendering.getDiagnostics().imageryError,
'Hidden by this map source · choose a globe map',
);
host = { collection: h.viewer.imageryLayers, kind: 'globe' };
h.rendering.rehome();
assert.equal(h.imagery.length, 1);
assert.equal(h.rendering.getDiagnostics().imageryError, null);
h.rendering.destroy();
});
for (const overlay of ['speed', 'temperature', 'pressure']) {
test(`${overlay} shell alpha follows the height fade in 0.1 steps on moveEnd, install or rehome`, () => {
const gpu = {
supported: () => true,
setField: () => true,
updateVisibility: () => true,
tick() {},
setOptions() {},
clear() {},
destroy() {},
getParticleCount: () => 1,
getDiagnostics: () => ({ ready: true }),
};
let kind = 'tileset';
const h = harness({
shell: true,
createGpuRendering: () => gpu,
getHost: () => ({ collection: h.viewer.imageryLayers, kind }),
});
const camera = h.viewer.scene.camera;
const field = {
...FIELD,
scalar: {
kind: overlay,
units: overlay === 'pressure' ? 'hPa' : '°C',
values: Float32Array.of(overlay === 'pressure' ? 1013 : 20),
},
};
camera.positionCartographic.height = Math.sqrt(200_000 * 1_200_000);
h.rendering.attach();
h.rendering.setOptions({ overlay });
h.rendering.setField(field);
h.rendering.start();
assert.equal(h.imagery.length, 0);
const [primitive] = h.primitives();
const { uniforms } = primitive.appearance.material;
assert.equal(uniforms.alpha, overlay === 'temperature' ? 0.5 : 0.4);
let alpha = uniforms.alpha;
let writes = 0;
Object.defineProperty(uniforms, 'alpha', {
get: () => alpha,
set(value) {
alpha = value;
writes++;
},
});
camera.positionCartographic.height = 100_000;
h.preRender.emit();
h.rendering.setOptions({ paused: true });
assert.equal(writes, 0, 'preRender and pause do not change the shell');
camera.moveEnd.emit();
assert.equal(uniforms.alpha, 0);
assert.equal(primitive.show, false);
camera.positionCartographic.height = 59_999;
camera.moveEnd.emit();
assert.equal(uniforms.alpha, 0, 'the fade still hides the field low down');
assert.equal(primitive.show, false);
camera.positionCartographic.height = Math.sqrt(200_000 * 1_200_000);
camera.moveEnd.emit();
assert.equal(primitive.show, true);
writes = 0;
camera.positionCartographic.height *= 1.01;
camera.moveEnd.emit();
assert.equal(writes, 0, 'the same quantization bucket writes nothing');
camera.positionCartographic.height = 1_200_000;
h.rendering.rehome();
assert.equal(uniforms.alpha, overlay === 'temperature' ? 1 : 0.9);
kind = 'globe';
h.rendering.rehome();
assert.equal(primitive.destroyed, true);
assert.equal(h.imagery[0].provider.options.tileWidth, 360);
assert.equal(h.imagery[0].alpha, overlay === 'temperature' ? 1 : 0.85);
h.rendering.destroy();
assert.equal(camera.moveEnd.size, 0);
});
}
for (const overlay of ['speed', 'temperature', 'pressure']) {
test(`${overlay} canvas fallback shows the shell at street level without changing globe alpha`, () => {
let kind = 'tileset';
const h = harness({
shell: true,
getHost: () => ({ collection: h.viewer.imageryLayers, kind }),
});
const camera = h.viewer.scene.camera;
camera.positionCartographic.height = 1200;
h.rendering.attach();
h.rendering.setOptions({ overlay });
h.rendering.setField({
...FIELD,
scalar: {
kind: overlay,
units: overlay === 'pressure' ? 'hPa' : '°C',
values: Float32Array.of(overlay === 'pressure' ? 1013 : 20),
},
});
h.rendering.start();
const [primitive] = h.primitives();
const textures = h.textures.length;
const baseAlpha = overlay === 'temperature' ? 1 : 0.85;
assert.equal(primitive.show, true, 'no height gate on 3D Tiles');
assert.equal(primitive.appearance.material.uniforms.alpha, baseAlpha);
camera.moveEnd.emit();
h.preRender.emit();
assert.equal(primitive.show, true);
assert.equal(
h.textures.length,
textures,
'camera changes keep the field texture',
);
kind = 'globe';
h.rendering.rehome();
assert.equal(primitive.destroyed, true);
assert.equal(h.imagery[0].show, true);
assert.equal(h.imagery[0].alpha, baseAlpha);
h.rendering.destroy();
});
}
+3 -2
View File
@@ -2,6 +2,7 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { setLocale } from '../../i18n/index.js';
import { createWindLayer } from './index.js';
import { createFakeEngine } from '../../globe/testing/fakeEngine.js';
test('stale wind forecast is marked in the UI language', async () => {
const rendering = Object.fromEntries(
@@ -24,9 +25,9 @@ test('stale wind forecast is marked in the UI language', async () => {
reason: 'Wind upstream unavailable',
}),
},
createRendering: () => rendering,
createNativeRendering: () => rendering,
});
layer.init({ container: {} });
layer.init(null, { engine: createFakeEngine() });
layer.enable();
await layer.update();
try {
+3 -2
View File
@@ -3,6 +3,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createWindLayer } from './index.js';
import { createFakeEngine } from '../../globe/testing/fakeEngine.js';
import { setLocale } from '../../i18n/index.js';
function harness(problem) {
@@ -24,9 +25,9 @@ function harness(problem) {
throw new Error(problem);
},
},
createRendering: () => rendering,
createNativeRendering: () => rendering,
});
layer.init({ container: {} });
layer.init(null, { engine: createFakeEngine() });
layer.enable();
return layer;
}
+6 -2
View File
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createWindLayer, windStats } from './index.js';
import { createFakeEngine } from '../../globe/testing/fakeEngine.js';
import { setLocale, translateKnown } from '../../i18n/index.js';
import { windProxy } from '../../../server/providers/wind.js';
@@ -17,8 +18,11 @@ function harness(feed) {
].map((name) => [name, () => {}]),
);
rendering.getDiagnostics = () => ({});
const layer = createWindLayer({ feed, createRendering: () => rendering });
layer.init({ container: {} });
const layer = createWindLayer({
feed,
createNativeRendering: () => rendering,
});
layer.init(null, { engine: createFakeEngine() });
layer.enable();
return layer;
}