diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 205512676..f7c587e6c 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2276,9 +2276,17 @@ which embeds the MAP_KEY. windows reuse the active load. Disabling or returning Contacts to passive mode clears its anchor; passive refreshes cannot reclaim it. Background repaints refresh context records without publishing a new selection. - Installation tiles decode only the `landuse` layer. Reloads keep the Cesium - entities of sites whose geometry is unchanged, so outlines and fills do not - blink. While Contacts has a subject, the layer loads a window around it + Installation tiles decode only the `landuse` layer. The site dots, the + selected site's dot (a set of its own, so selecting one redraws no other), + their ground outlines and the selected site's fill are renderer draw sets; + reloads keep the drawn items of sites whose geometry is unchanged, so + outlines and fills do not blink. A double-click on a dot follows the site + through the camera port, centred on the surface under it (one on an outline + or fill zooms to it), as the default renderer's double-click followed its + entity; hiding the layer stops that follow. The layer no longer reaches + Cesium; a caller handing it a Cesium viewer, with no + renderer bound, loads the `./render/cesium/unbound` export once first. + While Contacts has a subject, the layer loads a window around it instead of the camera view (100 km half-width at mid latitudes, shrinking so it fits 16 z9 tiles), moves it only after the subject travels 20 km, and ignores camera `moveEnd`; clearing the subject returns to the viewport. The diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 967edb508..3cd1fc151 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2215,7 +2215,8 @@ "src/render/color.js", "src/layers/installations/policy.js", "src/layers/installations/rendering.js", - "src/layers/installations/markerState.js", + "src/geo/sphere.js", + "src/data/followed.js", "src/layers/installations/selection.js", "src/layers/installations/source.js", "src/layers/installations/state.js", @@ -3520,7 +3521,6 @@ "src/layers/installations/model.js", "src/layers/installations/policy.js", "src/layers/installations/rendering.js", - "src/layers/installations/markerState.js", "src/layers/installations/selection.js", "src/layers/installations/source.js", "src/layers/installations/state.js", @@ -4485,7 +4485,6 @@ "src/layers/installations/model.js", "src/layers/installations/policy.js", "src/layers/installations/rendering.js", - "src/layers/installations/markerState.js", "src/layers/installations/selection.js", "src/layers/installations/source.js", "src/layers/installations/state.js", diff --git a/scripts/qa-installation-navigation.mjs b/scripts/qa-installation-navigation.mjs index 5ecf03e1a..8eff6e99b 100644 --- a/scripts/qa-installation-navigation.mjs +++ b/scripts/qa-installation-navigation.mjs @@ -40,9 +40,29 @@ try { page.on('console', (m) => { if (m.type() === 'error') result.errors.push(m.text()); }); - await page.evaluateOnNewDocument(() => - sessionStorage.setItem('gev:first-run-mission-session:v1', 'dismissed'), - ); + await page.evaluateOnNewDocument(() => { + sessionStorage.setItem('gev:first-run-mission-session:v1', 'dismissed'); + // The site dots the layer draws, read from its draw-port point set: each + // row is a drawn dot whose pick id is the draw port's `{set, id, meta}`; + // `meta` is the site's carrier, kept while the site's geometry is. + window.__qaInstallationDots = () => { + const out = []; + const visit = (node) => { + if (!node || typeof node.get !== 'function') return; + if (typeof node.length !== 'number') return; + for (let index = 0; index < node.length; index += 1) { + const child = node.get(index); + const id = child?.id; + if (id && typeof id === 'object' && typeof id.set === 'string') { + if (/^military-installations:\d+:dots$/.test(id.set)) + out.push({ id: id.id, meta: id.meta, primitive: child }); + } else visit(child); + } + }; + visit(window.__godsEyeView.viewer.scene.primitives); + return out; + }; + }); await page.goto( args.find((a) => /^https?:/.test(a)), { waitUntil: 'domcontentloaded' }, @@ -156,14 +176,15 @@ try { .catch(() => {}); const snapshot = await page.evaluate(() => { const g = window.__godsEyeView; - const ds = g.viewer.dataSources.getByName('military-installations')[0]; - const points = ds.entities.values.filter((e) => e.point); + const points = window.__qaInstallationDots(); const stable = points.every( (e) => !window.installationEntityRefs.has(e.id) || - window.installationEntityRefs.get(e.id) === e, + window.installationEntityRefs.get(e.id) === e.meta, + ); + window.installationEntityRefs = new Map( + points.map((e) => [e.id, e.meta]), ); - window.installationEntityRefs = new Map(points.map((e) => [e.id, e])); return { ...g.dataManager.layers .get('military-installations') @@ -186,7 +207,7 @@ try { new Set(row.ids).size !== row.ids.length ) result.failures.push( - `${name}/${height}: unstable or duplicate site entities`, + `${name}/${height}: unstable or duplicate site markers`, ); if (name.endsWith('return')) { const first = result.views.find( @@ -244,10 +265,7 @@ try { 0.6, ); await page.waitForFunction( - () => - window.__godsEyeView.viewer.dataSources - .getByName('military-installations')[0] - .entities.values.some((e) => e.point), + () => window.__qaInstallationDots().length > 0, { timeout: 5000 }, ); await page.evaluate(() => { @@ -268,8 +286,7 @@ try { await sleep(1000); await page.evaluate(async () => { const g = window.__godsEyeView; - const ds = g.viewer.dataSources.getByName('military-installations')[0]; - const id = ds.entities.values.find((e) => e.point).id; + const id = window.__qaInstallationDots()[0].id; window.installationSubjectId = id; await g.dataManager.layers .get('military-awareness') diff --git a/scripts/qa-installation-polish.mjs b/scripts/qa-installation-polish.mjs index df1b8429e..8a9703e2c 100644 --- a/scripts/qa-installation-polish.mjs +++ b/scripts/qa-installation-polish.mjs @@ -177,18 +177,13 @@ export async function checkInstallationSelection( await import('/src/data/contextStore.js'); const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); - const knownFills = new Set(); - const fillEntities = () => { - const list = []; - for (let i = 0; i < g.viewer.dataSources.length; i++) - for (const e of g.viewer.dataSources.get(i).entities.values) - if (e.id.startsWith(`${record.id}:selected-fill:`)) list.push(e); - for (const e of list) knownFills.add(e); - return list; - }; - // Geometry-instance ids prove the ground primitive actually built, not just an entity declaration. - const primitives = () => { - let count = 0; + // The selected site's fill parts, as the ground primitives built for + // the layer's fill set hold them: each instance's id is the + // draw port's pick id `{set, id}`. Only built, shown instances count, + // so this proves the ground primitive actually built, not just an + // item declaration. + const fillParts = () => { + const parts = []; const walk = (collection) => { if (collection?._collectionsArray) { for (const child of collection._collectionsArray) walk(child); @@ -196,31 +191,44 @@ export async function checkInstallationSelection( } for (let i = 0; i < (collection?.length || 0); i++) { const p = collection.get(i); - if ( - p.ready && - typeof p.getGeometryInstanceAttributes === 'function' - ) { - for (const e of knownFills) { + const ids = p?._primitive?._primitive?._instanceIds; + if (p?.ready && Array.isArray(ids)) + for (const id of ids) { + if ( + !/^military-installations:\d+:fills$/.test(id?.set) || + !String(id.id).startsWith(`${record.id}:selected-fill:`) + ) + continue; try { - const a = p.getGeometryInstanceAttributes(e); - if (a && (!a.show || a.show[0])) count++; + const a = p.getGeometryInstanceAttributes(id); + if (a && (!a.show || a.show[0])) + parts.push({ + id: id.id, + classification: p.classificationType, + }); } catch {} } - } - if (typeof p.get === 'function' || p._collectionsArray) walk(p); + if (typeof p?.get === 'function' || p?._collectionsArray) + walk(p); } }; + // The draw port adds its ground primitives under the scene's + // primitives, in its set's collection. walk(g.viewer.scene.groundPrimitives); - return count; + walk(g.viewer.scene.primitives); + return parts; + }; + window.__polishFillProbe = () => { + const parts = fillParts(); + return { + // Distinct fill parts drawn, and the built instances drawing them + // (a ground swap can draw a part twice while it lasts). + entities: new Set(parts.map((part) => part.id)).size, + primitives: parts.length, + classification: parts.map((part) => part.classification), + selected: getSelectedEntityContext()?.id || null, + }; }; - window.__polishFillProbe = () => ({ - entities: fillEntities().length, - primitives: primitives(), - classification: fillEntities().map((e) => - e.polygon.classificationType.getValue(), - ), - selected: getSelectedEntityContext()?.id || null, - }); window.__stopPolishSelection = g.viewer.scene.postRender.addEventListener(() => { window.__polishSelectionFrames.push({ diff --git a/src/data/localGeojsonCore.js b/src/data/localGeojsonCore.js index e55a87bfc..ee2244907 100644 --- a/src/data/localGeojsonCore.js +++ b/src/data/localGeojsonCore.js @@ -8,13 +8,8 @@ import { findQuery, } from '../render/rendererOf.js'; import { cssColor } from '../render/color.js'; -import { - WGS84, - fromDegrees, - fromDegreesInto, - toLonLatH, -} from '../geo/ellipsoid.js'; -import { offsetFromHeadingPitchRange } from '../geo/frames.js'; +import { fromDegrees, fromDegreesInto, toLonLatH } from '../geo/ellipsoid.js'; +import { followOffsetFitting } from '../geo/frames.js'; import { sphereFromPoints } from '../geo/sphere.js'; import { densifyRhumb } from '../geo/rhumb.js'; import { heightsOf } from '../queries/heights.js'; @@ -321,32 +316,19 @@ const STEM_WIDTH_PX = 3.5; const PIN_SIZE_PX = 8; const BLACK = Object.freeze([0, 0, 0, 1]); -/** The range the default renderer frames a sphere of no size from. */ -const MINIMUM_FIT_RANGE_M = 100; - /** * Where the camera frames a part it starts following, as the default - * renderer framed an entity it started following with no view of its own: - * looking at the bounds' centre, heading north, pitched down 45° (steeper - * far from the ground), at the range that fits the bounds in view, within - * the camera's zoom limits. Returned as the eye's offset from the centre, - * east-north-up there; `at` is where the part stands. + * renderer framed an entity it started following with no view of its own + * (`followOffsetFitting`); `at` is where the part stands. */ function followViewFrom(sphere, at, camera) { const pose = camera.pose?.(); - const fovy = Number.isFinite(pose?.fovy) ? pose.fovy : Math.PI / 3; - const aspect = Number.isFinite(pose?.aspectRatio) ? pose.aspectRatio : 1; - const tanPhi = Math.tan(fovy / 2); - const tanTheta = aspect * tanPhi; - let range = - sphere.radius === 0 - ? MINIMUM_FIT_RANGE_M - : Math.max(sphere.radius / tanTheta, sphere.radius / tanPhi); - const { minDistance = 0, maxDistance = Infinity } = camera.controls ?? {}; - range = Math.min(Math.max(range, minDistance), maxDistance); - const factor = - 2 - 1 / Math.max(1, Math.hypot(at.x, at.y, at.z) / WGS84.radii.x); - return offsetFromHeadingPitchRange(0, (-Math.PI / 4) * factor, range); + return followOffsetFitting(sphere, at, { + fovy: pose?.fovy, + aspectRatio: pose?.aspectRatio, + minDistance: camera.controls?.minDistance, + maxDistance: camera.controls?.maxDistance, + }); } /** The GeoJSON loader's `marker-size` names, in pixels. */ diff --git a/src/data/militaryInstallations.test.mjs b/src/data/militaryInstallations.test.mjs index db6fb65de..466412644 100644 --- a/src/data/militaryInstallations.test.mjs +++ b/src/data/militaryInstallations.test.mjs @@ -28,6 +28,26 @@ import { import * as Cesium from 'cesium'; import { registerEntityContext, selectEntityContext, getSelectedEntityContext, clearSelectedEntityContextForLayer } from './contextStore.js'; import { readEntityRecord } from './entityRecords.js'; +import { drawOf } from '../render/rendererOf.js'; + +/** The installations layer's live site-dot set on `viewer`'s draw port. */ +function dotSetOf(viewer) { + return [...drawOf(viewer).sets.values()].find( + (set) => !set.disposed && /^military-installations:\d+:dots$/.test(set.spec.id), + ); +} + +/** The installations layer's live selected-dot set on `viewer`'s draw port. */ +function selectedSetOf(viewer) { + return [...drawOf(viewer).sets.values()].find( + (set) => !set.disposed && /^military-installations:\d+:selected$/.test(set.spec.id), + ); +} + +/** The drawn site dots on `viewer`, in drawing order. */ +function dotsOf(viewer) { + return [...(dotSetOf(viewer)?.items.values() ?? [])]; +} test('clicking a selected installation again or empty map clears it through refresh', async () => { const run = await runInstallationLoad({ elements: [{ type: 'node', id: 42, @@ -40,7 +60,7 @@ test('clicking a selected installation again or empty map clears it through refr assert.equal(getSelectedEntityContext(), null); await militaryInstallationsLayer.update(); assert.equal(getSelectedEntityContext(), null, 'refresh must not resurrect selection'); - assert.equal(run.entities()[0].point.pixelSize.getValue(), 9); + assert.equal(run.dots()[0].pixelSize, 9); } } finally { run.restore(); } }); @@ -58,7 +78,7 @@ test('background installation paints neither reopen Contacts nor resurrect a cle await militaryInstallationsLayer.update(); assert.equal(getSelectedEntityContext(),null); assert.equal(selected(),1,'an external clear must survive the next paint'); - assert.equal(run.entities()[0].point.pixelSize.getValue(),9); + assert.equal(run.dots()[0].pixelSize,9); } finally { run.restore(); } }); @@ -90,8 +110,9 @@ test('switching sites keeps the new selection through refresh and disable clears assert.equal(getSelectedEntityContext()?.id, 'osm:node:43'); await militaryInstallationsLayer.update(); assert.equal(getSelectedEntityContext()?.id, 'osm:node:43'); - assert.equal(run.entities().find(e => e.id === 'osm:node:42').point.pixelSize.getValue(), 9); - assert.equal(run.entities().find(e => e.id === 'osm:node:43').point.pixelSize.getValue(), 13); + assert.equal(run.dots().find(e => e.id === 'osm:node:42').show, true); + assert.equal(run.dots().find(e => e.id === 'osm:node:43').show, false); + assert.deepEqual(run.selectedDots().map(e => [e.id, e.pixelSize]), [['osm:node:43', 13]]); militaryInstallationsLayer.disable(); run.click('osm:node:42'); assert.equal(getSelectedEntityContext(), null, 'disabled layer ignores clicks'); @@ -133,7 +154,7 @@ test('places installation anchors on the shared cached rendered floor', () => { _clearMeshFloorCellsForTest(); }); -test('real enabled installation entities carry no native label graphics', async () => { +test('real enabled installation markers carry no native label graphics', async () => { const originalDocument = globalThis.document; const originalWindow = globalThis.window; const originalFetch = globalThis.fetch; @@ -205,9 +226,11 @@ test('real enabled installation entities carry no native label graphics', async militaryInstallationsLayer.init(viewer); militaryInstallationsLayer.enable(); await militaryInstallationsLayer.update(); - const entities = dataSources[0].entities.values; - assert.ok(entities.length > 0, 'runtime guard requires rendered installation records'); - assert.ok(entities.every((entity) => entity.label === undefined)); + // The dots are a draw-port point set, which draws no text of its own. + const dots = dotsOf(viewer); + assert.ok(dots.length > 0, 'runtime guard requires rendered installation records'); + assert.equal(dotSetOf(viewer).kind, 'points'); + assert.ok(dots.every((dot) => dot.text === undefined && dot.label === undefined)); } finally { militaryInstallationsLayer.destroy(viewer); globalThis.fetch = originalFetch; @@ -362,12 +385,20 @@ async function runInstallationLoad({ return { requests, cameraFlights, - entities: () => dataSources[0]?.entities?.values || [], + // Each drawn site's carrier: its id, and its record of what the tracked + // card and the shared selection read. + entities: () => dotsOf(viewer).map((dot) => dot.meta), + dots: () => dotsOf(viewer), + dotWrites: () => dotSetOf(viewer)?.writes ?? 0, + selectedDots: () => [...(selectedSetOf(viewer)?.items.values() ?? [])], contextLabels: () => contextEvents, stats: () => militaryInstallationsLayer.getStats(), click(target) { - const entity = typeof target === 'string' ? dataSources[0].entities.getById(target) : target; - picked = entity ? { id: entity } : undefined; + // A site's dot, picked as the draw port's pick id names it. + const dot = typeof target === 'string' ? dotSetOf(viewer)?.items.get(target) : null; + picked = dot + ? { id: { set: dotSetOf(viewer).spec.id, id: dot.id, meta: dot.meta } } + : target ? { id: target } : undefined; clickAction({ position: { x: 0, y: 0 } }); }, renderRequests: () => getRenderGovernorDiagnostics().recentRequests.map((item) => item.reason), @@ -638,16 +669,23 @@ test('a floor that lands after the render deadline lifts the dots off the ellips }; bindFakeCesiumCamera(viewer, fakeScenePorts(viewer)); - const heightOf = (entity) => Cesium.Cartographic.fromCartesian( - entity.position.getValue(Cesium.JulianDate.now()), - ).height; + // Where the dot stands (its display position, which the follow and the + // tracked card read), and the height it is drawn at before clamping. + const heightOf = (dot) => { + const at = readEntityRecord(dot.meta).displayPosition(); + const height = Cesium.Cartographic.fromCartesian( + new Cesium.Cartesian3(at.x, at.y, at.z), + ).height; + assert.ok(Math.abs(dot.pos.height - height) < 1e-6); + return height; + }; try { militaryInstallationsLayer.init(viewer); militaryInstallationsLayer.enable(); await militaryInstallationsLayer.update(); - const buried = dataSources[0].entities.values[0]; + const buried = dotsOf(viewer)[0]; assert.ok(buried, 'the cold-floor pass still renders the record'); assert.ok(Math.abs(heightOf(buried)) < 1, 'a cold floor anchors at the ellipsoid, as before'); @@ -657,7 +695,7 @@ test('a floor that lands after the render deadline lifts the dots off the ellips } assert.equal(cachedGroundFloor(lat, lon), 2400, 'the late floor landed in the shared cache'); - const lifted = dataSources[0].entities.values[0]; + const lifted = dotsOf(viewer)[0]; assert.ok( Math.abs(heightOf(lifted) - 2401.5) < 0.5, `re-render must lift the dot onto the resolved floor, got ${heightOf(lifted)}`, @@ -885,16 +923,18 @@ test('a Contacts anchor replaces the viewport and ignores small subject moves', } finally { run.restore(); } }); -test('unchanged installations keep their entities across reloads', async () => { +test('unchanged installations keep their markers across reloads', async () => { const run = await runInstallationLoad({ elements: [{ type: 'node', id: 42, lat: 30.2, lon: -97.7, tags: { military: 'base', name: 'Site' } }] }); try { const before = run.entities().slice(); assert.ok(before.length > 0); + const writes = run.dotWrites(); await militaryInstallationsLayer.update(); const after = run.entities(); assert.equal(after.length, before.length); - assert.ok(after.every((entity, index) => entity === before[index]), - 'a reload with the same geometry must not recreate entities'); + assert.ok(after.every((carrier, index) => carrier === before[index]), + 'a reload with the same geometry must not recreate markers'); + assert.equal(run.dotWrites(), writes, 'nor write them again'); } finally { run.restore(); } }); diff --git a/src/geo/frames.js b/src/geo/frames.js index 8693582c5..71aa3b84c 100644 --- a/src/geo/frames.js +++ b/src/geo/frames.js @@ -4,7 +4,7 @@ * east-north-up frame at a point, rotation about an axis, and the offset a * heading, pitch and range puts an eye at. */ -import { geodeticSurfaceNormal } from './ellipsoid.js'; +import { WGS84, geodeticSurfaceNormal } from './ellipsoid.js'; import { EPSILON14, PI_OVER_TWO, @@ -113,3 +113,34 @@ export function offsetFromHeadingPitchRange(heading, pitch, range) { ); return scale(negate(offset), range); } + +/** The range the default renderer frames a sphere of no size from. */ +const MINIMUM_FIT_RANGE_M = 100; + +/** + * Where the eye stands to follow a target, as the default renderer framed + * an entity it started following with no view of its own: looking at the + * centre of `sphere`, heading north, pitched down 45° (steeper far from the + * ground), at the range that fits the sphere in view (100 m for one of no + * size), within the camera's zoom limits. Returned as the eye's offset from + * the centre, east-north-up there; `at` is where the target stands. + * @param {{radius: number}} sphere + * @param {{x: number, y: number, z: number}} at + * @param {{fovy?: number, aspectRatio?: number, minDistance?: number, + * maxDistance?: number}} view The camera's field of view and zoom limits. + */ +export function followOffsetFitting(sphere, at, view = {}) { + const fovy = Number.isFinite(view.fovy) ? view.fovy : Math.PI / 3; + const aspect = Number.isFinite(view.aspectRatio) ? view.aspectRatio : 1; + const tanPhi = Math.tan(fovy / 2); + const tanTheta = aspect * tanPhi; + let range = + sphere.radius === 0 + ? MINIMUM_FIT_RANGE_M + : Math.max(sphere.radius / tanTheta, sphere.radius / tanPhi); + const { minDistance = 0, maxDistance = Infinity } = view; + range = Math.min(Math.max(range, minDistance), maxDistance); + const factor = + 2 - 1 / Math.max(1, Math.hypot(at.x, at.y, at.z) / WGS84.radii.x); + return offsetFromHeadingPitchRange(0, (-Math.PI / 4) * factor, range); +} diff --git a/src/layers/installations/lifecycle.js b/src/layers/installations/lifecycle.js index a2feb65ae..3162b1733 100644 --- a/src/layers/installations/lifecycle.js +++ b/src/layers/installations/lifecycle.js @@ -20,8 +20,6 @@ export function createLifecycle({ const camera = cameraOf(viewer); layerState.moveEndRemove = camera.on('moveEnd', cameraChanged); // Measured for this listener alone; off, a load is never scheduled. - // The sensitivity claim in enable() is for raw camera listeners - // elsewhere, which this layer has always made finer while on. layerState.changedRemove = camera.on('changed', cameraChanged, { threshold: CAMERA_CHANGED_THRESHOLD, }); @@ -48,9 +46,8 @@ export function createLifecycle({ }); parts.namedMarkers?.enable(); parts.namedMarkers?.sync(layerState.records || []); - parts.rendering.claimCameraChanges?.(); registerPickOwner(LAYER_ID, (id) => layerState.recordById.has(id)); - layerState.dataSource.show = true; + parts.rendering.setShown(true); // DataLayerManager invokes update() immediately after enable(), which owns // the first fetch. Avoid racing it with a second aborting request here. }, @@ -59,7 +56,6 @@ export function createLifecycle({ layerState.enabled = false; services.credits?.hideOsmCredit?.(layerState.viewer, LAYER_ID); parts.namedMarkers?.hide(); - parts.rendering.releaseCameraChanges?.(); layerState.contextAnchor = null; layerState.contextPosition = null; layerState.coverage = { kind: 'viewport' }; @@ -71,7 +67,7 @@ export function createLifecycle({ layerState.abort?.abort(); layerState.abort = null; layerState.loading = false; - if (layerState.dataSource) layerState.dataSource.show = false; + parts.rendering.setShown(false); clearSelectedEntityContextForLayer(LAYER_ID); layerState.selectedId = null; parts.rendering.clearSelectionFill?.(); diff --git a/src/layers/installations/lifecycle.test.mjs b/src/layers/installations/lifecycle.test.mjs index bf59fb387..963aa95cd 100644 --- a/src/layers/installations/lifecycle.test.mjs +++ b/src/layers/installations/lifecycle.test.mjs @@ -25,9 +25,9 @@ for (const source of [ viewer, records: source ? [{ id: 'base', sources: [source] }] : [], recordById: new Map(), - dataSource: { show: false }, }; let markersVisible = false; + let drawnShown = false; const parts = { namedMarkers: { enable: () => { @@ -38,7 +38,13 @@ for (const source of [ markersVisible = false; }, }, - rendering: { attach: noop, detach: noop }, + rendering: { + attach: noop, + detach: noop, + setShown: (shown) => { + drawnShown = shown; + }, + }, viewport: { clearUnavailableRetry: noop }, ingestion: { setInstallationStatus: noop }, }; @@ -61,12 +67,12 @@ for (const source of [ try { for (let cycle = 0; cycle < 2; cycle++) { lifecycle.enable(); - assert.equal(state.dataSource.show, true); + assert.equal(drawnShown, true); assert.equal(markersVisible, true); // No renderRecords or successful fetch occurs between toggles. assert.equal(visibleCredits.size, expected); lifecycle.disable(); - assert.equal(state.dataSource.show, false); + assert.equal(drawnShown, false); assert.equal(markersVisible, false); assert.equal(visibleCredits.size, 0); } diff --git a/src/layers/installations/markerState.js b/src/layers/installations/markerState.js deleted file mode 100644 index 295e9a733..000000000 --- a/src/layers/installations/markerState.js +++ /dev/null @@ -1,9 +0,0 @@ -import { createEntityStore } from '../../data/entityRecords.js'; - -/** - * What the installations layer last drew for a retained marker entity, so an - * unchanged record leaves it alone: `heightM` (surface height) and `selected`. - * Selection fills and outlines record the installation they belong to as - * `recordId`, which a pick on them resolves through. - */ -export const installationMarkers = createEntityStore(); diff --git a/src/layers/installations/namedMarkers.test.mjs b/src/layers/installations/namedMarkers.test.mjs index 91f48a887..e57b59496 100644 --- a/src/layers/installations/namedMarkers.test.mjs +++ b/src/layers/installations/namedMarkers.test.mjs @@ -26,7 +26,7 @@ function setup(t) { bindFakeCesiumCamera(state.viewer, { draw, query: fakeSceneQuery(state.viewer), frame: fakeSceneFrame(state.viewer) }); const services = { render: { governorRequestRender() {} }, picking: { registerPickOwner() {}, unregisterPickOwner() {} }, context: { clearSelectedEntityContextForLayer() {} } }; let loads = 0; - const parts = { model: { colorFor: () => [1, 165 / 255, 0, 1] }, rendering: { attach() { state.dataSource = { show: false }; }, detach() {}, installationSurfaceHeightM: () => 0, clearRendered() {} }, viewport: { scheduleLoad: () => loads++, clearUnavailableRetry() {} }, selection: { installInteraction() {} }, ingestion: { setInstallationStatus() {} } }; + const parts = { model: { colorFor: () => [1, 165 / 255, 0, 1] }, rendering: { attach() {}, setShown() {}, detach() {}, installationSurfaceHeightM: () => 0, clearRendered() {} }, viewport: { scheduleLoad: () => loads++, clearUnavailableRetry() {} }, selection: { installInteraction() {} }, ingestion: { setInstallationStatus() {} } }; const ctx = { state, services, parts, source: {}, overlayHost }; parts.namedMarkers = createNamedMarkers(ctx); const lifecycle = createLifecycle(ctx).methods; diff --git a/src/layers/installations/navigation.test.mjs b/src/layers/installations/navigation.test.mjs index d5e7c015f..5ee33700a 100644 --- a/src/layers/installations/navigation.test.mjs +++ b/src/layers/installations/navigation.test.mjs @@ -25,9 +25,8 @@ test('camera changes debounce, deduplicate moveEnd, cancel superseded loads and const parts = { selection: { installInteraction() {} }, rendering: { - attach() { - state.dataSource = { show: false }; - }, + attach() {}, + setShown() {}, detach() {}, clearRendered() {}, }, diff --git a/src/layers/installations/rendering.js b/src/layers/installations/rendering.js index e89f4007c..78b8d30f1 100644 --- a/src/layers/installations/rendering.js +++ b/src/layers/installations/rendering.js @@ -1,22 +1,38 @@ import { installationClassLabel, installationTitle } from './classLabel.js'; -import * as Cesium from 'cesium'; -// Still Cesium for its entities, so this layer loads the unbound camera -// factory its other parts reach the renderer through. -import '../../render/cesium/camera.js'; import { t } from '../../i18n/index.js'; +import { LAYER_ID, MAX_RENDERED, COLOR_BY_CLASS } from './policy.js'; +import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; +import { entityFollowTarget } from '../../data/followed.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { followOffsetFitting } from '../../geo/frames.js'; +import { sphereFromPoints } from '../../geo/sphere.js'; +import { heightsOf } from '../../queries/heights.js'; import { - CAMERA_CHANGED_THRESHOLD, - LAYER_ID, - MAX_RENDERED, - COLOR_BY_CLASS, -} from './policy.js'; -import { - claimCameraSensitivity, - releaseCameraSensitivity, -} from '../../data/cameraSensitivity.js'; -import { entityRecord } from '../../data/entityRecords.js'; -import { installationMarkers } from './markerState.js'; + drawOf, + findCamera, + findGlobe, + findQuery, +} from '../../render/rendererOf.js'; +let instances = 0; + +const DOT_OUTLINE = Object.freeze([0, 0, 0, 0.8]); +const SELECTED_DOT = Object.freeze([1, 1, 1, 1]); + +/** A record's footprint polygons, each its rings of `[lon, lat]`. */ +const footprintsOf = (record) => + record.footprints || (record.footprint ? [[record.footprint]] : []); + +/** A record's outline polylines of `[lon, lat]`. */ +const outlinesOf = (record) => + record.outlineLines || (record.footprint ? [record.footprint] : []); + +/** + * The installations layer's drawing: a draw-port point set of site dots, a + * point set of the selected site's dot (so selecting one restyles no other + * dot), a line set of their ground outlines and a shape set of the selected + * site's footprint fill, on the viewer's renderer (`drawOf`). + */ export function createRendering({ state: layerState, services, @@ -33,27 +49,48 @@ export function createRendering({ const { governorRequestRender } = services.render; const { warmFireAnchorFloors } = services.anchors; - /** A record's class colour, for the entities. */ - function colorFor(record) { + /** A record's class colour with alpha `alpha`, as the draw port takes it. */ + function colorFor(record, alpha = null) { const [r, g, b, a] = parts.model.colorFor(record); - return new Cesium.Color(r, g, b, a); + return [r, g, b, alpha ?? a]; } /** - * The layer's entities. They stay entities: the camera can follow a site - * (double-click), and the tracked card reads what it shows from them. + * Make the layer's draw sets, hidden until the layer is enabled, and + * follow a site on a double-click. */ function attach(viewer) { - layerState.dataSource = new Cesium.CustomDataSource( - 'military-installations', - ); - viewer.dataSources.add(layerState.dataSource); + const draw = drawOf(viewer); + selectedDotKey = null; + const prefix = `${LAYER_ID}:${++instances}`; + layerState.sets = { + dots: draw.points({ id: `${prefix}:dots`, show: false }), + selected: draw.points({ id: `${prefix}:selected`, show: false }), + outlines: draw.lines({ id: `${prefix}:outlines`, show: false }), + fills: draw.shapes({ id: `${prefix}:fills`, show: false }), + }; } - function detach(viewer) { - if (layerState.dataSource && viewer) - viewer.dataSources.remove(layerState.dataSource, true); - layerState.dataSource = null; + function detach() { + stopFollow(); + if (layerState.sets) + for (const set of Object.values(layerState.sets)) set.dispose(); + layerState.sets = null; + } + + /** Show or hide everything the layer draws. */ + function setShown(shown) { + if (!layerState.sets) return; + for (const set of Object.values(layerState.sets)) set.show = shown; + if (!shown) stopFollow(); + } + + /** Whether `setId` is one of this layer's sets. */ + function ownsSet(setId) { + return Boolean( + layerState.sets && + Object.values(layerState.sets).some((set) => set.id === setId), + ); } /** @@ -75,8 +112,7 @@ export function createRendering({ const selectedFillIds = []; function clearSelectionFill() { - for (const id of selectedFillIds) - layerState.dataSource?.entities.removeById(id); + if (selectedFillIds.length) layerState.sets?.fills.remove(selectedFillIds); selectedFillIds.length = 0; selectedFillKey = null; } @@ -84,68 +120,63 @@ export function createRendering({ /** Ground geometry classifies the active surface; no height/extrusion plane. */ function syncSelectionFill() { const record = - layerState.enabled && layerState.recordById.get(layerState.selectedId); + layerState.enabled && + layerState.sets && + layerState.recordById.get(layerState.selectedId); if (!record) { clearSelectionFill(); return; } - const classificationType = - layerState.viewer.scene.globe?.show === false - ? Cesium.ClassificationType.CESIUM_3D_TILE - : Cesium.ClassificationType.BOTH; - const key = `${record.id}|${renderKey(record)}|${classificationType}`; + // Tiles alone while the globe surface is hidden, as under photoreal. + const clampTo = + findGlobe(layerState.viewer)?.isGlobeVisible?.() === false + ? 'tiles' + : 'both'; + const key = `${record.id}|${renderKey(record)}|${clampTo}`; if (key === selectedFillKey) return; clearSelectionFill(); selectedFillKey = key; - const footprints = - record.footprints || (record.footprint ? [[record.footprint]] : []); - const material = new Cesium.ColorMaterialProperty( - colorFor(record).withAlpha(0.22), - ); - for (let i = 0; i < footprints.length; i++) { - const rings = footprints[i]; - const positions = (ring) => - ring.map(([lon, lat]) => Cesium.Cartesian3.fromDegrees(lon, lat)); - const fill = layerState.dataSource.entities.add({ - id: `${record.id}:selected-fill:${i}`, - polygon: { - hierarchy: new Cesium.PolygonHierarchy( - positions(rings[0]), - rings - .slice(1) - .map((ring) => new Cesium.PolygonHierarchy(positions(ring))), - ), - material, - classificationType, - }, - }); - installationMarkers.write(fill).recordId = record.id; - selectedFillIds.push(fill.id); - } + const fill = colorFor(record, 0.22); + const meta = { installationId: record.id }; + const items = footprintsOf(record).map((rings, i) => ({ + id: `${record.id}:selected-fill:${i}`, + geometry: { + kind: 'polygon', + rings: rings.map((ring) => ring.map(([lon, lat]) => ({ lon, lat }))), + }, + fill, + height: 'clampGround', + clampTo, + meta, + })); + if (items.length) layerState.sets.fills.upsert(items); + for (const item of items) selectedFillIds.push(item.id); governorRequestRender('installation-selection-fill'); } function clearRendered() { clearSelectionFill(); - if (layerState.dataSource?.entities) - layerState.dataSource.entities.removeAll(); + stopFollow(); + if (layerState.sets) { + layerState.sets.dots.clear(); + layerState.sets.selected.clear(); + layerState.sets.outlines.clear(); + } + selectedDotKey = null; layerState.renderedKeys.clear(); removeEntityContextsForLayer(LAYER_ID); } /** * Geometry identity of one rendered record. Records whose key is unchanged - * keep their Cesium entities across refreshes: ground-clamped outlines and - * classification fills rebuild asynchronously, so recreating them on every - * reload made unchanged sites blink. + * keep their drawn items across refreshes, only restyled or moved in + * place, so an unchanged site never blinks. * @param {object} record Installation record. * @returns {string} Stable key for the record's drawn geometry. */ function renderKey(record) { - const footprints = - record.footprints || (record.footprint ? [[record.footprint]] : []); - const outlines = - record.outlineLines || (record.footprint ? [record.footprint] : []); + const footprints = footprintsOf(record); + const outlines = outlinesOf(record); let points = 0; for (const rings of footprints) for (const ring of rings) points += ring.length; @@ -162,22 +193,84 @@ export function createRendering({ ].join('|'); } - function removeRecordEntities(id) { - const entities = layerState.dataSource.entities; - for (const entityId of layerState.renderedKeys.get(id)?.entityIds || []) - entities.removeById(entityId); + /** + * A site's dot. The selected site's is hidden here and drawn larger, in + * white, by the selected set (`selectedDotItem`): a clamped dot is + * restyled only by drawing it again, so its own set never changes look. + */ + function dotItem(record, rendered) { + return { + id: record.id, + pos: { + lon: record.longitude, + lat: record.latitude, + height: rendered.heightM, + }, + height: 'clampGround', + show: !record.namedArea && !rendered.selected, + pixelSize: 9, + color: colorFor(record), + outlineColor: DOT_OUTLINE, + outlineWidth: 1, + disableDepthTest: Number.POSITIVE_INFINITY, + meta: rendered.carrier, + }; + } + + /** The selected site's dot, as its own set draws it. */ + function selectedDotItem(record, rendered) { + return { + ...dotItem(record, rendered), + show: true, + pixelSize: 13, + color: SELECTED_DOT, + }; + } + + /** What the selected set draws now (site, place, height), or null. */ + let selectedDotKey = null; + + /** Draw the selected site's dot, when it has one shown. */ + function syncSelectedDot() { + const sets = layerState.sets; + if (!sets) return; + const rendered = layerState.selectedId + ? layerState.renderedKeys.get(layerState.selectedId) + : null; + const record = rendered + ? layerState.recordById.get(layerState.selectedId) + : null; + const key = + record && rendered.selected && !record.namedArea + ? [record.id, record.longitude, record.latitude, rendered.heightM].join( + '|', + ) + : null; + if (key === selectedDotKey) return; + selectedDotKey = key; + if (key) sets.selected.set([selectedDotItem(record, rendered)]); + else sets.selected.clear(); + } + + /** Stop drawing a record's dot and outlines, and following it. */ + function removeRecordItems(id, dotIds, outlineIds) { + const rendered = layerState.renderedKeys.get(id); + if (!rendered) return; + dotIds.push(id); + outlineIds.push(...rendered.outlineIds); + if (follow?.recordId === id) stopFollow(); layerState.renderedKeys.delete(id); } /** - * The records that get entities this paint: the nearest `MAX_RENDERED`, plus + * The records that get drawn this paint: the nearest `MAX_RENDERED`, plus * the selected one when it falls outside that window. * * Context navigation walks the FULL nearby cohort, which is not bounded by the - * render cap, so selecting item 701+ used to produce no entity at all — the - * camera flew, `getById` returned null, and the selection was silently dropped + * render cap, so selecting item 701+ used to produce no marker at all — the + * camera flew, the lookup returned null, and the selection was silently dropped * on the floor, leaving the Context subject stale so NEXT offered the same - * installation forever. One extra entity keeps every cohort item selectable + * installation forever. One extra marker keeps every cohort item selectable * and the cohort count honest. * @returns {Array} Records to render this paint. */ @@ -218,7 +311,7 @@ export function createRendering({ } } // Post-moveEnd debounced fetches commit after the camera settles; the - // rebuilt entities need one frame in idle mode. (perf wave 2 fix) + // rebuilt markers need one frame in idle mode. (perf wave 2 fix) governorRequestRender('installations-render'); if ( layerState.records.some((r) => @@ -237,81 +330,74 @@ export function createRendering({ const keys = new Map( records.map((record) => [record.id, renderKey(record)]), ); - const entities = layerState.dataSource.entities; - entities.suspendEvents(); + const removedDots = []; + const removedOutlines = []; for (const [id, rendered] of [...layerState.renderedKeys]) - if (keys.get(id) !== rendered.key) removeRecordEntities(id); + if (keys.get(id) !== rendered.key) + removeRecordItems(id, removedDots, removedOutlines); + const dots = []; + const outlines = []; for (const record of records) { - const color = colorFor(record); const surfaceHeightM = installationSurfaceHeightM(record); - const displayPosition = Cesium.Cartesian3.fromDegrees( + const selectedRecord = record.id === layerState.selectedId; + const retained = layerState.renderedKeys.get(record.id); + if (retained) { + // Same geometry: update the marker in place (selection, floor height). + let changed = false; + if (retained.heightM !== surfaceHeightM) { + retained.heightM = surfaceHeightM; + const displayPosition = fromDegrees( + record.longitude, + record.latitude, + surfaceHeightM, + ); + entityRecord(retained.carrier).displayPosition = () => + displayPosition; + changed = true; + } + if (retained.selected !== selectedRecord) { + retained.selected = selectedRecord; + changed = true; + } + if (changed) dots.push(dotItem(record, retained)); + continue; + } + const displayPosition = fromDegrees( record.longitude, record.latitude, surfaceHeightM, ); - const selectedRecord = record.id === layerState.selectedId; - const retained = layerState.renderedKeys.has(record.id) - ? entities.getById(record.id) - : null; - if (retained) { - // Same geometry: update the marker in place (selection, floor height). - const marker = installationMarkers.write(retained); - if (marker.heightM !== surfaceHeightM) { - marker.heightM = surfaceHeightM; - retained.position = displayPosition; - entityRecord(retained).displayPosition = () => displayPosition; - } - if (marker.selected !== selectedRecord) { - marker.selected = selectedRecord; - retained.point.pixelSize = selectedRecord ? 13 : 9; - retained.point.color = selectedRecord ? Cesium.Color.WHITE : color; - } - continue; - } - const entityIds = [record.id]; - layerState.renderedKeys.set(record.id, { + // What the dot's pick carries and the shared selection, the tracked + // card and a follow read this site through. + const carrier = { id: record.id, installationId: record.id }; + const rendered = { key: keys.get(record.id), - entityIds, - }); - const entity = layerState.dataSource.entities.add({ - id: record.id, - position: displayPosition, - point: { - show: !record.namedArea, - pixelSize: record.id === layerState.selectedId ? 13 : 9, - heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, - color: - record.id === layerState.selectedId ? Cesium.Color.WHITE : color, - outlineColor: Cesium.Color.BLACK.withAlpha(0.8), - outlineWidth: 1, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - }); - const outlines = - record.outlineLines || (record.footprint ? [record.footprint] : []); - for (let i = 0; i < outlines.length; i++) { - const outline = layerState.dataSource.entities.add({ - id: `${record.id}:outline:${i}`, - polyline: { - positions: outlines[i].map(([lon, lat]) => - Cesium.Cartesian3.fromDegrees(lon, lat), - ), - width: 2, - material: color.withAlpha(0.85), - clampToGround: true, - classificationType: Cesium.ClassificationType.BOTH, - }, - }); - installationMarkers.write(outline).recordId = record.id; - entityIds.push(outline.id); - } - Object.assign(installationMarkers.write(entity), { + outlineIds: [], + carrier, heightM: surfaceHeightM, selected: selectedRecord, - }); - entityRecord(entity).trackedId = `installations:${record.id}`; - entityRecord(entity).displayPosition = () => displayPosition; - entityRecord(entity).labelModel = { + }; + layerState.renderedKeys.set(record.id, rendered); + dots.push(dotItem(record, rendered)); + const outlineColor = colorFor(record, 0.85); + const outlineMeta = { installationId: record.id }; + const lines = outlinesOf(record); + for (let i = 0; i < lines.length; i++) { + const id = `${record.id}:outline:${i}`; + outlines.push({ + id, + positions: lines[i].map(([lon, lat]) => fromDegrees(lon, lat)), + widthPx: 2, + mode: 'draped', + clampTo: 'both', + style: { kind: 'solid', color: outlineColor }, + meta: outlineMeta, + }); + rendered.outlineIds.push(id); + } + entityRecord(carrier).trackedId = `installations:${record.id}`; + entityRecord(carrier).displayPosition = () => displayPosition; + entityRecord(carrier).labelModel = { title: installationTitle(record.name) || t('MAPPED INSTALLATION'), details: [ installationClassLabel(record.class), @@ -319,7 +405,7 @@ export function createRendering({ ], accent: COLOR_BY_CLASS[record.class] || '#9ca6b0', }; - registerEntityContext(entity, { + registerEntityContext(carrier, { id: record.id, layerId: LAYER_ID, layerName: @@ -340,19 +426,116 @@ export function createRendering({ }, }); } - entities.resumeEvents(); - const selectedEntity = layerState.selectedId - ? layerState.dataSource.entities.getById(layerState.selectedId) + const sets = layerState.sets; + if (removedDots.length) sets.dots.remove(removedDots); + if (removedOutlines.length) sets.outlines.remove(removedOutlines); + if (dots.length) sets.dots.upsert(dots); + if (outlines.length) sets.outlines.upsert(outlines); + syncSelectedDot(); + const selected = layerState.selectedId + ? layerState.renderedKeys.get(layerState.selectedId) : null; - if (selectedEntity && (claimSelection || migratedSelection)) - selectEntityContext(selectedEntity); - else if (!selectedEntity) layerState.selectedId = null; + if (selected && (claimSelection || migratedSelection)) + selectEntityContext(selected.carrier); + else if (!selected) layerState.selectedId = null; // Re-register rebuilt geometry and migrate aliases before pruning old context. removeEntityContextsForLayer(LAYER_ID, { retainIds: new Set(keys.keys()) }); parts.namedMarkers?.sync(layerState.records); syncSelectionFill(); } + /** The follow a double-click started, while the camera keeps it. */ + let follow = null; + + /** + * Follow the site whose dot is under `position`, as the default renderer + * followed the site's entity on a double-click: by the site's display + * position, framed as that renderer framed an entity it started + * following. A double-click on an outline or the selected fill, which had + * no position to follow, zooms to it at once instead. + * @param {{x: number, y: number}} position Canvas pixels. + */ + function followAt(position) { + const viewer = layerState.viewer; + if (!layerState.enabled || !layerState.sets) return; + const query = findQuery(viewer); + const hit = query?.pick(position.x, position.y); + if (!hit || !ownsSet(hit.set)) return; + const camera = findCamera(viewer); + if (!camera) return; + const recordId = hit.meta?.installationId; + const record = layerState.recordById.get(recordId); + if (!record) return; + try { + if ( + hit.set !== layerState.sets.dots.id && + hit.set !== layerState.sets.selected.id + ) { + const points = partPoints(record, hit.id); + if (!points.length) return; + // Following nothing then, as that zoom stopped any follow first. + if (camera.followed) camera.follow(null); + camera.flyToBounds(sphereFromPoints(points), { durationS: 0 }); + return; + } + const rendered = layerState.renderedKeys.get(recordId); + if (!rendered) return; + const { carrier } = rendered; + const shown = readEntityRecord(carrier)?.displayPosition?.(); + if (!shown) return; + // Centred where the dot is drawn, on the surface under it when its + // height is loaded (the cached floor may not be yet), and held there + // as the stock follow held the dot's bounding sphere. + const surface = heightsOf(viewer).now({ + lon: record.longitude, + lat: record.latitude, + }); + const at = Number.isFinite(surface) + ? fromDegrees(record.longitude, record.latitude, surface) + : shown; + const pose = camera.pose?.(); + const target = entityFollowTarget(carrier, { + key: `installations:${record.id}`, + position: () => at, + frame: 'enu', + viewFrom: followOffsetFitting({ center: at, radius: 0 }, at, { + fovy: pose?.fovy, + aspectRatio: pose?.aspectRatio, + minDistance: camera.controls?.minDistance, + maxDistance: camera.controls?.maxDistance, + }), + }); + camera.follow(target); + follow = { target, recordId }; + } catch (error) { + // A camera that cannot follow leaves the view where it is, as a + // viewer without entity tracking did on a double-click. + console.warn(`${LAYER_ID}: cannot follow`, error); + } + } + + /** The ground points of a record's outline or fill item `itemId`. */ + function partPoints(record, itemId) { + const outline = /:outline:(\d+)$/.exec(itemId); + if (outline) { + const line = outlinesOf(record)[Number(outline[1])] || []; + return line.map(([lon, lat]) => fromDegrees(lon, lat)); + } + const fill = /:selected-fill:(\d+)$/.exec(itemId); + if (fill) { + const rings = footprintsOf(record)[Number(fill[1])] || []; + return rings.flat().map(([lon, lat]) => fromDegrees(lon, lat)); + } + return []; + } + + /** Stop a follow this layer started, if the camera still keeps it. */ + function stopFollow() { + const camera = follow && findCamera(layerState.viewer); + if (follow && camera?.followed === follow.target) camera.follow(null); + follow = null; + } + /** * Second paint for floors that missed the bounded pre-render deadline. * @@ -383,7 +566,7 @@ export function createRendering({ .map((record) => ({ lat: record.latitude, lon: record.longitude })); if (!cold.length) return; warmFireAnchorFloors(cold).then(() => { - if (!layerState.enabled || !layerState.dataSource) return; + if (!layerState.enabled || !layerState.sets) return; if ( !cold.some((point) => cachedGroundFloor(point.lat, point.lon) != null) ) @@ -391,26 +574,13 @@ export function createRendering({ renderRecords(); }); } - /** - * While the layer is on, the Cesium camera reports changes at the layer's - * threshold to its own `changed` listeners too (the camera port measures - * each listener's threshold itself). - */ - function claimCameraChanges() { - claimCameraSensitivity( - layerState.viewer.camera, - LAYER_ID, - CAMERA_CHANGED_THRESHOLD, - ); - } - function releaseCameraChanges() { - releaseCameraSensitivity(layerState.viewer?.camera, LAYER_ID); - } return { attach, detach, - claimCameraChanges, - releaseCameraChanges, + setShown, + ownsSet, + followAt, + stopFollow, installationSurfaceHeightM, clearSelectionFill, syncSelectionFill, diff --git a/src/layers/installations/selection.js b/src/layers/installations/selection.js index a7b4d1185..b4f0cc061 100644 --- a/src/layers/installations/selection.js +++ b/src/layers/installations/selection.js @@ -1,6 +1,5 @@ import { inputFor } from '../../input/dispatcher.js'; import { LAYER_ID } from './policy.js'; -import { installationMarkers } from './markerState.js'; export function createSelection({ state: layerState, @@ -11,6 +10,7 @@ export function createSelection({ const { clearSelectedEntityContextForLayer } = services.context; let removeContextListeners = null; + let removeDoubleClick = null; function syncContextSelection(event) { if (!layerState.enabled) return; @@ -30,10 +30,10 @@ export function createSelection({ function selectRecord(id) { const record = layerState.recordById.get(id); - if (!record || !layerState.dataSource) return false; + if (!record || !layerState.sets) return false; layerState.selectedId = id; parts.rendering.renderRecords({ claimSelection: true }); - // renderRecords drops selectedId when the record produced no entity. + // renderRecords drops selectedId when the record produced no marker. return layerState.selectedId === id; } @@ -50,17 +50,17 @@ export function createSelection({ for (const event of events) globalThis.window?.removeEventListener?.(event, syncContextSelection); }; - layerState.clickSubscription = inputFor(viewer).onClick((event) => { + const input = inputFor(viewer); + layerState.clickSubscription = input.onClick((event) => { if (!layerState.enabled) return; - // A named marker is a draw item; site markers are still entities. + // A site's dot, outline or fill, or a named marker: each draw item + // names its installation in its `meta`. const hit = event.drawHit; - const target = event.pick?.id; const id = - (hit?.set === parts.namedMarkers?.setId + hit?.set === parts.namedMarkers?.setId || + parts.rendering.ownsSet(hit?.set) ? hit.meta?.installationId - : null) || - installationMarkers.read(target)?.recordId || - (typeof target?.id === 'string' ? target.id : null); + : null; if (id && layerState.recordById.has(id) && id !== layerState.selectedId) { selectRecord(id); } else if (layerState.selectedId) { @@ -72,6 +72,15 @@ export function createSelection({ parts.rendering.renderRecords(); } }); + // Follow a site on a double-click, as the renderer's own double-click + // followed the site's entity. + removeDoubleClick = + input.onPointer?.('dblclick', (event) => { + // The renderer's own double-click follow, off while a tool holds it + // or on a renderer without one. + if (input.stockEnabled?.('dblclickFollow') !== true) return; + parts.rendering.followAt(event.position); + }) ?? null; } return { selectRecord, @@ -79,6 +88,8 @@ export function createSelection({ destroy() { removeContextListeners?.(); removeContextListeners = null; + removeDoubleClick?.(); + removeDoubleClick = null; }, }; } diff --git a/src/layers/installations/selection.test.mjs b/src/layers/installations/selection.test.mjs index 150424fca..4ea334ce7 100644 --- a/src/layers/installations/selection.test.mjs +++ b/src/layers/installations/selection.test.mjs @@ -7,6 +7,7 @@ import { createRendering } from './rendering.js'; import { createNamedMarkers, namedPointId } from './namedMarkers.js'; import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs'; import { fakeInput } from '../../input/testDoubles.mjs'; +import { inputFor } from '../../input/dispatcher.js'; function harness(t) { const previousWindow = globalThis.window; @@ -37,9 +38,18 @@ function harness(t) { records: [record], recordById: new Map([[record.id, record]]), renderedKeys: new Map(), - dataSource: new Cesium.CustomDataSource(), viewer: { camera: { positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 1e6) }, + // The viewer's stock double-click follow, which the site follow + // stands in for. + screenSpaceEventHandler: { + getInputAction: (type) => + type === Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK + ? () => {} + : undefined, + setInputAction() {}, + removeInputAction() {}, + }, scene: { globe: { show: false }, canvas: Object.assign(new EventTarget(), { @@ -52,7 +62,7 @@ function harness(t) { }, }; let picked; - const { draw } = bindFakeCesiumScene(state.viewer); + const { draw, camera, query } = bindFakeCesiumScene(state.viewer); const input = fakeInput(state.viewer); t.mock.method( Cesium.SceneTransforms, @@ -85,6 +95,7 @@ function harness(t) { }, }; parts.rendering = createRendering(ctx); + parts.rendering.attach(state.viewer); parts.namedMarkers = createNamedMarkers(ctx); const selection = createSelection(ctx); selection.installInteraction(state.viewer); @@ -93,6 +104,7 @@ function harness(t) { state.clickSubscription(); parts.namedMarkers.destroy(); parts.rendering.clearRendered(); + parts.rendering.detach(); input.destroy(); if (previousWindow === undefined) delete globalThis.window; else globalThis.window = previousWindow; @@ -103,10 +115,7 @@ function harness(t) { assert.equal(state.selectedId, selected ? record.id : null); assert.equal(labels[0].selected, selected); assert.equal(labels[0].variant, selected ? 'selected' : 'card'); - assert.equal( - state.dataSource.entities.values.filter((e) => e.polygon).length, - selected ? 1 : 0, - ); + assert.equal(state.sets.fills.size(), selected ? 1 : 0); }; assert.equal(selection.selectRecord(record.id), true); assertSelected(true); @@ -115,6 +124,9 @@ function harness(t) { selection, assertSelected, draw, + camera, + query, + input, parts, /** Click on what `pick` names, as the scene would pick it. */ click(value) { @@ -186,3 +198,142 @@ test('a click on a named marker point selects its site; again releases it', (t) h.click({ id: { set: 'other:1', id: item.id, meta: item.meta } }); h.assertSelected(false); }); + +test('a click on a site dot or its outline selects the site; another set does not', (t) => { + const h = harness(t); + h.state.selectedId = null; + context.clearSelectedEntityContextForLayer('military-installations'); + h.state.records[0].namedArea = false; + h.state.records[0].outlineLines = [ + [ + [0, 0], + [0.01, 0], + ], + ]; + h.parts.rendering.renderRecords(); + const selectedNow = () => h.state.selectedId === 'base'; + assert.equal(selectedNow(), false); + const dots = h.state.sets.dots; + const dot = h.draw.set(dots.id).items.get('base'); + assert.equal(dot.show, true); + assert.equal(dot.height, 'clampGround'); + assert.equal(dot.pixelSize, 9); + assert.equal(dot.disableDepthTest, Infinity); + // The dot carries the site's shared context record, for point-and-ask. + assert.equal(context.getContextStore().entities.get('base').entity, dot.meta); + h.click({ id: { set: dots.id, id: 'base', meta: dot.meta } }); + assert.equal(selectedNow(), true); + assert.equal(context.getSelectedEntityContext().id, 'base'); + // Drawn larger and white by the selected set, hidden in its own. + assert.equal(h.draw.set(dots.id).items.get('base').show, false); + assert.equal(h.draw.set(dots.id).items.get('base').pixelSize, 9); + const selectedSet = h.draw.set(h.state.sets.selected.id); + const selected = selectedSet.items.get('base'); + assert.equal(selected.pixelSize, 13); + assert.deepEqual(selected.color, [1, 1, 1, 1]); + assert.equal(selected.meta, dot.meta); + // A click on the selected dot clears it. + h.click({ id: { set: selectedSet.spec.id, id: 'base', meta: dot.meta } }); + assert.equal(selectedNow(), false); + assert.equal(selectedSet.items.size, 0); + assert.equal(h.draw.set(dots.id).items.get('base').show, true); + const outlines = h.state.sets.outlines; + const outline = h.draw.set(outlines.id).items.get('base:outline:0'); + assert.equal(outline.mode, 'draped'); + assert.equal(outline.clampTo, 'both'); + h.click({ id: { set: outlines.id, id: outline.id, meta: outline.meta } }); + assert.equal(selectedNow(), true); + h.click({ id: { set: 'other:1', id: outline.id, meta: outline.meta } }); + assert.equal(selectedNow(), false); +}); + +test('a double-click follows a site dot where it is drawn and zooms to its outline', (t) => { + const h = harness(t); + h.state.records[0].namedArea = false; + h.state.records[0].outlineLines = [ + [ + [0, 0], + [0.01, 0], + ], + ]; + h.parts.rendering.renderRecords({ claimSelection: true }); + h.state.enabled = true; + const follows = []; + const flights = []; + let followed = null; + Object.assign(h.camera, { + follow(target) { + follows.push(target); + followed = target; + }, + flyToBounds(sphere, options) { + flights.push({ sphere, options }); + }, + controls: { minDistance: 1, maxDistance: 1e9 }, + }); + Object.defineProperty(h.camera, 'followed', { get: () => followed }); + let hit = null; + h.query.pick = () => hit; + const dots = h.state.sets.dots; + const dot = h.draw.set(dots.id).items.get('base'); + h.input.dblclick({ x: 640, y: 400 }); + assert.equal(follows.length, 0, 'nothing of the layer under it'); + hit = { set: dots.id, id: 'base', meta: dot.meta, surface: false }; + h.input.dblclick({ x: 640, y: 400 }); + const target = follows.at(-1); + assert.equal(target.key, 'installations:base'); + assert.equal(target.frame, 'enu'); + // The tracked card reads the site through the target's entity. + assert.equal(target.entity, dot.meta); + assert.equal(target.labelModel.title, 'Base'); + const at = target.position(0); + assert.ok(Math.abs(at.x - 6378137) < 1e-6 && Math.abs(at.y) < 1e-6); + // 100 m from it, north up, pitched down 45 degrees. + const range = Math.hypot( + target.viewFrom.x, + target.viewFrom.y, + target.viewFrom.z, + ); + assert.ok(Math.abs(range - 100) < 1e-6); + assert.ok(Math.abs(target.viewFrom.x) < 1e-9); + assert.ok(Math.abs(target.viewFrom.y + target.viewFrom.z) < 1e-6); + // On the surface under the dot once its height is loaded, before the + // cached floor has it, and held there. + h.query.sampleHeightNow = () => 2400; + h.input.dblclick({ x: 640, y: 400 }); + const raised = follows.at(-1).position(0); + assert.ok(Math.abs(raised.x - 6380537) < 1e-6); + h.query.sampleHeightNow = () => null; + h.input.dblclick({ x: 640, y: 400 }); + assert.ok(Math.abs(follows.at(-1).position(0).x - 6378137) < 1e-6); + const outlines = h.state.sets.outlines; + hit = { + set: outlines.id, + id: 'base:outline:0', + meta: { installationId: 'base' }, + surface: false, + }; + h.input.dblclick({ x: 640, y: 400 }); + assert.equal(followed, null, 'a zoom stops the follow'); + assert.equal(flights.length, 1); + assert.equal(flights[0].options.durationS, 0); + // The follow stops when the layer hides. + hit = { set: dots.id, id: 'base', meta: dot.meta, surface: false }; + h.input.dblclick({ x: 640, y: 400 }); + assert.equal(followed?.key, 'installations:base'); + h.parts.rendering.setShown(false); + assert.equal(followed, null); + // Another layer's item under the cursor neither follows nor zooms. + h.parts.rendering.setShown(true); + const before = follows.length; + hit = { set: 'another:1', id: 'base', meta: dot.meta, surface: false }; + h.input.dblclick({ x: 640, y: 400 }); + assert.equal(follows.length, before); + assert.equal(flights.length, 1); + // With the stock double-click follow turned off, nothing follows. + hit = { set: dots.id, id: 'base', meta: dot.meta, surface: false }; + const release = inputFor(h.state.viewer).suppressStockClicks(); + h.input.dblclick({ x: 640, y: 400 }); + assert.equal(follows.length, before); + release(); +}); diff --git a/src/layers/installations/selectionFill.test.mjs b/src/layers/installations/selectionFill.test.mjs index 5f1a3f5c7..984253687 100644 --- a/src/layers/installations/selectionFill.test.mjs +++ b/src/layers/installations/selectionFill.test.mjs @@ -1,54 +1,59 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import * as C from 'cesium'; import { createRendering } from './rendering.js'; import { createLifecycle } from './lifecycle.js'; -import { installationMarkers } from './markerState.js'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; function harness() { const ring = [[-97, 30], [-96.99, 30], [-96.99, 30.01], [-97, 30]]; const record = { id: 'base', latitude: 30, longitude: -97, name: 'Base', class: 'base', footprints: [[ring, ring.map(([x,y]) => [x+0.001,y+0.001])], [ring]] }; - const state = { enabled: true, selectedId: 'base', records: [record], recordById: new Map([['base', record]]), renderedKeys: new Map(), dataSource: new C.CustomDataSource(), viewer: { scene: { globe: { show: false } }, camera: {} } }; + let globeVisible = false; + const viewer = { scene: {}, camera: {} }; + const { draw } = bindFakeDraw(viewer, { globe: { isGlobeVisible: () => globeVisible } }); + const state = { enabled: true, selectedId: 'base', records: [record], recordById: new Map([['base', record]]), renderedKeys: new Map(), viewer }; let listener, removed = 0; const noop = () => {}; const services = { ground: { floorAltitudeM: () => 0, cachedGroundFloor: () => 0 }, anchors: {}, render: { governorRequestRender: noop }, context: { removeEntityContextsForLayer: noop, clearSelectedEntityContextForLayer: noop }, picking: { registerPickOwner: noop, unregisterPickOwner: noop }, maps: { subscribeMapStack(cb) { listener = cb; return () => { listener = null; removed++; }; } } }; const parts = { model: { colorFor: () => [1, 165 / 255, 0, 1], installationSourceLabel: () => 'OpenStreetMap' }, viewport: { clearUnavailableRetry: noop }, ingestion: { setInstallationStatus: noop } }; parts.rendering = createRendering({ state, services, parts }); + parts.rendering.attach(viewer); const lifecycle = createLifecycle({ state, services, parts, source: {} }).methods; - return { state, record, parts, lifecycle, changeSurface: () => listener(), removed: () => removed }; + const fills = () => [...draw.set(state.sets.fills.id).items.values()]; + return { state, record, parts, lifecycle, draw, fills, showGlobe: (shown) => { globeVisible = shown; }, changeSurface: () => listener(), removed: () => removed }; } -test('selected multipart footprints classify Google tiles with one constant translucent material and holes', () => { +test('selected multipart footprints drape on Google tiles with one constant translucent colour and holes', () => { const h = harness(), render = h.parts.rendering; render.syncSelectionFill(); - const fills = h.state.dataSource.entities.values.slice(); + const fills = h.fills(); assert.equal(fills.length, 2); for (const fill of fills) { - assert.equal(installationMarkers.read(fill)?.recordId, 'base'); - assert.equal(fill.polygon.classificationType.getValue(), C.ClassificationType.CESIUM_3D_TILE); - assert.equal(fill.polygon.height, undefined); - assert.equal(fill.polygon.extrudedHeight, undefined); - assert.equal(fill.polygon.material.isConstant, true); - assert.equal(fill.polygon.material.color.getValue().alpha, 0.22); + assert.equal(fill.meta.installationId, 'base'); + assert.equal(fill.clampTo, 'tiles'); + assert.equal(fill.height, 'clampGround'); + assert.equal(fill.extrudeHeight, undefined); + assert.deepEqual(fill.fill, [1, 165 / 255, 0, 0.22]); } - assert.equal(fills[0].polygon.hierarchy.getValue().holes.length, 1); - assert.equal(fills[0].polygon.material, fills[1].polygon.material); + assert.equal(fills[0].geometry.rings.length, 2, 'the hole is a second ring'); + assert.equal(fills[0].fill, fills[1].fill); + const writes = h.draw.set(h.state.sets.fills.id).writes; for (let i = 0; i < 100; i++) render.syncSelectionFill(); - assert.deepEqual(h.state.dataSource.entities.values, fills, 'repaints retain ground geometry'); + assert.equal(h.draw.set(h.state.sets.fills.id).writes, writes, 'repaints retain ground geometry'); + assert.deepEqual(h.fills(), fills); h.state.selectedId = null; render.syncSelectionFill(); - assert.equal(h.state.dataSource.entities.values.length, 0); + assert.equal(h.fills().length, 0); }); test('surface changes reclassify selected geometry and disable tears down fills and subscription', () => { const h = harness(); h.lifecycle.enable(); h.parts.rendering.syncSelectionFill(); - h.state.viewer.scene.globe.show = true; h.changeSurface(); - assert.ok(h.state.dataSource.entities.values.every(e => e.polygon.classificationType.getValue() === C.ClassificationType.BOTH)); + h.showGlobe(true); h.changeSurface(); + assert.ok(h.fills().every((fill) => fill.clampTo === 'both')); h.lifecycle.disable(); - assert.equal(h.state.dataSource.entities.values.length, 0); + assert.equal(h.fills().length, 0); assert.equal(h.removed(), 1); h.lifecycle.enable(); h.parts.rendering.syncSelectionFill(); - assert.equal(h.state.dataSource.entities.values.length, 0, 'reenabling cannot revive a stale selection'); + assert.equal(h.fills().length, 0, 'reenabling cannot revive a stale selection'); h.lifecycle.disable(); }); @@ -61,15 +66,16 @@ test('geometry rebuild and canonical alias migration preserve shared selection b const h = harness(); const services = { context, render: { governorRequestRender() {} }, ground: { floorAltitudeM: () => 0, cachedGroundFloor: () => 0 }, anchors: {} }; const rendering = createRendering({ state: h.state, services, parts: h.parts }); + rendering.attach(h.state.viewer); const cleared = []; window.addEventListener('gev:entity-selection-cleared', e => { cleared.push(e.detail); h.state.selectedId = null; }); rendering.renderRecords({ claimSelection: true }); - const oldEntity = context.getSelectedEntityContext().entity; + const oldCarrier = context.getSelectedEntityContext().entity; h.record.latitude += 0.001; rendering.renderRecords(); assert.equal(h.state.selectedId, 'base'); assert.equal(context.getSelectedEntityContext().id, 'base'); - assert.notEqual(context.getSelectedEntityContext().entity, oldEntity); + assert.notEqual(context.getSelectedEntityContext().entity, oldCarrier); const replacement = { ...h.record, id: 'canonical', aliasIds: ['base'] }; h.state.records = [replacement]; h.state.recordById = new Map([['canonical', replacement]]); rendering.renderRecords(); diff --git a/src/layers/installations/state.js b/src/layers/installations/state.js index 1dbca044f..244235494 100644 --- a/src/layers/installations/state.js +++ b/src/layers/installations/state.js @@ -3,7 +3,8 @@ export function createState({ services }) { Object.assign(state, { viewer: null, - dataSource: null, + /** The layer's draw sets (`dots`, `outlines`, `fills`) while attached. */ + sets: null, enabled: false, records: [], recordById: new Map(), @@ -32,7 +33,10 @@ export function createState({ services }) { contextPosition: null, /** Coverage of the last successful load: viewport, or radius around a subject. */ coverage: { kind: 'viewport' }, - /** Per-record geometry keys of the rendered entities, for in-place updates. */ + /** + * What each drawn record last drew: its geometry key, outline item ids, + * context carrier, height and selection, for in-place updates. + */ renderedKeys: new Map(), }); return state; diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index afead0d81..cf8a4d496 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -1795,6 +1795,100 @@ test('the installations layer draws its named markers as outlined point primitiv assert.equal(scene.added.includes(host), false); }); +test('the installations layer draws its site dots, outlines and selected dot on a viewer of its own', async () => { + const { createRendering } = + await import('../../layers/installations/rendering.js'); + const scene = fakeScene(); + const viewer = { scene }; + const record = (id, lon) => ({ + id, + name: `Site ${id}`, + class: 'base', + latitude: 30, + longitude: lon, + namedArea: false, + outlineLines: [ + [ + [lon, 30], + [lon + 0.01, 30], + ], + ], + }); + const records = [record('a', -97), record('b', -98)]; + const state = { + viewer, + enabled: true, + selectedId: null, + records, + recordById: new Map(records.map((r) => [r.id, r])), + renderedKeys: new Map(), + }; + const noop = () => {}; + const rendering = createRendering({ + state, + services: { + ground: { floorAltitudeM: () => 0, cachedGroundFloor: () => 0 }, + anchors: {}, + render: { governorRequestRender: noop }, + context: { + registerEntityContext: noop, + removeEntityContextsForLayer: noop, + selectEntityContext: noop, + getSelectedEntityContext: () => + state.selectedId ? { id: state.selectedId } : null, + clearSelectedEntityContextForLayer: noop, + }, + }, + parts: { + model: { + colorFor: (r, alpha = 1) => [1, 165 / 255, 0, alpha], + installationSourceLabel: () => 'OpenStreetMap', + }, + }, + }); + rendering.attach(viewer); + rendering.renderRecords(); + const billboards = (setId) => { + const out = []; + const visit = (node) => { + for (let i = 0; i < (node?.length ?? 0); i += 1) { + const child = node.get(i); + if (child?.id?.set === setId) out.push(child); + else if (typeof child?.get === 'function') visit(child); + } + }; + for (const host of scene.added) + if (host.id?.set === setId) out.push(host); + else visit(host); + return out; + }; + const dotsId = state.sets.dots.id; + const dots = billboards(dotsId); + assert.equal(dots.length, 2); + assert.ok(dots.every((dot) => dot instanceof Cesium.Billboard)); + assert.ok( + dots.every( + (dot) => dot.heightReference === Cesium.HeightReference.CLAMP_TO_GROUND, + ), + ); + assert.ok(dots.every((dot) => dot.id.meta?.installationId)); + // Selecting a site hides its dot where it is and draws the selected one + // in its own set: no other dot is drawn again. + state.selectedId = 'b'; + rendering.renderRecords(); + const after = billboards(dotsId); + assert.equal(after.length, 2); + assert.ok(after.every((dot, i) => dot === dots[i]), 'the same billboards'); + assert.equal(after.find((dot) => dot.id.id === 'b').show, false); + assert.equal(after.find((dot) => dot.id.id === 'a').show, true); + const [selected] = billboards(state.sets.selected.id); + assert.ok(selected instanceof Cesium.Billboard); + assert.equal(selected.id.id, 'b'); + assert.equal(selected.id.meta, dots.find((dot) => dot.id.id === 'b').id.meta); + rendering.detach(); + assert.equal(scene.added.length, 0, 'gone with the layer'); +}); + test('the ALPR layer draws its badges as icons that follow the ground, restyled in place', async () => { const { alprMarkers, createAlprMarkerSet } = await import('../../layers/alpr/markerState.js'); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index cddeacc54..90d76ce92 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -11,7 +11,6 @@ "src/input/dispatcher.js", "src/input/sensorPick.js", "src/layers/ghostMaps/index.js", - "src/layers/installations/rendering.js", "src/layers/launches/launchPad.js", "src/layers/launches/orbitRendering.js", "src/layers/launches/rendering.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index e277cd85a..c51098039 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -95,6 +95,9 @@ const DRAW_FROM_CALLER = new Set([ // Its station dots, clusters and selected marker draw through `drawOf`; // it clusters them on screen through the camera and query ports. './layers/radio', + // Its site dots, outlines and selected fill draw through `drawOf`; it + // follows a site and reads the globe through the camera and globe ports. + './layers/installations', // Its data packs draw through `drawOf`; its flights ask `cameraOf`, which // throws until then too. './scenes', diff --git a/src/sources/militaryTileGeometry.test.mjs b/src/sources/militaryTileGeometry.test.mjs index 32160a082..4907f4da5 100644 --- a/src/sources/militaryTileGeometry.test.mjs +++ b/src/sources/militaryTileGeometry.test.mjs @@ -186,9 +186,11 @@ test('distinct named bases separated by one seam quantization step retain separa }); test('named A+B to B to A+B preserves canonical identity, parent title and selection', async () => { - const C = await import('cesium'); const { createRendering } = await import('../layers/installations/rendering.js'); + const { bindFakeDraw } = await import('../testSupport/fakeDrawPort.mjs'); + const viewer = {}; + const { draw } = bindFakeDraw(viewer); const aliases = new Map(); const named = (n, footprint, areaM2) => record(String(n * 10 + 2), footprint, { @@ -213,7 +215,7 @@ test('named A+B to B to A+B preserves canonical identity, parent title and selec recordById: new Map(), selectedId: selected.id, renderedKeys: new Map(), - dataSource: new C.CustomDataSource(), + viewer, }; const rendering = createRendering({ state, @@ -238,6 +240,10 @@ test('named A+B to B to A+B preserves canonical identity, parent title and selec anchors: {}, }, }); + rendering.attach(viewer); + /** Whether the selected site's dot is drawn. */ + const selectedDrawn = () => + draw.set(state.sets.dots.id).items.has(state.selectedId); for (const members of [[a, b], [b], [a, b]]) { state.records = mergeMilitaryFragments(members, aliases); state.recordById = new Map(state.records.map((r) => [r.id, r])); @@ -246,7 +252,7 @@ test('named A+B to B to A+B preserves canonical identity, parent title and selec assert.deepEqual(state.records[0].memberNames, ['Site 2']); rendering.renderRecords(); assert.equal(state.selectedId, 'osm:military:w1'); - assert.ok(state.dataSource.entities.getById(state.selectedId)); + assert.ok(selectedDrawn()); } const [detail] = mergeMilitaryFragments([{ ...b, tileZoom: 12 }], aliases); assert.equal(detail.id, 'osm:military:w2'); @@ -258,9 +264,11 @@ test('named A+B to B to A+B preserves canonical identity, parent title and selec }); test('cold names reconcile selection through enrichment, identical groups at another zoom and wide-point handoff', async () => { - const C = await import('cesium'); const { createRendering } = await import('../layers/installations/rendering.js'); + const { bindFakeDraw } = await import('../testSupport/fakeDrawPort.mjs'); + const viewer = {}; + const { draw } = bindFakeDraw(viewer); const { retainNamedHandoff } = await import('../layers/installations/ingestion.js'); const aliases = new Map(); @@ -292,7 +300,7 @@ test('cold names reconcile selection through enrichment, identical groups at ano recordById: new Map(), selectedId: null, renderedKeys: new Map(), - dataSource: new C.CustomDataSource(), + viewer, }; const rendering = createRendering({ state, @@ -321,13 +329,17 @@ test('cold names reconcile selection through enrichment, identical groups at ano anchors: {}, }, }); + rendering.attach(viewer); + /** Whether the selected site's dot is drawn. */ + const selectedDrawn = () => + draw.set(state.sets.dots.id).items.has(state.selectedId); const publish = (records, claimSelection = false) => { state.records = records; state.recordById = new Map(records.map((r) => [r.id, r])); rendering.renderRecords({ claimSelection }); assert.equal(state.selectedId, records[0].id); assert.equal(selected.id, records[0].id); - assert.ok(state.dataSource.entities.getById(state.selectedId)); + assert.ok(selectedDrawn()); assert.ok(contexts.has(selected.id)); }; const cold = mergeMilitaryFragments(unnamed, aliases);