Read the canvas from the renderer in the layers, voice and tools

Files off the Cesium list sized themselves by, listened on and set the
cursor of `viewer.scene.canvas`. They now read `canvasOf(viewer)` from
src/render/rendererOf.js: the bound renderer's canvas, else the viewer's
own, the same element. Recent Imagery's divider moves the split through the
globe port (`globeSplitTarget`, moved from the flood event into
src/ui/imagerySplit.js), and traffic flow passes the viewer to the listed
surface module (`viewerRoadSurface`) instead of reaching for its scene.

The test fakes give their viewers a canvas, and the fake renderers report
it, as the Cesium renderer reports the viewer's.
This commit is contained in:
Sameh Khamis committed 2026-11-07 18:10:39 -08:00
1 parent abe9f97768
commit b19fa56565
49 files changed
+269 -119

No files matched your search

+3 -3
View File
@@ -18,7 +18,7 @@ import { onFollowChanged } from './data/followed.js';
import { ownCameraArrival } from './data/cameraArrival.js'; import { ownCameraArrival } from './data/cameraArrival.js';
import { distance, dot, fromDegrees, toLonLatH } from './geo/index.js'; import { distance, dot, fromDegrees, toLonLatH } from './geo/index.js';
import { heightsOf } from './queries/heights.js'; import { heightsOf } from './queries/heights.js';
import { findCamera } from './render/rendererOf.js'; import { canvasOf, findCamera } from './render/rendererOf.js';
/** Minimum eye height above the rendered surface for a usable view. */ /** Minimum eye height above the rendered surface for a usable view. */
export const MIN_EYE_CLEARANCE_M = 120; export const MIN_EYE_CLEARANCE_M = 120;
@@ -141,7 +141,7 @@ export function guardCameraAboveGround(viewer, at, options = {}) {
isStale = () => false, isStale = () => false,
onLift = null, onLift = null,
} = options; } = options;
if (!viewer?.scene || !Number.isFinite(at?.lat) || !Number.isFinite(at?.lon)) if (!viewer || !Number.isFinite(at?.lat) || !Number.isFinite(at?.lon))
return () => {}; return () => {};
// Without a readable pose the guard could not tell a later owner's move. // Without a readable pose the guard could not tell a later owner's move.
@@ -150,7 +150,7 @@ export function guardCameraAboveGround(viewer, at, options = {}) {
let timer = null; let timer = null;
let done = false; let done = false;
const canvas = viewer.scene.canvas; const canvas = canvasOf(viewer);
const documentRef = canvas?.ownerDocument; const documentRef = canvas?.ownerDocument;
const removers = []; const removers = [];
let release = () => {}; let release = () => {};
+9 -1
View File
@@ -1590,6 +1590,9 @@ test('vessel host publication preserves the shipped grid winner and separation s
const winner = makeCandidate('200', 'NAMED WINNER', 40, 30, 16); const winner = makeCandidate('200', 'NAMED WINNER', 40, 30, 16);
const separated = makeCandidate('300', 'SEPARATED', 400, 300, 3); const separated = makeCandidate('300', 'SEPARATED', 400, 300, 3);
const viewer = { const viewer = {
get canvas() {
return this.scene?.canvas;
},
scene: { canvas: { clientWidth: 1600, clientHeight: 900 } }, scene: { canvas: { clientWidth: 1600, clientHeight: 900 } },
}; };
const unbind = bindRenderer(viewer, { const unbind = bindRenderer(viewer, {
@@ -1657,7 +1660,12 @@ test('vessel real layer lifecycle publishes protected selection and leaves no st
}); });
_setVesselOverlayHostForTest(host); _setVesselOverlayHostForTest(host);
_setVesselStateForTest({ _setVesselStateForTest({
viewer: { scene: { canvas: { clientWidth: 1600, clientHeight: 900 } } }, viewer: {
get canvas() {
return this.scene?.canvas;
},
scene: { canvas: { clientWidth: 1600, clientHeight: 900 } },
},
records: [record], records: [record],
selectedRecord: record, selectedRecord: record,
}); });
+5 -18
View File
@@ -23,17 +23,17 @@ import {
resolveEmbeddedMediaSource, resolveEmbeddedMediaSource,
} from './bhoteKoshiEmbeddedMedia.js'; } from './bhoteKoshiEmbeddedMedia.js';
import { acquireImageryComparison } from '../maps/imageryComparison.js'; import { acquireImageryComparison } from '../maps/imageryComparison.js';
import { createImagerySplit } from '../ui/imagerySplit.js'; import { createImagerySplit, globeSplitTarget } from '../ui/imagerySplit.js';
import { formatDate, t, tn, msg, onLocaleChange } from '../i18n/index.js'; import { formatDate, t, tn, msg, onLocaleChange } from '../i18n/index.js';
import { useBhoteKoshiPanelStore } from '../ui/stores/bhoteKoshiPanel.js'; import { useBhoteKoshiPanelStore } from '../ui/stores/bhoteKoshiPanel.js';
import { applicationPinia } from '../ui/vueRuntime.js'; import { applicationPinia } from '../ui/vueRuntime.js';
import { heightsOf } from '../queries/heights.js'; import { heightsOf } from '../queries/heights.js';
import { import {
cameraOf, cameraOf,
canvasOf,
drawOf, drawOf,
findCamera, findCamera,
findGlobe, findGlobe,
rendererOf,
} from '../render/rendererOf.js'; } from '../render/rendererOf.js';
import { hexColor } from '../render/color.js'; import { hexColor } from '../render/color.js';
import { fromDegrees } from '../geo/ellipsoid.js'; import { fromDegrees } from '../geo/ellipsoid.js';
@@ -2704,26 +2704,13 @@ export function createBhoteKoshiEventLayer({
/** The canvas the scene is drawn on, for its pointer events. */ /** The canvas the scene is drawn on, for its pointer events. */
function sceneCanvas() { function sceneCanvas() {
if (!_viewer) return null; if (!_viewer) return null;
return rendererOf(_viewer)?.canvas ?? _viewer.scene?.canvas ?? null; return canvasOf(_viewer);
}
/** The split as the divider moves it: the globe's, through its port. */
function splitScene() {
const imagery = findGlobe(_viewer)?.imagery;
if (!imagery?.setSplit) return null;
return {
get splitPosition() {
return imagery.getSplit();
},
set splitPosition(value) {
imagery.setSplit(value);
},
};
} }
function createSplitControl(event) { function createSplitControl(event) {
_splitControl = createImagerySplit({ _splitControl = createImagerySplit({
scene: splitScene(), // The split as the divider moves it: the globe's, through its port.
scene: globeSplitTarget(findGlobe(_viewer)),
initialValue: _split, initialValue: _split,
id: 'bhote-koshi-split-line', id: 'bhote-koshi-split-line',
handleClass: 'bhote-koshi-split-handle', handleClass: 'bhote-koshi-split-handle',
+3
View File
@@ -231,6 +231,9 @@ test('traffic timing pairs real ordering to the scheduling change and guards re-
setLongitude(longitude); setLongitude(longitude);
viewer = { viewer = {
camera, camera,
get canvas() {
return this.scene?.canvas;
},
scene: { scene: {
canvas: { clientWidth: 0, clientHeight: 0, width: 0, height: 0 }, canvas: { clientWidth: 0, clientHeight: 0, width: 0, height: 0 },
preRender, preRender,
+8 -3
View File
@@ -23,7 +23,12 @@ import {
import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; import { entityRecord, readEntityRecord } from '../../data/entityRecords.js';
import { alprIconPosition, alprMarkers } from './markerState.js'; import { alprIconPosition, alprMarkers } from './markerState.js';
import { horizonFrom } from '../../geo/horizon.js'; import { horizonFrom } from '../../geo/horizon.js';
import { cameraOf, findCredits, findQuery } from '../../render/rendererOf.js'; import {
cameraOf,
canvasOf,
findCredits,
findQuery,
} from '../../render/rendererOf.js';
/** A `#rrggbb` colour as `rgb(r,g,b)`, the form the readout card has always had. */ /** A `#rrggbb` colour as `rgb(r,g,b)`, the form the readout card has always had. */
function cssRgb(hex) { function cssRgb(hex) {
@@ -162,7 +167,7 @@ export function createAlprPresentation({ state, services, source }) {
* @returns {number|null} Count, or null without a scene to project into. * @returns {number|null} Count, or null without a scene to project into.
*/ */
function countOnScreen() { function countOnScreen() {
const canvas = state.viewer?.scene?.canvas; const canvas = canvasOf(state.viewer);
const width = canvas?.clientWidth || canvas?.width; const width = canvas?.clientWidth || canvas?.width;
const height = canvas?.clientHeight || canvas?.height; const height = canvas?.clientHeight || canvas?.height;
const query = findQuery(state.viewer); const query = findQuery(state.viewer);
@@ -266,7 +271,7 @@ export function createAlprPresentation({ state, services, source }) {
// that point instead; the camera-to-ground range keeps zoom-out queries capped. // that point instead; the camera-to-ground range keeps zoom-out queries capped.
function viewportBox(viewer) { function viewportBox(viewer) {
const query = findQuery(viewer); const query = findQuery(viewer);
const canvas = viewer?.scene?.canvas; const canvas = canvasOf(viewer);
if (typeof query?.pickEllipsoid === 'function' && canvas) { if (typeof query?.pickEllipsoid === 'function' && canvas) {
const width = canvas.clientWidth || canvas.width; const width = canvas.clientWidth || canvas.width;
const height = canvas.clientHeight || canvas.height; const height = canvas.clientHeight || canvas.height;
@@ -24,6 +24,9 @@ function overlay(screenAngle) {
}); });
const viewer = { const viewer = {
container, container,
get canvas() {
return this.scene?.canvas;
},
scene: { canvas: { clientWidth: 800, clientHeight: 600 } }, scene: { canvas: { clientWidth: 800, clientHeight: 600 } },
}; };
bindRenderer(viewer, { camera: camera.port }); bindRenderer(viewer, { camera: camera.port });
+2 -2
View File
@@ -11,7 +11,7 @@ import {
import { bearingBetweenCoordinates } from '../../cockpitMath.js'; import { bearingBetweenCoordinates } from '../../cockpitMath.js';
import { AWARENESS_PAGE_SIZE, CONTEXT_RIM_HEIGHT_M } from './policy.js'; import { AWARENESS_PAGE_SIZE, CONTEXT_RIM_HEIGHT_M } from './policy.js';
import { formatAwarenessDirection } from './presentation.js'; import { formatAwarenessDirection } from './presentation.js';
import { drawOf, findCamera } from '../../render/rendererOf.js'; import { canvasOf, drawOf, findCamera } from '../../render/rendererOf.js';
import { import {
PI_OVER_TWO, PI_OVER_TWO,
distance, distance,
@@ -145,7 +145,7 @@ export function createRendering({
return; return;
} }
const canvas = layerState.viewer.scene.canvas; const canvas = canvasOf(layerState.viewer);
const width = canvas.clientWidth || canvas.width; const width = canvas.clientWidth || canvas.width;
const height = canvas.clientHeight || canvas.height; const height = canvas.clientHeight || canvas.height;
const sonar = isCyberSonarActive() const sonar = isCyberSonarActive()
+2 -2
View File
@@ -1,6 +1,6 @@
import { fromDegrees } from '../../geo/ellipsoid.js'; import { fromDegrees } from '../../geo/ellipsoid.js';
import { distance, dot } from '../../geo/vector.js'; import { distance, dot } from '../../geo/vector.js';
import { findCamera } from '../../render/rendererOf.js'; import { canvasOf, findCamera } from '../../render/rendererOf.js';
import { viewshedColors, cameraHue } from '../../data/cctvViewshed.js'; import { viewshedColors, cameraHue } from '../../data/cctvViewshed.js';
import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js'; import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js';
import { GIZMO_ID_PREFIX } from '../../data/cctvGizmo.js'; import { GIZMO_ID_PREFIX } from '../../data/cctvGizmo.js';
@@ -365,7 +365,7 @@ export function createLifecycle({
attachViewListeners(); attachViewListeners();
// A resize or rotation changes what is on screen without moving the // A resize or rotation changes what is on screen without moving the
// camera. // camera.
const canvas = layerState._viewer.scene?.canvas; const canvas = canvasOf(layerState._viewer);
if (layerState._viewResizeCanvas !== canvas) { if (layerState._viewResizeCanvas !== canvas) {
// A re-init against a new viewer observes its canvas instead. // A re-init against a new viewer observes its canvas instead.
layerState._viewResizeObserver?.disconnect(); layerState._viewResizeObserver?.disconnect();
+3 -3
View File
@@ -23,7 +23,7 @@ import {
translateKnown, translateKnown,
} from '../../i18n/index.js'; } from '../../i18n/index.js';
import { formatQuantity } from '../../ui/unitLabels.js'; import { formatQuantity } from '../../ui/unitLabels.js';
import { cameraOf } from '../../render/rendererOf.js'; import { cameraOf, canvasOf } from '../../render/rendererOf.js';
// "10-12 15:00 UTC" never breaks across lines: no-break spaces, and a word // "10-12 15:00 UTC" never breaks across lines: no-break spaces, and a word
// joiner after the hyphen (JetBrains Mono has no U+2011 non-breaking hyphen). // joiner after the hyphen (JetBrains Mono has no U+2011 non-breaking hyphen).
@@ -98,12 +98,12 @@ export function createCyclonesLayer({
rendering?.setSelection(id); rendering?.setSelection(id);
} }
function installSelection() { function installSelection() {
if (selectionOwner || !viewer?.scene?.canvas) return; const canvas = canvasOf(viewer);
if (selectionOwner || !canvas) return;
const owner = {}; const owner = {};
selectionOwner = owner; selectionOwner = owner;
// Snapshot before sibling bubble listeners can rebuild the overlay hit // Snapshot before sibling bubble listeners can rebuild the overlay hit
// rectangles. A vessel selection does that synchronously in the same click. // rectangles. A vessel selection does that synchronously in the same click.
const canvas = viewer.scene.canvas;
let capturedHit = null; let capturedHit = null;
const overlayHit = (x, y) => { const overlayHit = (x, y) => {
const hit = hitTestOverlay(x, y); const hit = hitTestOverlay(x, y);
+6
View File
@@ -114,6 +114,9 @@ test('map selection yields to pointer owners and owns only its enabled handler',
const canvas = new EventTarget(); const canvas = new EventTarget();
canvas.getBoundingClientRect = () => ({ left: 100, top: 200 }); canvas.getBoundingClientRect = () => ({ left: 100, top: 200 });
const viewer = { const viewer = {
get canvas() {
return this.scene?.canvas;
},
scene: { scene: {
canvas, canvas,
pick() { pick() {
@@ -308,6 +311,9 @@ test('a click on a storm card or lead-hour label selects that storm without pick
const canvas = new EventTarget(); const canvas = new EventTarget();
canvas.getBoundingClientRect = () => ({ left: 0, top: 0 }); canvas.getBoundingClientRect = () => ({ left: 0, top: 0 });
const viewer = { const viewer = {
get canvas() {
return this.scene?.canvas;
},
scene: { scene: {
canvas, canvas,
pick() { pick() {
+4 -3
View File
@@ -4,6 +4,7 @@ import {
FIRMS_AMBIENT_COHORT_LIMIT, FIRMS_AMBIENT_COHORT_LIMIT,
} from '../../data/firmsLabels.js'; } from '../../data/firmsLabels.js';
import { MAX_AMBIENT_LABELS, LABEL_VIEW_MARGIN_PX } from './policy.js'; import { MAX_AMBIENT_LABELS, LABEL_VIEW_MARGIN_PX } from './policy.js';
import { canvasOf } from '../../render/rendererOf.js';
export function createCards({ export function createCards({
layerState, layerState,
@@ -29,7 +30,6 @@ export function createCards({
function rebuildAmbientLabels() { function rebuildAmbientLabels() {
if (!layerState._viewer) return; if (!layerState._viewer) return;
const scene = layerState._viewer.scene;
const { query } = components.rendering.scenePorts(); const { query } = components.rendering.scenePorts();
const project = (position) => query?.project(position) ?? null; const project = (position) => query?.project(position) ?? null;
const now = Date.now(); const now = Date.now();
@@ -70,8 +70,9 @@ export function createCards({
} }
} }
const width = scene.canvas.clientWidth; const canvas = canvasOf(layerState._viewer);
const height = scene.canvas.clientHeight; const width = canvas.clientWidth;
const height = canvas.clientHeight;
let ambientCount = 0; let ambientCount = 0;
for (const candidate of layerState._labelCandidates) { for (const candidate of layerState._labelCandidates) {
+3
View File
@@ -53,6 +53,9 @@ function harness(fires, heightM, { sceneFromViewer = false } = {}) {
heightM, heightM,
), ),
}, },
get canvas() {
return this.scene?.canvas;
},
scene: { scene: {
canvas: { clientWidth: 800, clientHeight: 600 }, canvas: { clientWidth: 800, clientHeight: 600 },
preRender: new Cesium.Event(), preRender: new Cesium.Event(),
+7 -5
View File
@@ -7,6 +7,7 @@ import { fromDegrees } from '../../geo/index.js';
import { horizonFrom } from '../../geo/horizon.js'; import { horizonFrom } from '../../geo/horizon.js';
import { import {
cameraOf, cameraOf,
canvasOf,
drawOf, drawOf,
findFrame, findFrame,
findQuery, findQuery,
@@ -57,8 +58,8 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) {
!same(pose.position, lastPose.position) || !same(pose.position, lastPose.position) ||
!same(pose.direction, lastPose.direction) || !same(pose.direction, lastPose.direction) ||
!same(pose.up, lastPose.up) || !same(pose.up, lastPose.up) ||
width !== viewer.scene.canvas.clientWidth || width !== canvasOf(viewer).clientWidth ||
height !== viewer.scene.canvas.clientHeight height !== canvasOf(viewer).clientHeight
); );
} }
@@ -69,8 +70,9 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) {
function refresh(pose = null) { function refresh(pose = null) {
const viewer = state.viewer; const viewer = state.viewer;
if (!state.enabled || !points) return; if (!state.enabled || !points) return;
width = viewer.scene.canvas.clientWidth; const canvas = canvasOf(viewer);
height = viewer.scene.canvas.clientHeight; width = canvas.clientWidth;
height = canvas.clientHeight;
pose ??= cameraOf(viewer).pose(); pose ??= cameraOf(viewer).pose();
lastPose = { lastPose = {
position: { ...pose.position }, position: { ...pose.position },
@@ -175,7 +177,7 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) {
function sync(records) { function sync(records) {
const viewer = state.viewer; const viewer = state.viewer;
if (!viewer?.scene) return; if (!viewer) return;
points ??= drawOf(viewer).points({ id: setId, horizonCull: true }); points ??= drawOf(viewer).points({ id: setId, horizonCull: true });
points.show = state.enabled; points.show = state.enabled;
const named = records const named = records
+6 -1
View File
@@ -156,7 +156,12 @@ test('mission hover throttles, clears on motion/hidden, and releases listeners',
removeEventListener: (_n, fn) => listeners.delete(fn), removeEventListener: (_n, fn) => listeners.delete(fn),
}; };
const camera = fakeCameraPort(); const camera = fakeCameraPort();
const viewer = { scene: { canvas: { style: {} } } }; const viewer = {
get canvas() {
return this.scene?.canvas;
},
scene: { canvas: { style: {} } },
};
bindRenderer(viewer, { camera: camera.port }); bindRenderer(viewer, { camera: camera.port });
const hover = createLaunchHover({ const hover = createLaunchHover({
viewer, viewer,
+7 -6
View File
@@ -1,6 +1,6 @@
import { isPointerFree } from '../../data/inputOwnership.js'; import { isPointerFree } from '../../data/inputOwnership.js';
import { inputFor } from '../../input/dispatcher.js'; import { inputFor } from '../../input/dispatcher.js';
import { findCamera, findFrame } from '../../render/rendererOf.js'; import { canvasOf, findCamera, findFrame } from '../../render/rendererOf.js';
const HOVER_PICK_INTERVAL_MS = 120; const HOVER_PICK_INTERVAL_MS = 120;
@@ -25,8 +25,9 @@ export function createLaunchHover({
let pendingPosition = null; let pendingPosition = null;
let trailingTimer = null; let trailingTimer = null;
const clearCursor = () => { const clearCursor = () => {
if (ownsCursor && viewer.scene.canvas.style.cursor === 'pointer') const canvas = canvasOf(viewer);
viewer.scene.canvas.style.cursor = ''; if (ownsCursor && canvas.style.cursor === 'pointer')
canvas.style.cursor = '';
ownsCursor = false; ownsCursor = false;
}; };
const cancelTrailing = () => { const cancelTrailing = () => {
@@ -60,7 +61,7 @@ export function createLaunchHover({
const pick = (position, at) => { const pick = (position, at) => {
lastPick = at; lastPick = at;
if (launchAt(position)) { if (launchAt(position)) {
viewer.scene.canvas.style.cursor = 'pointer'; canvasOf(viewer).style.cursor = 'pointer';
ownsCursor = true; ownsCursor = true;
} else clearCursor(); } else clearCursor();
}; };
@@ -215,8 +216,8 @@ export function createLifecycle({
parts.selection.stopMissionZoomAnchor(); parts.selection.stopMissionZoomAnchor();
parts.rendering.showMissions(false); parts.rendering.showMissions(false);
parts.orbitRendering.syncMissionOrbitPrimitiveVisibility(); parts.orbitRendering.syncMissionOrbitPrimitiveVisibility();
if (layerState._viewer?.scene?.canvas) const canvas = canvasOf(layerState._viewer);
layerState._viewer.scene.canvas.style.cursor = ''; if (canvas) canvas.style.cursor = '';
parts.launchPad.hideLaunchPadZone(); parts.launchPad.hideLaunchPadZone();
parts.overlays.hideReplayVehicleOverlay(); parts.overlays.hideReplayVehicleOverlay();
layerState._selectedLaunchId = null; layerState._selectedLaunchId = null;
+2 -2
View File
@@ -1,6 +1,6 @@
import { WGS84 } from '../../geo/ellipsoid.js'; import { WGS84 } from '../../geo/ellipsoid.js';
import { dot, magnitude, normalize, toDegrees } from '../../geo/vector.js'; import { dot, magnitude, normalize, toDegrees } from '../../geo/vector.js';
import { findQuery } from '../../render/rendererOf.js'; import { canvasOf, findQuery } from '../../render/rendererOf.js';
import { t, msg } from '../../i18n/index.js'; import { t, msg } from '../../i18n/index.js';
import { import {
createCyberSonarSampler, createCyberSonarSampler,
@@ -489,7 +489,7 @@ export function createOverlays({ state: layerState, services, parts, source }) {
hideReplayVehicleOverlay(); hideReplayVehicleOverlay();
return null; return null;
} }
const canvas = layerState._viewer.scene.canvas; const canvas = canvasOf(layerState._viewer);
if ( if (
windowPosition.x < -80 || windowPosition.x < -80 ||
windowPosition.y < -100 || windowPosition.y < -100 ||
+6 -1
View File
@@ -122,7 +122,12 @@ test('the scene chrome renders the overlay in the globe container', async (t) =>
test('the replay overlay sits where the query port projects the vehicle, facing along its path', async () => { test('the replay overlay sits where the query port projects the vehicle, facing along its path', async () => {
const { bindRenderer } = await import('../../render/rendererOf.js'); const { bindRenderer } = await import('../../render/rendererOf.js');
const viewer = { scene: { canvas: { clientWidth: 800, clientHeight: 600 } } }; const viewer = {
get canvas() {
return this.scene?.canvas;
},
scene: { canvas: { clientWidth: 800, clientHeight: 600 } },
};
const projected = []; const projected = [];
let behindEye = false; let behindEye = false;
// The path runs along x; the port puts x metres at x pixels, y = 300. // The path runs along x; the port puts x metres at x pixels, y = 300.
+3 -3
View File
@@ -12,7 +12,7 @@ import {
vec, vec,
} from '../../geo/vector.js'; } from '../../geo/vector.js';
import { MISSION_GLOBE_VIEW_RANGE_M, MISSION_FOCUS_RANGE_M } from './policy.js'; import { MISSION_GLOBE_VIEW_RANGE_M, MISSION_FOCUS_RANGE_M } from './policy.js';
import { cameraOf, findCamera } from '../../render/rendererOf.js'; import { cameraOf, canvasOf, findCamera } from '../../render/rendererOf.js';
export function createSelection({ export function createSelection({
state: layerState, state: layerState,
@@ -23,7 +23,7 @@ export function createSelection({
const { getKeyholeGeometry } = services.geometry; const { getKeyholeGeometry } = services.geometry;
function focusFullGlobe(viewer, duration = 2.4) { function focusFullGlobe(viewer, duration = 2.4) {
const canvas = viewer?.scene?.canvas; const canvas = canvasOf(viewer);
const height = canvas?.clientHeight || canvas?.height; const height = canvas?.clientHeight || canvas?.height;
const width = canvas?.clientWidth || canvas?.width; const width = canvas?.clientWidth || canvas?.width;
if (!(width > 0) || !(height > 0)) return; if (!(width > 0) || !(height > 0)) return;
@@ -121,7 +121,7 @@ export function createSelection({
const launchPosition = fromDegrees(launch.lon, launch.lat); const launchPosition = fromDegrees(launch.lon, launch.lat);
let range = 18000000; let range = 18000000;
if (orbitPositions?.length > 1) { if (orbitPositions?.length > 1) {
const canvas = layerState._viewer.scene.canvas; const canvas = canvasOf(layerState._viewer);
const fovy = camera.pose().fovy || toRadians(60); const fovy = camera.pose().fovy || toRadians(60);
const aspect = Math.max( const aspect = Math.max(
0.1, 0.1,
+2 -2
View File
@@ -6,7 +6,7 @@ import {
GLOBAL_RADIO_ALTITUDE_M, GLOBAL_RADIO_ALTITUDE_M,
RADIO_GLOBE_RECENTER_MAX_HEIGHT_M, RADIO_GLOBE_RECENTER_MAX_HEIGHT_M,
} from './policy.js'; } from './policy.js';
import { cameraOf, findCamera } from '../../render/rendererOf.js'; import { cameraOf, canvasOf, findCamera } from '../../render/rendererOf.js';
export function createNavigation({ export function createNavigation({
state: layerState, state: layerState,
@@ -157,7 +157,7 @@ export function createNavigation({
function radioGlobeRecenterPlan(viewer = layerState._viewer) { function radioGlobeRecenterPlan(viewer = layerState._viewer) {
const pose = findCamera(viewer)?.pose() ?? null; const pose = findCamera(viewer)?.pose() ?? null;
const canvas = viewer?.scene?.canvas; const canvas = canvasOf(viewer);
const width = canvas?.clientWidth || canvas?.width; const width = canvas?.clientWidth || canvas?.width;
const height = canvas?.clientHeight || canvas?.height; const height = canvas?.clientHeight || canvas?.height;
// The eye at the earth's centre has no geodetic position. // The eye at the earth's centre has no geodetic position.
+3
View File
@@ -100,6 +100,9 @@ export function boxToolFakes() {
const sources = []; const sources = [];
const viewer = { const viewer = {
renders: 0, renders: 0,
get canvas() {
return this.scene.canvas;
},
scene: { scene: {
canvas: { clientWidth: 1000, clientHeight: 500 }, canvas: { clientWidth: 1000, clientHeight: 500 },
screenSpaceCameraController: { enableInputs: true }, screenSpaceCameraController: { enableInputs: true },
+2 -2
View File
@@ -3,7 +3,7 @@ import { horizonFrom } from '../../geo/horizon.js';
import { densifyRhumb } from '../../geo/rhumb.js'; import { densifyRhumb } from '../../geo/rhumb.js';
import { distance, toRadians } from '../../geo/vector.js'; import { distance, toRadians } from '../../geo/vector.js';
import { cssColor } from '../../render/color.js'; import { cssColor } from '../../render/color.js';
import { cameraOf, drawOf } from '../../render/rendererOf.js'; import { cameraOf, canvasOf, drawOf } from '../../render/rendererOf.js';
import { import {
clampLabel, clampLabel,
createCableOverlayEntry, createCableOverlayEntry,
@@ -418,7 +418,7 @@ export function createRendering({ state }) {
const pose = cameraOf(viewer).pose(); const pose = cameraOf(viewer).pose();
const cameraPos = pose?.position; const cameraPos = pose?.position;
if (!cameraPos) return false; if (!cameraPos) return false;
const canvasHeight = viewer.scene?.canvas?.clientHeight || 1080; const canvasHeight = canvasOf(viewer)?.clientHeight || 1080;
// The field of view along the canvas's longer side. // The field of view along the canvas's longer side.
const fov = const fov =
pose.aspectRatio > 1 pose.aspectRatio > 1
+4 -1
View File
@@ -80,7 +80,7 @@ test('superseding a stalled pass aborts promptly without clearing newer loading'
// and the near plane, and window positions from the scene itself. // and the near plane, and window positions from the scene itself.
const ANGLE = 35 * Math.PI / 180; const ANGLE = 35 * Math.PI / 180;
function portView(scene) { function portView(scene) {
const viewer = { scene }; const viewer = { scene, canvas: scene.canvas };
const position = { x: 0, y: 0, z: 450 }; const position = { x: 0, y: 0, z: 450 };
const direction = { x: 0, y: Math.cos(ANGLE), z: -Math.sin(ANGLE) }; const direction = { x: 0, y: Math.cos(ANGLE), z: -Math.sin(ANGLE) };
bindRenderer(viewer, { bindRenderer(viewer, {
@@ -213,6 +213,9 @@ function flowFixture(source) {
_roadMode: 'osm', _roadMode: 'osm',
_parseRoads: (data) => data.roads, _parseRoads: (data) => data.roads,
_viewer: { _viewer: {
get canvas() {
return this.scene?.canvas;
},
scene: { scene: {
globe: { globe: {
show: true, show: true,
+19 -20
View File
@@ -1,13 +1,13 @@
import { roadIdentity } from './retention.js'; import { roadIdentity } from './retention.js';
import { fromDegrees, toCartographicRadians } from '../../geo/ellipsoid.js'; import { fromDegrees, toCartographicRadians } from '../../geo/ellipsoid.js';
import { copyInto, distance, distanceSquared } from '../../geo/vector.js'; import { copyInto, distance, distanceSquared } from '../../geo/vector.js';
import { findCamera, findFrame, findQuery } from '../../render/rendererOf.js';
import { import {
drawnSurfaceReady, canvasOf,
prepareRoadSurfaces, findCamera,
roadHeightStations, findFrame,
trafficSurfaceReady, findQuery,
} from './surface.js'; } from '../../render/rendererOf.js';
import { roadHeightStations, viewerRoadSurface } from './surface.js';
import { matchFlowToRoads } from '../../data/flowMatch.js'; import { matchFlowToRoads } from '../../data/flowMatch.js';
import { import {
DOT_HEIGHT_OFFSET, DOT_HEIGHT_OFFSET,
@@ -260,7 +260,8 @@ export function createFlow({ state: layerState, services, parts, source }) {
// Separate whole-graph preparation from tile completion and publication. // Separate whole-graph preparation from tile completion and publication.
await nextTask(); await nextTask();
if (!current()) return false; if (!current()) return false;
const scene = layerState._viewer.scene; const surface = viewerRoadSurface(layerState._viewer);
const canvas = canvasOf(layerState._viewer);
// The enable-time estimate can predate the first local mesh (especially // The enable-time estimate can predate the first local mesh (especially
// after an intercontinental jump). Once previews have measured roads, use // after an intercontinental jump). Once previews have measured roads, use
// that local evidence to select the detail view at its real elevation. // that local evidence to select the detail view at its real elevation.
@@ -283,11 +284,11 @@ export function createFlow({ state: layerState, services, parts, source }) {
// its camera port says where the eye is. // its camera port says where the eye is.
const query = findQuery(layerState._viewer); const query = findQuery(layerState._viewer);
let depthHeight; let depthHeight;
if (query && scene.canvas?.clientWidth) { if (query && canvas?.clientWidth) {
try { try {
const hit = query.pickPosition( const hit = query.pickPosition(
scene.canvas.clientWidth / 2, canvas.clientWidth / 2,
scene.canvas.clientHeight * 0.6, canvas.clientHeight * 0.6,
); );
const height = hit && toCartographicRadians(hit)?.height; const height = hit && toCartographicRadians(hit)?.height;
if (Number.isFinite(height) && Math.abs(height) <= 9000) if (Number.isFinite(height) && Math.abs(height) <= 9000)
@@ -344,7 +345,7 @@ export function createFlow({ state: layerState, services, parts, source }) {
) )
return false; return false;
// Spend surface work on roads crossing the canvas, with a small pan margin. // Spend surface work on roads crossing the canvas, with a small pan margin.
if (!scene.canvas?.clientWidth) return true; if (!canvas?.clientWidth) return true;
let minX = Infinity, let minX = Infinity,
minY = Infinity, minY = Infinity,
maxX = -Infinity, maxX = -Infinity,
@@ -357,7 +358,7 @@ export function createFlow({ state: layerState, services, parts, source }) {
minY = Math.min(minY, screen.y); minY = Math.min(minY, screen.y);
maxY = Math.max(maxY, screen.y); maxY = Math.max(maxY, screen.y);
} }
road.coverageBand = maxY < scene.canvas.clientHeight / 2 ? 1 : 0; road.coverageBand = maxY < canvas.clientHeight / 2 ? 1 : 0;
if (clamped.coverage && camera) { if (clamped.coverage && camera) {
road.baseDensityWeight ??= road.densityWeight || 1; road.baseDensityWeight ??= road.densityWeight || 1;
road.densityWeight = road.densityWeight =
@@ -368,9 +369,9 @@ export function createFlow({ state: layerState, services, parts, source }) {
if (!query) return true; if (!query) return true;
return ( return (
maxX >= -100 && maxX >= -100 &&
minX <= scene.canvas.clientWidth + 100 && minX <= canvas.clientWidth + 100 &&
maxY >= -100 && maxY >= -100 &&
minY <= scene.canvas.clientHeight + 100 minY <= canvas.clientHeight + 100
); );
}); });
const budgets = parts.model.allocateRoadDotBudgets( const budgets = parts.model.allocateRoadDotBudgets(
@@ -475,9 +476,8 @@ export function createFlow({ state: layerState, services, parts, source }) {
// The first bounded surface slice needs its own task, not the prefix's tail. // The first bounded surface slice needs its own task, not the prefix's tail.
await nextTask(); await nextTask();
if (!current()) return false; if (!current()) return false;
let prepared = await prepareRoadSurfaces( let prepared = await viewerRoadSurface(layerState._viewer).prepare(
unresolved, unresolved,
layerState._viewer.scene,
services.ground, services.ground,
[layerState._pointCollection], [layerState._pointCollection],
signal, signal,
@@ -497,9 +497,8 @@ export function createFlow({ state: layerState, services, parts, source }) {
) { ) {
await new Promise((resolve) => setTimeout(resolve, 100)); await new Promise((resolve) => setTimeout(resolve, 100));
if (!current()) return false; if (!current()) return false;
prepared = await prepareRoadSurfaces( prepared = await viewerRoadSurface(layerState._viewer).prepare(
prepared.pending, prepared.pending,
layerState._viewer.scene,
services.ground, services.ground,
[layerState._pointCollection], [layerState._pointCollection],
signal, signal,
@@ -517,7 +516,7 @@ export function createFlow({ state: layerState, services, parts, source }) {
!preview && !preview &&
!label.includes('refined') && !label.includes('refined') &&
frame && frame &&
(!trafficSurfaceReady(scene) || (!surface.ready() ||
prepared.pending.length || prepared.pending.length ||
ready.some((road) => road.surfaceSettled === false)) ready.some((road) => road.surfaceSettled === false))
) { ) {
@@ -533,7 +532,7 @@ export function createFlow({ state: layerState, services, parts, source }) {
stop(); stop();
return; return;
} }
if (!drawnSurfaceReady(scene)) return; if (!surface.drawnReady()) return;
stop(); stop();
// Revalidate only local samples taken at a coarser rendered LOD. This // Revalidate only local samples taken at a coarser rendered LOD. This
// background upgrade never holds road acquisition or first paint. // background upgrade never holds road acquisition or first paint.
+2 -3
View File
@@ -2,7 +2,7 @@ import { requestWithDeadline } from '../../sources/requestDeadline.js';
import { resolveRoadMode, ROAD_SOURCE_LABELS } from './roadModes.js'; import { resolveRoadMode, ROAD_SOURCE_LABELS } from './roadModes.js';
import { phaseTiming } from '../../sources/phaseTiming.js'; import { phaseTiming } from '../../sources/phaseTiming.js';
import { RoadRequestError, roadRequestError } from './source.js'; import { RoadRequestError, roadRequestError } from './source.js';
import { loadedSurfaceHeight } from './surface.js'; import { viewerRoadSurface } from './surface.js';
import { import {
isUnavailableCapability, isUnavailableCapability,
sourceResponseError, sourceResponseError,
@@ -273,8 +273,7 @@ export function createIngestion({
let estimated = services.ground?.cachedGroundFloor?.(centerLat, centerLon); let estimated = services.ground?.cachedGroundFloor?.(centerLat, centerLon);
// A miss is the local mesh still loading. // A miss is the local mesh still loading.
if (!Number.isFinite(estimated)) if (!Number.isFinite(estimated))
estimated = loadedSurfaceHeight( estimated = viewerRoadSurface(layerState._viewer).loadedHeight(
layerState._viewer?.scene,
{ lon: centerLon, lat: centerLat }, { lon: centerLon, lat: centerLat },
[layerState._pointCollection], [layerState._pointCollection],
); );
+13 -2
View File
@@ -32,7 +32,12 @@ function setup(t) {
state._enabled = true; state._enabled = true;
state._liveMode = true; state._liveMode = true;
state._pointCollection = new C.PointPrimitiveCollection(); state._pointCollection = new C.PointPrimitiveCollection();
state._viewer = { scene: {} }; state._viewer = {
scene: {},
get canvas() {
return this.scene?.canvas;
},
};
const parts = { const parts = {
rendering: { rendering: {
removeHeatLines() {}, removeHeatLines() {},
@@ -735,6 +740,9 @@ test('selection asks the query port for depth and screen positions, and the came
segmentDist: [11], segmentDist: [11],
}); });
const viewer = { const viewer = {
get canvas() {
return this.scene?.canvas;
},
scene: { scene: {
canvas: { clientWidth: 1000, clientHeight: 800 }, canvas: { clientWidth: 1000, clientHeight: 800 },
globe: { show: true, tilesLoaded: true, getHeight: () => 0 }, globe: { show: true, tilesLoaded: true, getHeight: () => 0 },
@@ -813,6 +821,9 @@ test('selection asks the query port for depth and screen positions, and the came
test('height easing stops visible waypoints at the camera near plane', () => { test('height easing stops visible waypoints at the camera near plane', () => {
const viewer = { const viewer = {
get canvas() {
return this.scene?.canvas;
},
scene: { scene: {
canvas: { clientWidth: 1000, clientHeight: 800 }, canvas: { clientWidth: 1000, clientHeight: 800 },
camera: {}, camera: {},
@@ -879,7 +890,7 @@ test('height easing through the Cesium ports stops at the near plane of a looked
const centre = C.Cartesian3.fromDegrees(0, 0, 0); const centre = C.Cartesian3.fromDegrees(0, 0, 0);
// A transformed camera: lookAt leaves the camera in the target's frame. // A transformed camera: lookAt leaves the camera in the target's frame.
scene.camera.lookAt(centre, new C.HeadingPitchRange(0, -0.5, 600)); scene.camera.lookAt(centre, new C.HeadingPitchRange(0, -0.5, 600));
const viewer = { scene, camera: scene.camera }; const viewer = { scene, camera: scene.camera, canvas: scene.canvas };
const eyeDepth = (p) => const eyeDepth = (p) =>
-C.Matrix4.multiplyByPoint(scene.camera.viewMatrix, p, new C.Cartesian3()) -C.Matrix4.multiplyByPoint(scene.camera.viewMatrix, p, new C.Cartesian3())
.z; .z;
+5 -5
View File
@@ -4,7 +4,7 @@ import {
equalsEpsilon, equalsEpsilon,
lerpInto, lerpInto,
} from '../../geo/vector.js'; } from '../../geo/vector.js';
import { findCamera, findQuery } from '../../render/rendererOf.js'; import { canvasOf, findCamera, findQuery } from '../../render/rendererOf.js';
import { MAX_DOTS, roadDotBudget } from './policy.js'; import { MAX_DOTS, roadDotBudget } from './policy.js';
export const DOT_CHANGE_BUDGET = 768; export const DOT_CHANGE_BUDGET = 768;
@@ -207,15 +207,15 @@ export function createRetention({ state, parts }) {
*/ */
function frameView() { function frameView() {
const viewer = state._viewer; const viewer = state._viewer;
const scene = viewer?.scene; const canvas = canvasOf(viewer);
if (!scene?.canvas?.clientHeight) return null; if (!canvas?.clientHeight) return null;
const query = findQuery(viewer); const query = findQuery(viewer);
if (!query) return null; if (!query) return null;
return { return {
query, query,
pose: findCamera(viewer)?.pose() ?? null, pose: findCamera(viewer)?.pose() ?? null,
width: scene.canvas.clientWidth, width: canvas.clientWidth,
height: scene.canvas.clientHeight, height: canvas.clientHeight,
}; };
} }
function easeHeights(dt) { function easeHeights(dt) {
+16
View File
@@ -80,6 +80,22 @@ export function trafficSurfaceReady(scene) {
return currentRenderedFrame(scene)?.ready === true; return currentRenderedFrame(scene)?.ready === true;
} }
/**
* The surface reads here over the scene `viewer` draws, for code that holds
* the viewer: the scene is read once, as this is called.
* @param {object|undefined} viewer
*/
export function viewerRoadSurface(viewer) {
const scene = viewer?.scene;
return {
drawnReady: () => drawnSurfaceReady(scene),
ready: () => trafficSurfaceReady(scene),
prepare: (roads, ...rest) => prepareRoadSurfaces(roads, scene, ...rest),
loadedHeight: (location, exclude) =>
loadedSurfaceHeight(scene, location, exclude),
};
}
/** Preserve bends and insert height samples at most 150 m apart, splitting long roads. */ /** Preserve bends and insert height samples at most 150 m apart, splitting long roads. */
export function roadSurfaceChunks(coordinates) { export function roadSurfaceChunks(coordinates) {
const chunks = []; const chunks = [];
+2 -2
View File
@@ -1,6 +1,6 @@
import { createReticleFootprint } from './footprint.js'; import { createReticleFootprint } from './footprint.js';
import { toLonLatH } from '../../geo/ellipsoid.js'; import { toLonLatH } from '../../geo/ellipsoid.js';
import { findCamera, findQuery } from '../../render/rendererOf.js'; import { canvasOf, findCamera, findQuery } from '../../render/rendererOf.js';
import { import {
deriveFetchCenter, deriveFetchCenter,
clampBoundsAroundCenter, clampBoundsAroundCenter,
@@ -27,7 +27,7 @@ export function createViewport({ state: layerState, services, parts, source }) {
/** The canvas size in CSS pixels, as the layer has always read it. */ /** The canvas size in CSS pixels, as the layer has always read it. */
function canvasSize() { function canvasSize() {
const canvas = layerState._viewer.scene.canvas; const canvas = canvasOf(layerState._viewer);
return { return {
width: canvas.clientWidth || canvas.width, width: canvas.clientWidth || canvas.width,
height: canvas.clientHeight || canvas.height, height: canvas.clientHeight || canvas.height,
+2 -2
View File
@@ -1,5 +1,5 @@
import { toLonLatH } from '../../geo/ellipsoid.js'; import { toLonLatH } from '../../geo/ellipsoid.js';
import { findCamera, findQuery } from '../../render/rendererOf.js'; import { canvasOf, findCamera, findQuery } from '../../render/rendererOf.js';
import { viewAreaRadiusKm } from './viewArea.js'; import { viewAreaRadiusKm } from './viewArea.js';
/** /**
@@ -13,7 +13,7 @@ export function vesselViewArea(viewer) {
const radiusKm = viewAreaRadiusKm(pose?.height); const radiusKm = viewAreaRadiusKm(pose?.height);
if (radiusKm == null) return null; if (radiusKm == null) return null;
let { lat, lon } = pose; let { lat, lon } = pose;
const canvas = viewer?.scene?.canvas; const canvas = canvasOf(viewer);
if (canvas?.clientWidth && canvas?.clientHeight) { if (canvas?.clientWidth && canvas?.clientHeight) {
try { try {
const hit = findQuery(viewer)?.pickEllipsoid( const hit = findQuery(viewer)?.pickEllipsoid(
+3
View File
@@ -7,6 +7,9 @@ import { vesselViewArea } from './cameraArea.js';
/** A viewer whose camera and query ports answer as given. */ /** A viewer whose camera and query ports answer as given. */
function viewerWith({ height, lon = 4, lat = 52, hit, size = [1600, 900] }) { function viewerWith({ height, lon = 4, lat = 52, hit, size = [1600, 900] }) {
const viewer = { const viewer = {
get canvas() {
return this.scene?.canvas;
},
scene: { canvas: { clientWidth: size[0], clientHeight: size[1] } }, scene: { canvas: { clientWidth: size[0], clientHeight: size[1] } },
}; };
const picks = []; const picks = [];
+2 -1
View File
@@ -10,6 +10,7 @@ import { fromDegrees } from '../../geo/ellipsoid.js';
import { horizonFrom, liftedForHorizon } from '../../geo/horizon.js'; import { horizonFrom, liftedForHorizon } from '../../geo/horizon.js';
import { distance } from '../../geo/vector.js'; import { distance } from '../../geo/vector.js';
import { import {
canvasOf,
drawOf, drawOf,
findCamera, findCamera,
findFrame, findFrame,
@@ -552,7 +553,7 @@ export function createRendering({
*/ */
function publishVesselOverlayEntries(entries) { function publishVesselOverlayEntries(entries) {
const canvas = state.viewer?.scene?.canvas || state.viewer?.canvas; const canvas = canvasOf(state.viewer);
const width = Number(canvas?.clientWidth) || 0; const width = Number(canvas?.clientWidth) || 0;
const height = Number(canvas?.clientHeight) || 0; const height = Number(canvas?.clientHeight) || 0;
const ambientLimit = vesselOverlayCohortLimit( const ambientLimit = vesselOverlayCohortLimit(
+7 -2
View File
@@ -11,7 +11,12 @@ import {
import { formatUtcDayMonth, t, msg } from '../../i18n/index.js'; import { formatUtcDayMonth, t, msg } from '../../i18n/index.js';
import { formatScaleLabel } from '../../ui/unitLabels.js'; import { formatScaleLabel } from '../../ui/unitLabels.js';
import { toLonLatH } from '../../geo/ellipsoid.js'; import { toLonLatH } from '../../geo/ellipsoid.js';
import { cameraOf, findCamera, findQuery } from '../../render/rendererOf.js'; import {
cameraOf,
canvasOf,
findCamera,
findQuery,
} from '../../render/rendererOf.js';
/** /**
* A stored (English) failure in the language. HTTP failures from source.js * A stored (English) failure in the language. HTTP failures from source.js
@@ -580,7 +585,7 @@ export function createWeatherLayer({
const shownProblem = problem ? presentWeatherProblem(problem) : null; const shownProblem = problem ? presentWeatherProblem(problem) : null;
const shownHost = hostStatus ? t(hostStatus) : null; const shownHost = hostStatus ? t(hostStatus) : null;
const b = manifest?.bounds; const b = manifest?.bounds;
const canvas = viewer?.scene?.canvas; const canvas = canvasOf(viewer);
const point = const point =
canvas && canvas &&
findQuery(viewer)?.pickEllipsoid( findQuery(viewer)?.pickEllipsoid(
+2 -2
View File
@@ -7,7 +7,7 @@ import {
} from './presentation.js'; } from './presentation.js';
import { inspectWindAtCenter, WIND_UNITS } from './inspection.js'; import { inspectWindAtCenter, WIND_UNITS } from './inspection.js';
import { createWindInspectionMarker } from './inspectionMarker.js'; import { createWindInspectionMarker } from './inspectionMarker.js';
import { findQuery } from '../../render/rendererOf.js'; import { canvasOf, findQuery } from '../../render/rendererOf.js';
import { t, msg, translateKnown } from '../../i18n/index.js'; import { t, msg, translateKnown } from '../../i18n/index.js';
import { unitLabel } from '../../ui/unitLabels.js'; import { unitLabel } from '../../ui/unitLabels.js';
@@ -81,7 +81,7 @@ export function createWindLayer({
}; };
const sample = (position) => { const sample = (position) => {
const view = viewer const view = viewer
? { query: findQuery(viewer), canvas: viewer.scene?.canvas } ? { query: findQuery(viewer), canvas: canvasOf(viewer) }
: {}; : {};
reading = inspectWindAtCenter(manifest, view, { reading = inspectWindAtCenter(manifest, view, {
position, position,
+3
View File
@@ -317,6 +317,9 @@ test('sample stays fixed across model, field and unit changes; dismissal and dis
let center = fromDegrees(0, 0); let center = fromDegrees(0, 0);
const viewer = { const viewer = {
container, container,
get canvas() {
return this.scene?.canvas;
},
scene: { scene: {
canvas: { clientWidth: 800, clientHeight: 600, getBoundingClientRect: () => ({ left: 0, top: 0 }) }, canvas: { clientWidth: 800, clientHeight: 600, getBoundingClientRect: () => ({ left: 0, top: 0 }) },
}, },
+2 -2
View File
@@ -1,6 +1,6 @@
import { useWindInspectionStore } from '../../ui/stores/windInspection.js'; import { useWindInspectionStore } from '../../ui/stores/windInspection.js';
import { applicationPinia } from '../../ui/vueRuntime.js'; import { applicationPinia } from '../../ui/vueRuntime.js';
import { findFrame, findQuery } from '../../render/rendererOf.js'; import { canvasOf, findFrame, findQuery } from '../../render/rendererOf.js';
/** /**
* One passive marker for the captured location; it never samples on camera * One passive marker for the captured location; it never samples on camera
@@ -33,7 +33,7 @@ export function createWindInspectionMarker({
return { return {
show(position) { show(position) {
clear(); clear();
const canvas = viewer?.scene?.canvas; const canvas = canvasOf(viewer);
const query = viewer ? findQuery(viewer) : null; const query = viewer ? findQuery(viewer) : null;
const frame = viewer ? findFrame(viewer) : null; const frame = viewer ? findFrame(viewer) : null;
if (!position || !container?.ownerDocument || !canvas || !query || !frame) if (!position || !container?.ownerDocument || !canvas || !query || !frame)
@@ -26,6 +26,9 @@ function fixture(t) {
const projected = []; const projected = [];
const requests = []; const requests = [];
const viewer = { const viewer = {
get canvas() {
return this.scene?.canvas;
},
scene: { scene: {
canvas: { canvas: {
clientWidth: 800, clientWidth: 800,
+10
View File
@@ -186,6 +186,16 @@ export function bindRenderer(host, renderer) {
*/ */
export const rendererOf = (host) => (host && renderers.get(host)) || null; export const rendererOf = (host) => (host && renderers.get(host)) || null;
/**
* The canvas the renderer bound to `host` draws in; with none bound, the
* scene object's own `canvas` (a viewer's), the same element the default
* renderer reports. For sizing by it and listening on it as DOM.
* @param {object|null|undefined} host
* @returns {HTMLCanvasElement|null}
*/
export const canvasOf = (host) =>
rendererOf(host)?.canvas ?? host?.canvas ?? null;
/** /**
* The camera port of the renderer bound to `host`; with no renderer bound, * The camera port of the renderer bound to `host`; with no renderer bound,
* one built over `host` by the provided factory and kept with it while * one built over `host` by the provided factory and kept with it while
+14
View File
@@ -3,6 +3,7 @@ import test from 'node:test';
import { import {
bindRenderer, bindRenderer,
cameraOf, cameraOf,
canvasOf,
drawOf, drawOf,
findCamera, findCamera,
findCredits, findCredits,
@@ -27,6 +28,19 @@ test('a scene finds its renderer until it is unbound', () => {
assert.equal(rendererOf(scene), null); assert.equal(rendererOf(scene), null);
}); });
test("canvasOf answers with the renderer's canvas, else the host's own", () => {
const own = { id: 'own' };
const drawn = { id: 'drawn' };
const scene = { canvas: own };
assert.equal(canvasOf(scene), own);
assert.equal(canvasOf({}), null);
assert.equal(canvasOf(null), null);
const unbind = bindRenderer(scene, { canvas: drawn });
assert.equal(canvasOf(scene), drawn);
unbind();
assert.equal(canvasOf(scene), own);
});
test('a stale unbind leaves a later binding alone', () => { test('a stale unbind leaves a later binding alone', () => {
const scene = {}; const scene = {};
const unbindFirst = bindRenderer(scene, { id: 'first' }); const unbindFirst = bindRenderer(scene, { id: 'first' });
+2 -2
View File
@@ -22,7 +22,7 @@ import { createToast } from '../ui/toast.js';
import { buildPlaybackQueue, playSceneQueue } from '../director/playback.js'; import { buildPlaybackQueue, playSceneQueue } from '../director/playback.js';
import { createScenePlaybackAdapter } from './playbackAdapter.js'; import { createScenePlaybackAdapter } from './playbackAdapter.js';
import { toRadians } from '../geo/vector.js'; import { toRadians } from '../geo/vector.js';
import { cameraOf, findCamera, rendererOf } from '../render/rendererOf.js'; import { cameraOf, canvasOf, findCamera } from '../render/rendererOf.js';
import { import {
SCENE_APPEND_RECIPES, SCENE_APPEND_RECIPES,
SCENE_RECIPES, SCENE_RECIPES,
@@ -137,7 +137,7 @@ export class SceneDirector {
this._cameraHandoffUnsubscribe = this._cameraHandoffUnsubscribe =
styleManager.subscribeCameraHandoff?.(yieldCamera); styleManager.subscribeCameraHandoff?.(yieldCamera);
// A viewer of the caller's own, with no renderer bound, has its canvas. // A viewer of the caller's own, with no renderer bound, has its canvas.
const canvas = rendererOf(viewer)?.canvas ?? viewer.scene?.canvas; const canvas = canvasOf(viewer);
for (const event of ['pointerdown', 'wheel']) for (const event of ['pointerdown', 'wheel'])
canvas?.addEventListener(event, yieldCamera, { passive: true }); canvas?.addEventListener(event, yieldCamera, { passive: true });
this._removeCameraInput = () => { this._removeCameraInput = () => {
+11 -1
View File
@@ -20,6 +20,7 @@
* - frame: phases from the scene's own `preUpdate`, `preRender` and * - frame: phases from the scene's own `preUpdate`, `preRender` and
* `postRender` events. * `postRender` events.
* - draw: a fake draw port (`fakeDrawPort.mjs`) unless one is given. * - draw: a fake draw port (`fakeDrawPort.mjs`) unless one is given.
* - canvas: the double's `canvas`, else its scene's.
*/ */
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { bindRenderer } from '../render/rendererOf.js'; import { bindRenderer } from '../render/rendererOf.js';
@@ -209,6 +210,15 @@ export function bindFakeCesiumScene(viewer, { draw = fakeDrawPort() } = {}) {
}; };
const query = fakeSceneQuery(viewer); const query = fakeSceneQuery(viewer);
const frame = fakeSceneFrame(viewer); const frame = fakeSceneFrame(viewer);
const unbind = bindRenderer(viewer, { draw, camera, query, frame }); const unbind = bindRenderer(viewer, {
// The double's canvas, as `bindFakeCesiumCamera`'s renderer reports it.
get canvas() {
return viewer.canvas ?? viewer.scene?.canvas;
},
draw,
camera,
query,
frame,
});
return { draw, camera, query, frame, unbind }; return { draw, camera, query, frame, unbind };
} }
+8 -1
View File
@@ -94,6 +94,13 @@ export function fakeDrawPort() {
*/ */
export function bindFakeDraw(viewer, renderer = {}) { export function bindFakeDraw(viewer, renderer = {}) {
const draw = fakeDrawPort(); const draw = fakeDrawPort();
const unbind = bindRenderer(viewer, { ...renderer, draw }); const unbind = bindRenderer(viewer, {
// The double's canvas, as `bindFakeCesiumCamera`'s renderer reports it.
get canvas() {
return viewer.canvas ?? viewer.scene?.canvas;
},
...renderer,
draw,
});
return { draw, unbind }; return { draw, unbind };
} }
+8 -3
View File
@@ -17,7 +17,12 @@ import {
TWO_PI, TWO_PI,
zeroToTwoPi, zeroToTwoPi,
} from '../geo/index.js'; } from '../geo/index.js';
import { findCamera, findFrame, findQuery } from '../render/rendererOf.js'; import {
canvasOf,
findCamera,
findFrame,
findQuery,
} from '../render/rendererOf.js';
import { placeFollowEye } from './shareFollow.js'; import { placeFollowEye } from './shareFollow.js';
function trackedTarget(viewer) { function trackedTarget(viewer) {
@@ -55,7 +60,7 @@ function cubicInOut(k) {
/** Return the world position under the center of the canvas, when available. */ /** Return the world position under the center of the canvas, when available. */
export function pickViewTarget(viewer) { export function pickViewTarget(viewer) {
const query = findQuery(viewer); const query = findQuery(viewer);
const canvas = viewer?.scene?.canvas; const canvas = canvasOf(viewer);
if (!query || !canvas) return null; if (!query || !canvas) return null;
const width = canvas.clientWidth || canvas.width || 0; const width = canvas.clientWidth || canvas.width || 0;
const height = canvas.clientHeight || canvas.height || 0; const height = canvas.clientHeight || canvas.height || 0;
@@ -329,7 +334,7 @@ export function bindCameraOrientationControls({
subscribe(findCamera(viewer)?.on('moveEnd', refreshTilt)); subscribe(findCamera(viewer)?.on('moveEnd', refreshTilt));
if (viewer) removers.push(onFollowChanged(viewer, animator.cancel)); if (viewer) removers.push(onFollowChanged(viewer, animator.cancel));
for (const type of ['pointerdown', 'wheel']) { for (const type of ['pointerdown', 'wheel']) {
const canvas = viewer?.scene?.canvas; const canvas = canvasOf(viewer);
canvas?.addEventListener?.(type, animator.cancel, { passive: true }); canvas?.addEventListener?.(type, animator.cancel, { passive: true });
removers.push(() => canvas?.removeEventListener?.(type, animator.cancel)); removers.push(() => canvas?.removeEventListener?.(type, animator.cancel));
} }
+3 -2
View File
@@ -15,6 +15,7 @@ import { inputFor as defaultInputFor } from '../input/dispatcher.js';
import { validateBox } from '../layers/recentImagery/model.js'; import { validateBox } from '../layers/recentImagery/model.js';
import { createImageryBoxPreview } from '../layers/recentImagery/rendering.js'; import { createImageryBoxPreview } from '../layers/recentImagery/rendering.js';
import { msg } from '../i18n/index.js'; import { msg } from '../i18n/index.js';
import { canvasOf } from '../render/rendererOf.js';
/** The id this tool claims the pointer under. */ /** The id this tool claims the pointer under. */
export const IMAGERY_BOX_POINTER_OWNER = 'recent-imagery-box'; export const IMAGERY_BOX_POINTER_OWNER = 'recent-imagery-box';
@@ -39,7 +40,7 @@ export function initImageryBoxTool({
pickWorld = pickWorldFromScreen, pickWorld = pickWorldFromScreen,
documentRef = globalThis.document, documentRef = globalThis.document,
} = {}) { } = {}) {
if (!viewer?.scene || typeof onBox !== 'function') return null; if (!viewer || typeof onBox !== 'function') return null;
let active = false; let active = false;
let destroyed = false; let destroyed = false;
@@ -62,7 +63,7 @@ export function initImageryBoxTool({
const setPreview = (visible) => preview.setVisible(visible); const setPreview = (visible) => preview.setVisible(visible);
const worldAt = (position) => { const worldAt = (position) => {
if (!position) return null; if (!position) return null;
const canvas = viewer.scene.canvas; const canvas = canvasOf(viewer);
const w = canvas?.clientWidth || canvas?.width || 1; const w = canvas?.clientWidth || canvas?.width || 1;
const h = canvas?.clientHeight || canvas?.height || 1; const h = canvas?.clientHeight || canvas?.height || 1;
const point = pickWorld(viewer, position.x / w, position.y / h); const point = pickWorld(viewer, position.x / w, position.y / h);
+20
View File
@@ -24,6 +24,26 @@ function defaultValueText(beforePercent, afterPercent) {
return `A ${beforePercent} percent, B ${afterPercent} percent`; return `A ${beforePercent} percent, B ${afterPercent} percent`;
} }
/**
* A globe port's split as `createImagerySplit` writes it (its `scene`): the
* divider moves the globe's split through the port. Null when the globe
* has no split.
* @param {import('../render/contract/globe').GlobePort|null|undefined} globe
* @returns {{splitPosition: number}|null}
*/
export function globeSplitTarget(globe) {
const imagery = globe?.imagery;
if (!imagery?.setSplit) return null;
return {
get splitPosition() {
return imagery.getSplit();
},
set splitPosition(value) {
imagery.setSplit(value);
},
};
}
/** /**
* Split divider for before/after imagery comparison. * Split divider for before/after imagery comparison.
* *
+4 -3
View File
@@ -17,7 +17,7 @@ import {
tn, tn,
translateKnown, translateKnown,
} from '../i18n/index.js'; } from '../i18n/index.js';
import { createImagerySplit } from './imagerySplit.js'; import { createImagerySplit, globeSplitTarget } from './imagerySplit.js';
import RecentImageryReadout from './recentImagery/RecentImageryReadout.vue'; import RecentImageryReadout from './recentImagery/RecentImageryReadout.vue';
import { import {
PRODUCTS, PRODUCTS,
@@ -27,6 +27,7 @@ import {
import { displayDay, displayMetres } from '../layers/recentImagery/display.js'; import { displayDay, displayMetres } from '../layers/recentImagery/display.js';
import { formatQuantity } from './unitLabels.js'; import { formatQuantity } from './unitLabels.js';
import { pointerOwnerName } from '../data/pointerOwnerNames.js'; import { pointerOwnerName } from '../data/pointerOwnerNames.js';
import { canvasOf, findGlobe } from '../render/rendererOf.js';
const PANEL_ID = 'recent-imagery-panel'; const PANEL_ID = 'recent-imagery-panel';
const OVERVIEW_MIN_BOX_KM = 25; const OVERVIEW_MIN_BOX_KM = 25;
@@ -701,7 +702,7 @@ export function createRecentImageryPanel({
} }
if (!live || split || destroyed) return; if (!live || split || destroyed) return;
split = createSplit({ split = createSplit({
scene: viewer?.scene, scene: globeSplitTarget(findGlobe(viewer)),
initialValue: snapshot.split, initialValue: snapshot.split,
id: 'recent-imagery-split-line', id: 'recent-imagery-split-line',
handleClass: 'recent-imagery-split-handle', handleClass: 'recent-imagery-split-handle',
@@ -722,7 +723,7 @@ export function createRecentImageryPanel({
right: rightPercent, right: rightPercent,
}), }),
getViewportWidth: () => getViewportWidth: () =>
Number(viewer?.scene?.canvas?.clientWidth) || Number(canvasOf(viewer)?.clientWidth) ||
Number(document.documentElement?.clientWidth) || Number(document.documentElement?.clientWidth) ||
0, 0,
onChange: (value) => layer.setSplit(value), onChange: (value) => layer.setSplit(value),
+7 -1
View File
@@ -17,6 +17,7 @@ import {
settle, settle,
} from '../layers/recentImagery/testDoubles.mjs'; } from '../layers/recentImagery/testDoubles.mjs';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { fakeGlobePort } from '../testSupport/fakeGlobePort.mjs';
const S18 = 'S30:2026-09-18'; const S18 = 'S30:2026-09-18';
const L16 = 'L30:2026-09-16'; const L16 = 'L30:2026-09-16';
@@ -130,7 +131,8 @@ function fixture({ fetchImpl, controller = fakeController() } = {}) {
camera: {}, camera: {},
scene: { canvas: { clientWidth: 1000 }, requestRender() {} }, scene: { canvas: { clientWidth: 1000 }, requestRender() {} },
}; };
bindFakeCesiumCamera(viewer); const globe = fakeGlobePort();
bindFakeCesiumCamera(viewer, { globe });
layer.init(viewer); layer.init(viewer);
layer.attachMapStackController(controller); layer.attachMapStackController(controller);
let active = false; let active = false;
@@ -213,6 +215,7 @@ function fixture({ fetchImpl, controller = fakeController() } = {}) {
...dom, ...dom,
layer, layer,
viewer, viewer,
globe,
renderer, renderer,
thumbnails, thumbnails,
catalog, catalog,
@@ -879,6 +882,9 @@ test('the divider exists only while a swipe is live, labelled A / B or IMAGE / B
assert.equal(f.splits.length, 1); assert.equal(f.splits.length, 1);
assert.deepEqual(labels(), ['IMAGE', 'BASEMAP']); assert.deepEqual(labels(), ['IMAGE', 'BASEMAP']);
assert.equal(f.splits[0].options.id, 'recent-imagery-split-line'); assert.equal(f.splits[0].options.id, 'recent-imagery-split-line');
// The divider moves the globe's split, through the renderer's globe port.
f.splits[0].options.scene.splitPosition = 0.3;
assert.equal(f.globe.imagery.getSplit(), 0.3);
assert.deepEqual(swapState(), [false, false, 'false', 'false']); assert.deepEqual(swapState(), [false, false, 'false', 'false']);
assert.deepEqual(directions(), ['left', undefined]); assert.deepEqual(directions(), ['left', undefined]);
// VS BASEMAP: SWAP puts the image right of the basemap, and back. // VS BASEMAP: SWAP puts the image right of the basemap, and back.
+2 -1
View File
@@ -5,6 +5,7 @@ import { createVoiceCommands } from './commands.js';
import { cameraPoseKey, createPointerTracker } from './pointerContext.js'; import { cameraPoseKey, createPointerTracker } from './pointerContext.js';
import { createPointerPicker } from './pointerPick.js'; import { createPointerPicker } from './pointerPick.js';
import { createReferentRegistry } from './referents.js'; import { createReferentRegistry } from './referents.js';
import { canvasOf } from '../render/rendererOf.js';
export * from './realtimeController.js'; export * from './realtimeController.js';
const ACTION_NAMES = new Set(GEV_ACTION_SCHEMAS.map((schema) => schema.name)); const ACTION_NAMES = new Set(GEV_ACTION_SCHEMAS.map((schema) => schema.name));
@@ -32,7 +33,7 @@ export function withToolCatalog(runner, loadCatalog) {
/** Compose the standalone action runner with the voice controls. */ /** Compose the standalone action runner with the voice controls. */
export function initGevVoiceCommands(options) { export function initGevVoiceCommands(options) {
const canvas = options.viewer?.scene?.canvas || null; const canvas = canvasOf(options.viewer);
const cameraKey = () => cameraPoseKey(options.viewer); const cameraKey = () => cameraPoseKey(options.viewer);
// Point-and-ask: the tracker and referents are shared by the runner (which // Point-and-ask: the tracker and referents are shared by the runner (which
// resolves 'pointer' and referent:n) and the controls (which snapshot the // resolves 'pointer' and referent:n) and the controls (which snapshot the
+3 -4
View File
@@ -1,5 +1,5 @@
import { pickAt as defaultPickAt } from '../input/dispatcher.js'; import { pickAt as defaultPickAt } from '../input/dispatcher.js';
import { findCamera } from '../render/rendererOf.js'; import { canvasOf, findCamera } from '../render/rendererOf.js';
import { resolvePickedContext } from '../data/pickedContext.js'; import { resolvePickedContext } from '../data/pickedContext.js';
import { cameraPoseKey } from './pointerContext.js'; import { cameraPoseKey } from './pointerContext.js';
import * as defaultAnnotationResolver from '../annotations/annotationResolver.js'; import * as defaultAnnotationResolver from '../annotations/annotationResolver.js';
@@ -37,9 +37,8 @@ export function createPointerPicker({
pickAt = defaultPickAt, pickAt = defaultPickAt,
}) { }) {
return function pickPointer(x, y) { return function pickPointer(x, y) {
const scene = viewer?.scene; const canvas = canvasOf(viewer);
const canvas = scene?.canvas; if (!canvas) return null;
if (!scene || !canvas) return null;
const width = canvas.clientWidth || canvas.width || 0; const width = canvas.clientWidth || canvas.width || 0;
const height = canvas.clientHeight || canvas.height || 0; const height = canvas.clientHeight || canvas.height || 0;
if (!width || !height) return null; if (!width || !height) return null;
+3 -2
View File
@@ -3,6 +3,7 @@ import {
hasStructuredViewIdentity, hasStructuredViewIdentity,
} from './realtimeProtocol.js'; } from './realtimeProtocol.js';
import { cameraPoseKey } from './pointerContext.js'; import { cameraPoseKey } from './pointerContext.js';
import { canvasOf } from '../render/rendererOf.js';
/** The live viewer's camera pose identity (Cesium-free read). */ /** The live viewer's camera pose identity (Cesium-free read). */
function readViewerCameraKey() { function readViewerCameraKey() {
@@ -20,7 +21,7 @@ const VIEWPORT_MAX_ENCODED_BYTES = 200 * 1024;
export async function captureViewportImage() { export async function captureViewportImage() {
const viewer = window.__godsEyeView?.viewer; const viewer = window.__godsEyeView?.viewer;
const source = const source =
viewer?.scene?.canvas || canvasOf(viewer) ||
document.querySelector('#cesiumContainer .cesium-widget canvas'); document.querySelector('#cesiumContainer .cesium-widget canvas');
if (!source || !source.width || !source.height) return null; if (!source || !source.width || !source.height) return null;
// No fresh frame (hidden, or the bounded render wait timed out) → no // No fresh frame (hidden, or the bounded render wait timed out) → no
@@ -130,7 +131,7 @@ export function pointerCropRect({
*/ */
async function capturePointerCrop(screenPx) { async function capturePointerCrop(screenPx) {
const viewer = window.__godsEyeView?.viewer; const viewer = window.__godsEyeView?.viewer;
const source = viewer?.scene?.canvas; const source = canvasOf(viewer);
if (!source?.width || !source?.height || !screenPx) return null; if (!source?.width || !source?.height || !screenPx) return null;
const fresh = await renderFreshPointerFrame(viewer); const fresh = await renderFreshPointerFrame(viewer);
if (!fresh) return null; if (!fresh) return null;