Draw the Bhote Koshi event through the renderer's ports and take it off the Cesium list

The flood is two draw sets per layer: the corridor's dashed halo and
glowing core as draped lines (on tiles too under photoreal, on terrain
otherwise), moved in the frame the event moves them, and the surge front
as a clamped point. Only what changed is drawn again. Neither set is
pickable, and height queries see through both, so the shot paths no
longer list them to exclude.

The before/after images are globe-port layers on either side of the
split, over every layer drawn when they are added and draped on the
globe's surface only, as before. The divider moves the globe port's
split. An image that fails to load now takes the comparison (the pair,
the divider and its labels) down and leaves the event on, where a
failed provider used to fail the enable.

Evidence heights come through heightsOf, whose batch can now count an
answer from the bare ellipsoid as a miss, so points still fall back to
their authored elevations without terrain. The camera, canvas and the
event's vector maths go through the camera port, the renderer and
src/geo (lerp joins geo/vector).
This commit is contained in:
Sameh Khamis committed 2026-11-07 07:23:25 -08:00
1 parent bddb890326
commit 6bbe35f232
6 files changed
+570 -312

No files matched your search

+281 -169
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { isPointerFree } from './inputOwnership.js';
import {
clearOverlaySource,
@@ -28,9 +27,17 @@ import { createImagerySplit } from '../ui/imagerySplit.js';
import { formatDate, t, tn, msg, onLocaleChange } from '../i18n/index.js';
import { useBhoteKoshiPanelStore } from '../ui/stores/bhoteKoshiPanel.js';
import { applicationPinia } from '../ui/vueRuntime.js';
import { heightsFor } from '../render/cesium/heights.js';
import { cameraOf } from '../render/cesium/camera.js';
import { findCamera } from '../render/rendererOf.js';
import { heightsOf } from '../queries/heights.js';
import {
cameraOf,
drawOf,
findCamera,
findGlobe,
rendererOf,
} from '../render/rendererOf.js';
import { hexColor } from '../render/color.js';
import { fromDegrees } from '../geo/ellipsoid.js';
import { clone, lerp, lerpInto, toRadians, vec } from '../geo/vector.js';
export const BHOTE_KOSHI_LAYER_ID = 'bhote-koshi-2026';
export const BHOTE_KOSHI_OVERLAY_SOURCE_ID = 'bhote-koshi-witnesses';
@@ -49,8 +56,24 @@ const SCENE_PATH_RENDER_HOLD = 'bhote-koshi-scene-path-travel';
const SCENE_MEDIA_MIN_PLAYBACK_SECONDS = 6;
const SCENE_MEDIA_EXIT_SECONDS = 0.65;
const BHOTE_EVENT_ACCENT = WORLD_OVERLAY_STYLE.accent;
const FLOOD_COLOR = Cesium.Color.fromCssColorString('#d8954e').withAlpha(0.68);
const SURGE_COLOR = Cesium.Color.fromCssColorString('#e8b47c');
const FLOOD_ACCENT = '#d8954e';
const FLOOD_HALO_COLOR = hexColor(FLOOD_ACCENT, 0.38);
const FLOOD_CORE_COLOR = hexColor(FLOOD_ACCENT, 0.96);
const SURGE_COLOR = hexColor('#e8b47c');
const SURGE_OUTLINE_COLOR = [0, 0, 0, 0.85];
const FLOOD_HALO_ID = 'bhote-koshi-flood-halo';
const FLOOD_CORE_ID = 'bhote-koshi-flood-core';
const SURGE_FRONT_ID = 'bhote-koshi-surge-front';
const IMAGERY_CREDIT = Object.freeze({
text: 'Vantor WorldView Open Data · CC BY-NC 4.0',
});
// Each layer's draw sets have ids of their own.
let layerSerial = 0;
/** Whether two positions are the same point; either may be null. */
const samePoint = (a, b) =>
a === b || (Boolean(a && b) && a.x === b.x && a.y === b.y && a.z === b.z);
const CINEMATIC_INPUT_EVENTS = Object.freeze(['pointerdown', 'wheel']);
const CINEMATIC_VIEW_SPECS = Object.freeze([
{
@@ -122,12 +145,23 @@ const DEFAULT_EVENT_LOADER = async () => {
throw new Error(`Bhote Koshi event pack unavailable (${response.status})`);
return response.json();
};
const DEFAULT_IMAGERY_PROVIDER_FACTORY = (url, options) =>
Cesium.SingleTileImageryProvider.fromUrl(url, options);
/** The globe port's spec for one of the event's images, over `rectangle`. */
const DEFAULT_IMAGERY_SPEC_FACTORY = (url, { rectangle, credit }) => ({
kind: 'single-image',
url,
rectangle,
credit,
});
/**
* Terrain heights under the observations, once the most detailed terrain
* has loaded. The bare ellipsoid answers no height, as there is no terrain
* to sample then.
*/
const DEFAULT_TERRAIN_SAMPLER = async (viewer, observations) => {
if (!viewer?.scene || !viewer.terrainProvider?.availability) return null;
const heights = await heightsFor(viewer.scene).batch(observations, {
if (!viewer) return null;
const heights = await heightsOf(viewer).batch(observations, {
against: 'terrain',
ellipsoidMisses: true,
});
return heights.map((height) => ({ height }));
};
@@ -181,7 +215,7 @@ export function visibleSegmentCount(progress, segmentCount) {
/**
* Build a corridor whose final vertex is the exact animated surge position.
* Returns true only when the Cesium polyline assignments need refreshing.
* Returns true only when the drawn corridor needs refreshing.
*/
export function updateCorridorPositionCache(progress, terrainPositions, cache) {
const positions = Array.isArray(terrainPositions) ? terrainPositions : [];
@@ -204,15 +238,15 @@ export function updateCorridorPositionCache(progress, terrainPositions, cache) {
const startIndex = Math.min(segmentCount - 1, Math.floor(scaledProgress));
const segmentProgress =
normalizedProgress >= 1 ? 1 : scaledProgress - startIndex;
cache.headPosition = Cesium.Cartesian3.lerp(
cache.headPosition = lerpInto(
positions[startIndex],
positions[startIndex + 1],
segmentProgress,
cache.headPosition || new Cesium.Cartesian3(),
cache.headPosition || vec(),
);
cache.positions = positions.slice(0, startIndex + 1);
if (segmentProgress > 0) {
cache.positions.push(Cesium.Cartesian3.clone(cache.headPosition));
cache.positions.push(clone(cache.headPosition));
}
return true;
}
@@ -519,19 +553,19 @@ export function sampleCinematicPose(progress, keyframes, result = {}) {
: (linearAmount - BHOTE_KOSHI_CAMERA_HOLD_RATIO) /
(1 - BHOTE_KOSHI_CAMERA_HOLD_RATIO);
const amount = travelAmount * travelAmount * (3 - 2 * travelAmount);
result.target = Cesium.Cartesian3.lerp(
result.target = lerpInto(
from.target,
to.target,
amount,
result.target || new Cesium.Cartesian3(),
result.target || vec(),
);
result.headingDeg = interpolateHeadingDegrees(
from.headingDeg,
to.headingDeg,
amount,
);
result.pitchDeg = Cesium.Math.lerp(from.pitchDeg, to.pitchDeg, amount);
result.rangeM = Cesium.Math.lerp(from.rangeM, to.rangeM, amount);
result.pitchDeg = lerp(from.pitchDeg, to.pitchDeg, amount);
result.rangeM = lerp(from.rangeM, to.rangeM, amount);
result.fromId = from.id;
result.toId = to.id;
return result;
@@ -885,14 +919,14 @@ function openExternal(url) {
function focusView(viewer, viewpoint) {
announceNavigationAuthority('bhote-koshi-event-focus');
const target = Cesium.Cartesian3.fromDegrees(
const target = fromDegrees(
viewpoint.lon,
viewpoint.lat,
viewpoint.targetElevationM,
);
const offset = {
heading: Cesium.Math.toRadians(viewpoint.headingDeg),
pitch: Cesium.Math.toRadians(viewpoint.pitchDeg),
heading: toRadians(viewpoint.headingDeg),
pitch: toRadians(viewpoint.pitchDeg),
range: viewpoint.rangeM,
};
const camera = cameraOf(viewer);
@@ -985,7 +1019,7 @@ export function createBhoteKoshiEventLayer({
overlayHost = DEFAULT_OVERLAY_HOST,
renderHost = DEFAULT_RENDER_HOST,
eventLoader = DEFAULT_EVENT_LOADER,
imageryProviderFactory = DEFAULT_IMAGERY_PROVIDER_FACTORY,
imagerySpecFactory = DEFAULT_IMAGERY_SPEC_FACTORY,
terrainSampler = DEFAULT_TERRAIN_SAMPLER,
mediaLoader = DEFAULT_MEDIA_LOADER,
evidenceFrameFactory = createEvidenceFrame,
@@ -1011,12 +1045,19 @@ export function createBhoteKoshiEventLayer({
let _splitControl = null;
let _beforeLayer = null;
let _afterLayer = null;
let _imageryLayerCollection = null;
let _floodDataSource = null;
// An event image failed to load this enable: no comparison is shown.
let _imageryFailed = false;
const _serial = ++layerSerial;
// The flood's draw sets: the corridor's halo and core lines, and the
// surge front. Null while the layer is off.
let _floodSets = null;
let _floodSurfaceMode = null;
let _floodHalo = null;
let _floodCore = null;
let _surgePoint = null;
// What the flood shows, set as the story moves, and what was last drawn
// of it (`drawFlood`).
let _floodShow = false;
let _surgeShow = false;
let _surgePosition = null;
let _floodDrawn = null;
let _terrainPositions = [];
let _sourceShotPaths = new Map();
let _scenePathPositionCache = new Map();
@@ -1050,7 +1091,7 @@ export function createBhoteKoshiEventLayer({
let _cinematicKeyframes = [];
let _cinematicActive = false;
let _cinematicReplayArmed = false;
let _cinematicPose = { target: new Cesium.Cartesian3() };
let _cinematicPose = { target: vec() };
const _cinematicOffset = { heading: 0, pitch: 0, range: 0 };
let _lastCinematicProgress = null;
let _cameraInputTarget = null;
@@ -1066,7 +1107,6 @@ export function createBhoteKoshiEventLayer({
let _comparisonLease = null;
let _introTimer = null;
let _introGeneration = 0;
let _lastSurgePosition = null;
let _lastSurgeVisible = null;
let _presentation = 'standalone';
let _sceneBeatId = null;
@@ -1152,33 +1192,52 @@ export function createBhoteKoshiEventLayer({
}
async function createImagery(event) {
const rectangle = Cesium.Rectangle.fromDegrees(
event.imagery.rectangle.west,
event.imagery.rectangle.south,
event.imagery.rectangle.east,
event.imagery.rectangle.north,
);
const [beforeProvider, afterProvider] = await Promise.all([
imageryProviderFactory(eventAsset(event.imagery.before.path), {
rectangle,
credit: 'Vantor WorldView Open Data · CC BY-NC 4.0',
}),
imageryProviderFactory(eventAsset(event.imagery.after.path), {
rectangle,
credit: 'Vantor WorldView Open Data · CC BY-NC 4.0',
}),
_imageryFailed = false;
const { west, south, east, north } = event.imagery.rectangle;
const options = {
rectangle: { west, south, east, north },
credit: IMAGERY_CREDIT,
};
const [beforeSpec, afterSpec] = await Promise.all([
imagerySpecFactory(eventAsset(event.imagery.before.path), options),
imagerySpecFactory(eventAsset(event.imagery.after.path), options),
]);
if (!_enabled) return;
_imageryLayerCollection = _viewer.imageryLayers;
_beforeLayer = _imageryLayerCollection.addImageryProvider(beforeProvider);
_afterLayer = _imageryLayerCollection.addImageryProvider(afterProvider);
_beforeLayer.splitDirection = Cesium.SplitDirection.LEFT;
_afterLayer.splitDirection = Cesium.SplitDirection.RIGHT;
_beforeLayer.alpha = 0.96;
_afterLayer.alpha = 0.96;
const globe = findGlobe(_viewer);
if (!globe)
throw new Error('Bhote Koshi imagery needs a globe to drape on');
_beforeLayer = addEventImagery(globe, beforeSpec, 'left');
_afterLayer = addEventImagery(globe, afterSpec, 'right');
setSplit(_split);
}
/**
* One of the before/after images, on its side of the split, over every
* layer drawn so far. It drapes on the globe's surface only, as the
* comparison is drawn on terrain.
*/
function addEventImagery(globe, spec, split) {
const layer = globe.imagery.add(spec, globe.imagery.list().length);
layer.split = split;
layer.alpha = 0.96;
layer.drapeOn = 'surface';
layer.on('tileError', (error) => imageryFailed(error));
return layer;
}
/**
* An image that did not load: without both images there is nothing to
* compare, so the pair and the comparison's divider and labels go.
*/
function imageryFailed(error) {
if (_imageryFailed) return;
_imageryFailed = true;
console.warn('[Data:BhoteKoshi] Event imagery unavailable:', error);
removeImagery();
syncPresentationMode();
renderHost.request('bhote-koshi-imagery-failed');
}
async function resolveEvidenceAnchors(event, signal) {
const observations = Array.isArray(event.evidenceSpine)
? event.evidenceSpine
@@ -1198,7 +1257,7 @@ export function createBhoteKoshiEventLayer({
// A miss is null or undefined, never sea level.
const sampledHeight = Number(sampled?.[index]?.height ?? Number.NaN);
const fallbackHeight = Number(observation.fallbackElevationM) || 0;
return Cesium.Cartesian3.fromDegrees(
return fromDegrees(
observation.lon,
observation.lat,
(Number.isFinite(sampledHeight) ? sampledHeight : fallbackHeight) + 18,
@@ -1239,7 +1298,7 @@ export function createBhoteKoshiEventLayer({
function showWitnessEmbed() {
const witness = _event?.witnessAnchors?.[0];
if (!witness?.sourceUrl) return false;
const anchor = Cesium.Cartesian3.fromDegrees(
const anchor = fromDegrees(
witness.lon,
witness.lat,
(Number(witness.elevationM) || 0) + 18,
@@ -1565,22 +1624,21 @@ export function createBhoteKoshiEventLayer({
const cached = _scenePathPositionCache.get(cacheKey);
if (cached) return cached;
const positions = (_sourceShotPaths.get(beatId) || []).map((point) => {
const position = Cesium.Cartographic.fromDegrees(point.lon, point.lat);
const position = { lon: point.lon, lat: point.lat };
let height;
// Some schematic reaches have a source elevation profile. Do not replace
// it with coarse mesh heights on entry/exit from the comparison surface:
// a single high sample can make the front dive backward in screen space.
if (_sceneControls.evidencePathElevation !== 'source') {
// Sample once while preparing the shot, never from an animation frame.
const heights = _viewer?.scene ? heightsFor(_viewer.scene) : null;
height = heights?.now(position, {
exclude: [_floodCore, _floodHalo, _surgePoint].filter(Boolean),
});
// The flood's own sets are not ground: queries see through them.
const heights = _viewer ? heightsOf(_viewer) : null;
height = heights?.now(position);
if (!Number.isFinite(height))
height = heights?.now(position, { against: 'terrain' });
}
if (!Number.isFinite(height)) height = point.fallbackElevationM;
return Cesium.Cartesian3.fromDegrees(point.lon, point.lat, height + 8);
return fromDegrees(point.lon, point.lat, height + 8);
});
_scenePathPositionCache.set(cacheKey, positions);
return positions;
@@ -2477,11 +2535,7 @@ export function createBhoteKoshiEventLayer({
const elevationOffsetM =
_presentation === BHOTE_KOSHI_SCENE_PRESENTATION ? 55 : 8;
_terrainPositions = event.reconstruction.corridor.map((point) =>
Cesium.Cartesian3.fromDegrees(
point.lon,
point.lat,
point.elevationM + elevationOffsetM,
),
fromDegrees(point.lon, point.lat, point.elevationM + elevationOffsetM),
);
prepareScenePath();
_evidenceTimeline = buildEvidenceTimeline(
@@ -2519,86 +2573,157 @@ export function createBhoteKoshiEventLayer({
updateProgress(_progress);
}
function createFloodDataSource() {
const tileSafe = usesPhotorealFloodSurface();
_floodSurfaceMode = tileSafe ? 'tiles' : 'terrain';
const haloMaterial = new Cesium.PolylineDashMaterialProperty({
color: FLOOD_COLOR.withAlpha(0.38),
dashLength: 18,
});
const coreMaterial = new Cesium.PolylineGlowMaterialProperty({
color: FLOOD_COLOR.withAlpha(0.96),
glowPower: 0.24,
taperPower: 0.7,
});
_floodDataSource = new Cesium.CustomDataSource('bhote-koshi-flood');
_floodHalo = _floodDataSource.entities.add({
id: 'bhote-koshi-flood-halo',
/** The flood's draw sets, drawing nothing until the story shows it. */
function createFloodSets() {
_floodSurfaceMode = usesPhotorealFloodSurface() ? 'tiles' : 'terrain';
const draw = drawOf(_viewer);
const prefix = `${BHOTE_KOSHI_LAYER_ID}:${_serial}`;
// Presentation only: clicks go through to what is under them.
_floodSets = {
lines: draw.lines({ id: `${prefix}:flood`, pickable: false }),
surge: draw.points({
id: `${prefix}:surge-front`,
pickable: false,
clampTo: 'both',
}),
};
resetFloodDrawn();
}
function resetFloodDrawn() {
_floodShow = false;
_surgeShow = false;
_surgePosition = null;
_lastSurgeVisible = null;
_floodDrawn = {
positions: null,
show: false,
polyline: {
positions: new Cesium.CallbackProperty(
() => _corridorPositionCache.positions,
false,
),
width: 18,
// Dynamic non-ground Cesium lines do not support depthFailMaterial.
// Classify the active surface so later-refined mesh tiles cannot bury it.
clampToGround: true,
material: haloMaterial,
classificationType: tileSafe
? Cesium.ClassificationType.BOTH
: Cesium.ClassificationType.TERRAIN,
surge: null,
surgeShow: false,
};
}
function removeFloodSets() {
_floodSets?.lines.dispose();
_floodSets?.surge.dispose();
_floodSets = null;
_floodSurfaceMode = null;
resetFloodDrawn();
}
/**
* The corridor's lines along `positions`: a dashed halo under a glowing
* core, draped on the surface the flood is drawn on (tiles too under
* photoreal, so later-refined tiles cannot bury it).
*/
function floodLines(positions, show) {
const clampTo = _floodSurfaceMode === 'tiles' ? 'both' : 'terrain';
return [
{
id: FLOOD_HALO_ID,
positions,
widthPx: 18,
mode: 'draped',
clampTo,
style: { kind: 'dash', color: FLOOD_HALO_COLOR, length: 18 },
show,
},
});
_floodCore = _floodDataSource.entities.add({
id: 'bhote-koshi-flood-core',
show: false,
polyline: {
positions: new Cesium.CallbackProperty(
() => _corridorPositionCache.positions,
false,
),
width: 5,
clampToGround: true,
material: coreMaterial,
classificationType: tileSafe
? Cesium.ClassificationType.BOTH
: Cesium.ClassificationType.TERRAIN,
{
id: FLOOD_CORE_ID,
positions,
widthPx: 5,
mode: 'draped',
clampTo,
style: {
kind: 'glow',
color: FLOOD_CORE_COLOR,
power: 0.24,
taper: 0.7,
},
show,
},
});
_surgePoint = _floodDataSource.entities.add({
id: 'bhote-koshi-surge-front',
show: false,
position: Cesium.Cartesian3.ZERO,
point: {
pixelSize: 11,
color: SURGE_COLOR,
outlineColor: Cesium.Color.BLACK.withAlpha(0.85),
outlineWidth: 3,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: tileSafe ? Number.POSITIVE_INFINITY : 0,
},
});
_viewer.dataSources.add(_floodDataSource);
];
}
function surgeItem(position, show) {
return {
id: SURGE_FRONT_ID,
pos: position,
height: 'clampGround',
pixelSize: 11,
color: SURGE_COLOR,
outlineColor: SURGE_OUTLINE_COLOR,
outlineWidth: 3,
disableDepthTest:
_floodSurfaceMode === 'tiles' ? Number.POSITIVE_INFINITY : 0,
show,
};
}
/**
* Draw the flood as it now stands, changing only what changed: the
* corridor where it has grown to and whether it shows, and the surge
* front's place and whether it shows.
*/
function drawFlood() {
if (!_floodSets) return;
const drawn = _floodDrawn;
const positions = _corridorPositionCache.positions;
if (positions.length > 1) {
if (positions !== drawn.positions || _floodShow !== drawn.show) {
_floodSets.lines.upsert(floodLines(positions, _floodShow));
drawn.positions = positions;
drawn.show = _floodShow;
}
} else if (drawn.show) {
// Too short to be a line: the last one drawn hides, kept so the next
// can still be drawn where it moves in the same frame.
_floodSets.lines.upsert(floodLines(drawn.positions, false));
drawn.show = false;
}
if (
_surgePosition &&
(!samePoint(_surgePosition, drawn.surge) ||
_surgeShow !== drawn.surgeShow)
) {
drawn.surge = _surgePosition;
drawn.surgeShow = _surgeShow;
_floodSets.surge.upsert([surgeItem(drawn.surge, _surgeShow)]);
}
}
function syncFloodSurfaceMode() {
const nextMode = usesPhotorealFloodSurface() ? 'tiles' : 'terrain';
if (!_viewer || !_floodDataSource || _floodSurfaceMode === nextMode) return;
_viewer.dataSources.remove(_floodDataSource, true);
_floodDataSource = null;
_floodHalo = null;
_floodCore = null;
_surgePoint = null;
_lastSurgePosition = null;
_lastSurgeVisible = null;
if (!_viewer || !_floodSets || _floodSurfaceMode === nextMode) return;
// Drawn anew on the other surface as the story next moves.
removeFloodSets();
_corridorPositionCache = { visibleCount: -1, positions: [] };
createFloodDataSource();
createFloodSets();
}
/** The canvas the scene is drawn on, for its pointer events. */
function sceneCanvas() {
if (!_viewer) return null;
return rendererOf(_viewer)?.canvas ?? _viewer.scene?.canvas ?? null;
}
/** 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) {
_splitControl = createImagerySplit({
scene: _viewer.scene,
scene: splitScene(),
initialValue: _split,
id: 'bhote-koshi-split-line',
handleClass: 'bhote-koshi-split-handle',
@@ -2618,7 +2743,7 @@ export function createBhoteKoshiEventLayer({
function applyCinematicCamera() {
if (
!_cinematicActive ||
!_viewer?.camera ||
!findCamera(_viewer) ||
_cinematicKeyframes.length === 0
)
return;
@@ -2629,8 +2754,8 @@ export function createBhoteKoshiEventLayer({
_cinematicPose,
);
if (!pose) return;
_cinematicOffset.heading = Cesium.Math.toRadians(pose.headingDeg);
_cinematicOffset.pitch = Cesium.Math.toRadians(pose.pitchDeg);
_cinematicOffset.heading = toRadians(pose.headingDeg);
_cinematicOffset.pitch = toRadians(pose.pitchDeg);
_cinematicOffset.range = pose.rangeM;
findCamera(_viewer)?.lookAt(pose.target, _cinematicOffset);
_lastCinematicProgress = _progress;
@@ -2753,7 +2878,7 @@ export function createBhoteKoshiEventLayer({
}
function attachCameraInputRelease() {
_cameraInputTarget = _viewer?.scene?.canvas || null;
_cameraInputTarget = sceneCanvas();
for (const type of CINEMATIC_INPUT_EVENTS) {
_cameraInputTarget?.addEventListener?.(type, handleManualCameraInput);
}
@@ -2799,7 +2924,7 @@ export function createBhoteKoshiEventLayer({
}
function attachEvidenceCardActivation() {
_evidenceClickTarget = _viewer?.scene?.canvas || null;
_evidenceClickTarget = sceneCanvas();
_evidenceClickTarget?.addEventListener?.('click', handleEvidenceCardClick);
}
@@ -3248,7 +3373,8 @@ export function createBhoteKoshiEventLayer({
function syncPresentationMode() {
const sceneDirected = _presentation === BHOTE_KOSHI_SCENE_PRESENTATION;
const imageryAvailable =
!sceneDirected || _sceneControls.imageryComparison === true;
!_imageryFailed &&
(!sceneDirected || _sceneControls.imageryComparison === true);
const scrubberAvailable =
!sceneDirected || Boolean(_sceneController?.seekScene);
const knownSceneBeat =
@@ -3298,13 +3424,13 @@ export function createBhoteKoshiEventLayer({
}
function updateFloodTrace(progress) {
if (!_floodHalo || !_floodCore) return;
if (!_floodSets) return;
if (
_presentation === BHOTE_KOSHI_SCENE_PRESENTATION &&
_sceneSurface !== BHOTE_KOSHI_SCENE_EVIDENCE_BEAT
) {
_floodHalo.show = false;
_floodCore.show = false;
_floodShow = false;
drawFlood();
return;
}
if (
@@ -3315,31 +3441,24 @@ export function createBhoteKoshiEventLayer({
)
)
return;
const positions = _corridorPositionCache.positions;
_floodHalo.show = positions.length > 1;
_floodCore.show = positions.length > 1;
_floodShow = _corridorPositionCache.positions.length > 1;
drawFlood();
}
function updateSurgeFront(progress) {
if (!_surgePoint) return;
if (!_floodSets) return;
if (
_presentation === BHOTE_KOSHI_SCENE_PRESENTATION &&
_sceneSurface !== BHOTE_KOSHI_SCENE_EVIDENCE_BEAT
) {
_surgePoint.show = false;
_surgeShow = false;
drawFlood();
return;
}
const headPosition = _corridorPositionCache.headPosition;
if (
headPosition &&
!Cesium.Cartesian3.equals(_lastSurgePosition, headPosition)
) {
_surgePoint.position = headPosition;
_lastSurgePosition = Cesium.Cartesian3.clone(
headPosition,
_lastSurgePosition || new Cesium.Cartesian3(),
);
}
// A copy, as the cache's head is written in place as the flood moves.
if (headPosition && !samePoint(_surgePosition, headPosition))
_surgePosition = clone(headPosition);
const visible =
Boolean(headPosition) &&
progress > 0 &&
@@ -3348,9 +3467,10 @@ export function createBhoteKoshiEventLayer({
sceneKeepsFloodVisible() ||
progress < 1);
if (_lastSurgeVisible !== visible) {
_surgePoint.show = visible;
_surgeShow = visible;
_lastSurgeVisible = visible;
}
drawFlood();
}
function updateProgress(progress) {
@@ -3451,11 +3571,10 @@ export function createBhoteKoshiEventLayer({
}
function removeImagery() {
if (_beforeLayer) _imageryLayerCollection?.remove(_beforeLayer, true);
if (_afterLayer) _imageryLayerCollection?.remove(_afterLayer, true);
_beforeLayer?.remove();
_afterLayer?.remove();
_beforeLayer = null;
_afterLayer = null;
_imageryLayerCollection = null;
}
async function init(viewer) {
@@ -3489,7 +3608,7 @@ export function createBhoteKoshiEventLayer({
throwIfEnableCancelled(signal, _enabled);
await syncTerrainComparison();
throwIfEnableCancelled(signal, _enabled);
createFloodDataSource();
createFloodSets();
createSplitControl(event);
_panelRefs = createPanelRecords(event);
_panelOwner = {};
@@ -3614,14 +3733,7 @@ export function createBhoteKoshiEventLayer({
closeFrame(slot.poster);
}
_evidenceFrameSlots = [];
if (_floodDataSource) _viewer.dataSources.remove(_floodDataSource, true);
_floodDataSource = null;
_floodSurfaceMode = null;
_floodHalo = null;
_floodCore = null;
_surgePoint = null;
_lastSurgePosition = null;
_lastSurgeVisible = null;
removeFloodSets();
if (_panelOwner && panelStore.panel?.owner === _panelOwner) {
panelStore.connect(null);
panelStore.publish(null);
+252 -137
View File
@@ -1,4 +1,6 @@
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import { fakeGlobePort } from '../testSupport/fakeGlobePort.mjs';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
@@ -232,16 +234,27 @@ function installEventDom() {
return { body, removedProperties };
}
function eventViewer(splitPosition = 0.37) {
const imagery = [];
const removedImagery = [];
const dataSources = [];
const removedDataSources = [];
/**
* A viewer with fake draw and globe ports bound, under the Cesium camera
* port over a fake camera. `_test` reads what the event draws: its imagery
* layers (`imagery`, `removedImagery`), its flood sets (`floodSets`, live
* or not) and a flood item by id (`flood`); `scene.splitPosition` is the
* globe's split.
*/
function eventViewer(splitPosition = 0.37, ports = {}) {
const draw = fakeDrawPort();
const globe = fakeGlobePort();
globe.imagery.setSplit(splitPosition);
const canvas = new FakeElement('canvas');
const cameraLooks = [];
const cameraTransforms = [];
return bindFakeCesiumCamera({
scene: { splitPosition, canvas },
const floodSets = () => [...draw.sets.values()].filter(({ spec }) => spec.id.startsWith(`${BHOTE_KOSHI_LAYER_ID}:`));
const liveFloodSets = () => floodSets().filter((set) => !set.disposed);
const viewer = {
scene: {
get splitPosition() { return globe.imagery.getSplit(); },
canvas,
},
camera: {
cancelFlight() {},
lookAt(target, offset) {
@@ -252,28 +265,38 @@ function eventViewer(splitPosition = 0.37) {
},
lookAtTransform(transform) { cameraTransforms.push(transform); },
},
imageryLayers: {
addImageryProvider(provider) {
const layer = { provider };
imagery.push(layer);
return layer;
},
remove(layer) { removedImagery.push(layer); },
},
dataSources: {
add(source) { dataSources.push(source); },
remove(source) { removedDataSources.push(source); },
},
_test: {
imagery,
removedImagery,
dataSources,
removedDataSources,
draw,
globe,
imagery: globe.added,
get removedImagery() { return globe.added.filter((layer) => layer.removed); },
floodSets,
liveFloodSets,
/** The live flood item with this id, or undefined. */
flood(id) {
for (const set of liveFloodSets()) if (set.items.has(id)) return set.items.get(id);
return undefined;
},
/** Reads the flood item with this id as it is drawn now: whether it shows, its positions or position. */
floodView(id) {
const view = viewer._test;
return {
get show() { return view.floodShows(id); },
get positions() { return view.flood(id)?.positions; },
get position() { return view.flood(id)?.pos; },
};
},
/** Whether the flood item with this id is drawn showing. */
floodShows(id) {
for (const set of liveFloodSets()) if (set.items.has(id)) return set.items.get(id).show !== false;
return false;
},
canvas,
cameraLooks,
cameraTransforms,
},
});
};
return bindFakeCesiumCamera(viewer, { draw, globe, ...ports });
}
test('public lifecycle restores Nepal scene ownership without forwarding origin to enable', async () => {
@@ -294,7 +317,7 @@ test('public lifecycle restores Nepal scene ownership without forwarding origin
const mapCalls = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: 800 })),
mediaLoader: async () => { const error = new Error('No bundled clip'); error.name = 'AbortError'; throw error; },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
@@ -317,16 +340,11 @@ test('public lifecycle restores Nepal scene ownership without forwarding origin
assert.equal(layer.getPlaybackState().enabled, true);
assert.deepEqual(mapCalls, [], `${initialMap}/${origin}: preserve the shot map`);
assert.equal(activeMap, initialMap);
const floodSource = viewer._test.dataSources.at(-1);
for (const id of ['bhote-koshi-flood-halo', 'bhote-koshi-flood-core']) {
const line = floodSource.entities.getById(id).polyline;
assert.equal(line.clampToGround.getValue(), true, 'dynamic trail follows the rendered surface');
assert.equal(line.classificationType.getValue(), initialMap === 'photoreal'
? Cesium.ClassificationType.BOTH : Cesium.ClassificationType.TERRAIN);
assert.equal(line.depthFailMaterial, undefined, 'do not rely on unsupported dynamic depth-fail rendering');
}
assert.equal(floodSource.entities.getById('bhote-koshi-surge-front').point.heightReference.getValue(),
Cesium.HeightReference.CLAMP_TO_GROUND);
const floodSets = viewer._test.liveFloodSets();
assert.deepEqual(floodSets.map(({ kind }) => kind), ['lines', 'points']);
assert.ok(floodSets.every(({ spec }) => spec.pickable === false));
assert.equal(floodSets[1].spec.clampTo, 'both', 'the surge front clamps to the ground');
assert.ok(floodSets.every(({ items }) => items.size === 0), 'a panel-only shot draws no flood');
assert.deepEqual(viewer._test.cameraLooks, [], 'enable must not focus the corridor');
assert.deepEqual(timers, [], 'enable must not schedule independent playback');
assert.equal(layer.getPlaybackState().playing, false);
@@ -356,7 +374,7 @@ test('trimmed scene media holds through provider startup, playback and fade, the
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: 800 })),
mediaLoader: async () => { const error = new Error('No bundled clip'); error.name = 'AbortError'; throw error; },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
@@ -404,7 +422,7 @@ test('Pinokio source-card fallback selects authored Director dwell, not an impos
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async url => ({ url }),
imagerySpecFactory: async url => ({ url }),
terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: 800 })),
mediaLoader: async () => { throw Object.assign(new Error('No bundled clip'), { name: 'AbortError' }); },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
@@ -449,7 +467,7 @@ test('saved autoplay controls cannot authorize media; live shot ownership is can
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async url => ({ url }),
imagerySpecFactory: async url => ({ url }),
terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: 800 })),
mediaLoader: async () => { throw Object.assign(new Error('No bundled clip'), { name: 'AbortError' }); },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
@@ -839,12 +857,10 @@ test('Bhote Koshi failed direct enable restores the prior map and shared split',
let generation = 7;
const viewer = {
scene: { splitPosition: 0.37 },
imageryLayers: { remove() {} },
dataSources: { remove() {} },
};
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async () => { throw new Error('fixture image failure'); },
imagerySpecFactory: async () => { throw new Error('fixture image failure'); },
overlayHost: {
setEntries() {},
setVisible(id, visible) { overlayCalls.push(['visible', id, visible]); },
@@ -947,7 +963,7 @@ test('Bhote Koshi disable preserves an operator-selected map and tears down ever
const renderCalls = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
overlayHost: {
setEntries() {},
setVisible(id, visible) { overlayCalls.push(['visible', id, visible]); },
@@ -972,7 +988,7 @@ test('Bhote Koshi disable preserves an operator-selected map and tears down ever
try {
assert.equal(await layer.enable(viewer, { origin: 'scene' }), true);
assert.equal(viewer._test.imagery.length, 2);
assert.equal(viewer._test.dataSources.length, 1);
assert.equal(viewer._test.floodSets().length, 2);
assert.ok(eventPanel());
assert.ok(eventSplit());
@@ -982,7 +998,7 @@ test('Bhote Koshi disable preserves an operator-selected map and tears down ever
assert.deepEqual(mapCalls, ['esri-imagery']);
assert.equal(viewer._test.removedImagery.length, 2);
assert.equal(viewer._test.removedDataSources.length, 1);
assert.equal(viewer._test.liveFloodSets().length, 0, 'its flood sets let go');
assert.equal(eventPanel(), undefined);
assert.equal(eventSplit(), undefined);
assert.equal(viewer.scene.splitPosition, 0.37);
@@ -1014,7 +1030,7 @@ test('Bhote Koshi disable stops active playback and releases its global render h
const viewer = eventViewer();
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
renderHost: {
request() {},
@@ -1072,7 +1088,7 @@ test('Bhote Koshi passive restores do not start off-screen playback', async () =
const viewer = eventViewer();
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
embeddedMediaFactory: () => ({ show() {}, hide() {}, pause() {}, destroy() {} }),
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
renderHost: { request() {}, hold() {}, release() {} },
@@ -1121,7 +1137,7 @@ test('Bhote Koshi standalone Scene keeps its Esri cinematic contract', async ()
const mapCalls = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -1196,7 +1212,7 @@ test('Bhote Koshi scene beats preserve photoreal and never take camera ownership
const overlayVisibility = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -1376,7 +1392,7 @@ test('Bhote Koshi scene beats preserve photoreal and never take camera ownership
'bhote-koshi-flood-core',
'bhote-koshi-surge-front',
]) {
assert.equal(viewer._test.dataSources[0].entities.getById(id).show, false);
assert.equal(viewer._test.floodShows(id), false);
}
panel.querySelector('[data-action="play"]').dispatch('click');
await Promise.resolve();
@@ -1465,9 +1481,7 @@ test('Bhote Koshi scene beats preserve photoreal and never take camera ownership
assert.ok(entries
.filter((entry) => entry.id.startsWith('evidence-breadcrumb-'))
.every((entry) => entry.position() == null));
assert.equal(viewer._test.dataSources.filter((source) => (
!viewer._test.removedDataSources.includes(source)
)).length, 1, 'surface transitions leave exactly one active event surface');
assert.equal(viewer._test.liveFloodSets().length, 2, 'surface transitions leave exactly one active event surface');
assert.equal(viewer._test.cameraLooks.length, 0, 'consecutive beats never write the camera');
}
panel.querySelector('[data-action="open-source"]').dispatch('click');
@@ -1486,7 +1500,7 @@ test('Bhote Koshi scene beats preserve photoreal and never take camera ownership
'disable revokes the pending real-time scene-clock scrub frame',
);
assert.deepEqual(mapCalls, []);
assert.equal(viewer._test.removedDataSources.length, viewer._test.dataSources.length);
assert.equal(viewer._test.liveFloodSets().length, 0);
} finally {
globalThis.document = originalDocument;
globalThis.window = originalWindow;
@@ -1507,7 +1521,7 @@ test('Nepal hybrid comparison preserves native split and terrain-clamped flood t
const comparisonCalls = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -1541,17 +1555,17 @@ test('Nepal hybrid comparison preserves native split and terrain-clamped flood t
assert.equal(viewer._test.imagery.length, 2);
assert.ok(viewer._test.imagery.every((imageryLayer) => imageryLayer.show === true));
assert.equal(viewer.scene.splitPosition, 0.5);
assert.equal(viewer._test.imagery[0].splitDirection, Cesium.SplitDirection.LEFT);
assert.equal(viewer._test.imagery[1].splitDirection, Cesium.SplitDirection.RIGHT);
assert.equal(viewer._test.imagery[0].split, 'left');
assert.equal(viewer._test.imagery[1].split, 'right');
assert.ok(viewer._test.imagery.every((imageryLayer) => imageryLayer.alpha === 0.96 && imageryLayer.drapeOn === 'surface'));
layer.setParams({ split: 0.25 });
assert.equal(viewer.scene.splitPosition, 0.25);
const flood = viewer._test.dataSources[0].entities.getById('bhote-koshi-flood-core');
const surge = viewer._test.dataSources[0].entities.getById('bhote-koshi-surge-front');
assert.equal(flood.polyline.clampToGround.getValue(), true);
assert.equal(
surge.point.heightReference.getValue(),
Cesium.HeightReference.CLAMP_TO_GROUND,
);
const flood = viewer._test.flood('bhote-koshi-flood-core');
const surge = viewer._test.flood('bhote-koshi-surge-front');
assert.equal(flood.mode, 'draped');
assert.equal(flood.clampTo, 'terrain', 'the comparison surface is terrain');
assert.equal(surge.height, 'clampGround');
assert.equal(surge.disableDepthTest, 0);
layer.setParams({
presentation: 'scene-beat',
@@ -1562,9 +1576,12 @@ test('Nepal hybrid comparison preserves native split and terrain-clamped flood t
assert.ok(viewer._test.imagery.every((imageryLayer) => imageryLayer.show === false));
assert.equal(comparisonCalls.at(-1), null);
const tileFlood = viewer._test.dataSources.at(-1).entities.getById('bhote-koshi-flood-core');
assert.equal(tileFlood.polyline.clampToGround.getValue(), true);
assert.equal(tileFlood.polyline.classificationType.getValue(), Cesium.ClassificationType.BOTH);
assert.equal(viewer._test.flood('bhote-koshi-flood-core'), undefined, 'drawn anew on the tiles as the story moves');
layer.setParams({ progress: 0.6 }, { origin: 'scene' });
const tileFlood = viewer._test.flood('bhote-koshi-flood-core');
assert.equal(tileFlood.mode, 'draped');
assert.equal(tileFlood.clampTo, 'both', 'photoreal drapes it on tiles too');
assert.equal(viewer._test.flood('bhote-koshi-surge-front').disableDepthTest, Number.POSITIVE_INFINITY);
await layer.disable();
assert.equal(viewer._test.removedImagery.length, 2);
@@ -1651,7 +1668,7 @@ test('Bhote Koshi publishes the evidence spine once and scrubs through cards and
const publications = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -1748,7 +1765,7 @@ test('Bhote Koshi keeps one local fallback video active and unloads it on beat c
};
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -1849,7 +1866,7 @@ test('Upper Valley Collapse autoplays its muted local fallback without starting
};
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -1925,7 +1942,7 @@ test('Debris-Dammed Lake card opens its source and is armed for approved local v
let activeCard = null;
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -2016,7 +2033,7 @@ test('Nepal evidence shots resume the standalone callout and flood sequence from
const releases = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -2074,8 +2091,8 @@ test('Nepal evidence shots resume the standalone callout and flood sequence from
layer.setSceneMediaPlayback({ sceneId: 'scene', shotId: 'shot', token: { cancelled: false } });
await layer.enable(viewer, { origin: 'scene' });
const card = entries.find(({ id }) => id === 'evidence-card-gyirong-border-gate');
const flood = viewer._test.dataSources[0].entities.getById('bhote-koshi-flood-core');
const surge = viewer._test.dataSources[0].entities.getById('bhote-koshi-surge-front');
const flood = viewer._test.floodView('bhote-koshi-flood-core');
const surge = viewer._test.floodView('bhote-koshi-surge-front');
assert.equal(card.position(), null, 'the evidence card is absent during the camera flight');
assert.equal(flood.show, false);
assert.equal(surge.show, false);
@@ -2187,7 +2204,7 @@ test('Bhote Koshi beat controls keep cards, flood, camera, and panel on the one
const publications = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -2240,8 +2257,8 @@ test('Bhote Koshi beat controls keep cards, flood, camera, and panel on the one
panel.querySelector('[data-role="beat-meta"]').textContent,
'PROPAGATION / TIME UNVERIFIED / 5 SOURCES',
);
const flood = viewer._test.dataSources[0].entities.getById('bhote-koshi-flood-core');
assert.ok(flood.polyline.positions.getValue().length > 1);
const flood = viewer._test.floodView('bhote-koshi-flood-core');
assert.ok(flood.positions.length > 1);
assert.equal(
body.children.some((element) => element.id === 'bhote-koshi-story-strap'),
false,
@@ -2307,7 +2324,7 @@ test('Bhote Koshi repeated event frames republish no panel and churn no camera',
const viewer = eventViewer();
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -2337,7 +2354,10 @@ test('Bhote Koshi repeated event frames republish no panel and churn no camera',
const panelStore = useBhoteKoshiPanelStore(applicationPinia());
const published = panelStore.panel;
const cameraLookCount = viewer._test.cameraLooks.length;
const floodWrites = () => viewer._test.liveFloodSets().map(({ writes }) => writes);
const drawnWrites = floodWrites();
for (let index = 0; index < 20; index += 1) progress.dispatch('input');
assert.deepEqual(floodWrites(), drawnWrites, 'unchanged frames draw no flood again');
assert.ok(panelStore.panel === published, 'unchanged frames do not republish the panel');
assert.equal(
@@ -2390,7 +2410,7 @@ test('Bhote Koshi cinematic camera stays synchronized through pause and determin
const viewer = eventViewer();
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -2471,7 +2491,7 @@ test('Bhote Koshi replay restores cinematic ownership unless the operator releas
const viewer = eventViewer();
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => (
observations.map((observation) => ({ height: observation.fallbackElevationM }))
),
@@ -2553,7 +2573,7 @@ test('Bhote Koshi closes a poster that resolves after disable', async () => {
const poster = { closed: false, close() { this.closed = true; } };
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async () => [{ height: 2800 }],
mediaLoader: async (url) => {
assert.equal(url, '/events/bhote-koshi-2026/evidence-09.jpg');
@@ -2593,13 +2613,15 @@ test('every sourced shot grows its tail with its head, keeps its own card, and c
globalThis.performance = { now: () => now };
globalThis.requestAnimationFrame = (callback) => { frames.set(++nextFrame, callback); return nextFrame; };
globalThis.cancelAnimationFrame = (id) => frames.delete(id);
const viewer = eventViewer();
let heightSamples = 0;
viewer.scene.sampleHeight = () => { heightSamples++; return 1500; };
let surfaceHeight = 1500;
const viewer = eventViewer(0.37, {
query: { sampleHeightNow: () => { heightSamples++; return surfaceHeight; } },
});
let entries = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async () => null,
mediaLoader: async () => { throw Object.assign(new Error('fixture'), { name: 'AbortError' }); },
overlayHost: { setEntries(_id, value) { entries = value; }, setVisible() {}, clearSource() {} },
@@ -2619,23 +2641,23 @@ test('every sourced shot grows its tail with its head, keeps its own card, and c
try {
layer.setParams(params(SOURCE_PATH_BEAT_IDS[0], false));
await layer.enable(viewer, { origin: 'scene' });
const source = viewer._test.dataSources.at(-1);
const flood = source.entities.getById('bhote-koshi-flood-core');
const surge = source.entities.getById('bhote-koshi-surge-front');
const flood = viewer._test.floodView('bhote-koshi-flood-core');
const surge = viewer._test.floodView('bhote-koshi-surge-front');
for (const id of SOURCE_PATH_BEAT_IDS) {
layer.setParams(params(id, false));
assert.equal(flood.show, false, `${id}: hide the previous route during flight`);
assert.equal(surge.show, false);
layer.setParams(params(id, true));
const sampleCount = heightSamples;
assert.ok(sampleCount > 0, 'surface heights are sampled while preparing the shot');
let previousLength = 0;
for (const elapsed of [400, 1800, 4000]) {
advance(elapsed);
const points = flood.polyline.positions.getValue();
const points = flood.positions;
assert.ok(points.length >= previousLength);
assert.equal(flood.show, true);
assert.equal(surge.show, true);
assert.ok(Cesium.Cartesian3.equals(points.at(-1), surge.position.getValue()), `${id}: tail must reach head in every frame`);
assert.ok(Cesium.Cartesian3.equals(points.at(-1), surge.position), `${id}: tail must reach head in every frame`);
previousLength = points.length;
}
assert.equal(heightSamples, sampleCount, 'do not resample geometry during motion');
@@ -2650,28 +2672,27 @@ test('every sourced shot grows its tail with its head, keeps its own card, and c
assert.equal(flood.show, false, 'new shot clears its tail before the first animation frame');
assert.equal(surge.show, false);
advance(1800);
const headBeforeSync = Cesium.Cartesian3.clone(surge.position.getValue());
const headBeforeSync = Cesium.Cartesian3.clone(surge.position);
const frameBeforeSync = nextFrame;
layer.setParams(params('dhunche', true));
assert.equal(nextFrame, frameBeforeSync, 'repeated settled notification does not restart the reveal');
assert.ok(Cesium.Cartesian3.equals(headBeforeSync, surge.position.getValue()));
assert.ok(Cesium.Cartesian3.equals(headBeforeSync, surge.position));
advance(2200);
assert.ok(!Cesium.Cartesian3.equals(headBeforeSync, surge.position.getValue()));
assert.ok(!Cesium.Cartesian3.equals(headBeforeSync, surge.position));
// The comparison exit can expose coarse photogrammetry samples a kilometre
// above the river. Dhunche's schematic profile must not dive through them.
viewer.scene.sampleHeight = () => { heightSamples++; return 2703; };
viewer.scene.globe = { getHeight: () => 0 };
surfaceHeight = 2703;
layer.setParams(params('dhunche', false, 'source', 'source'));
const samplesBeforeProfile = heightSamples;
layer.setParams(params('dhunche', true, 'source', 'source'));
for (const elapsed of [40, 400, 1800, 4000]) {
advance(elapsed);
const points = flood.polyline.positions.getValue();
const points = flood.positions;
for (const position of points) {
const height = Cesium.Cartographic.fromCartesian(position).height;
assert.ok(height >= 1307 && height <= 1332, `source profile stays near river elevation, got ${height}`);
}
assert.ok(Cesium.Cartesian3.equals(points.at(-1), surge.position.getValue()));
assert.ok(Cesium.Cartesian3.equals(points.at(-1), surge.position));
}
assert.equal(heightSamples, samplesBeforeProfile, 'source elevation does not sample the changing mesh');
layer.setParams(params('charaudi', false, 'none'));
@@ -2701,7 +2722,7 @@ test('media-led upper-valley shots retain only their upstream prefix during came
const viewer = eventViewer();
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async url => ({ url }),
imagerySpecFactory: async url => ({ url }),
terrainSampler: async () => null,
mediaLoader: async () => { throw Object.assign(new Error('fixture'), { name: 'AbortError' }); },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
@@ -2726,12 +2747,11 @@ test('media-led upper-valley shots retain only their upstream prefix during came
try {
layer.setParams(params('debris-dammed-lake', false));
await layer.enable(viewer, { origin: 'scene' });
const source = viewer._test.dataSources.at(-1);
const flood = source.entities.getById('bhote-koshi-flood-core');
const surge = source.entities.getById('bhote-koshi-surge-front');
const flood = viewer._test.floodView('bhote-koshi-flood-core');
const surge = viewer._test.floodView('bhote-koshi-surge-front');
layer.setParams(params('debris-dammed-lake', true));
finishReveal();
const lakeTail = flood.polyline.positions.getValue().map(point => Cesium.Cartesian3.clone(point));
const lakeTail = flood.positions.map(({ x, y, z }) => ({ x, y, z }));
assert.ok(lakeTail.length > 1);
const origin = Cesium.Cartographic.fromCartesian(lakeTail[0]);
assert.ok(Math.abs(Cesium.Math.toDegrees(origin.longitude) - 85.48476) < 1e-6);
@@ -2739,16 +2759,16 @@ test('media-led upper-valley shots retain only their upstream prefix during came
'the rendered trail starts at the lake reach, not the earlier trigger reach');
layer.setParams(params('second-landslide', false));
assert.equal(flood.show, true, 'lake trail survives departure before the next camera settles');
assert.deepEqual(flood.polyline.positions.getValue(), lakeTail, 'retain the prefix without revealing the next segment');
assert.ok(Cesium.Cartesian3.equals(surge.position.getValue(), lakeTail.at(-1)));
assert.deepEqual(flood.positions, lakeTail, 'retain the prefix without revealing the next segment');
assert.ok(Cesium.Cartesian3.equals(surge.position, lakeTail.at(-1)));
layer.setParams(params('second-landslide', true));
assert.deepEqual(flood.polyline.positions.getValue(), lakeTail, 'arrival does not clear the prefix');
assert.deepEqual(flood.positions, lakeTail, 'arrival does not clear the prefix');
finishReveal();
assert.ok(flood.polyline.positions.getValue().length > lakeTail.length);
assert.ok(flood.positions.length > lakeTail.length);
layer.setParams(params('debris-dammed-lake', false));
assert.equal(flood.show, false, 'backward replay trims future segments instead of retaining stale history');
layer.setParams(params('second-landslide', false));
assert.deepEqual(flood.polyline.positions.getValue(), lakeTail, 'direct load reconstructs the same prefix');
assert.deepEqual(flood.positions, lakeTail, 'direct load reconstructs the same prefix');
layer.setParams(params('second-landslide', false, { evidencePathPersistent: false }));
assert.equal(flood.show, false, 'nonpersistent shots retain their arrival gate');
for (const beatId of ['devighat-taadi-khola-bridge', 'charaudi', 'final-view']) {
@@ -2757,13 +2777,13 @@ test('media-led upper-valley shots retain only their upstream prefix during came
evidencePathDuringMedia: false, evidenceMediaAutoplay: beatId !== 'final-view',
};
layer.setParams(params(beatId, false, historyControls));
const completedTail = [...flood.polyline.positions.getValue()];
const completedTail = [...flood.positions];
assert.ok(completedTail.length > 100, `${beatId}: direct load reconstructs full sourced history`);
layer.setParams(params(beatId, true, historyControls));
assert.deepEqual(flood.polyline.positions.getValue(), completedTail,
assert.deepEqual(flood.positions, completedTail,
`${beatId}: arrival must not reset the completed history`);
finishReveal();
assert.deepEqual(flood.polyline.positions.getValue(), completedTail,
assert.deepEqual(flood.positions, completedTail,
`${beatId}: media/card reveal must not erase or regrow completed history`);
}
await layer.disable();
@@ -2799,7 +2819,7 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot
const viewer = eventViewer();
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async () => null,
mediaLoader: async () => { throw Object.assign(new Error('fixture'), { name: 'AbortError' }); },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
@@ -2841,44 +2861,42 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot
evidenceSequence: true,
}));
await layer.enable(viewer, { origin: 'scene' });
let source = viewer._test.dataSources.at(-1);
let flood = source.entities.getById('bhote-koshi-flood-core');
let surge = source.entities.getById('bhote-koshi-surge-front');
const timureStart = flood.polyline.positions.getValue().length;
let flood = viewer._test.floodView('bhote-koshi-flood-core');
let surge = viewer._test.floodView('bhote-koshi-surge-front');
const timureStart = flood.positions.length;
assert.ok(timureStart > 1, 'the completed Border Gate prefix is already visible during travel');
assert.equal(surge.show, true);
advance(420);
const earlyTimureLength = flood.polyline.positions.getValue().length;
const earlyTimureLength = flood.positions.length;
assert.ok(earlyTimureLength > timureStart,
'the trail leads during the opening tenth of camera travel instead of waiting for arrival');
advance(2880);
const timureEnd = flood.polyline.positions.getValue().length;
const timureEnd = flood.positions.length;
assert.ok(timureEnd > timureStart);
assert.equal(flood.show, true, 'the completed tail remains visible at the next point');
assert.ok(Cesium.Cartesian3.equals(flood.polyline.positions.getValue().at(-1), surge.position.getValue()));
assert.ok(Cesium.Cartesian3.equals(flood.positions.at(-1), surge.position));
layer.setParams(params('syabru-besi', 'comparison', travel(2), {
evidenceSequence: true,
}));
assert.ok(flood.polyline.positions.getValue().length >= timureEnd,
assert.ok(flood.positions.length >= timureEnd,
'the Timure segment remains painted when Syabru travel starts');
advance(3300);
assert.equal(surge.show, true, 'the amber head remains visible at comparison completion');
assert.ok(Cesium.Cartesian3.equals(flood.polyline.positions.getValue().at(-1), surge.position.getValue()));
assert.ok(Cesium.Cartesian3.equals(flood.positions.at(-1), surge.position));
layer.setParams(params('dhunche', 'source', travel(3), {
evidencePathHistory: true,
evidencePathElevation: 'source',
evidenceHoldCard: true,
}));
source = viewer._test.dataSources.at(-1);
flood = source.entities.getById('bhote-koshi-flood-core');
surge = source.entities.getById('bhote-koshi-surge-front');
const dhuncheStart = flood.polyline.positions.getValue().length;
flood = viewer._test.floodView('bhote-koshi-flood-core');
surge = viewer._test.floodView('bhote-koshi-surge-front');
const dhuncheStart = flood.positions.length;
assert.ok(dhuncheStart >= event.reconstruction.corridor.length,
'the comparison corridor survives the transition onto Google photogrammetry');
advance(3300);
const dhuncheEnd = flood.polyline.positions.getValue().length;
const dhuncheEnd = flood.positions.length;
assert.ok(dhuncheEnd > dhuncheStart);
assert.equal(surge.show, true);
@@ -2887,11 +2905,11 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot
evidencePathElevation: 'source',
evidenceHoldCard: true,
}));
assert.ok(flood.polyline.positions.getValue().length >= dhuncheEnd,
assert.ok(flood.positions.length >= dhuncheEnd,
'the completed Dhunche segment never disappears');
advance(900);
const frozenHead = Cesium.Cartesian3.clone(surge.position.getValue());
const frozenLength = flood.polyline.positions.getValue().length;
const frozenHead = Cesium.Cartesian3.clone(surge.position);
const frozenLength = flood.positions.length;
layer.setParams(params('mailung-upper-trishuli', 'source', travel(4, 4.2, {
active: false, cancelled: true,
}), {
@@ -2900,8 +2918,8 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot
evidenceHoldCard: true,
}));
assert.equal(frames.size, 0, 'cancelling camera travel revokes the path animation frame');
assert.equal(flood.polyline.positions.getValue().length, frozenLength);
assert.ok(Cesium.Cartesian3.equals(surge.position.getValue(), frozenHead));
assert.equal(flood.positions.length, frozenLength);
assert.ok(Cesium.Cartesian3.equals(surge.position, frozenHead));
assert.ok(holds.includes('bhote-koshi-scene-path-travel'));
assert.ok(releases.includes('bhote-koshi-scene-path-travel'));
@@ -2913,16 +2931,16 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot
evidencePathElevation: 'source',
evidenceHoldCard: true,
}));
const startLength = flood.polyline.positions.getValue().length;
const startLength = flood.positions.length;
assert.ok(startLength >= previousCompleteLength,
`${beatId} retains every completed upstream segment while travel begins`);
advance(3300);
const completeLength = flood.polyline.positions.getValue().length;
const completeLength = flood.positions.length;
assert.ok(completeLength > startLength, `${beatId} grows its own segment during travel`);
assert.equal(flood.show, true);
assert.equal(surge.show, true);
assert.ok(Cesium.Cartesian3.equals(
flood.polyline.positions.getValue().at(-1), surge.position.getValue(),
flood.positions.at(-1), surge.position,
));
previousCompleteLength = completeLength;
}
@@ -2941,20 +2959,20 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot
evidencePathElevation: 'source',
evidenceHoldCard: true,
}));
assert.ok(flood.polyline.positions.getValue().length > dhuncheEnd,
assert.ok(flood.positions.length > dhuncheEnd,
'a direct Bidur load reconstructs its complete upstream prefix');
advance(3300);
assert.equal(flood.polyline.positions.getValue().length, bidurCompleteLength);
assert.equal(flood.positions.length, bidurCompleteLength);
layer.setParams(params('dhunche', 'source', travel(travelId++), {
evidencePathHistory: true,
evidencePathElevation: 'source',
evidenceHoldCard: true,
}));
assert.ok(flood.polyline.positions.getValue().length < bidurCompleteLength,
assert.ok(flood.positions.length < bidurCompleteLength,
'backward navigation trims unsupported downstream history immediately');
advance(3300);
assert.equal(flood.polyline.positions.getValue().length, dhuncheEnd);
assert.equal(flood.positions.length, dhuncheEnd);
// The deadline is independent of RAF, so a throttled render loop still
// completes the active segment before the camera's longer flight ends.
@@ -2968,7 +2986,7 @@ test('camera-led Nepal flood motion preserves its prefix and stays ahead of shot
now += deadlineEntry[1].delay;
deadlineEntry[1].callback();
assert.equal(frames.size, 0, 'the deadline cancels a stalled animation frame');
assert.ok(flood.polyline.positions.getValue().length > dhuncheEnd);
assert.ok(flood.positions.length > dhuncheEnd);
layer.setParams({
presentation: 'scene-beat', sceneSurface: 'evidence-beat', beatId: 'charaudi',
@@ -3004,7 +3022,7 @@ test('an evidence point whose terrain sample misses sits at its fallback elevati
const publications = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: null })),
mediaLoader: async () => {
const error = new Error('fixture media intentionally unavailable');
@@ -3033,3 +3051,100 @@ test('an evidence point whose terrain sample misses sits at its fallback elevati
globalThis.window = originalWindow;
}
});
for (const [source, expected] of [['terrain', 'sampled'], ['ellipsoid', 'fallback']]) {
test(`the default terrain sampler places an evidence point at a ${source} answer's ${expected} height`, async () => {
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
const originalDocument = globalThis.document;
const originalWindow = globalThis.window;
installEventDom();
globalThis.window = { setTimeout: () => 71, clearTimeout() {} };
const asked = [];
const query = {
async sampleHeight(points, options) {
asked.push(options);
return points.map(() => ({ height: 1234, source, confidence: 1, lod: 'finest' }));
},
};
const viewer = eventViewer(0.37, { query });
const publications = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imagerySpecFactory: async (url) => ({ url }),
mediaLoader: async () => {
const error = new Error('fixture media intentionally unavailable');
error.name = 'AbortError';
throw error;
},
overlayHost: { setEntries(_source, entries) { publications.push(entries); }, setVisible() {}, clearSource() {} },
renderHost: { request() {}, hold() {}, release() {} },
});
try {
layer.setParams({
presentation: 'scene-beat',
sceneSurface: 'evidence-beat',
beatId: 'gyirong-border-gate',
}, { origin: 'scene' });
await layer.enable(viewer, { origin: 'scene' });
assert.deepEqual(asked, [{ against: 'terrain', mostDetailed: true }]);
const card = publications.at(-1).find((entry) => entry.id === 'evidence-card-gyirong-border-gate');
const fallback = event.evidenceSpine.find(({ id }) => id === 'gyirong-border-gate').fallbackElevationM;
const height = Cesium.Cartographic.fromCartesian(card.position()).height;
const want = (expected === 'sampled' ? 1234 : fallback) + 18;
assert.ok(Math.abs(height - want) < 1, `card at ${height} m, not ${want} m`);
await layer.disable();
} finally {
await layer.destroy();
globalThis.document = originalDocument;
globalThis.window = originalWindow;
}
});
}
test('an event image that fails to load takes the comparison down, not the event', async (t) => {
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
const originalDocument = globalThis.document;
const originalWindow = globalThis.window;
installEventDom();
globalThis.window = { setTimeout: () => 71, clearTimeout() {} };
const warn = t.mock.method(console, 'warn', () => {});
const viewer = eventViewer();
const renders = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
embeddedMediaFactory: () => ({ show() {}, hide() {}, pause() {}, destroy() {} }),
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
renderHost: { request(reason) { renders.push(reason); }, hold() {}, release() {} },
});
try {
layer.setParams({ progress: 0.4 }, { origin: 'local-restore' });
assert.equal(await layer.enable(viewer), true);
const [before, after] = viewer._test.imagery;
assert.equal(before.spec.kind, 'single-image', 'the default spec is one image');
assert.deepEqual(Object.keys(before.spec.rectangle).sort(), ['east', 'north', 'south', 'west']);
assert.equal(before.spec.credit.text, 'Vantor WorldView Open Data · CC BY-NC 4.0');
assert.deepEqual(viewer._test.globe.layers, [before, after], 'the pair goes on top, before under after');
assert.equal(eventSplit().view.hidden, false);
assert.equal(eventPanel().querySelector('[data-role="imagery-comparison"]').hidden, false);
after.fail({ tile: { x: 0, y: 0, level: 0 }, status: 404 });
assert.ok(before.removed && after.removed, 'neither image is left to compare');
assert.equal(eventSplit().view.hidden, true);
assert.equal(eventPanel().querySelector('[data-role="imagery-comparison"]').hidden, true);
assert.equal(layer.getPlaybackState().enabled, true, 'the event itself stays on');
assert.ok(renders.includes('bhote-koshi-imagery-failed'));
assert.equal(warn.mock.callCount(), 1);
before.fail({ tile: { x: 0, y: 0, level: 0 } });
assert.equal(warn.mock.callCount(), 1, 'a removed layer reports nothing more');
await layer.disable();
assert.equal(await layer.enable(viewer), true);
assert.equal(viewer._test.globe.layers.length, 2, 'the next enable tries the images again');
assert.equal(eventSplit().view.hidden, false);
await layer.disable();
} finally {
await layer.destroy();
globalThis.document = originalDocument;
globalThis.window = originalWindow;
}
});
+2
View File
@@ -56,6 +56,8 @@ export const DEGREES_PER_RADIAN = 180 / Math.PI;
export const toRadians = (degrees) => degrees * RADIANS_PER_DEGREE;
export const toDegrees = (radians) => radians * DEGREES_PER_RADIAN;
export const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
/** `a` to `b` by `t`, written as the default renderer writes it. */
export const lerp = (a, b, t) => (1 - t) * a + t * b;
/** Degrees in [0, 360). */
export const norm360 = (deg) => ((deg % 360) + 360) % 360;
/** Degrees in (-180, 180]. */
+10 -5
View File
@@ -95,9 +95,10 @@ function portOptions({ against, exclude } = NO_OPTIONS, extra) {
* @property {(position: {x: number, y: number, z: number}, options?: {exclude?: string[]}) => {x: number, y: number, z: number}|null} clampNow
* `position` (ECEF) moved onto the drawn surface along the ellipsoid
* normal, or null.
* @property {(points: HeightPoint[], options?: HeightOptions) => Promise<Array<number|null>>} batch
* @property {(points: HeightPoint[], options?: HeightOptions & {ellipsoidMisses?: boolean}) => Promise<Array<number|null>>} batch
* Heights once the most detailed data has loaded; null per miss. A failed
* query rejects.
* query rejects. With `ellipsoidMisses`, an answer from the bare
* ellipsoid (no terrain loaded there, or none at all) is a miss too.
* @property {(positions: Array<{x: number, y: number, z: number}>, options?: {exclude?: string[]}) => Promise<Array<{x: number, y: number, z: number}|null>>} clampBatch
* Clamped copies of `positions`; null per miss, rejecting as `batch` does.
* @property {() => {surface: boolean, clamp: boolean}} supported
@@ -163,9 +164,13 @@ function createHeights(host) {
portOptions(options, { mostDetailed: true }),
);
let next = 0;
return at.map((point) =>
point ? metres(samples[next++]?.height) : null,
);
return at.map((point) => {
if (!point) return null;
const sample = samples[next++];
if (options.ellipsoidMisses && sample?.source === 'ellipsoid')
return null;
return metres(sample?.height);
});
},
async clampBatch(positions, { exclude } = NO_OPTIONS) {
+25
View File
@@ -135,6 +135,31 @@ test('batch asks for the finest heights, null per miss and per bad point', async
assert.deepEqual(options, { exclude: ['own:1'], mostDetailed: true });
});
test('batch can count an answer from the bare ellipsoid as a miss', async () => {
const sources = ['terrain', 'ellipsoid'];
const { viewer, calls } = bound({
async sampleHeight(points, options) {
calls.push(['sample', points, options]);
return points.map((_, i) => ({
height: 120,
confidence: 1,
source: sources[i],
lod: 'finest',
}));
},
});
const points = [AUSTIN, { lon: 0, lat: 0 }];
assert.deepEqual(await heightsOf(viewer).batch(points), [120, 120]);
assert.deepEqual(
await heightsOf(viewer).batch(points, {
against: 'terrain',
ellipsoidMisses: true,
}),
[120, null],
);
assert.deepEqual(calls.at(-1)[2], { against: 'terrain', mostDetailed: true });
});
test('batch misses everything without a renderer, and rejects when the query fails', async () => {
assert.deepEqual(await heightsOf({}).batch([AUSTIN]), [null]);
assert.deepEqual(await heightsOf({}).clampBatch([{ x: 1, y: 0, z: 0 }]), [
-1
View File
@@ -11,7 +11,6 @@
"src/cyberSonarScene.js",
"src/data/aircraftModelLayer.js",
"src/data/aircraftMotionRegime.js",
"src/data/bhoteKoshiEvent.js",
"src/data/cctvGizmo.js",
"src/data/contactTrailRenderer.js",
"src/data/detection.js",