The renderer seam: clicks go to the newest tool, recession and display groups through the contract, drawing at parity with Cesium

- Clicks: when two tools want the globe's clicks, the newest takes them and the older is told and turns itself off; a click is decided when it arrives, and ambient selection fires only when no tool holds the pointer. The "map is busy" paths and their strings are removed.
- Recession: the limb fade is shared (src/render/recession.js) and reaches icon and model sets through SetSpec.recede; tuning applies on the next frame.
- Display panel groups are published through src/ui/displayGroups.js; the Weather group and src/viewWeather.js are removed.
- Draw port: a set whose icons only move is moved in place, and models that did not change are not restyled each frame, so moving fleets cost what they did when drawn directly; an untinted, fully opaque model is drawn without a colour.
- Conformance: input.lease.lost checks the new lease inside onLost and reports a throwing onLost; draw.sets.recede covers model sets.
- QA scripts read the renderer host instead of internals the seam replaced.
This commit is contained in:
Sameh Khamis committed 2026-11-15 17:03:09 -08:00
1 parent a0d299523d
commit 0ab31d4fb8
130 files changed
+5438 -1674

No files matched your search

+26 -25
View File
@@ -56,7 +56,10 @@ function sameView(a, b) {
* report: (error: unknown) => void, thresholds?: boolean}} options `pose`
* is read only while a `changed` listener is registered; `world` (the
* eye in world coordinates; `pose()` when omitted) is read by
* `stepMoveDetection`; `thresholds`
* `stepMoveDetection`, which keeps what it returns: a view it is handed
* again is the same eye, and a view is never changed once handed (a new
* eye is a new object); `pose` and `world` results are read, never
* changed; `thresholds`
* false (a renderer without `cameraChangeThreshold`) ignores a listener's
* own threshold, so every listener fires at 0.5.
*/
@@ -66,8 +69,10 @@ export function createCameraEvents({
report,
thresholds = true,
}) {
// Lists are copied on change, not on delivery: a delivery runs over the
// list as it stood, and a change made during it makes a new one.
const listeners = Object.fromEntries(CAMERA_EVENTS.map((e) => [e, []]));
const commandHooks = [];
let commandHooks = [];
let lastView = null;
let moving = false;
let lastMovedAt = 0;
@@ -82,7 +87,7 @@ export function createCameraEvents({
}
function emit(event) {
for (const entry of listeners[event].slice()) deliver(entry);
for (const entry of listeners[event]) deliver(entry);
}
/**
@@ -92,15 +97,14 @@ export function createCameraEvents({
* @returns {() => void}
*/
function on(event, cb, options = {}) {
const list = listeners[event];
if (!list) throw new Error(`Unknown camera event: ${event}`);
if (!listeners[event]) throw new Error(`Unknown camera event: ${event}`);
const threshold = thresholds ? (options.threshold ?? 0.5) : 0.5;
const entry = { cb, live: true, threshold };
list.push(entry);
listeners[event] = [...listeners[event], entry];
return () => {
if (!entry.live) return;
entry.live = false;
const i = list.indexOf(entry);
if (i >= 0) list.splice(i, 1);
listeners[event] = listeners[event].filter((e) => e !== entry);
};
}
@@ -113,7 +117,7 @@ export function createCameraEvents({
const list = listeners.changed;
if (!list.length) return;
const current = pose();
for (const entry of list.slice()) {
for (const entry of list) {
if (!entry.live) continue;
const t = entry.threshold;
entry.heading ??= current.heading;
@@ -152,14 +156,11 @@ export function createCameraEvents({
* @param {number} now
*/
function stepMoveDetection(now) {
const v = world();
const current = {
position: v.position,
direction: v.direction,
up: v.up,
lens: v.lens,
};
const changed = lastView && !sameView(lastView, current);
// `world` hands its last view again while the eye stands: that one is
// unchanged without comparing.
const current = world();
const changed =
lastView !== null && current !== lastView && !sameView(lastView, current);
lastView = current;
if (changed) {
lastMovedAt = now;
@@ -178,7 +179,7 @@ export function createCameraEvents({
* @param {import('../contract/camera').CameraCommand['kind']} kind
*/
function command(kind) {
for (const entry of commandHooks.slice()) {
for (const entry of commandHooks) {
if (!entry.live) continue;
try {
entry.cb({ kind });
@@ -196,22 +197,22 @@ export function createCameraEvents({
*/
function onCommand(cb) {
const entry = { cb, live: true };
commandHooks.push(entry);
commandHooks = [...commandHooks, entry];
return () => {
if (!entry.live) return;
entry.live = false;
const i = commandHooks.indexOf(entry);
if (i >= 0) commandHooks.splice(i, 1);
commandHooks = commandHooks.filter((e) => e !== entry);
};
}
/** Drop every listener and hook, including those of an event under way. */
function clear() {
for (const list of Object.values(listeners)) {
for (const entry of list) entry.live = false;
list.length = 0;
for (const event of CAMERA_EVENTS) {
for (const entry of listeners[event]) entry.live = false;
listeners[event] = [];
}
for (const entry of commandHooks) entry.live = false;
commandHooks.length = 0;
commandHooks = [];
}
return {
+20 -1
View File
@@ -23,6 +23,7 @@
* `cesiumViewerOf` (`viewers.js`), never through a renderer member, so no
* engine type crosses the contract.
*/
import * as Cesium from 'cesium';
import { createApplicationViewer } from './applicationViewer.js';
import { CONTRACT_VERSION } from '../contract/index.js';
import { bindRenderer } from '../rendererOf.js';
@@ -80,7 +81,13 @@ export function createCesiumRendererPlugin({
id: 'cesium',
/**
* The credentials are the globe port's, for a base set through it; the
* scene still loads the application's own base itself.
* scene still loads the application's own base itself. `msaa` makes
* the viewer (4 when not given);
* `sky` and `time` are set before the first frame; `clock.now` is what
* the frame ticks, the camera's `moveEnd` wait, input and flights (the
* scene's tweens step on it) read, `clock.date` what a `live` motion
* clock reads. Inertia keeps Cesium's own timing: its camera controls
* time a release by the system clock.
* @param {import('../contract/renderer').CreateOptions} options
* @returns {Promise<TransitionalRenderer>}
*/
@@ -90,6 +97,10 @@ export function createCesiumRendererPlugin({
googleApiKey,
googleTokens,
worldDataToken,
msaa,
sky,
time,
clock,
}) {
signal?.throwIfAborted();
// Provider attribution stays visible, including clean-view and recording.
@@ -109,7 +120,11 @@ export function createCesiumRendererPlugin({
// The application's notice (`renderFailureNotice`) replaces
// Cesium's dead-end panel when rendering stops.
showRenderLoopErrors: false,
msaa,
});
if (Number.isFinite(time))
viewer.clock.currentTime = Cesium.JulianDate.fromDate(new Date(time));
const now = clock ? () => clock.now() : undefined;
capabilities = new ReadonlySet(cesiumCapabilities(viewer.scene));
ports = createCesiumPorts(viewer, {
capabilities,
@@ -117,6 +132,7 @@ export function createCesiumRendererPlugin({
idleFps: IDLE_FRAME_RATE,
credentials: { googleApiKey, googleTokens, worldDataToken },
...(cameraController ? { cameraController } : {}),
...(clock ? { now, date: () => clock.date() } : {}),
});
input = createCesiumInput(viewer, {
query: ports.query,
@@ -124,7 +140,10 @@ export function createCesiumRendererPlugin({
...(ports.suspendCamera
? { suspendCamera: ports.suspendCamera }
: {}),
...(clock ? { now } : {}),
});
// Before the first frame, so nothing draws in the wrong sky.
if (sky) ports.globe.sky.set(sky);
ports.attachInput?.(input.port);
// Free look is limited to low heights from the start, on Cesium's
// own controls (the controller keeps its own limits).
+62 -3
View File
@@ -193,7 +193,7 @@ test('the application’s loop ticks at the idle rate while nothing moves, and a
renderer.destroy();
});
test('work pending at destroy settles and lets go of the scene', async (t) => {
test('work pending at destroy is rejected and lets go of the scene', async (t) => {
withDocument(t, fakeDocument());
const viewers = [];
const plugin = createCesiumRendererPlugin({
@@ -207,9 +207,10 @@ test('work pending at destroy settles and lets go of the scene', async (t) => {
const renderer = await plugin.create({ container: {} });
const rendered = renderer.frame.renderOnce();
renderer.destroy();
await rendered;
await assert.rejects(rendered, /renderer destroyed/, 'the one waiting');
assert.equal(viewers[0].listeners.size, 0, 'no one-shot render stays');
await renderer.frame.renderOnce();
await assert.rejects(renderer.frame.renderOnce(), /renderer destroyed/);
await assert.rejects(renderer.capture(), /renderer destroyed/);
const waiting = await plugin.create({ container: {} });
const standing = viewers[1].listeners.size;
@@ -325,3 +326,61 @@ test('only renderers this plugin made reach a Cesium viewer', () => {
});
const EXPECTED_MISSING = [];
test('the plugin makes its viewer with the creation options, and sets the sky, time and clock before the first frame', async (t) => {
const doc = fakeDocument();
withDocument(t, doc);
const log = [];
let given;
let viewer;
const plugin = createCesiumRendererPlugin({
createViewer(options) {
given = options;
viewer = fakeViewer(log);
for (const phase of [
'preUpdate',
'postUpdate',
'preRender',
'postRender',
])
viewer.scene[phase] = new Cesium.Event();
viewer.scene.skyAtmosphere = { show: true };
viewer.scene.fog = { enabled: true };
viewer.clock = { currentTime: Cesium.JulianDate.now() };
return viewer;
},
});
const time = Date.UTC(2030, 5, 21, 12);
const clock = { now: () => 1234.5, date: () => time + 60_000 };
const renderer = await plugin.create({
container: { tag: 'container' },
signal: new AbortController().signal,
msaa: 2,
sky: { atmosphere: false, fog: false },
time,
clock,
});
assert.equal(given.msaa, 2, 'multisampling');
assert.equal(viewer.scene.skyAtmosphere.show, false, 'the sky, set');
assert.equal(viewer.scene.fog.enabled, false);
assert.equal(renderer.globe.sky.get().fog, false);
assert.equal(
Cesium.JulianDate.toDate(viewer.clock.currentTime).getTime(),
time,
'the scene time',
);
const ticks = [];
renderer.frame.on('preUpdate', (tick) => ticks.push(tick.now));
viewer.scene.preUpdate.raiseEvent(viewer.scene, viewer.clock.currentTime);
assert.deepEqual(ticks, [1234.5], 'ticks read the clock given');
renderer.destroy();
// Not given, the viewer is made as it always was.
await plugin
.create({
container: { tag: 'container' },
signal: new AbortController().signal,
})
.then((r) => r.destroy());
assert.equal(given.msaa, undefined);
});
+15 -5
View File
@@ -54,11 +54,13 @@ if (typeof window !== 'undefined' && !window.__CESIUM__)
/**
* Cesium.Viewer options of the standard globe viewer. `showRenderLoopErrors`
* false leaves render errors to the caller's own notice instead of Cesium's
* panel.
* panel; `msaa` is the multisampling to start with (0 off, 4 by default).
* The drawing buffer is kept after presenting, for `capture` and
* `readPixels` to read the frame drawn.
*/
export function applicationViewerOptions(
creditContainer,
{ showRenderLoopErrors = true } = {},
{ showRenderLoopErrors = true, msaa = 4 } = {},
) {
return {
timeline: false,
@@ -77,23 +79,31 @@ export function applicationViewerOptions(
// which would also stop CesiumWidget from creating the Sun and Moon.
skyBox: new StarrySky(),
creditContainer,
msaaSamples: 4,
// Cesium's 1 is no multisampling.
msaaSamples: msaa || 1,
contextOptions: { webgl: { preserveDrawingBuffer: true } },
showRenderLoopErrors,
};
}
/** Create the standard globe viewer in caller-owned, visible containers. */
/**
* Create the standard globe viewer in caller-owned, visible containers;
* `msaa` as `applicationViewerOptions` takes it.
*/
export function createApplicationViewer({
container,
creditContainer,
showRenderLoopErrors,
msaa,
}) {
if (!container || !creditContainer)
throw new TypeError('Viewer and credit containers are required');
const viewer = new Cesium.Viewer(
container,
applicationViewerOptions(creditContainer, { showRenderLoopErrors }),
applicationViewerOptions(creditContainer, {
showRenderLoopErrors,
msaa,
}),
);
try {
// Until the frame port takes over (appRenderer.js), tick at the idle
@@ -74,3 +74,15 @@ test('flat maps keep zooming out unlimited', () => {
viewer.scene.preRender.raiseEvent();
assert.equal(controller.maximumZoomDistance, Infinity);
});
test('the viewer options take multisampling, by default 4, and keep the drawing buffer', async () => {
const { applicationViewerOptions } = await import('./applicationViewer.js');
const credits = {};
const plain = applicationViewerOptions(credits);
assert.equal(plain.msaaSamples, 4);
assert.equal(plain.contextOptions.webgl.preserveDrawingBuffer, true);
const given = applicationViewerOptions(credits, { msaa: 0 });
assert.equal(given.msaaSamples, 1, 'Cesium’s 1 is off');
assert.equal(given.contextOptions.webgl.preserveDrawingBuffer, true);
assert.equal(applicationViewerOptions(credits, { msaa: 8 }).msaaSamples, 8);
});
+130 -44
View File
@@ -79,20 +79,31 @@ function matrixArray(matrix) {
return out;
}
/** Whether `array` holds a Cesium matrix's 16 values, each the same. */
function sameMatrix(array, matrix) {
for (let i = 0; i < 16; i++)
if (!Object.is(array[i], matrix[i])) return false;
return true;
}
/**
* @param {{scene: object, camera: object, report: (error: unknown) => void,
* widget?: object, capabilities?: ReadonlySet<string>,
* now?: () => number, itemPosition?: Function}} options `scene`
* gives `requestRender` and the `postUpdate` tick `changed` is measured
* on; `widget`, the Viewer or CesiumWidget, gives the entity tracking
* gives `requestRender`, the `preUpdate` a frame drawn without the
* clock's tick measures `changed` at, and the `postUpdate` move detection
* runs on; `widget`, the Viewer or CesiumWidget, gives the entity tracking
* `follow` runs on (without it the camera cannot follow);
* `capabilities`, the renderer's, gates the optional members (a camera
* with none given has them all); `now`, the clock moveEnd waits by,
* ms (`performance.now` by default); `itemPosition`, where the draw port
* draws an item at a scene time, which a follow of a drawn item tracks.
* @returns {{port: import('../contract/camera').CameraPort,
* emit: (event: string) => void, dispose: () => void}} `emit` raises
* one of the port's events (a test's fake camera that raises its own).
* measureChanged: () => void, emit: (event: string) => void,
* dispose: () => void}} `measureChanged` measures this frame's `changed`
* if nothing has yet, for a frame loop to run before its own `preUpdate`
* listeners; `emit` raises one of the port's events (a test's fake camera
* that raises its own).
*/
export function createCesiumCamera({
scene,
@@ -105,42 +116,92 @@ export function createCesiumCamera({
}) {
const removers = [];
let lastWorld = null;
let lastMatrices = null;
let lastFollowFrame = null;
// Camera events, measured on every tick: moveStart and moveEnd (500 ms
// after the last change of the eye or its field of view, by `now`,
// following or not, as Cesium's own), and `changed` per listener, where Cesium measures its
// single threshold (`camera.percentageChanged`, which this leaves as it
// is for everyone else listening to Cesium's own event). Cesium's own
// moveStart and moveEnd are left out: it times them by the system clock.
// What the events read Cesium's camera through while it stands: the
// camera's own vectors, compared in place.
const eye = { position: null, direction: null, up: null };
const cameraEvents = createCameraEvents({
pose: () => cameraPort.pose(),
// The memoised pose itself: the events only read it.
pose: () => sharedPose(),
world: () => {
// Copies (Cesium updates its own vectors in place), and the last one
// again while Cesium's stand within rounding of it.
// The last view again while Cesium's vectors stand within rounding of
// it; copies once they move (Cesium updates its own in place).
const f = camera.frustum;
const current = {
position: Cesium.Cartesian3.clone(camera.positionWC),
direction: Cesium.Cartesian3.clone(camera.directionWC),
up: Cesium.Cartesian3.clone(camera.upWC),
eye.position = camera.positionWC;
eye.direction = camera.directionWC;
eye.up = camera.upWC;
if (
lastWorld &&
// A new field of view or aspect (a resize) is a move too, as
// Cesium's own camera events count it.
Object.is(lastWorld.fovy, f.fovy) &&
Object.is(lastWorld.aspectRatio, f.aspectRatio) &&
sameEye(eye, lastWorld)
)
return lastWorld;
lastWorld = {
position: Cesium.Cartesian3.clone(eye.position),
direction: Cesium.Cartesian3.clone(eye.direction),
up: Cesium.Cartesian3.clone(eye.up),
fovy: f.fovy,
aspectRatio: f.aspectRatio,
lens: `${f.fovy} ${f.aspectRatio}`,
};
if (
!lastWorld ||
current.lens !== lastWorld.lens ||
!sameEye(current, lastWorld)
)
lastWorld = current;
return lastWorld;
},
report,
thresholds: capabilities?.has('cameraChangeThreshold') ?? true,
});
// `changed` is measured once a frame where the contract's frame order
// puts it: after the flight and input (Cesium's `initializeFrame`), before
// follow and `preUpdate` move the camera. Cesium moves a followed target's
// camera in its clock's tick, so a frame of the loop is measured as that
// tick starts; a frame drawn with no tick (a forced render), as
// `preUpdate` starts. Move detection runs after `preUpdate`.
let measured = false;
const measureChanged = () => {
if (measured) return;
measured = true;
applyFov();
cameraEvents.stepChanged();
};
const clock = widget?.clock;
if (typeof clock?.tick === 'function') {
const ownTick = clock.tick;
let wrapping = true;
const tick = function (...args) {
if (wrapping) {
measured = false;
measureChanged();
}
return ownTick.apply(this, args);
};
clock.tick = tick;
// Disposed, the clock gets its own tick back; if something has wrapped
// it since, that wrapper stays and this part of it only passes through.
removers.push(() => {
wrapping = false;
if (clock.tick !== tick) return;
if (Object.getPrototypeOf(clock)?.tick === ownTick) delete clock.tick;
else clock.tick = ownTick;
});
}
const offPreUpdate = scene.preUpdate?.addEventListener(measureChanged);
if (offPreUpdate) removers.push(offPreUpdate);
removers.push(
scene.postUpdate.addEventListener(() => {
applyFov();
cameraEvents.stepChanged();
// Measured already, unless the scene has no `preUpdate`.
measureChanged();
cameraEvents.stepMoveDetection(now());
measured = false;
}),
);
@@ -413,10 +474,19 @@ export function createCesiumCamera({
// The scene's own frame: ECEF in 3D, the only mode the app runs (Cesium's
// 2D and Columbus view frames are projected map coordinates).
matrices() {
return {
view: matrixArray(camera.viewMatrix),
projection: matrixArray(camera.frustum.projectionMatrix),
};
// The last ones again while Cesium's stand, new ones once they move.
const view = camera.viewMatrix;
const projection = camera.frustum.projectionMatrix;
if (
!lastMatrices ||
!sameMatrix(lastMatrices.view, view) ||
!sameMatrix(lastMatrices.projection, projection)
)
lastMatrices = {
view: matrixArray(view),
projection: matrixArray(projection),
};
return lastMatrices;
},
// Cesium's own corner picks (`computeViewRectangle`), on rays that
// keep their precision (`pickRayAt`).
@@ -442,18 +512,24 @@ export function createCesiumCamera({
);
},
pose() {
// An unmoved camera answers from the pose last read: a frame reads
// the pose many times over. Each caller gets objects of its own.
if (!poseKeyHolds() || !poseMemo) {
poseMemo = readPose();
// Outside 3D, Cesium measures heading, pitch and roll by moving the
// camera into the eye's frame and back, which can change its last
// bits: keyed as it is left.
if (scene.mode !== Cesium.SceneMode.SCENE3D) poseKeyHolds();
}
return copyPose(poseMemo);
// Each caller gets objects of its own.
return copyPose(sharedPose());
},
};
/**
* The pose, read again only when the camera has moved: a frame reads the
* pose many times over. Shared: never changed once read.
*/
function sharedPose() {
if (!poseKeyHolds() || !poseMemo) {
poseMemo = readPose();
// Outside 3D, Cesium measures heading, pitch and roll by moving the
// camera into the eye's frame and back, which can change its last
// bits: keyed as it is left.
if (scene.mode !== Cesium.SceneMode.SCENE3D) poseKeyHolds();
}
return poseMemo;
}
// The camera as the memoised pose was read: eye, axes, transform,
// frustum and mode, compared value for value.
const poseKey = new Float64Array(37);
@@ -469,15 +545,8 @@ export function createCesiumCamera({
const r = camera.rightWC;
const f = camera.frustum;
const t = camera.transform;
let same = true;
let at = 0;
const put = (value) => {
if (!Object.is(poseKey[at], value)) {
same = false;
poseKey[at] = value;
}
at += 1;
};
keySame = true;
keyAt = 0;
put(p.x);
put(p.y);
put(p.z);
@@ -502,7 +571,17 @@ export function createCesiumCamera({
put(f.bottom ?? NaN);
put(scene.mode ?? NaN);
for (let i = 0; i < 16; i++) put(t[i]);
return same;
return keySame;
}
// Where `poseKeyHolds` writes next, and whether all it wrote held.
let keyAt = 0;
let keySame = true;
function put(value) {
if (!Object.is(poseKey[keyAt], value)) {
keySame = false;
poseKey[keyAt] = value;
}
keyAt += 1;
}
const enuScratch = new Cesium.Matrix4();
/**
@@ -591,10 +670,15 @@ export function createCesiumCamera({
// Cesium keeps the eye in `camera.transform`: a tracked entity's frame, a
// `lookAt` target's, or the identity.
if (!capabilities || capabilities.has('followFrame'))
cameraPort.followFrame = () => matrixArray(camera.transform);
cameraPort.followFrame = () => {
if (!lastFollowFrame || !sameMatrix(lastFollowFrame, camera.transform))
lastFollowFrame = matrixArray(camera.transform);
return lastFollowFrame;
};
return {
port: cameraPort,
measureChanged,
emit: (event) => cameraEvents.emit(event),
dispose() {
following?.dispose();
@@ -607,7 +691,9 @@ export function createCesiumCamera({
}
// A Cesium viewer with no renderer bound to it gets a
// camera port over its camera when code first asks `cameraOf` for one.
// camera port over its camera when code first asks `cameraOf` for one. The
// port wraps the viewer's `clock.tick` to measure `changed`, and gives it
// back when a renderer is bound to the viewer.
provideUnboundCamera((viewer) =>
// By shape, not `instanceof`: the viewer may come from another
// copy of Cesium.
+51 -1
View File
@@ -21,7 +21,7 @@ import {
} from './cameraGoldens.js';
import { createCesiumCamera } from './camera.js';
import { createCesiumPorts } from './ports.js';
import { cameraOf } from '../rendererOf.js';
import { bindRenderer, cameraOf } from '../rendererOf.js';
/** Records the headless scene cannot answer: they need the query port. */
const QUERY_RECORDS = new Set([
@@ -78,6 +78,7 @@ function headlessHarness(clock, { input = false } = {}) {
clock.now += FRAME_MS;
scene.tweens.update();
if (input) scene.screenSpaceCameraController.update();
scene.preUpdate.raiseEvent(scene);
scene.postUpdate.raiseEvent(scene);
},
scene,
@@ -287,6 +288,55 @@ test('a Cesium viewer with no renderer bound gets a camera port over its own cam
});
});
test('the camera port gives the clock its own tick back as it goes', () => {
const ownTick = Cesium.Clock.prototype.tick;
// A viewer with no renderer bound: its port goes when a renderer is bound.
{
const { scene, camera } = headlessCamera();
scene.postUpdate = new Cesium.Event();
scene.requestRender = () => {};
const viewer = { scene, camera, clock: new Cesium.Clock() };
cameraOf(viewer);
assert.notEqual(viewer.clock.tick, ownTick, 'measured as the tick starts');
bindRenderer(viewer, {});
assert.equal(viewer.clock.tick, ownTick, 'its own tick once unbound');
assert.equal(Object.hasOwn(viewer.clock, 'tick'), false);
}
// Wrapped again after the port: disposing leaves the later wrapper, and
// the port's own part of the tick measures nothing more.
{
const { scene, camera } = headlessCamera();
scene.postUpdate = new Cesium.Event();
scene.requestRender = () => {};
const clock = new Cesium.Clock();
const part = createCesiumCamera({
scene,
camera,
report: () => {},
widget: { clock },
});
const wrapped = clock.tick;
let later = 0;
clock.tick = function (...args) {
later += 1;
return wrapped.apply(this, args);
};
part.dispose();
let reads = 0;
const frustum = camera.frustum;
Object.defineProperty(camera, 'frustum', {
get: () => {
reads += 1;
return frustum;
},
configurable: true,
});
clock.tick();
assert.equal(later, 1, 'the later wrapper still runs');
assert.equal(reads, 0, 'the disposed port reads nothing');
}
});
test('setFov holds the vertical angle across resizes, and waits for a first one', () => {
const { scene, camera } = headlessCamera();
scene.postUpdate = new Cesium.Event();
+8 -6
View File
@@ -14,22 +14,24 @@ import * as Cesium from 'cesium';
* @param {(error: unknown) => void} onThrow
*/
export function listenerList(onThrow) {
const entries = [];
// Copied on change, not on delivery: a delivery runs over the list as it
// stood, and a change made during it makes a new one.
let entries = [];
return {
get size() {
return entries.length;
},
on(cb) {
const entry = { cb, live: true };
entries.push(entry);
entries = [...entries, entry];
return () => {
if (!entry.live) return;
entry.live = false;
const i = entries.indexOf(entry);
if (i >= 0) entries.splice(i, 1);
entries = entries.filter((e) => e !== entry);
};
},
fire(...args) {
for (const entry of entries.slice()) {
for (const entry of entries) {
if (!entry.live) continue;
try {
entry.cb(...args);
@@ -40,7 +42,7 @@ export function listenerList(onThrow) {
},
clear() {
for (const entry of entries) entry.live = false;
entries.length = 0;
entries = [];
},
};
}
+1 -1
View File
@@ -61,7 +61,7 @@ const plain = (v) => ({ x: v.x, y: v.y, z: v.z });
/**
* @param {{
* scene: object,
* controller: Function,
* controller: import('../contract/camera').CameraControllerFactory,
* query: {pickPosition?: Function, sampleHeightNow?: Function},
* itemPosition?: (item: {set: string, id: string|number}, aheadMs?: number) => object|null,
* requestRender: (reason: string) => void,
+21 -18
View File
@@ -207,23 +207,8 @@ export function createCesiumCredits({ display, scene, report, requestRender }) {
const { statics, screen, lightbox, logo } = creditDisplayContents(
displayLive() ? display : undefined,
);
let same = true;
let at = 0;
const put = (value) => {
if (!Object.is(lastInputs[at], value)) {
same = false;
lastInputs[at] = value;
}
at += 1;
};
const putElements = (elements) => {
put(elements.length);
for (const element of elements) {
put(element.credit);
put(element.count);
put(element.credit?.showOnScreen);
}
};
inputsSame = true;
inputAt = 0;
put(coreVersion);
put(logo);
put(logo?.showOnScreen);
@@ -234,7 +219,25 @@ export function createCesiumCredits({ display, scene, report, requestRender }) {
}
putElements(screen);
putElements(lightbox);
return same;
return inputsSame;
}
// Where `inputsHeld` writes next, and whether all it wrote held.
let inputAt = 0;
let inputsSame = true;
function put(value) {
if (!Object.is(lastInputs[inputAt], value)) {
inputsSame = false;
lastInputs[inputAt] = value;
}
inputAt += 1;
}
function putElements(elements) {
put(elements.length);
for (const element of elements) {
put(element.credit);
put(element.count);
put(element.credit?.showOnScreen);
}
}
inputsHeld();
+158 -47
View File
@@ -24,7 +24,7 @@
* settle into static batches that cost nothing until they change, and a
* line that moves again goes back to the collection (`settleLines`).
*
* Icon sets whose items move, glide, recede, pick by proxy or switch images
* Icon sets that recede, or whose items move, glide, pick by proxy or switch images
* by size, or that take columns, draw on the GPU instead (`gpuIcons.js`).
*
* Built over a scene by `createCesiumPorts`, and on its own over a Cesium
@@ -441,6 +441,9 @@ const ICONS_KEPT = 'kept';
const POINTS_ADDED = 'added';
const POINTS_KEPT = 'kept';
/** Whether a set's GPU icons move on in the frames that follow. */
const animating = (record) => record.gpu?.animating();
/**
* The draw port over `scene`, and what the other ports read of it: the live
* sets by id, a version that changes with what height queries see through
@@ -448,17 +451,20 @@ const POINTS_KEPT = 'kept';
* the clamp-state watch the frame loop runs after each draw.
* @param {{scene: object, report: (error: unknown) => void,
* capabilities?: ReadonlySet<string>,
* requestRender?: (reason: string) => void}} options `capabilities` gate
* requestRender?: (reason: string) => void,
* date?: () => number}} options `capabilities` gate
* the GPU icon sets' members (by default they all are); `requestRender`,
* the frame port's, asks for the frames a GPU icon set needs on its own
* (its images packed), under the reason `icons:<set id>` (by default the
* scene's, with no reason).
* scene's, with no reason); `date`, the epoch ms a `live` motion clock
* reads (by default the system clock's).
*/
export function createCesiumDraw({
scene,
report,
capabilities = new Set(GPU_ICON_CAPABILITIES),
requestRender: requestFrame = null,
date = null,
}) {
const sets = new Map();
// Fields share the sets' ids.
@@ -481,6 +487,15 @@ export function createCesiumDraw({
const requestRender = () => {
if (live()) scene.requestRender();
};
// Once the port is disposed (its renderer destroyed), every set does
// nothing, and so does a set asked for after that.
let portDisposed = false;
/** A disposed set's listeners hear nothing more, even mid-delivery. */
function silence(record) {
record.listeners.ready.clear();
record.listeners.loadFailed.clear();
}
function makeSet(kind, spec, build) {
if (sets.has(spec.id) || fieldPart.has(spec.id))
@@ -569,6 +584,9 @@ export function createCesiumDraw({
record.gpu.write(list);
return patched();
}
// Icons drawn already, with the images they are drawn with, each
// changed where it is.
if (patchDrawnIcons(record, list)) return iconsPatched(ICONS_KEPT);
// Points restyled, moved or added keep the pick ids they had, so
// only points added change what height queries see through.
const points = patchPoints(record, list);
@@ -578,13 +596,22 @@ export function createCesiumDraw({
requestRender();
return;
}
// Models are changed where they are; moved or restyled they keep
// their pick ids, so only models added change what height queries
// see through.
if (kind === 'models') {
const added = modelSets.upsert(record, list);
for (const item of list) items.set(item.id, item);
if (added) setsVersion += 1;
requestRender();
return;
}
// Lines that only change how they show or where an undraped one
// runs, and clamped shapes that only show or hide, or a few colour
// fills that only move (`moveShape`), are changed where they are.
if (
patchLines(record, list) ||
patchShapes(record, list) ||
(kind === 'models' && modelSets.upsert(record, list)) ||
(kind === 'quads' && quadSets.upsert(record, list)) ||
(kind === 'meshes' && meshSets.upsert(record, list))
) {
@@ -639,8 +666,12 @@ export function createCesiumDraw({
requestRender();
return;
}
// Refused, changing nothing, where icons on the GPU cannot take it.
// Refused, changing nothing, where icons on the GPU cannot take it
// (all of them, for billboards told to recede, which go onto it).
const toGpu =
kind === 'icons' && !record.gpu && Boolean(options.recede);
if (record.gpu) gpu.check([], { ...spec, ...options });
else if (toGpu) gpu.check(items.values(), { ...spec, ...options });
const culled = spec.horizonCull;
const clampTo = spec.clampTo;
const blend = spec.blend;
@@ -666,6 +697,10 @@ export function createCesiumDraw({
// A set that stops picking lets its old ground go now: still drawn
// while the new builds, it would keep hiding the ground from picks.
if (pickable && spec.pickable === false) retire(record);
if (toGpu) {
onGpu(record, [], true, true);
record.gpu.sync();
}
record.gpu?.restyle();
if (kind === 'models') modelSets.restyle(record);
setsVersion += 1;
@@ -784,6 +819,42 @@ export function createCesiumDraw({
handle.upsert([...record.inertialDraped.values()]);
};
}
// A disposed set does nothing on later calls: one would draw what
// nothing removes.
record.disposed = portDisposed;
for (const name of [
'set',
'upsert',
'remove',
'clear',
'setOptions',
'setColumns',
]) {
const call = handle[name];
if (!call) continue;
handle[name] = (...args) => {
if (!record.disposed) return call(...args);
};
}
const { set: showSet } = Object.getOwnPropertyDescriptor(handle, 'show');
Object.defineProperty(handle, 'show', {
get: () => spec.show !== false,
set(value) {
if (!record.disposed) showSet.call(handle, value);
},
enumerable: true,
});
const on = handle.on;
handle.on = (event, cb) => (record.disposed ? () => {} : on(event, cb));
const disposeOnce = handle.dispose;
handle.dispose = () => {
if (record.disposed) return;
record.disposed = true;
// A listener that disposes the set stops the rest of that delivery.
silence(record);
disposeOnce();
};
if (record.disposed) return handle;
sets.set(spec.id, record);
setsVersion += 1;
return handle;
@@ -792,6 +863,7 @@ export function createCesiumDraw({
const gpu = createGpuIcons({
scene,
capabilities,
date,
toColor,
imageOf: (record, image) => iconImage(record, image),
peekImage: (image) => atlases.get(image.atlas)?.[image.slot],
@@ -811,7 +883,7 @@ export function createCesiumDraw({
*/
function onGpu(record, list, replacing = false, force = false) {
if (record.kind !== 'icons') return false;
if (!record.gpu && !force && !gpu.wants(list)) return false;
if (!record.gpu && !force && !gpu.wants(list, record.spec)) return false;
gpu.check(list, record.spec);
if (record.gpu) return true;
if (!replacing) gpu.check(record.items.values(), record.spec);
@@ -1073,11 +1145,6 @@ export function createCesiumDraw({
*/
function clusterIcons(frameState = scene.frameState) {
let pose;
const poseNow = () => {
const eye = scene.camera?.positionWC;
const dir = scene.camera?.directionWC;
return `${eye?.x},${eye?.y},${eye?.z},${dir?.x},${dir?.y},${dir?.z},${scene.canvas?.clientWidth},${scene.canvas?.clientHeight}`;
};
for (const record of sets.values()) {
if (!clusters(record)) {
if (record.clusterHost || record.clusterState) {
@@ -1095,21 +1162,54 @@ export function createCesiumDraw({
record.clusterKey = null;
record.clusteredHost = host;
}
pose ??= poseNow();
// Rows still moving on their segments cluster again every frame.
const key = record.gpu?.moving(frameState)
? `${pose}@${frameState?.frameNumber ?? Math.random()}`
: pose;
if (record.clusterKey === key) {
pose ??= clusterPoseNow();
// Rows still moving on their segments cluster again every frame (NaN,
// a frame with no number, is never the last).
const frameKey = record.gpu?.moving(frameState)
? (frameState?.frameNumber ?? NaN)
: null;
if (record.clusterKey === pose && record.clusterFrame === frameKey) {
if (record.clusterHost)
record.clusterHost.show = record.spec.show !== false;
continue;
}
record.clusterKey = key;
record.clusterKey = pose;
record.clusterFrame = frameKey;
reclusterIcons(record, frameState);
}
}
// The eye and canvas the clusters were last measured at, and a count of
// their changes: a set clusters again when the count it clustered at is
// not the count now.
const clusterPose = new Float64Array(8).fill(NaN);
let clusterPoseVersion = 0;
let clusterPoseAt = 0;
let clusterPoseSame = true;
function putClusterPose(value) {
if (!Object.is(clusterPose[clusterPoseAt], value)) {
clusterPoseSame = false;
clusterPose[clusterPoseAt] = value;
}
clusterPoseAt += 1;
}
function clusterPoseNow() {
const eye = scene.camera?.positionWC;
const dir = scene.camera?.directionWC;
clusterPoseAt = 0;
clusterPoseSame = true;
putClusterPose(eye?.x ?? NaN);
putClusterPose(eye?.y ?? NaN);
putClusterPose(eye?.z ?? NaN);
putClusterPose(dir?.x ?? NaN);
putClusterPose(dir?.y ?? NaN);
putClusterPose(dir?.z ?? NaN);
putClusterPose(scene.canvas?.clientWidth ?? NaN);
putClusterPose(scene.canvas?.clientHeight ?? NaN);
if (!clusterPoseSame) clusterPoseVersion += 1;
return clusterPoseVersion;
}
/** The points a GPU set clusters: its shown rows where they are drawn. */
function gpuClusterPoints(record, frameState, horizon) {
const points = [];
@@ -1274,9 +1374,13 @@ export function createCesiumDraw({
/** Whether a shown set shows flow lines, which draw on in later frames. */
const flowing = () =>
[...sets.values()].some(
(record) => record.spec.show !== false && record.flowShown,
);
anySet((record) => record.spec.show !== false && record.flowShown);
/** Whether any set passes `test`, without copying the sets (per frame). */
function anySet(test) {
for (const record of sets.values()) if (test(record)) return true;
return false;
}
/** Note whether a line set shows any flow line, once its lines change. */
function noteFlows(record) {
@@ -1621,37 +1725,48 @@ export function createCesiumDraw({
}
/**
* `syncIcons`' quick case: every item is drawn, every touched one keeps
* the image it is drawn with, and nothing drawn has gone, so each touched
* one is changed where it is and nothing is added, removed or reordered.
* False, changing nothing, otherwise.
* `upsert`'s quick case for an icon set on billboards: every item is
* drawn, every one of `list` keeps the image it is drawn with, and
* nothing drawn has gone, so each of `list` is changed where it is
* (`patchIcon`: only moved, when that is all that changed) and nothing is
* added, removed or reordered. Each item is read once: a layer moves its
* icons every frame. The items are taken as the set's. False, changing
* nothing, otherwise.
* @param {object} record
* @param {readonly string[]} touched
* @param {readonly object[]} list
*/
function patchDrawnIcons(record, touched) {
function patchDrawnIcons(record, list) {
const drawn = record.billboards;
const host = record.billboardHost;
// Nothing to remove: every item drawn, and nothing drawn but items.
if (
!Array.isArray(touched) ||
touched.length === 0 ||
record.kind !== 'icons' ||
!drawn ||
!host ||
record.host !== host ||
host.isDestroyed() ||
list.length === 0 ||
drawn.size !== record.items.size
)
return false;
for (const id of touched) {
const entry = drawn.get(id);
const item = record.items.get(id);
if (!entry || !item) return false;
const image = iconImage(record, item.image);
const entries = new Array(list.length);
const images = new Array(list.length);
for (let i = 0; i < list.length; i++) {
const entry = drawn.get(list[i].id);
if (!entry) return false;
const image = iconImage(record, list[i].image);
if (
image === undefined ||
imageKeyOf(image) !== entry.image ||
(isKeyed(image) && image.canvas !== entry.canvas)
)
return false;
entries[i] = entry;
images[i] = image;
}
for (const id of touched) {
const item = record.items.get(id);
patchIcon(record, drawn.get(id), item, iconImage(record, item.image));
for (let i = 0; i < list.length; i++) {
record.items.set(list[i].id, list[i]);
patchIcon(record, entries[i], list[i], images[i]);
}
return true;
}
@@ -1685,7 +1800,6 @@ export function createCesiumDraw({
host.isDestroyed()
)
return false;
if (!reordered && patchDrawnIcons(record, touched)) return ICONS_KEPT;
const images = new Map();
for (const id of touched) {
const item = record.items.get(id);
@@ -2467,7 +2581,7 @@ export function createCesiumDraw({
? Cesium.JulianDate.toDate(
scene.frameState?.time ?? Cesium.JulianDate.now(),
).getTime()
: Date.now() - (clock?.delayMs ?? 0);
: (date ? date() : Date.now()) - (clock?.delayMs ?? 0);
}
/**
@@ -5300,7 +5414,7 @@ export function createCesiumDraw({
return record.gpu.drawnAt(ref.id, aheadMs, time ? { time } : undefined);
},
/** Whether a set's ground primitives are still being built. */
building: () => [...sets.values()].some((record) => record.pending),
building: () => anySet((record) => record.pending),
/** Each frame, before it draws: the horizon cull. */
beforeRender() {
pulsing = runPulses();
@@ -5343,19 +5457,14 @@ export function createCesiumDraw({
// Rows moving on a live clock, and flowing lines, draw on in the
// frames that follow.
const playing = quadSets.afterRender(sets.values());
if (
[...sets.values()].some((record) => record.gpu?.animating()) ||
flowing() ||
pulsing ||
playing
)
requestRender();
if (anySet(animating) || flowing() || pulsing || playing) requestRender();
},
/**
* Let go of the sets; with `removeHosts`, take what they draw out of
* the scene too (a scene the port does not own outlives it).
*/
dispose({ removeHosts = false } = {}) {
portDisposed = true;
clampListeners.clear();
// Fields go with the port, and their frame listeners with them.
fieldPart.dispose();
@@ -5366,6 +5475,8 @@ export function createCesiumDraw({
retire(record);
}
record.host = null;
record.disposed = true;
silence(record);
}
sets.clear();
},
+404 -1
View File
@@ -4394,6 +4394,22 @@ test('an aircraft layer draws its contacts as one GPU icon set moving on the del
assert.equal(flags & ICON_RECEDES, ICON_RECEDES);
assert.equal(flags & ICON_CULL_LIFT, ICON_CULL_LIFT);
assert.ok(set.depthTestDistance(row) >= 1e30, 'over depth everywhere');
// The set recedes by the aircraft tuning, and follows it when it changes.
const recession = await import('../../data/aircraftRecession.js');
assert.equal(
part.sets.get(setId).spec.recede,
recession.aircraftRecedeSpec(),
);
assert.equal('recede' in part.sets.get(setId).items.get('abc123'), false);
try {
recession.setAircraftRecessionParams({ scaleFloor: 0.6 });
icons._syncRecede();
assert.equal(host._recedeParams().scaleFloor, 0.6);
} finally {
recession.resetAircraftRecessionParams();
icons._syncRecede();
}
assert.equal(host._recedeParams().scaleFloor, 0.45);
// Drawn where the layer reads it, between its two fixes.
const t = Date.now() - delayMs;
@@ -6674,7 +6690,7 @@ test('models re-pose and restyle in place; only a new url loads again', async ()
Cesium.ColorBlendMode.HIGHLIGHT,
'no tint to blend in: its own colour',
);
assert.equal(model.color.alpha, 1);
assert.equal(model.color, undefined, 'and no colour of its own');
set.upsert([plane({ show: false })]);
assert.equal(model.show, false, 'hidden in place');
@@ -6911,6 +6927,193 @@ test('a model past its pixel cap is scaled down each frame; fades and culls too'
}
});
test('an untinted model drawn fully opaque is given no colour; a fade gives one, and full opacity takes it away again', async () => {
// A colour on a Cesium model adds a colour stage to every draw of it.
const { loads, restore } = fakeModelLoads();
try {
const scene = fakeScene();
let metresPerPixel = 0.1;
scene.camera.getPixelSize = () => metresPerPixel;
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
});
const set = part.port.models({ id: 'm' });
const eye = scene.camera.positionWC;
const at = Cesium.Cartesian3.fromDegrees(0, 0, 1000);
const distance = Cesium.Cartesian3.distance(eye, at);
const item = (extra = {}) => ({
id: 'a',
pos: { lon: 0, lat: 0, height: 1000 },
url: 'a.glb',
orientation: { heading: 0, pitch: 0, roll: 0 },
...extra,
});
set.set([item()]);
loads[0].resolve();
await settle();
const model = loads[0].model;
loads[0].ready();
part.beforeRender();
assert.equal(model.color, undefined, 'opaque, untinted: no colour');
set.upsert([
item({
fadeByDistance: {
near: distance - 10,
nearValue: 1,
far: distance + 10,
farValue: 0,
},
}),
]);
part.beforeRender();
assert.ok(model.color, 'faded: a colour');
assert.ok(Math.abs(model.color.alpha - 0.5) < 1e-6, 'faded halfway');
set.upsert([item()]);
part.beforeRender();
assert.equal(model.color, undefined, 'opaque again: no colour');
set.dispose();
} finally {
restore();
}
});
test('models moved every frame keep their shader and pick ids: only a new look or a new model changes them', async () => {
// A fleet re-poses every model each frame with the same look.
const { loads, restore } = fakeModelLoads();
const toCss = Cesium.Color.prototype.toCssHexString;
let shaderLookups = 0;
Cesium.Color.prototype.toCssHexString = function () {
shaderLookups += 1;
return toCss.call(this);
};
try {
const scene = fakeScene();
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
});
const set = part.port.models({ id: 'fleet' });
const item = (id, lon, extra = {}) => ({
id,
pos: { lon, lat: 0, height: 10 },
url: 'a.glb',
orientation: { heading: 0, pitch: 0, roll: 0 },
maskColor: '#ff8800',
...extra,
});
set.set([item('a', 0), item('b', 1)]);
for (const load of loads) load.resolve();
await settle();
for (const load of loads) load.ready();
const [a, b] = loads.map((load) => load.model);
const shader = a.customShader;
assert.ok(shader instanceof Cesium.CustomShader, 'the mask shader');
const version = part.version();
shaderLookups = 0;
for (let frame = 1; frame <= 5; frame++) {
set.upsert([item('a', frame * 1e-5), item('b', 1 + frame * 1e-5)]);
part.beforeRender();
}
const moved = Cesium.Matrix4.getTranslation(
a.modelMatrix,
new Cesium.Cartesian3(),
);
assert.ok(
Cesium.Cartesian3.distance(
moved,
Cesium.Cartesian3.fromDegrees(5e-5, 0, 10),
) < 1e-6,
'moved',
);
assert.equal(a.customShader, shader, 'the same shader');
assert.equal(shaderLookups, 0, 'not looked up again');
assert.equal(part.version(), version, 'no pick id added or gone');
// A new mask colour, a new shading and the mask again: each drawn.
set.upsert([item('a', 0, { maskColor: '#0000ff' })]);
assert.notEqual(a.customShader, shader, 'a new colour, a new shader');
assert.equal(b.customShader, shader, 'the other keeps its own');
set.upsert([item('a', 0, { maskColor: '#0000ff', shading: 'thermal' })]);
const thermal = a.customShader;
assert.ok(thermal instanceof Cesium.CustomShader);
assert.notEqual(thermal, shader);
set.upsert([item('a', 0)]);
assert.equal(a.customShader, shader, 'its mask again');
set.upsert([item('a', 0, { maskColor: undefined })]);
assert.equal(a.customShader, undefined, 'no mask: lit as it is');
// A model added changes what height queries see through.
set.upsert([item('c', 2)]);
assert.notEqual(part.version(), version, 'a pick id added');
set.dispose();
} finally {
Cesium.Color.prototype.toCssHexString = toCss;
restore();
}
});
test('a model set that recedes fades its models toward the limb with their focus; focus alone dims', async () => {
const { recedeFactors, recedeFrame, recedeParams, recededAlpha } =
await import('../recession.js');
const { loads, restore } = fakeModelLoads();
try {
const scene = fakeScene();
const heightM = 1_000_000;
scene.camera.positionWC = new Cesium.Cartesian3(6_378_137 + heightM, 0, 0);
scene.camera.positionCartographic = { height: heightM };
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
});
const set = part.port.models({ id: 'm', recede: {} });
const item = (extra = {}) => ({
id: 'a',
pos: { lon: 25, lat: 0, height: 0 },
url: 'a.glb',
orientation: { heading: 0, pitch: 0, roll: 0 },
tint: [1, 0, 0, 0.8],
focus: 0.5,
...extra,
});
set.set([item()]);
loads[0].resolve();
await settle();
const model = loads[0].model;
loads[0].ready();
part.beforeRender();
const params = recedeParams({});
const d = Cesium.Cartesian3.distance(
scene.camera.positionWC,
Cesium.Cartesian3.fromDegrees(25, 0, 0),
);
const haze = recedeFactors(d, recedeFrame(heightM, params), params).alpha;
assert.ok(haze < 0.9, `receding: ${haze}`);
const want = 0.8 * recededAlpha(0.5, haze, params);
assert.ok(
Math.abs(model.color.alpha - want) < 1e-6,
`${model.color.alpha} vs ${want}`,
);
assert.equal(model.color.red, 1, 'the tint kept');
// Not receding: the tint's alpha times the focus.
set.setOptions({ recede: null });
part.beforeRender();
assert.ok(Math.abs(model.color.alpha - 0.4) < 1e-6, `${model.color.alpha}`);
set.upsert([item({ focus: undefined })]);
part.beforeRender();
assert.ok(Math.abs(model.color.alpha - 0.8) < 1e-6);
// Receding again, over the blend band: only the combined floor holds.
set.setOptions({ recede: {} });
scene.camera.positionCartographic = { height: 9_000_000 };
set.upsert([item({ focus: 0.1 })]);
part.beforeRender();
assert.ok(Math.abs(model.color.alpha - 0.8 * 0.2) < 1e-6);
set.dispose();
} finally {
restore();
}
});
test('a raised polygon outlines its holes as well as its outer ring', () =>
withImageClasses(() => {
const { scene, draw } = drawOver();
@@ -7894,6 +8097,70 @@ test('icons that only move are moved on the billboards they have, and still rest
set.dispose();
});
test('icons moved every frame are each read once, and a new image or a new icon still draws', () => {
const scene = fakeScene();
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
});
const set = part.port.icons({ id: 'icons:fleet' });
// Reads of each item's image: what a moved icon is drawn with is
// looked up once an update.
let imageReads = 0;
const icon = (id, lon) => {
let image = 'a.png';
return {
id,
pos: { ...Cesium.Cartesian3.fromDegrees(lon, 10) },
get image() {
imageReads += 1;
return image;
},
set image(value) {
image = value;
},
size: [20, 20],
color: '#33ccff',
rotationMode: 'screen',
rotation: 0,
disableDepthTest: Infinity,
meta: { id },
};
};
const items = [icon('a', 0), icon('b', 1), icon('c', 2)];
set.set(items);
const [host] = scene.added;
const billboards = [0, 1, 2].map((i) => host.get(i));
const version = part.version();
imageReads = 0;
for (let frame = 1; frame <= 4; frame++) {
for (const item of items) item.pos.x += 1;
set.upsert(items);
}
assert.equal(imageReads, 4 * items.length, 'each image read once a frame');
assert.equal(scene.added[0], host, 'the same collection');
billboards.forEach((billboard, i) => {
assert.equal(host.get(i), billboard, 'the same billboards');
assert.equal(billboard.position.x, items[i].pos.x, 'moved');
});
assert.equal(part.version(), version, 'nothing added or removed');
// Only some moved: the others stay where they are.
items[1].pos.x += 1;
set.upsert([items[1]]);
assert.equal(billboards[1].position.x, items[1].pos.x);
// A new image is drawn on the billboard it has.
items[0].image = 'b.png';
set.upsert(items);
assert.equal(host.get(0), billboards[0], 'the same billboard');
assert.equal(billboards[0].image, 'b.png');
// An icon added joins after the others.
set.upsert([...items, icon('d', 3)]);
assert.equal(host.length, 4);
assert.notEqual(part.version(), version, 'an icon added');
set.dispose();
});
test('the transit layer draws its vehicles as two icon sets, moving a marker between them, on a viewer of its own', async () => {
const { createRendering } = await import('../../layers/transit/rendering.js');
const { createState } = await import('../../layers/transit/state.js');
@@ -8361,3 +8628,139 @@ test('a quad that moves from a blob to a URL lets the blob go once its old mater
names.forEach((name, i) => (globalThis[name] = real[i]));
}
});
test('a set disposed by one of its listeners tells the later ones nothing more', async () => {
const { loads, restore } = fakeModelLoads();
try {
const plane = (id) => ({
id,
pos: { lon: 0, lat: 0, height: 10 },
url: 'a.glb',
});
const loaded = async (load) => {
load.resolve();
await settle();
load.ready();
};
// Disposed by its handle, from its first ready listener.
const part = createCesiumDraw({
scene: fakeScene(),
report: (error) => assert.fail(error),
});
const set = part.port.models({ id: 'planes' });
const heard = [];
set.on('ready', () => set.dispose());
set.on('ready', (id) => heard.push(id));
set.on('loadFailed', (id) => heard.push(`failed ${id}`));
set.set([plane('p')]);
await loaded(loads[0]);
assert.deepEqual(heard, [], 'the second listener does not run');
// Every set, when the port is disposed from a ready listener.
const gone = createCesiumDraw({
scene: fakeScene(),
report: (error) => assert.fail(error),
});
const other = gone.port.models({ id: 'planes' });
const late = [];
other.on('ready', () => gone.dispose({ removeHosts: true }));
other.on('ready', (id) => late.push(id));
other.set([plane('q')]);
await loaded(loads[1]);
assert.deepEqual(late, [], 'nothing after the port is gone');
} finally {
restore();
}
});
test('a disposed set, and every set once the port is disposed, does nothing on later calls', async () => {
const { loads, restore } = fakeModelLoads();
try {
const items = {
points: { id: 'a', pos: { lon: 0, lat: 0 }, pixelSize: 4, color: '#fff' },
lines: {
id: 'a',
positions: [
{ lon: 0, lat: 0 },
{ lon: 1, lat: 1 },
],
widthPx: 2,
style: { kind: 'solid', color: '#fff' },
},
icons: {
id: 'a',
pos: { lon: 0, lat: 0 },
image: 'data:image/png;base64,iVBORw0KGgo=',
},
shapes: {
id: 'a',
geometry: {
kind: 'ellipse',
center: { lon: 0, lat: 0 },
semiMajor: 1000,
semiMinor: 1000,
},
fill: [1, 0, 0, 0.5],
},
models: { id: 'a', pos: { lon: 0, lat: 0, height: 10 }, url: 'a.glb' },
};
const lateCalls = (set, item) => {
set.set([item]);
set.upsert([{ ...item, id: 'b' }]);
set.show = true;
set.setOptions({ clampTo: 'terrain', pickable: false, drawOrder: 3 });
set.setOptions({ show: true });
set.setColumns?.({
ids: ['c'],
positions: new Float64Array([6378137, 0, 0]),
});
set.remove(['a']);
set.clear();
assert.equal(typeof set.on('ready', () => {}), 'function');
};
// Disposed by its handle.
const scene = fakeScene();
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
});
for (const [kind, item] of Object.entries(items)) {
const set = part.port[kind]({ id: kind });
set.dispose();
lateCalls(set, item);
assert.equal(scene.added.length, 0, `${kind}: nothing drawn`);
assert.equal(part.sets.size, 0, `${kind}: no set live`);
set.dispose();
}
// A newer set under the same id is not changed by the old handle.
const old = part.port.points({ id: 'same' });
old.dispose();
const newer = part.port.points({ id: 'same' });
old.set([items.points]);
assert.equal(newer.size(), 0, 'the newer set keeps its items');
newer.dispose();
// Every set, once the port is disposed (its renderer destroyed), and a
// set asked for after that.
const held = fakeScene();
const gone = createCesiumDraw({
scene: held,
report: (error) => assert.fail(error),
});
const before = Object.keys(items).map((kind) => [
kind,
gone.port[kind]({ id: kind }),
]);
gone.dispose({ removeHosts: true });
for (const [kind, set] of before) lateCalls(set, items[kind]);
for (const [kind, item] of Object.entries(items))
lateCalls(gone.port[kind]({ id: `${kind}:late` }), item);
assert.equal(held.added.length, 0, 'nothing drawn after the port is gone');
assert.equal(gone.sets.size, 0, 'no set live after the port is gone');
assert.equal(loads.length, 0, 'no model loads');
} finally {
restore();
}
});
+13
View File
@@ -664,8 +664,20 @@ export function createCesiumFields({
return handle;
}
// Once the fields are disposed (their renderer destroyed), a field asked
// for draws nothing and does nothing.
let gone = false;
const inert = (spec) => ({
id: spec?.id,
show: true,
update() {},
on: () => () => {},
dispose() {},
});
return {
field(spec) {
if (gone) return inert(spec);
if (fields.has(spec?.id))
throw new Error(`a field with id ${spec.id} is live`);
if (spec?.kind === 'rasterShell') return rasterShell(spec);
@@ -688,6 +700,7 @@ export function createCesiumFields({
},
has: (id) => fields.has(id),
dispose() {
gone = true;
for (const handle of [...fields.values()]) handle.dispose();
},
};
+29
View File
@@ -691,3 +691,32 @@ test('the Cesium fields refuse kinds they cannot draw and live ids', () => {
field.dispose();
h.fields.field(spec).dispose();
});
test('once the fields are disposed, a field asked for draws nothing and does nothing', () => {
const h = fieldHarness();
const field = h.fields.field({
kind: 'rasterShell',
id: 'shell',
image: h.image(),
rectangle: RECT,
heightM: 1,
});
h.fields.dispose();
assert.equal(h.live().length, 0, 'the live field went');
field.update({ alpha: 0.5 });
field.show = true;
const late = h.fields.field({
kind: 'rasterShell',
id: 'late',
image: h.image(),
rectangle: RECT,
heightM: 1,
});
late.update({ heightM: 2 });
late.show = true;
assert.equal(typeof late.on('drawn', () => {}), 'function');
h.render();
assert.equal(h.live().length, 0, 'nothing drawn after');
assert.equal(h.fields.has('late'), false);
late.dispose();
});
+101 -13
View File
@@ -14,7 +14,10 @@
* `maxPixelSize` (the scale capped so the bounding sphere spans at most that
* many drawing-buffer pixels at its distance from the eye, as Cesium
* measures `minPixelSize`), `scaleByDistance`, `fadeByDistance` (the tint's
* alpha) and the set's `horizonCull`.
* alpha), the set's `horizonCull`, and its `recede`: the tint's alpha times
* the focus and haze (`render/recession.js`), written again once that moves
* by more than `RECEDE_WRITE_EPSILON`. A model of a set that does not
* recede draws at its tint's alpha times its `focus`.
*
* A failed load fires `loadFailed` (after the frame Cesium reported it in,
* so a listener may change the set), and is tried again when its item is
@@ -25,6 +28,12 @@
* them. Heights are absolute: models clamp nothing.
*/
import * as Cesium from 'cesium';
import {
recedeFactors,
recedeFrame,
recedeParams,
recededAlpha,
} from '../recession.js';
const BLEND_MODES = {
highlight: Cesium.ColorBlendMode.HIGHLIGHT,
@@ -39,6 +48,13 @@ const BLEND_MODES = {
*/
export const MODEL_RETRY_MS = 5000;
/**
* How far a receding model's emphasis (focus and haze) moves before its
* colour is written again: an eye in motion would otherwise write every
* model's colour every frame.
*/
export const RECEDE_WRITE_EPSILON = 0.005;
/** Cesium's own blend amount, for a `mix` that names none. */
const DEFAULT_MIX = 0.5;
@@ -85,9 +101,17 @@ void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
*/
function entryShader(entry) {
const shading = entry.item.shading;
if (entry.mask && shading !== 'thermal')
return maskShaderOf(shading, entry.mask);
return shaderOf(shading);
// Kept while its shading and mask colour are: a fleet re-poses every
// frame with the same look.
if (entry.shaderShading === shading && entry.shaderMask === entry.mask)
return entry.shader;
entry.shader =
entry.mask && shading !== 'thermal'
? maskShaderOf(shading, entry.mask)
: shaderOf(shading);
entry.shaderShading = shading;
entry.shaderMask = entry.mask;
return entry.shader;
}
/**
@@ -151,8 +175,12 @@ const scratchAxes = new Cesium.Cartesian3();
const scratchMatrix = new Cesium.Matrix4();
const scratchSphere = new Cesium.BoundingSphere();
const scratchColor = new Cesium.Color();
const scratchFactors = { scale: 1, alpha: 1, limbRatio: null };
const scratchFrame = { active: false, limbM: 1, strength: 0 };
/** The colour last written to each model. */
const writtenColors = new WeakMap();
/** Written to a model drawn in its own colours: no colour at all. */
const NO_COLOR = Symbol('drawModels.noColor');
/** What the per-frame pass found, for a model it does not run on. */
const STILL = Object.freeze({ scale: 1, alpha: 1, shown: true });
@@ -189,7 +217,12 @@ const needsFrame = (item, spec) =>
item.maxPixelSize > 0 ||
Boolean(item.scaleByDistance) ||
Boolean(item.fadeByDistance) ||
Boolean(spec.horizonCull);
Boolean(spec.horizonCull) ||
Boolean(spec.recede);
/** An item's focus, 0..1. */
const focusOf = (item) =>
Number.isFinite(item.focus) ? Math.min(1, Math.max(0, item.focus)) : 1;
/**
* The models part of a Cesium draw port.
@@ -421,12 +454,27 @@ export function createModelSets({
entry.tint ?? Cesium.Color.WHITE,
scratchColor,
);
color.alpha *= frame.alpha;
color.alpha *= frame.alpha * (entry.emphasis ?? focusOf(item));
// An untinted model at full opacity is drawn without a colour: a colour
// adds a colour stage to every draw of the model.
const plain = !entry.tint && color.alpha === 1;
// Written only when what is asked changes, so a theme's own write to a
// model's colour stands until then.
const written = writtenColors.get(model);
if (!written || !Cesium.Color.equals(written, color)) {
writtenColors.set(model, Cesium.Color.clone(color, written));
if (plain) {
if (written !== NO_COLOR) {
writtenColors.set(model, NO_COLOR);
model.color = undefined;
}
} else if (
!written ||
written === NO_COLOR ||
!Cesium.Color.equals(written, color)
) {
writtenColors.set(
model,
Cesium.Color.clone(color, written === NO_COLOR ? undefined : written),
);
model.color = color;
}
const show =
@@ -434,17 +482,24 @@ export function createModelSets({
if (model.show !== show) model.show = show;
}
/** Add or change items, by id; true once handled (always, for models). */
/**
* Add or change items, by id. Whether any was added: models moved or
* restyled keep their pick ids, so only one added changes what height
* queries see through.
*/
function upsert(record, list) {
hostOf(record);
for (const item of list) put(record, item);
notePickIds(record);
let added = false;
for (const item of list) if (put(record, item)) added = true;
if (added) notePickIds(record);
requestRender();
return true;
return added;
}
/** Draw `item` on its entry, made when it has none; true when made. */
function put(record, item) {
let entry = record.models.get(item.id);
const made = !entry;
if (!entry) {
entry = {
item,
@@ -463,8 +518,15 @@ export function createModelSets({
failedAt: 0,
settleLoad: null,
styled: null,
// The custom shader drawn with, for the shading and mask it is of
// (`entryShader`).
shader: undefined,
shaderShading: null,
shaderMask: null,
dynamic: false,
frame: null,
// Focus and haze in a set that recedes, else null (focus alone).
emphasis: null,
pickId: pickId(record, item),
};
record.models.set(item.id, entry);
@@ -495,6 +557,7 @@ export function createModelSets({
if (model) style(record, entry, model);
const retry = entry.failed && Date.now() - entry.failedAt >= MODEL_RETRY_MS;
if (entry.url !== item.url || retry) load(record, entry);
return made;
}
/** Stop the entry's load in flight, keeping the model it draws. */
@@ -527,8 +590,17 @@ export function createModelSets({
const width = scene.drawingBufferWidth ?? scene.canvas?.width ?? 0;
const height = scene.drawingBufferHeight ?? scene.canvas?.height ?? 0;
let horizon;
const eyeHeight = scene.camera.positionCartographic?.height;
for (const record of sets) {
if (record.kind !== 'models' || !record.models) continue;
if (record.recedeFrom !== record.spec.recede) {
record.recedeFrom = record.spec.recede;
record.recede = recedeParams(record.spec.recede);
}
const recede = record.recede;
const recedeNow = recede
? recedeFrame(eyeHeight, recede, scratchFrame)
: null;
for (const entry of record.models.values()) {
if (!entry.dynamic) {
if (entry.frame) {
@@ -548,6 +620,20 @@ export function createModelSets({
Math.max(0, nearFarValue(item.fadeByDistance, distance)),
)
: 1;
if (recede) {
const haze = recedeFactors(
distance,
recedeNow,
recede,
scratchFactors,
).alpha;
const emphasis = recededAlpha(focusOf(item), haze, recede);
if (
entry.emphasis === null ||
Math.abs(entry.emphasis - emphasis) > RECEDE_WRITE_EPSILON
)
entry.emphasis = emphasis;
} else entry.emphasis = null;
let shown = frame.alpha > 0;
if (record.spec.horizonCull) {
horizon ??= horizonNow();
@@ -609,8 +695,10 @@ export function createModelSets({
/** The set's options changed: whether models need the frame pass. */
function restyle(record) {
if (!record.models) return;
for (const entry of record.models.values())
for (const entry of record.models.values()) {
entry.dynamic = needsFrame(entry.item, record.spec);
if (!record.spec.recede) entry.emphasis = null;
}
}
return { build, upsert, beforeRender, restyle };
+3 -2
View File
@@ -150,7 +150,7 @@ export function createCesiumEffects(
onChange: () => {
if (gone() || modulation.draws() === modulationListed) return;
modulationListed = modulation.draws();
listeners.fire(port.diagnostics());
if (listeners.size) listeners.fire(port.diagnostics());
},
})
: null;
@@ -223,7 +223,8 @@ export function createCesiumEffects(
if (gone()) return;
apply();
frame.requestRender(reason);
listeners.fire(port.diagnostics());
// A fade changes every frame: its diagnostics are listed only for ears.
if (listeners.size) listeners.fire(port.diagnostics());
}
/** Whether `id` names a style; changes to unknown ones are ignored. */
+12 -8
View File
@@ -144,9 +144,12 @@ export function createCesiumGlobe(
// The vector base's sources' credits.
const vectorCredits = [];
/** Every 3D tileset the scene holds. */
function tilesets() {
const found = [];
/**
* Every 3D tileset the scene holds, into `found` (emptied first): the
* per-frame readers pass `scratchTilesets` rather than make a list.
*/
function tilesets(found = []) {
found.length = 0;
const primitives = scene.primitives;
const n = primitives?.length ?? 0;
for (let i = 0; i < n; i++) {
@@ -155,12 +158,13 @@ export function createCesiumGlobe(
}
return found;
}
const scratchTilesets = [];
/** The base tileset drawn now, which `objects` imagery drapes on. */
function drawnBase() {
if (photoreal && !photoreal.isDestroyed() && photoreal.show)
return photoreal;
for (const tileset of tilesets())
for (const tileset of tilesets(scratchTilesets))
if (isBaseTileset(tileset) && tileset.show && !tileset.isDestroyed())
return tileset;
return null;
@@ -401,7 +405,7 @@ export function createCesiumGlobe(
function surfaceLoaded() {
if (scene.globe?.show) return scene.globe.tilesLoaded !== false;
let found = false;
for (const tileset of tilesets()) {
for (const tileset of tilesets(scratchTilesets)) {
if (!tileset.show || tileset.isDestroyed?.()) continue;
found = true;
if (tileset.tilesLoaded === false) return false;
@@ -423,7 +427,7 @@ export function createCesiumGlobe(
// The shown tilesets as a set: their order among the primitives is no
// change to the surface.
let count = 0;
for (const tileset of tilesets()) {
for (const tileset of tilesets(scratchTilesets)) {
if (!tileset.show || tileset.isDestroyed?.()) continue;
count += 1;
if (!surfaceSeen.tiles.has(tileset)) changed = true;
@@ -433,7 +437,7 @@ export function createCesiumGlobe(
surfaceSeen.globe = globe;
surfaceSeen.terrain = terrain;
surfaceSeen.tiles.clear();
for (const tileset of tilesets())
for (const tileset of scratchTilesets)
if (tileset.show && !tileset.isDestroyed?.())
surfaceSeen.tiles.add(tileset);
surfaceVersion = ++surfaceVersions;
@@ -480,7 +484,7 @@ export function createCesiumGlobe(
applyShading();
requestRender('base');
}
if (imagery.list().length) imagery.sync();
if (imagery.size) imagery.sync();
if (progressListeners.size === 0) return;
const base = drawnBase();
progress.tilesPending = base && !base.tilesLoaded ? 1 : 0;
+20 -9
View File
@@ -2,7 +2,7 @@
* @module render/cesium/gpuIcons
* @description The Cesium draw port's GPU icon sets: an icon set whose items
* move (`motionSegments`), glide their course (`courseGlide`), recede
* toward the limb, pick through a larger proxy,
* toward the limb (`recede`, the set's), pick through a larger proxy,
* switch images by drawn size, or that takes columns (`columns`), draws as
* one instanced primitive (`IconSetPrimitive`) over an icon set's typed
* columns (`iconSet.js`) instead of a billboard collection. Each item is one
@@ -200,16 +200,19 @@ function rasterPxOf(url, item) {
/**
* @param {{scene: object, capabilities: ReadonlySet<string>,
* date?: (() => number)|null,
* toColor: (color: unknown) => Cesium.Color,
* imageOf: (record: object, image: unknown) => unknown,
* peekImage: (ref: {atlas: string, slot: string}) => unknown,
* requestRender: (reason: string) => void}} options `imageOf` reads an atlas slot
* requestRender: (reason: string) => void}} options `date` is the epoch
* ms a `live` motion clock reads (null: the system clock's); `imageOf` reads an atlas slot
* through the draw port's atlases (undefined while it is not registered),
* noting that the set draws from it; `peekImage` only reads it.
*/
export function createGpuIcons({
scene,
capabilities,
date = null,
toColor,
imageOf,
peekImage,
@@ -217,13 +220,13 @@ export function createGpuIcons({
}) {
const can = (capability) => capabilities.has(capability);
/** Whether drawing these items needs a GPU icon set. */
function wants(items) {
/** Whether drawing these items (in a set of `spec`) needs a GPU icon set. */
function wants(items, spec = {}) {
if (spec.recede) return true;
for (const item of items) {
if (
(item.motion && can('motionSegments')) ||
(item.courseGlide && can('courseGlide')) ||
item.recede ||
item.pickProxy ||
item.imageLod
)
@@ -293,7 +296,9 @@ export function createGpuIcons({
result,
);
return Cesium.JulianDate.addSeconds(
Cesium.JulianDate.now(result),
date
? Cesium.JulianDate.fromDate(new Date(date()), result)
: Cesium.JulianDate.now(result),
-(clock?.delayMs ?? 0) / 1000,
result,
);
@@ -309,6 +314,7 @@ export function createGpuIcons({
clockTime(frameState, new Cesium.JulianDate()),
requestRender: () => requestRender(`icons:${spec.id}`),
cull: () => spec.horizonCull === true,
recede: () => spec.recede,
translucent: () => spec.blend === 'translucent',
// Picked as the draw port's other items are: `{set, id, meta}` as
// the item now is, hidden row by row for drill picks.
@@ -423,7 +429,7 @@ export function createGpuIcons({
isCurve(item.scaleByDistance) ? item.scaleByDistance : undefined,
);
set.setFlag(row, ICON_ROTATES, item.rotationMode === 'course');
set.setFlag(row, ICON_RECEDES, item.recede === true);
set.setFlag(row, ICON_RECEDES, Boolean(spec.recede));
set.setFlag(row, ICON_CULL_LIFT, spec.horizonCull === true);
set.setPickProxy(
row,
@@ -727,10 +733,15 @@ export function createGpuIcons({
}
columnIds = ids;
},
/** After `setOptions`: the cull lift follows `horizonCull`. */
/**
* After `setOptions`: the cull lift follows `horizonCull`, and every
* row recedes while the set does.
*/
restyle() {
for (let row = 0; row < set.count; row++)
for (let row = 0; row < set.count; row++) {
set.setFlag(row, ICON_CULL_LIFT, spec.horizonCull === true);
set.setFlag(row, ICON_RECEDES, Boolean(spec.recede));
}
},
/** Rewrite the rows drawing from atlas `id`. */
reatlas(id) {
+62 -2
View File
@@ -221,9 +221,45 @@ test('rows moving on a live clock keep frames coming until their segments end',
assert.equal(scene.renders, onScene);
});
test('a set that recedes draws on the GPU, every row receding by the set’s parameters, and changes live', () => {
const { scene, part, draw } = drawOver();
// An item's own `recede` is not the contract's: it changes nothing.
const still = draw.icons({ id: 'gpu:still' });
still.set([icon('a', { recede: true })]);
assert.ok(
!(scene.added.at(-1) instanceof IconSetPrimitive),
'still icons stay billboards',
);
const set = draw.icons({
id: 'gpu:recede',
recede: { scaleFloor: 0.6 },
});
set.set([icon('a'), icon('b')]);
const host = scene.added.at(-1);
assert.ok(host instanceof IconSetPrimitive, 'on the GPU, though still');
const { set: s } = rows(part, 'gpu:recede');
for (const id of ['a', 'b'])
assert.equal(s.flags(s.row(id)) & ICON_RECEDES, ICON_RECEDES, id);
assert.equal(host._recedeParams().scaleFloor, 0.6);
assert.equal(host._recedeParams().alphaFloor, 0.35, 'the rest the defaults');
set.setOptions({ recede: null });
for (const id of ['a', 'b'])
assert.equal(s.flags(s.row(id)) & ICON_RECEDES, 0, `${id} no longer`);
assert.equal(host._recedeParams(), null);
// A billboard set told to recede goes onto the GPU, its icons with it.
still.setOptions({ recede: {} });
const moved = part.sets.get('gpu:still').gpu;
assert.ok(moved, 'on the GPU now');
assert.equal(moved.set.count, 1);
assert.equal(
moved.set.flags(moved.set.row('a')) & ICON_RECEDES,
ICON_RECEDES,
);
});
test('an item’s look goes into its row: size, scale, tint, focus, flags, proxy, depth and images', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:look', horizonCull: true });
const set = draw.icons({ id: 'gpu:look', horizonCull: true, recede: {} });
set.set([
icon('a', {
motion: { kind: 'hold', courseDeg: 10 },
@@ -232,7 +268,6 @@ test('an item’s look goes into its row: size, scale, tint, focus, flags, proxy
alpha: 0.5,
color: [1, 0, 0, 1],
focus: 0.25,
recede: true,
rotationMode: 'course',
pickProxy: { size: [48, 40] },
disableDepthTest: Infinity,
@@ -1127,3 +1162,28 @@ test('a GPU icon set asks the frame port for its atlas frames, under its own rea
iconAtlas.onChange = onChange;
}
});
test('a live motion clock reads the date the draw port is given', () => {
const t0 = Date.UTC(2031, 0, 2, 3, 4, 5);
let date = t0 + 4000;
const { part, draw } = drawOver({ date: () => date });
const set = draw.icons({
id: 'gpu:dated',
motionClock: { kind: 'live', delayMs: 1000 },
});
const to = ecef(Cesium.Cartesian3.fromDegrees(4.2, 51.95, 2));
const item = icon('a', {
motion: { kind: 'lerp', from: ecef(AT), to, t0, t1: t0 + 10_000 },
});
set.set([item]);
const at = (ms) => iconPosition(item, ms);
assert.ok(
distance(part.drawnPosition({ set: 'gpu:dated', id: 'a' }), at(t0 + 3000)) <
0.1,
);
date = t0 + 8000;
assert.ok(
distance(part.drawnPosition({ set: 'gpu:dated', id: 'a' }), at(t0 + 7000)) <
0.1,
);
});
+25
View File
@@ -24,6 +24,7 @@ export const CESIUM_CHECKS = new Set([
'camera.trace.commands inside a lookAt frame',
'camera.trace.changed fires by each listener’s threshold',
'camera.moveEnd',
'camera.changed.order',
'camera.controls.holds',
'camera.controls.settings',
'camera.follow',
@@ -74,6 +75,9 @@ export const CESIUM_CHECKS = new Set([
'draw.lines.segments',
'draw.lines.segmentStyles',
'draw.sets.blend',
'draw.sets.recede',
'draw.sets.recede.models',
'draw.afterDispose',
'draw.ids',
'draw.models',
'draw.shapes.lit',
@@ -123,6 +127,7 @@ export const CESIUM_CHECKS = new Set([
'input.clickPick',
'input.lease',
'input.lease.grab',
'input.lease.lost',
'input.lease.press',
'query.heights',
'query.pickBeforeStyles',
@@ -134,12 +139,24 @@ export const CESIUM_CHECKS = new Set([
'quality',
'quality.signals',
'quality.signals.gpuTiming',
'renderer.afterDestroy',
'renderer.afterDestroy.frames',
'renderer.listeners',
'renderer.listenerRules',
'renderer.shape',
'renderer.capture',
'renderer.readPixels',
'renderer.releaseUnused',
'renderer.whenSettled',
'renderer.resize',
'frame.setTargetFps',
'globe.setTerrain',
'globe.setPhotoreal',
'globe.progress',
'effects.setStyleParams',
'effects.bloom',
'effects.sharpen',
'quality.probe',
]);
/** A frame fails the check rather than hang it when frames stop. */
@@ -183,6 +200,7 @@ export function createCesiumHarness({
// own that each frame moves on by 1/60 s: flights then step as the
// reference traces do, frame by frame.
const clocks = new WeakMap();
const containers = new WeakMap();
return {
name,
// A camera controller hears the pointer events sent through `pointer`
@@ -220,8 +238,15 @@ export function createCesiumHarness({
}
};
clocks.set(renderer, clock);
containers.set(renderer, container);
return renderer;
},
resizeContainer: (r, { width, height }) => {
const container = containers.get(r);
if (!container) return;
container.style.width = `${width}px`;
container.style.height = `${height}px`;
},
frame: (r) => {
const clock = clocks.get(r);
if (clock) clock.ms += 1000 / 60;
+33 -28
View File
@@ -10,7 +10,8 @@
* (`alignedAxis` zero), depth test disabled at any distance (drawn on the near plane),
* opaque and translucent passes, horizon culling, and per-row picks whose object is
* `{ id, meta, primitive }` (`primitive.show` hides that one row, as drillPick expects).
* Rows flagged to recede also take the aircraft limb recession, composed with focus.
* Rows flagged to recede (the set's `recede`) also take the limb recession
* (`render/recession.js`), composed with focus.
*
* On WebGL 2 each row also reads its extras ({@link module:iconSet}'s
* `extras`) from a float texture by instance: a screen offset and anchor, a
@@ -37,10 +38,10 @@ import {
MIN_ICON_SLOTS,
NEAR_IMAGE_DEVICE_PX,
} from '../../data/iconAtlas.js';
import {
cameraLimbDistanceM,
getAircraftRecessionParams,
} from '../../data/aircraftRecession.js';
import { recedeFrame, recedeParams } from '../recession.js';
/** The parameters the uniforms hold while the set does not recede. */
const NO_RECEDE = recedeParams({});
const ATTRIBUTE_LOCATIONS = Object.freeze({
corner: 0,
@@ -339,12 +340,18 @@ export class IconSetPrimitive {
renderTime,
requestRender,
cull,
recede,
translucent,
pickObject,
}) {
this.set = set;
this.renderTime = renderTime;
this._cull = cull ?? (() => true);
// The set's `recede`, and the parameters last made from it.
this._recede = recede ?? (() => null);
this._recedeFrom = undefined;
this._recedeResolved = null;
this._recedeFrame = { active: false, limbM: 1, strength: 0 };
this._translucent = translucent ?? (() => false);
this._pickObject = pickObject ?? null;
this._pickPass = 0;
@@ -694,31 +701,19 @@ export class IconSetPrimitive {
this._horizon,
);
const tuning = getAircraftRecessionParams();
const height = camera.positionCartographic?.height;
const limb = cameraLimbDistanceM(height, tuning.earthRadiusM);
const active =
Number.isFinite(height) &&
height > 0 &&
height < tuning.globeViewBlendEndM &&
limb > 0;
let strength = 0;
if (active) {
const g = Math.min(
1,
Math.max(
0,
(height - tuning.globeViewBlendStartM) /
(tuning.globeViewBlendEndM - tuning.globeViewBlendStartM),
),
);
strength = 1 - g * g * (3 - 2 * g);
}
// Rows recede only while the set does (their flag says so); its
// parameters, or the defaults' while it does not, fill the uniforms.
const tuning = this._recedeParams() ?? NO_RECEDE;
const frame = recedeFrame(
camera.positionCartographic?.height,
tuning,
this._recedeFrame,
);
Cesium.Cartesian4.fromElements(
active ? limb : 1,
frame.limbM,
tuning.startLimbRatio,
strength,
active ? 1 : 0,
frame.strength,
frame.active ? 1 : 0,
this._recession,
);
Cesium.Cartesian3.fromElements(
@@ -729,6 +724,16 @@ export class IconSetPrimitive {
);
}
/** The set's `recede` as the parameters it draws with; null: it does not recede. */
_recedeParams() {
const spec = this._recede();
if (spec !== this._recedeFrom) {
this._recedeFrom = spec;
this._recedeResolved = recedeParams(spec);
}
return this._recedeResolved;
}
_createCommands(context) {
this._slotCount = contextIconSlots(context);
this._slotUniform = this._slots.slice(0, this._slotCount);
+8
View File
@@ -835,6 +835,10 @@ export function createCesiumImagery(
/** After each frame: each timed layer's shown frame, once it is drawn. */
function announceFrames() {
if (disposed) return;
// Most frames have no timed layer: the copy below is made only for one.
let timedLayers = false;
for (const record of layers) if (record.timed?.at) timedLayers = true;
if (!timedLayers) return;
for (const record of layers.slice()) {
const timed = record.timed;
// A layer removed by another's listener says nothing.
@@ -858,6 +862,10 @@ export function createCesiumImagery(
return {
add,
list: () => layers.map((record) => record.handle),
/** How many layers the port holds, without listing them. */
get size() {
return layers.length;
},
/** Layers whose providers are still being built, as promises. */
ready: (handles) =>
Promise.allSettled(
+29
View File
@@ -94,6 +94,7 @@ function setup({ stock = true, document = null, takeStock = true } = {}) {
handler.fire(T.LEFT_CLICK, { position: at(x, y) }, modifier);
};
return {
widget,
input,
port: input.port,
handler,
@@ -442,3 +443,31 @@ test('not taking the stock, they stay on the viewer’s handler but while held',
'dispose gives a held one back',
);
});
test("a tool that does not hold off stock clicks leaves the viewer's select and double-click follow running; one that does stops them", async (t) => {
const { inputFor } = await import('../../input/dispatcher.js');
const { claimPointer, releasePointer } =
await import('../../data/inputOwnership.js');
const s = setup();
// The dispatcher over this port, as the application's layers take input.
const dispatcher = inputFor(s.widget, {
query: { pick: () => null, drillPick: () => [] },
});
t.after(() => dispatcher.destroy());
const placed = [];
const lease = claimPointer('placing-tool');
t.after(() => releasePointer(lease));
dispatcher.onPointer('click', () => placed.push('tool'), { lease });
s.press(5, 6);
s.handler.fire(T.LEFT_DOUBLE_CLICK, { position: s.at(5, 6) });
assert.deepEqual(placed, ['tool']);
assert.equal(s.selected.length, 1, 'the stock select ran on its click');
assert.equal(s.followed.length, 1, 'and the double-click follow');
const hold = dispatcher.suppressStockClicks();
s.press(5, 6);
s.handler.fire(T.LEFT_DOUBLE_CLICK, { position: s.at(5, 6) });
hold();
assert.deepEqual(placed, ['tool', 'tool']);
assert.equal(s.selected.length, 1, 'held off: no stock select');
assert.equal(s.followed.length, 1, 'nor follow');
});
+110 -46
View File
@@ -108,20 +108,26 @@ export function cesiumCapabilities(scene, only) {
);
}
/** What `renderOnce` and `capture` reject with once the renderer is destroyed. */
const destroyedError = () => new Error('renderer destroyed');
/**
* @param {object} widget A Cesium `CesiumWidget` or `Viewer`.
* @param {{capabilities: ReadonlySet<string>, credentials?: object,
* cameraController?: Function, now?: () => number,
* cameraController?: import('../contract/camera').CameraControllerFactory,
* now?: () => number,
* date?: () => number,
* idleFps?: number}} options
* The renderer's capabilities, which gate the members that need them, and
* the credentials its globe loads photoreal tiles and world data with
* (`googleApiKey`, `googleTokens`, `worldDataToken`). `now` is the clock
* each tick reads (`performance.now` by default; a test's virtual one).
* With `idleFps`, the loop ticks at most that often while no hold is out
* (Cesium ticks its clock and every update listener each animation frame
* even when it draws nothing), and at the display's rate while one is;
* `setTargetFps` then caps both, and the loop starts with no cap of its
* own. Without it, the widget's own rate is the cap.
* each tick reads (`performance.now` by default; a test's virtual one);
* `date`, the epoch ms a `live` motion clock reads (the system clock's by
* default). With `idleFps`, the loop ticks at most that often while no
* hold is out (Cesium ticks its clock and every update listener each
* animation frame even when it draws nothing), and at the display's rate
* while one is; `setTargetFps` then caps both, and the loop starts with no
* cap of its own. Without it, the widget's own rate is the cap.
* With
* `cameraController`, the camera port is that controller's over Cesium's
* camera (`controlledCamera.js`); the ports then have `attachInput` and
@@ -134,6 +140,7 @@ export function createCesiumPorts(
credentials = {},
cameraController,
now: clockNow = () => performance.now(),
date = null,
idleFps = 0,
},
) {
@@ -187,23 +194,39 @@ export function createCesiumPorts(
});
liveTick = null;
};
// The camera's `changed`, measured before any `preUpdate` listener moves
// the camera, in a frame that had no clock tick to measure it at.
let measureCameraChanged = null;
const settleUndrawn = () => void settleTick(false);
const tick = () => {
measureCameraChanged?.();
settleTick(false);
// A tick that does not draw settles at its end; one that does, at
// preRender, before this runs.
atEndOfTick(scene, () => void settleTick(false));
atEndOfTick(scene, settleUndrawn);
const now = clockNow();
dt = (now - tickNow) / 1000;
tickNow = now;
frames += 1;
};
// A scene time as epoch ms, worked out again only when the time moves:
// the phases of a frame, and the frames of a paused clock, share one.
let msJulian = null;
let msValue = 0;
// What `setTime` reads a time through.
const scratchDate = new Date(0);
const scratchJulian = new Cesium.JulianDate();
const msOf = (time) => {
if (msJulian && Cesium.JulianDate.equals(msJulian, time)) return msValue;
msValue = Cesium.JulianDate.toDate(time).getTime();
msJulian = Cesium.JulianDate.clone(time, msJulian ?? undefined);
return msValue;
};
const onPhase = (phase) => (_scene, time) => {
if (frameListeners[phase].size === 0) return;
const t = {
frame: frames,
time: Cesium.JulianDate.toDate(
time ?? widget.clock.currentTime,
).getTime(),
time: msOf(time ?? widget.clock.currentTime),
now: tickNow,
dt,
rendering: true,
@@ -245,7 +268,7 @@ export function createCesiumPorts(
let controlled = null;
const cameraTick = (time) => ({
now: tickNow,
time: Cesium.JulianDate.toDate(time ?? widget.clock.currentTime).getTime(),
time: msOf(time ?? widget.clock.currentTime),
});
const removers = [
scene.preUpdate.addEventListener(tick),
@@ -289,24 +312,26 @@ export function createCesiumPorts(
idleFps <= 0 && widget.targetFrameRate > 0 ? widget.targetFrameRate : 0;
if (idleFps > 0) applyRate();
// Pending one-shot renders; disposal settles them rather than leave them
// Pending one-shot renders; disposal rejects them rather than leave them
// attached to a scene that will not render again.
const pendingRenders = new Set();
/** Resolves after the next drawn frame; rejects after `timeoutMs`, if given. */
/**
* Resolves after the next drawn frame; rejects after `timeoutMs`, if
* given, and once the renderer is destroyed.
*/
function nextPostRender({ timeoutMs } = {}) {
if (disposed) return Promise.resolve();
if (disposed) return Promise.reject(destroyedError());
return new Promise((resolve, reject) => {
let timer;
const settle = (error) => {
off();
clearTimeout(timer);
pendingRenders.delete(done);
pendingRenders.delete(settle);
if (error) reject(error);
else resolve();
};
const done = () => settle();
const off = scene.postRender.addEventListener(done);
pendingRenders.add(done);
const off = scene.postRender.addEventListener(() => settle());
pendingRenders.add(settle);
if (timeoutMs !== undefined)
timer = setTimeout(
() => settle(new Error('renderOnce timed out')),
@@ -380,9 +405,11 @@ export function createCesiumPorts(
*/
setTime(ms) {
const clock = widget.clock;
const time = Cesium.JulianDate.fromDate(new Date(ms));
scratchDate.setTime(ms);
const time = Cesium.JulianDate.fromDate(scratchDate, scratchJulian);
const changed = !Cesium.JulianDate.equals(clock.currentTime, time);
clock.currentTime = time;
// The clock keeps the time it is given; it ignores an equal one.
if (changed) clock.currentTime = Cesium.JulianDate.clone(time);
// In `preUpdate` the frame under way draws at it: Cesium stamps the
// frame with this object next.
if (stampTime) {
@@ -391,7 +418,7 @@ export function createCesiumPorts(
if (liveTick) liveTick.time = ms;
} else if (changed) frame.requestRender('time');
},
time: () => Cesium.JulianDate.toDate(widget.clock.currentTime).getTime(),
time: () => msOf(widget.clock.currentTime),
};
// --- Draw ------------------------------------------------------------------
@@ -401,6 +428,7 @@ export function createCesiumPorts(
report,
capabilities,
requestRender: (reason) => frame.requestRender(reason),
date,
});
const { port: draw, sets, tilesets } = drawPart;
@@ -454,6 +482,7 @@ export function createCesiumPorts(
: {}),
});
const cameraPort = cameraPart.port;
measureCameraChanged = cameraPart.measureChanged ?? null;
const effectsPart = createCesiumEffects(scene, {
capabilities,
frame,
@@ -482,10 +511,36 @@ export function createCesiumPorts(
credentials,
});
async function capture({ type = 'png' } = {}) {
scene.render(widget.clock.currentTime);
return new Promise((resolve) =>
scene.canvas.toBlob(resolve, `image/${type}`),
/**
* Whether the canvas still holds the last presented frame: a context that
* keeps its drawing buffer, once a frame has drawn. Otherwise the frame is
* drawn again to be read.
*/
const frameKept = () =>
rendered > 0 &&
webglContext(scene)?.getContextAttributes?.()?.preserveDrawingBuffer ===
true;
/**
* The last presented frame, encoded: `crop` in CSS pixels, `scale`
* relative to the canvas's CSS size, `quality` for JPEG. Read from the
* canvas as it is where it keeps that frame, so a capture draws nothing.
*/
async function capture({ type = 'png', quality, crop, scale = 1 } = {}) {
if (disposed) throw destroyedError();
if (!frameKept()) scene.render(widget.clock.currentTime);
const out = document.createElement('canvas').getContext('2d');
copyFrame(out, crop, scale);
return new Promise((resolve, reject) =>
out.canvas.toBlob(
(blob) => {
out.canvas.width = out.canvas.height = 0;
if (blob) resolve(blob);
else reject(new Error('the frame could not be encoded'));
},
`image/${type}`,
quality,
),
);
}
@@ -493,33 +548,24 @@ export function createCesiumPorts(
let reader = null;
/**
* The drawn frame's pixels, `crop` in CSS pixels and `scale` relative to
* the canvas's CSS size. Read straight off the canvas: the application
* and conformance widgets keep their drawing buffers, and a read right
* after a draw sees it either way.
* Draws the canvas's frame into the 2D context `into`, `crop` in CSS
* pixels and `scale` relative to the canvas's CSS size, sized to it.
* Returns whether there was a frame to draw.
*/
function readPixels({ crop, scale = 1 } = {}) {
function copyFrame(into, crop, scale = 1) {
const canvas = scene.canvas;
const cssWidth = canvas.clientWidth || canvas.width;
const cssHeight = canvas.clientHeight || canvas.height;
const rect = crop ?? { x: 0, y: 0, width: cssWidth, height: cssHeight };
const width = Math.max(1, Math.round(rect.width * scale));
const height = Math.max(1, Math.round(rect.height * scale));
const made =
reader ??
document
.createElement('canvas')
.getContext('2d', { willReadFrequently: true });
// Disposed ports keep nothing to free.
if (!disposed) reader = made;
made.canvas.width = width;
made.canvas.height = height;
// A canvas with no size has drawn nothing: the read is blank.
if (!canvas.width || !canvas.height)
return made.getImageData(0, 0, width, height);
into.canvas.width = width;
into.canvas.height = height;
// A canvas with no size has drawn nothing: the copy is blank.
if (!canvas.width || !canvas.height) return false;
const sx = canvas.width / cssWidth;
const sy = canvas.height / cssHeight;
made.drawImage(
into.drawImage(
canvas,
rect.x * sx,
rect.y * sy,
@@ -530,7 +576,25 @@ export function createCesiumPorts(
width,
height,
);
return made.getImageData(0, 0, width, height);
return true;
}
/**
* The drawn frame's pixels, `crop` in CSS pixels and `scale` relative to
* the canvas's CSS size. Read straight off the canvas: the application
* and conformance widgets keep their drawing buffers, and a read right
* after a draw sees it either way.
*/
function readPixels({ crop, scale = 1 } = {}) {
const made =
reader ??
document
.createElement('canvas')
.getContext('2d', { willReadFrequently: true });
// Disposed ports keep nothing to free.
if (!disposed) reader = made;
copyFrame(made, crop, scale);
return made.getImageData(0, 0, made.canvas.width, made.canvas.height);
}
// A release asked for whose globe trim waits for the next drawn frame.
@@ -779,7 +843,7 @@ export function createCesiumPorts(
effectsPart.dispose();
globePart.dispose();
qualityPart.dispose();
for (const done of [...pendingRenders]) done();
for (const settle of [...pendingRenders]) settle(destroyedError());
},
};
}
+3 -2
View File
@@ -373,6 +373,7 @@ export function createCesiumQuery({
},
pickRay(x, y) {
const ray = pickRayAt(scene, camera, x, y);
if (!ray) return null;
return { origin: ecef(ray.origin), direction: ecef(ray.direction) };
},
project(position) {
@@ -387,8 +388,8 @@ export function createCesiumQuery({
return s ? { x: s.x, y: s.y } : null;
},
projectMany(source, out) {
const p = new Cesium.Cartesian3();
const s = new Cesium.Cartesian2();
const p = projectedPoint;
const s = projectedWindow;
for (let i = 0, j = 0; i + 2 < source.length; i += 3, j += 2) {
p.x = source[i];
p.y = source[i + 1];
+19
View File
@@ -274,3 +274,22 @@ test('hiding the sets seen through answers as seeing through their items did, ne
ground.dispose();
markers.dispose();
});
test('a canvas with no size has no pick ray: null, not a throw', () => {
const viewer = fakeViewer();
const { scene } = viewer;
scene.mode = Cesium.SceneMode.SCENE3D;
scene.canvas = { clientWidth: 0, clientHeight: 0 };
Object.assign(scene.camera, {
frustum: new Cesium.PerspectiveFrustum({ fov: 1, aspectRatio: 1 }),
directionWC: new Cesium.Cartesian3(-1, 0, 0),
rightWC: new Cesium.Cartesian3(0, 1, 0),
upWC: new Cesium.Cartesian3(0, 0, 1),
});
const query = queryOf(viewer);
assert.equal(query.pickRay(0, 0), null);
scene.canvas = { clientWidth: 100, clientHeight: 100 };
const ray = query.pickRay(50, 50);
assert.deepEqual(ray.origin, { x: 2e7, y: 0, z: 0 });
assert.ok(Math.abs(ray.direction.x + 1) < 1e-9);
});
+2 -1
View File
@@ -35,7 +35,8 @@ export const pointerFeedOf = (renderer) => feeds.get(renderer) ?? null;
/**
* @param {{container: HTMLElement, msaa?: number, capabilities?: Iterable<string>,
* cameraController?: Function, now?: () => number}} options
* cameraController?: import('../contract/camera').CameraControllerFactory,
* now?: () => number}} options
* `capabilities` limits the renderer to those it lists; `cameraController`
* puts the camera port on that controller (`controlledCamera.js`); `now`
* is the clock its ticks and pointer events read (`performance.now` by
+54 -1
View File
@@ -4,6 +4,7 @@
*/
import goldens from '../goldens/camera.json' with { type: 'json' };
import {
AUSTIN,
CAMERA_SCRIPTS,
SCRIPT_VIEWPORT,
usesInput,
@@ -432,6 +433,58 @@ export function cameraChecks() {
r.destroy();
},
},
{
id: 'camera.changed.order',
port: 'camera',
title:
'`changed` is measured before preUpdate; a move made in preUpdate is reported on the next frame',
async run(h) {
const r = await fresh(h);
try {
const at = (height) => ({
destination: { ...AUSTIN, height },
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
});
r.camera.setView(at(2000));
const seen = [];
let move = null;
r.camera.on('changed', () => seen.push('changed'));
r.frame.on('preUpdate', () => {
seen.push('preUpdate');
if (move) r.camera.setView(move);
move = null;
});
// The first measure is the listener's starting point.
await h.frame(r);
await h.frame(r);
seen.length = 0;
r.camera.setView(at(8000));
await h.frame(r);
deepEqual(
seen,
['changed', 'preUpdate'],
'a move made before the frame is reported before preUpdate',
);
seen.length = 0;
move = at(2000);
await h.frame(r);
deepEqual(
seen,
['preUpdate'],
'a move made in preUpdate is not reported in its own frame',
);
seen.length = 0;
await h.frame(r);
deepEqual(
seen,
['changed', 'preUpdate'],
'it is reported as the next frame starts',
);
} finally {
r.destroy();
}
},
},
{
id: 'camera.follow',
port: 'camera',
@@ -786,7 +839,7 @@ export function cameraChecks() {
const r = await fresh(h);
const at = async (height, pitch = -Math.PI / 2) => {
r.camera.setView({
destination: { lon: -97.74, lat: 30.27, height },
destination: { ...AUSTIN, height },
orientation: { heading: 0, pitch, roll: 0 },
});
await h.frame(r);
+577 -5
View File
@@ -137,6 +137,27 @@ async function listenerRules(r, where, subscribe, fire) {
offError();
}
/**
* Every call a set takes after it is disposed: each must do nothing. `item`
* (null: none) is what `set` and `upsert` are given.
*/
function lateCalls(set, item) {
const list = item ? [item] : [];
set.set(list);
set.upsert(item ? [{ ...item, id: 'b' }] : []);
set.show = true;
set.setOptions({ pickable: true, drawOrder: 3 });
set.setColumns?.({
ids: ['c'],
positions: new Float64Array(
item?.pos ? [item.pos.x, item.pos.y, item.pos.z] : [0, 0, 0],
),
});
set.remove(['missing']);
set.upsert(list);
set.dispose();
}
/** A check over a fresh renderer, destroyed afterwards. */
/**
* The sky with the renderer's look off (`SkySettings`): what is drawn shows
@@ -774,6 +795,130 @@ export function portChecks() {
b.dispose();
},
),
check(
'draw.afterDispose',
'a disposed set draws nothing, whatever is called on it after',
async (h, r) => {
await overAustin(h, r);
const pos = h.toEcef({ ...AUSTIN, height: 0 });
// A live set beside them, so the picks below can find something.
const live = r.draw.points({ id: 'conf:kept' });
live.set([{ id: 'kept', pos, pixelSize: 8, color: '#0f0' }]);
const point = { id: 'a', pos, pixelSize: 30, color: '#f00' };
const icon = { id: 'a', pos, image: DOT, size: [32, 32] };
const gone = [
[r.draw.points({ id: 'conf:gone:points' }), point],
[r.draw.icons({ id: 'conf:gone:icons' }), icon],
];
for (const [kind, capability] of SET_KINDS)
if (!capability || r.capabilities.has(capability))
gone.push([r.draw[kind]({ id: `conf:gone:${kind}:empty` }), null]);
for (const [set] of gone) set.dispose();
for (const [set, item] of gone) lateCalls(set, item);
await drawn(h, r);
await settled(r);
const s = r.query.project(pos);
ok(s, 'the point projects');
const hits = r.query.drillPick(s.x, s.y);
ok(
hits.some((hit) => hit.set === 'conf:kept'),
'the live set is picked',
);
ok(
hits.every((hit) => !String(hit.set).startsWith('conf:gone')),
'nothing of a disposed set is picked',
);
ok(
gone.every(([set]) => set.show === false || set.show === true),
'show still reads',
);
// Its id is free; the old handle does not reach the new set.
const again = r.draw.points({ id: 'conf:gone:points' });
lateCalls(gone[0][0], point);
equal(again.size(), 0, 'the newer set under the id is untouched');
again.dispose();
live.dispose();
},
),
{
id: 'renderer.afterDestroy',
port: 'renderer',
title: 'once the renderer is destroyed, its sets and new ones do nothing',
async run(h) {
const r = await fresh(h);
const sets = [];
try {
await overAustin(h, r);
for (const [kind, capability] of SET_KINDS)
if (!capability || r.capabilities.has(capability))
sets.push(r.draw[kind]({ id: `conf:destroyed:${kind}` }));
} finally {
r.destroy();
}
const pos = h.toEcef({ ...AUSTIN, height: 0 });
const point = { id: 'a', pos, pixelSize: 30, color: '#f00' };
const late = r.draw.points({ id: 'conf:destroyed:late' });
// What is set on them is not kept, so nothing is drawn of it.
for (const set of [sets[1], late]) {
set.set([point]);
set.upsert([{ ...point, id: 'b' }]);
equal(set.size(), 0, `${set.id} keeps nothing set after destroy`);
}
for (const set of sets) lateCalls(set, set === sets[1] ? point : null);
lateCalls(late, point);
for (const set of [...sets, late]) set.dispose();
},
},
{
id: 'renderer.afterDestroy.frames',
port: 'renderer',
title:
'once the renderer is destroyed, renderOnce and capture reject, and a renderOnce waiting rejects too',
async run(h) {
const r = await fresh(h);
let waiting;
try {
await overAustin(h, r);
// Suspended, the loop draws nothing: the renderOnce waits.
r.frame.suspend(true);
waiting = r.frame.renderOnce().then(
() => 'resolved',
(error) => error,
);
} finally {
r.destroy();
}
const destroyed = (error, what) =>
ok(
error instanceof Error && /destroyed/.test(error.message),
`${what} rejects saying the renderer is destroyed (${error})`,
);
const settledIn = (promise) =>
Promise.race([
promise,
new Promise((resolve) => setTimeout(() => resolve('hung'), 2000)),
]);
destroyed(await settledIn(waiting), 'a renderOnce waiting at destroy');
destroyed(
await settledIn(
r.frame.renderOnce().then(
() => 'resolved',
(error) => error,
),
),
'renderOnce',
);
destroyed(
await settledIn(
r.capture().then(
() => 'resolved',
(error) => error,
),
),
'capture',
);
},
},
check(
'draw.pick',
'a drawn icon is picked under its projection with its set, id and meta',
@@ -1842,11 +1987,11 @@ export function portChecks() {
[kind, image],
[`atlas-${kind}`, { atlas: 'conf:images', slot: kind }],
]);
// Two sets: still icons, and icons that recede (drawn as moving
// ones are, where a renderer draws them apart).
// Two sets: still icons, and a set that recedes (drawn as moving
// icons are, where a renderer draws them apart).
const rows = [
['still', {}, AUSTIN.lat + 0.004],
['receding', { recede: true }, AUSTIN.lat - 0.004],
['receding', { recede: {} }, AUSTIN.lat - 0.004],
];
const at = (i, lat) =>
h.toEcef({
@@ -1855,14 +2000,13 @@ export function portChecks() {
height: 0,
});
const sets = rows.map(([name, extra, lat]) => {
const set = r.draw.icons({ id: `conf:images-${name}` });
const set = r.draw.icons({ id: `conf:images-${name}`, ...extra });
set.set(
images.map(([id, image], i) => ({
id,
pos: at(i, lat),
image,
size: [20, 20],
...extra,
})),
);
return set;
@@ -1884,6 +2028,105 @@ export function portChecks() {
for (const set of sets) set.dispose();
},
),
check(
'draw.sets.recede',
'icon and model sets take `recede` and change it live: their items, near the eye, are drawn and picked whether the set recedes or not',
async (h, r) => {
await overAustin(h, r);
const pos = h.toEcef({ ...AUSTIN, height: 0 });
const icons = r.draw.icons({ id: 'conf:recede-icons', recede: {} });
icons.set([{ id: 'one', pos, image: DOT, size: [24, 24], focus: 0.5 }]);
const models = r.draw.models?.({
id: 'conf:recede-models',
recede: { alphaFloor: 0.5 },
});
try {
await drawn(h, r);
await settled(r);
const s = r.query.project(pos);
ok(s, 'the icon projects');
const picked = () => r.query.pick(s.x, s.y);
deepEqual(
[picked()?.set, picked()?.id],
['conf:recede-icons', 'one'],
'a receding icon near the eye is drawn and picked',
);
for (const recede of [null, { scaleFloor: 0.6 }, {}]) {
icons.setOptions({ recede });
models?.setOptions({ recede });
await drawn(h, r);
equal(
picked()?.id,
'one',
`drawn and picked with recede ${JSON.stringify(recede)}`,
);
}
} finally {
icons.dispose();
models?.dispose();
}
},
),
check(
'draw.sets.recede.models',
'a model set that recedes composes each model’s focus as `RecedeSpec` says, and takes a new `recede` live: near the eye a model at focus 1 draws at full strength, at focus 0.25 faded, and a combined floor of 1 brings it back',
async (h, r) => {
if (!h.assets?.model) return { skip: 'no model asset in this harness' };
await overAustin(h, r);
const set = r.draw.models({ id: 'conf:recede-models', recede: {} });
const ready = [];
set.on('ready', (id) => ready.push(id));
const pos = h.toEcef({ ...AUSTIN, height: 0 });
const model = (focus) => ({
id: 'm',
pos,
url: h.assets.model,
orientation: { heading: 0, pitch: 0, roll: 0 },
minPixelSize: 160,
environmentMap: false,
shading: 'unlit',
tint: '#ff0000',
colorBlend: { mode: 'replace' },
focus,
});
try {
set.set([model(1)]);
for (let i = 0; i < 600 && !ready.length; i++) await drawn(h, r, 1);
deepEqual(ready, ['m'], 'ready');
const s = r.query.project(pos);
// How many pixels of a patch at the model's centre are red.
const red = async () => {
await drawn(h, r, 3);
await settled(r);
r.frame.renderNow();
const image = r.readPixels({
crop: {
x: Math.round(s.x) - 4,
y: Math.round(s.y) - 4,
width: 9,
height: 9,
},
});
let n = 0;
for (let i = 0; i < image.data.length; i += 4) {
const [r0, g, b] = image.data.subarray(i, i + 3);
if (r0 > 180 && g < 70 && b < 70) n++;
}
return n;
};
ok((await red()) >= 40, 'near the eye, focus 1: full strength');
set.upsert([model(0.25)]);
ok((await red()) < 10, 'focus 0.25 fades it');
set.setOptions({ recede: { combinedAlphaFloor: 1 } });
ok((await red()) >= 40, 'a combined floor of 1 holds it, live');
equal(r.query.pick(s.x, s.y)?.set, set.id, 'and it is picked');
deepEqual(ready, ['m'], 'without loading again');
} finally {
set.dispose();
}
},
{ capability: 'models', bareSky: true },
),
clusterCheck(false),
clusterCheck(true),
check(
@@ -4136,6 +4379,7 @@ export function portChecks() {
const seen = [];
r.input.on('click', () => seen.push('ambient'));
const lease = r.input.claimPointer('tool');
equal(lease.owner, 'tool', 'the lease names its owner');
for (const type of POINTER_TYPES) await h.pointer(r, type, 640, 360);
deepEqual(ambient, ['move', 'up'], 'ambient under a lease');
seen.length = 0;
@@ -4155,6 +4399,61 @@ export function portChecks() {
deepEqual(seen, ['ambient'], 'ambient again');
},
),
check(
'input.lease.lost',
'the newest claim takes over: the lease it ends is told once, after the new one holds the pointer, and its late release frees nothing; a throwing onLost is reported',
async (h, r) => {
if (!h.pointer) return { skip: 'no pointer in this harness' };
const told = [];
// What the ended lease's holder sees from inside its `onLost`.
let inside = null;
const a = r.input.claimPointer('a', {
onLost: () => {
told.push('a');
inside = { free: r.input.isPointerFree(), current: a.current };
},
});
const heard = [];
r.input.on('down', () => heard.push('a'), { lease: a });
const b = r.input.claimPointer('b', { onLost: () => told.push('b') });
r.input.on('down', () => heard.push('b'), { lease: b });
deepEqual(told, ['a'], 'the ended lease is told');
deepEqual(
inside,
{ free: false, current: false },
'inside onLost the new lease already holds the pointer and the old one has ended',
);
ok(!a.current && b.current, 'the newest lease holds the pointer');
await h.pointer(r, 'down', 640, 360);
await h.pointer(r, 'up', 640, 360);
deepEqual(heard, ['b'], 'the newest holder gets the press');
a.release();
ok(b.current, "the ended lease's release frees nothing");
ok(!r.input.isPointerFree(), 'still taken');
deepEqual(told, ['a'], 'told once');
b.release();
deepEqual(told, ['a'], 'a lease its holder releases is not told');
ok(r.input.isPointerFree(), 'free again');
const errors = [];
r.on('error', (e) => errors.push(e));
r.input.claimPointer('c', {
onLost: () => {
throw new Error('conformance onLost');
},
});
const d = r.input.claimPointer('d');
equal(errors.length, 1, 'a throwing onLost is reported');
ok(d.current, 'and the new lease holds the pointer regardless');
heard.length = 0;
r.input.on('down', () => heard.push('d'), { lease: d });
await h.pointer(r, 'down', 640, 360);
await h.pointer(r, 'up', 640, 360);
deepEqual(heard, ['d'], 'and gets the press');
d.release();
ok(r.input.isPointerFree(), 'free at the end');
},
),
check(
'input.lease.grab',
'a lease with grab takes only the presses it grabs; wheel and the rest stay free',
@@ -5377,6 +5676,279 @@ fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
);
},
),
check(
'renderer.capture',
'capture encodes the last drawn frame as asked: cropped, scaled, its type and quality, drawing none of its own when the frame is kept',
async (h, r) => {
if (h.pixels === false || typeof createImageBitmap !== 'function')
return { skip: 'no encoded pixels to read' };
await overAustin(h, r);
const set = r.draw.points({ id: 'conf:capture' });
const pos = h.toEcef({ ...AUSTIN, height: 0 });
set.set([{ id: 'p', pos, pixelSize: 24, color: '#ff0000' }]);
await drawn(h, r);
await settled(r);
const size = async (blob) => {
const bitmap = await createImageBitmap(blob);
const wh = [bitmap.width, bitmap.height];
bitmap.close();
return wh;
};
let frames = 0;
const off = r.frame.on('postRender', () => (frames += 1));
const full = await r.capture();
equal(full.type, 'image/png', 'a PNG by default');
deepEqual(
await size(full),
[SCRIPT_VIEWPORT.width, SCRIPT_VIEWPORT.height],
'the canvas’s CSS size',
);
const crop = { x: 10, y: 20, width: 40, height: 30 };
deepEqual(
await size(await r.capture({ crop, scale: 0.5 })),
[20, 15],
'a crop, scaled',
);
deepEqual(
await size(await r.capture({ scale: 0.25 })),
[SCRIPT_VIEWPORT.width / 4, SCRIPT_VIEWPORT.height / 4],
'scaled',
);
const low = await r.capture({ type: 'jpeg', quality: 0.05 });
const high = await r.capture({ type: 'jpeg', quality: 1 });
equal(low.type, 'image/jpeg', 'a JPEG when asked');
ok(low.size < high.size, 'a lower quality encodes smaller');
// What a crop over the point shows is the point, as drawn.
const s = r.query.project(pos);
const around = { x: s.x - 4, y: s.y - 4, width: 8, height: 8 };
const bitmap = await createImageBitmap(
await r.capture({ crop: around }),
);
const canvas = new OffscreenCanvas(8, 8);
const g = canvas.getContext('2d');
g.drawImage(bitmap, 0, 0);
bitmap.close();
const [red, green, blue] = g.getImageData(4, 4, 1, 1).data;
ok(
red > 200 && green < 60 && blue < 60,
`the point is in the crop (${red}, ${green}, ${blue})`,
);
off();
// Where the renderer keeps its frame it reads it; otherwise it may
// draw again to read.
const gl =
r.canvas.getContext?.('webgl2') ?? r.canvas.getContext?.('webgl');
if (gl?.getContextAttributes?.()?.preserveDrawingBuffer === true)
equal(frames, 0, 'no frame drawn for a capture of a kept frame');
set.dispose();
},
),
check(
'renderer.resize',
'resize follows the container: the lens and the frame read take its new size',
async (h, r) => {
if (!h.resizeContainer)
return { skip: 'the harness cannot resize the container' };
await overAustin(h, r);
// A new aspect too, so a lens left as it was shows.
const size = { width: 480, height: 320 };
await h.resizeContainer(r, size);
r.resize();
await drawn(h, r);
near(
r.camera.pose().aspectRatio,
size.width / size.height,
1e-6,
'the aspect is the container’s',
);
const full = r.readPixels({ scale: 0.1 });
deepEqual(
[full.width, full.height],
[size.width / 10, size.height / 10],
'the frame is the container’s size',
);
},
),
check(
'frame.setTargetFps',
'setTargetFps caps the loop; diagnostics say the cap, 0 the display rate',
(h, r) => {
r.frame.setTargetFps(24);
equal(r.frame.diagnostics().targetFps, 24, 'capped');
r.frame.setTargetFps(0);
equal(r.frame.diagnostics().targetFps, 0, 'the display’s rate');
},
),
check(
'globe.setTerrain',
'setTerrain to the ellipsoid, exaggerated or not, resolves and leaves the globe settling',
async (h, r) => {
await r.globe.setTerrain({ kind: 'ellipsoid', exaggeration: 2 });
await r.globe.setTerrain({ kind: 'ellipsoid' });
await overAustin(h, r);
await drawn(h, r);
const result = await r.whenSettled({ timeoutMs: 10_000 });
ok(
!result.blockers.includes('terrain'),
`the ellipsoid has nothing to load (${result.blockers})`,
);
},
),
check(
'globe.setPhotoreal',
'setPhotoreal(null) turns photoreal off: its status is route none',
async (h, r) => {
const status = await r.globe.setPhotoreal(null);
equal(status.route, 'none', 'off');
},
),
check(
'globe.progress',
'progress listeners hear counts of what is loading, and their Off ends them',
async (h, r) => {
const heard = [];
const off = r.globe.on('progress', (p) => heard.push(p));
equal(typeof off, 'function', 'an Off');
await overAustin(h, r);
// Something to load: an image over the view.
const over = (url) =>
r.globe.imagery.add({
kind: 'single-image',
url,
rectangle: {
west: AUSTIN.lon - 1,
south: AUSTIN.lat - 1,
east: AUSTIN.lon + 1,
north: AUSTIN.lat + 1,
},
});
const layer = over(PIXEL_PNGS[0]);
// Frames until the load is heard, or a while passes: a renderer may
// first say nothing loads, before it starts on the image. The image
// loads in time of its own, so each frame lets some pass.
const loading = (p) =>
p.tilesPending + p.imageryPending + p.terrainPending > 0;
const until = Date.now() + 10_000;
for (let i = 0; !heard.some(loading) && i < 600; i++) {
if (Date.now() > until) break;
await drawn(h, r, 1);
await new Promise((resolve) => setTimeout(resolve, 5));
}
ok(heard.some(loading), 'a load is heard');
for (const p of heard)
for (const key of [
'tilesPending',
'imageryPending',
'terrainPending',
])
ok(p[key] >= 0, `${key} is a count (${p[key]})`);
off();
const before = heard.length;
layer.remove();
const again = over(PIXEL_PNGS[1]);
await overAustin(h, r, 9000);
await drawn(h, r);
equal(heard.length, before, 'none after its Off');
again.remove();
},
),
check(
'effects.setStyleParams',
'a style’s parameters change what it draws',
async (h, r) => {
if (h.pixels === false) return { skip: 'no pixels to read' };
const off = r.effects.defineStyle({
id: 'conf:fill',
params: [{ key: 'red', min: 0, max: 1, default: 0 }],
animated: false,
shader: {
glsl: `uniform float red;
void main() {
out_FragColor = vec4(red, 0.0, 0.0, 1.0);
}`,
wgsl: `@fragment
fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
return vec4f(params.red, 0.0, 0.0, 1.0);
}`,
},
});
try {
await overAustin(h, r);
// Below the eye, in the units `readPixels` crops in.
const below = r.query.project(h.toEcef({ ...AUSTIN, height: 0 }));
ok(below, 'the ground below projects');
const red = async () => {
await settled(r);
r.frame.renderNow();
const px = r.readPixels({
crop: {
x: Math.round(below.x),
y: Math.round(below.y),
width: 1,
height: 1,
},
});
return px.data[0];
};
r.effects.setStyleIntensity('conf:fill', 1);
r.effects.setStyle('conf:fill', { red: 0 });
ok((await red()) < 30, 'its default draws black');
r.effects.setStyleParams('conf:fill', { red: 1 });
ok((await red()) > 225, 'red once its parameter is 1');
r.effects.setStyle(null);
r.effects.setStyleIntensity('conf:fill', 0);
} finally {
off();
}
},
{ capability: 'styles' },
),
check(
'effects.bloom',
'bloom on lists its pass, off drops it; the strength is kept',
(h, r) => {
const passes = () => r.effects.diagnostics().passes;
r.effects.bloom({ enabled: true, strength: 0.4 });
ok(passes().includes('bloom'), 'drawn while on');
r.effects.bloom({ enabled: false });
ok(!passes().includes('bloom'), 'not while off');
r.effects.bloom({ enabled: true });
ok(passes().includes('bloom'), 'on again at the kept strength');
r.effects.bloom({ enabled: false });
},
{ capability: 'bloom' },
),
check(
'effects.sharpen',
'sharpen on lists its pass, off drops it',
(h, r) => {
const passes = () => r.effects.diagnostics().passes;
r.effects.sharpen({ enabled: true, amount: 0.5 });
ok(passes().includes('sharpen'), 'drawn while on');
r.effects.sharpen({ enabled: false });
ok(!passes().includes('sharpen'), 'not while off');
},
{ capability: 'sharpen' },
),
check(
'quality.probe',
'probe says the device, the browser and the knobs',
(h, r) => {
const probe = r.quality.probe();
ok(
['webgl1', 'webgl2', 'webgpu'].includes(probe.device.backend),
`a backend (${probe.device.backend})`,
);
ok(probe.device.maxTextureSize > 0, 'a texture size');
ok(probe.browser.devicePixelRatio > 0, 'a pixel ratio');
equal(typeof probe.browser.touchOnly, 'boolean', 'touch only or not');
deepEqual(
probe.knobs.map((k) => k.key),
r.quality.knobs().map((k) => k.key),
'the knobs, as knobs() lists them',
);
},
),
check(
'renderer.releaseUnused',
'releaseUnused keeps what is in view drawn and picked',
+255
View File
@@ -0,0 +1,255 @@
/**
* The renderer conformance suite (`index.js`): every check run against a
* renderer through the contract alone, in Node or in a browser page.
*/
import type {
CameraPose,
Ecef,
Flight,
Renderer,
ScreenXY,
} from '../contract/index';
export interface ConformanceTolerance {
/** Positions and heights. */
metres: number;
/** Unit vectors (direction, up, right). */
unit: number;
/** Heading, pitch and roll. */
radians: number;
/** Screen positions. */
pixels: number;
/** `changed` events per script. */
changedCount: number;
}
/** How to make the renderer under test and drive its clock. */
export interface ConformanceHarness {
name: string;
/** Null when it cannot make a renderer with fewer capabilities. */
create(options: {
viewport: { width: number; height: number };
capabilities?: string[];
}): Promise<Renderer | null>;
frame(r: Renderer): void | Promise<void>;
now(r: Renderer): number;
toEcef(p: { lon: number; lat: number; height?: number }): Ecef;
tolerance: ConformanceTolerance;
/** Flight paths compared frame by frame, or only where flights end. */
flightPaths: 'trace' | 'endpoints';
/** Synthetic input. */
pointer?(
r: Renderer,
type: string,
x: number,
y: number,
extra?: object,
): void | Promise<void>;
/** False when the renderer draws only models into its pixels. */
pixels?: boolean;
/** The camera moves on pointer input sent through `pointer`. */
cameraInput?: boolean;
scriptHeights?(
r: Renderer,
fn: (
point: { lon: number; lat: number },
against?: string,
) => number | null,
): void;
/** Epoch ms a `live` motion clock reads. */
wallTime?(r: Renderer): number;
/**
* Sizes the element the renderer fills, in CSS pixels, for the check that
* `resize` follows it. Without it, that check is skipped.
*/
resizeContainer?(
r: Renderer,
size: { width: number; height: number },
): void | Promise<void>;
assets?: {
model?: string;
missingModel?: string;
modelBytes?: () => Promise<Uint8Array>;
};
}
export interface ConformanceCheck {
id: string;
port: string;
title: string;
run(h: ConformanceHarness): Promise<{ skip: string } | void>;
}
export interface ConformanceResult {
id: string;
port: string;
title: string;
status: 'pass' | 'fail' | 'skip';
detail?: string;
ms: number;
}
export interface ConformanceReport {
harness: string;
passed: number;
failed: number;
skipped: number;
results: ConformanceResult[];
}
/** A camera script: the steps a trace check runs. */
export interface CameraScript {
name: string;
steps: object[];
}
/** A camera script's pointer event. */
export interface ScriptPointer {
type: 'down' | 'move' | 'up' | 'wheel';
position: ScreenXY;
endPosition?: ScreenXY;
button: 0 | 1 | 2;
modifiers: { shift: boolean; ctrl: boolean; alt: boolean; meta: boolean };
wheel?: { deltaY: number; deltaMode: number };
}
/** What a camera script drives. */
export interface CameraDriver {
command(name: string, args: unknown[]): Flight | void;
frame(): void | Promise<void>;
/** Counts `changed`; returns a reader. */
listen(threshold: number): () => number;
pose(): CameraPose;
project(position: Ecef): ScreenXY | null;
pickEllipsoid(screen: ScreenXY): Ecef | null;
pickRay(screen: ScreenXY): object;
occluded(position: Ecef): boolean;
flying(): boolean;
toEcef(position: object): Ecef;
pointer?(ev: ScriptPointer): void | Promise<void>;
}
/** A reference scene, built from contract calls only. */
export interface ReferenceScene {
id: string;
family: string;
capability: string | null;
needs?: string[];
build(r: Renderer, ctx: object): Promise<() => void>;
views: Array<{ name: string; view: object }>;
}
export const DEFAULT_TOLERANCE: Readonly<ConformanceTolerance>;
/** Every check, in run order. */
export function conformanceChecks(): ConformanceCheck[];
export function runConformance(
harness: ConformanceHarness,
options?: { only?: (id: string) => boolean },
): Promise<ConformanceReport>;
export const CAMERA_SCRIPTS: ReadonlyArray<CameraScript>;
/** The viewport every script runs in, CSS pixels. */
export const SCRIPT_VIEWPORT: Readonly<{ width: number; height: number }>;
/** Whether a script moves the camera by user input. */
export function usesInput(script: CameraScript): boolean;
export const REFERENCE_SCENES: ReadonlyArray<ReferenceScene>;
/** The city scene's poses from orbit down to the street. */
export const CALIBRATION_PATH: Readonly<{
scene: string;
poses: ReadonlyArray<object>;
}>;
/** Why a renderer and context cannot draw a scene; null when they can. */
export function sceneSupport(
scene: ReferenceScene,
renderer: Renderer,
ctx?: { assets?: Record<string, unknown> },
): string | null;
export const VISUAL_TOLERANCE: Readonly<{
threshold: number;
maxSolidPixels: number;
maxMismatchedPixels: number;
}>;
type Pixels = { width: number; height: number; data: Uint8ClampedArray };
export function compareImages(
actual: Pixels,
expected: Pixels,
options?: {
threshold?: number;
maxSolidPixels?: number;
maxMismatchedPixels?: number;
diff?: Uint8ClampedArray;
},
): {
match: boolean;
diffPixels: number;
diffFraction: number;
solidPixels: number;
mismatchedPixels: number;
reason?: string;
};
/** Draws a scene, then each of its views once the renderer has settled. */
export function drawScene(
renderer: Renderer,
scene: ReferenceScene,
ctx: { toEcef: Function; assets?: object },
onView: (
view: { name: string },
capture: Blob,
settle: { state: string; blockers: string[] },
) => void | Promise<void>,
): Promise<void>;
/** The file a view's reference image is stored under. */
export function referenceName(sceneId: string, viewName: string): string;
export function contractDriver(
renderer: Renderer,
hooks: {
frame: () => void | Promise<void>;
toEcef: (p: object) => Ecef;
pointer?: (
type: string,
x: number,
y: number,
extra: object,
) => void | Promise<void>;
},
): CameraDriver;
export function runCameraScript(
driver: CameraDriver,
script: CameraScript,
): Promise<{ records: object[]; flights: object[] }>;
/** The parts of a pose a trace keeps. */
export function tracePose(pose: CameraPose): object;
/** The suite's assertions. */
export namespace expect {
class ConformanceError extends Error {}
function ok(value: unknown, message: string): void;
function equal(actual: unknown, expected: unknown, message: string): void;
function deepEqual(actual: unknown, expected: unknown, message: string): void;
function near(
actual: number,
expected: number,
tolerance: number,
message: string,
): void;
function nearAngle(
actual: number,
expected: number,
tolerance: number,
message: string,
): void;
function nearVec(
actual: { x: number; y: number; z: number },
expected: { x: number; y: number; z: number },
tolerance: number,
message: string,
): void;
function rejects(
promiseOrFn: Promise<unknown> | (() => Promise<unknown>),
message: string,
): Promise<void>;
function throws(fn: () => unknown, message: string): void;
}
+3 -1
View File
@@ -21,7 +21,8 @@
* Optional harness members widen what is checked: `pointer(r, type, x, y)`
* (synthetic input; with `cameraInput`, the camera scripts' drags and
* wheels too), `scriptHeights(r, fn)` (heights from a function),
* `wallTime(r)` (the wall clock a `live` motion clock reads), `pixels`
* `wallTime(r)` (the wall clock a `live` motion clock reads),
* `resizeContainer(r, size)` (sizes the element the renderer fills), `pixels`
* (false skips the checks that read drawn pixels),
* `assets.model` (a glTF URL). `create` may return null when it cannot
* make a renderer with fewer capabilities; those checks are then skipped.
@@ -55,6 +56,7 @@ import { portChecks } from './checks/ports.js';
* @property {boolean} [cameraInput] The renderer's camera moves on pointer input sent through `pointer` (its own gestures, or a camera controller's): the camera scripts with `input` steps run.
* @property {(r: object, fn: (point: {lon: number, lat: number}, against?: string) => number|null) => void} [scriptHeights]
* @property {(r: object) => number} [wallTime] Epoch ms the renderer's `live` motion clock reads.
* @property {(r: object, size: {width: number, height: number}) => void|Promise<void>} [resizeContainer] Sizes the element the renderer fills, in CSS pixels, for the check that `resize` follows it.
* @property {{model?: string, missingModel?: string, modelBytes?: () => Promise<Uint8Array>}} [assets] `modelBytes`: the bytes of a model, for the check that a model given its bytes never fetches its url.
*/
+77 -2
View File
@@ -30,12 +30,15 @@ import type {
GeoRect,
HeadingPitchRange,
HeadingPitchRoll,
LonLat,
Off,
Position,
Release,
Sphere,
Vec3,
} from './common';
import type { PointerEv, PointerEventType } from './input';
import type { HeightOptions } from './query';
export interface CameraPose {
lon: number;
@@ -297,6 +300,7 @@ export interface CameraPort {
* reading is valid only for the tick it is read in. `setView` places a
* world pose and keeps this frame, so code can re-express an offset in
* the follow's own frame, whichever frame that is, and place the eye there.
* Read-only, handed again while it holds, as `matrices()` are.
*/
followFrame?(): Float64Array;
readonly controls: CameraControls;
@@ -313,7 +317,78 @@ export interface CameraPort {
* Column-major, right-handed: `view` takes ECEF to eye space (absolute,
* not eye-relative); `projection` takes eye space to clip space with depth
* in [-1, 1]. A renderer with an infinite far plane returns the
* infinite-far form, and `pose().far` is `Infinity`.
* infinite-far form, and `pose().far` is `Infinity`. Read-only: a
* renderer may hand the same arrays again while they hold, and hands new
* ones once they change (one kept from an earlier frame stays as it was).
*/
matrices(): { view: Float64Array; projection: Float64Array };
matrices(): {
readonly view: Float64Array;
readonly projection: Float64Array;
};
}
/** A camera controller's frame tick: the loop's clock and the scene time. */
export interface CameraTick {
/** The loop's clock, ms, on the `performance.now()` timeline. */
now: number;
/** Scene time, epoch ms. */
time: number;
}
/** The eye a camera controller writes, in ECEF; `fovy` vertical, radians. */
export interface ControllerEye {
position: Ecef;
direction: Ecef;
up: Ecef;
right: Ecef;
fovy: number;
}
/**
* The camera a renderer hands a camera controller: it reads and writes the
* eye exactly, says the canvas's CSS size, and lends the query, draw and
* frame ports' members the controller needs.
*/
export interface NativeCamera {
pose(): {
position: Ecef;
direction: Ecef;
up: Ecef;
near: number;
far: number;
};
setPose(eye: ControllerEye): void;
viewport(): { width: number; height: number };
sampleHeightNow?(point: LonLat, options?: HeightOptions): number | null;
pickPosition?(x: number, y: number): Ecef | null;
/** Where the draw port draws an item it moves itself. */
itemPosition?(
item: { set: string; id: string | number },
aheadMs?: number,
): Ecef | null;
requestRender?(reason: string): void;
}
/**
* A camera controller, as an application hands one to a renderer without a
* camera of its own (or in place of its own): given the native camera, the
* input port's pointer events and the page's keys, it makes the camera port.
* The renderer runs `frame.beforeUpdate` before its `preUpdate` listeners
* and `frame.afterUpdate` after them, each tick, drawn or not.
*/
export type CameraControllerFactory = (options: {
native: NativeCamera;
input?: {
on(type: PointerEventType, cb: (event: PointerEv) => void): Off;
};
report?: (error: unknown) => void;
keyTarget?: EventTarget;
thresholds?: boolean;
}) => {
port: CameraPort;
frame: {
beforeUpdate(tick: CameraTick): void;
afterUpdate(tick: CameraTick): void;
};
destroy(): void;
};
+6 -1
View File
@@ -121,7 +121,12 @@ export type Off = () => void;
/** Gives back a hold. Calling it twice is harmless. */
export type Release = () => void;
/** A handle on something the renderer draws. */
/**
* A handle on something the renderer draws. Once disposed, and once the
* renderer is destroyed, it does nothing: its methods neither draw nor
* throw, and a set or field asked for after destroy is such a handle.
* Disposing it again is harmless.
*/
export interface Handle {
show: boolean;
dispose(): void;
+44 -3
View File
@@ -55,6 +55,35 @@ export interface ClusterSpec {
icon?: (count: number) => ImageRef;
}
/**
* `recede`: a set's items shrink and fade toward the globe's limb, as
* `src/render/recession.js` (exported as `render/recession`) works it out,
* so the renderer draws exactly those factors. Nearer than `startLimbRatio` of
* the eye's distance to the limb an item is drawn as it is; from there it
* eases (smoothstep) to `scaleFloor` times its scale and `alphaFloor` haze
* at the limb and beyond. All of it eases back to nothing as the eye climbs
* from `globeViewBlendStartM` to `globeViewBlendEndM` above the ellipsoid.
* An item draws at its alpha times `max(combinedAlphaFloor, focus × haze)`,
* that floor holding even while nothing recedes. Icons shrink and fade;
* models only fade. Every parameter is optional, the defaults in brackets.
*/
export interface RecedeSpec {
/** Where receding starts, as a share of the limb's distance [0.5]. */
startLimbRatio?: number;
/** The scale an item reaches at the limb [0.45]; icons only. */
scaleFloor?: number;
/** The haze an item reaches at the limb [0.35]. */
alphaFloor?: number;
/** The least `focus × haze` draws with [0.2]. */
combinedAlphaFloor?: number;
/** Eye height above the ellipsoid where receding starts to ease off, metres [3,500,000]. */
globeViewBlendStartM?: number;
/** Eye height from which nothing recedes, metres [4,500,000]. */
globeViewBlendEndM?: number;
/** The radius of the sphere the limb is measured on, metres [6,378,137]. */
earthRadiusM?: number;
}
/** Options of a whole set; the mutable ones can change later through `setOptions`. */
export interface SetSpec {
/**
@@ -66,6 +95,11 @@ export interface SetSpec {
horizonCull?: boolean;
/** `cluster`: screen-space clustering (icons only; see `ClusterSpec`). */
cluster?: ClusterSpec | null;
/**
* Icons and models: the items recede toward the limb (`RecedeSpec`; `{}`
* for the defaults). Omitted or `null`: they do not. Changes live.
*/
recede?: RecedeSpec | null;
/**
* How the set's items blend with what is drawn. Omitted: opaque parts
* opaque with depth writes, items with alpha under 1 alpha-blended without
@@ -212,9 +246,10 @@ export interface IconItem extends Placed {
imageLod?: { near: ImageRef; switchPx: number };
/** A larger invisible pick target, CSS pixels. */
pickProxy?: { size: [width: number, height: number] };
/** Fade and shrink toward the globe's limb. */
recede?: boolean;
/** Emphasis factor for a focused item, 1 = none. */
/**
* Emphasis for a focused item, 0..1, 1 = none: the alpha is multiplied by
* it (in a set that recedes, as `RecedeSpec` says).
*/
focus?: number;
}
@@ -409,6 +444,12 @@ export interface ModelItem extends Placed {
* would not hide what lies below it). Can change live.
*/
clip?: 'belowOrigin';
/**
* Emphasis for a focused model, 0..1, 1 = none: the tint's alpha is
* multiplied by it (in a set that recedes, as `RecedeSpec` says). Can
* change live.
*/
focus?: number;
}
/** A plane showing an image, a video or a canvas. */
+5 -1
View File
@@ -84,7 +84,11 @@ export interface FramePort {
* the animation frames the loop runs on.
*/
renderNow(options?: { ifDue?: boolean }): void;
/** Resolves after the next frame has been drawn and presented. */
/**
* Resolves after the next frame has been drawn and presented. Once the
* renderer is destroyed it rejects with a "renderer destroyed" error, and
* so does one still waiting when the renderer is destroyed.
*/
renderOnce(options?: { timeoutMs?: number }): Promise<void>;
/** Cap the loop's rate; 0 is the display's rate. */
setTargetFps(fps: number): void;
+11 -2
View File
@@ -93,7 +93,12 @@ export interface InputPort {
options?: { lease?: Lease | (() => Lease | null) },
): Off;
/**
* Take the pointer for a tool. A new claim ends the previous lease.
* Take the pointer for a tool. The newest claim takes over: it ends the
* previous lease, whose `onLost` is called once, after the new lease holds
* the pointer, so that tool turns itself off (its button, a half-drawn
* shape). A lease its holder releases, or that has already ended, is never
* told, and releasing an ended lease frees nothing. An `onLost` that throws
* is reported.
* `grab` decides each press from its `down` event, synchronously: true
* makes it the tool's, anything else leaves it. A `down` carries no pick,
* so `grab` decides from the position, button and modifiers (and the
@@ -103,7 +108,11 @@ export interface InputPort {
*/
claimPointer(
owner: string,
options?: { grab?: (down: PointerEv) => boolean },
options?: {
grab?: (down: PointerEv) => boolean;
/** Called once when a newer claim ends this lease. */
onLost?: () => void;
},
): Lease;
isPointerFree(): boolean;
/** Suspend user camera input until released. Holds are counted. */
+2 -1
View File
@@ -82,7 +82,8 @@ export interface QueryPort {
pickEllipsoid(x: number, y: number): Ecef | null;
/** Where a ray meets the globe surface (not tiles). */
pickGlobe(ray: Ray): Ecef | null;
pickRay(x: number, y: number): Ray;
/** Null while the canvas has no size (hidden, not laid out yet). */
pickRay(x: number, y: number): Ray | null;
/** Screen position, or null behind the eye (off-screen points still answer). */
project(position: Ecef): ScreenXY | null;
/**
+14 -6
View File
@@ -104,16 +104,16 @@ export interface CreateOptions {
worldDataToken?: string;
/** Initial multisampling; quality can change it later. */
msaa?: 0 | 2 | 4 | 8;
/** Keep the drawing buffer after presenting, for capture. */
preserveDrawingBuffer?: boolean;
/** Sky applied before the first frame, so nothing draws in the wrong sky. */
sky?: Partial<SkySettings>;
/** Scene time in epoch ms. The application passes its boot time. */
time?: number;
/**
* The clocks the renderer reads, for flights, inertia, tweens and
* `FrameTime.now`: `now` on the `performance.now()` timeline, `date` in
* epoch ms. Omitted: the browser's. Tests pass virtual ones.
* The clocks the renderer reads, for `FrameTime.now`, the camera's
* `moveEnd` wait, input, flights and tweens, and for inertia where it
* times that itself (Cesium's keeps Cesium's own timing): `now` on the
* `performance.now()` timeline, `date` in epoch ms. Omitted: the
* browser's. Tests pass virtual ones.
*/
clock?: { now(): number; date(): number };
/** Aborts creation; the renderer cleans up whatever it had built. */
@@ -149,7 +149,10 @@ export interface Renderer {
readonly effects: EffectsPort;
readonly credits: CreditsPort;
readonly quality: QualityPort;
/** The last presented frame as an encoded image. */
/**
* The last presented frame as an encoded image. Once the renderer is
* destroyed it rejects with a "renderer destroyed" error.
*/
capture(options?: CaptureOptions): Promise<Blob>;
/**
* The last presented frame's pixels, synchronously, for loops that render
@@ -175,5 +178,10 @@ export interface Renderer {
* a new renderer.
*/
on(event: 'contextLost' | 'contextRestored', cb: () => void): Off;
/**
* Lets go of everything. Afterwards handles do nothing (`Handle`), and
* `frame.renderOnce` and `capture` reject with a "renderer destroyed"
* error, as does a `renderOnce` still waiting.
*/
destroy(): void;
}
+39
View File
@@ -0,0 +1,39 @@
/**
* Who hears each pointer event: the contract's input rules
* (`router.js`).
*/
import type { InputPort, Lease, PointerEv } from '../contract/index';
/** Who an event went to: one lease's listeners, everyone else, or both. */
export interface Recipients {
lease: Lease | null;
ambient: boolean;
}
export interface InputRouter {
/** The input port the router keeps. */
port: InputPort;
/**
* Delivers one event to the listeners it belongs to. `before` runs first
* with who it goes to (a renderer's stock behaviours); its error is
* reported. A `move` or `up` always reads as going to both.
*/
dispatch(ev: PointerEv, before?: (to: Recipients) => void): Recipients;
/** Live listeners, for leak checks. */
listenerCount(): number;
/** Ends delivery: no listener runs again, even for the event under way. */
dispose(): void;
}
export function createInputRouter(options: {
/** Where a listener's or a `grab`'s error goes. */
report: (error: unknown) => void;
/** The renderer's counted camera-input hold. */
suspendCamera: (reason: string) => () => void;
/** Stock behaviours beyond `select` and `dblclickFollow`. */
behaviours?: string[];
/** Told when a behaviour turns off (first hold) or on (last release). */
onBehaviour?: (name: string, enabled: boolean) => void;
/** Behaviours the renderer cannot do, as `false`: listed, reported disabled. */
supported?: Record<string, boolean>;
}): InputRouter;
+17 -1
View File
@@ -74,6 +74,8 @@ export function createInputRouter({
/** Each lease's `grab`, or null when it takes every press. */
const leaseGrab = new WeakMap();
/** Each lease's ending by a newer claim, which hands back its `onLost`. */
const endLease = new WeakMap();
/**
* The presses under way, by button, from their `down`: `owner` is the
* lease each went to, or null when it went to everyone else. A press's
@@ -96,9 +98,12 @@ export function createInputRouter({
};
},
claimPointer(owner, opts = {}) {
if (currentLease) currentLease.release();
// The newest claim takes over. The lease it ends is told once, after
// this one holds the pointer, so its holder turns itself off.
const ended = currentLease ? endLease.get(currentLease)() : null;
let released = false;
const grab = typeof opts.grab === 'function' ? opts.grab : null;
const onLost = typeof opts.onLost === 'function' ? opts.onLost : null;
const lease = {
owner: String(owner),
get current() {
@@ -110,8 +115,19 @@ export function createInputRouter({
if (currentLease === lease) currentLease = null;
},
};
// Ends it for a newer claim; returns who to tell.
endLease.set(lease, () => {
lease.release();
return onLost;
});
currentLease = lease;
leaseGrab.set(lease, grab);
if (ended)
try {
ended();
} catch (error) {
report(error);
}
return lease;
},
isPointerFree: () => currentLease === null,
+40
View File
@@ -122,3 +122,43 @@ test('dispose ends delivery, even of the event under way', () => {
assert.equal(lease.current, false, 'the lease ended');
assert.equal(port.isPointerFree(), true);
});
test('a newer claim takes over and tells the lease it ended, once', () => {
const { port, dispatch } = router();
const lost = [];
const a = port.claimPointer('a', { onLost: () => lost.push('a') });
const heard = [];
port.on('down', () => heard.push('a'), { lease: a });
const b = port.claimPointer('b', {
onLost: () => lost.push('b'),
});
port.on('down', () => heard.push('b'), { lease: b });
assert.deepEqual(lost, ['a'], 'the old holder is told');
assert.equal(a.current, false);
assert.equal(b.current, true);
dispatch(ev('down'));
assert.deepEqual(heard, ['b'], 'the newest holder gets the press');
a.release();
assert.equal(b.current, true, "the old holder's late release frees nothing");
assert.equal(port.isPointerFree(), false);
assert.deepEqual(lost, ['a'], 'told once');
b.release();
assert.deepEqual(lost, ['a'], 'a holder that lets go is not told');
assert.equal(port.isPointerFree(), true);
});
test('the ended lease is told after the new one holds; its error is reported', () => {
const errors = [];
const { port } = router({ report: (error) => errors.push(error) });
let seen = null;
const a = port.claimPointer('a', {
onLost: () => {
seen = { free: port.isPointerFree(), current: a.current };
throw new Error('onLost');
},
});
const b = port.claimPointer('b');
assert.deepEqual(seen, { free: false, current: false });
assert.equal(b.current, true);
assert.equal(errors.length, 1);
});
+53
View File
@@ -0,0 +1,53 @@
/**
* Where an icon is drawn along its motion segment, and with what course
* (`iconMotion.js`): where the renderer draws a moving icon.
*/
import type {
CourseGlide,
Ecef,
MotionSegment,
Position,
} from '../contract/index';
/** Below this turn rate, rad/s, an arc is drawn as a straight line. */
export const STRAIGHT_BELOW_RAD_PER_S: number;
/** The shortest a lerp runs, ms: one with no length steps. */
export const LERP_STEP_MS: number;
/** An angle in degrees, wrapped into (-180, 180]. */
export function norm180(deg: number): number;
/** An angle in degrees, wrapped into [0, 360). */
export function norm360(deg: number): number;
/** Where `segment` puts an icon at `t` (epoch ms), from its own `pos`. */
export function motionPosition(
segment: MotionSegment | undefined,
pos: Position,
t: number,
): Ecef;
/** How far, degrees in (-180, 180], a glide starts from its segment's course. */
export function glideOffset(
segment: MotionSegment | undefined,
course: number | undefined,
glide: CourseGlide,
): number;
/** The course drawn at `t`, degrees clockwise from north in [0, 360). */
export function motionCourse(
segment: MotionSegment | undefined,
course: number | undefined,
t: number,
glide?: CourseGlide,
): number;
/** Where an icon item is drawn at `t` (epoch ms on its set's motion clock). */
export function iconPosition(
item: { pos: Position; motion?: MotionSegment },
t: number,
): Ecef;
/** The course an icon item is drawn with at `t`. */
export function iconCourse(
item: { course?: number; motion?: MotionSegment; courseGlide?: CourseGlide },
t: number,
): number;
/** Until when, epoch ms, an item's drawn position or course may change. */
export function motionEndsAt(item: {
motion?: MotionSegment;
courseGlide?: CourseGlide;
}): number;
+182
View File
@@ -0,0 +1,182 @@
/**
* The Cesium-free modules the package exports: each
* export names a module that imports no engine, has declarations beside it
* that say every name it exports and no other, and type-checks when imported
* through the package's exports.
*/
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath, pathToFileURL } from 'node:url';
import ts from 'typescript';
const ROOT = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'../..',
);
const PKG = JSON.parse(readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
/** The Cesium-free exports, with declarations. */
const NEUTRAL = [
'./render/contract',
'./render/conformance',
'./render/input/router',
'./render/stub/camera',
'./render/stub/viewRectangle',
'./render/stub/harness',
'./render/motion',
'./render/vectorBase',
'./render/iconSegment',
'./render/recession',
'./render/windStreamlines',
'./render/weather',
'./weather/effects',
'./geo/screenCluster',
];
const fileOf = (key) => path.join(ROOT, PKG.exports[key]);
const declarationOf = (key) => fileOf(key).replace(/\.js$/, '.d.ts');
test('each Cesium-free export is declared, beside its module', () => {
for (const key of NEUTRAL) {
assert.equal(typeof PKG.exports[key], 'string', `${key} is exported`);
assert.doesNotThrow(
() => readFileSync(declarationOf(key)),
`${key} has declarations`,
);
}
});
test('each one names in its declarations exactly what its module exports', async () => {
for (const key of NEUTRAL) {
const runtime = Object.keys(await import(pathToFileURL(fileOf(key)).href))
.filter((name) => name !== 'default')
.sort();
const source = ts.createSourceFile(
declarationOf(key),
readFileSync(declarationOf(key), 'utf8'),
ts.ScriptTarget.ES2022,
);
// Values only: types and interfaces have no runtime name. A module that
// re-exports another's declarations (`export *`) is checked through it.
if (
source.statements.some(
(s) => ts.isExportDeclaration(s) && !s.exportClause,
)
)
continue;
const declared = [];
for (const s of source.statements) {
const exported = s.modifiers?.some(
(m) => m.kind === ts.SyntaxKind.ExportKeyword,
);
if (!exported) continue;
if (
ts.isFunctionDeclaration(s) ||
ts.isClassDeclaration(s) ||
ts.isModuleDeclaration(s)
)
declared.push(s.name.text);
else if (ts.isVariableStatement(s))
for (const d of s.declarationList.declarations)
declared.push(d.name.text);
}
assert.deepEqual([...new Set(declared)].sort(), runtime, key);
}
});
test('they type-check under strict TypeScript, imported by their package names', () => {
const probe = path.join(ROOT, 'src/render/neutralExports.probe.ts');
const lines = NEUTRAL.map(
(key, i) =>
`import * as m${i} from '${PKG.name}${key.slice(1)}';\nvoid m${i};`,
);
const host = ts.createCompilerHost({});
const read = host.readFile;
host.readFile = (file) =>
path.resolve(file) === probe ? lines.join('\n') : read(file);
const exists = host.fileExists;
host.fileExists = (file) => path.resolve(file) === probe || exists(file);
const program = ts.createProgram(
[probe],
{
strict: true,
noEmit: true,
target: ts.ScriptTarget.ES2022,
module: ts.ModuleKind.ESNext,
moduleResolution: ts.ModuleResolutionKind.Bundler,
lib: ['lib.es2022.d.ts', 'lib.dom.d.ts'],
types: [],
allowJs: false,
},
host,
);
const problems = ts
.getPreEmitDiagnostics(program)
.map((d) => ts.flattenDiagnosticMessageText(d.messageText, '\n'));
assert.deepEqual(problems, []);
// Each resolved to its declarations, not to an untyped module.
for (const key of NEUTRAL)
assert.ok(
program.getSourceFile(declarationOf(key)),
`${key} resolves to its declarations`,
);
});
test('none of them reaches Cesium', () => {
const engines = /from ['"]cesium['"]/;
const seen = new Set();
const walk = (file) => {
if (seen.has(file)) return;
seen.add(file);
const text = readFileSync(file, 'utf8');
assert.doesNotMatch(text, engines, path.relative(ROOT, file));
for (const [, spec] of text.matchAll(
/(?:from|import)\s*['"](\.[^'"]+)['"]/g,
))
walk(path.resolve(path.dirname(file), spec));
};
for (const key of NEUTRAL) walk(fileOf(key));
});
test('a camera controller written against the contract reads its pointer events', () => {
const probe = path.join(ROOT, 'src/render/controllerFactory.probe.ts');
const text = `
import type { CameraControllerFactory, CameraPort } from '${PKG.name}/render/contract';
declare const port: CameraPort;
export const controller: CameraControllerFactory = ({ native, input }) => {
const off = input?.on('move', (event) => {
const [x, y] = [event.position.x, event.position.y];
void [x, y, event.type, native.viewport().width];
});
return {
port,
frame: { beforeUpdate() {}, afterUpdate() {} },
destroy: () => off?.(),
};
};
`;
const host = ts.createCompilerHost({});
const read = host.readFile;
host.readFile = (file) => (path.resolve(file) === probe ? text : read(file));
const exists = host.fileExists;
host.fileExists = (file) => path.resolve(file) === probe || exists(file);
const program = ts.createProgram(
[probe],
{
strict: true,
noEmit: true,
target: ts.ScriptTarget.ES2022,
module: ts.ModuleKind.ESNext,
moduleResolution: ts.ModuleResolutionKind.Bundler,
lib: ['lib.es2022.d.ts', 'lib.dom.d.ts'],
types: [],
},
host,
);
const problems = ts
.getPreEmitDiagnostics(program)
.map((d) => ts.flattenDiagnosticMessageText(d.messageText, '\n'));
assert.deepEqual(problems, []);
});
+1 -1
View File
@@ -11,7 +11,7 @@ const FAR = 100_000;
const WIDTH = 64;
const HEIGHT = 32;
/** A depth texture of a frame drawn with three's log depth (near 0): left half a wall 400 m away, right half ground 500 m away. */
/** A depth texture of a frame drawn with log depth and no near plane: left half a wall 400 m away, right half ground 500 m away. */
function depthSource(gl, { webgl2 = true } = {}) {
const texture = gl.createTexture();
texture.image = rawDepthImage(WIDTH, HEIGHT, (column) =>
+62
View File
@@ -0,0 +1,62 @@
/**
* How a set that recedes (`SetSpec.recede`) shrinks and fades its items
* toward the globe's limb (`recession.js`), so the renderer draws exactly
* same factors.
*/
import type { RecedeSpec } from './contract/index';
/** A set's `recede` with every parameter filled in. */
export type RecedeParams = Required<RecedeSpec>;
/** What a frame's items recede by, from the eye's height. */
export interface RecedeFrame {
/** False: nothing recedes this frame (the eye is over the blend band). */
active: boolean;
/** The distance from the eye to the limb, metres (1 while not active). */
limbM: number;
/** 1 under the blend band, easing to 0 across it. */
strength: number;
}
export interface RecedeFactors {
scale: number;
/** The haze: what the item's alpha recedes by before focus and the floor. */
alpha: number;
/** The item's distance as a share of the limb's; null while not active. */
limbRatio: number | null;
}
/** What a set that recedes takes for what its `recede` leaves out. */
export const RECEDE_DEFAULTS: Readonly<RecedeParams>;
/**
* A set's `recede` as the parameters it draws with (each clamped to what
* draws, the rest from `base`); null when the set does not recede.
*/
export function recedeParams(
spec: RecedeSpec | null | undefined,
base?: RecedeParams,
): RecedeParams | null;
/** The distance from an eye this high to the limb; NaN at or under the surface. */
export function limbDistanceM(heightM: number, earthRadiusM?: number): number;
export function recedeFrame(
cameraHeightM: number,
params: RecedeParams,
result?: RecedeFrame,
): RecedeFrame;
export function recedeFactors(
distanceM: number,
frame: RecedeFrame,
params: RecedeParams,
result?: RecedeFactors,
): RecedeFactors;
/** `max(combinedAlphaFloor, clamp(focus, 0, 1) × haze)`. */
export function recededAlpha(
focus: number,
haze: number,
params: RecedeParams,
): number;
+174
View File
@@ -0,0 +1,174 @@
/**
* @module render/recession
* @description How a set that recedes (`SetSpec.recede`) shrinks and fades
* its items toward the globe's limb, free of Cesium, so the renderer
* draws the same factors. The factors are 1 while an item is nearer than
* `startLimbRatio` of the distance from the eye to the limb, and ease
* (smoothstep) to `scaleFloor` and `alphaFloor` at the limb. The whole of it
* eases back to nothing as the eye climbs through the blend band
* (`globeViewBlendStartM` to `globeViewBlendEndM`), so a view of the whole
* globe draws its items unreceded, with no step on the way there.
*
* An item's alpha is its own times `max(combinedAlphaFloor, focus × haze)`:
* focus and haze multiply, and their product never falls under the floor.
* Icons also draw at their scale times the scale factor; models only fade.
*/
/** What a set that recedes takes for what its `recede` leaves out. */
export const RECEDE_DEFAULTS = Object.freeze({
startLimbRatio: 0.5,
scaleFloor: 0.45,
alphaFloor: 0.35,
combinedAlphaFloor: 0.2,
globeViewBlendStartM: 3_500_000,
globeViewBlendEndM: 4_500_000,
earthRadiusM: 6_378_137,
});
const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
/**
* A set's `recede` as the parameters it draws with: each one given taken
* (clamped to what draws), the rest from `base`; null when the set does not
* recede.
* @param {object|null|undefined} spec
* @param {typeof RECEDE_DEFAULTS} [base]
* @returns {typeof RECEDE_DEFAULTS|null}
*/
export function recedeParams(spec, base = RECEDE_DEFAULTS) {
if (spec === null || spec === undefined || spec === false) return null;
const given = typeof spec === 'object' ? spec : {};
const next = {
startLimbRatio: base.startLimbRatio,
scaleFloor: base.scaleFloor,
alphaFloor: base.alphaFloor,
combinedAlphaFloor: base.combinedAlphaFloor,
globeViewBlendStartM: base.globeViewBlendStartM,
globeViewBlendEndM: base.globeViewBlendEndM,
earthRadiusM: base.earthRadiusM,
};
if (Number.isFinite(given.startLimbRatio))
next.startLimbRatio = clamp(given.startLimbRatio, 0, 0.99);
if (Number.isFinite(given.scaleFloor))
next.scaleFloor = clamp(given.scaleFloor, 0.05, 1);
if (Number.isFinite(given.alphaFloor))
next.alphaFloor = clamp(given.alphaFloor, 0.05, 1);
if (Number.isFinite(given.combinedAlphaFloor))
next.combinedAlphaFloor = clamp(given.combinedAlphaFloor, 0.05, 1);
if (Number.isFinite(given.globeViewBlendStartM))
next.globeViewBlendStartM = Math.max(1, given.globeViewBlendStartM);
if (Number.isFinite(given.globeViewBlendEndM))
next.globeViewBlendEndM = Math.max(
next.globeViewBlendStartM + 1,
given.globeViewBlendEndM,
);
if (next.globeViewBlendStartM >= next.globeViewBlendEndM)
next.globeViewBlendStartM = Math.max(1, next.globeViewBlendEndM - 1);
if (Number.isFinite(given.earthRadiusM))
next.earthRadiusM = Math.max(1, given.earthRadiusM);
return next;
}
/**
* The straight-line distance from an eye this high above a sphere of this
* radius to the sphere's limb; NaN at or under the surface.
* @param {number} heightM
* @param {number} [earthRadiusM]
* @returns {number}
*/
export function limbDistanceM(
heightM,
earthRadiusM = RECEDE_DEFAULTS.earthRadiusM,
) {
if (!Number.isFinite(heightM) || heightM <= 0) return Number.NaN;
return Math.sqrt(heightM * (2 * earthRadiusM + heightM));
}
/**
* What one frame's items recede by, from the eye's height: whether they
* recede at all (`active`), the limb's distance, and the strength the blend
* band leaves (1 under it, 0 over it).
* @param {number} cameraHeightM
* @param {typeof RECEDE_DEFAULTS} params
* @param {{active: boolean, limbM: number, strength: number}} [result]
* @returns {{active: boolean, limbM: number, strength: number}}
*/
export function recedeFrame(
cameraHeightM,
params,
result = { active: false, limbM: 1, strength: 0 },
) {
const limbM = limbDistanceM(cameraHeightM, params.earthRadiusM);
const active =
Number.isFinite(cameraHeightM) &&
cameraHeightM > 0 &&
cameraHeightM < params.globeViewBlendEndM &&
limbM > 0;
result.active = active;
if (!active) {
result.limbM = 1;
result.strength = 0;
return result;
}
const g = clamp(
(cameraHeightM - params.globeViewBlendStartM) /
(params.globeViewBlendEndM - params.globeViewBlendStartM),
0,
1,
);
result.limbM = limbM;
result.strength = 1 - g * g * (3 - 2 * g);
return result;
}
/**
* The scale and haze an item this far from the eye recedes by in `frame`,
* and its distance as a share of the limb's (null while nothing recedes).
* @param {number} distanceM
* @param {{active: boolean, limbM: number, strength: number}} frame
* @param {typeof RECEDE_DEFAULTS} params
* @param {{scale: number, alpha: number, limbRatio: number|null}} [result]
* @returns {{scale: number, alpha: number, limbRatio: number|null}}
*/
export function recedeFactors(
distanceM,
frame,
params,
result = { scale: 1, alpha: 1, limbRatio: null },
) {
if (!frame.active || !Number.isFinite(distanceM) || distanceM < 0) {
result.scale = 1;
result.alpha = 1;
result.limbRatio = null;
return result;
}
const limbRatio = distanceM / frame.limbM;
result.limbRatio = limbRatio;
if (limbRatio <= params.startLimbRatio) {
result.scale = 1;
result.alpha = 1;
return result;
}
const t = clamp(
(limbRatio - params.startLimbRatio) / (1 - params.startLimbRatio),
0,
1,
);
// Smoothstep: no slope at either end of the band.
const ease = t * t * (3 - 2 * t) * frame.strength;
result.scale = 1 + (params.scaleFloor - 1) * ease;
result.alpha = 1 + (params.alphaFloor - 1) * ease;
return result;
}
/**
* What a receding item's own alpha is multiplied by: its focus (0..1) times
* its haze, never under the combined floor.
* @param {number} focus
* @param {number} haze `recedeFactors(...).alpha`.
* @param {typeof RECEDE_DEFAULTS} params
* @returns {number}
*/
export function recededAlpha(focus, haze, params) {
return Math.max(params.combinedAlphaFloor, clamp(focus, 0, 1) * haze);
}
+95
View File
@@ -0,0 +1,95 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
RECEDE_DEFAULTS,
limbDistanceM,
recedeFactors,
recedeFrame,
recedeParams,
recededAlpha,
} from './recession.js';
const near = (a, b, what) =>
assert.ok(Math.abs(a - b) < 1e-12, `${what}: ${a} vs ${b}`);
test('a set that does not recede has no parameters; an empty one takes the defaults', () => {
assert.equal(recedeParams(undefined), null);
assert.equal(recedeParams(null), null);
assert.deepEqual(recedeParams({}), { ...RECEDE_DEFAULTS });
assert.deepEqual(RECEDE_DEFAULTS, {
startLimbRatio: 0.5,
scaleFloor: 0.45,
alphaFloor: 0.35,
combinedAlphaFloor: 0.2,
globeViewBlendStartM: 3_500_000,
globeViewBlendEndM: 4_500_000,
earthRadiusM: 6_378_137,
});
});
test('parameters are clamped to what draws, and the blend band kept in order', () => {
const p = recedeParams({
startLimbRatio: 2,
scaleFloor: 0,
alphaFloor: 3,
combinedAlphaFloor: -1,
globeViewBlendStartM: 5_000_000,
globeViewBlendEndM: 10,
earthRadiusM: -4,
});
assert.equal(p.startLimbRatio, 0.99);
assert.equal(p.scaleFloor, 0.05);
assert.equal(p.alphaFloor, 1);
assert.equal(p.combinedAlphaFloor, 0.05);
assert.equal(p.globeViewBlendStartM, 5_000_000);
assert.equal(p.globeViewBlendEndM, 5_000_001);
assert.equal(p.earthRadiusM, 1);
// Not numbers: the base's.
assert.deepEqual(recedeParams({ scaleFloor: 'x', alphaFloor: NaN }), {
...RECEDE_DEFAULTS,
});
// Over another base.
assert.equal(
recedeParams({}, { ...RECEDE_DEFAULTS, scaleFloor: 0.7 }).scaleFloor,
0.7,
);
});
test('the frame: the limb distance and the strength the blend band leaves', () => {
const p = recedeParams({});
const low = recedeFrame(1_000_000, p);
assert.equal(low.active, true);
near(low.limbM, Math.sqrt(1_000_000 * (2 * 6_378_137 + 1_000_000)), 'limb');
assert.equal(low.strength, 1);
const mid = recedeFrame(4_000_000, p);
near(mid.strength, 0.5, 'halfway through the band');
for (const height of [4_500_000, 9_000_000, 0, -1, NaN])
assert.equal(recedeFrame(height, p).active, false, `${height}`);
near(limbDistanceM(1_000_000), low.limbM, 'limbDistanceM');
assert.ok(Number.isNaN(limbDistanceM(0)));
});
test('the factors: identity inside the start ratio, the floors at the limb', () => {
const p = recedeParams({});
const frame = recedeFrame(1_000_000, p);
assert.deepEqual(recedeFactors(frame.limbM * 0.5, frame, p), {
scale: 1,
alpha: 1,
limbRatio: 0.5,
});
const at = recedeFactors(frame.limbM, frame, p);
near(at.scale, 0.45, 'scale floor');
near(at.alpha, 0.35, 'alpha floor');
const beyond = recedeFactors(frame.limbM * 1.2, frame, p);
near(beyond.scale, 0.45, 'beyond the limb');
const off = recedeFactors(1e9, recedeFrame(9_000_000, p), p);
assert.deepEqual(off, { scale: 1, alpha: 1, limbRatio: null });
});
test('the alpha a receding item draws with: focus times haze, never under the combined floor', () => {
const p = recedeParams({});
assert.equal(recededAlpha(0.25, 0.35, p), 0.2);
near(recededAlpha(1, 0.35, p), 0.35, 'haze alone');
assert.equal(recededAlpha(0.5, 1, p), 0.5);
assert.equal(recededAlpha(2, 1, p), 1);
});
+58
View File
@@ -0,0 +1,58 @@
/**
* The stub renderer's camera (`camera.js`): the reference camera's poses,
* views, flights and events in plain maths, which a renderer of its own can
* build its camera port on.
*/
import type { CameraPort, Ecef, GeoRect, Vec3 } from '../contract/index';
/** The eye in world (ECEF) terms. */
export interface StubEye {
position: Ecef;
direction: Vec3;
up: Vec3;
right: Vec3;
/** Vertical field of view, radians. */
fovy: number;
aspectRatio: number;
near: number;
}
export interface StubCamera {
port: CameraPort;
/** Ends a flight in progress as cancelled, without announcing a command. */
endFlight(): void;
/** One frame's camera steps, run in the contract's order. */
steps: {
stepFlight(): void;
stepChanged(): void;
stepFollow(): void;
stepMoveDetection(): void;
};
eye(): StubEye;
/** The reasons camera controls are held for. */
holds(): string[];
/** The frame the eye is in, column-major from it to the world. */
eyeFrame(): Float64Array;
/** Puts `viewRectangle` on the port. */
setViewRectangle(fn: () => GeoRect | null): void;
}
export function createStubCamera(options: {
/** CSS size. */
viewport: () => { width: number; height: number };
/** The clock, ms. */
now: () => number;
/** Scene time, epoch ms. */
sceneTime: () => number;
requestRender: (reason: string) => void;
report: (error: Error) => void;
/** Where a drawn item is, `aheadMs` on, for a follow of it. */
drawnPosition?: (
item: { set: string; id: string },
aheadMs: number,
) => Ecef | null;
/** `cameraChangeThreshold` (default true). */
thresholds?: boolean;
/** `keepEarthFramed` (default false). */
framing?: boolean;
}): StubCamera;
+4
View File
@@ -0,0 +1,4 @@
/** The stub renderer as the conformance suite's renderer under test. */
import type { ConformanceHarness } from '../conformance/index';
export function createStubHarness(name?: string): ConformanceHarness;
+18 -2
View File
@@ -9,10 +9,26 @@ import { toEcef } from './math.js';
/** @returns {import('../conformance/index.js').ConformanceHarness} */
export function createStubHarness(name = 'stub') {
// Each renderer's container: a stand-in that says its size, which the
// stub's `resize` follows.
const containers = new WeakMap();
return {
name,
create: async ({ viewport, capabilities }) =>
createStubRenderer({ viewport, capabilities }),
create: async ({ viewport, capabilities }) => {
const container = {
clientWidth: viewport.width,
clientHeight: viewport.height,
};
const r = createStubRenderer({ viewport, capabilities, container });
containers.set(r, container);
return r;
},
resizeContainer: (r, { width, height }) => {
const container = containers.get(r);
if (!container) return;
container.clientWidth = width;
container.clientHeight = height;
},
frame: (r) => {
r.testing.tick();
},
+71 -8
View File
@@ -14,6 +14,12 @@ import { alongLength } from '../../geo/polyline.js';
import { clusterScreenPoints } from '../../geo/screenCluster.js';
import { createInputRouter } from '../input/router.js';
import { cssColor } from '../color.js';
import {
recedeFactors,
recedeFrame,
recedeParams,
recededAlpha,
} from '../recession.js';
import { CLEAR_WEATHER, mergeWeather } from '../weather.js';
import { CAPABILITIES, CONTRACT_VERSION } from '../contract/index.js';
import { createStubCamera } from './camera.js';
@@ -154,7 +160,9 @@ function createCanvas(container, viewport) {
* @param {object} [options]
* @param {Iterable<import('../contract/common').Capability>} [options.capabilities] Default: all.
* @param {HTMLElement} [options.container] In a page: the element the stub's
* canvas fills, as a plugin's `CreateOptions.container`.
* canvas fills, as a plugin's `CreateOptions.container`. Elsewhere, an
* object that says a size (`clientWidth`, `clientHeight`): `resize`
* follows it.
* @param {{width: number, height: number}} [options.viewport] CSS size; default 1280 × 720.
* @param {number} [options.time] Scene time, epoch ms.
* @returns {import('../contract/renderer').Renderer & {testing: StubTesting}}
@@ -183,6 +191,7 @@ export function createStubRenderer(options = {}) {
// The frame under way while its `preUpdate` listeners run.
let updating = null;
const onceWaiters = [];
const destroyedError = () => new Error('renderer destroyed');
const onceTimers = new Set();
const stepLog = [];
@@ -296,6 +305,11 @@ export function createStubRenderer(options = {}) {
// A frame each timed layer was asked to show is now drawn.
for (const [layer, flush] of [...frameFlushes])
if (frameFlushes.get(layer) === flush) flush();
// The imagery added since the last frame is drawn: loaded.
if (imageryLoading > 0) {
imageryLoading = 0;
announceProgress();
}
step('postRender');
runPhase('postRender', t);
for (const waiter of onceWaiters.splice(0)) waiter();
@@ -351,12 +365,15 @@ export function createStubRenderer(options = {}) {
tick();
},
renderOnce({ timeoutMs } = {}) {
if (destroyed) return Promise.reject(destroyedError());
requestRender('renderOnce');
return new Promise((resolve, reject) => {
let timer = null;
const waiter = () => {
// Called with an error when the renderer is destroyed first.
const waiter = (error) => {
clearTimeout(timer);
resolve();
if (error) reject(error);
else resolve();
};
onceWaiters.push(waiter);
if (timeoutMs !== undefined)
@@ -405,6 +422,7 @@ export function createStubRenderer(options = {}) {
};
sets.set(spec.id, record);
log('draw', kind, [spec]);
const gone = () => destroyed || sets.get(spec.id) !== record;
// A model is ready once per load: when it is new or its url changes,
// not when it is moved or restyled. One under the failing scheme fails
// its load instead, unless it came with its bytes (`gltf`).
@@ -490,6 +508,9 @@ export function createStubRenderer(options = {}) {
dispose() {
// A newer set under the same id is not this handle's to remove.
if (sets.get(spec.id) === record) sets.delete(spec.id);
// Its listeners hear nothing more, even mid-delivery.
for (const entry of record.readyListeners) entry.live = false;
for (const entry of record.loadFailedListeners) entry.live = false;
requestRender('draw');
},
};
@@ -529,10 +550,20 @@ export function createStubRenderer(options = {}) {
const call = handle[name];
if (!call) continue;
handle[name] = (...args) => {
// Disposed, or its renderer destroyed, it does nothing.
if (gone()) return;
record.version += 1;
return call(...args);
};
}
const { set: showSet } = Object.getOwnPropertyDescriptor(handle, 'show');
Object.defineProperty(handle, 'show', {
get: () => record.show,
set(value) {
if (!gone()) showSet.call(handle, value);
},
enumerable: true,
});
return handle;
}
@@ -774,12 +805,17 @@ export function createStubRenderer(options = {}) {
/**
* The shown models as the stub draws them: a square as wide as a pick
* takes (at most `maxPixelSize`, at least `minPixelSize`), far
* ones first, in white shading blended with the tint by `colorBlend`.
* ones first, in white shading blended with the tint by `colorBlend`,
* over black at the tint's alpha times the model's emphasis (its `focus`,
* composed with the haze in a set that recedes).
*/
function modelSquares() {
const squares = [];
const eyeHeight = toCartographicRadians(eye().position).height;
for (const set of sets.values()) {
if (set.kind !== 'models' || !set.show) continue;
const recede = recedeParams(set.spec.recede);
const frame = recede ? recedeFrame(eyeHeight, recede) : null;
for (const item of set.items.values()) {
if (item.show === false) continue;
const p = itemPosition(set, item);
@@ -795,20 +831,33 @@ export function createStubRenderer(options = {}) {
let side = 10;
if (item.maxPixelSize > 0) side = Math.min(side, item.maxPixelSize);
side = Math.max(side, item.minPixelSize ?? 0);
const focus = Number.isFinite(item.focus)
? Math.min(1, Math.max(0, item.focus))
: 1;
const emphasis = recede
? recededAlpha(
focus,
recedeFactors(distance, frame, recede).alpha,
recede,
)
: focus;
squares.push({
x: s.x,
y: s.y,
half: side / 2,
distance,
rgba: modelColor(item),
rgba: modelColor(item, emphasis),
});
}
}
return squares.sort((a, b) => b.distance - a.distance);
}
/** A model's colour: white shading, the tint blended in by `colorBlend`. */
function modelColor(item) {
/**
* A model's colour: white shading, the tint blended in by `colorBlend`,
* over black at the tint's alpha times `emphasis`.
*/
function modelColor(item, emphasis = 1) {
const shaded = [1, 1, 1];
const tint =
item.tint === undefined || item.tint === null
@@ -829,7 +878,8 @@ export function createStubRenderer(options = {}) {
amount === null ? c * tint[i] : c + (tint[i] - c) * amount,
);
}
return [...rgb.map((c) => Math.round(c * 255)), 255];
const alpha = (tint ? (tint[3] ?? 1) : 1) * emphasis;
return [...rgb.map((c) => Math.round(c * alpha * 255)), 255];
}
/** Where a drawn item is now (or `aheadMs` from now), or null. */
@@ -1431,6 +1481,15 @@ export function createStubRenderer(options = {}) {
/** Each timed layer's announcement of the frame it drew, run after a render. */
const frameFlushes = new Map();
const progressListeners = [];
/** Imagery added since the last drawn frame: loading until it is drawn. */
let imageryLoading = 0;
function announceProgress() {
deliver(progressListeners, {
tilesPending: 0,
imageryPending: imageryLoading,
terrainPending: 0,
});
}
const settled = { base: true, tiles: true, terrain: true, imagery: true };
let sky = {
atmosphere: true,
@@ -1555,6 +1614,8 @@ export function createStubRenderer(options = {}) {
else imageryLayers.splice(index, 0, layer);
log('globe', 'imagery.add', [spec, index]);
requestRender('imagery');
imageryLoading += 1;
announceProgress();
return layer;
}
@@ -1911,6 +1972,7 @@ export function createStubRenderer(options = {}) {
credits,
quality,
async capture(opts = {}) {
if (destroyed) throw destroyedError();
return new Blob([], { type: `image/${opts.type ?? 'png'}` });
},
readPixels(opts = {}) {
@@ -1980,6 +2042,7 @@ export function createStubRenderer(options = {}) {
if (options.container) canvas.remove?.();
for (const clear of onceTimers) clear();
onceTimers.clear();
for (const waiter of onceWaiters.splice(0)) waiter(destroyedError());
sets.clear();
sceneFrameLayers.clear();
frameFlushes.clear();
+67 -1
View File
@@ -20,7 +20,7 @@ test('the stub passes the conformance suite', async () => {
.filter((r) => r.status === 'skip')
.map((r) => r.id);
// It draws only models into pixels, so the sweep's, a lit shape's, a line outline's, a
// split line's, a draped outlined line's and the blends' (over a drawn shape), video tiles' and the weather's pixels (drawn, and by scene time) go unread; its camera takes no user gestures: the drag and wheel scripts are for a
// split line's, a draped outlined line's and the blends' (over a drawn shape), video tiles', the weather's pixels (drawn, and by scene time) and an encoded capture go unread; its camera takes no user gestures: the drag and wheel scripts are for a
// camera that does (a controller over it, say).
assert.deepEqual(skipped, [
'effects.screenModulation.pixels',
@@ -33,6 +33,8 @@ test('the stub passes the conformance suite', async () => {
'globe.imagery.video',
'globe.weather.drawn',
'globe.weather.sceneTime',
'renderer.capture',
'effects.setStyleParams',
...CAMERA_SCRIPTS.filter(usesInput).map((s) => `camera.trace.${s.name}`),
]);
});
@@ -346,3 +348,67 @@ test('a lit-shape check that fails still shows the globe again', async () => {
assert.equal(report.results[0].status, 'fail');
assert.deepEqual(shown, [true]);
});
/** One check over the stub with `change` made to each renderer it makes. */
async function checkWith(id, change, extra = {}) {
const base = createStubHarness();
const report = await runConformance(
{
...base,
...extra,
create: async (options) => {
const r = await base.create(options);
change(r);
return r;
},
},
{ only: (c) => c === id },
);
return report.results[0];
}
test('the resize check fails a renderer whose resize does not follow its container', async () => {
assert.equal((await checkWith('renderer.resize', () => {})).status, 'pass');
const result = await checkWith('renderer.resize', (r) => {
r.resize = () => {};
});
assert.equal(result.status, 'fail', result.detail);
});
test('the progress check fails a renderer that never says what it loads', async () => {
assert.equal((await checkWith('globe.progress', () => {})).status, 'pass');
const result = await checkWith('globe.progress', (r) => {
r.globe.on = () => () => {};
});
assert.equal(result.status, 'fail', result.detail);
});
test('the after-destroy check fails a renderer whose sets keep items once it is destroyed', async () => {
assert.equal(
(await checkWith('renderer.afterDestroy', () => {})).status,
'pass',
);
const result = await checkWith('renderer.afterDestroy', (r) => {
const points = r.draw.points;
r.draw.points = (spec) => {
const set = points(spec);
let held = 0;
set.set = (items) => (held = items.length);
set.upsert = (items) => (held += items.length);
set.size = () => held;
return set;
};
});
assert.equal(result.status, 'fail', result.detail);
});
test('the stub keeps a set’s `recede` as given and as changed', () => {
const r = createStubRenderer({ capabilities: ['models'] });
r.draw.icons({ id: 'i', recede: { scaleFloor: 0.6 } });
const models = r.draw.models({ id: 'm', recede: {} });
assert.deepEqual(r.testing.setRecord('i').spec.recede, { scaleFloor: 0.6 });
assert.deepEqual(r.testing.setRecord('m').spec.recede, {});
models.setOptions({ recede: null });
assert.equal(r.testing.setRecord('m').spec.recede, null);
r.destroy();
});
+8
View File
@@ -0,0 +1,8 @@
/** The view rectangle of a pose, as the reference camera measures it. */
import type { CameraPose, Ecef, GeoRect } from '../contract/index';
export function computeViewRectangle(
pose: CameraPose,
viewport: { width: number; height: number },
pickEllipsoid: (x: number, y: number) => Ecef | null,
): GeoRect | null;
+78
View File
@@ -0,0 +1,78 @@
/**
* The vector base painter (`index.js`): a MapLibre style's vector tiles
* painted as raster tiles, Cesium-free.
*/
/** The fetch the painter calls. */
export type VectorFetch = (
url: string,
init?: RequestInit,
) => Promise<Response>;
/** A loaded style, as `paintVectorTile` paints it. */
export interface VectorStyle {
url: string;
style: object;
sources: Record<
string,
{
tiles: string[];
minzoom: number;
maxzoom: number;
scheme: 'xyz' | 'tms';
attribution?: string;
}
>;
layers: object[];
background: { color: string; opacity: number } | null;
/** Each layer the painter cannot draw, with why. */
skipped: Array<{ id: string; reason: string }>;
/** Each vector source's attribution (markup). */
attribution: string[];
tiles: Map<string, Promise<object>>;
}
/** Layer types the painter draws. */
export const PAINTED_TYPES: readonly string[];
/** A painted tile's side, CSS pixels. */
export const STYLE_TILE_SIZE: number;
/**
* Load a style document and the TileJSON its vector sources name; rejects
* for a document that is no style, or a source that fails to load.
*/
export function loadVectorStyle(
styleUrl: string,
fetch?: VectorFetch,
options?: { signal?: AbortSignal },
): Promise<VectorStyle>;
/** Paint Web Mercator tile `z`/`x`/`y` of `style`. */
export function paintVectorTile(
style: VectorStyle,
z: number,
x: number,
y: number,
options?: {
size?: number;
fetch?: VectorFetch;
signal?: AbortSignal;
canvas?: (size: number) => HTMLCanvasElement | OffscreenCanvas;
},
): Promise<HTMLCanvasElement | OffscreenCanvas>;
/** What a style asks for that the painter does not draw. */
export class Unsupported extends Error {}
/** A style expression, compiled. */
export function compileExpression(expr: unknown): (feature: object) => unknown;
/** A layer's `filter`, compiled (none: every feature). */
export function compileFilter(filter: unknown): (feature: object) => boolean;
/** A layout or paint value, compiled. */
export function compileValue(
value: unknown,
options?: { array?: boolean; interpolated?: boolean },
): (feature: object) => unknown;
/** A CSS colour as `[r, g, b, a]` (0..255, alpha 0..1), or null. */
export function parseColor(
text: unknown,
): [r: number, g: number, b: number, a: number] | null;
+14
View File
@@ -0,0 +1,14 @@
import type { WeatherSettings } from './contract/globe';
/** All clear, no wind: what a renderer draws until weather is set. */
export const CLEAR_WEATHER: Readonly<WeatherSettings>;
/**
* `current` with `patch` applied as `globe.weather.set` applies it, as a new
* object: each strength given is clamped to 0..1, one not given is kept;
* `wind` is taken whole.
*/
export function mergeWeather(
current: WeatherSettings,
patch?: Partial<WeatherSettings>,
): WeatherSettings;