Draw weather, wind and Bhote Koshi through engine.imagery, one display each

engine.imagery gains what these rasters need, on every engine:
- geographic (EPSG:4326) tile schemes and a transform applied to each
  decoded tile (the satellite infrared mask);
- staged source changes, which keep the drawn source until the new one
  has loaded (the weather frame swap), and credit-only changes in place;
- raised layers that draw on a shell above terrain and 3D tiles, rising
  with the camera, with a detail image inside a rectangle. On Cesium this
  is the weather shell primitive, moved into the engine; on Navara the
  pixel's ray meets the ellipsoid grown by the height.

Rain radar, satellite clouds, lightning, the wind field and the Bhote
Koshi event and locator each draw through one render/display.js on both
engines; their Navara renderers and Navara's weather surface pass go.
Cesium's pixels are unchanged in every compared scene. On Navara the
Bhote Koshi images are no longer upside down. Two engine-specific parts
stay behind one backend option each: the wind's streamlines and the
Bhote Koshi story entities.

The coupling report now counts defineGroundEffect calls, not its own
declaration. Coupling: Navara renderer lines fall from 2304 to 1695,
Navara ground passes from 3 to 1 (the Global Context pulses), engine
kind checks from 5 to 2. The contract suite passes on both engines
(Cesium 71/71, Navara 74/74).
This commit is contained in:
German Khokhlov committed 2026-11-07 11:14:50 +04:00
1 parent b53b6a48a7
commit c73c5382d4
39 files changed
+4677 -1114

No files matched your search

