From dabdab47d66b23ab30b1375b9884826b64fc27fe Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 8 Nov 2026 11:54:43 -0800 Subject: [PATCH] Draw S2 GhostMaps through the renderer draw port, off Cesium Each product edition now draws as three renderer sets (pins, lines and fills) instead of a Cesium data source. Pins keep the depth test off and the Street Level horizon cull, clicks resolve through the draw hit of the current edition, and a new edition is drawn before the old one goes. A viewer with no renderer bound draws nothing and releases the edition's packed images. The layer leaves the Cesium list; a caller handing it a viewer of their own loads ./render/cesium/unbound first. The QA script reads pins from the scene instead of data sources. --- docs/CURRENT-STATE.md | 8 +- scripts/package-boundaries.json | 1 + scripts/qa-ghostmaps.mjs | 126 +++++++---- src/layers/ghostMaps/index.js | 282 ++++++++++++++++-------- src/layers/ghostMaps/lifecycle.test.mjs | 55 +++-- src/render/cesiumAllowList.json | 1 - src/render/unboundCamera.test.mjs | 3 + 7 files changed, 317 insertions(+), 159 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index ee95f4f89..a12fc3b6b 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -5687,14 +5687,14 @@ request viewbox and continues searching without that geographic preference. - Only a new head costs REST calls: one recursive tree and one commit. An optional `GITHUB_TOKEN` raises the REST limit. - After an upstream outage, a successful branch-head check clears the error and pushes a recovered catalog even when the commit is unchanged. Cached products stay in place; subsequent healthy unchanged checks stay silent. - The new catalog goes to `.gev-cache/ghostmaps/catalog.json` and to every open page over server-sent events (`/api/ghostmaps/events`, 25 s heartbeat, at most 64 subscribers). Default products are downloaded at once. - - The layer reloads only products whose blob changed. The new edition's data source is added before the old one is removed. A product that leaves the catalog leaves the globe. + - The layer reloads only products whose blob changed. The new edition's draw sets are added before the old ones are removed. A product that leaves the catalog leaves the globe. - The row reads `LIVE` while the stream is open. A five-minute catalog read is the backstop. - **Files.** `/api/ghostmaps/file/{product}` serves only catalog products. Files are downloaded by commit-pinned raw URLs, so a CDN cannot return an older edition. They are cached on disk by blob sha, and blobs no current product uses are pruned. A request whose `?v=` names the current blob is `immutable`. Repository paths never reach the page. - **Source ownership.** The application catalog receives `sources['s2-ghostmaps']` through the shared source contracts; an omitted or null source stays unavailable without opening a stream or fetching. The standalone source factory supplies the same-origin implementation and accepts replacements. Packed-image URLs are released on cancelled or failed product construction, and remain owned by a successfully loaded product until it is removed. - **Voice and locales.** S2 can be toggled through its registered id and aliases. The model already sees the S2 GhostMaps brand in the id, and compact alias-hint separators keep the complete voice prompt within its existing 52,000-character limit; accepted aliases are unchanged. The row and reports are translated in Spanish, Russian and Simplified Chinese. -- **Rendering.** The page parses the KMZ with the import module's zip, KMZ and XML helpers into one `CustomDataSource` per product. - - Points become ground-clamped billboards with the depth test off, so they never sink into terrain or 3D tiles. Because the Google 3D map hides the globe, nothing else would stop far-side pins drawing through the planet. Pins are therefore horizon-culled with Street Level's `createHorizonCull` before their first frame and again whenever the camera moves. - - Lines and polygon outlines are ground-clamped polylines. +- **Rendering.** The page parses the KMZ with the import module's zip, KMZ and XML helpers into renderer draw sets (icons, lines and shapes) per product edition. The layer no longer reaches Cesium, so a consumer handing it a Cesium viewer, with no renderer bound, loads the `./render/cesium/unbound` export once first. + - Points become ground-clamped icons with the depth test off, so they never sink into terrain or 3D tiles. Because the Google 3D map hides the globe, nothing else would stop far-side pins drawing through the planet. Pins are therefore horizon-culled with Street Level's `createHorizonCull` before their first frame and again whenever the camera moves. + - Lines and polygon outlines are ground-clamped lines; polygon fills are ground-clamped shapes. - Styles, StyleMaps and inline styles are honoured. Icons come only from images packed in the same KMZ and at most 512 KB. Anything else uses a per-product round marker. - Network links, overlays, models and remote hrefs are never followed. Hidden placemarks are skipped. Bounds are 20,000 placemarks and 250,000 positions per product. - **Reports.** Clicking a marker opens a card with the product, folder, edition date and the placemark's report fields. `src/layers/ghostMaps/records.js` reads ArcGIS popup tables as text only: `` and internal fields are dropped and values are capped. Description markup is never inserted into the page. The first `http(s)` research link opens from the card. The card is `stateless`, so it comes and goes with the click, as CCTV cards do. It is also `horizonCull`ed, so it hides when its marker turns behind the planet. Picks are registered under `s2-ghostmaps`. diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index da7df1827..8f2e98edf 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -5946,6 +5946,7 @@ "exports": ["./layers/ghostmaps"], "modules": [ "src/layers/ghostMaps/index.js", + "src/render/color.js", "src/geo/index.js", "src/geo/julian.js", "src/layers/ghostMaps/catalog.js", diff --git a/scripts/qa-ghostmaps.mjs b/scripts/qa-ghostmaps.mjs index 83dc8ed97..45f94ebb2 100644 --- a/scripts/qa-ghostmaps.mjs +++ b/scripts/qa-ghostmaps.mjs @@ -8,7 +8,7 @@ * * (i) LIVE — enabling the layer loads the default products (Common * Intelligence Picture and the 30-day kinetic pull) from the live - * repository through /api/ghostmaps, one data source per product, + * repository through /api/ghostmaps, one pin set per product, * matching the proxy's catalog commit; the row shows one chip per * catalog product with the defaults active, and the page holds an * open event stream to /api/ghostmaps/events. @@ -17,12 +17,14 @@ * and clicking empty ground clears it. * (iii) PUSH (synthetic) — the event stream is replaced in the page and a * catalog naming a new edition of one product is pushed: only that - * product reloads (a new data source replaces the old one, no - * duplicates), the other keeps its data source. A catalog without a + * product reloads (a new pin set replaces the old one, no + * duplicates), the other keeps its pin set. A catalog without a * product removes it. * (iv) CHIPS — clicking an active product chip removes that product, * clicking it again restores it; the choice survives a reload. - * (v) DISABLE — every GhostMaps data source leaves the viewer. + * (v) DISABLE — every GhostMaps pin set leaves the viewer. + * The checks read pins (billboards) only: a product's lines and fills + * are not counted. * (vi) VIEWPORT — at a 390x844 phone viewport the open row and its chips * fit the panel width with no horizontal overflow. * (vii) FAR SIDE — pins skip the depth test, so they are horizon-culled: @@ -76,18 +78,43 @@ async function boot(page) { await page.keyboard.press('Escape'); } -/** GhostMaps data sources on the viewer: name → entity count. */ -function ghostSources(prefix) { - const { dataSources } = window.__godsEyeView.viewer; - const out = []; - for (let i = 0; i < dataSources.length; i++) { - const ds = dataSources.get(i); - if (ds.name?.startsWith(prefix)) - out.push({ name: ds.name, count: ds.entities.values.length }); - } +/** + * The GhostMaps pins drawn, by edition: each product's pins are drawn in a + * billboard collection of their own (a data source's, or a draw set's), so + * whatever draws them is read the same way. In the page: `layerId:product` + * → `{collection, pins: [{show, position}]}`. + */ +function ghostPins(prefix) { + const out = new Map(); + const seen = new Set(); + const visit = (node) => { + if (!node || typeof node !== 'object' || seen.has(node)) return; + seen.add(node); + if (Array.isArray(node._billboards)) { + for (const billboard of node._billboards) { + const id = String(billboard?.id?.id ?? billboard?.id ?? ''); + if (!id.startsWith('ghostmaps:')) continue; + const name = `${prefix}${id.split(':')[1]}`; + if (!out.has(name)) out.set(name, { collection: node, pins: [] }); + out.get(name).pins.push(billboard); + } + return; + } + if (Array.isArray(node._primitives)) node._primitives.forEach(visit); + visit(node._billboardCollection); + }; + visit(window.__godsEyeView.viewer.scene.primitives); return out; } +/** GhostMaps editions drawn: name → pin count. */ +function ghostSources(prefix) { + return [...ghostPins(prefix)].map(([name, { pins }]) => ({ + name, + count: pins.length, + })); +} + function paintedOverlayPixels() { const canvas = document.getElementById('world-overlay-canvas'); if (!canvas) return -1; @@ -124,7 +151,9 @@ const stats = (page) => LAYER_ID, ); const sources = (page) => - page.evaluate(`(${ghostSources})(${JSON.stringify(`${LAYER_ID}:`)})`); + page.evaluate( + `${ghostPins};(${ghostSources})(${JSON.stringify(`${LAYER_ID}:`)})`, + ); async function showRow(page) { await page.evaluate((id) => { @@ -175,7 +204,7 @@ async function main() { const live = await stats(page); const liveSources = await sources(page); record( - 'LIVE: default products load as one data source each', + 'LIVE: default products load as one pin set each', liveSources.length === 2 && liveSources.every((s) => s.count > 0) && live.products.sort().join() === 'cip,kinetic-30d', @@ -225,14 +254,14 @@ async function main() { await page.screenshot({ path: path.join(SHOTS_DIR, 'ghostmaps-live.png') }); // ---- (ii) PICK ---------------------------------------------------------- - const target = await page.evaluate((id) => { + const target = await page.evaluate(`(() => { + ${ghostPins}; const gev = window.__godsEyeView; - const ds = [...Array(gev.viewer.dataSources.length).keys()] - .map((i) => gev.viewer.dataSources.get(i)) - .find((item) => item.name === `${id}:cip`); - const entity = ds.entities.values.find((e) => e.billboard); + const pin = ghostPins(${JSON.stringify(`${LAYER_ID}:`)}).get( + ${JSON.stringify(`${LAYER_ID}:cip`)}, + ).pins[0]; const carto = gev.viewer.scene.globe.ellipsoid.cartesianToCartographic( - entity.position.getValue(gev.viewer.clock.currentTime), + pin.position, ); try { gev.viewer.camera.cancelFlight(); @@ -248,8 +277,8 @@ async function main() { orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); gev.viewer.scene.requestRender?.(); - return entity.id; - }, LAYER_ID); + return String(pin.id?.id ?? pin.id); + })()`); await page .waitForFunction( () => window.__godsEyeView.viewer.scene.globe.tilesLoaded, @@ -300,7 +329,7 @@ async function main() { }; }); record( - 'PICK: the centred marker picks as a GhostMaps entity', + 'PICK: the centred marker picks as a GhostMaps pin', probe.ids.some((id) => id.startsWith('ghostmaps:cip:')), `${target} → [${probe.ids.slice(0, 3).join(', ')}]`, ); @@ -366,7 +395,9 @@ async function main() { // be hidden, and pins facing the camera must still show. const horizonCounts = (lon, lat) => page.evaluate( - async (id, lo, la) => { + async (id, lo, la, pinsSource) => { + // eslint-disable-next-line no-new-func + const ghostPins = new Function(`return (${pinsSource})`)(); const gev = window.__godsEyeView; const d2r = Math.PI / 180; try { @@ -389,12 +420,9 @@ async function main() { const norm = (v) => Math.hypot(v.x, v.y, v.z); let far = 0; let nearShown = 0; - for (let i = 0; i < gev.viewer.dataSources.length; i++) { - const ds = gev.viewer.dataSources.get(i); - if (!ds.name?.startsWith(`${id}:`)) continue; - for (const e of ds.entities.values) { - if (!e.billboard) continue; - const p = e.position.getValue(gev.viewer.clock.currentTime); + for (const { pins } of ghostPins(`${id}:`).values()) { + for (const e of pins) { + const p = e.position; // Angle from the camera's nadir to the pin, against the // geometric horizon angle; the cull's 1 km margin shows pins up // to about 1° past it, so "clearly behind" is beyond 2°. @@ -412,6 +440,7 @@ async function main() { LAYER_ID, lon, lat, + String(ghostPins), ); const fromIndianOcean = await horizonCounts(80, -30); record( @@ -459,7 +488,7 @@ async function main() { ); const without = await sources(page); record( - 'CHIPS: turning a product off removes only its data source', + 'CHIPS: turning a product off removes only its pins', without.length === 1 && without[0].name === `${LAYER_ID}:cip`, without.map((s) => s.name).join(', '), ); @@ -498,7 +527,7 @@ async function main() { ); await sleep(500); record( - 'DISABLE: every GhostMaps data source leaves the viewer', + 'DISABLE: every GhostMaps pin leaves the viewer', (await sources(page)).length === 0, ); await page.close(); @@ -533,20 +562,23 @@ async function main() { await boot(push); await enableAndSettle(push); const identity = () => - push.evaluate((id) => { - const { dataSources } = window.__godsEyeView.viewer; - window.__qaIds ||= new WeakMap(); - window.__qaNext ||= 1; - const out = {}; - for (let i = 0; i < dataSources.length; i++) { - const ds = dataSources.get(i); - if (!ds.name?.startsWith(`${id}:`)) continue; - if (!window.__qaIds.has(ds)) - window.__qaIds.set(ds, window.__qaNext++); - out[ds.name] = window.__qaIds.get(ds); - } - return out; - }, LAYER_ID); + push.evaluate( + (id, pinsSource) => { + // eslint-disable-next-line no-new-func + const ghostPins = new Function(`return (${pinsSource})`)(); + window.__qaIds ||= new WeakMap(); + window.__qaNext ||= 1; + const out = {}; + for (const [name, { collection }] of ghostPins(`${id}:`)) { + if (!window.__qaIds.has(collection)) + window.__qaIds.set(collection, window.__qaNext++); + out[name] = window.__qaIds.get(collection); + } + return out; + }, + LAYER_ID, + String(ghostPins), + ); const first = await identity(); const pushed = Date.now(); await push.evaluate(async (id) => { diff --git a/src/layers/ghostMaps/index.js b/src/layers/ghostMaps/index.js index ee69a044d..664d7885b 100644 --- a/src/layers/ghostMaps/index.js +++ b/src/layers/ghostMaps/index.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { decodeXml, kmzImageResolver, @@ -15,9 +14,9 @@ import { tn, } from '../../i18n/index.js'; import { createHorizonCull } from '../streetLevel/view.js'; -// The horizon cull reads the camera and frame ports: a viewer of a -// caller's own gets them from the unbound factories this loads. -import '../../render/cesium/camera.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { hexColor } from '../../render/color.js'; +import { drawOf, findFrame } from '../../render/rendererOf.js'; import { readGhostMapsKml } from './kml.js'; import { fieldLabel, parseDescriptionFields, wrapCardText } from './records.js'; import { inputFor as defaultInputFor } from '../../input/dispatcher.js'; @@ -110,10 +109,34 @@ function markerImage(color) { return url; } -const cesiumColor = (rgba, fallback, alpha) => +const drawColor = (rgba, fallback, alpha) => rgba - ? new Cesium.Color(rgba[0], rgba[1], rgba[2], alpha ?? rgba[3]) - : Cesium.Color.fromCssColorString(fallback).withAlpha(alpha ?? 1); + ? [rgba[0], rgba[1], rgba[2], alpha ?? rgba[3]] + : hexColor(fallback, alpha ?? 1); + +/** The size a marker image draws at, before its scale: the product marker. */ +const MARKER_SIZE = [20, 20]; + +/** + * An image's own size in pixels, as an icon drew it unsized; null when it + * cannot be read here (no DOM, or the image does not decode). + */ +async function imageSizeOf(url) { + if (typeof globalThis.Image !== 'function' || !url) return null; + try { + const image = new globalThis.Image(); + image.src = url; + await image.decode(); + return image.naturalWidth > 0 && image.naturalHeight > 0 + ? [image.naturalWidth, image.naturalHeight] + : null; + } catch { + return null; + } +} + +/** Each layer's draw sets have ids of their own. */ +let instances = 0; function anchorOf(geometry) { if (geometry.type === 'point') return geometry.position; @@ -157,7 +180,7 @@ export function createGhostMapsLayer({ let _selectedLink = null; let _lifetime = new AbortController(); let _selection = readStoredSelection(storage); - /** productId → {version, dataSource, urls, count, features} */ + /** productId → {version, sets, urls, features, pins} */ const _loaded = new Map(); /** productId → in-flight version */ const _loading = new Map(); @@ -165,7 +188,11 @@ export function createGhostMapsLayer({ const _failed = new Map(); const notifyRow = () => _rowListener?.(); - const render = () => _viewer?.scene?.requestRender?.(); + const render = () => + _viewer && findFrame(_viewer)?.requestRender?.('ghostmaps'); + /** This layer's draw sets' ids start with this; one set per edition. */ + const setBase = `${GHOSTMAPS_LAYER_ID}:${++instances}`; + let editions = 0; // Pins skip the depth test, and with Google 3D tiles the globe is hidden, // so nothing else stops far-side pins drawing through the planet. const _horizon = createHorizonCull({ @@ -173,7 +200,16 @@ export function createGhostMapsLayer({ items: function* () { for (const item of _loaded.values()) yield* item.pins; }, - onChange: render, + // Pins the cull turned are written to their editions' icon sets. + onChange: (changed) => { + const bySet = new Map(); + for (const pin of changed) { + if (!bySet.has(pin.set)) bySet.set(pin.set, []); + bySet.get(pin.set).push(pin.item); + } + for (const [set, items] of bySet) set?.upsert(items); + render(); + }, }); const canSelect = () => overlayHost && inputFor && picking; @@ -189,12 +225,61 @@ export function createGhostMapsLayer({ const item = _loaded.get(id); if (!item) return; _loaded.delete(id); - _viewer?.dataSources?.remove(item.dataSource, true); + disposeSets(item.sets); item.urls.forEach((url) => URL.revokeObjectURL(url)); if (_selectedKey?.startsWith(`${id}:`)) clearSelection(); } - /** Build one product's data source off-scene, then swap it in. */ + function disposeSets(sets) { + if (!sets) return; + for (const set of Object.values(sets)) set.dispose(); + } + + /** + * Draw a loaded edition in sets of its own, beside any edition drawing + * now. One that cannot be drawn draws nothing and lets its images go. + */ + function mount(next) { + const base = `${setBase}:${++editions}`; + const sets = {}; + try { + // Inside the try: a viewer with no renderer bound draws nothing and + // still lets the edition's images go. + const draw = drawOf(_viewer); + sets.shapes = draw.shapes({ id: `${base}:shapes`, clampTo: 'both' }); + sets.lines = draw.lines({ id: `${base}:lines`, clampTo: 'both' }); + sets.icons = draw.icons({ id: `${base}:icons`, clampTo: 'both' }); + sets.shapes.set(next.items.shapes); + sets.lines.set(next.items.lines); + sets.icons.set(next.items.icons); + } catch (error) { + disposeSets(sets); + next.urls.forEach((url) => URL.revokeObjectURL(url)); + throw error; + } + for (const pin of next.pins) pin.set = sets.icons; + next.sets = sets; + } + + /** The placemark a hit on one of this layer's items is, or null. */ + function hitKey(hit) { + if ( + !hit?.set?.startsWith(`${setBase}:`) || + !hit.id?.startsWith(PICK_PREFIX) + ) + return null; + const [productId, index] = hit.id.slice(PICK_PREFIX.length).split(':'); + const loaded = _loaded.get(productId); + // Only the drawing edition's sets: a retiring one may still pick. + const current = loaded?.sets + ? Object.values(loaded.sets).some((set) => set?.id === hit.set) + : false; + return current && loaded.features[Number(index)] + ? `${productId}:${index}` + : null; + } + + /** Build one product's draw items off-scene, then swap them in. */ async function load(product, signal) { const bytes = await source.getFile(product.id, product.version, { signal }); signal.throwIfAborted(); @@ -222,93 +307,113 @@ export function createGhostMapsLayer({ entries.clear(); signal.throwIfAborted(); const color = PRODUCT_COLORS[product.id] || ACCENT; - const dataSource = new Cesium.CustomDataSource( - `${GHOSTMAPS_LAYER_ID}:${product.id}`, - ); + const icons = []; + const lines = []; + const shapes = []; const features = []; const pins = []; - dataSource.entities.suspendEvents(); + // Each distinct icon's own size, read once: icons draw at it, scaled. + const sizes = new Map(); + const marker = markerImage(color); + for (const feature of parsed.features) + for (const geometry of feature.geometries) + if (geometry.type === 'point') { + const image = feature.style.icon || marker; + if (image && !sizes.has(image)) + sizes.set( + image, + image === marker ? MARKER_SIZE : imageSizeOf(image), + ); + } + for (const [image, size] of sizes) sizes.set(image, await size); + signal.throwIfAborted(); parsed.features.forEach((feature, index) => { const key = `${product.id}:${index}`; const { style } = feature; feature.geometries.forEach((geometry, part) => { const id = `${PICK_PREFIX}${key}:${part}`; if (geometry.type === 'point') { - const position = Cesium.Cartesian3.fromDegrees( - ...geometry.position, - ); - const entity = dataSource.entities.add({ + const position = fromDegrees(...geometry.position); + const image = style.icon || marker; + // An image that cannot be drawn shows nothing, as before. + if (!image) return; + const item = { id, - position, - billboard: { - image: style.icon || markerImage(color), - scale: Math.min( - 1.5, - Math.max(0.35, (style.iconScale ?? 1) * 0.7), - ), - color: - style.icon && style.iconColor - ? cesiumColor(style.iconColor) - : undefined, - heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, - verticalOrigin: Cesium.VerticalOrigin.CENTER, - // Ground-clamped icons would sink into terrain and 3D tiles; the - // horizon cull hides the far side instead (see `_horizon`). - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - }); + pos: position, + image, + size: sizes.get(image) ?? MARKER_SIZE, + scale: Math.min( + 1.5, + Math.max(0.35, (style.iconScale ?? 1) * 0.7), + ), + ...(style.icon && style.iconColor + ? { color: style.iconColor } + : {}), + height: 'clampGround', + anchor: 'center', + // Ground-clamped icons would sink into terrain and 3D tiles; the + // horizon cull hides the far side instead (see `_horizon`). + disableDepthTest: Number.POSITIVE_INFINITY, + }; + const at = icons.push(item) - 1; + // What the horizon cull turns: the icon as it draws now, in its + // edition's icon set once mounted. pins.push({ position, + set: null, + get item() { + return icons[at]; + }, get show() { - return entity.show; + return icons[at].show !== false; }, set show(value) { - entity.show = value; + icons[at] = { ...icons[at], show: value }; }, }); } else if (geometry.type === 'line') { - dataSource.entities.add({ + lines.push({ id, - polyline: { - positions: Cesium.Cartesian3.fromDegreesArray( - geometry.positions.flat(), - ), - width: Math.min(8, Math.max(1.5, style.lineWidth ?? 2)), - material: cesiumColor(style.lineColor, color), - clampToGround: true, + positions: geometry.positions.map(([lon, lat]) => + fromDegrees(lon, lat), + ), + widthPx: Math.min(8, Math.max(1.5, style.lineWidth ?? 2)), + mode: 'draped', + style: { + kind: 'solid', + color: drawColor(style.lineColor, color), }, }); } else { - const ring = (points) => - Cesium.Cartesian3.fromDegreesArray(points.flat()); - dataSource.entities.add({ + const ring = (points) => points.map(([lon, lat]) => ({ lon, lat })); + shapes.push({ id, - polygon: { - hierarchy: new Cesium.PolygonHierarchy( - ring(geometry.outer), - geometry.holes.map( - (hole) => new Cesium.PolygonHierarchy(ring(hole)), - ), - ), - material: - style.fill === false - ? Cesium.Color.TRANSPARENT - : cesiumColor( - style.polyColor, - color, - style.polyColor ? undefined : 0.25, - ), - classificationType: Cesium.ClassificationType.BOTH, + geometry: { + kind: 'polygon', + rings: [ring(geometry.outer), ...geometry.holes.map(ring)], }, + // An unfilled polygon is still there to click, as before. + fill: + style.fill === false + ? [0, 0, 0, 0] + : drawColor( + style.polyColor, + color, + style.polyColor ? undefined : 0.25, + ), + height: 'clampGround', }); if (style.outline !== false) - dataSource.entities.add({ + lines.push({ id: `${id}:outline`, - polyline: { - positions: ring([...geometry.outer, geometry.outer[0]]), - width: Math.min(6, Math.max(1.5, style.lineWidth ?? 2)), - material: cesiumColor(style.lineColor, color), - clampToGround: true, + positions: [...geometry.outer, geometry.outer[0]].map( + ([lon, lat]) => fromDegrees(lon, lat), + ), + widthPx: Math.min(6, Math.max(1.5, style.lineWidth ?? 2)), + mode: 'draped', + style: { + kind: 'solid', + color: drawColor(style.lineColor, color), }, }); } @@ -320,8 +425,14 @@ export function createGhostMapsLayer({ anchor: anchorOf(feature.geometries[0]), }); }); - dataSource.entities.resumeEvents(); - return { version: product.version, dataSource, urls, features, pins }; + return { + version: product.version, + items: { icons, lines, shapes }, + sets: null, + urls, + features, + pins, + }; } catch (error) { urls.forEach((url) => URL.revokeObjectURL(url)); throw error; @@ -351,8 +462,8 @@ export function createGhostMapsLayer({ return; } // Cull before the first frame so far-side pins never flash. - _horizon.update(next.pins); - await _viewer.dataSources.add(next.dataSource); + _horizon.update(next.pins, { quiet: true }); + mount(next); // The new edition is on the globe before the old one leaves. unload(product.id); _loaded.set(product.id, next); @@ -459,7 +570,7 @@ export function createGhostMapsLayer({ // when its marker turns behind the planet. stateless: true, horizonCull: true, - position: Cesium.Cartesian3.fromDegrees(...feature.anchor), + position: fromDegrees(...feature.anchor), }; if (card.interactive) { const link = _selectedLink; @@ -487,16 +598,6 @@ export function createGhostMapsLayer({ overlayHost?.setEntries(GHOSTMAPS_OVERLAY_SOURCE_ID, [], CARD_HOST_OPTIONS); } - function pickedKey(picked) { - const pickId = picking.resolvePickId(picked); - if (typeof pickId !== 'string' || !pickId.startsWith(PICK_PREFIX)) - return null; - const [productId, index] = pickId.slice(PICK_PREFIX.length).split(':'); - return _loaded.get(productId)?.features[Number(index)] - ? `${productId}:${index}` - : null; - } - function installClickHandler() { if (!canSelect() || _clickSubscription || !_viewer) return; picking.registerPickOwner?.( @@ -515,7 +616,7 @@ export function createGhostMapsLayer({ return; } const picked = event.pick; - const key = picked ? pickedKey(picked) : null; + const key = picked ? hitKey(event.drawHit) : null; if (key) { _selectedKey = key; publishCard(); @@ -563,7 +664,8 @@ export function createGhostMapsLayer({ enable() { _enabled = true; _lifetime = new AbortController(); - for (const item of _loaded.values()) item.dataSource.show = true; + for (const item of _loaded.values()) + for (const set of Object.values(item.sets ?? {})) set.show = true; installClickHandler(); if (!_unsubscribe && typeof source.subscribe === 'function') _unsubscribe = source.subscribe( diff --git a/src/layers/ghostMaps/lifecycle.test.mjs b/src/layers/ghostMaps/lifecycle.test.mjs index 51d546017..ab0515168 100644 --- a/src/layers/ghostMaps/lifecycle.test.mjs +++ b/src/layers/ghostMaps/lifecycle.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import * as Cesium from 'cesium'; import { createGhostMapsLayer } from './index.js'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; function element(localName, children = [], value = '', attributes = {}) { const node = { @@ -104,17 +104,17 @@ function fixture(t, { beforeFileReturns, onCreateUrl } = {}) { }); t.mock.method(URL, 'revokeObjectURL', (url) => revoked.push(url)); t.mock.method(console, 'warn', () => {}); - const mounted = new Set(); - const viewer = { - scene: { requestRender() {} }, - dataSources: { - async add(dataSource) { - mounted.add(dataSource); - return dataSource; - }, - remove(dataSource) { - return mounted.delete(dataSource); - }, + const viewer = {}; + const { draw, unbind } = bindFakeDraw(viewer); + t.after(unbind); + // The editions drawn: each draws in sets of its own. + const mounted = { + get size() { + return new Set( + [...draw.sets.values()] + .filter((set) => !set.disposed) + .map((set) => set.spec.id.split(':').slice(0, 3).join(':')), + ).size; }, }; const layer = createGhostMapsLayer({ @@ -132,7 +132,7 @@ function fixture(t, { beforeFileReturns, onCreateUrl } = {}) { layer.init(viewer); layer.enable(); t.after(() => layer.destroy()); - return { layer, viewer, mounted, created, revoked }; + return { layer, viewer, draw, unbind, mounted, created, revoked }; } test('cancelling a file read does not allocate packed-image URLs', async (t) => { @@ -155,9 +155,9 @@ test('cancellation during parsing releases every packed-image URL', async (t) => assert.equal(mounted.size, 0); }); -test('entity construction failure releases parsed image URLs', async (t) => { - const { layer, viewer, mounted, created, revoked } = fixture(t); - t.mock.method(Cesium.EntityCollection.prototype, 'add', () => { +test('a draw failure releases parsed image URLs', async (t) => { + const { layer, viewer, draw, mounted, created, revoked } = fixture(t); + t.mock.method(draw, 'icons', () => { throw new Error('fixture entity failure'); }); await layer.update(viewer); @@ -167,13 +167,34 @@ test('entity construction failure releases parsed image URLs', async (t) => { assert.equal(layer.getStats().error, 'fixture entity failure'); }); +test('a viewer with no renderer bound releases parsed image URLs', async (t) => { + const { layer, viewer, unbind, mounted, created, revoked } = fixture(t); + unbind(); + await layer.update(viewer); + assert.equal(created.length, 1); + assert.deepEqual(revoked, created); + assert.equal(mounted.size, 0); + assert.ok(layer.getStats().error); +}); + test('successful load keeps icons until the product is disabled', async (t) => { - const { layer, viewer, mounted, created, revoked } = fixture(t); + const { layer, viewer, draw, mounted, created, revoked } = fixture(t); await layer.update(viewer); assert.equal(created.length, 1); assert.equal(revoked.length, 0); assert.equal(mounted.size, 1); assert.equal(layer.getStats().count, 1); + const pins = [...draw.sets.values()].find( + (set) => !set.disposed && set.kind === 'icons', + ); + const [pin] = pins.items.values(); + assert.equal(pin.id, 'ghostmaps:cip:0:0'); + assert.equal(pin.image, 'blob:local-0'); + assert.equal(pin.height, 'clampGround'); + assert.equal(pins.spec.clampTo, 'both'); + assert.equal(pin.disableDepthTest, Infinity); + assert.equal(pin.scale, 0.7); + assert.deepEqual(pin.size, [20, 20], 'unread in Node: the marker size'); layer.disable(); assert.deepEqual(revoked, created); assert.equal(mounted.size, 0); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 7ff397090..921880900 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -14,7 +14,6 @@ "src/layers/cctv/projection.js", "src/layers/cctv/rendering.js", "src/layers/firms/rendering.js", - "src/layers/ghostMaps/index.js", "src/layers/installations/rendering.js", "src/layers/radio/rendering.js", "src/layers/recentImagery/rendering.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index 473464049..4698465d9 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -103,6 +103,9 @@ const DRAW_FROM_CALLER = new Set([ // Not wholly Cesium-free (its pointer input still is), but its missions // draw, pick and fly through the ports alone. './layers/launches', + // Its pins, footprints and outlines draw through `drawOf`; its horizon + // cull reads the camera and frame ports. + './layers/ghostmaps', ]); /**