Move scene effects and imported geometry behind the globe contract

Move Cesium viewer, map, sky, projection, trail and sonar internals into
its engine. Drive styles, bloom, sharpening and contact sonar through
engine.render. Count camera-input suspensions across all three engines
and migrate the feature callers. Preserve Cesium's effects and input
behaviour; fix transit lens clicks on Cesium and make zero sharpening on
Navara disable sharpening, as it does on Cesium.

Parse imported files into plain records and draw them through movers,
lines, ground and imagery on both engines. Follow Cesium's KML style
precedence, preserve local KMZ images and frame the drawable records.
Open overlays use imagery when the engine has no native map-overlay API.
Run every imported-display case on fake and headless Cesium engines.

The shared import path retains these known differences from Cesium's old
DataSources: wall fills, extruded prisms and gx:LatLonQuad are undrawn;
raised polygon fills drape while outlines retain altitude; GroundOverlay
rotation, altitude and RGB tint are not applied; rhumb lines become great
circles. Ground heights use the loaded surface synchronously instead of
waiting for most-detailed sampling. Supported KMZ ground overlays now
draw on Navara too. Document the limits rather than claiming full parity.

Combine batches B and C because their disjoint path manifests cannot
place the shared boundary and format files in a later commit while
keeping B independently valid. This combined commit owns the shared
docs, package boundaries, format scope, locale catalogs and coupling
baseline. Remove five obsolete import strings from all eleven catalogs.
Make the load-time source scan include new files and skip deleted paths
so the same checks work before and after recording the moves.

Coupling: Navara renderer lines fall from 1695 to 1294, Cesium import
files from 25 to 9, viewer lines from 1177 to 1026, SDK loads from 4 to 3
and engine-name lines from 62 to 42. No count grows.

The full unit suite and the boundary, format and coupling checks pass.
Browser validation remains to be run.

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-navara-visual-styles.mjs http://localhost:4291
node scripts/qa-navara-bloom.mjs http://localhost:4291
node scripts/qa-navara-sonar.mjs http://localhost:4291
QA_BASE_URL=http://localhost:4291 node scripts/qa-visual-effects.mjs
QA_BASE_URL=http://localhost:4291 node scripts/qa-zoom-out-guard.mjs
node scripts/qa-sky-model-lighting.mjs --url http://localhost:4291
node scripts/qa-geo-import.mjs http://localhost:4291
node scripts/qa-geo-import-regressions.mjs http://localhost:4291
node scripts/qa-geo-import-large.mjs http://localhost:4291
node scripts/qa-navara-geo-import.mjs http://localhost:4291

Use the keyless server for every check. Photoreal-only cases remain
unverified; do not enable paid tiles to run them.
This commit is contained in:
German Khokhlov committed 2026-11-07 12:45:21 +04:00
1 parent c079b329d0
commit 97c4dc76ce
130 files changed
+4763 -3495

No files matched your search