+23 -15
View File
@@ -125,23 +125,31 @@ 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?.kind === 'navara'
? createNativeRendering(engine)
: 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',
},
(engine
? createNativeRendering?.(engine, {
flow: nextViewer ? () => cesiumRendering({ field: false }) : null,
onStatusChange: notify,
});
})
: null) ?? cesiumRendering();
rendering.attach();
rendering.setOptions?.({ overlay, paused });
const target =
+216
View File
@@ -0,0 +1,216 @@
// The wind on the globe contract: its colour field (speed, temperature or
// pressure) is one engine.imagery image over the globe, draped where
// 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.
import { createFieldRaster } from '../fields.js';
import { fieldUnavailableText } from '../rendering.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';
const FADE_LOW_METERS = 200_000;
const FADE_HIGH_METERS = 1_200_000;
const FADE_LOG_RANGE = Math.log(FADE_HIGH_METERS / FADE_LOW_METERS);
const OVERLAYS = ['none', 'speed', 'temperature', 'pressure'];
let fields = 0;
/** The field's alpha for a camera `height` m up: none below 200 km, full
* above 1200 km, logarithmic between, while streamlines draw. */
export function windFieldAlpha(overlay, height, flowing) {
const base = overlay === 'temperature' ? 1 : 0.85;
if (!flowing) return base;
const fade = Math.max(
0,
Math.min(
1,
Math.log(Math.max(1, height) / FADE_LOW_METERS) / FADE_LOG_RANGE,
),
);
return base * fade;
}
function rasterCanvas(raster) {
const canvas = document.createElement('canvas');
canvas.width = raster.width;
canvas.height = raster.height;
const context = canvas.getContext('2d');
const pixels = context.createImageData(raster.width, raster.height);
pixels.data.set(raster.rgba);
context.putImageData(pixels, 0, 0);
return canvas;
}
/**
* The wind layer's renderer on any engine (index.js).
* @param {import('../../../globe/contract.js').GlobeEngine} engine
* @param {{ flow?: (engine: 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).
*/
export function createWindDisplay(
engine,
{
flow: makeFlow = null,
onStatusChange = () => {},
createCanvas = rasterCanvas,
} = {},
) {
if (!engine?.imagery)
throw new TypeError('The wind display needs a globe engine');
const flow = makeFlow?.(engine) ?? null;
const id = `wind-field-${++fields}`;
let snapshot = null;
let overlay = 'none';
let paused = false;
let layer = null;
let layerSurface = null;
let imageryError = null;
let lastAlpha = null;
let removeFrame = null;
const flowing = () =>
flow?.getDiagnostics?.().renderMode === 'gpu-streamlines';
function removeField() {
layer?.destroy();
layer = null;
layerSurface = null;
lastAlpha = null;
}
function fade() {
if (!layer) return;
let height;
try {
height = engine.camera.pose().cartographic.height;
} catch {
return;
}
let alpha = windFieldAlpha(overlay, height, flowing());
// On 3D tiles the shell keeps a coarse fade: fewer restyles.
if (layer.raise() !== null) alpha = Math.round(alpha * 10) / 10;
if (
lastAlpha !== null &&
Math.abs(alpha - lastAlpha) <= 0.005 &&
!(alpha === 0 && lastAlpha !== 0)
)
return;
lastAlpha = alpha;
layer.setAlpha(alpha);
layer.show(alpha > 0);
}
function installField() {
removeField();
const previous = imageryError;
imageryError = null;
if (snapshot && overlay !== 'none') {
const surface = engine.imagery.surface();
layerSurface = surface;
if (surface === 'none') imageryError = NO_IMAGERY_HOST;
else {
const raster = createFieldRaster(snapshot, overlay);
if (!raster) imageryError = fieldUnavailableText(overlay);
else {
layer = engine.imagery.createLayer({
id,
order: WEATHER_IMAGERY_ORDER.wind,
alpha: 0,
show: false,
source: { kind: 'image', image: createCanvas(raster) },
...(surface === 'tiles'
? { raise: WEATHER_SHELL_HEIGHTS.wind }
: {}),
});
layerSurface = surface;
fade();
}
}
}
if (previous !== imageryError) onStatusChange();
}
// Every frame: the fade, and the field again on another surface.
function frame() {
if (
snapshot &&
overlay !== 'none' &&
engine.imagery.surface() !== layerSurface
)
installField();
else fade();
}
return {
rehome() {
flow?.rehome?.();
if (snapshot && engine.imagery.surface() !== layerSurface) installField();
},
attach() {
flow?.attach();
removeFrame ??= engine.frames.preRender.addEventListener(frame);
},
setField(next) {
snapshot = next;
flow?.setField(next);
installField();
engine.render.request('wind');
},
setOptions(next = {}) {
paused = typeof next.paused === 'boolean' ? next.paused : paused;
const nextOverlay = OVERLAYS.includes(next.overlay)
? next.overlay
: overlay;
flow?.setOptions({ overlay: nextOverlay, paused });
if (nextOverlay !== overlay) {
overlay = nextOverlay;
installField();
}
engine.render.request('wind');
},
start() {
flow?.start();
engine.render.request('wind');
},
stop() {
flow?.stop();
},
clear() {
flow?.clear();
snapshot = null;
removeField();
imageryError = null;
},
destroy() {
flow?.stop();
flow?.destroy();
removeFrame?.();
removeFrame = null;
snapshot = null;
removeField();
},
getParticleCount: () => flow?.getParticleCount() ?? 0,
getDiagnostics() {
const drawn = flow?.getDiagnostics?.() ?? {};
return {
...drawn,
overlay,
paused,
imageryActive: layer !== null,
host: layer ? (layer.raise() !== null ? 'shell' : 'globe') : null,
field: layer
? {
alpha: layer.alpha(),
shown: layer.shown(),
raise: layer.raise(),
ready: layer.ready(),
}
: null,
imageryError: imageryError ?? drawn.imageryError ?? null,
};
},
};
}
+121
View File
@@ -0,0 +1,121 @@
// The wind display on the fake engine: 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 { WEATHER_SHELL_HEIGHTS } from '../../weather/shellRendering.js';
import { createWindDisplay, windFieldAlpha } from './display.js';
const snapshot = () => {
const nx = 8;
const ny = 5;
return {
model: 'gfs',
grid: { nx, ny, lo1: 0, la1: 90, dx: 45, dy: 45 },
u: Array.from({ length: nx * ny }, (_, i) => 5 + (i % 7)),
v: Array.from({ length: nx * ny }, (_, i) => (i % 3) - 1),
};
};
const canvasOf = (raster) => ({ width: raster.width, height: raster.height });
function flowStub() {
const calls = [];
const flow = {
calls,
attach: () => calls.push('attach'),
setField: () => calls.push('setField'),
setOptions: (options) => calls.push(['setOptions', options.overlay]),
start: () => calls.push('start'),
stop: () => calls.push('stop'),
clear: () => calls.push('clear'),
destroy: () => calls.push('destroy'),
getParticleCount: () => 12,
getDiagnostics: () => ({
renderMode: 'gpu-streamlines',
imageryError: null,
}),
};
return flow;
}
const at = (engine, height) => {
engine.camera.setView({
destination: geo.cartesian3.fromDegrees(0, 0, height),
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
});
engine.fake.emit('frames.preRender');
};
test('the field fades below 1200 km while streamlines draw', () => {
assert.equal(windFieldAlpha('speed', 2_000_000, true), 0.85);
assert.equal(windFieldAlpha('temperature', 100_000, true), 0);
assert.equal(windFieldAlpha('temperature', 100_000, false), 1);
const middle = windFieldAlpha('speed', 489_898, true);
assert.ok(Math.abs(middle - 0.85 / 2) < 0.01);
});
test('the field is one image layer over the globe, faded by height; the flow draws the paths', () => {
const engine = createFakeEngine();
const flow = flowStub();
const display = createWindDisplay(engine, {
flow: () => flow,
createCanvas: canvasOf,
});
display.attach();
display.setField(snapshot());
display.start();
assert.deepEqual(engine.fake.imageryLayers(), [], 'no overlay: no field');
display.setOptions({ overlay: 'speed', paused: false });
const [id] = engine.fake.imageryLayers();
at(engine, 12_000_000);
let field = engine.fake.imageryLayer(id);
assert.equal(field.source.kind, 'image');
assert.deepEqual(
{ ...field.source.rectangle },
{
west: -180,
south: -90,
east: 180,
north: 90,
},
);
assert.equal(field.raise, null);
assert.equal(field.alpha, 0.85);
assert.equal(field.shown, true);
at(engine, 50_000);
field = engine.fake.imageryLayer(id);
assert.equal(field.alpha, 0);
assert.equal(field.shown, false, 'low down the paths carry the wind');
assert.equal(display.getParticleCount(), 12);
assert.deepEqual(flow.calls.slice(0, 3), ['attach', 'setField', 'start']);
display.destroy();
assert.deepEqual(engine.fake.imageryLayers(), []);
assert.equal(flow.calls.at(-1), 'destroy');
});
test('on 3D tiles the field is raised at the wind’s shell height; none: a status', () => {
const engine = createFakeEngine();
let surface = 'tiles';
engine.imagery.surface = () => surface;
let changes = 0;
const display = createWindDisplay(engine, {
createCanvas: canvasOf,
onStatusChange: () => changes++,
});
display.attach();
display.setOptions({ overlay: 'speed' });
display.setField(snapshot());
const [id] = engine.fake.imageryLayers();
assert.equal(engine.fake.imageryLayer(id).raise, WEATHER_SHELL_HEIGHTS.wind);
assert.equal(display.getDiagnostics().host, 'shell');
surface = 'none';
engine.fake.emit('frames.preRender');
assert.deepEqual(engine.fake.imageryLayers(), []);
assert.match(display.getDiagnostics().imageryError, /Hidden by this map/);
assert.equal(changes, 1);
surface = 'globe';
engine.fake.emit('frames.preRender');
assert.equal(engine.fake.imageryLayers().length, 1);
assert.equal(display.getDiagnostics().host, 'globe');
assert.equal(display.getDiagnostics().imageryError, null);
});
@@ -3,88 +3,49 @@ import {
WIND_NARROW_PATH_LIMIT,
WIND_PATH_LIMIT,
} from '../streamlines.js';
import { createFieldRaster } from '../fields.js';
import { fieldUnavailableText, sameWind } from '../rendering.js';
import { createWeatherSurface } from '../../weather/render/navaraSurface.js';
import { WEATHER_SHELL_HEIGHTS } from '../../weather/shellRendering.js';
import { sameWind } from '../rendering.js';
import { createWindFlowMesh } from './flowMesh.js';
const world = {
west: -Math.PI,
south: -Math.PI / 2,
east: Math.PI,
north: Math.PI / 2,
};
const clamp = (n) => Math.max(0, Math.min(1, n));
export function createWindNavaraRenderer(engine, native) {
/**
* The wind's streamlines on Navara (the display's flow backend,
* render/display.js): baked paths as one flow mesh in Navara's view, faded
* in with the camera's height and moved by the page clock while the scene
* is shown and motion is allowed. The colour field is the display's.
*/
export function createWindNavaraFlow(engine, native) {
const canvas = engine.host.canvas,
media = matchMedia('(prefers-reduced-motion: reduce)');
let snapshot,
field,
mesh,
surface,
removeFrame,
lastAlpha,
lastTime,
let snapshot = null,
field = null,
mesh = null,
removeFrame = null,
lastTime = null,
seconds = 0,
paths = 0,
fade = 0;
let running = false,
paused = false,
overlay = 'none',
error = null,
fade = 0,
budget = 0;
let running = false,
paused = false;
const wake = () => engine.render.request('wind');
const limit = () =>
canvas.clientWidth < 700 ? WIND_NARROW_PATH_LIMIT : WIND_PATH_LIMIT;
const build = () => {
mesh?.destroy();
mesh = null;
budget =
canvas.clientWidth < 700 ? WIND_NARROW_PATH_LIMIT : WIND_PATH_LIMIT;
budget = limit();
const baked = bakeWindStreamlines(field, { count: budget });
paths = baked.length;
if (paths) mesh = createWindFlowMesh(native, baked);
};
const paint = () => {
surface?.destroy();
surface = null;
lastAlpha = null;
error = null;
if (!snapshot || overlay === 'none') return;
const raster = createFieldRaster(snapshot, overlay);
if (!raster) {
error = fieldUnavailableText(overlay);
return;
}
const texture = document.createElement('canvas');
texture.width = raster.width;
texture.height = raster.height;
texture
.getContext('2d')
.putImageData(
new ImageData(raster.rgba, raster.width, raster.height),
0,
0,
);
surface = createWeatherSurface(engine, native, 'wind', {
rectangle: world,
height: WEATHER_SHELL_HEIGHTS.wind,
onSettled: wake,
});
surface.setImage(texture);
wake();
};
const frame = () => {
if (!running || document.hidden) {
lastTime = null;
return;
}
const h = engine.camera.pose().cartographic.height;
if (
field &&
budget !==
(canvas.clientWidth < 700 ? WIND_NARROW_PATH_LIMIT : WIND_PATH_LIMIT)
)
build();
if (field && budget !== limit()) build();
fade = clamp((h - 15000) / 45000);
const still = paused || media.matches;
const now = performance.now();
@@ -98,32 +59,14 @@ export function createWindNavaraRenderer(engine, native) {
width: canvas.clientWidth,
height: canvas.clientHeight,
});
if (surface) {
let alpha =
(overlay === 'temperature' ? 1 : 0.85) *
clamp(Math.log(Math.max(1, h) / 200000) / Math.log(6));
if (engine.maps.photorealActive()) alpha = Math.round(alpha * 10) / 10;
if (
lastAlpha == null ||
Math.abs(alpha - lastAlpha) > 0.005 ||
(alpha === 0 && lastAlpha !== 0)
) {
lastAlpha = alpha;
surface.setAlpha(alpha);
surface.setShow(alpha > 0);
}
}
if (mesh && !still && fade) wake();
};
const reset = () => {
mesh?.destroy();
mesh = null;
surface?.destroy();
surface = null;
field = snapshot = null;
paths = 0;
error = null;
lastAlpha = lastTime = null;
lastTime = null;
};
const preferenceChanged = () => {
lastTime = null;
@@ -135,21 +78,17 @@ export function createWindNavaraRenderer(engine, native) {
media.addEventListener('change', preferenceChanged);
document.addEventListener('visibilitychange', preferenceChanged);
},
/** A wind snapshot; its paths are baked again when its vectors changed. */
setField(next) {
const nextField = { ...next.grid, u: next.u, v: next.v };
const changed = !sameWind(snapshot, next, field, nextField);
snapshot = next;
field = nextField;
if (changed) build();
paint();
if (changed || !mesh) build();
wake();
},
setOptions(next) {
paused = next.paused;
if (overlay !== next.overlay) {
overlay = next.overlay;
paint();
}
wake();
},
start() {
@@ -172,7 +111,6 @@ export function createWindNavaraRenderer(engine, native) {
getDiagnostics: () => ({
renderMode: 'gpu-streamlines',
reducedMotion: media.matches,
imageryError: error,
gpu: {
pathCount: paths,
phaseSeconds: seconds,
@@ -180,7 +118,6 @@ export function createWindNavaraRenderer(engine, native) {
heightFade: fade,
vertexCount: (mesh?.segments ?? 0) * 4,
},
surface: surface?.getDiagnostics() ?? null,
}),
};
}
+6 -3
View File
@@ -57,7 +57,9 @@ export function sameWind(previous, next, previousField, nextField) {
}
/** Globe-projected surface flow plus one owned, static colour field: globe
* imagery on the globe host, a raised shell on the 3D Tiles host. */
* 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). */
export function createWindRendering({
cesium,
container,
@@ -70,6 +72,7 @@ export function createWindRendering({
eventTarget = globalThis.window,
createGpuRendering = createWindGpuRendering,
onStatusChange,
field: drawsField = true,
} = {}) {
let canvas = null;
let context = null;
@@ -343,7 +346,7 @@ export function createWindRendering({
removeImagery();
imageryError = null;
const viewer = viewerReady();
if (!snapshot || overlay === 'none' || !viewer) return;
if (!drawsField || !snapshot || overlay === 'none' || !viewer) return;
const { collection, kind } = getHost();
if (kind === 'none') {
imageryError = NO_IMAGERY_HOST;
@@ -409,7 +412,7 @@ export function createWindRendering({
}
function rehome() {
if (!snapshot || overlay === 'none') return;
if (!drawsField || !snapshot || overlay === 'none') return;
const { collection, kind } = getHost();
const wasHidden = imageryError === NO_IMAGERY_HOST;
if ((imagery || shell) && kind !== 'none' && kind !== imageryKind) {