render: wind relief is the globe port's hillshade; the wind layer no longer reaches Cesium

The wind relief now asks the globe port for hillshade surface shading at
0.28 instead of building a globe material itself; the Cesium globe port
draws the same view-directed shading, over terrain normals or the globe's
curvature, and the unbound provider now lists surfaceShading. The wind
layer's canvas flow, bounds, imagery fade and render requests go through
the camera, frame and query ports, so src/layers/wind/rendering.js and
relief.js leave the Cesium allow list.

A refused shading request is taken back so it never shows after Wind is
off, and a camera height that is not a number falls back as before.

The application layers and standalone catalog entries no longer load the
unbound factories themselves: a viewer with no renderer bound
needs render/cesium/unbound loaded first. The contract and current-state
docs say what the Cesium adapter's fields and surface shading do now.
This commit is contained in:
Sameh Khamis committed 2026-11-09 08:13:04 -08:00
1 parent fcd1c09565
commit 2a26d13fff
10 files changed
+285 -315

No files matched your search

+8
View File
@@ -2,6 +2,14 @@
## [Unreleased] ## [Unreleased]
- `gods-eye-view/application/layers` and `gods-eye-view/standalone/catalog`
no longer reach Cesium: the weather shells and the wind layer's colour
shell and flow draw through the renderer's `draw.field` (`rasterShell` and
`windStreamlines`, which the Cesium renderer now draws), and the wind
relief is the globe port's `hillshade` surface shading. The flow animates
as before, and still falls back to the canvas where the renderer refuses
it. A viewer with no renderer bound needs
`gods-eye-view/render/cesium/unbound` loaded once first (samehkhamis).
- `gods-eye-view/input` no longer reaches Cesium: the dispatcher takes its - `gods-eye-view/input` no longer reaches Cesium: the dispatcher takes its
pointer events from the renderer's input port and its picks from the query pointer events from the renderer's input port and its picks from the query
port. A click's `hit`, `topHit`, `drawHit` and `drill()` hits, and port. A click's `hit`, `topHit`, `drawHit` and `drill()` hits, and
+4 -3
View File
@@ -363,9 +363,10 @@ resources and subscriptions. The globe relief helper is enabled with Wind and
released when Wind is disabled. It uses terrain vertex normals released when Wind is disabled. It uses terrain vertex normals
for view-directed shading, falling back to global globe-curvature shading when for view-directed shading, falling back to global globe-curvature shading when
normals are unavailable; the fallback does not show local hillshade. Neither mode normals are unavailable; the fallback does not show local hillshade. Neither mode
adds elevation data or represents sunlight. Relief declines to replace an adds elevation data or represents sunlight. Relief is the globe port's
existing globe material, restores the prior empty material only while still `hillshade` surface shading: the renderer never replaces a globe material
owning it, and leaves later owners intact. someone else holds (it waits until that one is gone), gives the globe back
when Wind is disabled, and leaves later owners intact.
Source acquisition retains deadlines, body budgets, disconnect cancellation, Source acquisition retains deadlines, body budgets, disconnect cancellation,
per-model/field singleflight caching and one-minute failure backoff. Application per-model/field singleflight caching and one-minute failure backoff. Application
catalog construction owns each instance. catalog construction owns each instance.
+6 -2
View File
@@ -65,8 +65,12 @@ optional, so a renderer written before it still conforms:
one, and says how shells stack, blend and update. `FieldHandle.on('drawn')` one, and says how shells stack, blend and update. `FieldHandle.on('drawn')`
says once per spec or `update` that it is drawn, never while hidden. These says once per spec or `update` that it is drawn, never while hidden. These
change `fields` itself rather than add to it, so the renderer follows change `fields` itself rather than add to it, so the renderer follows
`fields` before must follow them; only the stub lists it, and the Cesium `fields` before must follow them. The Cesium adapter lists `fields` and
adapter has no `fields` yet. draws `rasterShell` and `windStreamlines`; it refuses `scalarRaster`. It
draws streamlines only over the whole globe: it reads the grid's samples
as points, the first column at `rectangle.west` and the first row at
`rectangle.north`, rows running south, and traces paths that wrap east
and west, so it refuses a grid short of 360° of longitude.
- `ModulationSector` gains `radius` and `floor` and says what it modulates: - `ModulationSector` gains `radius` and `floor` and says what it modulates:
icons, points and models dimmed toward `floor` outside the band, the map, icons, points and models dimmed toward `floor` outside the band, the map,
lines and shapes as they are, picks unchanged. Its pass is named lines and shapes as they are, picks unchanged. Its pass is named
+40 -75
View File
@@ -1,98 +1,63 @@
// View-directed display lighting over existing terrain normals. This does not import { findGlobe } from '../../render/rendererOf.js';
// represent the Sun, change terrain geometry, or supply missing elevation data.
function reliefSource(terrainNormals) {
const normal = terrainNormals
? 'vec3 normal = normalize(materialInput.normalEC);'
: `vec3 worldPosition = (czm_inverseView * vec4(-materialInput.positionToEyeEC, 1.0)).xyz;
vec3 geodeticNormal = normalize(worldPosition * czm_ellipsoidInverseRadii * czm_ellipsoidInverseRadii);
vec3 normal = normalize(czm_viewRotation * geodeticNormal);`;
return `
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
${normal}
vec3 displayLight = normalize(vec3(-0.45, 0.55, 0.8));
float shade = clamp((1.0 - dot(normal, displayLight)) * 0.32, 0.0, 0.28);
material.diffuse = vec3(0.0);
material.alpha = shade;
return material;
}
`;
}
/** Optional, exclusive globe-material owner; no animation or source acquisition. */ /** The darkest the relief shading gets, as an opacity. */
export function createWindRelief({ cesium, getViewer } = {}) { export const WIND_RELIEF_STRENGTH = 0.28;
/**
* View-directed display shading of the globe's relief while the wind layer
* shows: the globe port's `hillshade` surface shading (capability
* `surfaceShading`), over the terrain's own normals or, without them, the
* ellipsoid's curvature. It stands for no sun, changes no geometry and asks
* for no data. The renderer owns the material: it never takes one someone
* else holds, and gives it back when cleared. No animation or source
* acquisition.
*/
export function createWindRelief({ getViewer, globeOf = findGlobe } = {}) {
// The globe port shading for this layer, and the viewer it belongs to.
let globe = null; let globe = null;
let scene = null; let viewer = null;
let owned = null;
let previous = undefined;
let destroyed = false; let destroyed = false;
let reason = 'Not attached'; let reason = 'Not attached';
let mode = null;
const alive = (value) => value && !value.isDestroyed?.(); const alive = (value) => value && !value.isDestroyed?.();
const active = () =>
Boolean(owned && alive(globe) && globe.material === owned);
function clear() { function clear() {
const changed = active(); if (globe && alive(viewer)) globe.setSurfaceShading(null);
if (changed) globe.material = previous;
if (owned && !owned.isDestroyed?.()) owned.destroy?.();
if (changed && alive(scene)) scene.requestRender?.();
owned = null;
mode = null;
globe = null; globe = null;
scene = null; viewer = null;
previous = undefined;
reason = destroyed ? 'Destroyed' : 'Not attached'; reason = destroyed ? 'Destroyed' : 'Not attached';
} }
return { return {
attach() { attach() {
if (destroyed) return false; if (destroyed) return false;
const viewer = getViewer?.(); const next = getViewer?.();
const nextScene = alive(viewer) ? viewer.scene : null; const port = alive(next) ? globeOf(next) : null;
const nextGlobe = nextScene?.globe; if (globe && globe === port) return true;
const nextMode =
nextGlobe?.terrainProvider?.hasVertexNormals === true
? 'terrain relief'
: 'globe curvature';
if (active() && globe === nextGlobe && mode === nextMode) return true;
clear(); clear();
if (!alive(nextGlobe) || typeof cesium?.Material !== 'function') { if (typeof port?.setSurfaceShading !== 'function') {
reason = 'Globe material unavailable'; reason = 'Globe material unavailable';
return false; return false;
} }
if (nextGlobe.material != null) {
reason = 'Globe material already owned';
return false;
}
// Cesium excludes normal-dependent materials without terrain normals.
// The fallback uses existing position/ellipsoid uniforms: curvature only,
// never an invented terrain normal or an additional provider request.
try { try {
owned = new cesium.Material({ port.setSurfaceShading({
fabric: { kind: 'hillshade',
type: strength: WIND_RELIEF_STRENGTH,
nextMode === 'terrain relief'
? 'GEVWindTerrainRelief'
: 'GEVWindGlobeCurvature',
source: reliefSource(nextMode === 'terrain relief'),
},
translucent: true,
}); });
mode = nextMode;
globe = nextGlobe;
scene = nextScene;
previous = globe.material;
globe.material = owned;
scene.requestRender?.();
reason = null;
return true;
} catch { } catch {
clear(); // The port may hold the request even though it could not draw it;
// take it back so it never shows up later, after Wind is off.
try {
port.setSurfaceShading(null);
} catch {
// Nothing was kept.
}
reason = 'Relief material unavailable'; reason = 'Relief material unavailable';
return false; return false;
} }
globe = port;
viewer = next;
reason = null;
return true;
}, },
clear, clear,
destroy() { destroy() {
@@ -102,11 +67,11 @@ export function createWindRelief({ cesium, getViewer } = {}) {
}, },
getDiagnostics() { getDiagnostics() {
return { return {
active: active(), active: globe !== null,
reason: owned && !active() ? 'Globe material replaced' : reason, reason,
lighting: 'View-directed display shading', lighting: 'View-directed display shading',
mode: active() ? mode : null, mode: globe ? 'hillshade' : null,
maxOpacity: 0.28, maxOpacity: WIND_RELIEF_STRENGTH,
}; };
}, },
}; };
+78 -76
View File
@@ -1,101 +1,103 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { createWindRelief } from './relief.js'; import { createWindRelief, WIND_RELIEF_STRENGTH } from './relief.js';
function fixture({ material = undefined, normals = true } = {}) { // A viewer whose globe port records the shading it is asked for.
const materials = []; function fixture({ shading = true } = {}) {
class Material { const calls = [];
constructor(options) { const port = (name) => ({
this.options = options; name,
this.destroyed = false; ...(shading
materials.push(this); ? {
setSurfaceShading(next) {
calls.push([name, next]);
},
} }
isDestroyed() { : {}),
return this.destroyed;
}
destroy() {
assert.equal(this.destroyed, false);
this.destroyed = true;
}
}
let renders = 0;
const globe = { material, terrainProvider: { hasVertexNormals: normals } };
const scene = { globe, requestRender: () => renders++ };
const viewer = { scene };
const relief = createWindRelief({
cesium: { Material },
getViewer: () => viewer,
}); });
return { relief, globe, scene, viewer, materials, renders: () => renders }; const ports = new Map();
const viewer = { isDestroyed: () => false };
ports.set(viewer, port('first'));
let current = viewer;
const relief = createWindRelief({
getViewer: () => current,
globeOf: (given) => ports.get(given) ?? null,
});
return {
relief,
calls,
viewer,
ports,
port,
use: (next) => (current = next),
};
} }
test('relief acquires once and restores the exact prior empty material on clear', () => { test('relief asks the globe port for hillshade once and gives it back on clear', () => {
for (const material of [null, undefined]) { const f = fixture();
const f = fixture({ material });
f.globe.material = material;
assert.equal(f.relief.attach(), true); assert.equal(f.relief.attach(), true);
assert.equal(f.relief.attach(), true); assert.equal(f.relief.attach(), true);
assert.equal(f.materials.length, 1); assert.deepEqual(f.calls, [
assert.equal(f.globe.material, f.materials[0]); ['first', { kind: 'hillshade', strength: WIND_RELIEF_STRENGTH }],
]);
assert.equal(WIND_RELIEF_STRENGTH, 0.28);
assert.equal(f.relief.getDiagnostics().active, true); assert.equal(f.relief.getDiagnostics().active, true);
assert.equal(f.relief.getDiagnostics().maxOpacity, 0.28);
f.relief.clear(); f.relief.clear();
assert.equal(f.globe.material, material); assert.deepEqual(f.calls.at(-1), ['first', null]);
assert.equal(f.materials[0].destroyed, true);
assert.equal(f.renders(), 2);
f.relief.clear(); f.relief.clear();
assert.equal(f.renders(), 2); assert.equal(f.calls.length, 2, 'a second clear asks nothing');
assert.equal(f.relief.getDiagnostics().active, false);
assert.equal(f.relief.attach(), true); assert.equal(f.relief.attach(), true);
f.relief.destroy(); f.relief.destroy();
assert.equal(f.materials[1].destroyed, true); assert.deepEqual(f.calls.at(-1), ['first', null]);
assert.equal(f.relief.attach(), false); assert.equal(f.relief.attach(), false);
} assert.equal(f.relief.getDiagnostics().reason, 'Destroyed');
}); });
test('pre-existing and replacement material owners are never overwritten', () => { test('a globe with no surface shading, or one that refuses it, is reported', () => {
const other = { name: 'other-owner' }; const f = fixture({ shading: false });
const f = fixture({ material: other });
assert.equal(f.relief.attach(), false); assert.equal(f.relief.attach(), false);
assert.equal(f.globe.material, other); assert.equal(f.relief.getDiagnostics().reason, 'Globe material unavailable');
assert.equal(f.materials.length, 0); const refusing = fixture();
f.globe.material = undefined; const asked = [];
assert.equal(f.relief.attach(), true); refusing.ports.get(refusing.viewer).setSurfaceShading = (next) => {
f.globe.material = other; asked.push(next);
assert.equal(f.relief.getDiagnostics().reason, 'Globe material replaced'); if (next) throw new TypeError('no hillshade');
f.relief.clear(); };
assert.equal(f.globe.material, other); assert.equal(refusing.relief.attach(), false);
assert.equal(f.materials[0].destroyed, true); assert.equal(
assert.equal(f.relief.attach(), false); refusing.relief.getDiagnostics().reason,
f.relief.destroy(); 'Relief material unavailable',
assert.equal(f.globe.material, other); );
assert.equal(refusing.relief.getDiagnostics().active, false);
assert.deepEqual(
asked.at(-1),
null,
'a refused request is taken back so it never shows later',
);
}); });
test('missing terrain normals uses curvature only and upgrades when normals exist', () => { test('moving to a new viewer releases the old globe and shades only the new one', () => {
const f = fixture({ normals: false });
assert.equal(f.relief.attach(), true);
assert.equal(f.relief.getDiagnostics().mode, 'globe curvature');
const source = f.materials[0].options.fabric.source;
assert.doesNotMatch(source, /normalEC|slope/);
assert.match(source, /materialInput.positionToEyeEC/);
assert.match(source, /czm_ellipsoidInverseRadii/);
f.globe.terrainProvider.hasVertexNormals = true;
assert.equal(f.relief.attach(), true);
assert.equal(f.materials[0].destroyed, true);
assert.equal(f.relief.getDiagnostics().mode, 'terrain relief');
assert.match(f.materials[1].options.fabric.source, /materialInput.normalEC/);
f.relief.destroy();
assert.equal(f.globe.material, undefined);
});
test('moving to a new viewer releases the old globe and owns only the new one', () => {
const f = fixture(); const f = fixture();
f.relief.attach(); f.relief.attach();
const old = f.globe; const next = { isDestroyed: () => false };
const next = { material: null, terrainProvider: { hasVertexNormals: true } }; f.ports.set(next, f.port('second'));
f.viewer.scene = { globe: next, requestRender() {} }; f.use(next);
assert.equal(f.relief.attach(), true); assert.equal(f.relief.attach(), true);
assert.equal(old.material, undefined); assert.deepEqual(f.calls, [
assert.equal(f.materials[0].destroyed, true); ['first', { kind: 'hillshade', strength: 0.28 }],
assert.equal(next.material, f.materials[1]); ['first', null],
['second', { kind: 'hillshade', strength: 0.28 }],
]);
f.relief.destroy(); f.relief.destroy();
assert.equal(next.material, null); assert.deepEqual(f.calls.at(-1), ['second', null]);
});
test('a destroyed viewer is never asked to give the shading back', () => {
const f = fixture();
f.relief.attach();
f.viewer.isDestroyed = () => true;
f.relief.clear();
assert.equal(f.calls.length, 1);
}); });
+99 -122
View File
@@ -1,16 +1,19 @@
import * as Cesium from 'cesium';
// The renderer drapes through `findGlobe`, and the layer's inspection marker
// reads `findQuery` and `findFrame`; a viewer with no renderer bound gets
// those ports from the factories these modules provide.
import '../../render/cesium/globe.js';
import '../../render/cesium/camera.js';
import { import {
followShellLift, followShellLift,
globeImageryHost,
WEATHER_SHELL_HEIGHTS, WEATHER_SHELL_HEIGHTS,
} from '../weather/shellRendering.js'; } from '../weather/shellRendering.js';
import { createWindRelief } from './relief.js'; import { createWindRelief } from './relief.js';
import { WEATHER_IMAGERY_Z } from '../weather/imageryOrder.js'; import { WEATHER_IMAGERY_Z } from '../weather/imageryOrder.js';
import { findDraw, findGlobe } from '../../render/rendererOf.js'; import {
canvasOf,
findCamera,
findDraw,
findFrame,
findGlobe,
findQuery,
} from '../../render/rendererOf.js';
import { fromDegreesInto } from '../../geo/ellipsoid.js';
import { NO_IMAGERY_HOST } from '../weather/imageryHost.js'; import { NO_IMAGERY_HOST } from '../weather/imageryHost.js';
import { msg } from '../../i18n/index.js'; import { msg } from '../../i18n/index.js';
import { createWindGpuRendering } from './gpuRendering.js'; import { createWindGpuRendering } from './gpuRendering.js';
@@ -67,7 +70,7 @@ let windShells = 0;
/** The colour field as a raised shell over the whole globe, through the /** The colour field as a raised shell over the whole globe, through the
* draw port's raster-shell field; it rises with the camera. */ * draw port's raster-shell field; it rises with the camera. */
function createWindShell(viewer, draw, texture, alpha) { function createWindShell(viewer, draw, texture, alpha, ports) {
const seq = (windShells += 1); const seq = (windShells += 1);
const height = WEATHER_SHELL_HEIGHTS.wind; const height = WEATHER_SHELL_HEIGHTS.wind;
const field = draw.field({ const field = draw.field({
@@ -85,10 +88,14 @@ function createWindShell(viewer, draw, texture, alpha) {
drawn = true; drawn = true;
owed = false; owed = false;
}); });
const offLift = followShellLift(viewer, (liftM) => { const offLift = followShellLift(
viewer,
(liftM) => {
owed = true; owed = true;
field.update({ liftM }); field.update({ liftM });
}); },
ports,
);
return { return {
setAlpha(value) { setAlpha(value) {
if (value === shownAlpha) return; if (value === shownAlpha) return;
@@ -118,7 +125,6 @@ function createWindShell(viewer, draw, texture, alpha) {
/** Globe-projected surface flow plus one owned, static colour field: globe /** 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. */
export function createWindRendering({ export function createWindRendering({
cesium = Cesium,
container, container,
getViewer, getViewer,
getHost: hostOf, getHost: hostOf,
@@ -126,15 +132,13 @@ export function createWindRendering({
createGpuRendering = createWindGpuRendering, createGpuRendering = createWindGpuRendering,
globeOf = findGlobe, globeOf = findGlobe,
drawOf = findDraw, drawOf = findDraw,
cameraOf = findCamera,
frameOf = findFrame,
queryOf = findQuery,
onStatusChange, onStatusChange,
} = {}) { } = {}) {
// The host the shell names, else the viewer's globe imagery. // The host the shell names, else the viewer's globe imagery.
const getHost = () => const getHost = () => hostOf?.() ?? globeImageryHost(getViewer?.());
hostOf?.() ?? {
collection:
getViewer?.()?.imageryLayers ?? getViewer?.()?.scene?.imageryLayers,
kind: 'globe',
};
let canvas = null; let canvas = null;
let context = null; let context = null;
let snapshot = null; let snapshot = null;
@@ -163,16 +167,11 @@ export function createWindRendering({
let gpuActive = false; let gpuActive = false;
let reportedGpuReady = null; let reportedGpuReady = null;
let gpuNarrow = false; let gpuNarrow = false;
const relief = createWindRelief({ cesium, getViewer }); const relief = createWindRelief({ getViewer, globeOf });
const signature = Array(8).fill(null); const signature = Array(8).fill(null);
const wind = { u: 0, v: 0 }; const wind = { u: 0, v: 0 };
const before = { lon: 0, lat: 0 }; const before = { lon: 0, lat: 0 };
const world = const world = { x: 0, y: 0, z: 0 };
typeof cesium.Cartesian3 === 'function' ? new cesium.Cartesian3() : {};
const screenA =
typeof cesium.Cartesian2 === 'function' ? new cesium.Cartesian2() : {};
const screenB =
typeof cesium.Cartesian2 === 'function' ? new cesium.Cartesian2() : {};
const degree = Math.PI / 180; const degree = Math.PI / 180;
const hidden = () => globalThis.document?.hidden === true; const hidden = () => globalThis.document?.hidden === true;
const still = () => paused || reducedMotion; const still = () => paused || reducedMotion;
@@ -188,6 +187,19 @@ export function createWindRendering({
const viewer = getViewer?.(); const viewer = getViewer?.();
return viewer && !viewer.isDestroyed?.() ? viewer : null; return viewer && !viewer.isDestroyed?.() ? viewer : null;
}; };
const poseOf = (viewer) => cameraOf(viewer)?.pose?.() ?? null;
// The camera's height, or undefined where there is none (or the eye sits
// at the earth's centre and it is not a number).
const heightOf = (viewer) => {
const height = viewer ? poseOf(viewer)?.height : undefined;
return Number.isFinite(height) ? height : undefined;
};
const requestRender = (viewer) => frameOf(viewer)?.requestRender?.('wind');
// What a paint projects with: the query port and the eye's position.
const viewOf = (viewer) => ({
query: queryOf(viewer),
eye: poseOf(viewer)?.position ?? null,
});
function cancel() { function cancel() {
if (frame !== null) globalThis.cancelAnimationFrame(frame); if (frame !== null) globalThis.cancelAnimationFrame(frame);
@@ -211,10 +223,9 @@ export function createWindRendering({
function resize(viewer) { function resize(viewer) {
const ratio = Math.min(2, globalThis.devicePixelRatio || 1); const ratio = Math.min(2, globalThis.devicePixelRatio || 1);
cssWidth = const surface = canvasOf(viewer);
viewer?.scene?.canvas?.clientWidth || container?.clientWidth || 1; cssWidth = surface?.clientWidth || container?.clientWidth || 1;
cssHeight = cssHeight = surface?.clientHeight || container?.clientHeight || 1;
viewer?.scene?.canvas?.clientHeight || container?.clientHeight || 1;
const width = Math.max(1, Math.floor(cssWidth * ratio)); const width = Math.max(1, Math.floor(cssWidth * ratio));
const height = Math.max(1, Math.floor(cssHeight * ratio)); const height = Math.max(1, Math.floor(cssHeight * ratio));
// Assigning even unchanged dimensions erases a real canvas. // Assigning even unchanged dimensions erases a real canvas.
@@ -227,16 +238,16 @@ export function createWindRendering({
return true; return true;
} }
function checkCamera(scene) { function checkCamera(viewer) {
const camera = scene.camera; const pose = poseOf(viewer);
const position = camera?.positionWC; const position = pose?.position;
const values = [ const values = [
position?.x, position?.x,
position?.y, position?.y,
position?.z, position?.z,
camera?.heading, pose?.heading,
camera?.pitch, pose?.pitch,
camera?.roll, pose?.roll,
cssWidth, cssWidth,
cssHeight, cssHeight,
]; ];
@@ -248,16 +259,17 @@ export function createWindRendering({
return changed; return changed;
} }
function updateBounds(scene) { function updateBounds(viewer) {
bounds = null; bounds = null;
if (!scene.camera?.computeViewRectangle || !cesium.Ellipsoid) return; const camera = cameraOf(viewer);
if (!camera?.viewRectangle) return;
try { try {
const rect = scene.camera.computeViewRectangle(cesium.Ellipsoid.WGS84); const rect = camera.viewRectangle();
if (!rect) return; if (!rect) return;
const west = rect.west / degree; const west = rect.west;
let east = rect.east / degree; let east = rect.east;
const south = Math.max(-89, rect.south / degree); const south = Math.max(-89, rect.south);
const north = Math.min(89, rect.north / degree); const north = Math.min(89, rect.north);
if (east < west) east += 360; if (east < west) east += 360;
if ( if (
[west, east, south, north].every(Number.isFinite) && [west, east, south, north].every(Number.isFinite) &&
@@ -275,34 +287,12 @@ export function createWindRendering({
} }
} }
function makeOccluder(scene) { function project(view, lon, lat) {
if ( if (!Number.isFinite(lon) || !Number.isFinite(lat) || !view.query)
!cesium.EllipsoidalOccluder ||
!cesium.Ellipsoid ||
!scene.camera?.positionWC
)
return null; return null;
return new cesium.EllipsoidalOccluder( const point = fromDegreesInto(lon, lat, 0, world);
cesium.Ellipsoid.WGS84, if (view.eye && view.query.isOccluded?.(point)) return null;
scene.camera.positionWC, const projected = view.query.project(point);
);
}
function project(scene, occluder, lon, lat, result) {
if (!Number.isFinite(lon) || !Number.isFinite(lat)) return null;
const point = cesium.Cartesian3.fromDegrees(
lon,
lat,
0,
cesium.Ellipsoid?.WGS84,
world,
);
if (occluder && !occluder.isPointVisible(point)) return null;
const projected = cesium.SceneTransforms.worldToWindowCoordinates(
scene,
point,
result,
);
if ( if (
!projected || !projected ||
!Number.isFinite(projected.x) || !Number.isFinite(projected.x) ||
@@ -310,7 +300,7 @@ export function createWindRendering({
) )
return null; return null;
// A perspective surface normal dims the limb instead of accumulating a bright rim. // A perspective surface normal dims the limb instead of accumulating a bright rim.
const camera = scene.camera?.positionWC; const camera = view.eye;
const dx = camera?.x - point.x; const dx = camera?.x - point.x;
const dy = camera?.y - point.y; const dy = camera?.y - point.y;
const dz = camera?.z - point.z; const dz = camera?.z - point.z;
@@ -332,7 +322,7 @@ export function createWindRendering({
point.x <= cssWidth && point.x <= cssWidth &&
point.y <= cssHeight; point.y <= cssHeight;
function spawn(particle, scene, occluder) { function spawn(particle, view) {
for (let attempt = 0; attempt < 6; attempt++) { for (let attempt = 0; attempt < 6; attempt++) {
const west = bounds?.west ?? -180; const west = bounds?.west ?? -180;
const east = bounds?.east ?? 180; const east = bounds?.east ?? 180;
@@ -342,17 +332,16 @@ export function createWindRendering({
particle.lat = Math.asin(low + Math.random() * (high - low)) / degree; particle.lat = Math.asin(low + Math.random() * (high - low)) / degree;
particle.age = 1 + Math.random() * 7; particle.age = 1 + Math.random() * 7;
particle.life = 8 + Math.random() * 4; particle.life = 8 + Math.random() * 4;
if (inView(project(scene, occluder, particle.lon, particle.lat, screenA))) if (inView(project(view, particle.lon, particle.lat))) return;
return;
} }
} }
function seed(scene, occluder) { function seed(viewer, view = viewOf(viewer)) {
const count = budget(); const count = budget();
if (particles.length > count) particles.length = count; if (particles.length > count) particles.length = count;
while (particles.length < count) while (particles.length < count)
particles.push({ lon: 0, lat: 0, age: 0, life: 10 }); particles.push({ lon: 0, lat: 0, age: 0, life: 10 });
updateBounds(scene); updateBounds(viewer);
for (const particle of particles) spawn(particle, scene, occluder); for (const particle of particles) spawn(particle, view);
} }
function removeImagery() { function removeImagery() {
@@ -364,16 +353,15 @@ export function createWindRendering({
shell = null; shell = null;
imageryKind = null; imageryKind = null;
} }
function updateImageryFade(camera, settled = false) { function updateImageryFade(height, settled = false) {
// The tileset shell keeps the quantised move-end fade; globe imagery keeps // The tileset shell keeps the quantised move-end fade; globe imagery keeps
// its smooth per-frame fade. // its smooth per-frame fade.
if ( if (
(!imagery && !shell) || (!imagery && !shell) ||
!camera?.positionCartographic || !Number.isFinite(height) ||
(imageryKind === 'tileset' && !settled) (imageryKind === 'tileset' && !settled)
) )
return; return;
const height = camera.positionCartographic.height;
const fade = !gpuActive const fade = !gpuActive
? 1 ? 1
: height <= WIND_FIELD_FADE_LOW_METERS : height <= WIND_FIELD_FADE_LOW_METERS
@@ -432,10 +420,11 @@ export function createWindRendering({
draw, draw,
texture, texture,
overlay === 'temperature' ? 1 : 0.85, overlay === 'temperature' ? 1 : 0.85,
{ cameraOf, frameOf },
); );
imageryKind = kind; imageryKind = kind;
updateImageryFade(viewer.scene.camera, true); updateImageryFade(heightOf(viewer), true);
viewer.scene?.requestRender?.(); requestRender(viewer);
return; return;
} }
imagery = globe.imagery.add({ imagery = globe.imagery.add({
@@ -449,11 +438,11 @@ export function createWindRendering({
// Temperature colors carry quantitative meaning; double transparency // Temperature colors carry quantitative meaning; double transparency
// blends orange heat into blue ocean and obscures useful gradients. // blends orange heat into blue ocean and obscures useful gradients.
imagery.alpha = overlay === 'temperature' ? 1 : 0.85; imagery.alpha = overlay === 'temperature' ? 1 : 0.85;
if (gpuActive) updateImageryFade(viewer.scene.camera, true); if (gpuActive) updateImageryFade(heightOf(viewer), true);
imageryErrorRemove = imagery.on('tileError', () => { imageryErrorRemove = imagery.on('tileError', () => {
imageryError = msg('Globe field image unavailable'); imageryError = msg('Globe field image unavailable');
}); });
viewer.scene?.requestRender?.(); requestRender(viewer);
} catch { } catch {
removeImagery(); removeImagery();
imageryError = msg('Globe field image unavailable'); imageryError = msg('Globe field image unavailable');
@@ -476,10 +465,10 @@ export function createWindRendering({
const show = kind !== 'none' && imagery?.alpha > 0; const show = kind !== 'none' && imagery?.alpha > 0;
if (imagery && imagery.show !== show) { if (imagery && imagery.show !== show) {
imagery.show = show; imagery.show = show;
viewerReady()?.scene?.requestRender?.(); requestRender(viewerReady());
} }
if ((gpuActive || kind === 'tileset') && kind !== 'none') if ((gpuActive || kind === 'tileset') && kind !== 'none')
updateImageryFade(viewerReady()?.scene?.camera, true); updateImageryFade(heightOf(viewerReady()), true);
if (kind === 'none') imageryError = NO_IMAGERY_HOST; if (kind === 'none') imageryError = NO_IMAGERY_HOST;
else if (wasHidden) { else if (wasHidden) {
imageryError = null; imageryError = null;
@@ -492,15 +481,15 @@ export function createWindRendering({
function viewChanged() { function viewChanged() {
if (gpuActive) { if (gpuActive) {
const viewer = viewerReady(); const viewer = viewerReady();
if (viewer) updateImageryFade(viewer.scene.camera); if (viewer) updateImageryFade(heightOf(viewer));
const narrow = (viewer?.scene?.canvas?.clientWidth || 800) < 700; const narrow = (canvasOf(viewer)?.clientWidth || 800) < 700;
let visibilityUpdated = false; let visibilityUpdated = false;
if (running && field && !hidden() && narrow !== gpuNarrow) { if (running && field && !hidden() && narrow !== gpuNarrow) {
gpuNarrow = narrow; gpuNarrow = narrow;
gpuActive = gpu.setField(field); gpuActive = gpu.setField(field);
if (!gpuActive && viewer) { if (!gpuActive && viewer) {
resize(viewer); resize(viewer);
seed(viewer.scene, makeOccluder(viewer.scene)); seed(viewer);
} }
motionChanged(); motionChanged();
visibilityUpdated = true; visibilityUpdated = true;
@@ -512,13 +501,13 @@ export function createWindRendering({
reportedGpuReady = ready; reportedGpuReady = ready;
onStatusChange?.(); onStatusChange?.();
} }
return; // Cesium projects persistent curves; only a responsive budget change rebuilds them. return; // The renderer projects persistent curves; only a responsive budget change rebuilds them.
} }
if (!running || !field || hidden() || !canvas) return; if (!running || !field || hidden() || !canvas) return;
const viewer = viewerReady(); const viewer = viewerReady();
if (!viewer) return; if (!viewer) return;
const resized = resize(viewer); const resized = resize(viewer);
if (resized || checkCamera(viewer.scene)) { if (resized || checkCamera(viewer)) {
cameraChanged = true; cameraChanged = true;
if (still()) paint(viewer, 0, true); if (still()) paint(viewer, 0, true);
else schedule(); else schedule();
@@ -533,7 +522,7 @@ export function createWindRendering({
if (!running || !field || hidden()) return; if (!running || !field || hidden()) return;
const viewer = viewerReady(); const viewer = viewerReady();
if (gpuActive) { if (gpuActive) {
if (viewer) updateImageryFade(viewer.scene.camera); if (viewer) updateImageryFade(heightOf(viewer));
if (viewer) gpu.updateVisibility(); if (viewer) gpu.updateVisibility();
return; return;
} }
@@ -547,23 +536,18 @@ export function createWindRendering({
} }
function cameraSettled() { function cameraSettled() {
if (gpuActive || imageryKind === 'tileset') if (gpuActive || imageryKind === 'tileset')
updateImageryFade(viewerReady()?.scene?.camera, true); updateImageryFade(heightOf(viewerReady()), true);
cameraMoved(); cameraMoved();
} }
function cameraMoved() { function cameraMoved() {
viewChanged(); viewChanged();
// A parked request-render scene may never run preRender until we wake it. // A parked request-render scene may never run preRender until we wake it.
if (gpuActive && running && field && !hidden()) if (gpuActive && running && field && !hidden())
viewerReady()?.scene?.requestRender?.(); requestRender(viewerReady());
} }
function listenScene(event, callback) { function listenPort(port, event, callback) {
if (!event?.addEventListener) return; const off = port?.on?.(event, () => callback());
const remove = event.addEventListener(callback); if (typeof off === 'function') removers.push(off);
removers.push(
typeof remove === 'function'
? remove
: () => event.removeEventListener(callback),
);
} }
function attachListeners() { function attachListeners() {
if (removers.length) return; if (removers.length) return;
@@ -574,9 +558,9 @@ export function createWindRendering({
listen(globalThis, 'resize', cameraMoved); listen(globalThis, 'resize', cameraMoved);
listen(eventTarget, 'gev:map-stack-changed', rehome); listen(eventTarget, 'gev:map-stack-changed', rehome);
const viewer = viewerReady(); const viewer = viewerReady();
const camera = viewer?.scene?.camera; if (!viewer) return;
listenScene(viewer?.scene?.preRender, viewChanged); listenPort(frameOf(viewer), 'preRender', viewChanged);
listenScene(camera?.moveEnd, cameraSettled); listenPort(cameraOf(viewer), 'moveEnd', cameraSettled);
} }
function detachListeners() { function detachListeners() {
for (const remove of removers) remove(); for (const remove of removers) remove();
@@ -585,16 +569,15 @@ export function createWindRendering({
} }
function paint(viewer, dt, staticFrame, fadeSeconds = dt) { function paint(viewer, dt, staticFrame, fadeSeconds = dt) {
const scene = viewer.scene;
const resized = resize(viewer); const resized = resize(viewer);
const changed = checkCamera(scene) || cameraChanged || resized; const changed = checkCamera(viewer) || cameraChanged || resized;
const occluder = makeOccluder(scene); const view = viewOf(viewer);
if (changed) { if (changed) {
clearPixels(); clearPixels();
updateBounds(scene); updateBounds(viewer);
cameraChanged = false; cameraChanged = false;
} }
if (particles.length !== budget()) seed(scene, occluder); if (particles.length !== budget()) seed(viewer, view);
if (staticFrame) clearPixels(); if (staticFrame) clearPixels();
context.globalAlpha = 1; context.globalAlpha = 1;
context.globalCompositeOperation = 'destination-out'; context.globalCompositeOperation = 'destination-out';
@@ -602,7 +585,7 @@ export function createWindRendering({
context.fillRect(0, 0, cssWidth, cssHeight); context.fillRect(0, 0, cssWidth, cssHeight);
context.globalCompositeOperation = 'source-over'; context.globalCompositeOperation = 'source-over';
context.lineCap = 'round'; context.lineCap = 'round';
const cameraHeight = scene.camera?.positionCartographic?.height ?? 1e6; const cameraHeight = heightOf(viewer) ?? 1e6;
const speedScale = Math.max(0.002, Math.min(4000, cameraHeight / 400)); const speedScale = Math.max(0.002, Math.min(4000, cameraHeight / 400));
const advection = { speedScale }; const advection = { speedScale };
// Stroke length is a display sample of the local field, not frame travel. // Stroke length is a display sample of the local field, not frame travel.
@@ -616,27 +599,21 @@ export function createWindRendering({
advectParticle(particle, wind, dt, advection); advectParticle(particle, wind, dt, advection);
particle.age += dt; particle.age += dt;
} }
let point = project(scene, occluder, particle.lon, particle.lat, screenB); let point = project(view, particle.lon, particle.lat);
if (changed && !inView(point)) { if (changed && !inView(point)) {
// Refill newly exposed regions while retaining world anchors still in view. // Refill newly exposed regions while retaining world anchors still in view.
spawn(particle, scene, occluder); spawn(particle, view);
sampleWind(field, particle.lon, particle.lat, wind); sampleWind(field, particle.lon, particle.lat, wind);
point = project(scene, occluder, particle.lon, particle.lat, screenB); point = project(view, particle.lon, particle.lat);
} }
if (particle.age > particle.life || !inView(point)) { if (particle.age > particle.life || !inView(point)) {
spawn(particle, scene, occluder); spawn(particle, view);
continue; continue;
} }
before.lon = particle.lon; before.lon = particle.lon;
before.lat = particle.lat; before.lat = particle.lat;
advectParticle(before, wind, -strokeSeconds, advection); advectParticle(before, wind, -strokeSeconds, advection);
const previous = project( const previous = project(view, before.lon, before.lat);
scene,
occluder,
before.lon,
before.lat,
screenA,
);
if (!inView(previous)) continue; if (!inView(previous)) continue;
const startX = previous.x; const startX = previous.x;
const startY = previous.y; const startY = previous.y;
@@ -735,7 +712,7 @@ export function createWindRendering({
? { ...next.grid, u: next.u, v: next.v } ? { ...next.grid, u: next.u, v: next.v }
: next; : next;
const viewer = viewerReady(); const viewer = viewerReady();
const nextNarrow = (viewer?.scene?.canvas?.clientWidth || 800) < 700; const nextNarrow = (canvasOf(viewer)?.clientWidth || 800) < 700;
const reuseGeometry = const reuseGeometry =
gpuActive && gpuActive &&
gpuNarrow === nextNarrow && gpuNarrow === nextNarrow &&
@@ -756,7 +733,7 @@ export function createWindRendering({
particles = []; particles = [];
if (viewer && !gpuActive) { if (viewer && !gpuActive) {
resize(viewer); resize(viewer);
seed(viewer.scene, makeOccluder(viewer.scene)); seed(viewer);
} }
installImagery(); installImagery();
relief.attach(); relief.attach();
+43 -35
View File
@@ -1,7 +1,5 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createWindRendering } from './rendering.js'; import { createWindRendering } from './rendering.js';
import { NO_IMAGERY_HOST } from '../weather/imageryHost.js'; import { NO_IMAGERY_HOST } from '../weather/imageryHost.js';
import { WEATHER_IMAGERY_Z } from '../weather/imageryOrder.js'; import { WEATHER_IMAGERY_Z } from '../weather/imageryOrder.js';
@@ -11,6 +9,7 @@ import {
renderShells, renderShells,
} from '../weather/shellFixture.mjs'; } from '../weather/shellFixture.mjs';
import { createCesiumFields } from '../../render/cesium/drawFields.js'; import { createCesiumFields } from '../../render/cesium/drawFields.js';
import { toLonLatH } from '../../geo/ellipsoid.js';
function event() { function event() {
const listeners = new Set(); const listeners = new Set();
@@ -179,6 +178,7 @@ function harness({
const viewer = { const viewer = {
container, container,
imageryLayers, imageryLayers,
canvas,
scene: { scene: {
canvas, canvas,
camera: { camera: {
@@ -200,40 +200,48 @@ function harness({
isDestroyed: () => false, isDestroyed: () => false,
}; };
const shellCesium = shell ? createShellCesium() : null; const shellCesium = shell ? createShellCesium() : null;
const cesium = { // The camera, frame and query ports over the doubles above, read live.
...(shellCesium ?? {}), const cameraPort = {
GeographicTilingScheme: Cesium.GeographicTilingScheme, pose() {
Credit: Cesium.Credit, const camera = viewer.scene.camera;
Event: Cesium.Event, return {
Cartesian3: { fromDegrees: (lon, lat) => ({ lon, lat }) }, position: camera.positionWC,
Ellipsoid: { WGS84: {} }, heading: camera.heading,
Rectangle: { MAX_VALUE: {} }, pitch: camera.pitch,
EllipsoidalOccluder: class { roll: camera.roll,
isPointVisible() { height: camera.positionCartographic?.height,
return !occluded; };
}
},
SceneTransforms: {
worldToWindowCoordinates: projected ?? (() => ({ x: 100, y: 100 })),
},
SingleTileImageryProvider: class {
constructor(options) {
this.options = options;
this.errorEvent = event();
}
}, },
viewRectangle: () => viewer.scene.camera.viewRectangle?.() ?? null,
on: (name, cb) =>
name === 'moveEnd'
? viewer.scene.camera.moveEnd.addEventListener(cb)
: () => {},
};
const framePort = {
on: (name, cb) =>
name === 'preRender' ? preRender.addEventListener(cb) : () => {},
requestRender: () => viewer.scene.requestRender(),
};
// Projections see the point as degrees, as the doubles above were written.
const project = projected ?? (() => ({ x: 100, y: 100 }));
const queryPort = {
isOccluded: () => occluded,
project: (point) => project(viewer.scene, toLonLatH(point)),
}; };
const fields = shellCesium const fields = shellCesium
? createCesiumFields({ scene: viewer.scene, cesium: shellCesium }) ? createCesiumFields({ scene: viewer.scene, cesium: shellCesium })
: null; : null;
const draw = fields && { field: (spec) => fields.field(spec) }; const draw = fields && { field: (spec) => fields.field(spec) };
const rendering = createWindRendering({ const rendering = createWindRendering({
cesium,
container, container,
getViewer: () => viewer, getViewer: () => viewer,
globeOf: (given) => (given === viewer ? globe : null), globeOf: (given) => (given === viewer ? globe : null),
// The Cesium draw port's raster shells, over the doubles. // The Cesium draw port's raster shells, over the doubles.
drawOf: (given) => (given === viewer ? draw : null), drawOf: (given) => (given === viewer ? draw : null),
cameraOf: (given) => (given === viewer ? cameraPort : null),
frameOf: (given) => (given === viewer ? framePort : null),
queryOf: (given) => (given === viewer ? queryPort : null),
createGpuRendering, createGpuRendering,
onStatusChange, onStatusChange,
getHost, getHost,
@@ -254,7 +262,7 @@ function harness({
motion, motion,
preRender, preRender,
viewer, viewer,
cesium: shellCesium ?? cesium, cesium: shellCesium,
imagery, imagery,
removed, removed,
primitives: () => shellScene?.primitives.items ?? [], primitives: () => shellScene?.primitives.items ?? [],
@@ -595,11 +603,11 @@ test('a large camera move immediately refills the newly visible region', () => {
y: 300 + point.lat * 20, y: 300 + point.lat * 20,
}), }),
}); });
h.viewer.scene.camera.computeViewRectangle = () => ({ h.viewer.scene.camera.viewRectangle = () => ({
west: ((center - 10) * Math.PI) / 180, west: center - 10,
east: ((center + 10) * Math.PI) / 180, east: center + 10,
south: (-10 * Math.PI) / 180, south: -10,
north: (10 * Math.PI) / 180, north: 10,
}); });
h.rendering.attach(); h.rendering.attach();
h.rendering.setField(FIELD); h.rendering.setField(FIELD);
@@ -624,11 +632,11 @@ test('world-anchored wind glyphs remain readable at low FPS without accelerating
y: 300 + point.lat * 20, y: 300 + point.lat * 20,
}), }),
}); });
h.viewer.scene.camera.computeViewRectangle = () => ({ h.viewer.scene.camera.viewRectangle = () => ({
west: (-5 * Math.PI) / 180, west: -5,
east: (5 * Math.PI) / 180, east: 5,
south: (-0.001 * Math.PI) / 180, south: -0.001,
north: (0.001 * Math.PI) / 180, north: 0.001,
}); });
h.rendering.attach(); h.rendering.attach();
h.rendering.setField(FIELD); h.rendering.setField(FIELD);
+2
View File
@@ -639,6 +639,8 @@ provideUnboundGlobe((viewer) => {
]); ]);
if (typeof viewer.scene.globe?.show === 'boolean') if (typeof viewer.scene.globe?.show === 'boolean')
capabilities.add('globeVisibility'); capabilities.add('globeVisibility');
// The globe's surface shading needs a globe to shade.
if (viewer.scene.globe) capabilities.add('surfaceShading');
const { port, dispose } = createCesiumGlobe(viewer, { const { port, dispose } = createCesiumGlobe(viewer, {
capabilities, capabilities,
requestRender: () => viewer.scene.requestRender?.(), requestRender: () => viewer.scene.requestRender?.(),
-2
View File
@@ -5,8 +5,6 @@
"src/app/scene.js", "src/app/scene.js",
"src/app/viewer.js", "src/app/viewer.js",
"src/data/geoImportPins.js", "src/data/geoImportPins.js",
"src/layers/wind/relief.js",
"src/layers/wind/rendering.js",
"src/maps/catalog.js", "src/maps/catalog.js",
"src/maps/controller.js", "src/maps/controller.js",
"src/maps/google3d.js", "src/maps/google3d.js",
+5
View File
@@ -133,6 +133,11 @@ const DRAW_FROM_CALLER = new Set([
// It configures the sources of layers, the traffic layer's among them, // It configures the sources of layers, the traffic layer's among them,
// that draw and read the surface through the ports alone. // that draw and read the surface through the ports alone.
'./application/sources', './application/sources',
// The layer catalog and the standalone catalog over it: their layers, the
// weather shells and the wind flow and relief among them, draw, read the
// eye and shade the globe through the ports alone.
'./application/layers',
'./standalone/catalog',
]); ]);
/** /**