+189
View File
@@ -0,0 +1,189 @@
/**
* Workaround for Apple's Metal/ANGLE shader translator rejecting Cesium's
* per-vertex model atmosphere.
*
* Cesium's `AtmosphereStageVS` calls a function whose `out` parameters are
* bound DIRECTLY to varyings:
*
* czm_computeGroundAtmosphereScattering(
* v_positionWC, lightDirection,
* v_atmosphereRayleighColor, v_atmosphereMieColor, v_atmosphereOpacity);
*
* ANGLE's Metal backend wraps each `out` argument in an `ANGLE_out(...)`
* helper that takes a `thread T &`. Vertex-output struct members live in
* `__metal_generic`, which cannot bind to `thread`, so the program fails to
* LINK (not compile) and Cesium tears the render loop down:
*
* RuntimeError: Program failed to link. ... MSL compilation error:
* reference to type 'thread float3' could not bind to an lvalue of type
* '__metal_generic float3'
*
* This is the only shader in Cesium that binds varyings to `out` params --
* SkyAtmosphere and the ground-atmosphere fragment path both route through
* locals first, so they are unaffected and stay on.
*
* Cesium attaches that stage in `ModelSceneGraph.configurePipeline` under a
* single condition:
*
* const fogRenderable = frameState.fog.enabled && frameState.fog.renderable;
* if (fogRenderable) modelPipelineStages.push(AtmospherePipelineStage);
*
* so clearing `scene.fog.renderable` keeps the broken stage out of the
* pipeline entirely -- the program is never built, so it cannot fail to link.
*
* We clear `renderable` rather than `enabled` deliberately:
* - `Fog.update` still computes fog density when only `renderable` is off,
* preserving the distance-based screen-space-error scaling that governs
* 3D Tiles refinement. Clearing `enabled` returns early and forfeits it.
* - `visualSettings.js` saves and restores `scene.fog.enabled` around IR
* boost. Parking our fix on `enabled` would let that restore resurrect
* the broken shader mid-session; `renderable` is orthogonal to it.
*
* @module globe/cesium/atmosphereCompat
*/
/** Minimal vertex shader reproducing the exact out-param-to-varying bind. */
const PROBE_VERTEX_SHADER = `#version 300 es
precision highp float;
in vec3 a_position;
out vec3 v_probe;
void writeOut(out vec3 value) { value = vec3(1.0); }
void main() {
writeOut(v_probe);
gl_Position = vec4(a_position, 1.0);
}`;
const PROBE_FRAGMENT_SHADER = `#version 300 es
precision highp float;
in vec3 v_probe;
out vec4 fragColor;
void main() { fragColor = vec4(v_probe, 1.0); }`;
/**
* True when the user agent is iOS or iPadOS.
*
* iPadOS 13+ defaults to desktop-mode browsing and reports `MacIntel` with no
* iPad token, so it is identified by touch points instead -- real Macs report
* `maxTouchPoints` of 0, including Apple Silicon ones that also claim
* `MacIntel`. Brave/Chrome/Firefox on iOS are all WebKit underneath and share
* the same Metal backend, so matching the platform rather than the browser is
* what we want.
*/
export function isAppleMobilePlatform(navigatorLike = globalThis.navigator) {
if (!navigatorLike) return false;
const ua = String(navigatorLike.userAgent || '');
if (/\b(iPad|iPhone|iPod)\b/.test(ua)) return true;
// Desktop-mode iPadOS presents as a Mac. What separates it from a real Mac
// is touch: Macs report 0 touch points, including Apple Silicon ones that
// also claim `MacIntel`. `navigator.platform` is deprecated and may be
// empty, so the UA's Macintosh token is accepted as an equal signal rather
// than relying on platform alone.
const platform = String(navigatorLike.platform || '');
const macLike =
platform === 'MacIntel' ||
platform === 'MacARM' ||
/\bMacintosh\b/.test(ua);
const touchPoints = Number(navigatorLike.maxTouchPoints) || 0;
return macLike && touchPoints > 1;
}
/**
* Link the probe program and report whether the driver rejects the pattern.
*
* Returns `false` when WebGL2 is unavailable so that a missing context is
* never mistaken for a broken driver -- Cesium has its own handling for that,
* and the caller still falls back to platform detection.
*/
export function probeOutParamVaryingLinkFailure(gl) {
if (!gl) return false;
const vs = gl.createShader(gl.VERTEX_SHADER);
const fs = gl.createShader(gl.FRAGMENT_SHADER);
const program = gl.createProgram();
if (!vs || !fs || !program) return false;
try {
gl.shaderSource(vs, PROBE_VERTEX_SHADER);
gl.compileShader(vs);
gl.shaderSource(fs, PROBE_FRAGMENT_SHADER);
gl.compileShader(fs);
// A compile failure here is not the bug we are probing for: the driver
// rejects this pattern at LINK time, after both stages compile cleanly.
if (
!gl.getShaderParameter(vs, gl.COMPILE_STATUS) ||
!gl.getShaderParameter(fs, gl.COMPILE_STATUS)
)
return false;
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
return !gl.getProgramParameter(program, gl.LINK_STATUS);
} catch {
return false;
} finally {
gl.deleteShader(vs);
gl.deleteShader(fs);
gl.deleteProgram(program);
}
}
/** Build a throwaway WebGL2 context for the probe, or null if unavailable. */
function defaultProbeContext() {
try {
const canvas =
typeof OffscreenCanvas === 'function'
? new OffscreenCanvas(1, 1)
: globalThis.document?.createElement('canvas');
return canvas?.getContext('webgl2') ?? null;
} catch {
return null;
}
}
/**
* Decide whether the per-vertex model atmosphere must be kept out of the
* pipeline on this device.
*
* The probe is authoritative when it fires, so a future driver fix silently
* restores the effect without a code change. Platform detection is the
* backstop for the case where no context can be created -- on Apple mobile a
* link failure is fatal and unrecoverable, so we would rather lose fog than
* gamble the whole render loop on the probe having run.
*/
export function shouldDisableModelAtmosphere({
navigatorLike = globalThis.navigator,
createProbeContext = defaultProbeContext,
} = {}) {
const gl = createProbeContext();
if (gl) {
let linkFails;
try {
linkFails = probeOutParamVaryingLinkFailure(gl);
} finally {
// Browsers cap live WebGL contexts (Safari especially); release the
// throwaway probe context now rather than waiting for GC.
try {
gl.getExtension?.('WEBGL_lose_context')?.loseContext();
} catch {
// A context that cannot be released is left to GC.
}
}
if (linkFails) return true;
// Probe ran and the driver accepted the pattern. Apple mobile is still
// quarantined: the probe program is far simpler than Cesium's, and a
// false negative there costs the entire scene.
return isAppleMobilePlatform(navigatorLike);
}
return isAppleMobilePlatform(navigatorLike);
}
/**
* Keep Cesium's broken model-atmosphere stage out of the pipeline.
*
* Returns true when the workaround was applied. Safe to call on any scene;
* scenes without a fog object are left untouched.
*/
export function applyModelAtmosphereWorkaround(scene, options = {}) {
if (!scene?.fog) return false;
if (!shouldDisableModelAtmosphere(options)) return false;
scene.fog.renderable = false;
return true;
}
+221
View File
@@ -0,0 +1,221 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
isAppleMobilePlatform,
probeOutParamVaryingLinkFailure,
shouldDisableModelAtmosphere,
applyModelAtmosphereWorkaround,
} from './atmosphereCompat.js';
const IPAD_OS12 = {
userAgent:
'Mozilla/5.0 (iPad; CPU OS 12_5 like Mac OS X) AppleWebKit/605.1.15',
platform: 'iPad',
maxTouchPoints: 5,
};
// iPadOS 13+ desktop mode: no iPad token, reports as a Mac.
const IPAD_DESKTOP_MODE = {
userAgent:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15',
platform: 'MacIntel',
maxTouchPoints: 5,
};
const MAC_DESKTOP = {
userAgent:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15',
platform: 'MacIntel',
maxTouchPoints: 0,
};
const LINUX_DESKTOP = {
userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/141',
platform: 'Linux x86_64',
maxTouchPoints: 0,
};
/** Minimal GL double. `linkOk: false` mimics the Metal translator's refusal. */
function fakeGl({ linkOk = true, compileOk = true, throwOn = null } = {}) {
const deleted = { shaders: 0, programs: 0 };
return {
deleted,
VERTEX_SHADER: 1,
FRAGMENT_SHADER: 2,
COMPILE_STATUS: 3,
LINK_STATUS: 4,
createShader: () => ({}),
createProgram: () => ({}),
shaderSource() {
if (throwOn === 'shaderSource') throw new Error('context lost');
},
compileShader() {},
attachShader() {},
linkProgram() {},
getShaderParameter: () => compileOk,
getProgramParameter: () => linkOk,
deleteShader: () => (deleted.shaders += 1),
deleteProgram: () => (deleted.programs += 1),
};
}
test('identifies iPadOS in both legacy and desktop-mode guises', () => {
assert.equal(isAppleMobilePlatform(IPAD_OS12), true);
assert.equal(isAppleMobilePlatform(IPAD_DESKTOP_MODE), true);
});
test('does not mistake a real Mac or a Linux desktop for Apple mobile', () => {
// Regression guard: the desktop-mode check keys on touch points, and a Mac
// reports the same MacIntel platform string with zero of them.
assert.equal(isAppleMobilePlatform(MAC_DESKTOP), false);
assert.equal(isAppleMobilePlatform(LINUX_DESKTOP), false);
});
test('treats a missing navigator as not-Apple rather than throwing', () => {
assert.equal(isAppleMobilePlatform(undefined), false);
assert.equal(isAppleMobilePlatform(null), false);
});
test('detects desktop-mode iPadOS without navigator.platform', () => {
// `navigator.platform` is deprecated and can be absent or stripped; the UA's
// Macintosh token plus touch points has to carry the detection on its own.
assert.equal(
isAppleMobilePlatform({
userAgent:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15',
maxTouchPoints: 5,
}),
true,
);
// Same UA, no touch: a real Mac, which must stay untouched.
assert.equal(
isAppleMobilePlatform({
userAgent:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15',
maxTouchPoints: 0,
}),
false,
);
});
test('probe reports failure only when the program fails to link', () => {
assert.equal(
probeOutParamVaryingLinkFailure(fakeGl({ linkOk: false })),
true,
);
assert.equal(
probeOutParamVaryingLinkFailure(fakeGl({ linkOk: true })),
false,
);
});
test('a compile failure is not reported as the link bug', () => {
// The Metal defect surfaces at link time; both stages compile cleanly.
// Treating a compile error as the bug would disable fog for the wrong reason.
assert.equal(
probeOutParamVaryingLinkFailure(
fakeGl({ compileOk: false, linkOk: false }),
),
false,
);
});
test('probe releases its GL objects on both paths', () => {
const ok = fakeGl({ linkOk: true });
probeOutParamVaryingLinkFailure(ok);
assert.equal(ok.deleted.shaders, 2);
assert.equal(ok.deleted.programs, 1);
const thrown = fakeGl({ throwOn: 'shaderSource' });
probeOutParamVaryingLinkFailure(thrown);
assert.equal(thrown.deleted.shaders, 2, 'shaders freed even when GL throws');
assert.equal(thrown.deleted.programs, 1);
});
test('probe treats a null context as healthy, not broken', () => {
assert.equal(probeOutParamVaryingLinkFailure(null), false);
});
test('a failing probe disables the stage on any platform', () => {
assert.equal(
shouldDisableModelAtmosphere({
navigatorLike: LINUX_DESKTOP,
createProbeContext: () => fakeGl({ linkOk: false }),
}),
true,
);
});
test('a passing probe still quarantines Apple mobile but frees desktops', () => {
const createProbeContext = () => fakeGl({ linkOk: true });
assert.equal(
shouldDisableModelAtmosphere({
navigatorLike: IPAD_DESKTOP_MODE,
createProbeContext,
}),
true,
);
assert.equal(
shouldDisableModelAtmosphere({
navigatorLike: LINUX_DESKTOP,
createProbeContext,
}),
false,
);
});
test('falls back to platform detection when no context can be made', () => {
const createProbeContext = () => null;
assert.equal(
shouldDisableModelAtmosphere({
navigatorLike: IPAD_OS12,
createProbeContext,
}),
true,
);
assert.equal(
shouldDisableModelAtmosphere({
navigatorLike: MAC_DESKTOP,
createProbeContext,
}),
false,
);
});
test('applies to the scene by clearing renderable, never enabled', () => {
// `enabled` must survive: Fog.update short-circuits when it is false, which
// forfeits the density used for 3D Tiles screen-space-error scaling, and
// visualSettings' IR boost saves/restores that same flag.
const scene = { fog: { enabled: true, renderable: true } };
const applied = applyModelAtmosphereWorkaround(scene, {
navigatorLike: IPAD_DESKTOP_MODE,
createProbeContext: () => null,
});
assert.equal(applied, true);
assert.equal(scene.fog.renderable, false);
assert.equal(scene.fog.enabled, true);
});
test('leaves unaffected devices completely untouched', () => {
const scene = { fog: { enabled: true, renderable: true } };
const applied = applyModelAtmosphereWorkaround(scene, {
navigatorLike: LINUX_DESKTOP,
createProbeContext: () => fakeGl({ linkOk: true }),
});
assert.equal(applied, false);
assert.equal(scene.fog.renderable, true);
});
test('tolerates a scene with no fog object', () => {
assert.equal(applyModelAtmosphereWorkaround({}, {}), false);
assert.equal(applyModelAtmosphereWorkaround(null, {}), false);
});
test('releases the throwaway probe context after probing', () => {
let lost = 0;
const gl = fakeGl({ linkOk: true });
gl.getExtension = (name) =>
name === 'WEBGL_lose_context' ? { loseContext: () => (lost += 1) } : null;
shouldDisableModelAtmosphere({
navigatorLike: LINUX_DESKTOP,
createProbeContext: () => gl,
});
assert.equal(lost, 1, 'probe context must not linger until GC');
});
+15
View File
@@ -0,0 +1,15 @@
// Cesium's ICRF rotation and the bare-viewer fallback for CelestialRing.
import * as Cesium from 'cesium';
/** Cesium's ICRF-to-fixed rotation, once its data has loaded; else undefined. */
export const cesiumIcrfToFixed = (epochMs, result) =>
Cesium.Transforms.computeIcrfToFixedMatrix(
Cesium.JulianDate.fromDate(new Date(epochMs)),
result,
);
export const projectCelestialPoint = (scene, position, result) =>
Cesium.SceneTransforms.worldToWindowCoordinates(scene, position, result);
export const flyCelestialViewer = (viewer, options) =>
viewer.camera.flyTo({
...options,
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
});
+7 -1
View File
@@ -36,10 +36,13 @@ import { createCesiumSurface } from './surface.js';
* lineFactories?: object,
* groundFactories?: object,
* imageryFactories?: object,
* createStage?: Function,
* createSonar?: Function,
* }} [options] `requestRender` defaults to the render governor; `appClock`
* to the page's app clock; the `create*`/`load*` options and the mover and
* line, ground and imagery factories (movers.js, lines.js, ground.js,
* imagery.js) are test seams.
* imagery.js) are test seams, `createStage` and `createSonar` too
* (render.js).
*
* `render.setContinuous` takes a hold on the app's singleton renderGovernor
* (src/renderGovernor.js), which governs the one viewer it was installed on;
@@ -107,6 +110,9 @@ export function createCesiumEngine(viewer, options = {}) {
kind: 'cesium',
// What only Cesium has, for code still written against the viewer.
extensions: Object.freeze({ cesium: Object.freeze({ viewer }) }),
// Cesium only, not contract: what the contact sonar holds (sonar.js),
// live; the app reads whether its command adapter runs here.
contactSonarDiagnostics: render.sonarDiagnostics,
host: {
container: viewer.container,
canvas,
+18 -1
View File
@@ -1,7 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { assertGlobeEngine } from '../contract.js';
import { assertGlobeEngine, engineCapabilities } from '../contract.js';
import {
_resetRenderGovernorForTest,
getRenderGovernorDiagnostics,
@@ -55,6 +55,23 @@ test('the engine satisfies the contract shape and changes nothing at creation',
assert.deepEqual(engine.host.size(), { width: 640, height: 600 });
});
test('the engine draws the visual styles, bloom and contact sonar, not the cloud cover', () => {
const viewer = createFakeViewer();
const engine = createCesiumEngine(viewer);
assert.deepEqual(engineCapabilities(engine), {
visualStyles: true,
bloom: true,
cloudCover: false,
contactSonar: true,
movers: true,
lines: true,
ground: true,
imagery: true,
});
assert.equal(engine.contactSonarDiagnostics().contacts, 0);
engine.destroy();
});
test('the render option reaches render.request', () => {
const viewer = createFakeViewer();
const reasons = [];
+22 -1
View File
@@ -48,6 +48,11 @@ export function createCesiumInput(
let handler = null;
let destroyed = false;
const groups = new Map();
// Camera-input suspensions held, and the enableInputs the last resume
// puts back: the controller's own from before the first, or what
// setCameraInputs asked for since.
let suspended = 0;
let resumeTo = true;
const delivery = createPickDelivery({
pick: (position) => picker?.pick(position),
drill: (position, limit) => picker?.drillPick(position, limit) ?? [],
@@ -84,7 +89,23 @@ export function createCesiumInput(
};
},
setCameraInputs(enabled) {
scene.screenSpaceCameraController.enableInputs = Boolean(enabled);
if (suspended) resumeTo = Boolean(enabled);
else scene.screenSpaceCameraController.enableInputs = Boolean(enabled);
},
// The controller's switch: whatever else turned it off counts too.
cameraInputsEnabled: () =>
scene.screenSpaceCameraController?.enableInputs !== false,
suspendCameraInputs() {
const controller = scene.screenSpaceCameraController;
if (suspended++ === 0) resumeTo = controller.enableInputs;
controller.enableInputs = false;
let resumed = false;
return () => {
if (resumed) return;
resumed = true;
if (--suspended === 0)
scene.screenSpaceCameraController.enableInputs = resumeTo;
};
},
};
return {
+26
View File
@@ -105,6 +105,32 @@ test('setCameraInputs toggles the camera controller', () => {
assert.equal(viewer.scene.screenSpaceCameraController.enableInputs, true);
});
test('suspendCameraInputs counts and the last resume restores enableInputs', () => {
const { viewer, input } = setup();
const controller = viewer.scene.screenSpaceCameraController;
assert.equal(input.cameraInputsEnabled(), true);
const outer = input.suspendCameraInputs();
const inner = input.suspendCameraInputs();
assert.equal(controller.enableInputs, false);
assert.equal(input.cameraInputsEnabled(), false);
inner();
inner();
assert.equal(controller.enableInputs, false, 'the outer one still holds');
outer();
assert.equal(controller.enableInputs, true);
assert.equal(input.cameraInputsEnabled(), true);
// Off before the first suspension: off again after the last.
controller.enableInputs = false;
input.suspendCameraInputs()();
assert.equal(controller.enableInputs, false);
// A choice made under a suspension applies at its resume.
const resume = input.suspendCameraInputs();
input.setCameraInputs(true);
assert.equal(controller.enableInputs, false);
resume();
assert.equal(controller.enableInputs, true);
});
test('destroy destroys the handler', () => {
const { handlers, input, destroy } = setup();
input.on('click', () => {});
+91
View File
@@ -0,0 +1,91 @@
import * as Cesium from 'cesium';
import {
SENTINEL2_CREDIT,
SENTINEL2_MAX_ZOOM,
SENTINEL2_URL,
} from '../../maps/sentinel2.js';
// Attribution and service rights are documented in DATA_SOURCES.md.
export const ESRI_ATTRIBUTION_HTML =
'<a href="https://www.esri.com" target="_blank" rel="noopener">Powered by Esri</a>';
export function createOsmImagery() {
return new Cesium.OpenStreetMapImageryProvider({
url: 'https://tile.openstreetmap.org/',
credit: '© OpenStreetMap contributors',
});
}
export function createEsriImagery() {
return Cesium.ArcGisMapServerImageryProvider.fromUrl(
'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
{
credit:
'Powered by Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community',
enablePickFeatures: false,
},
);
}
export function createIonImagery(style, accessToken) {
accessToken = String(accessToken || '').trim();
if (!accessToken) throw new Error('Ion imagery requires an explicit token');
if (
style === Cesium.IonWorldImageryStyle.AERIAL ||
style === Cesium.IonWorldImageryStyle.AERIAL_WITH_LABELS
) {
return createBingIonImagery(style, accessToken);
}
return Cesium.IonImageryProvider.fromAssetId(style, { accessToken });
}
/**
* The imagery factory a globe stack descriptor names: ion styles, OSM, or
* Esri. Shared by the default map sources and the Cesium globe engine.
* @param {{ kind: string, style?: number }} descriptor
* @param {string} [ionToken]
* @returns {(request?: { signal?: AbortSignal }) => object | Promise<object>}
*/
export function imageryFactoryFor(descriptor, ionToken = '') {
if (descriptor.kind === 'sentinel2')
return () =>
new Cesium.UrlTemplateImageryProvider({
url: SENTINEL2_URL,
maximumLevel: SENTINEL2_MAX_ZOOM,
credit: new Cesium.Credit(SENTINEL2_CREDIT, true),
});
if (descriptor.kind === 'ion')
return () => createIonImagery(descriptor.style, ionToken);
return descriptor.kind === 'osm' ? createOsmImagery : createEsriImagery;
}
async function createBingIonImagery(style, accessToken) {
const endpoint = await new Cesium.Resource({
url: `https://api.cesium.com/v1/assets/${style}/endpoint`,
queryParameters: { access_token: accessToken },
}).fetchJson();
if (
endpoint?.type !== 'IMAGERY' ||
endpoint.externalType !== 'BING' ||
typeof endpoint.options?.url !== 'string'
) {
throw new Error('Ion world imagery did not return a Bing imagery endpoint');
}
// Bing otherwise follows the page's HTTP scheme on localhost. Resolve its
// ion-issued credentials through public APIs so tiles use HTTPS without
// weakening CSP, changing SDK defaults or touching provider internals.
const { url, ...options } = endpoint.options;
const provider = await Cesium.BingMapsImageryProvider.fromUrl(url, {
...options,
tileProtocol: 'https',
});
const ionCredits = (endpoint.attributions ?? []).map(
({ html, collapsible }) => new Cesium.Credit(html, collapsible === false),
);
const getTileCredits = provider.getTileCredits.bind(provider);
provider.getTileCredits = (x, y, level) => [
...ionCredits,
...(getTileCredits(x, y, level) ?? []),
];
return provider;
}
+66
View File
@@ -0,0 +1,66 @@
import * as Cesium from 'cesium';
import { createCesiumCredits } from './credits.js';
import { createMapCredits } from '../../maps/credits.js';
/**
* The scene changes a map source makes on a Cesium viewer: the base imagery
* layer, which 3D tileset shows, the globe, and the source's static credit.
* Shared by MapSourceController and the Cesium globe engine's `maps`, so
* both apply sources the same way. Creating it touches nothing.
* @param {Cesium.Viewer} viewer
* @param {{
* createImageryLayer?: (provider: object) => object,
* credits?: import('../contract.js').GlobeEngine['credits'],
* }} [options] `credits`: the globe engine's credits (default: the viewer's
* credit display through the Cesium engine's credits).
*/
export function createMapScene(
viewer,
{
createImageryLayer = (provider) => new Cesium.ImageryLayer(provider),
credits: engineCredits = createCesiumCredits(viewer).credits,
} = {},
) {
const credits = createMapCredits(engineCredits);
let layer = null;
let provider = null;
const scene = {
/** The provider of the live base layer, or null. */
get baseProvider() {
return provider;
},
/**
* Show `next` as the bottom imagery layer. The live layer (and its loaded
* tiles) stays when its provider is unchanged: rebuilding it exposes the
* bare globe while imagery loads again. Returns whether it was replaced.
*/
showBaseImagery(next) {
if (layer && provider === next) return false;
scene.removeBaseImagery();
layer = createImageryLayer(next);
provider = next;
viewer.imageryLayers.add(layer, 0);
return true;
},
removeBaseImagery() {
if (layer) viewer.imageryLayers.remove(layer, true);
layer = null;
provider = null;
},
/** Show `active` (or none) among `tilesets`. */
showTileset(active, tilesets) {
for (const tileset of tilesets) tileset.show = tileset === active;
},
showGlobe(visible) {
viewer.scene.globe.show = visible;
},
showCredit(html) {
credits.show(html || null);
},
destroy() {
scene.removeBaseImagery();
credits.destroy();
},
};
return scene;
}
+109
View File
@@ -0,0 +1,109 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createMapScene } from './mapScene.js';
function fixture() {
const layers = [];
const removed = [];
const credits = [];
const viewer = {
scene: {
globe: { show: true },
frameState: {
creditDisplay: {
addStaticCredit: (credit) => credits.push(credit),
removeStaticCredit: (credit) =>
credits.splice(credits.indexOf(credit), 1),
},
},
},
imageryLayers: {
add: (layer, index) => layers.splice(index ?? layers.length, 0, layer),
remove(layer, destroy) {
layers.splice(layers.indexOf(layer), 1);
removed.push({ layer, destroy });
},
},
};
const scene = createMapScene(viewer, {
createImageryLayer: (provider) => ({ provider }),
});
return { viewer, scene, layers, removed, credits };
}
test('creating the map scene touches nothing', () => {
const { viewer, layers, credits } = fixture();
assert.deepEqual(layers, []);
assert.deepEqual(credits, []);
assert.equal(viewer.scene.globe.show, true);
});
test('showBaseImagery puts a new layer at the bottom and replaces the old one', () => {
const { scene, layers, removed } = fixture();
layers.push({ name: 'overlay' });
const first = { name: 'esri' };
assert.equal(scene.showBaseImagery(first), true);
assert.deepEqual(layers[0], { provider: first });
assert.equal(scene.baseProvider, first);
const second = { name: 'osm' };
assert.equal(scene.showBaseImagery(second), true);
assert.deepEqual(
layers.map((layer) => layer.provider?.name ?? layer.name),
['osm', 'overlay'],
);
assert.deepEqual(removed, [{ layer: { provider: first }, destroy: true }]);
});
test('re-applying the same provider keeps the live layer', () => {
const { scene, layers, removed } = fixture();
const provider = { name: 'esri' };
scene.showBaseImagery(provider);
const live = layers[0];
assert.equal(scene.showBaseImagery(provider), false);
assert.equal(layers[0], live);
assert.deepEqual(removed, []);
});
test('removeBaseImagery, tilesets, globe and credits', () => {
const { viewer, scene, layers, credits } = fixture();
scene.showBaseImagery({ name: 'esri' });
scene.removeBaseImagery();
scene.removeBaseImagery();
assert.deepEqual(layers, []);
assert.equal(scene.baseProvider, null);
const a = { show: true };
const b = { show: false };
scene.showTileset(b, [a, b]);
assert.deepEqual([a.show, b.show], [false, true]);
scene.showTileset(null, [a, b]);
assert.deepEqual([a.show, b.show], [false, false]);
scene.showGlobe(false);
assert.equal(viewer.scene.globe.show, false);
scene.showCredit('<b>Esri</b>');
assert.equal(credits.length, 1);
scene.showCredit(null);
assert.equal(credits.length, 0);
scene.showCredit('<b>Esri</b>');
scene.showBaseImagery({ name: 'osm' });
scene.destroy();
assert.deepEqual(layers, []);
assert.deepEqual(credits, []);
});
test('the map scene shows its credit through a given credits capability', async () => {
const { createFakeEngine } = await import('../testing/fakeEngine.js');
const engine = createFakeEngine();
const { viewer, credits } = fixture();
const scene = createMapScene(viewer, {
createImageryLayer: (provider) => ({ provider }),
credits: engine.credits,
});
scene.showCredit('Esri');
scene.showCredit('Esri');
assert.deepEqual(engine.fake.credits, [{ html: 'Esri', onScreen: true }]);
scene.showCredit('OSM');
assert.deepEqual(engine.fake.credits, [{ html: 'OSM', onScreen: true }]);
scene.destroy();
assert.deepEqual(engine.fake.credits, []);
assert.deepEqual(credits, [], 'nothing on the viewer display');
});
+3 -6
View File
@@ -5,12 +5,9 @@
import * as Cesium from 'cesium';
import { loadPhotorealisticTileset } from '../../maps/google3d.js';
import { createMapScene } from '../../maps/sceneApply.js';
import {
ESRI_ATTRIBUTION_HTML,
imageryFactoryFor,
} from '../../maps/imagery.js';
import { applyTerrain, terrainSourceFor } from '../../maps/terrain.js';
import { createMapScene } from './mapScene.js';
import { ESRI_ATTRIBUTION_HTML, imageryFactoryFor } from './mapImagery.js';
import { applyTerrain, terrainSourceFor } from './terrain.js';
const IMAGERY_KINDS = new Set(['osm', 'esri-imagery', 'sentinel2', 'ion']);
+1 -1
View File
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { MAP_STACKS } from '../../maps/catalog.js';
import { createDefaultMapSources } from '../../maps/defaultSources.js';
import { ESRI_ATTRIBUTION_HTML } from '../../maps/imagery.js';
import { ESRI_ATTRIBUTION_HTML } from './mapImagery.js';
import { createCesiumMaps } from './maps.js';
import { createFakeViewer } from './testing/fakeViewer.mjs';
+244
View File
@@ -0,0 +1,244 @@
// The app's full-frame effects on Cesium (GlobeRender's visualStyles,
// bloom and setSharpen), through the scene's post-process stages: one stage
// per visual style, each the style's own shader (src/styles), then the
// sharpening; the bloom is the scene's own stage, borrowed. Cesium draws its
// stages in the order they were added, so the six join the scene together,
// styles first, at the first style or sharpen call (creating the engine
// changes nothing), and each is enabled only while it draws. Anime fades the
// sky box's Milky Way with its intensity (starrySky.js). destroy() removes
// the stages and gives the bloom stage back as it was borrowed.
import { PostProcessStage } from 'cesium';
import {
BLOOM_INITIAL,
SHARPEN_INITIAL,
STYLE_INITIAL,
mergeBloom,
mergeSharpen,
mergeStyle,
} from '../contract.js';
import { retroShader } from '../../styles/retro.js';
import { nightVisionShader } from '../../styles/surveillance.js';
import { thermalShader } from '../../styles/thermal.js';
import { animeShader } from '../../styles/anime.js';
import { noirShader } from '../../styles/noir.js';
// The app's styles by their names, in their stage order
// (src/ui/visualPresets.js STYLES).
const STYLE_SHADERS = Object.freeze({
retro: retroShader,
surveillance: nightVisionShader,
thermal: thermalShader,
anime: animeShader,
noir: noirShader,
});
/** Intensity under which a style draws nothing (its stage is disabled). */
const STYLE_VISIBLE_INTENSITY = 0.001;
/** Strength at or under which the bloom draws nothing. */
const BLOOM_DEAD_ZONE = 0.06;
// The bloom stage's uniforms the engine sets, given back on destroy.
const BLOOM_UNIFORMS = [
'glowOnly',
'contrast',
'brightness',
'delta',
'sigma',
'stepSize',
];
/**
* GLSL fragment shader implementing an unsharp-mask sharpening filter.
* Samples a 3x3 neighborhood, computes box blur, then adds the
* difference (center - blur) scaled by `amount` for edge enhancement.
*/
export const SHARPEN_SHADER = /* glsl */ `
uniform sampler2D colorTexture;
uniform vec2 colorTextureDimensions;
uniform float amount;
in vec2 v_textureCoordinates;
void main() {
vec2 uv = v_textureCoordinates;
vec2 texel = 1.0 / colorTextureDimensions;
vec4 center = texture(colorTexture, uv);
vec4 blur = (
texture(colorTexture, uv + vec2(-texel.x, -texel.y)) +
texture(colorTexture, uv + vec2( 0.0, -texel.y)) +
texture(colorTexture, uv + vec2( texel.x, -texel.y)) +
texture(colorTexture, uv + vec2(-texel.x, 0.0)) +
center +
texture(colorTexture, uv + vec2( texel.x, 0.0)) +
texture(colorTexture, uv + vec2(-texel.x, texel.y)) +
texture(colorTexture, uv + vec2( 0.0, texel.y)) +
texture(colorTexture, uv + vec2( texel.x, texel.y))
) / 9.0;
vec4 sharpened = center + (center - blur) * amount;
out_FragColor = vec4(clamp(sharpened.rgb, 0.0, 1.0), center.a);
}
`;
/** A style's uniforms before it is first set: `time` if it animates, then its parameters' defaults. */
function styleDefaults(shader) {
const uniforms = {};
if (shader.fragmentShader.includes('uniform float time')) uniforms.time = 0;
for (const [name, meta] of Object.entries(shader.uniforms || {}))
uniforms[name] = meta.default;
return uniforms;
}
/**
* Cesium's bloom stage uniforms for a strength (0..1): above the dead zone
* the strength eases (smoothstep) into a lower contrast, a brighter offset
* and a wider blur, so more of the frame glows, further out.
*/
export function bloomUniforms(strength) {
const raw =
strength <= BLOOM_DEAD_ZONE
? 0
: (strength - BLOOM_DEAD_ZONE) / (1 - BLOOM_DEAD_ZONE);
const eased = raw * raw * (3 - 2 * raw);
return {
contrast: 255 - eased * 168,
brightness: -0.5 + eased * 0.36,
sigma: 0.28 + eased * 6.3,
delta: 0.2 + eased * 2.25,
stepSize: 1 + eased * 1.25,
};
}
/**
* @param {Cesium.Viewer} viewer
* @param {{ requestRender: (reason: string) => void,
* createStage?: (options: object) => object }} options `createStage` is
* a test seam (Cesium's PostProcessStage).
* @returns {{ render: object, destroy: () => void }} `render`: the
* GlobeRender members (visualStyles, setStyle, style, setBloom, bloom,
* setSharpen, sharpen).
*/
export function createCesiumPostStages(
viewer,
{ requestRender, createStage = (options) => new PostProcessStage(options) },
) {
const { scene } = viewer;
const styles = new Map(
Object.entries(STYLE_SHADERS).map(([name, shader]) => {
const uniforms = styleDefaults(shader);
return [
name,
{
shader,
names: Object.keys(uniforms),
state: { ...STYLE_INITIAL, uniforms },
stage: null,
},
];
}),
);
let sharpen = { ...SHARPEN_INITIAL };
let sharpenStage = null;
let bloom = { ...BLOOM_INITIAL };
let borrowed = null;
let destroyed = false;
// Every stage at once, in draw order: the styles, then the sharpening.
const ensureStages = () => {
if (sharpenStage || destroyed) return;
for (const [name, style] of styles) {
style.stage = createStage({
name: `godsEyeView_${name}`,
fragmentShader: style.shader.fragmentShader,
uniforms: { intensity: 0, ...style.state.uniforms },
});
style.stage.enabled = false;
scene.postProcessStages.add(style.stage);
}
sharpenStage = createStage({
name: 'godsEyeView_sharpen',
fragmentShader: SHARPEN_SHADER,
uniforms: { amount: sharpen.amount },
});
sharpenStage.enabled = false;
scene.postProcessStages.add(sharpenStage);
};
const knownStyle = (name) => {
const style = styles.get(name);
if (!style) throw new TypeError(`Unknown visual style: ${name}`);
return style;
};
const showStyle = (name, { stage, state }) => {
Object.assign(stage.uniforms, state.uniforms);
stage.uniforms.intensity = state.intensity;
stage.enabled = state.intensity > STYLE_VISIBLE_INTENSITY;
// Anime's bands turn the faint Milky Way into blotches, and depth
// cannot tell the sky from far geometry, so the glow fades with it.
if (name === 'anime' && scene.skyBox?.milkyWayVisibility !== undefined)
scene.skyBox.milkyWayVisibility = 1 - state.intensity;
};
// The scene's bloom stage, set up for the app's bloom the first time.
const bloomStage = () => {
const stage = scene.postProcessStages.bloom;
if (!borrowed) {
borrowed = {
enabled: stage.enabled,
uniforms: Object.fromEntries(
BLOOM_UNIFORMS.map((name) => [name, stage.uniforms[name]]),
),
};
stage.uniforms.glowOnly = false;
}
return stage;
};
const render = {
visualStyles: Object.freeze([...styles.keys()]),
setStyle(name, options) {
const style = knownStyle(name);
style.state = mergeStyle(style.state, options, style.names);
if (destroyed) return;
ensureStages();
showStyle(name, style);
requestRender('style-stage');
},
style(name) {
const { intensity, uniforms } = knownStyle(name).state;
return { intensity, uniforms: { ...uniforms } };
},
setBloom(options) {
bloom = mergeBloom(bloom, options);
if (destroyed) return;
const stage = bloomStage();
Object.assign(stage.uniforms, bloomUniforms(bloom.strength));
stage.enabled = bloom.enabled && bloom.strength > BLOOM_DEAD_ZONE;
requestRender('bloom');
},
bloom: () => ({ ...bloom }),
setSharpen(options) {
sharpen = mergeSharpen(sharpen, options);
if (destroyed) return;
ensureStages();
sharpenStage.uniforms.amount = sharpen.amount;
sharpenStage.enabled = sharpen.enabled;
requestRender('sharpen');
},
sharpen: () => ({ ...sharpen }),
};
return {
render,
destroy() {
if (destroyed) return;
destroyed = true;
const collection = scene.postProcessStages;
if (!collection || collection.isDestroyed?.()) return;
if (sharpenStage) {
for (const { stage } of styles.values()) collection.remove(stage);
collection.remove(sharpenStage);
}
if (borrowed) {
const stage = collection.bloom;
Object.assign(stage.uniforms, borrowed.uniforms);
stage.enabled = borrowed.enabled;
}
},
};
}
+149
View File
@@ -0,0 +1,149 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { bloomUniforms, createCesiumPostStages } from './postStages.js';
function setup() {
const stages = [];
const requests = [];
const bloom = {
enabled: false,
uniforms: {
glowOnly: true,
contrast: 128,
brightness: -0.3,
delta: 1,
sigma: 3.78,
stepSize: 5,
},
};
const original = structuredClone(bloom);
const scene = {
skyBox: { milkyWayVisibility: 1 },
postProcessStages: {
bloom,
add: (stage) => stages.push(stage),
remove: (stage) => {
const index = stages.indexOf(stage);
if (index >= 0) stages.splice(index, 1);
return index >= 0;
},
},
};
const effects = createCesiumPostStages(
{ scene },
{
requestRender: (reason) => requests.push(reason),
createStage: (options) => ({ ...options, enabled: true }),
},
);
const stage = (name) =>
stages.find((entry) => entry.name === `godsEyeView_${name}`);
return {
effects,
render: effects.render,
scene,
stages,
stage,
requests,
bloom,
original,
};
}
test('creation adds nothing; the first style or sharpen call adds all six, in draw order', () => {
const { render, stages } = setup();
assert.deepEqual(render.visualStyles, [
'retro',
'surveillance',
'thermal',
'anime',
'noir',
]);
render.bloom();
render.style('thermal');
assert.equal(stages.length, 0);
render.setSharpen({ amount: 1.5 });
assert.deepEqual(
stages.map(({ name }) => name),
[
'godsEyeView_retro',
'godsEyeView_surveillance',
'godsEyeView_thermal',
'godsEyeView_anime',
'godsEyeView_noir',
'godsEyeView_sharpen',
],
);
assert.ok(stages.every((stage) => !stage.enabled));
render.setStyle('noir', { intensity: 0.5 });
assert.equal(stages.length, 6);
});
test('a style draws above 0.001 with its uniforms; style() is a copy; unknown names throw', () => {
const { render, stage, requests } = setup();
assert.deepEqual(render.style('thermal'), {
intensity: 0,
uniforms: {
time: 0,
sensitivity: 0.75,
bloom: 0.65,
mode: 0,
pixelation: 1.5,
palette: 0,
},
});
render.setStyle('thermal', { intensity: 0.0005 });
assert.equal(stage('thermal').enabled, false);
render.setStyle('thermal', { intensity: 1, uniforms: { palette: 1 } });
assert.equal(stage('thermal').enabled, true);
assert.equal(stage('thermal').uniforms.intensity, 1);
assert.equal(stage('thermal').uniforms.palette, 1);
render.style('thermal').uniforms.palette = 0;
assert.equal(render.style('thermal').uniforms.palette, 1);
assert.ok(requests.includes('style-stage'));
assert.throws(() => render.setStyle('sepia', {}), TypeError);
assert.throws(
() => render.setStyle('noir', { uniforms: { palette: 1 } }),
TypeError,
);
assert.throws(() => render.setStyle('noir', { intensity: 2 }), TypeError);
});
test('Anime fades the Milky Way with its intensity; a sky without one is left alone', () => {
const { render, scene } = setup();
render.setStyle('anime', { intensity: 0.25 });
assert.equal(scene.skyBox.milkyWayVisibility, 0.75);
render.setStyle('thermal', { intensity: 1 });
assert.equal(scene.skyBox.milkyWayVisibility, 0.75);
render.setStyle('anime', { intensity: 0 });
assert.equal(scene.skyBox.milkyWayVisibility, 1);
scene.skyBox = {};
render.setStyle('anime', { intensity: 1 });
assert.equal('milkyWayVisibility' in scene.skyBox, false);
});
test('bloom eases the strength above its dead zone and gives the stage back on destroy', () => {
const { effects, render, bloom, original, stages } = setup();
render.setBloom({ enabled: true, strength: 0.05 });
assert.equal(bloom.enabled, false, 'the dead zone glows nothing');
assert.equal(bloom.uniforms.glowOnly, false);
render.setBloom({ strength: 1 });
assert.equal(bloom.enabled, true);
assert.deepEqual(bloom.uniforms, {
glowOnly: false,
...bloomUniforms(1),
});
assert.equal(bloom.uniforms.contrast, 87);
render.setBloom({ enabled: false });
assert.equal(bloom.enabled, false);
assert.deepEqual(render.bloom(), { enabled: false, strength: 1 });
render.setSharpen({ enabled: true });
effects.destroy();
effects.destroy();
assert.equal(stages.length, 0);
assert.deepEqual(bloom, original);
// Later calls keep the state only.
render.setStyle('noir', { intensity: 1 });
assert.equal(stages.length, 0);
assert.equal(render.style('noir').intensity, 1);
});
+57 -12
View File
@@ -1,6 +1,8 @@
// GlobeRender on the app's render governor, which owns Cesium's
// requestRenderMode and maximumRenderTimeChange; the engine only takes a
// hold under its own owner id.
// hold under its own owner id. The full-frame effects (visual styles,
// bloom, sharpening) are the scene's post stages (postStages.js), the
// contact sonar the scene's native draw commands (sonar.js).
import {
governorRequestRender,
@@ -8,16 +10,22 @@ import {
isRenderGovernorInstalled,
releaseContinuousRender,
} from '../../renderGovernor.js';
import { SHARPEN_INITIAL, mergeSharpen } from '../contract.js';
import { CONTACT_SONAR_INITIAL, mergeContactSonar } from '../contract.js';
import { createCesiumPostStages } from './postStages.js';
import { createCesiumSonar } from './sonar.js';
export const RENDER_OWNER = 'globe-engine';
/**
* @param {Cesium.Viewer} viewer
* @param {{ requestRender?: (reason: string) => void }} [options] Defaults to
* the render governor when it governs this viewer, else the scene itself
* (before the governor is installed, or on another viewer).
* @returns {{ render: import('../contract.js').GlobeRender, destroy: () => void }}
* @param {{ requestRender?: (reason: string) => void,
* createStage?: (options: object) => object,
* createSonar?: typeof createCesiumSonar }} [options] `requestRender`
* defaults to the render governor when it governs this viewer, else the
* scene itself (before the governor is installed, or on another viewer);
* `createStage` (postStages.js) and `createSonar` are test seams.
* @returns {{ render: import('../contract.js').GlobeRender,
* sonarDiagnostics: () => object, destroy: () => void }}
*/
export function createCesiumRender(
viewer,
@@ -26,10 +34,36 @@ export function createCesiumRender(
if (isRenderGovernorInstalled(viewer)) governorRequestRender(reason);
else viewer.scene.requestRender?.();
},
createStage,
createSonar = createCesiumSonar,
} = {},
) {
let held = false;
let sharpen = { ...SHARPEN_INITIAL };
const effects = createCesiumPostStages(viewer, {
requestRender,
...(createStage ? { createStage } : {}),
});
const sonar = createSonar(viewer);
let contactSonar = { ...CONTACT_SONAR_INITIAL };
// Whether Cesium is drawing a frame: a sonar change outside one asks for
// a frame, one inside it (the app's, every frame) draws in it.
let drawing = false;
let removeFrameWatch = null;
const watchFrames = () => {
const { scene } = viewer;
if (removeFrameWatch || !scene.preUpdate?.addEventListener) return;
const removers = [
scene.preUpdate.addEventListener(() => {
drawing = true;
}),
scene.postRender.addEventListener(() => {
drawing = false;
}),
];
removeFrameWatch = () => {
for (const remove of removers) remove();
};
};
const render = {
request(reason = RENDER_OWNER) {
requestRender(reason);
@@ -41,17 +75,28 @@ export function createCesiumRender(
},
// The scene's real mode: another owner's hold keeps it continuous.
isContinuous: () => viewer.scene.requestRenderMode === false,
// State only: in Cesium mode the app's own post stage sharpens
// (src/ui/visualEffects.js), and the scene stays as it was.
setSharpen(options) {
sharpen = mergeSharpen(sharpen, options);
...effects.render,
setContactSonar(options) {
const next = mergeContactSonar(contactSonar, options);
const changed = Object.keys(next).some(
(key) => next[key] !== contactSonar[key],
);
contactSonar = next;
if (!changed) return;
watchFrames();
sonar.set({ ...next });
if (!drawing) requestRender('cyber-sonar');
},
sharpen: () => ({ ...sharpen }),
contactSonar: () => ({ ...contactSonar }),
};
return {
render,
sonarDiagnostics: () => sonar.diagnostics(),
destroy() {
if (held) render.setContinuous(false);
removeFrameWatch?.();
sonar.destroy();
effects.destroy();
},
};
}
+17
View File
@@ -0,0 +1,17 @@
import * as Cesium from 'cesium';
export function worldToWindowCoordinates(scene, position, result) {
return Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
position,
result,
);
}
let occluder;
export function horizonOccluder(camera) {
occluder ??= new Cesium.EllipsoidalOccluder(
Cesium.Ellipsoid.WGS84,
new Cesium.Cartesian3(),
);
occluder.cameraPosition = camera.positionWC;
return occluder;
}
+6
View File
@@ -0,0 +1,6 @@
// Native constants shared by the W1 adapters; keep the SDK import here.
// Read on call: the production build's Cesium global loads with the first
// Cesium globe, after this module has loaded on a Navara start.
import { ScreenSpaceEventType } from 'cesium';
export const trackingEventTypes = () => ScreenSpaceEventType;
+214
View File
@@ -0,0 +1,214 @@
// The Cyber HUD sonar's contact treatment on Cesium (render.setContactSonar,
// the `contactSonar` capability), drawn from the state the app hands the
// engine each frame (src/cyberSonarEngine.js). Native dots, icons and
// glyphs get derived draw commands whose shaders apply the sweep
// (sonarCommands.js); models keep their reversible CPU colour treatment
// (src/cyberSonar.js applyCyberSonarPrimitive), without walking native
// records. Nothing joins the scene before the treatment is first on; turning
// it off gives the models their colours back at once.
import * as Cesium from 'cesium';
import {
applyCyberSonarPrimitive,
cyberSonarSampler,
} from '../../cyberSonar.js';
import {
CYBER_SONAR_CESIUM_VERSION,
createCyberSonarGpu,
} from './sonarCommands.js';
const alive = (value) => value && !value.isDestroyed?.();
export function visitCyberSonarModels(primitive, visit, visible = true) {
if (!alive(primitive)) return;
visible = visible && primitive.show !== false;
if (primitive instanceof Cesium.PrimitiveCollection) {
for (let i = 0; i < primitive.length; i++)
visitCyberSonarModels(primitive.get(i), visit, visible);
} else if (primitive instanceof Cesium.Model) {
visit(primitive, primitive, 'model', visible && primitive.ready);
}
}
/**
* The sonar on `viewer`'s scene. `set(state)` takes the merged
* ContactSonar (src/globe/contract.js) for the next drawn frame;
* `diagnostics()` is what the treatment holds, live: whether the command
* adapter runs on this Cesium (`supported`), the models it tinted last
* frame (`contacts`) and the native batches it drew (`gpu`: commands,
* visibleCommands, programs, error).
* @param {Cesium.Viewer} viewer
* @param {{ createGpu?: typeof createCyberSonarGpu }} [options] A test seam.
*/
export function createCesiumSonar(
viewer,
{ createGpu = createCyberSonarGpu } = {},
) {
const scene = viewer?.scene;
let state = null;
let treatment = null;
const stats = { contacts: 0, updateMs: 0, frames: 0, gpu: null };
// Read every frame (src/cyberSonarEngine.js): one live view, no copies.
const report = Object.freeze({
get supported() {
return (
stats.gpu?.supported ?? Cesium.VERSION === CYBER_SONAR_CESIUM_VERSION
);
},
get contacts() {
return stats.contacts;
},
get updateMs() {
return stats.updateMs;
},
get frames() {
return stats.frames;
},
get gpu() {
return stats.gpu;
},
});
function attach() {
if (
!scene?.postUpdate?.addEventListener ||
!scene?.preRender?.addEventListener
)
return null;
const tracked = new Map();
const matrix = new Cesium.Matrix4();
const position = new Cesium.Cartesian3();
let epoch = 0;
let sampler, width, height, active, count;
const gpu = createGpu(scene, () => state);
stats.gpu = gpu.stats;
const restore = (visual, entry) => {
if (!alive(entry.owner)) return;
for (const key of entry.keys)
applyCyberSonarPrimitive(visual, 1, false, undefined, key);
};
const restoreAll = () => {
for (const [visual, entry] of tracked) restore(visual, entry);
tracked.clear();
stats.contacts = 0;
stats.updateMs = 0;
};
const visit = (visual, owner, kind, visible) => {
let entry = tracked.get(visual);
if (!visible) {
if (entry) {
restore(visual, entry);
tracked.delete(visual);
}
return;
}
let p = visual.position;
if (kind === 'model')
p = Cesium.Matrix4.getTranslation(visual.modelMatrix, position);
else if (
p &&
owner.modelMatrix &&
!Cesium.Matrix4.equals(owner.modelMatrix, Cesium.Matrix4.IDENTITY)
)
p = Cesium.Matrix4.multiplyByPoint(owner.modelMatrix, p, position);
if (!p) return;
const w =
matrix[3] * p.x + matrix[7] * p.y + matrix[11] * p.z + matrix[15];
const x =
(matrix[0] * p.x + matrix[4] * p.y + matrix[8] * p.z + matrix[12]) / w;
const y =
(matrix[1] * p.x + matrix[5] * p.y + matrix[9] * p.z + matrix[13]) / w;
if (w <= 0 || Math.abs(x) > 1.1 || Math.abs(y) > 1.1) return;
if (!entry) {
entry = {
owner,
keys:
kind === 'label'
? ['fillColor', 'outlineColor', 'backgroundColor']
: kind === 'marker' && visual.outlineColor
? ['color', 'outlineColor']
: ['color'],
epoch,
};
tracked.set(visual, entry);
}
entry.epoch = epoch;
const factor = active
? sampler.at((x + 1) * width * 0.5, (1 - y) * height * 0.5)
: sampler.neutral;
for (const key of entry.keys) {
if (key === 'outlineColor' && visual.outlineWidth === 0) continue;
if (key === 'backgroundColor' && !visual.showBackground) continue;
applyCyberSonarPrimitive(
visual,
kind === 'label' ? sampler.label(factor) : factor,
true,
sampler,
key,
kind === 'model',
);
}
count++;
};
const update = () => {
if (!state?.enabled || !gpu.stats.supported) {
restoreAll();
return;
}
const started = performance.now();
width = scene.canvas.clientWidth;
height = scene.canvas.clientHeight;
sampler = cyberSonarSampler(width, height, state);
active = state.active;
Cesium.Matrix4.multiply(
scene.camera.frustum.projectionMatrix,
scene.camera.viewMatrix,
matrix,
);
epoch++;
count = 0;
visitCyberSonarModels(scene.primitives, visit);
for (const [visual, entry] of tracked)
if (entry.epoch !== epoch) {
restore(visual, entry);
tracked.delete(visual);
}
stats.contacts = count;
stats.updateMs = performance.now() - started;
stats.frames++;
};
let removeRender;
// Aircraft fleet writers run in preRender, while tracked models and
// entity visualizers update earlier. Compose AFTER all those owners and
// BEFORE Cesium uploads primitive attributes for this draw. Requeue at
// postUpdate so writers installed later (enable/re-enable/track) cannot
// overwrite sonar. This only reorders one callback; the contact walk
// runs once per actual draw.
const removeUpdate = scene.postUpdate.addEventListener(() => {
removeRender?.();
removeRender = scene.preRender.addEventListener(update);
});
return {
restoreAll,
destroy() {
removeUpdate();
removeRender?.();
gpu.destroy();
restoreAll();
},
};
}
return {
set(next) {
state = next;
if (next.enabled) treatment ??= attach();
else treatment?.restoreAll();
},
diagnostics: () => report,
destroy() {
treatment?.destroy();
treatment = null;
},
};
}
+219
View File
@@ -0,0 +1,219 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { CONTACT_SONAR_INITIAL } from '../contract.js';
import { createCesiumSonar, visitCyberSonarModels } from './sonar.js';
import { createCesiumRender } from './render.js';
const ON = Object.freeze({
...CONTACT_SONAR_INITIAL,
enabled: true,
active: true,
angleDeg: 90,
opacity: 40,
});
// A scene with its frame events, camera and the given primitives.
function sonarScene(primitives, extra = {}) {
let requests = 0;
const scene = {
primitives,
preUpdate: new Cesium.Event(),
postUpdate: new Cesium.Event(),
preRender: new Cesium.Event(),
postRender: new Cesium.Event(),
canvas: { clientWidth: 1000, clientHeight: 800 },
drawingBufferWidth: 1000,
drawingBufferHeight: 800,
camera: {
frustum: { projectionMatrix: Cesium.Matrix4.IDENTITY },
viewMatrix: Cesium.Matrix4.IDENTITY,
},
requestRender() {
requests++;
},
...extra,
};
const draw = () => {
scene.preUpdate.raiseEvent();
scene.postUpdate.raiseEvent();
scene.preRender.raiseEvent();
scene.postRender.raiseEvent();
};
return { scene, viewer: { scene }, draw, requests: () => requests };
}
// A model-shaped fixture exercises the actual scene walk without loading a
// glTF or allocating a WebGL context. Rendering remains the browser gate.
function fakeModel(color) {
return Object.create(Cesium.Model.prototype, {
ready: { value: true },
show: { value: true },
color: { value: color.clone(), writable: true },
modelMatrix: { value: Cesium.Matrix4.IDENTITY },
});
}
test('model walk never enumerates native contact or EntityCluster records', () => {
const root = new Cesium.PrimitiveCollection();
const points = root.add(new Cesium.PointPrimitiveCollection());
points.add();
points.get = () => {
throw new Error('must not enumerate contacts');
};
const cluster = root.add(new Cesium.EntityCluster());
Object.defineProperty(cluster, '_billboardCollection', {
get() {
throw new Error('must not access cluster internals');
},
configurable: true,
});
const seen = [];
visitCyberSonarModels(root, (...v) => seen.push(v));
assert.equal(seen.length, 0);
delete cluster._billboardCollection;
root.destroy();
});
test('nothing joins the scene until the treatment is first on', () => {
const primitives = new Cesium.PrimitiveCollection();
const original = primitives.update;
const { viewer, scene } = sonarScene(primitives);
const sonar = createCesiumSonar(viewer);
sonar.set({ ...CONTACT_SONAR_INITIAL });
assert.equal(primitives.update, original);
assert.equal(scene.postUpdate.numberOfListeners, 0);
sonar.set({ ...ON });
assert.notEqual(primitives.update, original);
assert.equal(scene.postUpdate.numberOfListeners, 1);
sonar.destroy();
sonar.destroy();
assert.equal(primitives.update, original);
assert.equal(scene.postUpdate.numberOfListeners, 0);
assert.equal(scene.preRender.numberOfListeners, 0);
primitives.destroy();
});
test('native owner colors remain untouched; models take the sweep and get theirs back', () => {
const primitives = new Cesium.PrimitiveCollection({
destroyPrimitives: false,
});
const points = primitives.add(new Cesium.PointPrimitiveCollection());
const point = points.add({ color: new Cesium.Color(0.3, 0.7, 0.5, 0.8) });
const nativeColor = new Cesium.Color(0.2, 0.4, 0.8, 1);
const model = fakeModel(nativeColor);
primitives.add(model);
const { viewer, draw } = sonarScene(primitives);
const sonar = createCesiumSonar(viewer);
try {
for (const active of [true, false, true]) {
for (const opacity of [35, 84, 100]) {
sonar.set({ ...ON, active, opacity });
point.color = new Cesium.Color(0.6, 0.4, 0.2, 0.7);
draw();
assert.equal(point.color.alpha, 0.7);
assert.equal(point.color.red, 0.6);
}
}
assert.notDeepEqual(model.color, nativeColor, 'the model is tinted');
assert.equal(sonar.diagnostics().contacts, 1);
// Off: the model's colour comes back at once, before any frame.
sonar.set({ ...ON, enabled: false });
assert.deepEqual(model.color, nativeColor);
assert.equal(sonar.diagnostics().contacts, 0);
} finally {
sonar.destroy();
points.destroy();
primitives.destroy();
}
});
test('a shader failure turns the treatment off and the next frame restores the models', () => {
const nativeColor = new Cesium.Color(0.2, 0.4, 0.8, 1);
const model = fakeModel(nativeColor);
const primitives = new Cesium.PrimitiveCollection({
destroyPrimitives: false,
});
primitives.add(model);
const points = new Cesium.PointPrimitiveCollection();
const nativeCommand = {
owner: points,
uniformMap: {},
shaderProgram: {
vertexShaderSource: new Cesium.ShaderSource({
sources: ['void main() {}'],
}),
},
};
primitives.update = (frame) => frame.commandList.push(nativeCommand);
const { viewer, scene } = sonarScene(primitives);
const sonar = createCesiumSonar(viewer);
try {
assert.equal(sonar.diagnostics().supported, true);
sonar.set({ ...ON, active: false });
scene.postUpdate.raiseEvent();
scene.preRender.raiseEvent();
assert.notDeepEqual(
model.color,
nativeColor,
'Cyber neutral treatment precedes shader compilation',
);
const frame = { commandList: [], passes: { render: true } };
primitives.update(frame);
assert.equal(sonar.diagnostics().supported, false);
assert.equal(frame.commandList[0], nativeCommand);
scene.postUpdate.raiseEvent();
scene.preRender.raiseEvent();
assert.deepEqual(
model.color,
nativeColor,
'the next draw restores native model color',
);
assert.equal(sonar.diagnostics().contacts, 0);
} finally {
sonar.destroy();
points.destroy();
primitives.destroy();
}
});
test('render.setContactSonar merges, hands the sonar a copy and asks for a frame only outside one', () => {
const primitives = new Cesium.PrimitiveCollection();
const { viewer, draw, scene } = sonarScene(primitives);
const reasons = [];
const states = [];
const { render, sonarDiagnostics, destroy } = createCesiumRender(viewer, {
requestRender: (reason) => reasons.push(reason),
createSonar: () => ({
set: (state) => states.push(state),
diagnostics: () => ({ supported: true }),
destroy() {},
}),
});
assert.deepEqual(render.contactSonar(), CONTACT_SONAR_INITIAL);
render.setContactSonar({ enabled: true, angleDeg: 10 });
assert.deepEqual(reasons, ['cyber-sonar']);
assert.deepEqual(states.at(-1), {
...CONTACT_SONAR_INITIAL,
enabled: true,
angleDeg: 10,
});
// The app sets it every frame, in preRender: no request then.
const off = scene.preRender.addEventListener(() =>
render.setContactSonar({ angleDeg: 20 }),
);
draw();
off();
assert.deepEqual(reasons, ['cyber-sonar']);
assert.equal(render.contactSonar().angleDeg, 20);
// An unchanged state is not handed on.
const handed = states.length;
render.setContactSonar({ angleDeg: 20 });
assert.equal(states.length, handed);
assert.throws(() => render.setContactSonar({ range: 0 }), TypeError);
assert.equal(sonarDiagnostics().supported, true);
destroy();
assert.equal(scene.preUpdate.numberOfListeners, 0);
assert.equal(scene.postRender.numberOfListeners, 0);
primitives.destroy();
});
+301
View File
@@ -0,0 +1,301 @@
// The Cyber HUD sonar on Cesium's native dots, icons and glyphs
// (render.setContactSonar, sonar.js): each drawn point or billboard batch
// gets a derived draw command whose shader applies the sweep.
import * as Cesium from 'cesium';
// Narrow, version-tested engine adapter. Cesium has no public custom shader
// option for native point/billboard collections. Do not patch its prototypes or
// access EntityCluster's private collections. An engine upgrade must revalidate
// this adapter; unsupported versions keep the original commands unchanged.
export const CYBER_SONAR_CESIUM_VERSION = '1.138.0';
// Follow every public DrawCommand setter, including pick/shadow/culling flags.
// Copying native.dirty would keep derived pipelines dirty forever: the scene
// consumes our command, so it never clears that flag on the native command.
let commandProperties;
export function syncCyberSonarCommand(
native,
record,
program,
uniforms,
labelBackground,
) {
commandProperties ??= Object.entries(
Object.getOwnPropertyDescriptors(Cesium.DrawCommand.prototype),
)
.filter(
([key, descriptor]) =>
descriptor.set && key !== 'shaderProgram' && key !== 'uniformMap',
)
.map(([key]) => key);
if (!record.command) {
record.command = new Cesium.DrawCommand();
record.uniformMap = {
...uniforms,
u_gevSonarLabelBackground: () => record.labelBackground,
};
}
const command = record.command;
record.labelBackground = labelBackground;
// Uniform values (angle/viewport/etc.) change through stable callbacks, not
// new maps/functions. Owner callback replacement and removal still propagate.
for (const key in record.uniformMap) {
if (
!(key in uniforms) &&
key !== 'u_gevSonarLabelBackground' &&
!(key in native.uniformMap)
) {
delete record.uniformMap[key];
command.dirty = true;
}
}
for (const key in native.uniformMap) {
if (record.uniformMap[key] !== native.uniformMap[key]) {
record.uniformMap[key] = native.uniformMap[key];
command.dirty = true;
}
}
for (const key of commandProperties) command[key] = native[key];
command.shaderProgram = program;
command.uniformMap = record.uniformMap;
return command;
}
export function sonarVertexSource(source, kind) {
const text = source.sources.join('\n');
const attribute =
kind === 'point' ? 'positionHighAndSize' : 'positionHighAndScale';
const lowAttribute =
kind === 'point' ? 'positionLowAndOutline' : 'positionLowAndRotation';
if (
!text.includes(attribute) ||
!text.includes(lowAttribute) ||
!text.includes('v_color') ||
!/void\s+main\s*\(\s*\)/.test(text)
)
return null;
const next = source.clone();
next.sources = [
text.replace(/void\s+main\s*\(\s*\)/, 'void gev_sonar_main()'),
`
uniform vec4 u_gevSonar; // angle, radius, opacity floor, sweep enabled
uniform vec2 u_gevSonarViewport;
uniform float u_gevSonarSector;
uniform float u_gevSonarLabelBackground;
void main() {
gev_sonar_main();
// All corners/glyphs share the contact anchor, before native screen offsets.
// Leave gl_Position untouched so appearance never changes geometry or picks.
vec4 anchor = czm_modelViewProjectionRelativeToEye * czm_translateRelativeToEye(${attribute}.xyz, ${lowAttribute}.xyz);
if (anchor.w <= 0.0) return;
vec2 pixel = anchor.xy / anchor.w * u_gevSonarViewport * 0.5;
float floorValue = u_gevSonar.z;
float factor = floorValue + (1.0 - floorValue) * 0.46;
if (u_gevSonar.w > 0.5) {
float distanceSquared = dot(pixel, pixel);
float radiusSquared = u_gevSonar.y * u_gevSonar.y;
float delta = mod(degrees(atan(pixel.x, pixel.y)) - u_gevSonar.x + 360.0, 360.0);
if (delta > 359.9999) delta = 0.0;
factor = floorValue;
if (distanceSquared < radiusSquared * 0.000625) factor = 1.0;
else if (distanceSquared <= radiusSquared && delta <= u_gevSonarSector)
factor += (1.0 - floorValue) * min(1.0, (u_gevSonarSector - delta) / min(10.0, u_gevSonarSector * 0.42));
}
#ifdef SDF
factor = (1.0 + factor) * 0.5;
#else
if (u_gevSonarLabelBackground > 0.5) factor = (1.0 + factor) * 0.5;
#endif
float coverage = floorValue >= 0.9999 ? 1.0 : clamp((factor - floorValue) / (1.0 - floorValue), 0.0, 1.0);
if (u_gevSonarLabelBackground < 0.5)
v_color.rgb = v_color.rgb * 0.28 + (vec3(0.62, 0.68, 0.72) + vec3(0.38, 0.16, 0.12) * coverage) * 0.72;
// Apply before native fragment pass classification, never after main().
v_color.a *= factor;
${kind === 'point' ? 'v_outlineColor.a *= factor;' : '#ifdef SDF\n v_outlineColor.a *= factor;\n #endif'}
}
`,
];
return next;
}
// Use native batch bounds, never individual contacts, for idle render demand.
// Like Cesium's frustum builder, exclude the far plane (it fits multiple frusta).
export function isCyberSonarCommandVisible(command, frameState, culling) {
const bounds = command.boundingVolume;
if (!bounds || !command.cull) return true;
culling ??= new Cesium.CullingVolume(
frameState.cullingVolume.planes.slice(0, 5),
);
if (culling.computeVisibility(bounds) === Cesium.Intersect.OUTSIDE)
return false;
return !(
frameState.mode === Cesium.SceneMode.SCENE3D &&
frameState.occluder &&
command.occlude &&
bounds.isOccluded(frameState.occluder)
);
}
/** Work scales with draw commands, not the number of contacts in a collection.
* Source programs, colors, pick IDs, render states and other scenes stay owned
* by Cesium. Only this scene's rendered command slice receives derived shaders.
* `readFrame` returns the sonar state to draw (the contract's ContactSonar).
*/
export function createCyberSonarGpu(scene, readFrame) {
const root = scene.primitives;
const original = root.update;
const programs = new Map();
let commands = new WeakMap();
let disposed = false;
const stats = {
commands: 0,
visibleCommands: 0,
programs: 0,
supported: Cesium.VERSION === CYBER_SONAR_CESIUM_VERSION,
error: null,
};
const uniforms = new Cesium.Cartesian4();
const viewport = new Cesium.Cartesian2();
let sector = 24;
const sonarUniforms = {
u_gevSonar: () => uniforms,
u_gevSonarViewport: () => viewport,
u_gevSonarSector: () => sector,
};
const culling = new Cesium.CullingVolume();
const used = new Set();
const replaced = [];
const release = () => {
for (const { program } of programs.values())
if (!program.isDestroyed()) program.destroy();
programs.clear();
commands = new WeakMap();
used.clear();
replaced.length = 0;
stats.programs = 0;
};
const wrapped = function (frameState) {
const start = frameState.commandList.length;
original.call(this, frameState);
stats.commands = 0;
stats.visibleCommands = 0;
if (
disposed ||
!stats.supported ||
!frameState.passes.render ||
frameState.passes.pick
)
return;
const frame = readFrame();
if (!frame.enabled) {
if (programs.size) release();
return;
}
viewport.x = scene.drawingBufferWidth;
viewport.y = scene.drawingBufferHeight;
uniforms.x = frame.angleDeg;
uniforms.y =
(Math.min(viewport.x * 0.4, viewport.y * 0.52) * frame.range) / 100;
uniforms.z = frame.opacity / 100;
uniforms.w = frame.active ? 1 : 0;
sector = frame.sector;
used.clear();
replaced.length = 0;
if (frameState.cullingVolume)
for (let i = 0; i < 5; i++)
culling.planes[i] = frameState.cullingVolume.planes[i];
try {
for (let i = start; i < frameState.commandList.length; i++) {
const native = frameState.commandList[i];
const kind =
native.owner instanceof Cesium.PointPrimitiveCollection
? 'point'
: native.owner instanceof Cesium.BillboardCollection
? 'billboard'
: null;
if (!kind || !native.shaderProgram || !native.uniformMap) continue;
const source = native.shaderProgram;
// Label backgrounds are non-SDF billboard batches. The version-tested
// engine pick association distinguishes them without enumerating labels
// or reaching into EntityCluster. One representative per draw batch;
// Cesium's label glyph/background collections are homogeneous.
const labelBackground =
kind === 'billboard' &&
!source.vertexShaderSource.defines.includes('SDF') &&
native.owner.length > 0 &&
native.owner.get(0).pickPrimitive instanceof Cesium.Label
? 1
: 0;
let entry = programs.get(source);
if (!entry) {
const vertex = sonarVertexSource(source.vertexShaderSource, kind);
if (!vertex) throw new Error('Unsupported native contact shader');
const attributes = Object.fromEntries(
Object.entries(source.vertexAttributes).map(([name, value]) => [
name,
value.index,
]),
);
const program = Cesium.ShaderProgram.fromCache({
context: frameState.context,
vertexShaderSource: vertex,
fragmentShaderSource: source.fragmentShaderSource,
attributeLocations: attributes,
});
// Compile while errors can still leave the whole native command slice
// intact, rather than stopping the viewer's render loop at draw time.
try {
void program.allUniforms;
} catch (error) {
program.destroy();
throw error;
}
programs.set(source, (entry = { program }));
}
used.add(source);
let record = commands.get(native);
if (!record) commands.set(native, (record = {}));
const derived = syncCyberSonarCommand(
native,
record,
entry.program,
sonarUniforms,
labelBackground,
);
replaced.push(i, native);
frameState.commandList[i] = derived;
stats.commands++;
if (isCyberSonarCommandVisible(native, frameState, culling))
stats.visibleCommands++;
}
for (const [source, entry] of programs)
if (!used.has(source)) {
if (!entry.program.isDestroyed()) entry.program.destroy();
programs.delete(source);
}
stats.programs = programs.size;
} catch (error) {
// Recover the original commands already replaced in this slice.
for (let i = 0; i < replaced.length; i += 2)
frameState.commandList[replaced[i]] = replaced[i + 1];
stats.supported = false;
stats.commands = 0;
stats.visibleCommands = 0;
stats.error = String(error?.message || error);
release();
}
};
root.update = wrapped;
return {
stats,
destroy() {
if (disposed) return;
disposed = true;
if (root.update === wrapped && !root.isDestroyed?.())
root.update = original;
release();
},
};
}
+354
View File
@@ -0,0 +1,354 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
createCyberSonarGpu,
sonarVertexSource,
CYBER_SONAR_CESIUM_VERSION,
isCyberSonarCommandVisible,
syncCyberSonarCommand,
} from './sonarCommands.js';
test('stable commands reuse uniforms and derived pipelines while all native fields remain live', () => {
const native = new Cesium.DrawCommand({
count: 6,
uniformMap: { value: () => 1 },
});
const record = {},
program = {},
uniforms = { u_gevSonar: () => 42 };
const derived = syncCyberSonarCommand(native, record, program, uniforms, 0);
const map = derived.uniformMap;
derived.dirty = false;
derived.lastDirtyTime = 7;
assert.equal(native.dirty, true);
assert.equal(
syncCyberSonarCommand(native, record, program, uniforms, 1),
derived,
);
assert.equal(
derived.dirty,
false,
'stale native dirty flag must not rebuild pipelines',
);
assert.equal(derived.lastDirtyTime, 7);
assert.equal(derived.uniformMap, map);
assert.equal(map.u_gevSonarLabelBackground(), 1);
for (const [key, value] of Object.entries({
count: 12,
offset: 2,
instanceCount: 3,
pickId: 'pick',
pass: Cesium.Pass.TRANSLUCENT,
cull: false,
occlude: false,
castShadows: true,
receiveShadows: true,
pickOnly: true,
renderState: {},
vertexArray: {},
modelMatrix: Cesium.Matrix4.IDENTITY,
framebuffer: {},
})) {
derived.dirty = false;
native[key] = value;
syncCyberSonarCommand(native, record, program, uniforms, 0);
assert.equal(derived[key], value, key);
assert.equal(derived.dirty, true, key);
}
native.uniformMap.value = () => 2;
syncCyberSonarCommand(native, record, program, uniforms, 0);
assert.equal(map.value(), 2);
native.uniformMap = { replacement: () => 3 };
syncCyberSonarCommand(native, record, program, uniforms, 0);
assert.equal(map.value, undefined);
assert.equal(map.replacement(), 3);
assert.equal(map.u_gevSonar(), 42);
const nextProgram = {};
syncCyberSonarCommand(native, record, nextProgram, uniforms, 0);
assert.equal(derived.shaderProgram, nextProgram);
assert.equal(native.shaderProgram, undefined);
});
test('GPU shader transform is isolated, settings-driven, and precedes native fragment classification', () => {
assert.equal(
Cesium.VERSION,
CYBER_SONAR_CESIUM_VERSION,
'engine upgrades require GPU revalidation',
);
for (const [kind, attr, low] of [
['point', 'positionHighAndSize', 'positionLowAndOutline'],
['billboard', 'positionHighAndScale', 'positionLowAndRotation'],
]) {
const source = new Cesium.ShaderSource({
defines: ['SDF'],
sources: [
`in vec4 ${attr}; in vec4 ${low}; out vec4 v_color; void main() { v_color=vec4(1.); }`,
],
});
const original = source.sources[0];
const next = sonarVertexSource(source, kind);
assert.equal(source.sources[0], original);
assert.notEqual(next, source);
assert.deepEqual(next.defines, ['SDF']);
assert.match(next.sources[0], /void gev_sonar_main/);
assert.match(next.sources[1], /v_color.a \*= factor/);
assert.match(next.sources[1], /u_gevSonarSector/);
assert.match(next.sources[1], /floorValue \+ \(1.0 - floorValue\) \* 0.46/);
assert.ok(
next.sources[1].includes(
`czm_translateRelativeToEye(${attr}.xyz, ${low}.xyz)`,
),
);
assert.match(next.sources[1], /anchor.xy \/ anchor.w/);
assert.doesNotMatch(next.sources[1], /gl_Position\s*[=\/]/);
}
assert.equal(
sonarVertexSource(
new Cesium.ShaderSource({ sources: ['void main() {}'] }),
'point',
),
null,
);
});
test('render demand follows batch bounds, including horizon culling, without far-plane rejection', () => {
const planes = Array.from(
{ length: 6 },
(_, i) => new Cesium.Cartesian4(1, 0, 0, i),
);
const frame = {
cullingVolume: { planes },
mode: Cesium.SceneMode.SCENE3D,
occluder: {},
};
let intersections = 0;
let occluded = false;
const command = {
cull: true,
occlude: true,
boundingVolume: {
intersectPlane(plane) {
intersections++;
return plane.distance === 5
? Cesium.Intersect.OUTSIDE
: Cesium.Intersect.INSIDE;
},
isOccluded() {
return occluded;
},
},
};
assert.equal(isCyberSonarCommandVisible(command, frame), true);
assert.equal(intersections, 5);
occluded = true;
assert.equal(isCyberSonarCommandVisible(command, frame), false);
frame.mode = Cesium.SceneMode.SCENE2D;
assert.equal(isCyberSonarCommandVisible(command, frame), true);
command.boundingVolume.intersectPlane = () => Cesium.Intersect.OUTSIDE;
assert.equal(isCyberSonarCommandVisible(command, frame), false);
command.cull = false;
assert.equal(isCyberSonarCommandVisible(command, frame), true);
assert.equal(isCyberSonarCommandVisible({}, frame), true);
});
test('adapter never walks contacts, touches other scenes, or transforms pick-only passes', () => {
let calls = 0;
const original = function (fs) {
assert.equal(this, root);
calls++;
fs.commandList.push({ owner: {}, id: 'terrain' });
};
const root = { update: original };
const other = { update: original };
const adapter = createCyberSonarGpu({ primitives: root }, () => ({
enabled: false,
}));
const frame = { commandList: [], passes: { render: true, pick: false } };
root.update(frame);
assert.equal(calls, 1);
assert.equal(frame.commandList[0].id, 'terrain');
assert.equal(other.update, original);
root.update({ commandList: [], passes: { render: false, pick: true } });
assert.equal(calls, 2);
adapter.destroy();
adapter.destroy();
assert.equal(root.update, original);
});
test('unknown native shaders fail closed without losing native commands', () => {
const points = new Cesium.PointPrimitiveCollection();
const command = {
owner: points,
uniformMap: {},
shaderProgram: {
vertexShaderSource: new Cesium.ShaderSource({
sources: ['void main() {}'],
}),
},
};
const root = {
update(fs) {
fs.commandList.push(command);
},
};
const adapter = createCyberSonarGpu(
{ primitives: root, drawingBufferWidth: 800, drawingBufferHeight: 600 },
() => ({
enabled: true,
active: true,
angleDeg: 0,
range: 100,
opacity: 84,
sector: 24,
}),
);
const frame = { commandList: [], passes: { render: true } };
root.update(frame);
assert.equal(frame.commandList[0], command);
assert.equal(adapter.stats.supported, false);
assert.match(adapter.stats.error, /Unsupported native contact shader/);
assert.equal(adapter.stats.programs, 0);
adapter.destroy();
points.destroy();
});
test('program swaps, layer removal and late shader failure release only adapter resources', () => {
const points = new Cesium.PointPrimitiveCollection();
const source = () => ({
vertexShaderSource: new Cesium.ShaderSource({
sources: [
'in vec4 positionHighAndSize; in vec4 positionLowAndOutline; out vec4 v_color; void main() {}',
],
}),
vertexAttributes: {},
fragmentShaderSource: new Cesium.ShaderSource({
sources: ['void main() {}'],
}),
});
const native = new Cesium.DrawCommand({
owner: points,
uniformMap: {},
shaderProgram: source(),
cull: false,
vertexArray: { generation: 1 },
pickId: 'native-pick',
});
const unknown = new Cesium.DrawCommand({
owner: points,
uniformMap: {},
shaderProgram: {
vertexShaderSource: new Cesium.ShaderSource({
sources: ['void main() {}'],
}),
},
});
let nativeCommands = [native];
let enabled = true;
const root = {
update(frame) {
frame.commandList.push(...nativeCommands);
},
};
const fromCache = Cesium.ShaderProgram.fromCache;
const created = [];
Cesium.ShaderProgram.fromCache = () => {
const program = {
allUniforms: {},
destroyed: false,
isDestroyed() {
return this.destroyed;
},
destroy() {
assert.equal(this.destroyed, false);
this.destroyed = true;
},
};
created.push(program);
return program;
};
const adapter = createCyberSonarGpu(
{ primitives: root, drawingBufferWidth: 800, drawingBufferHeight: 600 },
() => ({
enabled,
active: true,
angleDeg: 0,
range: 100,
opacity: 84,
sector: 24,
}),
);
const draw = () => {
const frame = { commandList: [], passes: { render: true } };
root.update(frame);
return frame.commandList;
};
try {
const first = draw()[0];
assert.notEqual(first, native);
first.dirty = false;
assert.equal(draw()[0], first);
assert.equal(first.dirty, false);
assert.equal(created.length, 1, 'stable draws reuse the program');
const buffer = { generation: 2 };
native.vertexArray = buffer;
native.shaderProgram = source();
const swapped = draw()[0];
assert.equal(swapped, first);
assert.equal(swapped.vertexArray, buffer);
assert.equal(swapped.pickId, 'native-pick');
assert.equal(swapped.shaderProgram, created[1]);
assert.equal(created[0].destroyed, true);
assert.equal(adapter.stats.programs, 1);
nativeCommands = [];
draw();
assert.equal(created[1].destroyed, true);
assert.equal(
adapter.stats.programs,
0,
'disabled layers retain no adapter program',
);
nativeCommands = [native];
draw();
enabled = false;
assert.equal(draw()[0], native);
assert.equal(
created[2].destroyed,
true,
'theme/cockpit exit releases the derived program',
);
enabled = true;
nativeCommands = [native, unknown];
assert.deepEqual(
draw(),
nativeCommands,
'a later failure rolls back earlier replacements in the same slice',
);
assert.equal(created[3].destroyed, true);
assert.equal(adapter.stats.supported, false);
assert.equal(adapter.stats.programs, 0);
assert.equal(adapter.stats.commands, 0);
assert.equal(adapter.stats.visibleCommands, 0);
assert.deepEqual(draw(), nativeCommands);
assert.equal(
created.length,
4,
'unsupported draws do not retry compilation',
);
} finally {
adapter.destroy();
Cesium.ShaderProgram.fromCache = fromCache;
points.destroy();
}
});
test('disposal does not overwrite a successor update owner', () => {
const root = { update() {} };
const adapter = createCyberSonarGpu({ primitives: root }, () => ({
enabled: false,
}));
const successor = () => {};
root.update = successor;
adapter.destroy();
assert.equal(root.update, successor);
});
+451
View File
@@ -0,0 +1,451 @@
import * as Cesium from 'cesium';
import { loadBundledJson } from '../../data/bundledJson.js';
import { governorRequestRender } from '../../renderGovernor.js';
import { buildStarVertices, STAR_VERTEX_FLOATS } from '../../sky/stars.js';
/**
* Space background in the `Scene#skyBox` slot: catalogue stars as point
* sprites over a soft Milky Way cube map, both turned by one ICRF→fixed
* rotation at the scene clock (TEME until Cesium's tables load). Scene runs
* the command from `update()` first in the environment pass, so the sky
* stays behind everything without depth. Revalidate on engine upgrades.
*/
export const STARRY_SKY_CESIUM_VERSION = '1.138.0';
/** Brightness of the Milky Way glow; the stars carry the sky. */
export const MILKY_WAY_INTENSITY = 0.4;
/** Clock change, in seconds, below which the sky rotation is reused. */
export const SKY_ROTATION_EPSILON_SECONDS = 1;
const STAR_PACK_URL = new URL(
'../../data/local_data/sky/bright_stars.json',
import.meta.url,
);
const MILKY_WAY_FACE_URLS = Object.freeze({
positiveX: new URL(
'../../data/local_data/sky/milkyway_px.webp',
import.meta.url,
),
negativeX: new URL(
'../../data/local_data/sky/milkyway_nx.webp',
import.meta.url,
),
positiveY: new URL(
'../../data/local_data/sky/milkyway_py.webp',
import.meta.url,
),
negativeY: new URL(
'../../data/local_data/sky/milkyway_ny.webp',
import.meta.url,
),
positiveZ: new URL(
'../../data/local_data/sky/milkyway_pz.webp',
import.meta.url,
),
negativeZ: new URL(
'../../data/local_data/sky/milkyway_nz.webp',
import.meta.url,
),
});
// Directions, not points: w = 0 drops the camera translation, and z just
// under w keeps every fragment at the far plane, inside any frustum.
const SKY_DIRECTION_GLSL = `
uniform mat3 u_icrfToFixed;
vec4 skyClipPosition(vec3 icrfDirection)
{
vec3 eye = czm_viewRotation * (u_icrfToFixed * icrfDirection);
vec4 clip = czm_projection * vec4(eye, 0.0);
clip.z = clip.w * 0.99999;
return clip;
}
`;
const MILKY_WAY_VS = `${SKY_DIRECTION_GLSL}
in vec3 position;
out vec3 v_direction;
void main()
{
gl_Position = skyClipPosition(position);
v_direction = position;
}
`;
const MILKY_WAY_FS = `
uniform samplerCube u_milkyWay;
uniform float u_intensity;
in vec3 v_direction;
void main()
{
vec3 color = czm_textureCube(u_milkyWay, normalize(v_direction)).rgb * u_intensity;
// Interleaved-gradient dither: the dim glow spans only a few 8-bit steps.
float noise = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));
color = max(color + (noise - 0.5) / 255.0, 0.0);
out_FragColor = vec4(czm_gammaCorrect(color), 1.0);
}
`;
const STAR_VS = `${SKY_DIRECTION_GLSL}
in vec3 position;
in float sigma;
in vec4 color;
out vec4 v_color;
out float v_sigma;
out float v_radius;
void main()
{
gl_Position = skyClipPosition(position);
// σ is in CSS pixels; the sprite holds ±3σ plus a pixel of margin.
v_sigma = sigma * czm_pixelRatio;
v_radius = ceil(3.0 * v_sigma) + 1.0;
gl_PointSize = 2.0 * v_radius;
v_color = color;
}
`;
const STAR_FS = `
in vec4 v_color;
in float v_sigma;
in float v_radius;
void main()
{
vec2 offset = (gl_PointCoord - 0.5) * (2.0 * v_radius);
float alpha = v_color.a *
exp(-0.5 * dot(offset, offset) / (v_sigma * v_sigma));
if (alpha < 1.0 / 512.0) discard;
out_FragColor = vec4(czm_gammaCorrect(v_color.rgb) * alpha, alpha);
}
`;
/** Pick the ICRF→fixed rotation for `time`, or TEME while tables load. */
export function computeSkyRotation(time, result) {
const { Transforms } = Cesium;
const icrf = Transforms.computeIcrfToFixedMatrix(time, result);
if (icrf) return { matrix: icrf, precise: true };
return {
matrix: Transforms.computeTemeToPseudoFixedMatrix(time, result),
precise: false,
};
}
/** Whether a cached rotation at `cachedTime` still serves `time`. */
export function isSkyRotationCurrent(cachedTime, time) {
return (
cachedTime !== undefined &&
Math.abs(Cesium.JulianDate.secondsDifference(time, cachedTime)) <
SKY_ROTATION_EPSILON_SECONDS
);
}
export class StarrySky {
/**
* @param {object} [options]
* @param {() => void} [options.requestRender] renders one frame when an
* asset or the precise rotation arrives; the idle governor by default.
*/
constructor({
requestRender = () => governorRequestRender('sky-assets'),
} = {}) {
/** Matches `SkyBox#show`. */
this.show = true;
this.milkyWayIntensity = MILKY_WAY_INTENSITY;
/** 0..1 multiplier a style sets to hide the glow (see postStages.js). */
this.milkyWayVisibility = 1;
this._requestRender = requestRender;
this._rotation = Cesium.Matrix3.clone(Cesium.Matrix3.IDENTITY);
this._rotationTime = undefined;
this._rotationPrecise = false;
this._icrfRequest = undefined;
this._icrfUnavailable = false;
this._icrfMissing = undefined;
this._loading = false;
this._starData = undefined;
this._faceImages = undefined;
// Scene reads `_cubeMap` for model lighting. Keep it dark as on main;
// Cesium's fallback is white, and the ICRF glow is only a background.
this._cubeMap = undefined;
this._milkyWayCubeMap = undefined;
this._milkyWayCommand = undefined;
this._milkyWayAttributes = undefined;
this._starCommand = undefined;
this._useHdr = undefined;
this._destroyed = false;
const uniforms = {
u_icrfToFixed: () => this._rotation,
};
this._milkyWayUniforms = {
...uniforms,
u_milkyWay: () => this._milkyWayCubeMap,
u_intensity: () => this.milkyWayIntensity * this.milkyWayVisibility,
};
this._starUniforms = uniforms;
const commands = [];
this._commands = commands;
// The environment pass reads `derivedCommands` (log depth, HDR, picking)
// before calling `execute`; none apply to a far-plane background.
this._compositeCommand = {
derivedCommands: {},
execute(context, passState) {
for (const command of commands) command.execute(context, passState);
},
};
}
/** Start loading assets; failures leave a plain black sky. */
_load() {
if (this._loading) return;
this._loading = true;
loadBundledJson(STAR_PACK_URL)
.then((pack) => {
if (this._destroyed) return;
this._starData = buildStarVertices(pack);
this._requestRender();
})
.catch((error) =>
console.warn('[sky] star catalogue unavailable', error),
);
const faces = Object.entries(MILKY_WAY_FACE_URLS);
Promise.all(
faces.map(([, url]) => Cesium.Resource.fetchImage({ url: url.href })),
)
.then((images) => {
if (this._destroyed) return;
this._faceImages = Object.fromEntries(
faces.map(([face], index) => [face, images[index]]),
);
this._requestRender();
})
.catch((error) => console.warn('[sky] Milky Way unavailable', error));
}
_updateRotation(time) {
// An approximate rotation is final only while nothing better can come.
const settled =
this._rotationPrecise || this._icrfRequest || !this._canPreloadIcrf(time);
if (settled && isSkyRotationCurrent(this._rotationTime, time)) return;
const { precise } = computeSkyRotation(time, this._rotation);
this._rotationPrecise = precise;
this._rotationTime = Cesium.JulianDate.clone(time, this._rotationTime);
if (!precise) this._preloadIcrf(time);
}
/** Whether loading Cesium's IAU 2006 tables could still help at `time`. */
_canPreloadIcrf(time) {
return (
!this._icrfUnavailable &&
!(
this._icrfMissing &&
Cesium.TimeInterval.contains(this._icrfMissing, time)
)
);
}
/** Fetch Cesium's IAU 2006 tables around `time` once per span. */
_preloadIcrf(time) {
if (this._icrfRequest || !this._canPreloadIcrf(time)) return;
const interval = new Cesium.TimeInterval({
start: Cesium.JulianDate.addDays(time, -1, new Cesium.JulianDate()),
stop: Cesium.JulianDate.addDays(time, 1, new Cesium.JulianDate()),
});
this._icrfRequest = Promise.resolve(
Cesium.Transforms.preloadIcrfFixed(interval),
)
.then(
() => {
// The tables cover roughly 1975–2050; outside them the preload
// resolves with nothing, and TEME stays for this span.
if (!Cesium.Transforms.computeIcrfToFixedMatrix(time)) {
this._icrfMissing = interval;
return;
}
this._rotationTime = undefined;
if (!this._destroyed) this._requestRender();
},
(error) => {
// TEME is within a fraction of a degree; do not retry every frame.
this._icrfUnavailable = true;
console.warn('[sky] ICRF tables unavailable, using TEME', error);
},
)
.finally(() => {
this._icrfRequest = undefined;
});
}
_createMilkyWayCommand(context) {
const cubeMap = new Cesium.CubeMap({
context,
source: this._faceImages,
flipY: false,
});
cubeMap.generateMipmap();
cubeMap.sampler = new Cesium.Sampler({
minificationFilter: Cesium.TextureMinificationFilter.LINEAR_MIPMAP_LINEAR,
});
this._milkyWayCubeMap = cubeMap;
this._faceImages = undefined;
const geometry = Cesium.BoxGeometry.createGeometry(
Cesium.BoxGeometry.fromDimensions({
dimensions: new Cesium.Cartesian3(2, 2, 2),
vertexFormat: Cesium.VertexFormat.POSITION_ONLY,
}),
);
const attributeLocations =
Cesium.GeometryPipeline.createAttributeLocations(geometry);
this._milkyWayCommand = new Cesium.DrawCommand({
owner: this,
vertexArray: Cesium.VertexArray.fromGeometry({
context,
geometry,
attributeLocations,
bufferUsage: Cesium.BufferUsage.STATIC_DRAW,
}),
renderState: Cesium.RenderState.fromCache({}),
uniformMap: this._milkyWayUniforms,
});
this._milkyWayAttributes = attributeLocations;
}
_createStarCommand(context) {
const { count, vertices } = this._starData;
this._starData = undefined;
if (count === 0) return;
const vertexBuffer = Cesium.Buffer.createVertexBuffer({
context,
typedArray: vertices,
usage: Cesium.BufferUsage.STATIC_DRAW,
});
const stride = STAR_VERTEX_FLOATS * Float32Array.BYTES_PER_ELEMENT;
const attribute = (index, components, offsetFloats) => ({
index,
vertexBuffer,
componentsPerAttribute: components,
componentDatatype: Cesium.ComponentDatatype.FLOAT,
offsetInBytes: offsetFloats * Float32Array.BYTES_PER_ELEMENT,
strideInBytes: stride,
});
this._starCommand = new Cesium.DrawCommand({
owner: this,
primitiveType: Cesium.PrimitiveType.POINTS,
count,
vertexArray: new Cesium.VertexArray({
context,
attributes: [
attribute(0, 3, 0),
attribute(1, 1, 3),
attribute(2, 4, 4),
],
}),
// Premultiplied additive: starlight adds to the Milky Way glow and
// leaves the framebuffer alpha alone.
renderState: Cesium.RenderState.fromCache({
blending: {
enabled: true,
equationRgb: Cesium.BlendEquation.ADD,
equationAlpha: Cesium.BlendEquation.ADD,
functionSourceRgb: Cesium.BlendFunction.ONE,
functionDestinationRgb: Cesium.BlendFunction.ONE,
functionSourceAlpha: Cesium.BlendFunction.ZERO,
functionDestinationAlpha: Cesium.BlendFunction.ONE,
},
}),
uniformMap: this._starUniforms,
});
}
_updateShaders(context, useHdr) {
if (this._useHdr === useHdr) return;
this._useHdr = useHdr;
const defines = useHdr ? ['HDR'] : [];
for (const [command, vs, fs, attributeLocations] of [
[
this._milkyWayCommand,
MILKY_WAY_VS,
MILKY_WAY_FS,
this._milkyWayAttributes,
],
[
this._starCommand,
STAR_VS,
STAR_FS,
{ position: 0, sigma: 1, color: 2 },
],
]) {
if (!command) continue;
command.shaderProgram?.destroy();
command.shaderProgram = Cesium.ShaderProgram.fromCache({
context,
vertexShaderSource: vs,
fragmentShaderSource: new Cesium.ShaderSource({
defines,
sources: [fs],
}),
attributeLocations,
});
}
}
/** `Scene#skyBox` contract: the command to draw this frame, if any. */
update(frameState, useHdr) {
if (!this.show) return undefined;
const { mode, passes, context } = frameState;
if (mode !== Cesium.SceneMode.SCENE3D) return undefined;
if (!passes.render) return undefined;
if (!this._cubeMap) {
const face = {
width: 1,
height: 1,
arrayBufferView: new Uint8Array([0, 0, 0, 255]),
};
this._cubeMap = new Cesium.CubeMap({
context,
source: {
positiveX: face,
negativeX: face,
positiveY: face,
negativeY: face,
positiveZ: face,
negativeZ: face,
},
flipY: false,
});
}
this._load();
let rebuilt = false;
if (this._faceImages && !this._milkyWayCommand) {
this._createMilkyWayCommand(context);
rebuilt = true;
}
if (this._starData && !this._starCommand) {
this._createStarCommand(context);
rebuilt = true;
}
if (rebuilt) this._useHdr = undefined;
this._updateShaders(context, Boolean(useHdr));
this._commands.length = 0;
if (this._milkyWayCommand) this._commands.push(this._milkyWayCommand);
if (this._starCommand) this._commands.push(this._starCommand);
if (this._commands.length === 0) return undefined;
this._updateRotation(frameState.time);
return this._compositeCommand;
}
isDestroyed() {
return this._destroyed;
}
destroy() {
for (const command of [this._milkyWayCommand, this._starCommand]) {
if (!command) continue;
command.vertexArray?.destroy();
command.shaderProgram?.destroy();
}
this._milkyWayCubeMap = this._milkyWayCubeMap?.destroy();
this._cubeMap = this._cubeMap?.destroy();
this._milkyWayCommand = undefined;
this._starCommand = undefined;
this._commands.length = 0;
this._destroyed = true;
return undefined;
}
}
+200
View File
@@ -0,0 +1,200 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
MILKY_WAY_INTENSITY,
STARRY_SKY_CESIUM_VERSION,
SKY_ROTATION_EPSILON_SECONDS,
StarrySky,
computeSkyRotation,
isSkyRotationCurrent,
} from './starrySky.js';
const close = (actual, expected, epsilon = 1e-9) =>
assert.ok(Math.abs(actual - expected) <= epsilon, `${actual} vs ${expected}`);
test('the sky-box adapter was validated against this engine version', () => {
assert.equal(
Cesium.VERSION,
STARRY_SKY_CESIUM_VERSION,
'engine upgrades require revalidating the Scene#skyBox contract',
);
});
test('the ICRF rotation is preferred and TEME fills in while tables load', () => {
const time = Cesium.JulianDate.fromIso8601('2026-10-19T00:00:00Z');
const icrf = Cesium.Matrix3.fromRotationZ(0.3);
const teme = Cesium.Matrix3.fromRotationZ(0.2);
const { Transforms } = Cesium;
const original = { ...Transforms };
try {
Transforms.computeIcrfToFixedMatrix = (_, result) =>
Cesium.Matrix3.clone(icrf, result);
Transforms.computeTemeToPseudoFixedMatrix = () =>
assert.fail('TEME not needed');
const precise = computeSkyRotation(time, new Cesium.Matrix3());
assert.equal(precise.precise, true);
assert.ok(Cesium.Matrix3.equals(precise.matrix, icrf));
Transforms.computeIcrfToFixedMatrix = () => undefined;
Transforms.computeTemeToPseudoFixedMatrix = (_, result) =>
Cesium.Matrix3.clone(teme, result);
const approximate = computeSkyRotation(time, new Cesium.Matrix3());
assert.equal(approximate.precise, false);
assert.ok(Cesium.Matrix3.equals(approximate.matrix, teme));
} finally {
Object.assign(Transforms, original);
}
});
test('the TEME fallback keeps the celestial pole on the Earth axis', () => {
// TEME only spins about Z; ICRF differs from it by precession (~0.36° by
// 2026), so the fallback sky is right up to a fraction of a degree.
const time = Cesium.JulianDate.fromIso8601('2026-10-19T00:00:00Z');
const teme = Cesium.Transforms.computeTemeToPseudoFixedMatrix(time);
const pole = Cesium.Matrix3.multiplyByVector(
teme,
Cesium.Cartesian3.UNIT_Z,
new Cesium.Cartesian3(),
);
assert.ok(Math.abs(pole.z - 1) < 1e-9);
});
test('the rotation is reused only within the clock epsilon', () => {
const time = Cesium.JulianDate.fromIso8601('2026-10-19T00:00:00Z');
const later = (seconds) =>
Cesium.JulianDate.addSeconds(time, seconds, new Cesium.JulianDate());
assert.equal(isSkyRotationCurrent(undefined, time), false);
assert.equal(isSkyRotationCurrent(time, later(0.5)), true);
assert.equal(isSkyRotationCurrent(time, later(-0.5)), true);
assert.equal(
isSkyRotationCurrent(time, later(SKY_ROTATION_EPSILON_SECONDS)),
false,
);
});
test('the sky draws nothing when hidden, outside 3D, or in a pick pass', () => {
const sky = new StarrySky({ requestRender: () => {} });
const frameState = (overrides) => ({
mode: Cesium.SceneMode.SCENE3D,
passes: { render: true },
...overrides,
});
sky._loading = true; // keep the test off the network
sky.show = false;
assert.equal(sky.update(frameState()), undefined);
sky.show = true;
assert.equal(
sky.update(frameState({ mode: Cesium.SceneMode.SCENE2D })),
undefined,
);
assert.equal(
sky.update(frameState({ passes: { render: false, pick: true } })),
undefined,
);
// Nothing has loaded yet, so even a render pass has no command.
sky._cubeMap = { destroy() {} }; // no WebGL context in this unit test
assert.equal(sky.update(frameState()), undefined);
assert.equal(sky.isDestroyed(), false);
assert.equal(sky.destroy(), undefined);
assert.equal(sky.isDestroyed(), true);
});
const frame = () => new Promise((resolve) => setImmediate(resolve));
for (const iso of ['1970-01-01T00:00:00Z', '2060-01-01T00:00:00Z']) {
test(`a clock outside the IAU 2006 tables (${iso}) settles on TEME instead of re-rendering every frame`, async () => {
const time = Cesium.JulianDate.fromIso8601(iso);
let renders = 0;
let preloads = 0;
const original = Cesium.Transforms.preloadIcrfFixed;
Cesium.Transforms.preloadIcrfFixed = (interval) => {
preloads += 1;
return original(interval);
};
try {
const sky = new StarrySky({ requestRender: () => (renders += 1) });
for (let i = 0; i < 20; i += 1) {
sky._updateRotation(time); // what update() does once per frame
await frame();
}
assert.ok(
renders <= 1 && preloads <= 1,
`20 frames at a frozen clock -> ${preloads} preloads, ${renders} render requests (expected <= 1 each)`,
);
} finally {
Cesium.Transforms.preloadIcrfFixed = original;
}
});
}
test('the Milky Way glow scales with its visibility, for styles that hide it', () => {
const sky = new StarrySky({ requestRender: () => {} });
close(sky._milkyWayUniforms.u_intensity(), MILKY_WAY_INTENSITY);
sky.milkyWayVisibility = 0;
assert.equal(sky._milkyWayUniforms.u_intensity(), 0);
sky.destroy();
});
test('destroy releases both the background and model environment maps', () => {
const sky = new StarrySky({ requestRender: () => {} });
let destroyed = 0;
sky._cubeMap = {
destroy: () => {
destroyed++;
},
};
sky._milkyWayCubeMap = {
destroy: () => {
destroyed++;
},
};
sky.destroy();
assert.equal(destroyed, 2);
assert.equal(sky._cubeMap, undefined);
assert.equal(sky._milkyWayCubeMap, undefined);
sky.destroy();
assert.equal(destroyed, 2);
});
test('a render update uploads six opaque black environment faces only once', () => {
const uploads = [];
const gl = {
...Cesium.WebGLConstants,
createTexture: () => ({}),
activeTexture() {},
bindTexture() {},
texParameteri() {},
pixelStorei() {},
texImage2D: (...args) => uploads.push(args),
deleteTexture() {},
};
const previous = Cesium.ContextLimits._maximumCubeMapSize;
Cesium.ContextLimits._maximumCubeMapSize = 16;
const sky = new StarrySky({ requestRender: () => {} });
sky._loading = true;
const state = {
context: { _gl: gl },
mode: Cesium.SceneMode.SCENE3D,
passes: { render: true },
};
try {
sky.update(state);
const environment = sky._cubeMap;
assert.ok(environment instanceof Cesium.CubeMap);
assert.equal(uploads.length, 6);
assert.equal(new Set(uploads.map((args) => args[0])).size, 6);
for (const args of uploads) {
assert.equal(args[3], 1);
assert.equal(args[4], 1);
assert.deepEqual([...args[8]], [0, 0, 0, 255]);
}
sky.update(state);
assert.equal(sky._cubeMap, environment);
assert.equal(uploads.length, 6);
sky.destroy();
assert.equal(environment.isDestroyed(), true);
} finally {
if (!sky.isDestroyed()) sky.destroy();
Cesium.ContextLimits._maximumCubeMapSize = previous;
}
});
+83
View File
@@ -0,0 +1,83 @@
import * as Cesium from 'cesium';
import { createTerrainRetryPolicy } from '../../maps/terrainRetry.js';
/** Re:Earth / Mapterhorn ellipsoidal quantized mesh, CC BY 4.0. */
export const KEYLESS_TERRAIN_URL =
'https://terrain.reearth.land/cesium-mesh/ellipsoid';
/** These factories are lazy: a hidden globe must not trigger terrain loading. */
export async function createWorldTerrain(accessToken, { signal } = {}) {
accessToken = String(accessToken || '').trim();
if (!accessToken)
throw new Error('World terrain requires an explicit ion token');
signal?.throwIfAborted();
const resource = await Cesium.IonResource.fromAssetId(1, { accessToken });
signal?.throwIfAborted();
return {
provider: await Cesium.CesiumTerrainProvider.fromUrl(resource, {
requestVertexNormals: true,
requestWaterMask: false,
ellipsoid: Cesium.Ellipsoid.WGS84,
}),
};
}
function logThrottle({ statusCode, delayMs, inWindow }) {
// One line per cooldown window, not per tile: a burst throttles dozens.
if (inWindow !== 1) return;
console.warn(
`[MapStack] Re:Earth terrain answered ${statusCode}; retrying throttled tiles after ${Math.round(delayMs)} ms`,
);
}
/**
* The Re:Earth resource with the tile retry policy attached. Cesium copies
* `retryCallback`/`retryAttempts` onto every derived resource, so layer.json
* and each `{z}/{x}/{y}.terrain` fetch inherit it (see `terrainRetry.js`).
* @param {ReturnType<typeof createTerrainRetryPolicy>} [policy]
* @returns {Cesium.Resource}
*/
export function createKeylessTerrainResource(
policy = createTerrainRetryPolicy({ onThrottle: logThrottle }),
) {
return new Cesium.Resource({
url: KEYLESS_TERRAIN_URL,
retryCallback: policy.retryCallback,
retryAttempts: policy.retryAttempts,
});
}
export async function createKeylessTerrain() {
try {
return {
provider: await Cesium.CesiumTerrainProvider.fromUrl(
createKeylessTerrainResource(),
),
};
} catch (error) {
console.warn(
'[MapStack] Re:Earth terrain unavailable, falling back to flat ellipsoid terrain:',
error,
);
return { provider: new Cesium.EllipsoidTerrainProvider(), fallback: true };
}
}
/**
* The terrain source for a session: Cesium World Terrain with an ion token,
* otherwise the keyless Re:Earth mesh.
* @param {string} [ionToken]
* @returns {{ id: 'world' | 'keyless', create: Function }}
*/
export function terrainSourceFor(ionToken = '') {
const token = String(ionToken || '').trim();
return token
? { id: 'world', create: (request) => createWorldTerrain(token, request) }
: { id: 'keyless', create: createKeylessTerrain };
}
/** Install a terrain factory result (`{ terrain }` or `{ provider }`) on a viewer. */
export function applyTerrain(viewer, result) {
if (result.terrain) viewer.scene.setTerrain(result.terrain);
else viewer.terrainProvider = result.provider;
}
+141
View File
@@ -0,0 +1,141 @@
/**
* @module trailRenderer
* @description Shared track-history renderer (PRD WS-F F4; rebuilt round 6,
* 2026-07-06).
*
* One trail = one ENTITY polyline. Round 6 replaced the faded per-vertex
* Primitive for two owner directives from the field:
* - "the line must ALWAYS be visible": the Primitive's depthFailAppearance
* did not reliably render segments below the photoreal mesh — entity
* polylines with `depthFailMaterial` DO (in-repo proof: CCTV's frustum
* wireframes read through geometry with exactly this), so occluded
* segments now draw dimmed instead of vanishing.
* - "show actual tracks, don't style them too much": the tail-fade is gone;
* the whole history renders at one readable alpha (dimmer where it passes
* behind/below geometry).
*
* Trails update at poll cadence (~15-60 s) plus once on history backfill, so
* assigning a fresh positions array per update is cheap. `allowPicking` has
* no entity equivalent; the polyline entity is excluded from clicks by never
* carrying a pick id the layers' click handlers resolve.
*/
import * as Cesium from 'cesium';
import { registerPickOwner } from '../../data/pickRegistry.js';
// Round 6: trail ENTITIES are pickable (the old Primitive had
// allowPicking:false). A trail hugs its aircraft, so an unclaimed pick would
// read as "empty space" in every layer's click handler and deselect the very
// plane being tracked. Claiming the 'gev-trail:' id namespace makes
// isOwnedByOtherLayer() true for every layer — clicking a trail is a no-op
// everywhere. Registered once at module load; the predicate is pure.
registerPickOwner('trails', (pickedId) =>
String(pickedId).startsWith('gev-trail:'),
);
/** @type {number} Uniquifier for trail entity ids (Cesium requires unique entity ids). */
let _trailSeq = 0;
/** @constant {number} Alpha where the trail passes the depth test. */
const TRAIL_ALPHA = 0.85;
/** @constant {number} Alpha where the trail is behind/below scene geometry —
* visible (owner: never vanish) but readable as occluded. */
const TRAIL_OCCLUDED_ALPHA = 0.4;
/** @constant {number} Squared distance (m^2) below which consecutive points are merged. */
const MIN_SEGMENT_DISTANCE_SQ = 0.01;
/**
* Create an always-visible polyline trail bound to a viewer.
* @param {Cesium.Viewer} viewer - Viewer whose entity collection owns the trail.
* @param {object} options - Trail options.
* @param {string} options.color - CSS color string for the trail hue.
* @param {number} [options.width=2.5] - Polyline width in pixels.
* @returns {{setPositions: function(Cesium.Cartesian3[]): void, setVisible: function(boolean): void, clear: function(): void, destroy: function(): void}}
* Trail handle: setPositions replaces the geometry, setVisible temporarily
* hides it without discarding history, clear empties it, and destroy removes
* the entity permanently.
*/
export function createTrail(viewer, { color, width = 2.5 }) {
const baseColor = Cesium.Color.fromCssColorString(color);
/** @type {Cesium.Cartesian3[]} Current deduped positions (owned copy). */
let current = [];
let destroyed = false;
let visible = true;
/** @type {Cesium.Entity|null} */
let entity = null;
function ensureEntity() {
if (entity || destroyed || !viewer || viewer.isDestroyed()) return;
entity = viewer.entities.add({
id: `gev-trail:${++_trailSeq}`,
show: visible,
polyline: {
// CallbackProperty so a positions swap never rebuilds the entity —
// Cesium re-reads on change; `false` marks it non-constant.
positions: new Cesium.CallbackProperty(() => current, false),
width,
material: baseColor.withAlpha(TRAIL_ALPHA),
// The owner-locked rule (round 6): a segment below the photoreal
// mesh renders dimmed — it must never disappear into the ground.
depthFailMaterial: baseColor.withAlpha(TRAIL_OCCLUDED_ALPHA),
// Round 8 (owner: UAL1104's Pacific trail "cutting through the
// globe"): NONE draws straight 3D chords between waypoints — over a
// sparse trans-oceanic trace a single segment spans hundreds of km
// and tunnels through the planet. GEODESIC subdivides each segment
// along the curved surface (heights interpolated), so long legs hug
// the globe instead of chording through it.
arcType: Cesium.ArcType.GEODESIC,
},
});
}
return {
/**
* Replace the trail geometry with a chronological position list
* (oldest first). Fewer than 2 distinct positions clears the trail.
* @param {Cesium.Cartesian3[]} cartesians - Positions, oldest -> newest.
*/
setPositions(cartesians) {
if (destroyed || !viewer || viewer.isDestroyed()) return;
// Drop consecutive near-duplicates: zero-length segments add nothing.
const positions = [];
for (const position of Array.isArray(cartesians) ? cartesians : []) {
if (!position) continue;
const last = positions[positions.length - 1];
if (
last &&
Cesium.Cartesian3.distanceSquared(last, position) <
MIN_SEGMENT_DISTANCE_SQ
)
continue;
positions.push(position);
}
current = positions.length >= 2 ? positions : [];
ensureEntity();
},
/** Temporarily hide/show the trail without discarding accumulated history. */
setVisible(nextVisible) {
visible = nextVisible !== false;
if (entity) entity.show = visible;
},
/** Empty the trail without removing the entity (cheap re-arm). */
clear() {
current = [];
},
/** Remove the trail entity permanently (layer disable/teardown). */
destroy() {
destroyed = true;
current = [];
if (entity && viewer && !viewer.isDestroyed()) {
try {
viewer.entities.remove(entity);
} catch {
/* torn down */
}
}
entity = null;
},
};
}
+442
View File
@@ -0,0 +1,442 @@
import * as Cesium from 'cesium';
import { applyModelAtmosphereWorkaround } from './atmosphereCompat.js';
import { StarrySky } from './starrySky.js';
import { loadPhotorealisticTileset } from '../../maps/google3d.js';
import {
FREE_LOOK_MAX_HEIGHT_METERS,
globeOutOfFrame,
} from '../../globeInView.js';
// Dev convenience: expose the app's Cesium instance for console/preview probing
// (single shared module instance — avoids dual-Cesium state bugs when testing).
// A getter, because the production build's Cesium global loads only with the
// first Cesium globe.
if (typeof window !== 'undefined' && !('__CESIUM__' in window))
Object.defineProperty(window, '__CESIUM__', {
configurable: true,
get: () => Cesium,
});
const PINCH_ZOOM_MULTIPLIER = 8;
const MAX_PINCH_PIXEL_DELTA = 120;
function boundedPinchDelta(delta) {
if (!Number.isFinite(delta) || delta === 0) return delta;
return (
Math.sign(delta) *
Math.min(Math.abs(delta) * PINCH_ZOOM_MULTIPLIER, MAX_PINCH_PIXEL_DELTA)
);
}
/**
* Add browser trackpad pinch to Cesium's zoom inputs and return its disposer.
* Browsers expose this gesture as a small pixel-mode Ctrl+wheel event.
*/
export function installTrackpadPinchZoom(
viewer,
{ createWheelEvent = (type, init) => new WheelEvent(type, init) } = {},
) {
const controller = viewer?.scene?.screenSpaceCameraController;
const container = viewer?.container;
const canvas = viewer?.canvas;
if (!controller || !container || !canvas)
throw new TypeError('A complete Cesium viewer is required');
const originalZoomEventTypes = controller.zoomEventTypes;
const zoomEventTypes = Array.isArray(originalZoomEventTypes)
? originalZoomEventTypes
: originalZoomEventTypes === undefined
? []
: [originalZoomEventTypes];
const alreadyHandlesControlWheel = zoomEventTypes.some(
(binding) =>
binding?.eventType === Cesium.CameraEventType.WHEEL &&
binding?.modifier === Cesium.KeyboardEventModifier.CTRL,
);
const configuredZoomEventTypes = alreadyHandlesControlWheel
? originalZoomEventTypes
: [
...zoomEventTypes,
{
eventType: Cesium.CameraEventType.WHEEL,
modifier: Cesium.KeyboardEventModifier.CTRL,
},
];
if (!alreadyHandlesControlWheel)
controller.zoomEventTypes = configuredZoomEventTypes;
const relayedEvents = new WeakSet();
const relayPinch = (event) => {
if (
!event.ctrlKey ||
relayedEvents.has(event) ||
event.deltaMode !== 0 ||
!Number.isFinite(event.deltaY) ||
event.deltaY === 0
)
return;
let relayed;
try {
relayed = createWheelEvent('wheel', {
deltaX: event.deltaX,
deltaY: boundedPinchDelta(event.deltaY),
deltaZ: event.deltaZ,
deltaMode: event.deltaMode,
screenX: event.screenX,
screenY: event.screenY,
clientX: event.clientX,
clientY: event.clientY,
ctrlKey: true,
bubbles: true,
cancelable: true,
view: globalThis.window,
});
} catch {
// The registered Ctrl+wheel binding can still consume the original.
return;
}
relayedEvents.add(relayed);
event.preventDefault();
event.stopPropagation();
canvas.dispatchEvent(relayed);
};
container.addEventListener('wheel', relayPinch, {
capture: true,
passive: false,
});
let active = true;
return () => {
if (!active) return;
active = false;
container.removeEventListener('wheel', relayPinch, true);
if (
!alreadyHandlesControlWheel &&
controller.zoomEventTypes === configuredZoomEventTypes
)
controller.zoomEventTypes = originalZoomEventTypes;
};
}
/**
* The pose src/globeInView.js judges, for a Cesium camera: its world-space
* position and basis, its frustum and the eye's height. A frustum other than
* a perspective one is marked, and counts as fully covered there.
* @param {Cesium.Camera} camera
*/
export function cesiumFramePose(camera) {
const frustum = camera.frustum;
return {
position: camera.positionWC,
direction: camera.directionWC,
up: camera.upWC,
right: camera.rightWC,
perspective: frustum instanceof Cesium.PerspectiveFrustum,
fovy: frustum.fovy,
aspectRatio: frustum.aspectRatio,
height: camera.positionCartographic?.height,
};
}
/**
* A free globe camera on a Cesium viewer: in 3D, following no tracked
* entity, and not locked to a reference frame.
*/
function isFreeCesiumGlobeCamera(viewer) {
return (
viewer.scene.mode === Cesium.SceneMode.SCENE3D &&
!viewer.trackedEntity &&
Cesium.Matrix4.equals(viewer.camera.transform, Cesium.Matrix4.IDENTITY)
);
}
/**
* Allow Cesium's free look only below `maxHeight` and return its disposer.
* Orbit, tilt and zoom stay available at every height. A value other code
* sets later is kept as the one to allow below that height, and restored on
* dispose; a `false` written while the camera is above `maxHeight` cannot be
* told apart from this limit's own write, so dispose restores the earlier
* value then. `enableLook` gates the Shift+drag binding only: below its trackball
* height Cesium also turns the camera in place for a drag that starts on the
* stars. That height is lowered to `maxHeight` too, so above it such a drag
* orbits the globe, as it does above Cesium's own 7,500 km.
*/
export function installFreeLookHeightLimit(
viewer,
maxHeight = FREE_LOOK_MAX_HEIGHT_METERS,
) {
const scene = viewer?.scene;
const controller = scene?.screenSpaceCameraController;
const camera = viewer?.camera;
if (!controller || !camera || !scene?.preUpdate)
throw new TypeError('A complete Cesium viewer is required');
const originalTrackBallHeight = controller.minimumTrackBallHeight;
const trackBallHeight = Math.min(originalTrackBallHeight, maxHeight);
controller.minimumTrackBallHeight = trackBallHeight;
let wanted = controller.enableLook;
let written;
const sync = () => {
if (written !== undefined && controller.enableLook !== written)
wanted = controller.enableLook;
const height = camera.positionCartographic?.height;
written = wanted && !(Number.isFinite(height) && height > maxHeight);
controller.enableLook = written;
};
sync();
const removeListener = scene.preUpdate.addEventListener(sync);
let active = true;
return () => {
if (!active) return;
active = false;
removeListener();
if (controller.enableLook === written) controller.enableLook = wanted;
if (controller.minimumTrackBallHeight === trackBallHeight)
controller.minimumTrackBallHeight = originalTrackBallHeight;
};
}
// How often a moving camera is sampled to see whether it has come to rest, how
// far a pose may drift between samples and still count as at rest, and how
// long after the camera last moved the check gives up if Cesium never raises
// moveEnd.
const SETTLE_SAMPLE_MS = 250;
const SETTLE_POSITION_TOLERANCE_M = 1e-3;
const SETTLE_DIRECTION_TOLERANCE = 1e-9;
const SETTLE_GIVE_UP_MS = 5 * 60_000;
/**
* Turn the camera back to the planet when a move ends above `minHeight` with
* no surface on screen (`globeOutOfFrame`: limb glow and slivers up to about
* one sample cell thick can count as none), and return the disposer. Views with
* more surface, such as an oblique orbital shot, are left as they are. This
* catches a saved or shared view that looked away, or any other move that ends
* looking away from the planet.
* Heading and position are kept. Tracked cameras, locked ones (non-identity
* transform), a camera flight in progress, a pointer held down on the canvas
* (a drag held still), the 2D and Columbus modes, and any time `paused`
* returns true (an authored scene playing) are left alone; a check they defer
* runs once they end, however long they last.
* `keyholeRadius`
* returns the radius of the visible circle when a scope mask hides the rest of
* the frame (see `globeFrameShare`), or 0; it is read at every check.
*
* Cesium's `moveEnd` alone is not enough: Cesium compares the camera with the
* last frame's to the last rounding error, and at some of these poses the
* camera drifts by a rounding error every frame, so Cesium never sees it stop.
* So each `moveStart` also starts a check of its own that samples the pose
* every 250 ms, with a tolerance for that drift, and once the pose has held
* for half a second after moving runs the same recovery. It keeps watching
* until Cesium raises `moveEnd`, since under that drift Cesium raises no new
* `moveStart` for a later move, and gives up five minutes after the camera
* last moved.
* `setTimeout` and `clearTimeout` can be injected for tests.
*/
export function installGlobeInViewRecovery(
viewer,
{
minHeight = FREE_LOOK_MAX_HEIGHT_METERS,
keyholeRadius = () => 0,
paused = () => false,
setTimeout: schedule = globalThis.setTimeout,
clearTimeout: unschedule = globalThis.clearTimeout,
} = {},
) {
const scene = viewer?.scene;
const camera = viewer?.camera;
if (!scene || !camera?.moveEnd || !camera?.moveStart)
throw new TypeError('A complete Cesium viewer is required');
// A pointer held on the globe is a gesture in progress, even when it holds
// still for half a second: the check waits until every pointer pressed on
// it (each finger of a pinch) is released. A release the page never sees,
// outside the window, is taken as given when the window loses focus, the
// page is hidden, the canvas loses the pointer's capture, or the pointer
// moves with no button down.
const canvas = scene.canvas;
const releaseTarget = canvas?.ownerDocument ?? canvas;
const releaseWindow = canvas?.ownerDocument?.defaultView;
const heldPointers = new Set();
const onPointerDown = (event) => heldPointers.add(event?.pointerId);
const onPointerUp = (event) => heldPointers.delete(event?.pointerId);
const onPointerMove = (event) => {
if (event?.buttons === 0) heldPointers.delete(event.pointerId);
};
const releaseAll = () => heldPointers.clear();
const onVisibilityChange = () => {
if (canvas.ownerDocument.visibilityState === 'hidden') releaseAll();
};
const listeners = [
[canvas, 'pointerdown', onPointerDown],
[canvas, 'lostpointercapture', onPointerUp],
[releaseTarget, 'pointerup', onPointerUp],
[releaseTarget, 'pointercancel', onPointerUp],
[releaseTarget, 'pointermove', onPointerMove],
[canvas?.ownerDocument, 'visibilitychange', onVisibilityChange],
[releaseWindow, 'blur', releaseAll],
];
for (const [target, type, listener] of listeners)
target?.addEventListener?.(type, listener);
// Returns false while a flight, a paused scene or a held pointer defers the
// check, so the caller can try again once it ends.
const recover = () => {
if (!isFreeCesiumGlobeCamera(viewer)) return true;
// Cesium has no public running-flight flag.
if (camera._currentFlight || paused() || heldPointers.size > 0)
return false;
const height = camera.positionCartographic?.height;
if (
!(height > minHeight) ||
!globeOutOfFrame(cesiumFramePose(camera), {
keyholeRadius: keyholeRadius(),
})
)
return true;
camera.setView({
orientation: {
heading: camera.heading,
pitch: -Cesium.Math.PI_OVER_TWO,
roll: 0,
},
});
scene.requestRender?.();
return true;
};
const lastPosition = new Cesium.Cartesian3();
const lastDirection = new Cesium.Cartesian3();
let settleTimer = null;
let settleElapsed = 0;
let restingSamples = 0;
let movedSinceCheck = false;
const stopSettling = () => {
if (settleTimer !== null) unschedule(settleTimer);
settleTimer = null;
};
const sample = () => {
settleTimer = null;
settleElapsed += SETTLE_SAMPLE_MS;
const atRest =
Cesium.Cartesian3.equalsEpsilon(
camera.positionWC,
lastPosition,
0,
SETTLE_POSITION_TOLERANCE_M,
) &&
Cesium.Cartesian3.equalsEpsilon(
camera.directionWC,
lastDirection,
0,
SETTLE_DIRECTION_TOLERANCE,
);
restingSamples = atRest ? restingSamples + 1 : 0;
if (!atRest) {
movedSinceCheck = true;
settleElapsed = 0;
}
// Two quiet samples in a row after a move: at rest for half a second, as
// for moveEnd.
if (restingSamples >= 2 && movedSinceCheck) {
if (recover()) movedSinceCheck = false;
// A flight or a playing scene bounds its own deferral.
else settleElapsed = 0;
}
if (settleElapsed >= SETTLE_GIVE_UP_MS) return;
Cesium.Cartesian3.clone(camera.positionWC, lastPosition);
Cesium.Cartesian3.clone(camera.directionWC, lastDirection);
settleTimer = schedule(sample, SETTLE_SAMPLE_MS);
};
const startSettling = () => {
stopSettling();
settleElapsed = 0;
restingSamples = 0;
movedSinceCheck = true;
Cesium.Cartesian3.clone(camera.positionWC, lastPosition);
Cesium.Cartesian3.clone(camera.directionWC, lastDirection);
settleTimer = schedule(sample, SETTLE_SAMPLE_MS);
};
const removeMoveEnd = camera.moveEnd.addEventListener(() => {
if (recover()) stopSettling();
// Deferred: keep sampling so the check runs once the flight or scene ends.
else if (settleTimer === null) startSettling();
});
const removeMoveStart = camera.moveStart.addEventListener(startSettling);
let active = true;
return () => {
if (!active) return;
active = false;
stopSettling();
removeMoveEnd();
removeMoveStart();
for (const [target, type, listener] of listeners)
target?.removeEventListener?.(type, listener);
heldPointers.clear();
};
}
/**
* Google's photorealistic 3D tiles for the startup stack, on this Cesium
* (src/maps/google3d.js loadPhotorealisticTileset, which takes the SDK).
* @param {{ googleApiKey?: string, googleTokens?: object | null,
* cesiumToken?: string }} keys
*/
export const loadCesiumPhotorealTileset = (keys) =>
loadPhotorealisticTileset(Cesium, keys);
/** Cesium.Viewer options of the standard globe viewer. */
export function applicationViewerOptions(creditContainer) {
return {
timeline: false,
animation: false,
baseLayerPicker: false,
geocoder: false,
homeButton: false,
sceneModePicker: false,
navigationHelpButton: false,
fullscreenButton: false,
vrButton: false,
selectionIndicator: false,
infoBox: false,
baseLayer: false,
// Replaces the blocky Tycho-2 default. An option, not `skyBox: false`,
// which would also stop CesiumWidget from creating the Sun and Moon.
skyBox: new StarrySky(),
creditContainer,
msaaSamples: 4,
contextOptions: { webgl: { preserveDrawingBuffer: true } },
};
}
/** Create the standard globe viewer in caller-owned, visible containers. */
export function createApplicationViewer({ container, creditContainer }) {
if (!container || !creditContainer)
throw new TypeError('Viewer and credit containers are required');
const viewer = new Cesium.Viewer(
container,
applicationViewerOptions(creditContainer),
);
try {
viewer.targetFrameRate = 60;
// A phone pinch spans fewer screen pixels than desktop zoom gestures.
// Keep Cesium's distance-aware zoom and collision limits, with less travel
// required on touch-first screens. Mouse/trackpad sensitivity stays native.
if (globalThis.matchMedia?.('(pointer: coarse)').matches)
viewer.scene.screenSpaceCameraController.zoomFactor *= 3;
// Before any tile builds a draw command: Cesium's per-vertex model
// atmosphere fails to LINK on Apple's Metal backend and kills the
// render loop. See atmosphereCompat.js.
applyModelAtmosphereWorkaround(viewer.scene);
viewer.scene.globe.show = false;
viewer.scene.skyAtmosphere.show = true;
viewer.scene.skyAtmosphere.atmosphereLightIntensity = 18;
viewer.scene.skyAtmosphere.saturationShift = -0.12;
viewer.scene.skyAtmosphere.brightnessShift = -0.08;
return viewer;
} catch (error) {
viewer.destroy();
throw error;
}
}
+246
View File
@@ -0,0 +1,246 @@
import * as Cesium from 'cesium';
import { governorRequestRender } from '../../renderGovernor.js';
/** Whole-Earth input limit; explicit camera destinations can go farther. */
export const MAXIMUM_ZOOM_DISTANCE_M = 40_000_000;
/** Below this, oblique browsing is left alone. */
export const PITCH_CLAMP_MIN_HEIGHT_M = 300_000;
// Plain numbers: on a page that starts on Navara the Cesium SDK loads only
// with the first Cesium globe, after this module (src/app/loadCesium.js).
const RADIANS_PER_DEGREE = Math.PI / 180;
/** Look this far below the Earth's limb, so the globe stays on screen. */
const LIMB_MARGIN_RAD = 8 * RADIANS_PER_DEGREE;
const PITCH_EASE = 0.35;
const PITCH_SNAP_RAD = 0.1 * RADIANS_PER_DEGREE;
const HEIGHT_EPSILON_M = 0.0001;
const EARTH_RADIUS_M = 6_371_000;
let bindings = null;
const inputBindings = () =>
(bindings ??= Object.values(Cesium.CameraEventType).flatMap((type) =>
[undefined, ...Object.values(Cesium.KeyboardEventModifier)].map(
(modifier) => ({
type,
modifier,
}),
),
));
/**
* The shallowest pitch (radians, negative is down) that still keeps the Earth
* framed from height `h`, or null where tilted views are left alone.
* The limb sits acos(R / (R + h)) below the local horizontal.
*/
export function maxPitchForHeight(h) {
if (!(h >= PITCH_CLAMP_MIN_HEIGHT_M)) return null;
const limb = Math.acos(EARTH_RADIUS_M / (EARTH_RADIUS_M + h));
return -Math.min(limb + LIMB_MARGIN_RAD, Cesium.Math.PI_OVER_TWO);
}
function matchesZoomBinding(bindings, type, modifier) {
if (Array.isArray(bindings))
return bindings.some((binding) =>
matchesZoomBinding(binding, type, modifier),
);
return typeof bindings === 'number'
? bindings === type && modifier === undefined
: bindings?.eventType === type && bindings?.modifier === modifier;
}
function readInput(aggregator, bindings) {
let outward = false;
let cancel = false;
for (const { type, modifier } of inputBindings()) {
if (!aggregator.isMoving(type, modifier)) continue;
const movement = aggregator.getMovement(type, modifier);
const pinch = type === Cesium.CameraEventType.PINCH;
const distance = pinch ? movement.distance : movement;
const delta = distance.endPosition.y - distance.startPosition.y;
// Cesium tilts by the fingers' midpoint while zooming by their spacing,
// both in the same quarter-pixel units. Fingers rarely keep a perfectly
// even spacing, so the larger of the two movements decides the gesture.
const tilt = pinch
? movement.angleAndHeight.endPosition.y -
movement.angleAndHeight.startPosition.y
: 0;
if (
matchesZoomBinding(bindings, type, modifier) &&
Math.abs(delta) > Math.abs(tilt)
) {
outward ||= delta < 0;
cancel ||= delta > 0;
} else {
// Includes modifier-specific tilts and parallel two-finger movement.
cancel = true;
}
}
aggregator.reset();
return { outward, cancel };
}
/**
* Keep outward user zooms bounded and framed, without taking camera ownership
* from tilts, tracked entities or flights. Returns an idempotent disposer.
*/
export function installZoomOutGuard(
viewer,
{
requestRender = governorRequestRender,
subscribeCameraHandoff,
createAggregator = (canvas) => new Cesium.CameraEventAggregator(canvas),
} = {},
) {
const scene = viewer?.scene;
const controller = scene?.screenSpaceCameraController;
const camera = viewer?.camera;
const canvas = viewer?.canvas;
if (
!controller ||
!camera ||
!canvas ||
!scene.preRender ||
!scene.postUpdate
)
throw new TypeError('A complete Cesium viewer is required');
const aggregator = createAggregator(canvas);
const originalMaximumZoomDistance = controller.maximumZoomDistance;
const ownsCeiling = originalMaximumZoomDistance > MAXIMUM_ZOOM_DISTANCE_M;
let maximumZoomDistance = Math.min(
originalMaximumZoomDistance,
MAXIMUM_ZOOM_DISTANCE_M,
);
controller.maximumZoomDistance = maximumZoomDistance;
// Cesium clamps any zoom that starts above the limit to the limit, in either
// direction. A camera placed higher by a flight or share link keeps its own
// height as the limit, so it zooms in gradually and can't climb further.
const followCeiling = () => {
if (!ownsCeiling || controller.maximumZoomDistance !== maximumZoomDistance)
return;
// While tracking, Cesium measures zoom from the target, not the Earth, so
// the camera's altitude would lift the ceiling with every outward step.
const untracked =
scene.mode === Cesium.SceneMode.SCENE3D &&
Cesium.Matrix4.equals(camera.transform, Cesium.Matrix4.IDENTITY);
const height = untracked ? camera.positionCartographic?.height : undefined;
maximumZoomDistance =
height > MAXIMUM_ZOOM_DISTANCE_M ? height : MAXIMUM_ZOOM_DISTANCE_M;
controller.maximumZoomDistance = maximumZoomDistance;
};
followCeiling();
let lastHeight = camera.positionCartographic?.height;
let lastPosition = Cesium.Cartesian3.clone(camera.position);
let lastHeading = camera.heading;
let lastPitch = camera.pitch;
let lastRoll = camera.roll;
let zoomingOut = false;
let settling = false;
const cancel = () => {
zoomingOut = false;
settling = false;
};
const guard = () => {
const input = readInput(aggregator, controller.zoomEventTypes);
const height = camera.positionCartographic?.height;
const climbing = height > lastHeight + HEIGHT_EPSILON_M;
const descending = height < lastHeight - HEIGHT_EPSILON_M;
try {
if (
scene.mode !== Cesium.SceneMode.SCENE3D ||
controller.enableInputs === false ||
controller.enableZoom === false ||
!Cesium.Matrix4.equals(camera.transform, Cesium.Matrix4.IDENTITY) ||
// Cesium has no public running-flight flag.
camera._currentFlight ||
input.cancel ||
(descending && !settling)
) {
cancel();
return;
}
if (input.outward) {
zoomingOut = true;
// A genuine outward gesture can be blocked by the controller's ceiling.
settling = true;
}
if (climbing) {
if (!zoomingOut) return;
settling = true;
} else {
zoomingOut = false;
// Outward inertia can lower altitude when Cesium clamps slant range at
// the ceiling. Finish that correction; fresh inward input cancels above.
// A stationary correction owns only the pose it last produced.
if (
!input.outward &&
((!descending &&
!Cesium.Cartesian3.equals(camera.position, lastPosition)) ||
Math.abs(Cesium.Math.negativePiToPi(camera.heading - lastHeading)) >
1e-10 ||
Math.abs(camera.pitch - lastPitch) > 1e-10 ||
Math.abs(Cesium.Math.negativePiToPi(camera.roll - lastRoll)) >
1e-10)
)
settling = false;
if (!settling) return;
}
const maxPitch = maxPitchForHeight(height);
if (maxPitch === null || !(camera.pitch > maxPitch)) {
settling = false;
} else {
const error = maxPitch - camera.pitch;
const easedPitch =
Math.abs(error) <= PITCH_SNAP_RAD
? maxPitch
: camera.pitch + error * PITCH_EASE;
// A large wheel step must not leave the view above the limb while easing.
const limbPitch = -Math.acos(
EARTH_RADIUS_M / (EARTH_RADIUS_M + height),
);
const pitch = Math.min(easedPitch, limbPitch);
camera.setView({
orientation: { heading: camera.heading, pitch, roll: camera.roll },
});
settling = pitch > maxPitch;
}
// Observe the end of inertia too; no arbitrary timeout cuts off a long zoom.
if (zoomingOut || settling) requestRender('zoom-out-guard');
} finally {
lastHeight = camera.positionCartographic?.height;
lastPosition = Cesium.Cartesian3.clone(camera.position, lastPosition);
lastHeading = camera.heading;
lastPitch = camera.pitch;
lastRoll = camera.roll;
}
};
const removePreRender = scene.preRender.addEventListener(guard);
// Fires every frame, after Cesium has applied this frame's input, while
// preRender fires only on frames that draw. Input that didn't move the camera
// (such as wheel at the ceiling) would otherwise wait for an unrelated frame.
const removePostUpdate = scene.postUpdate.addEventListener(() => {
followCeiling();
if (
inputBindings().some(({ type, modifier }) =>
aggregator.isMoving(type, modifier),
)
)
requestRender('zoom-out-guard');
});
const removeCameraHandoff = subscribeCameraHandoff?.(() => {
cancel();
// Discard input queued before an explicit navigation action took ownership.
aggregator.reset();
});
let active = true;
return () => {
if (!active) return;
active = false;
removeCameraHandoff?.();
removePreRender?.();
removePostUpdate?.();
aggregator.destroy();
if (controller.maximumZoomDistance === maximumZoomDistance)
controller.maximumZoomDistance = originalMaximumZoomDistance;
};
}
+764
View File
@@ -0,0 +1,764 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
installZoomOutGuard,
maxPitchForHeight,
MAXIMUM_ZOOM_DISTANCE_M,
} from './zoomOutGuard.js';
const deg = Cesium.Math.toDegrees;
const { WHEEL, PINCH, RIGHT_DRAG, LEFT_DRAG, MIDDLE_DRAG } =
Cesium.CameraEventType;
const { CTRL, SHIFT, ALT } = Cesium.KeyboardEventModifier;
test('maxPitchForHeight leaves low-altitude tilt alone', () => {
assert.equal(maxPitchForHeight(0), null);
assert.equal(maxPitchForHeight(299_999), null);
assert.equal(maxPitchForHeight(NaN), null);
assert.equal(maxPitchForHeight(undefined), null);
});
test('maxPitchForHeight looks 8 degrees below the limb', () => {
assert.ok(Math.abs(deg(maxPitchForHeight(1_000_000)) + 38.19) < 0.01);
assert.equal(deg(maxPitchForHeight(1e12)), -90);
});
test('maxPitchForHeight steepens monotonically with height', () => {
let previous = 0;
for (let h = 300_000; h <= 100_000_000; h *= 1.5) {
const pitch = maxPitchForHeight(h);
assert.ok(pitch <= previous, `pitch at ${h} m`);
previous = pitch;
}
});
function guardFixture({ maximumZoomDistance = Infinity } = {}) {
const preRender = new Set();
const postUpdate = new Set();
const handoffs = new Set();
const container = new EventTarget();
const canvas = new EventTarget();
const movements = new Map();
const key = (type, modifier) => `${type}:${modifier}`;
const aggregator = {
resets: 0,
destroys: 0,
isMoving: (type, modifier) => movements.has(key(type, modifier)),
getMovement: (type, modifier) => movements.get(key(type, modifier)),
reset() {
movements.clear();
this.resets++;
},
destroy() {
this.destroys++;
movements.clear();
},
};
const camera = {
height: 170_000,
longitude: 0,
latitude: 0,
heading: 0.4,
pitch: Cesium.Math.toRadians(-25),
roll: 0,
transform: Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY),
views: [],
get positionCartographic() {
return {
height: this.height,
longitude: this.longitude,
latitude: this.latitude,
};
},
get position() {
return this.positionWC;
},
get positionWC() {
return Cesium.Cartesian3.fromRadians(
this.longitude,
this.latitude,
this.height,
);
},
setView({ orientation }) {
this.views.push(orientation);
this.heading = orientation.heading;
this.pitch = orientation.pitch;
this.roll = orientation.roll;
},
};
const controller = {
maximumZoomDistance,
enableInputs: true,
enableZoom: true,
zoomEventTypes: [
RIGHT_DRAG,
WHEEL,
PINCH,
{ eventType: WHEEL, modifier: CTRL },
],
};
const scene = {
mode: Cesium.SceneMode.SCENE3D,
screenSpaceCameraController: controller,
preRender: {
addEventListener(handler) {
preRender.add(handler);
return () => preRender.delete(handler);
},
},
postUpdate: {
addEventListener(handler) {
postUpdate.add(handler);
return () => postUpdate.delete(handler);
},
},
};
const renders = [];
const dispose = installZoomOutGuard(
{ camera, container, canvas, scene },
{
subscribeCameraHandoff(listener) {
handoffs.add(listener);
return () => handoffs.delete(listener);
},
createAggregator(element) {
assert.equal(element, canvas);
return aggregator;
},
requestRender: (reason) => renders.push(reason),
},
);
// A frame Cesium skips drawing in request-render mode: no preRender.
const idleFrame = () => {
for (const handler of postUpdate) handler();
};
const frame = (height = camera.height) => {
camera.height = height;
idleFrame();
for (const handler of preRender) handler();
};
const movement = (type, deltaY, { modifier, tiltDeltaY = 0 } = {}) => {
const distance = {
startPosition: new Cesium.Cartesian2(0, 0),
endPosition: new Cesium.Cartesian2(0, deltaY),
};
movements.set(
key(type, modifier),
type === PINCH
? {
distance,
angleAndHeight: {
startPosition: new Cesium.Cartesian2(0, 0),
endPosition: new Cesium.Cartesian2(0, tiltDeltaY),
},
}
: distance,
);
// Also exercise the former raw DOM path when running against the PR head.
const event = new Event(
type === WHEEL ? 'wheel' : type === PINCH ? 'touchmove' : 'pointermove',
);
Object.assign(event, {
buttons: type === RIGHT_DRAG ? 2 : type === MIDDLE_DRAG ? 4 : 1,
ctrlKey: modifier === CTRL,
shiftKey: modifier === SHIFT,
altKey: modifier === ALT,
touches: type === PINCH ? [1, 2] : [],
});
container.dispatchEvent(event);
};
return {
camera,
controller,
scene,
aggregator,
preRender,
postUpdate,
handoffs,
handoff: () => {
for (const listener of handoffs) listener();
},
renders,
dispose,
frame,
idleFrame,
movement,
};
}
test('a tilted wheel zoom-out pitches down and preserves heading and roll', () => {
const f = guardFixture();
f.frame();
f.movement(WHEEL, -10);
f.frame(1_000_000);
const target = maxPitchForHeight(1_000_000);
assert.ok(f.camera.pitch < Cesium.Math.toRadians(-25));
assert.ok(f.camera.pitch > target, 'eases rather than snapping');
assert.equal(f.camera.heading, 0.4);
assert.equal(f.camera.roll, 0);
for (let i = 1; i <= 40; i++) f.frame(1_000_000 + i);
assert.ok(
Math.abs(f.camera.pitch - maxPitchForHeight(f.camera.height)) < 1e-3,
);
assert.ok(f.renders.length > 0);
});
test('a large outward step immediately keeps the Earth limb in view', () => {
const f = guardFixture();
f.frame(500_000);
f.movement(WHEEL, -100);
f.frame(20_000_000);
const limbPitch = -Math.acos(6_371_000 / (6_371_000 + 20_000_000));
assert.ok(f.camera.pitch <= limbPitch);
assert.ok(f.camera.pitch > maxPitchForHeight(20_000_000));
});
test('pinch, right-drag and configured Ctrl+wheel can zoom out', () => {
for (const [type, modifier] of [[PINCH], [RIGHT_DRAG], [WHEEL, CTRL]]) {
const f = guardFixture();
f.frame(500_000);
f.movement(type, -10, { modifier });
f.frame(700_000);
assert.equal(f.camera.views.length, 1, `${type}:${modifier}`);
f.dispose();
}
});
test('Ctrl+right-drag tilt is left at the pose chosen by Cesium', () => {
const f = guardFixture();
f.frame(500_000);
f.movement(RIGHT_DRAG, 3, { modifier: CTRL });
// Real Cesium's orbit tilt raises altitude with no zoom movement.
f.camera.pitch = Cesium.Math.toRadians(-26.07722459498313);
f.frame(529_392.3759876974);
assert.equal(f.camera.views.length, 0);
assert.equal(deg(f.camera.pitch), -26.07722459498313);
});
test('parallel two-finger tilt is not mistaken for pinch zoom', () => {
const f = guardFixture();
f.frame(500_000);
f.movement(PINCH, 0, { tiltDeltaY: 3 });
f.frame(600_000);
assert.equal(f.camera.views.length, 0);
});
test('two-finger tilt with finger-spacing drift is left to Cesium', () => {
for (const [spacing, tilt] of [
[-0.01, 3],
[-2, 3],
[-3, -3],
]) {
const f = guardFixture();
f.frame(500_000);
f.movement(PINCH, spacing, { tiltDeltaY: tilt });
// Real Cesium's two-finger tilt climbs and picks its own pitch.
f.camera.pitch = Cesium.Math.toRadians(-26.07746);
f.frame(529_406);
assert.equal(f.camera.views.length, 0, `${spacing}, ${tilt}`);
f.dispose();
}
});
test('a pinch that closes the fingers more than it moves them still zooms out', () => {
// One finger still, the other sliding towards it: the midpoint moves half as far.
const f = guardFixture();
f.frame(500_000);
f.movement(PINCH, -10, { tiltDeltaY: -5 });
f.frame(700_000);
assert.equal(f.camera.views.length, 1);
f.dispose();
});
test('unconfigured wheel modifiers and one-finger drag do not enable the guard', () => {
for (const [type, modifier] of [[WHEEL, SHIFT], [WHEEL, ALT], [LEFT_DRAG]]) {
const f = guardFixture();
f.frame(500_000);
f.movement(type, -10, { modifier });
f.frame(600_000);
assert.equal(f.camera.views.length, 0, `${type}:${modifier}`);
f.dispose();
}
});
test('current controller zoom bindings are honored', () => {
const f = guardFixture();
f.frame(500_000);
f.controller.zoomEventTypes = { eventType: MIDDLE_DRAG, modifier: ALT };
f.movement(WHEEL, -10);
f.frame(600_000);
assert.equal(f.camera.views.length, 0);
f.movement(MIDDLE_DRAG, -10, { modifier: ALT });
f.frame(700_000);
assert.equal(f.camera.views.length, 1);
});
test('programmatic height changes alone never activate the guard', () => {
const f = guardFixture();
f.frame(170_000);
f.frame(2_000_000);
f.frame(3_000_000);
assert.equal(f.camera.views.length, 0);
});
test('inward zoom does not activate the guard even when altitude rises', () => {
const f = guardFixture();
f.frame(500_000);
f.movement(WHEEL, 10);
f.frame(600_000);
assert.equal(f.camera.views.length, 0);
});
test('outward input with falling height does not alter pitch', () => {
const f = guardFixture();
f.frame(2_000_000);
f.movement(WHEEL, -10);
f.frame(1_500_000);
f.frame(1_500_000);
assert.equal(f.camera.views.length, 0);
});
test('pitch finishes settling when the zoom stops changing height', () => {
const f = guardFixture();
f.frame(500_000);
f.movement(WHEEL, -10);
f.frame(2_000_000);
const firstPitch = f.camera.pitch;
for (let i = 0; i < 40; i++) f.frame();
assert.ok(f.camera.pitch < firstPitch);
assert.ok(Math.abs(f.camera.pitch - maxPitchForHeight(2_000_000)) < 1e-10);
const views = f.camera.views.length;
f.frame();
assert.equal(
f.camera.views.length,
views,
'settled pose does not keep rendering',
);
});
test('completed settling does not authorize a later programmatic climb', () => {
const f = guardFixture();
f.frame(500_000);
f.movement(WHEEL, -10);
f.frame(700_000);
for (let i = 0; i < 40; i++) f.frame();
const views = f.camera.views.length;
f.frame(3_000_000);
assert.equal(f.camera.views.length, views);
});
test('a fresh inward zoom or unrelated gesture cancels pending correction', () => {
for (const [type, delta, options] of [
[WHEEL, 10, {}],
[RIGHT_DRAG, 3, { modifier: CTRL }],
[LEFT_DRAG, 3, {}],
[MIDDLE_DRAG, 3, {}],
[PINCH, 0, { tiltDeltaY: 3 }],
]) {
const f = guardFixture();
f.frame(500_000);
f.movement(WHEEL, -10);
f.frame(700_000);
const views = f.camera.views.length;
f.movement(type, delta, options);
f.frame(800_000);
f.frame(900_000);
assert.equal(f.camera.views.length, views, `${type}:${options.modifier}`);
f.dispose();
}
});
test('an external pose change at fixed height cancels pending correction', () => {
for (const field of ['heading', 'pitch', 'roll', 'longitude', 'latitude']) {
const f = guardFixture();
f.frame(500_000);
f.movement(WHEEL, -10);
f.frame(700_000);
const views = f.camera.views.length;
f.camera[field] += 0.1;
f.frame();
f.frame(900_000);
assert.equal(f.camera.views.length, views, field);
f.dispose();
}
});
test('disabled controls, flights, tracked transforms and non-3D scenes cancel intent', () => {
const cases = [
(f) => {
f.controller.enableInputs = false;
return () => {
f.controller.enableInputs = true;
};
},
(f) => {
f.controller.enableZoom = false;
return () => {
f.controller.enableZoom = true;
};
},
(f) => {
f.camera._currentFlight = {};
return () => {
delete f.camera._currentFlight;
};
},
(f) => {
f.camera.transform = Cesium.Matrix4.fromTranslation(
new Cesium.Cartesian3(1, 2, 3),
);
return () => {
f.camera.transform = Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY);
};
},
(f) => {
f.scene.mode = Cesium.SceneMode.SCENE2D;
return () => {
f.scene.mode = Cesium.SceneMode.SCENE3D;
};
},
];
for (const block of cases) {
const f = guardFixture();
f.frame(500_000);
f.movement(WHEEL, -10);
f.frame(700_000);
const views = f.camera.views.length;
const restore = block(f);
f.movement(WHEEL, -10);
f.frame(800_000);
restore();
f.frame(900_000);
assert.equal(f.camera.views.length, views);
f.movement(WHEEL, -10);
f.frame(1_000_000);
assert.equal(f.camera.views.length, views + 1);
f.dispose();
}
});
test('installer sets the ceiling and disposer releases aggregator and frame listener', () => {
const f = guardFixture();
assert.equal(f.controller.maximumZoomDistance, MAXIMUM_ZOOM_DISTANCE_M);
assert.equal(f.preRender.size, 1);
assert.equal(f.postUpdate.size, 1);
f.frame();
assert.ok(f.aggregator.resets > 0);
f.dispose();
f.dispose();
assert.equal(f.controller.maximumZoomDistance, Infinity);
assert.equal(f.aggregator.destroys, 1);
assert.equal(f.preRender.size, 0);
assert.equal(f.postUpdate.size, 0);
assert.equal(f.handoffs.size, 0);
});
test('installer preserves a stricter host zoom ceiling', () => {
const f = guardFixture({ maximumZoomDistance: 123 });
assert.equal(f.controller.maximumZoomDistance, 123);
f.dispose();
assert.equal(f.controller.maximumZoomDistance, 123);
});
test('disposer keeps a ceiling someone else changed later', () => {
const f = guardFixture();
f.controller.maximumZoomDistance = 5;
f.dispose();
assert.equal(f.controller.maximumZoomDistance, 5);
});
test('installer rejects an incomplete viewer', () => {
assert.throws(() => installZoomOutGuard({}), TypeError);
});
test('outward input at the ceiling reframes a deliberately tilted camera', () => {
const f = guardFixture();
f.frame(MAXIMUM_ZOOM_DISTANCE_M);
f.movement(WHEEL, -10);
f.frame();
for (let i = 0; i < 40; i++) f.frame();
assert.ok(
Math.abs(f.camera.pitch - maxPitchForHeight(MAXIMUM_ZOOM_DISTANCE_M)) <
1e-10,
);
f.dispose();
});
test('input that leaves the camera still requests a frame to read it', () => {
const f = guardFixture();
f.frame(MAXIMUM_ZOOM_DISTANCE_M);
f.idleFrame();
assert.deepEqual(f.renders, [], 'an idle scene stays idle');
// At the ceiling Cesium doesn't move the camera, so nothing would draw.
f.movement(WHEEL, -10);
f.idleFrame();
assert.deepEqual(f.renders, ['zoom-out-guard']);
f.frame();
assert.ok(f.camera.pitch < Cesium.Math.toRadians(-25), 'read that frame');
f.dispose();
});
test('equivalent heading and roll wraps do not cancel stationary settling', () => {
const f = guardFixture();
f.frame(500_000);
f.movement(WHEEL, -10);
f.frame(2_000_000);
f.camera.heading += Cesium.Math.TWO_PI;
f.camera.roll += Cesium.Math.TWO_PI;
for (let i = 0; i < 40; i++) f.frame();
assert.ok(Math.abs(f.camera.pitch - maxPitchForHeight(2_000_000)) < 1e-10);
f.dispose();
});
test('a real Cesium camera settles across the north heading wrap at Istanbul', () => {
const scene = {
canvas: { clientWidth: 1200, clientHeight: 800, width: 1200, height: 800 },
drawingBufferWidth: 1200,
drawingBufferHeight: 800,
mapProjection: new Cesium.GeographicProjection(),
globe: { ellipsoid: Cesium.Ellipsoid.WGS84 },
mapMode2D: Cesium.MapMode2D.INFINITE_SCROLL,
mode: Cesium.SceneMode.SCENE3D,
pixelRatio: 1,
preRender: new Cesium.Event(),
postUpdate: new Cesium.Event(),
screenSpaceCameraController: {
maximumZoomDistance: Infinity,
enableInputs: true,
zoomEventTypes: [WHEEL],
},
};
const camera = new Cesium.Camera(scene);
scene.camera = camera;
const setHeight = (height) =>
camera.setView({
destination: Cesium.Cartesian3.fromDegrees(28.9784, 41.0082, height),
orientation: { heading: 0, pitch: Cesium.Math.toRadians(-25), roll: 0 },
});
setHeight(1_000_000);
let outward = false;
const dispose = installZoomOutGuard(
{ scene, camera, canvas: scene.canvas },
{
createAggregator: () => ({
isMoving: (type, modifier) =>
outward && type === WHEEL && modifier === undefined,
getMovement: () => ({
startPosition: { y: 0 },
endPosition: { y: -10 },
}),
reset: () => {
outward = false;
},
destroy() {},
}),
requestRender() {},
},
);
try {
setHeight(MAXIMUM_ZOOM_DISTANCE_M);
outward = true;
for (let i = 0; i < 40; i++) scene.preRender.raiseEvent(scene);
assert.ok(
Math.abs(
camera.pitch - maxPitchForHeight(camera.positionCartographic.height),
) < 1e-8,
);
} finally {
dispose();
}
});
test('an outward inertia ceiling adjustment can descend while pitch settles', () => {
const f = guardFixture();
f.frame(39_000_000);
f.movement(WHEEL, -10);
f.frame(39_999_999);
const before = f.camera.pitch;
// Cesium limits slant range on an inertial pick, slightly below the altitude cap.
f.frame(39_997_258);
for (let i = 0; i < 40; i++) f.frame();
assert.ok(f.camera.pitch < before);
assert.ok(
Math.abs(f.camera.pitch - maxPitchForHeight(f.camera.height)) < 1e-10,
);
f.dispose();
});
test('a descending programmatic tilt cancels pending correction', () => {
const f = guardFixture();
f.frame(39_000_000);
f.movement(WHEEL, -10);
f.frame(39_999_999);
const count = f.camera.views.length;
f.camera.pitch += 0.1;
f.frame(39_997_258);
for (let i = 0; i < 40; i++) f.frame();
assert.equal(f.camera.views.length, count);
f.dispose();
});
test('explicit navigation cancels outward inertia before a climbing UI tilt', () => {
const f = guardFixture();
f.movement(WHEEL, -10);
f.frame(1_000_000);
f.movement(WHEEL, -10);
f.handoff();
const writes = f.camera.views.length;
f.camera.pitch = Cesium.Math.toRadians(-25);
f.frame(1_100_000);
f.frame(1_200_000);
assert.equal(f.camera.views.length, writes);
assert.equal(deg(f.camera.pitch), -25);
// A subsequent user zoom starts a new correction normally.
f.movement(WHEEL, -10);
f.frame(1_300_000);
assert.ok(f.camera.views.length > writes);
f.dispose();
});
// A real Cesium camera and controller, fed by DOM wheel events on the canvas.
function realControllerScene(startHeight) {
const canvas = Object.assign(new EventTarget(), {
clientWidth: 1200,
clientHeight: 800,
width: 1200,
height: 800,
style: {},
// Keep Cesium's input handler off the missing `document`.
disableRootEvents: true,
onwheel: null,
getBoundingClientRect: () => ({
left: 0,
top: 0,
width: 1200,
height: 800,
}),
});
const scene = {
canvas,
drawingBufferWidth: 1200,
drawingBufferHeight: 800,
mapProjection: new Cesium.GeographicProjection(),
ellipsoid: Cesium.Ellipsoid.WGS84,
mapMode2D: Cesium.MapMode2D.INFINITE_SCROLL,
mode: Cesium.SceneMode.SCENE3D,
pixelRatio: 1,
verticalExaggeration: 1,
verticalExaggerationRelativeHeight: 0,
preRender: new Cesium.Event(),
postUpdate: new Cesium.Event(),
};
const camera = new Cesium.Camera(scene);
scene.camera = camera;
const controller = new Cesium.ScreenSpaceCameraController(scene);
controller.inertiaZoom = 0;
scene.screenSpaceCameraController = controller;
const setHeight = (h) =>
camera.setView({
destination: Cesium.Cartesian3.fromDegrees(28.9784, 41.0082, h),
orientation: { heading: 0, pitch: -Cesium.Math.PI_OVER_TWO, roll: 0 },
});
setHeight(startHeight);
const dispose = installZoomOutGuard(
{ scene, camera, canvas },
{ requestRender() {} },
);
// Scene.render order: the controller applies input, then postUpdate, then
// preRender on frames that draw.
const frame = () => {
controller.update();
scene.postUpdate.raiseEvent(scene);
scene.preRender.raiseEvent(scene);
};
const wheel = (deltaY) =>
canvas.dispatchEvent(
Object.assign(new Event('wheel'), {
deltaY,
deltaMode: 0,
clientX: 600,
clientY: 400,
}),
);
const height = () => camera.positionCartographic.height;
return {
scene,
camera,
controller,
setHeight,
frame,
wheel,
height,
dispose,
};
}
test('a camera placed above the ceiling cannot zoom out and zooms in without a jump', () => {
const s = realControllerScene(60_000_000);
try {
s.frame();
s.wheel(1);
s.frame();
assert.ok(Math.abs(s.height() - 60_000_000) < 1, `${s.height()} m`);
s.wheel(-1);
s.frame();
const firstStep = s.height();
assert.ok(firstStep < 60_000_000, 'zooms in');
assert.ok(firstStep > 50_000_000, `${firstStep} m is gradual`);
// The camera can no longer climb back above where it has descended to.
s.wheel(1);
s.frame();
assert.ok(Math.abs(s.height() - firstStep) < 1, `${s.height()} m`);
for (let i = 0; i < 40; i++) {
s.wheel(-100);
s.frame();
}
assert.ok(s.height() < MAXIMUM_ZOOM_DISTANCE_M);
assert.equal(s.controller.maximumZoomDistance, MAXIMUM_ZOOM_DISTANCE_M);
for (let i = 0; i < 80; i++) {
s.wheel(100);
s.frame();
}
assert.ok(Math.abs(s.height() - MAXIMUM_ZOOM_DISTANCE_M) < 1_000);
} finally {
s.dispose();
}
assert.equal(s.controller.maximumZoomDistance, Infinity);
});
test('a share-link view restored above the ceiling is honoured by later frames', () => {
const s = realControllerScene(1_000_000);
try {
s.frame();
s.setHeight(97_679_259);
s.frame();
s.wheel(100);
s.frame();
assert.ok(Math.abs(s.height() - 97_679_259) < 1, `${s.height()} m`);
} finally {
s.dispose();
}
});
test('a tracked camera cannot climb past the ceiling from its target', () => {
const s = realControllerScene(1_000_000);
try {
s.frame();
// In look-at mode Cesium measures zoom from the target, not the Earth.
s.camera.lookAt(
Cesium.Cartesian3.fromDegrees(0, 0, 35_786_000),
new Cesium.HeadingPitchRange(0, -0.5, 5_000_000),
);
for (let i = 0; i < 20; i++) {
s.wheel(100);
s.frame();
}
const range = Cesium.Cartesian3.magnitude(s.camera.position);
assert.ok(range <= MAXIMUM_ZOOM_DISTANCE_M + 1_000, `${range} m`);
assert.equal(s.controller.maximumZoomDistance, MAXIMUM_ZOOM_DISTANCE_M);
} finally {
s.dispose();
}
});