diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 8cc7df77d..56e78b377 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -19,6 +19,7 @@ "src/data/pickRegistry.js", "src/data/scenePick.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/camera/events.js", "src/geo/index.js", @@ -923,6 +924,7 @@ "src/input/sensorPick.js", "src/styles/styleStages.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", "src/render/cesium/ctrlWheelZoom.js", @@ -1204,6 +1206,7 @@ "src/data/pickRegistry.js", "src/input/sensorPick.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", "src/render/cesium/ctrlWheelZoom.js", @@ -1365,6 +1368,7 @@ "src/data/scenePick.js", "src/data/pickRegistry.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", "src/render/cesium/ctrlWheelZoom.js", @@ -1469,6 +1473,7 @@ "src/data/scenePick.js", "src/data/pickRegistry.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/follow.js", "src/render/camera/events.js", "src/geo/quaternion.js", @@ -1562,6 +1567,7 @@ "src/styles/styleStages.js", "src/data/pickRegistry.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/follow.js", "src/render/camera/events.js", "src/geo/celestial.js", @@ -1662,6 +1668,7 @@ "src/input/sensorPick.js", "src/styles/styleStages.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/follow.js", "src/render/cesium/cameraInput.js", "src/render/cesium/common.js", @@ -1787,6 +1794,7 @@ "src/data/scenePick.js", "src/data/pickRegistry.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/follow.js", "src/render/cesium/cameraInput.js", "src/render/cesium/internals.js", @@ -1847,6 +1855,7 @@ "src/data/scenePick.js", "src/data/pickRegistry.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/follow.js", "src/render/camera/events.js", "src/geo/celestial.js", @@ -1924,6 +1933,7 @@ "src/input/sensorPick.js", "src/styles/styleStages.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", "src/render/cesium/ctrlWheelZoom.js", @@ -2002,6 +2012,7 @@ "src/data/scenePick.js", "src/data/pickRegistry.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", "src/render/cesium/ctrlWheelZoom.js", @@ -2171,6 +2182,7 @@ "src/data/scenePick.js", "src/data/pickRegistry.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/follow.js", "src/render/cesium/cameraInput.js", "src/render/cesium/internals.js", @@ -2267,6 +2279,7 @@ "src/input/sensorPick.js", "src/styles/styleStages.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", "src/render/cesium/ctrlWheelZoom.js", @@ -2365,6 +2378,7 @@ "src/styles/styleStages.js", "src/data/pickRegistry.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", "src/render/cesium/ctrlWheelZoom.js", @@ -2431,6 +2445,7 @@ "src/data/scenePick.js", "src/data/pickRegistry.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", "src/render/cesium/ctrlWheelZoom.js", @@ -2506,6 +2521,7 @@ "src/styles/styleStages.js", "src/data/pickRegistry.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", "src/render/cesium/ctrlWheelZoom.js", @@ -2564,6 +2580,7 @@ "src/styles/styleStages.js", "src/data/pickRegistry.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", "src/render/cesium/ctrlWheelZoom.js", @@ -2829,6 +2846,7 @@ "src/render/rendererOf.js", "src/render/cesium/ports.js", "src/render/cesium/globe.js", + "src/render/cesium/drawHit.js", "src/render/cesium/draw.js", "src/render/cesium/quality.js", "src/render/cesium/credits.js", @@ -3555,6 +3573,7 @@ "src/layers/weather/imageryHost.js", "src/layers/cyclones/index.js", "src/layers/cyclones/rendering.js", + "src/geo/sphere.js", "src/layers/cyclones/labels.js", "src/layers/cyclones/source.js", "src/app/layers/localAdsb.js", @@ -4275,6 +4294,7 @@ "src/layers/weather/imageryHost.js", "src/layers/cyclones/index.js", "src/layers/cyclones/rendering.js", + "src/geo/sphere.js", "src/layers/cyclones/labels.js", "src/layers/cyclones/source.js", "src/app/layers/localAdsb.js", @@ -4411,6 +4431,7 @@ "src/input/sensorPick.js", "src/styles/styleStages.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", "src/render/cesium/ctrlWheelZoom.js", @@ -4544,6 +4565,7 @@ "exports": ["./input"], "modules": [ "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/follow.js", "src/render/cesium/cameraInput.js", "src/render/cesium/internals.js", @@ -4835,6 +4857,7 @@ "src/styles/styleStages.js", "src/data/pickRegistry.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/follow.js", "src/render/cesium/cameraInput.js", "src/render/cesium/common.js", @@ -5190,6 +5213,7 @@ "src/input/sensorPick.js", "src/styles/styleStages.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/cameraInput.js", "src/render/cesium/input.js", "src/render/cesium/ctrlWheelZoom.js", @@ -5253,6 +5277,7 @@ "src/data/scenePick.js", "src/data/pickRegistry.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/follow.js", "src/render/cesium/cameraInput.js", "src/render/cesium/common.js", @@ -5329,6 +5354,7 @@ "src/data/scenePick.js", "src/data/pickRegistry.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/follow.js", "src/render/cesium/cameraInput.js", "src/render/cesium/common.js", @@ -5439,6 +5465,7 @@ "src/styles/styleStages.js", "src/data/pickRegistry.js", "src/input/dispatcher.js", + "src/render/cesium/drawHit.js", "src/render/cesium/follow.js", "src/render/cesium/cameraInput.js", "src/render/cesium/common.js", diff --git a/src/data/infrastructure.test.mjs b/src/data/infrastructure.test.mjs index 5e9c518fc..cde4cfaba 100644 --- a/src/data/infrastructure.test.mjs +++ b/src/data/infrastructure.test.mjs @@ -196,6 +196,7 @@ test('consumer build includes only infrastructure code and resolves assets under 'ctrlWheelZoom.js', 'dispatcher.js', 'draw.js', + 'drawHit.js', 'events.js', 'follow.js', 'heights.js', diff --git a/src/geo/sphere.js b/src/geo/sphere.js new file mode 100644 index 000000000..a4612ac74 --- /dev/null +++ b/src/geo/sphere.js @@ -0,0 +1,83 @@ +/** + * @module geo/sphere + * @description Bounding spheres of ECEF points, by the default renderer's + * own method (`BoundingSphere.fromPoints`): Ritter's sphere and the box's + * circumsphere, whichever is smaller. Same arithmetic in the same order, so + * a camera framed on one goes where it went before. + */ + +const copy = (p) => ({ x: p.x, y: p.y, z: p.z }); +const squared = (a, b) => + (a.x - b.x) * (a.x - b.x) + + (a.y - b.y) * (a.y - b.y) + + (a.z - b.z) * (a.z - b.z); + +/** + * @param {ReadonlyArray<{x: number, y: number, z: number}>} points + * @returns {{center: {x: number, y: number, z: number}, radius: number}} + * Centre at the origin with radius 0 for no points. + */ +export function sphereFromPoints(points) { + if (!points?.length) return { center: { x: 0, y: 0, z: 0 }, radius: 0 }; + const first = points[0]; + let xMin = copy(first); + let yMin = copy(first); + let zMin = copy(first); + let xMax = copy(first); + let yMax = copy(first); + let zMax = copy(first); + for (let i = 1; i < points.length; i++) { + const p = points[i]; + if (p.x < xMin.x) xMin = copy(p); + if (p.x > xMax.x) xMax = copy(p); + if (p.y < yMin.y) yMin = copy(p); + if (p.y > yMax.y) yMax = copy(p); + if (p.z < zMin.z) zMin = copy(p); + if (p.z > zMax.z) zMax = copy(p); + } + const xSpan = squared(xMax, xMin); + const ySpan = squared(yMax, yMin); + const zSpan = squared(zMax, zMin); + let diameter1 = xMin; + let diameter2 = xMax; + let maxSpan = xSpan; + if (ySpan > maxSpan) { + maxSpan = ySpan; + diameter1 = yMin; + diameter2 = yMax; + } + if (zSpan > maxSpan) { + diameter1 = zMin; + diameter2 = zMax; + } + const ritter = { + x: (diameter1.x + diameter2.x) * 0.5, + y: (diameter1.y + diameter2.y) * 0.5, + z: (diameter1.z + diameter2.z) * 0.5, + }; + let radiusSquared = squared(diameter2, ritter); + let ritterRadius = Math.sqrt(radiusSquared); + const naive = { + x: (xMin.x + xMax.x) * 0.5, + y: (yMin.y + yMax.y) * 0.5, + z: (zMin.z + zMax.z) * 0.5, + }; + let naiveRadius = 0; + for (const p of points) { + const r = Math.sqrt(squared(p, naive)); + if (r > naiveRadius) naiveRadius = r; + const toPointSquared = squared(p, ritter); + if (toPointSquared > radiusSquared) { + const toPoint = Math.sqrt(toPointSquared); + ritterRadius = (ritterRadius + toPoint) * 0.5; + radiusSquared = ritterRadius * ritterRadius; + const oldToNew = toPoint - ritterRadius; + ritter.x = (ritterRadius * ritter.x + oldToNew * p.x) / toPoint; + ritter.y = (ritterRadius * ritter.y + oldToNew * p.y) / toPoint; + ritter.z = (ritterRadius * ritter.z + oldToNew * p.z) / toPoint; + } + } + return ritterRadius < naiveRadius + ? { center: ritter, radius: ritterRadius } + : { center: naive, radius: naiveRadius }; +} diff --git a/src/geo/sphere.test.mjs b/src/geo/sphere.test.mjs new file mode 100644 index 000000000..9cf0b7414 --- /dev/null +++ b/src/geo/sphere.test.mjs @@ -0,0 +1,30 @@ +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import test from 'node:test'; +import { fromDegrees } from './ellipsoid.js'; +import { sphereFromPoints } from './sphere.js'; + +test('a sphere from points is the default renderer’s, to the bit', () => { + let seed = 7; + const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647; + const cases = [ + [], + [fromDegrees(10, 20)], + [fromDegrees(-125.8, 15.5), fromDegrees(-130, 18), fromDegrees(-135, 21)], + // Across the antimeridian, and a long track. + Array.from({ length: 40 }, (_, i) => fromDegrees(170 + i, -10 + i / 2)), + Array.from({ length: 200 }, () => + fromDegrees(random() * 360 - 180, random() * 180 - 90, random() * 1e5), + ), + ]; + for (const points of cases) { + const ours = sphereFromPoints(points); + const theirs = Cesium.BoundingSphere.fromPoints( + points.map((p) => new Cesium.Cartesian3(p.x, p.y, p.z)), + ); + assert.deepEqual( + [ours.center.x, ours.center.y, ours.center.z, ours.radius], + [theirs.center.x, theirs.center.y, theirs.center.z, theirs.radius], + ); + } +}); diff --git a/src/input/dispatcher.js b/src/input/dispatcher.js index cf43edd2b..744d8e1f9 100644 --- a/src/input/dispatcher.js +++ b/src/input/dispatcher.js @@ -38,6 +38,7 @@ import * as Cesium from 'cesium'; import { isLeaseCurrent, isPointerFree } from '../data/inputOwnership.js'; import { acquireCameraInput } from '../render/cesium/cameraInput.js'; import { cesiumInputOf, createCesiumInput } from '../render/cesium/input.js'; +import { drawHitOf } from '../render/cesium/drawHit.js'; import { findPickOwner, pickContact, @@ -95,6 +96,9 @@ const dispatchers = new WeakMap(); * (corrected for sensor styles; see sensorPick.js). * @property {ClickGesture} gesture * @property {object|undefined} pick `scene.pick` at `position`. + * @property {import('../render/contract/query').Hit|null} drawHit `pick` as + * the contract's `Hit`, when it is an item of a renderer draw set; null + * for anything else. What layers on the draw port read a click by. * @property {object|undefined} hit `pick`, or on a coarse pointer the first * registered contact under a surface pick (`pickContact`). * @property {string|null} id The hit's canonical pick id. @@ -313,6 +317,9 @@ function createClickEvent(viewer, click, gesture) { get pick() { return once('pick', () => pickThroughFollowHelper(scene.pick(position))); }, + get drawHit() { + return once('drawHit', () => drawHitOf(this.pick)); + }, get hit() { return once('hit', () => pickContact(scene, position, { diff --git a/src/input/dispatcher.test.mjs b/src/input/dispatcher.test.mjs index c702e2745..807cfa506 100644 --- a/src/input/dispatcher.test.mjs +++ b/src/input/dispatcher.test.mjs @@ -82,6 +82,44 @@ test('a click on nothing is picked once, however its hit is read', (t) => { assert.equal(h.calls.pick, 1); }); +test('a click on a draw-set item reads as its hit; anything else as none', (t) => { + let picked = { + id: { set: 'quakes:1', id: 'quake:a', meta: { mag: 5 } }, + primitive: {}, + }; + const h = harness({ pick: () => picked }); + t.after(() => h.input.destroy()); + const seen = []; + h.input.onClick((event) => seen.push([event.drawHit, event.drawHit])); + h.click(); + assert.equal(h.calls.pick, 1, 'one pick serves the hit'); + assert.deepEqual(seen[0][0], { + set: 'quakes:1', + id: 'quake:a', + meta: { mag: 5 }, + surface: false, + }); + assert.equal(seen[0][0], seen[0][1], 'read once per click'); + picked = { id: { set: 'quakes:1', id: 'quake:b', lodGroup: 'near' } }; + h.click(); + assert.deepEqual(seen.at(-1)[0], { + set: 'quakes:1', + id: 'quake:b', + lodGroup: 'near', + surface: false, + }); + for (picked of [ + { id: 'plane-1' }, + { id: { id: 'entity' } }, + { id: { set: 'quakes:1', id: 7 } }, + { id: { set: null, id: 'quake:c' } }, + undefined, + ]) { + h.click(); + assert.equal(seen.at(-1)[0], null); + } +}); + test('a click nobody reads is never picked', (t) => { const h = harness(); t.after(() => h.input.destroy()); diff --git a/src/layers/cyclones/index.js b/src/layers/cyclones/index.js index 6136cb6c0..ddb2577a7 100644 --- a/src/layers/cyclones/index.js +++ b/src/layers/cyclones/index.js @@ -1,7 +1,7 @@ -import * as Cesium from 'cesium'; import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js'; import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js'; import { inputFor } from '../../input/dispatcher.js'; +import { isSurfacePick } from '../../data/scenePick.js'; import { registerPickOwner, unregisterPickOwner, @@ -23,7 +23,7 @@ import { translateKnown, } from '../../i18n/index.js'; import { formatQuantity } from '../../ui/unitLabels.js'; -import { cameraOf } from '../../render/cesium/camera.js'; +import { cameraOf } from '../../render/rendererOf.js'; // "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). @@ -68,7 +68,6 @@ export function createCyclonesLayer({ feed, hitTestOverlay = hitTestWorldOverlay, overlayHost, - cesium = Cesium, createRendering = createCycloneRendering, matchMedia = globalThis.matchMedia?.bind(globalThis), openLink = (url) => globalThis.open?.(url, '_blank', 'noopener,noreferrer'), @@ -98,14 +97,6 @@ export function createCyclonesLayer({ selectedId = id; rendering?.setSelection(id); } - // Photorealistic 3D Tiles pick as tileset content without an entity id; - // that is empty map, the same as no pick at all on the globe. - const isSurfacePick = (picked) => - !picked || - (picked.id === undefined && - (picked.content !== undefined || - (typeof cesium.Cesium3DTileset === 'function' && - picked.primitive instanceof cesium.Cesium3DTileset))); function installSelection() { if (selectionOwner || !viewer?.scene?.canvas) return; const owner = {}; @@ -176,10 +167,11 @@ export function createCyclonesLayer({ if (id) layer.setParams({ stormId: id }); return; } - const picked = event.pick; - const id = rendering?.pickStorm(picked); + // A storm's own drawing names it; empty map (the globe, or 3D tiles, + // which pick as tileset content without an id) clears the selection. + const id = rendering?.pickStorm(event.drawHit); if (id) layer.setParams({ stormId: id }); - else if (isSurfacePick(picked)) layer.setParams({ clear: true }); + else if (isSurfacePick(event.pick)) layer.setParams({ clear: true }); }); owner.unsubscribe = unsubscribe; } @@ -198,7 +190,7 @@ export function createCyclonesLayer({ updateInterval: 300_000, init(nextViewer) { viewer = nextViewer; - rendering = createRendering({ viewer, cesium, overlayHost }); + rendering = createRendering({ viewer, overlayHost }); }, attachShellServices(services) { runNavigation = diff --git a/src/layers/cyclones/index.test.mjs b/src/layers/cyclones/index.test.mjs index 3dc411786..5f07ed330 100644 --- a/src/layers/cyclones/index.test.mjs +++ b/src/layers/cyclones/index.test.mjs @@ -76,8 +76,16 @@ const deferred = () => { test('map selection yields to pointer owners and owns only its enabled handler', async () => { const handlers = [], - pickedEntity = {}, - foreignEntity = {}; + // A pick of an item in one of the layer's draw sets, and one of another + // layer's set: the dispatcher hands each to pickStorm as a draw hit. + pickedEntity = { + set: 'weather-cyclones:1:points', + id: 'cyclone:ep162026:center', + }, + foreignEntity = { + set: 'other-layer:points', + id: 'cyclone:ep162026:center', + }; let picked = { id: pickedEntity }, overlayHit = null, overlayTests = 0, @@ -88,16 +96,15 @@ test('map selection yields to pointer owners and owns only its enabled handler', setSelection() {}, clear() {}, destroy() {}, - pickStorm: (value) => (value?.id === pickedEntity ? 'ep162026' : null), + pickStorm: (hit) => + hit?.set === pickedEntity.set && hit.id === pickedEntity.id + ? 'ep162026' + : null, ownsPickId: (id) => id === 'cyclone:ep162026:center', getDiagnostics: () => ({}), }; - const cesium = { - ScreenSpaceEventType: { LEFT_CLICK: 'left' }, - }; const layer = createCyclonesLayer({ feed: { getSnapshot: async () => snapshot([storm(), storm('ep162026')]) }, - cesium, createRendering: () => rendering, hitTestOverlay: () => { overlayTests++; @@ -283,9 +290,6 @@ test('a click on a storm card or lead-hour label selects that storm without pick hostArgument; const layer = createCyclonesLayer({ feed: { getSnapshot: async () => snapshot([storm(), storm('ep162026')]) }, - cesium: { - ScreenSpaceEventType: { LEFT_CLICK: 'left' }, - }, overlayHost: 'host', createRendering: ({ overlayHost }) => { hostArgument = overlayHost; diff --git a/src/layers/cyclones/rendering.js b/src/layers/cyclones/rendering.js index 4803cc1da..1a07d9ca0 100644 --- a/src/layers/cyclones/rendering.js +++ b/src/layers/cyclones/rendering.js @@ -1,3 +1,6 @@ +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { sphereFromPoints } from '../../geo/sphere.js'; +import { drawOf } from '../../render/rendererOf.js'; import { CYCLONE_ACCENT, CYCLONE_MARKER_PX, @@ -5,6 +8,14 @@ import { createCycloneLabels, } from './labels.js'; +/** + * The draw sets the advisories are drawn in start with this; each rendering + * has its own (`weather-cyclones:1:points`, …), so several can share a + * renderer. Picks name them as `Hit.set`. + */ +export const CYCLONE_SET_PREFIX = 'weather-cyclones'; +let renderings = 0; + /** Only geometry from the displayed status advisory is eligible for rendering. */ export function coherentCycloneGeometry(storm) { return ( @@ -13,299 +24,250 @@ export function coherentCycloneGeometry(storm) { ); } +/** A `#rrggbb` colour at `alpha`, as CSS. */ +function withAlpha(hex, alpha) { + const n = Number.parseInt(hex.slice(1), 16); + return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${alpha})`; +} + +const BLACK = [0, 0, 0, 1]; +const WHITE = [1, 1, 1, 1]; + /** - * Static Cesium entities with owned horizon culling; no timers or clock. - * Storm names and lead hours are published to the shared overlay host at the - * same anchors the points use. + * Static renderer draw sets with the renderer's horizon cull; no timers or + * clock. Points are clamped and drawn over depth, so the points set culls + * them past the horizon; tracks, cones and their outlines drape on the + * ground, where the globe hides the far side. Storm names and lead hours + * are published to the shared overlay host at the same anchors the points + * use. */ -export function createCycloneRendering({ viewer, cesium: C, overlayHost }) { +export function createCycloneRendering({ viewer, overlayHost }) { const labels = createCycloneLabels({ host: overlayHost }); - let source = null, - generation = 0, + const draw = drawOf(viewer); + const prefix = `${CYCLONE_SET_PREFIX}:${++renderings}`; + const setIds = new Set( + ['points', 'lines', 'cones'].map((kind) => `${prefix}:${kind}`), + ); + const points = draw.points({ + id: `${prefix}:points`, + horizonCull: true, + clampTo: 'both', + }); + const lines = draw.lines({ id: `${prefix}:lines`, clampTo: 'both' }); + const cones = draw.shapes({ id: `${prefix}:cones`, clampTo: 'both' }); + let committed = false, selected = null, destroyed = false; + // Per storm: its center point (redrawn on selection), forecast points and + // focus sphere; per drawn item, the storm it belongs to. let centers = new Map(), - spheres = new Map(); - let entityStorms = new WeakMap(); - let entityIds = new Set(); + forecasts = [], + spheres = new Map(), + itemStorms = new Map(); let counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 }; - let horizonStorms = [], - removePreRender = null, - pointOccluder = null, - sphereOccluder = null; - const blue = C.Color.fromCssColorString(CYCLONE_ACCENT); - const gold = C.Color.fromCssColorString(CYCLONE_SELECTED_ACCENT); - const white = C.Color.WHITE; - const render = () => { - if (!viewer.isDestroyed?.()) viewer.scene.requestRender(); - }; - function cullHorizon() { - pointOccluder.cameraPosition = viewer.camera.positionWC; - sphereOccluder.cameraPosition = viewer.camera.positionWC; - let changed = false; - for (let i = 0; i < horizonStorms.length; i++) { - const storm = horizonStorms[i]; - for (let j = 0; j < storm.points.length; j++) { - const { entity, position } = storm.points[j]; - const show = pointOccluder.isPointVisible(position); - if (entity.show !== show) { - entity.show = show; - changed = true; - } - } - if (!storm.shapes.length) continue; - const show = sphereOccluder.isBoundingSphereVisible(storm.sphere); - for (let j = 0; j < storm.shapes.length; j++) { - const entity = storm.shapes[j]; - if (entity.show !== show) { - entity.show = show; - changed = true; - } - } - } - if (changed) render(); + let itemCount = 0; + + function centerItem(storm) { + const chosen = storm.id === selected; + return { + id: `cyclone:${storm.id}:center`, + pos: storm.at, + height: 'clampGround', + disableDepthTest: Number.POSITIVE_INFINITY, + pixelSize: chosen ? CYCLONE_MARKER_PX.selected : CYCLONE_MARKER_PX.storm, + color: chosen ? CYCLONE_SELECTED_ACCENT : CYCLONE_ACCENT, + outlineColor: BLACK, + outlineWidth: 2, + }; } - function syncHorizonListener() { - if (!horizonStorms.length) { - removePreRender?.(); - removePreRender = null; - return; - } - if (removePreRender) return; - pointOccluder ||= new C.EllipsoidalOccluder( - C.Ellipsoid.WGS84, - viewer.camera.positionWC, - ); - // EllipsoidalOccluder only tests points. An inscribed WGS84 sphere - // conservatively culls extents, retaining partially visible tracks/cones. - sphereOccluder ||= new C.Occluder( - new C.BoundingSphere(C.Cartesian3.ZERO, C.Ellipsoid.WGS84.minimumRadius), - viewer.camera.positionWC, - ); - removePreRender = viewer.scene.preRender.addEventListener(cullHorizon); - } - function remove(value) { - if (!value) return; - if (!viewer.dataSources.isDestroyed?.()) - viewer.dataSources.remove(value, true); - value.entities.removeAll(); + + function drawPoints() { + points.set([...[...centers.values()].map(centerItem), ...forecasts]); } + + // Only the centers show the selection: a change redraws the points set. function select(id) { + if (destroyed || id === selected) return; selected = id; - for (const [stormId, entity] of centers) { - entity.point.color = stormId === id ? gold : blue; - entity.point.pixelSize = - stormId === id ? CYCLONE_MARKER_PX.selected : CYCLONE_MARKER_PX.storm; - } + drawPoints(); labels.setSelection(id); - render(); } + return { async setSnapshot(snapshot, { signal } = {}) { signal?.throwIfAborted(); if (destroyed) return false; - const owner = ++generation; - const next = new C.CustomDataSource('weather-cyclones'); const nextCenters = new Map(), - nextSpheres = new Map(); - const nextEntityStorms = new WeakMap(); - const nextEntityIds = new Set(); + nextSpheres = new Map(), + nextItemStorms = new Map(); + const nextForecasts = [], + nextLines = [], + nextCones = [], + nextLabels = []; const nextCounts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 }; - const nextHorizonStorms = []; - const nextLabels = []; - const position = ({ longitude, latitude }) => - C.Cartesian3.fromDegrees(longitude, latitude, 0); - const coordinate = (pair) => - position({ longitude: pair[0], latitude: pair[1] }); - try { - for (const storm of snapshot.storms) { - const horizon = { points: [], shapes: [], sphere: null }; - const addEntity = (options) => { - const entity = next.entities.add(options); - if (options.position) - horizon.points.push({ entity, position: options.position }); - else horizon.shapes.push(entity); - nextEntityStorms.set(entity, storm.id); - nextEntityIds.add(entity.id); - return entity; - }; - const center = position(storm.position), - extent = [center]; - const entity = addEntity({ - id: `cyclone:${storm.id}:center`, - name: storm.name, - position: center, - point: { - heightReference: C.HeightReference.CLAMP_TO_GROUND, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - pixelSize: CYCLONE_MARKER_PX.storm, - color: blue, - outlineColor: C.Color.BLACK, - outlineWidth: 2, - }, + const lonLat = ({ longitude, latitude }) => ({ + lon: longitude, + lat: latitude, + height: 0, + }); + const pair = (coordinate) => ({ + lon: coordinate[0], + lat: coordinate[1], + height: 0, + }); + const ecef = (p) => fromDegrees(p.lon, p.lat, 0); + for (const storm of snapshot.storms) { + const own = (id) => (nextItemStorms.set(id, storm.id), id); + const at = lonLat(storm.position); + const center = ecef(at); + const extent = [center]; + own(`cyclone:${storm.id}:center`); + nextCenters.set(storm.id, { id: storm.id, at }); + const label = { + id: storm.id, + name: storm.name, + classification: storm.classification, + windKt: storm.windKt, + position: center, + forecasts: [], + }; + nextLabels.push(label); + nextCounts.storms++; + if (coherentCycloneGeometry(storm)) { + const tracks = + storm.track?.type === 'LineString' + ? [storm.track.coordinates] + : storm.track?.coordinates || []; + tracks.forEach((line, index) => { + // Lines take ECEF (draw.d.ts `LineItem`). + const positions = line.map((c) => ecef(pair(c))); + extent.push(...positions); + nextLines.push({ + id: own(`cyclone:${storm.id}:track:${index}`), + positions, + widthPx: 2.5, + mode: 'draped', + style: { kind: 'solid', color: CYCLONE_ACCENT }, + }); + nextCounts.tracks++; }); - nextCenters.set(storm.id, entity); - const label = { - id: storm.id, - name: storm.name, - classification: storm.classification, - windKt: storm.windKt, - position: center, - forecasts: [], - }; - nextLabels.push(label); - nextCounts.storms++; - if (coherentCycloneGeometry(storm)) { - const lines = - storm.track?.type === 'LineString' - ? [storm.track.coordinates] - : storm.track?.coordinates || []; - lines.forEach((line, index) => { - const positions = line.map(coordinate); - extent.push(...positions); - addEntity({ - id: `cyclone:${storm.id}:track:${index}`, - polyline: { - clampToGround: true, - classificationType: C.ClassificationType.BOTH, - positions, - width: 2.5, - material: blue, - arcType: C.ArcType.GEODESIC, - }, - }); - nextCounts.tracks++; + const polygons = + storm.cone?.type === 'Polygon' + ? [storm.cone.coordinates] + : storm.cone?.coordinates || []; + polygons.forEach((rings, index) => { + // Each exterior retains its own interior holes. Native geographic + // tessellation handles the antimeridian; never flatten rings. + const all = rings.map((ring) => ring.map(pair)); + const ecefRings = all.map((ring) => ring.map(ecef)); + extent.push(...ecefRings[0]); + nextCones.push({ + id: own(`cyclone:${storm.id}:cone:${index}`), + geometry: { kind: 'polygon', rings: all }, + fill: withAlpha(CYCLONE_ACCENT, 0.16), + height: 'clampGround', }); - const polygons = - storm.cone?.type === 'Polygon' - ? [storm.cone.coordinates] - : storm.cone?.coordinates || []; - polygons.forEach((rings, index) => { - // Each exterior retains its own interior holes. Native geographic - // tessellation handles the antimeridian; never flatten rings. - const exterior = rings[0].map(coordinate); - extent.push(...exterior); - const holes = rings - .slice(1) - .map((ring) => new C.PolygonHierarchy(ring.map(coordinate))); - addEntity({ - id: `cyclone:${storm.id}:cone:${index}`, - polygon: { - hierarchy: new C.PolygonHierarchy(exterior, holes), - classificationType: C.ClassificationType.BOTH, - material: blue.withAlpha(0.16), - arcType: C.ArcType.GEODESIC, + ecefRings.forEach((ring, ringIndex) => { + nextLines.push({ + id: own( + `cyclone:${storm.id}:cone:${index}:outline:${ringIndex}`, + ), + positions: ring, + widthPx: 1, + mode: 'draped', + style: { + kind: 'solid', + color: withAlpha(CYCLONE_ACCENT, 0.55), }, }); - [exterior, ...holes.map((hole) => hole.positions)].forEach( - (positions, ringIndex) => { - addEntity({ - id: `cyclone:${storm.id}:cone:${index}:outline:${ringIndex}`, - polyline: { - positions, - width: 1, - material: blue.withAlpha(0.55), - arcType: C.ArcType.GEODESIC, - clampToGround: true, - classificationType: C.ClassificationType.BOTH, - }, - }); - }, - ); - nextCounts.cones++; }); - for (const [index, point] of storm.forecastPoints.entries()) { - if (point.tauHours === 0) continue; - const p = position(point.position); - extent.push(p); - addEntity({ - id: `cyclone:${storm.id}:forecast:${index}`, - position: p, - point: { - heightReference: C.HeightReference.CLAMP_TO_GROUND, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - pixelSize: CYCLONE_MARKER_PX.forecast, - color: white, - outlineColor: C.Color.BLACK, - outlineWidth: 1, - }, - }); - label.forecasts.push({ tauHours: point.tauHours, position: p }); - nextCounts.forecastPoints++; - } + nextCounts.cones++; + }); + for (const [index, point] of storm.forecastPoints.entries()) { + if (point.tauHours === 0) continue; + const pos = lonLat(point.position); + const p = ecef(pos); + extent.push(p); + nextForecasts.push({ + id: own(`cyclone:${storm.id}:forecast:${index}`), + pos, + height: 'clampGround', + disableDepthTest: Number.POSITIVE_INFINITY, + pixelSize: CYCLONE_MARKER_PX.forecast, + color: WHITE, + outlineColor: BLACK, + outlineWidth: 1, + }); + label.forecasts.push({ tauHours: point.tauHours, position: p }); + nextCounts.forecastPoints++; } - const sphere = C.BoundingSphere.fromPoints(extent); - // A status-only point still has a useful regional camera destination. - sphere.radius = Math.max(sphere.radius, 500_000); - nextSpheres.set(storm.id, sphere); - horizon.sphere = sphere; - nextHorizonStorms.push(horizon); } - await viewer.dataSources.add(next); - if (destroyed || generation !== owner || signal?.aborted) { - remove(next); - return false; - } - remove(source); - source = next; - centers = nextCenters; - spheres = nextSpheres; - entityStorms = nextEntityStorms; - entityIds = nextEntityIds; - counts = nextCounts; - horizonStorms = nextHorizonStorms; - syncHorizonListener(); - labels.setSnapshot(nextLabels, selected); - select(selected); - return true; - } catch (error) { - remove(next); - if (signal?.aborted || generation !== owner || destroyed) return false; - throw error; + const sphere = sphereFromPoints(extent); + // A status-only point still has a useful regional camera destination. + sphere.radius = Math.max(sphere.radius, 500_000); + nextSpheres.set(storm.id, sphere); } + if (destroyed || signal?.aborted) return false; + centers = nextCenters; + forecasts = nextForecasts; + spheres = nextSpheres; + itemStorms = nextItemStorms; + counts = nextCounts; + itemCount = nextItemStorms.size; + committed = true; + lines.set(nextLines); + cones.set(nextCones); + // Every commit redraws the points, an empty advisory included. + drawPoints(); + labels.setSnapshot(nextLabels, selected); + return true; }, setSelection: select, ownsPickId(id) { - return source !== null && typeof id === 'string' && entityIds.has(id); + return committed && typeof id === 'string' && itemStorms.has(id); }, - pickStorm(picked) { - // Cesium Entity picks carry the exact entity in `id`. IDs/prefixes alone - // cannot establish ownership, especially after an advisory replacement. - const entity = picked?.id; - return source && entity && typeof entity === 'object' - ? entityStorms.get(entity) || null - : null; + /** + * The storm a click's draw hit (`Hit`, query.d.ts) belongs to: an item + * of these sets in the advisory drawn now, never an id from another. + */ + pickStorm(hit) { + if (!committed || !hit || hit.surface) return null; + if (!setIds.has(hit.set)) return null; + return itemStorms.get(hit.id) ?? null; }, getFocusSphere(id) { return spheres.get(id) || null; }, clear() { - ++generation; - horizonStorms = []; - syncHorizonListener(); - pointOccluder = null; - sphereOccluder = null; - remove(source); - source = null; + committed = false; + if (!destroyed) { + points.clear(); + lines.clear(); + cones.clear(); + } labels.clear(); - centers.clear(); - spheres.clear(); - entityStorms = new WeakMap(); - entityIds.clear(); + centers = new Map(); + forecasts = []; + spheres = new Map(); + itemStorms = new Map(); + itemCount = 0; selected = null; counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 }; - render(); }, destroy() { if (destroyed) return; this.clear(); destroyed = true; + points.dispose(); + lines.dispose(); + cones.dispose(); }, getDiagnostics() { return { ...counts, - dataSources: Number(!!source), - entities: source?.entities.values.length || 0, + // One display: the committed advisory's sets, and the items in them. + dataSources: Number(committed), + entities: itemCount, selectedId: selected, timerActive: false, }; diff --git a/src/layers/cyclones/rendering.test.mjs b/src/layers/cyclones/rendering.test.mjs index 65ac78601..38b5ea629 100644 --- a/src/layers/cyclones/rendering.test.mjs +++ b/src/layers/cyclones/rendering.test.mjs @@ -1,8 +1,15 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import * as Cesium from 'cesium'; -import { createCycloneRendering } from './rendering.js'; -import { CYCLONE_OVERLAY_SOURCE_ID } from './labels.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { sphereFromPoints } from '../../geo/sphere.js'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; +import { CYCLONE_SET_PREFIX, createCycloneRendering } from './rendering.js'; +import { + CYCLONE_ACCENT, + CYCLONE_MARKER_PX, + CYCLONE_OVERLAY_SOURCE_ID, + CYCLONE_SELECTED_ACCENT, +} from './labels.js'; /** Records what the renderer publishes to the shared overlay host. */ function overlayRecorder() { @@ -28,161 +35,40 @@ function overlayRecorder() { }; } -function harness({ deferred = false } = {}) { - const sources = [], - completions = [], - pointOccluders = [], - sphereOccluders = []; - const listeners = new Set(); - const visibility = { - points: new Map(), - spheres: new Map(), - pointCalls: [], - sphereCalls: [], - writes: 0, - }; - const color = (value) => ({ - value, - withAlpha: (alpha) => ({ value, alpha }), - }); - const cesium = { - Color: { - fromCssColorString: color, - WHITE: color('white'), - BLACK: color('black'), - }, - Cartesian2: class { - constructor(x, y) { - this.x = x; - this.y = y; - } - }, - Cartesian3: { - ZERO: { x: 0, y: 0, z: 0 }, - fromDegrees: (lon, lat, height) => ({ lon, lat, height }), - }, - Ellipsoid: { WGS84: { minimumRadius: 6356752 } }, - EllipsoidalOccluder: class { - constructor(ellipsoid, cameraPosition) { - this.ellipsoid = ellipsoid; - this.cameraPosition = cameraPosition; - pointOccluders.push(this); - } - isPointVisible(position) { - visibility.pointCalls.push(position); - return visibility.points.get(position) ?? true; - } - }, - Occluder: class { - constructor(sphere, cameraPosition) { - this.sphere = sphere; - this.cameraPosition = cameraPosition; - sphereOccluders.push(this); - } - isBoundingSphereVisible(sphere) { - visibility.sphereCalls.push(sphere); - return visibility.spheres.get(sphere) ?? true; - } - }, - PolygonHierarchy: class { - constructor(positions, holes = []) { - this.positions = positions; - this.holes = holes; - } - }, - BoundingSphere: class { - constructor(center, radius) { - this.center = center; - this.radius = radius; - } - static fromPoints(points) { - return { points, radius: 10 }; - } - }, - LabelStyle: { FILL_AND_OUTLINE: 1 }, - HorizontalOrigin: { LEFT: 1 }, - ArcType: { GEODESIC: 1 }, - HeightReference: Cesium.HeightReference, - ClassificationType: Cesium.ClassificationType, - DistanceDisplayCondition: Cesium.DistanceDisplayCondition, - CustomDataSource: class { - constructor() { - const values = []; - this.entities = { - values, - add: (value) => { - let show = true; - Object.defineProperty(value, 'show', { - get: () => show, - set: (next) => { - show = next; - visibility.writes++; - }, - }); - values.push(value); - return value; - }, - removeAll: () => { - values.length = 0; - }, - }; - } - }, - }; - let renders = 0; +/** A rendering on a viewer bound to a fake draw port. */ +function harness() { + const viewer = {}; + const { draw, unbind } = bindFakeDraw(viewer); const overlay = overlayRecorder(); - const viewer = { - camera: { positionWC: { x: 6378487, y: 0, z: 0 } }, - scene: { - requestRender: () => renders++, - preRender: { - addEventListener(listener) { - listeners.add(listener); - return () => listeners.delete(listener); - }, - }, - }, - dataSources: { - add(value) { - if (deferred) - return new Promise((resolve) => - completions.push(() => { - sources.push(value); - resolve(value); - }), - ); - sources.push(value); - return Promise.resolve(value); - }, - remove(value) { - const i = sources.indexOf(value); - if (i >= 0) sources.splice(i, 1); - }, - }, - }; - return { - rendering: createCycloneRendering({ - viewer, - cesium, - overlayHost: overlay.host, - }), - overlay, - sources, - completions, + const rendering = createCycloneRendering({ viewer, - cesium, - visibility, - pointOccluders, - sphereOccluders, - listeners, - frame() { - for (const listener of listeners) listener(); + overlayHost: overlay.host, + }); + const sets = {}; + for (const kind of ['points', 'lines', 'cones']) + sets[kind] = [...draw.sets.values()].find((record) => + record.spec.id.endsWith(`:${kind}`), + ); + return { + viewer, + draw, + unbind, + overlay, + rendering, + sets, + /** Every item drawn now, across the rendering's sets. */ + items() { + return Object.values(sets).flatMap((record) => [ + ...record.items.values(), + ]); }, - get renders() { - return renders; + /** A click's draw hit on the item `id`, in the set of `kind`. */ + hit(kind, id) { + return { set: sets[kind].spec.id, id, surface: false }; }, }; } + const storm = () => ({ id: 'ep152026', name: 'Fifteen-E', @@ -191,6 +77,7 @@ const storm = () => ({ geometryStatus: 'current', position: { longitude: 179, latitude: 15 }, forecastPoints: [ + { position: { longitude: 179, latitude: 15 }, tauHours: 0 }, { position: { longitude: -179, latitude: 16 }, tauHours: 12 }, ], track: { @@ -231,301 +118,94 @@ const storm = () => ({ }, }); -test('horizon culling updates only changed entities and keeps selection independent', async () => { - const h = harness(); - await h.rendering.setSnapshot({ - storms: [storm(), { ...storm(), id: 'near' }], +test('each rendering draws into its own point, line and cone sets', () => { + const a = harness(); + const { sets } = a; + assert.match(sets.points.spec.id, new RegExp(`^${CYCLONE_SET_PREFIX}:\\d+:`)); + assert.equal(sets.points.kind, 'points'); + assert.equal(sets.points.spec.horizonCull, true); + assert.equal(sets.points.spec.clampTo, 'both'); + assert.equal(sets.lines.kind, 'lines'); + assert.equal(sets.lines.spec.clampTo, 'both'); + assert.equal(sets.cones.kind, 'shapes'); + assert.equal(sets.cones.spec.clampTo, 'both'); + + // A second rendering on the same renderer is a separate display. + const viewer = {}; + const { draw } = bindFakeDraw(viewer); + const first = createCycloneRendering({ + viewer, + overlayHost: overlayRecorder().host, }); - const entities = h.sources[0].entities.values; - const far = entities.filter((e) => e.id.startsWith('cyclone:ep152026:')); - const near = entities.filter((e) => e.id.startsWith('cyclone:near:')); - const forecast = far.find((e) => e.id.endsWith('forecast:0')); - const sphere = h.rendering.getFocusSphere('ep152026'); - for (const entity of far) - if (entity.position) h.visibility.points.set(entity.position, false); - h.visibility.spheres.set(sphere, false); - h.rendering.setSelection('ep152026'); - const publishes = h.overlay.publishes; - const before = h.renders; - h.frame(); - assert.ok(far.every((e) => e.show === false)); - assert.ok(near.every((e) => e.show === true)); - assert.equal( - h.overlay.entry('lead:ep152026:12').position, - forecast.position, - 'the host culls labels at the same anchors the points use', - ); - assert.equal(h.overlay.publishes, publishes, 'culling never republishes'); - assert.equal(h.renders, before + 1); - assert.equal(h.visibility.writes, far.length); - assert.equal(h.visibility.pointCalls.length, 4); - assert.deepEqual(h.visibility.sphereCalls, [ - sphere, - h.rendering.getFocusSphere('near'), - ]); - h.frame(); - assert.equal(h.renders, before + 1); - assert.equal(h.visibility.writes, far.length); - - // A visible portion of the extent keeps all tracks/cones shown even when - // the centre and an individual forecast point remain beyond the horizon. - h.visibility.spheres.set(sphere, true); - h.viewer.camera.positionWC = { x: 0, y: 6378487, z: 0 }; - h.frame(); - assert.ok(far.filter((e) => !e.position).every((e) => e.show)); - assert.ok(far.filter((e) => e.position).every((e) => !e.show)); - assert.equal(h.renders, before + 2); - assert.equal(h.pointOccluders.length, 1); - assert.equal(h.sphereOccluders.length, 1); - assert.equal(h.pointOccluders[0].ellipsoid, h.cesium.Ellipsoid.WGS84); - assert.equal(h.pointOccluders[0].cameraPosition, h.viewer.camera.positionWC); - assert.equal(h.sphereOccluders[0].cameraPosition, h.viewer.camera.positionWC); - - h.rendering.setSelection('near'); - assert.equal(h.overlay.entry('lead:ep152026:12'), null); - assert.equal( - h.overlay.entry('lead:near:12').position, - near.find((e) => e.id.endsWith('forecast:0')).position, - ); - h.visibility.points.set(forecast.position, true); - const beforeReveal = h.renders; - const revealPublishes = h.overlay.publishes; - h.frame(); - assert.equal(forecast.show, true); - assert.equal(h.overlay.entry('lead:ep152026:12'), null); - assert.equal(h.overlay.publishes, revealPublishes); - assert.equal(far[0].show, false); - assert.equal(h.renders, beforeReveal + 1); - h.rendering.destroy(); -}); - -test('horizon listener follows committed nonempty snapshots and clear/destroy', async () => { - const h = harness(); - assert.equal(h.listeners.size, 0); - await h.rendering.setSnapshot({ storms: [] }); - assert.equal(h.listeners.size, 0); - await h.rendering.setSnapshot({ storms: [storm()] }); - assert.equal(h.listeners.size, 1); - const old = [...h.sources[0].entities.values]; - await h.rendering.setSnapshot({ storms: [storm()] }); - assert.equal(h.listeners.size, 1); - h.frame(); - assert.ok( - h.visibility.pointCalls.every((p) => !old.some((e) => e.position === p)), - ); - await h.rendering.setSnapshot({ storms: [] }); - assert.equal(h.listeners.size, 0); - await h.rendering.setSnapshot({ storms: [storm()] }); - h.rendering.clear(); - assert.equal(h.listeners.size, 0); - const before = h.renders; - h.frame(); - assert.equal(h.renders, before); - await h.rendering.setSnapshot({ storms: [storm()] }); - assert.equal(h.listeners.size, 1); - h.rendering.destroy(); - h.rendering.destroy(); - assert.equal(h.listeners.size, 0); - assert.equal(await h.rendering.setSnapshot({ storms: [storm()] }), false); - assert.equal(h.listeners.size, 0); -}); - -test('late asynchronous additions never restore a cleared or destroyed horizon listener', async () => { - for (const method of ['clear', 'destroy']) { - const h = harness({ deferred: true }); - const pending = h.rendering.setSnapshot({ storms: [storm()] }); - assert.equal(h.listeners.size, 0); - h.rendering[method](); - h.completions.shift()(); - assert.equal(await pending, false); - assert.equal(h.listeners.size, 0); - } -}); - -test('real Cesium culls far storms and retains partially visible extents with either globe visibility', async () => { - for (const globeShow of [true, false]) { - const sources = []; - const viewer = { - camera: { positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 350) }, - scene: { - globe: { show: globeShow }, - preRender: new Cesium.Event(), - requestRender() {}, - }, - dataSources: { - async add(source) { - sources.push(source); - }, - remove() {}, - }, - }; - const overlay = overlayRecorder(); - const rendering = createCycloneRendering({ - viewer, - cesium: Cesium, - overlayHost: overlay.host, - }); - const at = (id, longitude) => ({ - ...storm(), - id, - position: { longitude, latitude: 0 }, - forecastPoints: [{ position: { longitude, latitude: 0 }, tauHours: 24 }], - track: { - type: 'LineString', - coordinates: [ - [longitude, 0], - [longitude, 1], - ], - }, - cone: { - type: 'Polygon', - coordinates: [ - [ - [longitude, 0], - [longitude + 1, 0], - [longitude, 1], - [longitude, 0], - ], - ], - }, - }); - await rendering.setSnapshot({ - storms: [at('near', 0), at('far', 180), at('limb', 5)], - }); - rendering.setSelection('near'); - viewer.scene.preRender.raiseEvent(); - const entities = sources[0].entities.values; - for (const entity of entities.filter((e) => e.position)) { - assert.equal( - entity.point.heightReference.getValue(), - Cesium.HeightReference.CLAMP_TO_GROUND, - ); - assert.equal(entity.point.disableDepthTestDistance.getValue(), Infinity); - assert.equal(entity.label, undefined, 'no Cesium label graphics'); - const published = overlay.entry( - entity.id.includes(':forecast:') - ? `lead:${entity.id.split(':')[1]}:24` - : `storm:${entity.id.split(':')[1]}`, - ); - if (entity.id.startsWith('cyclone:near:')) { - assert.ok( - Cesium.Cartesian3.equals( - published.position, - entity.position.getValue(), - ), - ); - assert.equal(published.horizonCull, true); - } - if (entity.id === 'cyclone:near:forecast:0') - assert.equal(published.maxDistance, 4_000_000); - } - assert.ok( - entities - .filter((e) => e.id.startsWith('cyclone:near:')) - .every((e) => e.show), - ); - assert.ok( - entities - .filter((e) => e.id.startsWith('cyclone:far:')) - .every((e) => !e.show), - ); - const limb = entities.filter((e) => e.id.startsWith('cyclone:limb:')); - assert.ok(limb.filter((e) => e.position).every((e) => !e.show)); - assert.ok(limb.filter((e) => !e.position).every((e) => e.show)); - rendering.destroy(); - assert.equal(viewer.scene.preRender.numberOfListeners, 0); - } -}); - -test('picking accepts exact current owned entities, never prefixes or superseded identities', async () => { - const h = harness(); - await h.rendering.setSnapshot({ storms: [storm()] }); - const oldEntities = [...h.sources[0].entities.values]; - assert.equal(oldEntities.length, 8); - for (const entity of oldEntities) { - assert.equal(h.rendering.pickStorm({ id: entity }), 'ep152026', entity.id); - assert.equal(h.rendering.ownsPickId(entity.id), true); - assert.equal( - h.rendering.pickStorm({ id: { ...entity } }), - null, - 'copied ID is not ownership', - ); - assert.equal( - h.rendering.pickStorm({ id: entity.id }), - null, - 'string prefix is not ownership', - ); - } - assert.equal(h.rendering.pickStorm(undefined), null); - assert.equal(h.rendering.ownsPickId('cyclone:ep152026:unknown'), false); - await h.rendering.setSnapshot({ storms: [storm()] }); - for (const entity of oldEntities) - assert.equal(h.rendering.pickStorm({ id: entity }), null); - const current = h.sources[0].entities.values[0]; - assert.equal(h.rendering.pickStorm({ id: current }), 'ep152026'); - h.rendering.clear(); - assert.equal(h.rendering.pickStorm({ id: current }), null); - assert.equal(h.rendering.ownsPickId(current.id), false); - h.rendering.destroy(); -}); - -test('registry IDs switch only when the next coherent data source commits', async () => { - const h = harness({ deferred: true }); - const first = h.rendering.setSnapshot({ storms: [storm()] }); - assert.equal(h.rendering.ownsPickId('cyclone:ep152026:center'), false); - h.completions.shift()(); - await first; - assert.equal(h.rendering.ownsPickId('cyclone:ep152026:center'), true); - const next = h.rendering.setSnapshot({ - storms: [{ ...storm(), id: 'ep162026' }], + const second = createCycloneRendering({ + viewer, + overlayHost: overlayRecorder().host, }); - assert.equal(h.rendering.ownsPickId('cyclone:ep152026:center'), true); - assert.equal(h.rendering.ownsPickId('cyclone:ep162026:center'), false); - h.completions.shift()(); - await next; - assert.equal(h.rendering.ownsPickId('cyclone:ep152026:center'), false); - assert.equal(h.rendering.ownsPickId('cyclone:ep162026:center'), true); - h.rendering.destroy(); - assert.equal(h.rendering.ownsPickId('cyclone:ep162026:center'), false); + assert.equal(draw.sets.size, 6); + second.destroy(); + assert.equal( + [...draw.sets.values()].filter((record) => !record.disposed).length, + 3, + ); + first.destroy(); + a.rendering.destroy(); }); -test('static entities preserve polygon parts, holes and geographic seam coordinates', async () => { + +test('advisory geometry keeps polygon parts, holes and geographic seam coordinates', async () => { const h = harness(); - await h.rendering.setSnapshot({ storms: [storm()] }); - const entities = h.sources[0].entities.values; - const cones = entities.filter((e) => e.polygon); - assert.equal(cones.length, 2); - assert.equal(cones[0].polygon.hierarchy.holes.length, 1); - assert.equal(cones[0].polygon.hierarchy.positions[1].lon, -178); + assert.equal(await h.rendering.setSnapshot({ storms: [storm()] }), true); + const cones = [...h.sets.cones.items.values()]; + assert.deepEqual( + cones.map((cone) => cone.id), + ['cyclone:ep152026:cone:0', 'cyclone:ep152026:cone:1'], + ); + assert.equal(cones[0].geometry.kind, 'polygon'); + assert.equal(cones[0].geometry.rings.length, 2, 'the hole stays'); + assert.equal(cones[0].geometry.rings[0][1].lon, -178); for (const cone of cones) { - assert.equal( - cone.polygon.classificationType, - h.cesium.ClassificationType.BOTH, - ); - assert.equal(cone.polygon.height, undefined); - assert.equal(cone.polygon.extrudedHeight, undefined); - assert.equal(cone.polygon.outline, undefined); + assert.equal(cone.height, 'clampGround'); + assert.equal(cone.fill, 'rgba(127,230,237,0.16)'); + assert.equal(cone.outline, undefined, 'outlines are lines of their own'); + assert.equal(cone.extrudedHeight, undefined); } - const outlines = entities.filter((e) => e.id.includes(':outline:')); + const lines = [...h.sets.lines.items.values()]; + const outlines = lines.filter((line) => line.id.includes(':outline:')); assert.equal(outlines.length, 3); assert.deepEqual( - outlines.map((e) => e.polyline.positions.map((p) => [p.lon, p.lat])), - storm().cone.coordinates.flat(), + outlines.map((line) => line.positions), + storm() + .cone.coordinates.flat() + .map((ring) => ring.map(([lon, lat]) => fromDegrees(lon, lat, 0))), + 'lines take ECEF', ); for (const outline of outlines) { - assert.deepEqual(outline.polyline.material, { - value: '#7fe6ed', - alpha: 0.55, + assert.equal(outline.widthPx, 1); + assert.deepEqual(outline.style, { + kind: 'solid', + color: 'rgba(127,230,237,0.55)', }); } - for (const { polyline } of entities.filter((e) => e.polyline)) { - assert.equal(polyline.clampToGround, true); - assert.equal(polyline.classificationType, h.cesium.ClassificationType.BOTH); - assert.ok(polyline.positions.every((p) => p.height === 0)); - } - assert.equal( - entities.find((e) => e.polyline).polyline.positions[1].lon, - -179, + const track = lines.find((line) => line.id === 'cyclone:ep152026:track:0'); + assert.equal(track.widthPx, 2.5); + assert.deepEqual(track.style, { kind: 'solid', color: CYCLONE_ACCENT }); + assert.deepEqual(track.positions[1], fromDegrees(-179, 16, 0)); + for (const line of lines) assert.equal(line.mode, 'draped'); + const points = [...h.sets.points.items.values()]; + assert.deepEqual( + points.map((point) => point.id), + ['cyclone:ep152026:center', 'cyclone:ep152026:forecast:1'], + 'the zero-hour forecast is the center', ); + for (const point of points) { + assert.equal(point.height, 'clampGround'); + assert.equal(point.disableDepthTest, Number.POSITIVE_INFINITY); + assert.deepEqual(point.outlineColor, [0, 0, 0, 1]); + } + assert.deepEqual(points[1].color, [1, 1, 1, 1]); + assert.equal(points[1].pixelSize, CYCLONE_MARKER_PX.forecast); + assert.equal(points[0].pixelSize, CYCLONE_MARKER_PX.storm); + assert.equal(points[1].outlineWidth, 1); + assert.equal(points[0].outlineWidth, 2); assert.deepEqual(h.rendering.getDiagnostics(), { storms: 1, tracks: 1, @@ -536,17 +216,111 @@ test('static entities preserve polygon parts, holes and geographic seam coordina selectedId: null, timerActive: false, }); - h.rendering.setSelection('ep152026'); - assert.equal( - h.overlay.entry('lead:ep152026:12').position, - entities.find((e) => e.id.endsWith('forecast:0')).position, - ); - assert.ok(entities.every((e) => e.label === undefined)); - assert.ok(h.rendering.getFocusSphere('ep152026').radius >= 500000); h.rendering.destroy(); - assert.equal(h.sources.length, 0); + assert.ok(Object.values(h.sets).every((record) => record.disposed)); assert.equal(h.rendering.getDiagnostics().entities, 0); }); + +test('selection redraws the centers and labels; an unchanged one is quiet', async () => { + const h = harness(); + await h.rendering.setSnapshot({ + storms: [storm(), { ...storm(), id: 'near', name: 'Near' }], + }); + const center = (id) => h.sets.points.items.get(`cyclone:${id}:center`); + assert.equal(center('near').pixelSize, 9); + h.rendering.setSelection('near'); + assert.equal(center('near').pixelSize, 12); + assert.equal(center('near').color, CYCLONE_SELECTED_ACCENT); + assert.equal(center('ep152026').pixelSize, 9); + assert.equal(center('ep152026').color, CYCLONE_ACCENT); + assert.ok(h.sets.points.items.has('cyclone:near:forecast:1')); + const pointWrites = h.sets.points.writes; + const lineWrites = h.sets.lines.writes; + const publishes = h.overlay.publishes; + h.rendering.setSelection('near'); + assert.equal(h.overlay.publishes, publishes, 'unchanged selection is quiet'); + assert.equal(h.sets.points.writes, pointWrites, 'points are not redrawn'); + assert.equal(h.sets.lines.writes, lineWrites, 'tracks are not redrawn'); + h.rendering.destroy(); +}); + +test('a click names a storm only through a current item of its own sets', async () => { + const h = harness(); + await h.rendering.setSnapshot({ storms: [storm()] }); + const items = h.items(); + assert.equal(items.length, 8); + for (const kind of ['points', 'lines', 'cones']) + for (const id of h.sets[kind].items.keys()) { + assert.equal(h.rendering.pickStorm(h.hit(kind, id)), 'ep152026', id); + assert.equal(h.rendering.ownsPickId(id), true); + assert.equal( + h.rendering.pickStorm({ set: 'other:points', id, surface: false }), + null, + "another layer's set is not ownership", + ); + } + assert.equal( + h.rendering.pickStorm({ + ...h.hit('points', 'cyclone:ep152026:center'), + surface: true, + }), + null, + ); + assert.equal(h.rendering.pickStorm(undefined), null); + assert.equal(h.rendering.pickStorm(null), null); + assert.equal( + h.rendering.pickStorm(h.hit('points', 'cyclone:ep152026')), + null, + 'a prefix is not an item', + ); + assert.equal(h.rendering.ownsPickId('cyclone:ep152026:unknown'), false); + + // A newer advisory without the storm drops its ids at once. + await h.rendering.setSnapshot({ storms: [{ ...storm(), id: 'ep162026' }] }); + assert.equal( + h.rendering.pickStorm(h.hit('points', 'cyclone:ep152026:center')), + null, + ); + assert.equal(h.rendering.ownsPickId('cyclone:ep152026:center'), false); + assert.equal( + h.rendering.pickStorm(h.hit('points', 'cyclone:ep162026:center')), + 'ep162026', + ); + h.rendering.clear(); + assert.equal( + h.rendering.pickStorm(h.hit('points', 'cyclone:ep162026:center')), + null, + ); + assert.equal(h.rendering.ownsPickId('cyclone:ep162026:center'), false); + h.rendering.destroy(); +}); + +test('focus spheres bound the advisory and never shrink below a region', async () => { + const h = harness(); + const statusOnly = { + ...storm(), + id: 'status', + geometryStatus: 'pending', + }; + await h.rendering.setSnapshot({ storms: [storm(), statusOnly] }); + const at = ([lon, lat]) => fromDegrees(lon, lat, 0); + const expected = sphereFromPoints([ + at([179, 15]), + ...storm().track.coordinates[0].map(at), + ...storm().cone.coordinates[0][0].map(at), + ...storm().cone.coordinates[1][0].map(at), + at([-179, 16]), + ]); + const sphere = h.rendering.getFocusSphere('ep152026'); + assert.deepEqual(sphere.center, expected.center); + assert.equal(sphere.radius, Math.max(expected.radius, 500_000)); + assert.equal(h.rendering.getFocusSphere('status').radius, 500_000); + assert.equal(h.rendering.getFocusSphere('missing'), null); + h.rendering.clear(); + assert.equal(h.rendering.getFocusSphere('ep152026'), null); + h.rendering.destroy(); +}); + test('pending or mismatched advisory geometry never renders even when supplied', async () => { for (const changed of [ { geometryStatus: 'pending' }, @@ -554,60 +328,76 @@ test('pending or mismatched advisory geometry never renders even when supplied', ]) { const h = harness(); await h.rendering.setSnapshot({ storms: [{ ...storm(), ...changed }] }); - assert.equal(h.sources[0].entities.values.length, 1); + assert.deepEqual( + h.items().map((item) => item.id), + ['cyclone:ep152026:center'], + ); assert.equal(h.rendering.getDiagnostics().tracks, 0); h.rendering.destroy(); } }); -test('a data-source add settling after disable is removed, without a new owner', async () => { - const h = harness({ deferred: true }); - const pending = h.rendering.setSnapshot({ storms: [storm()] }); - h.rendering.clear(); - h.completions.shift()(); - assert.equal(await pending, false); - assert.equal(h.sources.length, 0); - assert.equal(h.rendering.getDiagnostics().dataSources, 0); -}); -test('superseded asynchronous additions cannot replace newer geometry', async () => { - const h = harness({ deferred: true }); - const old = h.rendering.setSnapshot({ storms: [storm()] }); - const latest = h.rendering.setSnapshot({ storms: [] }); - h.completions[1](); - assert.equal(await latest, true); - h.completions[0](); - assert.equal(await old, false); - assert.equal(h.sources.length, 1); - assert.equal(h.rendering.getDiagnostics().storms, 0); - h.rendering.destroy(); -}); -test('aborting a pending add retains the prior complete source', async () => { - const h = harness({ deferred: true }); - const initial = h.rendering.setSnapshot({ storms: [storm()] }); - h.completions.shift()(); - await initial; + +test('an aborted or destroyed update keeps what is drawn', async () => { + const h = harness(); + await h.rendering.setSnapshot({ storms: [storm()] }); const controller = new AbortController(); - const update = h.rendering.setSnapshot( - { storms: [] }, - { signal: controller.signal }, - ); controller.abort(); - h.completions.shift()(); - assert.equal(await update, false); - assert.equal(h.sources.length, 1); + await assert.rejects( + h.rendering.setSnapshot({ storms: [] }, { signal: controller.signal }), + ); + assert.equal(h.items().length, 8); assert.equal(h.rendering.getDiagnostics().storms, 1); h.rendering.destroy(); + h.rendering.destroy(); + assert.equal(await h.rendering.setSnapshot({ storms: [storm()] }), false); + assert.ok(Object.values(h.sets).every((record) => record.disposed)); +}); + +test('an empty advisory after a full one leaves nothing drawn', async () => { + const h = harness(); + await h.rendering.setSnapshot({ storms: [storm()] }); + h.rendering.setSelection('ep152026'); + assert.equal(await h.rendering.setSnapshot({ storms: [] }), true); + assert.deepEqual(h.items(), []); + assert.equal(h.rendering.getDiagnostics().entities, 0); + h.rendering.destroy(); + h.rendering.setSelection('ep152026'); +}); + +test('clear empties the sets and a later advisory draws again', async () => { + const h = harness(); + await h.rendering.setSnapshot({ storms: [storm()] }); + h.rendering.setSelection('ep152026'); + h.rendering.clear(); + assert.equal(h.items().length, 0); + assert.ok(Object.values(h.sets).every((record) => !record.disposed)); + assert.deepEqual(h.rendering.getDiagnostics(), { + storms: 0, + tracks: 0, + cones: 0, + forecastPoints: 0, + dataSources: 0, + entities: 0, + selectedId: null, + timerActive: false, + }); + await h.rendering.setSnapshot({ storms: [storm()] }); + assert.equal(h.items().length, 8); + assert.equal( + h.sets.points.items.get('cyclone:ep152026:center').pixelSize, + 9, + 'clear drops the selection', + ); + h.rendering.destroy(); }); test('labels publish committed anchors to the shared overlay and follow selection and clear', async () => { - const h = harness({ deferred: true }); - const pending = h.rendering.setSnapshot({ + const h = harness(); + await h.rendering.setSnapshot({ storms: [storm(), { ...storm(), id: 'near', name: 'Near' }], }); - assert.equal(h.overlay.calls.length, 0, 'nothing publishes before commit'); - h.completions.shift()(); - assert.equal(await pending, true); - const entities = h.sources[0].entities.values; - const center = (id) => entities.find((e) => e.id === `cyclone:${id}:center`); + const anchor = (item) => fromDegrees(item.pos.lon, item.pos.lat, 0); + const point = (id) => h.sets.points.items.get(id); assert.deepEqual( h.overlay.calls .slice(0, 2) @@ -623,24 +413,27 @@ test('labels publish committed anchors to the shared overlay and follow selectio 'no selection, no lead-hour labels', ); assert.equal(h.overlay.entry('storm:near').title, 'Near'); - assert.equal(h.overlay.entry('storm:near').position, center('near').position); + assert.deepEqual( + h.overlay.entry('storm:near').position, + anchor(point('cyclone:near:center')), + 'labels sit at the anchors the points use', + ); + assert.equal(h.overlay.entry('storm:near').horizonCull, true); h.rendering.setSelection('near'); - assert.equal(center('near').point.pixelSize, 12); - assert.equal(center('ep152026').point.pixelSize, 9); assert.equal(h.overlay.entry('storm:near').variant, 'selected'); assert.equal(h.overlay.entry('storm:ep152026').variant, 'card'); - assert.ok(h.overlay.entry('lead:near:12')); - const publishes = h.overlay.publishes; - h.rendering.setSelection('near'); - assert.equal(h.overlay.publishes, publishes, 'unchanged selection is quiet'); + assert.deepEqual( + h.overlay.entry('lead:near:12').position, + anchor(point('cyclone:near:forecast:1')), + ); + assert.equal(h.overlay.entry('lead:near:12').maxDistance, 4_000_000); + assert.equal(h.overlay.entry('lead:ep152026:12'), null); // A refresh republishes the new anchors with the retained selection. - const refresh = h.rendering.setSnapshot({ + await h.rendering.setSnapshot({ storms: [{ ...storm(), id: 'near', name: 'Near' }], }); - h.completions.shift()(); - await refresh; assert.deepEqual( h.overlay.published().map((entry) => [entry.id, entry.variant]), [ @@ -648,22 +441,13 @@ test('labels publish committed anchors to the shared overlay and follow selectio ['lead:near:12', 'card'], ], ); - assert.equal( - h.overlay.entry('storm:near').position, - h.sources[0].entities.values[0].position, - ); - // A superseded addition never publishes, and clear hides the source. - const stale = h.rendering.setSnapshot({ storms: [storm()] }); h.rendering.clear(); const afterClear = h.overlay.calls.slice(-2); assert.deepEqual(afterClear, [ { kind: 'clear', source: CYCLONE_OVERLAY_SOURCE_ID }, { kind: 'visible', source: CYCLONE_OVERLAY_SOURCE_ID, visible: false }, ]); - h.completions.shift()(); - assert.equal(await stale, false); - assert.equal(h.overlay.calls.at(-1), afterClear[1]); h.rendering.destroy(); assert.equal(h.overlay.calls.at(-1), afterClear[1]); }); diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 3f0def823..fc9777d55 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -359,3 +359,92 @@ test('the earthquakes layer draws its discs as ground fills on a viewer of its o layer.destroy(); assert.equal(scene.added.length, 0); }); + +test('the cyclones layer draws clamped dots, draped tracks and holed cones on a viewer of its own', async () => { + const { createCycloneRendering } = + await import('../../layers/cyclones/rendering.js'); + const { scene, frame } = drawOver(); + const rendering = createCycloneRendering({ + viewer: { scene }, + overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, + }); + const storm = (id, lon) => ({ + id, + name: id, + advisoryNumber: '1', + geometryAdvisoryNumber: '1', + geometryStatus: 'current', + position: { longitude: lon, latitude: 0 }, + forecastPoints: [ + { position: { longitude: lon, latitude: 1 }, tauHours: 12 }, + ], + track: { + type: 'LineString', + coordinates: [ + [lon, 0], + [lon, 1], + ], + }, + cone: { + type: 'Polygon', + coordinates: [ + [ + [lon - 2, -2], + [lon + 2, -2], + [lon + 2, 2], + [lon - 2, 2], + [lon - 2, -2], + ], + [ + [lon - 1, -1], + [lon + 1, -1], + [lon + 1, 1], + [lon - 1, -1], + ], + ], + }, + }); + await rendering.setSnapshot({ + storms: [storm('near', 0), storm('far', 180)], + }); + const all = (host, out = []) => { + out.push(host); + if (host instanceof Cesium.PrimitiveCollection) + for (let i = 0; i < host.length; i++) all(host.get(i), out); + return out; + }; + const primitives = scene.added.flatMap((host) => all(host)); + const of = (type) => primitives.filter((p) => p instanceof type); + const [dots] = of(Cesium.BillboardCollection); + assert.equal(dots.length, 4, 'two centers, two forecast points'); + for (let i = 0; i < dots.length; i++) { + const dot = dots.get(i); + assert.equal(dot.heightReference, Cesium.HeightReference.CLAMP_TO_GROUND); + assert.equal(dot.disableDepthTestDistance, Infinity); + } + const [tracks] = of(Cesium.GroundPolylinePrimitive); + assert.equal(tracks.classificationType, Cesium.ClassificationType.BOTH); + assert.equal(tracks.geometryInstances.length, 6, 'tracks and ring outlines'); + const cones = of(Cesium.GroundPrimitive); + const instances = cones.flatMap((cone) => cone.geometryInstances); + assert.deepEqual(instances.map((instance) => instance.id.id).sort(), [ + 'cyclone:far:cone:0', + 'cyclone:near:cone:0', + ]); + for (const { geometry } of instances) + assert.equal(geometry._polygonHierarchy.holes.length, 1, 'the hole stays'); + + // Past the horizon the dots go; their storms' shapes are the globe's to hide. + frame(); + const shown = []; + for (let i = 0; i < dots.length; i++) + shown.push([dots.get(i).id.id, dots.get(i).show]); + assert.deepEqual(shown.sort(), [ + ['cyclone:far:center', false], + ['cyclone:far:forecast:0', false], + ['cyclone:near:center', true], + ['cyclone:near:forecast:0', true], + ]); + rendering.destroy(); + assert.equal(scene.added.length, 0); +}); diff --git a/src/render/cesium/drawHit.js b/src/render/cesium/drawHit.js new file mode 100644 index 000000000..6ccf774e0 --- /dev/null +++ b/src/render/cesium/drawHit.js @@ -0,0 +1,27 @@ +/** + * @module render/cesium/drawHit + * @description A Cesium pick of a draw-set item, as the contract's `Hit`. + * No imports, so the click dispatcher can use it without the draw port. + */ +/** + * A Cesium pick as the contract's `Hit` (`query.d.ts`), when what it picked + * is a draw-set item (its pick id is `{set, id, meta, lodGroup}`); else + * null. For code that reads a pick Cesium already made (the click + * dispatcher's); `query.pick` makes its own, and also leaves out items of + * hidden or unpickable sets. It does not check that the set or item is + * still drawn (a ground swap can pick a retiring primitive), so a caller + * matches the hit against its own current sets and item ids. + * @param {object|null|undefined} picked + */ +export function drawHitOf(picked) { + const id = picked?.id; + if (!id || typeof id.set !== 'string' || typeof id.id !== 'string') + return null; + return { + set: id.set, + id: id.id, + ...(id.meta === undefined ? {} : { meta: id.meta }), + ...(id.lodGroup === undefined ? {} : { lodGroup: id.lodGroup }), + surface: false, + }; +} diff --git a/src/render/cesium/ports.js b/src/render/cesium/ports.js index 14ebfdfbe..cff83b317 100644 --- a/src/render/cesium/ports.js +++ b/src/render/cesium/ports.js @@ -18,6 +18,7 @@ import { createCesiumCamera } from './camera.js'; import { listenerList, toCartesian, uncaught } from './common.js'; import { createCesiumCredits } from './credits.js'; import { createCesiumDraw } from './draw.js'; +import { drawHitOf } from './drawHit.js'; import { createCesiumEffects } from './effects.js'; import { createCesiumGlobe } from './globe.js'; import { createCesiumQuality } from './quality.js'; @@ -412,15 +413,7 @@ export function createCesiumPorts(widget, { capabilities, credentials = {} }) { item.show !== false && item.pickable !== false; - function hitOf({ id }) { - return { - set: id.set, - id: id.id, - ...(id.meta === undefined ? {} : { meta: id.meta }), - ...(id.lodGroup === undefined ? {} : { lodGroup: id.lodGroup }), - surface: false, - }; - } + const hitOf = ({ id }) => drawHitOf({ id }); /** The globe (or ellipsoid) under a pixel, as a surface hit. */ function surfaceHit(x, y) { diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 04adac958..701f02b46 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -67,8 +67,6 @@ "src/layers/cctv/selection.js", "src/layers/cctv/state.js", "src/layers/cctv/testing.js", - "src/layers/cyclones/index.js", - "src/layers/cyclones/rendering.js", "src/layers/directions/index.js", "src/layers/firms/cards.js", "src/layers/firms/lifecycle.js",