diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 86e21ccad..c4a903891 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2569,12 +2569,15 @@ "src/geo/vector.js", "src/render/cesium/internals.js", "src/render/cesium/common.js", - "src/layers/submarineCables/pickState.js", + "src/layers/submarineCables/pin.js", "src/data/entityRecords.js", "src/layers/submarineCables/lifecycle.js", "src/layers/submarineCables/overlay.js", "src/layers/submarineCables/policy.js", "src/layers/submarineCables/rendering.js", + "src/geo/rhumb.js", + "src/render/color.js", + "src/geo/horizon.js", "src/layers/submarineCables/state.js", "src/layers/submarineCables/surface.js", "src/data/inputOwnership.js", @@ -3212,11 +3215,13 @@ "src/layers/submarineCables/index.js", "src/layers/submarineCables/ingestion.js", "src/layers/submarineCables/interaction.js", - "src/layers/submarineCables/pickState.js", + "src/layers/submarineCables/pin.js", "src/layers/submarineCables/lifecycle.js", "src/layers/submarineCables/overlay.js", "src/layers/submarineCables/policy.js", "src/layers/submarineCables/rendering.js", + "src/geo/rhumb.js", + "src/geo/horizon.js", "src/layers/submarineCables/state.js", "src/layers/submarineCables/surface.js", "src/layers/traffic/animation.js", @@ -4150,11 +4155,13 @@ "src/layers/submarineCables/index.js", "src/layers/submarineCables/ingestion.js", "src/layers/submarineCables/interaction.js", - "src/layers/submarineCables/pickState.js", + "src/layers/submarineCables/pin.js", "src/layers/submarineCables/lifecycle.js", "src/layers/submarineCables/overlay.js", "src/layers/submarineCables/policy.js", "src/layers/submarineCables/rendering.js", + "src/geo/rhumb.js", + "src/geo/horizon.js", "src/layers/submarineCables/state.js", "src/layers/submarineCables/surface.js", "src/layers/traffic/animation.js", @@ -5783,6 +5790,7 @@ "modules": [ "src/render/contract/index.js", "src/render/stub/index.js", + "src/geo/horizon.js", "src/render/conformance/index.js", "src/render/conformance/scenes.js", "src/render/conformance/cameraScripts.js", @@ -5799,6 +5807,7 @@ "src/geo/quaternion.js", "src/render/stub/motion.js", "src/render/stub/camera.js", + "src/geo/geodesic.js", "src/render/camera/events.js", "src/render/stub/geodesic.js", "src/render/stub/viewRectangle.js", diff --git a/src/data/telegeographySubmarineCables.js b/src/data/telegeographySubmarineCables.js index 6bee7c56d..d5d1cc086 100644 --- a/src/data/telegeographySubmarineCables.js +++ b/src/data/telegeographySubmarineCables.js @@ -24,7 +24,6 @@ export { createCableOverlayEntry, cableClassificationTypeForStack, cableClassificationTypeForScene, - applyTranslucentMarkerBlend, createCableReferenceSweepGate, updateCableReferenceStem, } from '../layers/submarineCables/index.js'; diff --git a/src/data/telegeographySubmarineCables.test.mjs b/src/data/telegeographySubmarineCables.test.mjs index 673041976..949d5a233 100644 --- a/src/data/telegeographySubmarineCables.test.mjs +++ b/src/data/telegeographySubmarineCables.test.mjs @@ -3,6 +3,9 @@ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import * as Cesium from 'cesium'; import { MAP_STACKS } from '../mapStackController.js'; +import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; +import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs'; import { CABLE_LABEL_DEPTH_DECISION, CABLE_OVERLAY_COLLISION_CAPACITY, @@ -11,7 +14,6 @@ import { CABLE_STEM_TIP_EPSILON_M, CABLE_SWEEP_MOTION_EPSILON_M, CABLE_SWEEP_MOTION_PROBE_INTERVAL_MS, - applyTranslucentMarkerBlend, cableClassificationTypeForScene, cableClassificationTypeForStack, cableReferencePriority, @@ -22,11 +24,10 @@ import { selectCableReferenceLabelWinners, updateCableReferenceStem, } from './telegeographySubmarineCables.js'; -import { cablePicks } from '../layers/submarineCables/pickState.js'; test('cable reference winners remain nearest-first and hard-capped', () => { const records = Array.from({ length: 300 }, (_, index) => ({ - entity: { id: `reference-${index}` }, + id: `reference-${index}`, label: `Reference ${index}`, visible: true, distanceM: 1000 + index, @@ -55,7 +56,7 @@ test('cable reference winners remain nearest-first and hard-capped', () => { }); test('cable overlay entries satisfy the shared presentation contract', () => { - const tip = Cesium.Cartesian3.fromDegrees(-40, 35, 2500); + const tip = fromDegrees(-40, 35, 2500); const record = { id: 'cable-reference-0-atlantic-1', kind: 'cable', @@ -79,7 +80,7 @@ test('cable overlay entries satisfy the shared presentation contract', () => { assert.equal( entry.interactive, false, - 'point/stem/line picking remains Cesium-native', + 'point/stem/line picking stays with the renderer', ); assert.equal(entry.maxDistance, 9_000_000); assert.equal(entry.distanceFadeStartRatio, 0.7); @@ -182,45 +183,24 @@ test('cable overlay publisher owns the production show/publish/hide lifecycle', ]); }); -test('cable ground lines classify against exactly the active surface on every stack', () => { - // Photorealistic tiles render with the globe hidden — 3D-tile pass only. - assert.equal( - cableClassificationTypeForStack('photoreal'), - Cesium.ClassificationType.CESIUM_3D_TILE, - ); - // Every globe stack renders imagery on the shown globe — terrain pass only. +test('cable ground lines drape on exactly the active surface on every stack', () => { + // Photorealistic tiles render with the globe hidden — the tiles only. + assert.equal(cableClassificationTypeForStack('photoreal'), 'tiles'); + // Every globe stack renders imagery on the shown globe — terrain only. for (const stackId of ['bing-aerial', 'bing-labels', 'esri-imagery', 'osm']) { assert.equal( cableClassificationTypeForStack(stackId), - Cesium.ClassificationType.TERRAIN, - `${stackId} must classify against terrain so cables stay visible there`, + 'terrain', + `${stackId} must drape on terrain so cables stay visible there`, ); } - // Unknown stack → BOTH: visible on every surface, the shipped fallback. + // Unknown stack → both: visible on every surface, the shipped fallback. // A TRUTHY unknown id must reach it too — "not photoreal" is not the same - // claim as "renders on the globe", and asserting TERRAIN for an id this + // claim as "renders on the globe", and asserting terrain for an id this // module has never heard of would hide the cables on a future 3D-tile // stack instead of degrading to the documented safe behavior. - assert.equal( - cableClassificationTypeForStack('some-future-stack'), - Cesium.ClassificationType.BOTH, - ); - assert.equal( - cableClassificationTypeForStack('photoreal-v2'), - Cesium.ClassificationType.BOTH, - ); - assert.equal( - cableClassificationTypeForStack(''), - Cesium.ClassificationType.BOTH, - ); - assert.equal( - cableClassificationTypeForStack(undefined), - Cesium.ClassificationType.BOTH, - ); - assert.equal( - cableClassificationTypeForStack(null), - Cesium.ClassificationType.BOTH, - ); + for (const id of ['some-future-stack', 'photoreal-v2', '', undefined, null]) + assert.equal(cableClassificationTypeForStack(id), 'both'); // Every id that actually ships must be a KNOWN id: a stack added to // MAP_STACKS without a mapping here silently loses its halved command set, @@ -228,8 +208,8 @@ test('cable ground lines classify against exactly the active surface on every st for (const stack of MAP_STACKS) { assert.notEqual( cableClassificationTypeForStack(stack.id), - Cesium.ClassificationType.BOTH, - `MAP_STACKS id '${stack.id}' has no cable classification mapping`, + 'both', + `MAP_STACKS id '${stack.id}' has no cable surface mapping`, ); } @@ -237,185 +217,13 @@ test('cable ground lines classify against exactly the active surface on every st // state exactly like the height-datum listeners: photoreal ⇔ globe hidden. assert.equal( cableClassificationTypeForScene({ globe: { show: false } }), - Cesium.ClassificationType.CESIUM_3D_TILE, + 'tiles', ); assert.equal( cableClassificationTypeForScene({ globe: { show: true } }), - Cesium.ClassificationType.TERRAIN, + 'terrain', ); - assert.equal( - cableClassificationTypeForScene(null), - Cesium.ClassificationType.BOTH, - ); -}); - -test('a map-stack change re-classifies every cable line once, and destroy detaches the listener', async () => { - const listeners = new Map(); - const eventTarget = { - addEventListener: (name, fn) => listeners.set(name, fn), - removeEventListener: (name, fn) => { - if (listeners.get(name) === fn) listeners.delete(name); - }, - }; - const env = await createRealCableLayerHarness({ - mapStackEventTarget: eventTarget, - }); - const cableSource = env.dataSources.find((ds) => - /Submarine Cables/.test(ds.name || ''), - ); - const classificationOf = (entity) => - entity.polyline.classificationType.getValue(); - - // The harness scene has no globe → BOTH at init (safe unknown fallback). - const cableEntity = cableSource.entities.values[0]; - assert.equal(classificationOf(cableEntity), Cesium.ClassificationType.BOTH); - const listener = listeners.get('gev:map-stack-changed'); - assert.equal( - typeof listener, - 'function', - 'init must subscribe to the stack event', - ); - - listener({ detail: { activeId: 'photoreal', status: 'ready' } }); - assert.equal( - classificationOf(cableEntity), - Cesium.ClassificationType.CESIUM_3D_TILE, - ); - - listener({ detail: { activeId: 'osm', status: 'ready' } }); - assert.equal( - classificationOf(cableEntity), - Cesium.ClassificationType.TERRAIN, - ); - - env.layer.destroy(env.viewer); - assert.equal( - listeners.has('gev:map-stack-changed'), - false, - 'destroy must detach the stack listener', - ); -}); - -test('marker collections blend in a single translucent pass behind a loud shape invariant', async () => { - // Helper contract on a REAL Cesium cluster shape. - const ds = new Cesium.CustomDataSource('blend-probe'); - let result = applyTranslucentMarkerBlend(ds); - assert.deepEqual( - result, - { applied: 0, pending: 2, invariantFailed: false }, - 'pre-visualizer clusters are pending, never a shape failure', - ); - - ds.clustering._billboardCollection = new Cesium.BillboardCollection(); - ds.clustering._pointCollection = new Cesium.PointPrimitiveCollection(); - result = applyTranslucentMarkerBlend(ds); - assert.deepEqual(result, { applied: 2, pending: 0, invariantFailed: false }); - assert.equal( - ds.clustering._billboardCollection.blendOption, - Cesium.BlendOption.TRANSLUCENT, - ); - assert.equal( - ds.clustering._pointCollection.blendOption, - Cesium.BlendOption.TRANSLUCENT, - ); - - // Shape drift fails LOUDLY-detectably instead of applying blindly: a - // renamed field or a foreign object type must never be touched. - assert.equal( - applyTranslucentMarkerBlend({ clustering: {} }).invariantFailed, - true, - 'missing private fields mean Cesium changed shape', - ); - const wrongType = new Cesium.CustomDataSource('wrong-type'); - wrongType.clustering._billboardCollection = { blendOption: 0 }; - const wrongResult = applyTranslucentMarkerBlend(wrongType); - assert.equal(wrongResult.invariantFailed, true); - assert.equal( - wrongType.clustering._billboardCollection.blendOption, - 0, - 'foreign objects are left untouched', - ); - assert.equal(applyTranslucentMarkerBlend(null).invariantFailed, true); - - // ATOMICITY: a shape failure on the SECOND collection must not leave the - // FIRST one already forced. Validation of every field/type completes before - // the first assignment, so a failed probe applies nothing at all — that is - // what "leaves Cesium's default blend untouched" has to mean. - const partial = new Cesium.CustomDataSource('partial-shape'); - partial.clustering._billboardCollection = new Cesium.BillboardCollection(); - partial.clustering._pointCollection = { blendOption: 0 }; // renamed/reshaped - const partialResult = applyTranslucentMarkerBlend(partial); - assert.equal(partialResult.invariantFailed, true); - assert.equal( - partialResult.applied, - 0, - 'a failed probe reports zero applications', - ); - assert.equal( - partial.clustering._billboardCollection.blendOption, - Cesium.BlendOption.OPAQUE_AND_TRANSLUCENT, - "the valid first collection keeps Cesium's default blend when the second fails", - ); - assert.equal( - partial.clustering._pointCollection.blendOption, - 0, - 'the malformed collection is never touched', - ); - - // Real-layer wiring: once the visualizers have created the collections, - // the next sweep applies the single-pass blend to both marker sources. - const env = await createRealCableLayerHarness(); - env.raiseSweep(); - const landingSource = env.dataSources.find((source) => - /Landing Points/.test(source.name || ''), - ); - const referenceSource = env.dataSources.find((source) => - /References/.test(source.name || ''), - ); - landingSource.clustering._billboardCollection = - new Cesium.BillboardCollection(); - landingSource.clustering._pointCollection = - new Cesium.PointPrimitiveCollection(); - referenceSource.clustering._billboardCollection = - new Cesium.BillboardCollection(); - referenceSource.clustering._pointCollection = - new Cesium.PointPrimitiveCollection(); - for (const fn of env.listeners.moveEnd) fn(); - env.raiseSweep(); - assert.equal( - landingSource.clustering._billboardCollection.blendOption, - Cesium.BlendOption.TRANSLUCENT, - 'landing billboards blend in one pass after the sweep', - ); - assert.equal( - referenceSource.clustering._pointCollection.blendOption, - Cesium.BlendOption.TRANSLUCENT, - 'reference points blend in one pass after the sweep', - ); - env.layer.destroy(env.viewer); - - // The same atomicity holds ACROSS the two marker sources: the layer probes - // both before committing either, so a reshaped reference source can never - // leave the landing source already forced to TRANSLUCENT. - const failEnv = await createRealCableLayerHarness(); - const failLanding = failEnv.dataSources.find((source) => - /Landing Points/.test(source.name || ''), - ); - const failReference = failEnv.dataSources.find((source) => - /References/.test(source.name || ''), - ); - failLanding.clustering._billboardCollection = - new Cesium.BillboardCollection(); - failLanding.clustering._pointCollection = - new Cesium.PointPrimitiveCollection(); - delete failReference.clustering._pointCollection; // Cesium reshaped - failEnv.raiseSweep(); - assert.equal( - failLanding.clustering._billboardCollection.blendOption, - Cesium.BlendOption.OPAQUE_AND_TRANSLUCENT, - 'a reference-source shape failure leaves the landing source on the default blend', - ); - failEnv.layer.destroy(failEnv.viewer); + assert.equal(cableClassificationTypeForScene(null), 'both'); }); test('cable reference sweep gate is dirty-only — no timer path', () => { @@ -533,45 +341,15 @@ test('the sweep gate falls back to motion probes for cameras that never emit mov ); }); -function makeStemRecord(lon = -40, lat = 35) { - const base = Cesium.Cartesian3.fromDegrees(lon, lat, 0); - const tip = Cesium.Cartesian3.fromDegrees(lon, lat, 2500); - const stemPositionBuffers = [ - [base, tip], - [base, tip], - ]; - const setCalls = { position: 0, polyline: 0, polylineArrays: [] }; - return { - record: { - entity: { - position: { - setValue: () => { - setCalls.position++; - }, - }, - polyline: { - positions: { - setValue: (value) => { - setCalls.polyline++; - setCalls.polylineArrays.push(value); - }, - }, - }, - }, - base, - tip, - nextTip: Cesium.Cartesian3.clone(tip), - stemPositionBuffers, - stemPositionBufferIndex: 0, - reference: { lon, lat }, - }, - setCalls, - stemPositionBuffers, +test('stems re-size only on real tip changes, moving the tip in place', () => { + const lon = -40; + const lat = 35; + const tip = fromDegrees(lon, lat, 2500); + const record = { + base: fromDegrees(lon, lat, 0), + tip, + reference: { lon, lat }, }; -} - -test('staticized stems redefine constants only on real tip changes, alternating buffers', () => { - const { record, setCalls, stemPositionBuffers } = makeStemRecord(); const canvasHeight = 900; const fov = Math.PI / 3; const camera = Cesium.Cartesian3.fromDegrees(-40, 35, 500_000); @@ -580,15 +358,10 @@ test('staticized stems redefine constants only on real tip changes, alternating updateCableReferenceStem(record, camera, canvasHeight, fov), true, ); - assert.equal(setCalls.position, 1); - assert.equal(setCalls.polyline, 1); - assert.equal( - setCalls.polylineArrays[0], - stemPositionBuffers[1], - 'first real update selects the alternate buffer', - ); + assert.equal(record.tip, tip, 'the overlay entry keeps its anchor object'); + const sized = { ...record.tip }; - // Sub-epsilon camera noise must not redefine anything. + // Sub-epsilon camera noise must not move anything. const jitter = Cesium.Cartesian3.add( camera, new Cesium.Cartesian3(CABLE_STEM_TIP_EPSILON_M / 10, 0, 0), @@ -598,11 +371,8 @@ test('staticized stems redefine constants only on real tip changes, alternating updateCableReferenceStem(record, jitter, canvasHeight, fov), false, ); - assert.equal(setCalls.position, 1); - assert.equal(setCalls.polyline, 1); + assert.deepEqual({ ...record.tip }, sized); - // A real camera move flips back to the first buffer: steady state allocates - // no arrays beyond the two preallocated ones. const moved = Cesium.Cartesian3.add( camera, new Cesium.Cartesian3(0, 0, 400_000), @@ -612,12 +382,11 @@ test('staticized stems redefine constants only on real tip changes, alternating updateCableReferenceStem(record, moved, canvasHeight, fov), true, ); - assert.equal(setCalls.polylineArrays[1], stemPositionBuffers[0]); - assert.equal(new Set(setCalls.polylineArrays).size, 2); + assert.notDeepEqual({ ...record.tip }, sized); // Stem height honors the shipped 700 m..85 km clamp. - const tipCarto = Cesium.Cartographic.fromCartesian(record.tip); - assert.ok(tipCarto.height >= 700 && tipCarto.height <= 85_000); + const { height } = toLonLatH(record.tip); + assert.ok(height >= 700 && height <= 85_000); }); test('the depth decision is the dated Option-2 host migration, superseding Option 1', () => { @@ -629,11 +398,8 @@ test('the depth decision is the dated Option-2 host migration, superseding Optio }); }); -test('cables create no native labels and no per-frame geometry callbacks', () => { - const source = [ - '../../data/telegeographySubmarineCables.js', - '../../app/layers/submarineCables.js', - '../../app/layers/overlayHost.js', +test('cables create no native labels and reach no renderer but through its ports', () => { + const files = [ 'rendering.js', 'overlay.js', 'surface.js', @@ -641,38 +407,26 @@ test('cables create no native labels and no per-frame geometry callbacks', () => 'interaction.js', 'geometry.js', 'lifecycle.js', - ] - .map((file) => - readFileSync( - new URL('../layers/submarineCables/' + file, import.meta.url), - 'utf8', - ), - ) - .join('\n'); - assert.doesNotMatch( - source, - /new Cesium\.LabelGraphics/, - 'reverting to native labels must fail this pin', - ); - assert.doesNotMatch( - source, - /new Cesium\.CallbackProperty/, - 'reverting to per-frame stem callbacks must fail this pin', - ); + 'policy.js', + 'state.js', + 'pin.js', + ]; + for (const file of files) { + const code = readFileSync( + new URL('../layers/submarineCables/' + file, import.meta.url), + 'utf8', + ); + assert.doesNotMatch(code, /from 'cesium'/, `${file} imports no Cesium`); + assert.doesNotMatch(code, /render\/cesium\//, `${file} skips the adapter`); + } assert.match( - source, + readFileSync( + new URL('../app/layers/overlayHost.js', import.meta.url), + 'utf8', + ), /setOverlayEntries/, 'labels must flow through the shared world-overlay host', ); - assert.match(source, /record\.entity\.position\.setValue\(record\.tip\)/); - assert.match( - source, - /const stemPositionBuffers = \[\s*\[base, tip\],\s*\[base, tip\],?\s*\]/, - ); - assert.match( - source, - /record\.entity\.polyline\.positions\.setValue\(stemPositions\)/, - ); }); const CABLE_FIXTURE = { @@ -692,604 +446,95 @@ const CABLE_FIXTURE = { }, ], }; -// Node has no `document`, so Point features (whose GeoJSON default marker -// needs a canvas PinBuilder) cannot load here. Landing references only need -// `properties.coordinates`, so a line geometry exercises the same path. const LANDING_FIXTURE = { type: 'FeatureCollection', features: [ { type: 'Feature', id: 'lisbon', - properties: { - id: 'lisbon', - name: 'Lisbon, Portugal', - coordinates: [-9.1, 38.7], - }, - geometry: { - type: 'LineString', - coordinates: [ - [-9.1, 38.7], - [-9.05, 38.72], - ], - }, + properties: { id: 'lisbon', name: 'Lisbon, Portugal' }, + geometry: { type: 'Point', coordinates: [-9.1, 38.7] }, }, ], }; -function fixtureForUrl(url) { - return String(url).includes('landing-point') - ? LANDING_FIXTURE - : CABLE_FIXTURE; -} - -function makeStubViewer( - listeners, - dataSources, - addCalls = { count: 0 }, - addControl = null, -) { - return { - dataSources: { - // Mirror Cesium's real DataSourceCollection.add(): the returned promise - // resolves — and the collection mutates — on a DEFERRED tick, never in - // the caller's synchronous frame. A remove() issued before the deferred - // add settles therefore removes NOTHING and the add still materializes - // afterwards (empirically verified against Cesium). Tests may hold the - // settle window open via addControl to abort inside it, and may mark an - // add rejected-AFTER-push: Cesium pushes into the collection BEFORE - // raising dataSourceAdded, so a throwing listener rejects the promise - // after the mutation already landed. - add: (source) => { - const callIndex = addCalls.count; - addCalls.count += 1; - return new Promise((resolve, reject) => { - const settle = () => { - dataSources.push(source); - if (addControl?.rejectAfterPush?.has(callIndex)) { - reject( - new Error( - 'dataSourceAdded listener threw after the push landed', - ), - ); - return; - } - resolve(source); - }; - if (addControl?.held) addControl.pending.push(settle); - else Promise.resolve().then(settle); - }); - }, - remove: (source) => { - const index = dataSources.indexOf(source); - if (index >= 0) dataSources.splice(index, 1); - return index >= 0; - }, - }, - camera: { - positionWC: Cesium.Cartesian3.fromDegrees(-40, 35, 4_500_000), - frustum: { fov: Math.PI / 3 }, - moveEnd: { - addEventListener: (fn) => { - listeners.moveEnd.add(fn); - return () => listeners.moveEnd.delete(fn); - }, - }, - heading: 0, - cancelFlight() {}, - flyTo() {}, - }, - scene: { - canvas: { clientHeight: 900 }, - requestRender() {}, - pick() { - return null; - }, - preRender: { - addEventListener: (fn) => { - listeners.preRender.add(fn); - return () => listeners.preRender.delete(fn); - }, - }, - }, - }; -} +const abortError = () => + Object.assign(new Error('The operation was aborted'), { + name: 'AbortError', + }); /** - * Harness whose fetches stay PENDING until the test releases them, honoring + * A source whose fetches stay PENDING until the test releases them, honoring * the abort signal like real fetch (reject with AbortError on abort). Load * lifecycle races are sequenced deterministically through it. */ -function createDeferredCableLayerHarness() { - const hostCalls = []; - const listeners = { preRender: new Set(), moveEnd: new Set() }; - const dataSources = []; - const addCalls = { count: 0 }; - const addControl = { held: false, pending: [], rejectAfterPush: new Set() }; - const pendingFetches = []; - const abortError = () => - Object.assign(new Error('The operation was aborted'), { - name: 'AbortError', - }); - const originalFetch = globalThis.fetch; - globalThis.fetch = (url, options = {}) => - new Promise((resolve, reject) => { - const entry = { - url: String(url), - settled: false, - release() { - if (entry.settled) return; - entry.settled = true; - resolve({ ok: true, json: async () => fixtureForUrl(url) }); - }, - }; - const signal = options?.signal; - if (signal) { - if (signal.aborted) { - entry.settled = true; - reject(abortError()); - return; - } - signal.addEventListener( - 'abort', - () => { - if (entry.settled) return; +function deferredSource(payload = {}) { + const pending = []; + return { + pending, + source: { + label: 'TeleGeography', + fetch(signal) { + return new Promise((resolve, reject) => { + const entry = { + settled: false, + release() { + if (entry.settled) return; + entry.settled = true; + resolve({ + cables: payload.cables ?? CABLE_FIXTURE, + landingPoints: payload.landingPoints ?? LANDING_FIXTURE, + }); + }, + }; + if (signal?.aborted) { entry.settled = true; reject(abortError()); - }, - { once: true }, - ); - } - pendingFetches.push(entry); - }); - - const layer = createTeleGeographySubmarineCableLayer({ - overlayHost: { - setVisible: (...args) => hostCalls.push(['visible', ...args]), - setEntries: (...args) => hostCalls.push(['entries', ...args]), - clearSource: (...args) => hostCalls.push(['clear', ...args]), - }, - inputFor: () => ({ onClick: () => () => {} }), - }); - const viewer = makeStubViewer(listeners, dataSources, addCalls, addControl); - layer.init(viewer); - - return { - layer, - viewer, - hostCalls, - dataSources, - addCalls, - listeners, - pendingFetches, - raiseSweep() { - for (const fn of listeners.preRender) fn(); + return; + } + signal?.addEventListener( + 'abort', + () => { + if (entry.settled) return; + entry.settled = true; + reject(abortError()); + }, + { once: true }, + ); + pending.push(entry); + }); + }, }, releaseAll() { - for (const entry of [...pendingFetches]) entry.release(); - pendingFetches.length = 0; - }, - /** Park every subsequent dataSources.add in its deferred settle window. */ - holdAdds() { - addControl.held = true; - }, - /** Make the Nth add (0-based) push into the collection, THEN reject. */ - failAddAfterPush(callIndex) { - addControl.rejectAfterPush.add(callIndex); - }, - /** Let the held adds mutate the collection (the deferred settle lands). */ - releaseHeldAdds() { - addControl.held = false; - const pending = addControl.pending.splice(0); - for (const settle of pending) settle(); - }, - async settle() { - // Drain the microtask/timer interleave the load path spans. - for (let i = 0; i < 8; i++) - await new Promise((resolve) => setTimeout(resolve, 0)); - }, - cleanup() { - globalThis.fetch = originalFetch; + for (const entry of pending.splice(0)) entry.release(); }, }; } +function geometrySource(cables, landingPoints = []) { + return { + label: 'Multipart test source', + async fetch() { + return { + cables: { type: 'FeatureCollection', features: cables }, + landingPoints: { type: 'FeatureCollection', features: landingPoints }, + }; + }, + }; +} + +const settle = async () => { + for (let i = 0; i < 8; i++) + await new Promise((resolve) => setTimeout(resolve, 0)); +}; + /** - * Gate Cesium's GeoJsonDataSource.load: each call runs the REAL load, then - * parks its resolution behind a test-owned gate. Opening gate N and aborting - * in the same synchronous frame lands the abort exactly at the caller's - * post-await ownership check for that boundary. + * A cable layer on a viewer double with a fake draw port and camera port + * bound, as the application binds its renderer. Not loaded until a test + * enables it (`load()` enables and waits). */ -function installGeoJsonLoadGate() { - const original = Cesium.GeoJsonDataSource.load; - const calls = []; - const gates = []; - Cesium.GeoJsonDataSource.load = function gatedLoad(...args) { - calls.push(args); - let open; - const opened = new Promise((resolve) => { - open = resolve; - }); - gates.push({ open }); - return original - .apply(Cesium.GeoJsonDataSource, args) - .then((result) => opened.then(() => result)); - }; - return { - calls, - open(index) { - gates[index]?.open(); - }, - /** - * Open every gate, including ones created by continuations the opening - * itself unblocks (a load calls the landing build only after the cable - * gate opens), until no new gates appear. - */ - async drainOpen(settle) { - let opened = 0; - while (opened < gates.length) { - for (; opened < gates.length; opened++) gates[opened].open(); - await settle(); - } - }, - restore() { - Cesium.GeoJsonDataSource.load = original; - }, - }; -} - -test('an abort landing at the post-fetch boundary stops the stale load before GeoJson work', async () => { - const env = createDeferredCableLayerHarness(); - const geojson = installGeoJsonLoadGate(); - try { - env.layer.enable(env.viewer); - // Release A's fetches and abort in the SAME frame: A's continuation runs - // with ownership already lost, and the post-fetch owns() check is the guard. - env.releaseAll(); - env.layer.disable(); - env.layer.enable(env.viewer); - await env.settle(); - assert.equal( - geojson.calls.length, - 0, - 'stale load A must not reach GeoJsonDataSource.load', - ); - - env.releaseAll(); - await env.settle(); - await geojson.drainOpen(() => env.settle()); - assert.equal( - geojson.calls.length, - 2, - 'load B alone performs the two GeoJson loads', - ); - assert.equal(env.addCalls.count, 3); - assert.equal(env.dataSources.length, 3); - assert.equal(env.layer.getStats().count, 2); - } finally { - geojson.restore(); - env.layer.destroy(env.viewer); - env.cleanup(); - } -}); - -test('an abort landing at the post-cable-GeoJson boundary stops the stale load before the landing build', async () => { - const env = createDeferredCableLayerHarness(); - const geojson = installGeoJsonLoadGate(); - try { - env.layer.enable(env.viewer); - env.releaseAll(); - await env.settle(); - assert.equal(env.pendingFetches.length, 0); - assert.equal( - geojson.calls.length, - 1, - 'load A is parked on the gated cable GeoJson build', - ); - - // Open the cable gate and abort in the same frame: A resumes at the - // post-cable owns() check with ownership lost. - geojson.open(0); - env.layer.disable(); - env.layer.enable(env.viewer); - await env.settle(); - // A already cached the fetched JSON, so load B skips the network and goes - // straight to its own CABLE build; the only new GeoJson call must be that - // one — a landing build here would mean stale A ran on past its check. - assert.equal( - env.pendingFetches.length, - 0, - 'load B rebuilds from the cached JSON without refetching', - ); - assert.equal( - geojson.calls.length, - 2, - 'stale load A must not start the landing GeoJson build', - ); - assert.ok( - Cesium.Color.equals( - geojson.calls[1][1].stroke, - geojson.calls[0][1].stroke, - ), - "the second GeoJson call is load B's cable build, not A's landing build", - ); - - env.releaseAll(); - await env.settle(); - await geojson.drainOpen(() => env.settle()); - assert.equal( - geojson.calls.length, - 3, - 'load B adds its own two GeoJson builds', - ); - assert.equal(env.addCalls.count, 3); - assert.equal(env.dataSources.length, 3); - assert.equal(env.layer.getStats().count, 2); - } finally { - geojson.restore(); - env.layer.destroy(env.viewer); - env.cleanup(); - } -}); - -test('an abort landing at the pre-add boundary stops the stale load before any dataSources.add', async () => { - const env = createDeferredCableLayerHarness(); - const geojson = installGeoJsonLoadGate(); - try { - env.layer.enable(env.viewer); - env.releaseAll(); - await env.settle(); - geojson.open(0); - await env.settle(); - assert.equal( - geojson.calls.length, - 2, - 'load A is parked on the gated landing GeoJson build', - ); - - // Open the landing gate and abort in the same frame: A resumes at the - // pre-add owns() check with ownership lost. - geojson.open(1); - env.layer.disable(); - env.layer.enable(env.viewer); - await env.settle(); - assert.equal( - env.addCalls.count, - 0, - 'stale load A must never call dataSources.add', - ); - - env.releaseAll(); - await env.settle(); - await geojson.drainOpen(() => env.settle()); - assert.equal(env.addCalls.count, 3, 'load B alone adds the trio'); - assert.equal(env.dataSources.length, 3); - assert.equal(env.layer.getStats().count, 2); - } finally { - geojson.restore(); - env.layer.destroy(env.viewer); - env.cleanup(); - } -}); - -test('a destroy inside the deferred add window leaves zero post-destroy data sources', async () => { - const env = createDeferredCableLayerHarness(); - try { - env.layer.enable(env.viewer); - env.releaseAll(); - env.holdAdds(); - // Let the load run until all three adds have been CALLED but none has - // settled — Cesium mutates the collection on a deferred tick, so this - // window is real, and a remove() issued inside it removes nothing. - const deadline = Date.now() + 2_000; - while (env.addCalls.count < 3 && Date.now() < deadline) { - await new Promise((resolve) => setTimeout(resolve, 0)); - } - assert.equal( - env.addCalls.count, - 3, - 'all three adds are in their deferred window', - ); - assert.equal( - env.dataSources.length, - 0, - 'nothing has settled into the collection yet', - ); - - // Destroy lands in the window: it can remove nothing, so the stale - // load's own post-add ownership check must compensate once the deferred - // adds settle. - env.layer.destroy(env.viewer); - env.releaseHeldAdds(); - await env.settle(); - assert.equal( - env.dataSources.length, - 0, - 'the deferred adds settled post-destroy and must be rolled back by their own load', - ); - - // The layer still honors its re-init contract afterwards. - env.layer.enable(env.viewer); - env.releaseAll(); - await env.settle(); - assert.equal( - env.dataSources.length, - 3, - 're-enable after the raced destroy loads cleanly', - ); - assert.equal(env.layer.getStats().count, 2); - } finally { - env.layer.destroy(env.viewer); - env.cleanup(); - } -}); - -test('a destroy in the deferred window with a rejected-after-push add still leaves zero sources', async () => { - const env = createDeferredCableLayerHarness(); - try { - env.layer.enable(env.viewer); - env.releaseAll(); - env.holdAdds(); - // Cesium pushes the source into the collection BEFORE raising - // dataSourceAdded, so a throwing listener rejects the add promise AFTER - // its mutation landed. Make add #1 exactly that: pushed, then rejected; - // #2/#3 fulfill normally. - env.failAddAfterPush(0); - const deadline = Date.now() + 2_000; - while (env.addCalls.count < 3 && Date.now() < deadline) { - await new Promise((resolve) => setTimeout(resolve, 0)); - } - assert.equal( - env.addCalls.count, - 3, - 'all three adds are in their deferred window', - ); - assert.equal( - env.dataSources.length, - 0, - 'nothing has settled into the collection yet', - ); - - // Destroy lands in the window; the adds then settle as - // [rejected-after-push, fulfilled, fulfilled]. Compensation that removes - // only FULFILLED adds would strand the rejected-but-pushed source. - env.layer.destroy(env.viewer); - env.releaseHeldAdds(); - await env.settle(); - assert.equal( - env.dataSources.length, - 0, - 'a rejected add still landed its push, so compensation must remove it too', - ); - } finally { - env.layer.destroy(env.viewer); - env.cleanup(); - } -}); - -test('a direct destroy of a published layer clears and hides its host source', async () => { - const env = createDeferredCableLayerHarness(); - try { - env.layer.enable(env.viewer); - env.releaseAll(); - await env.settle(); - assert.equal(env.dataSources.length, 3, 'layer is fully loaded'); - // Drive the sweep through the layer's real preRender listener so the - // host actually holds published cable entries. - env.raiseSweep(); - assert.ok( - env.hostCalls.some(([type]) => type === 'entries'), - 'sweep must publish before the direct destroy', - ); - env.hostCalls.length = 0; - - // Destroy DIRECTLY — no disable() first. The publisher teardown must - // still clear the published source and hide it; skipping it would leave - // a visible overlay source with orphan labels. - env.layer.destroy(env.viewer); - assert.ok( - env.hostCalls.some( - ([type, id]) => type === 'clear' && id === CABLE_OVERLAY_SOURCE_ID, - ), - 'direct destroy must clear the published host source', - ); - assert.deepEqual( - env.hostCalls.at(-1), - ['visible', CABLE_OVERLAY_SOURCE_ID, false], - 'direct destroy must hide the host source after clearing it', - ); - } finally { - env.cleanup(); - } -}); - -test("a stale aborted load never clobbers the next load's lifecycle (A/B/C toggle race)", async () => { - const env = createDeferredCableLayerHarness(); - try { - // A: enable starts a load whose fetches stay pending. - env.layer.enable(env.viewer); - assert.equal( - env.pendingFetches.length, - 2, - 'load A has two fetches in flight', - ); - - // Abort A and immediately start B before A\'s rejection lands. - env.layer.disable(); - env.layer.enable(env.viewer); - await env.settle(); // A\'s stale catch/finally runs here, after B began. - - // C: with A\'s stale completion having cleared nothing it does not own, - // the layer still reports a load in flight, so update() must not start a - // third load. - void env.layer.update(env.viewer); - await env.settle(); - const inFlight = env.pendingFetches.filter( - (entry) => !entry.settled, - ).length; - assert.equal( - inFlight, - 2, - "only load B's two fetches remain in flight — no duplicate load C", - ); - - // Releasing everything must produce exactly one set of scene adds. - env.releaseAll(); - await env.settle(); - assert.equal( - env.addCalls.count, - 3, - 'exactly one cable/landing/reference data-source trio is added', - ); - assert.equal(env.dataSources.length, 3); - const stats = env.layer.getStats(); - assert.equal(stats.error, null); - assert.equal(stats.count, 2, 'one cable + one landing point loaded once'); - } finally { - env.layer.destroy(env.viewer); - env.cleanup(); - } -}); - -test('destroy mid-load stays clean and a re-enabled layer reloads exactly once', async () => { - const env = createDeferredCableLayerHarness(); - try { - // Destroy while load A\'s fetches are still in flight. - env.layer.enable(env.viewer); - assert.equal(env.pendingFetches.length, 2); - env.layer.destroy(env.viewer); - - // Legacy contract: the layer supports re-init after destroy. Enable D - // before A\'s aborted rejection lands. - env.layer.enable(env.viewer); - await env.settle(); // A\'s stale finally runs here. - - // A\'s stale completion must not have cleared D\'s in-flight lifecycle: - // update() must not start a duplicate load E. - void env.layer.update(env.viewer); - await env.settle(); - const inFlight = env.pendingFetches.filter( - (entry) => !entry.settled, - ).length; - assert.equal(inFlight, 2, "only load D's two fetches remain in flight"); - - env.releaseAll(); - await env.settle(); - assert.equal( - env.addCalls.count, - 3, - 'the destroyed load added nothing; the re-enable added once', - ); - assert.equal(env.dataSources.length, 3); - assert.equal(env.layer.getStats().count, 2); - } finally { - env.layer.destroy(env.viewer); - env.cleanup(); - } -}); - -async function createRealCableLayerHarness({ - source, +function createCableHarness({ + source = deferredSource().source, mapStackEventTarget = null, } = {}) { const hostCalls = []; @@ -1297,141 +542,104 @@ async function createRealCableLayerHarness({ // the tests that exercise it, so every other harness test observes the pure // event-dirty behavior with no wall-clock coupling. let clockMs = 0; + let clickHandler = null; const layer = createTeleGeographySubmarineCableLayer({ overlayHost: { setVisible: (...args) => hostCalls.push(['visible', ...args]), setEntries: (...args) => hostCalls.push(['entries', ...args]), clearSource: (...args) => hostCalls.push(['clear', ...args]), }, - inputFor: () => ({ onClick: () => () => {} }), - ...(source ? { source } : {}), + inputFor: () => ({ + onClick: (fn) => { + clickHandler = fn; + return () => { + if (clickHandler === fn) clickHandler = null; + }; + }, + }), + source, mapStackEventTarget, sweepClock: () => clockMs, }); - - const listeners = { preRender: new Set(), moveEnd: new Set() }; - const dataSources = []; + const preRender = new Set(); const viewer = { - dataSources: { - add: (source) => { - dataSources.push(source); - return Promise.resolve(source); - }, - remove: (source) => { - const index = dataSources.indexOf(source); - if (index >= 0) dataSources.splice(index, 1); - return true; - }, - }, - camera: { - positionWC: Cesium.Cartesian3.fromDegrees(-40, 35, 4_500_000), - frustum: { fov: Math.PI / 3 }, - moveEnd: { - addEventListener: (fn) => { - listeners.moveEnd.add(fn); - return () => listeners.moveEnd.delete(fn); - }, - }, - heading: 0, - cancelFlight() {}, - flyTo() {}, - }, scene: { canvas: { clientHeight: 900 }, requestRender() {}, - pick() { - return null; - }, preRender: { addEventListener: (fn) => { - listeners.preRender.add(fn); - return () => listeners.preRender.delete(fn); + preRender.add(fn); + return () => preRender.delete(fn); }, }, }, }; - - const originalFetch = globalThis.fetch; - // Node has no `document`, so Point features (whose GeoJSON default marker - // needs a canvas PinBuilder) cannot load here. Landing references only need - // `properties.coordinates`, so a line geometry exercises the same path. - globalThis.fetch = async (url) => ({ - ok: true, - json: async () => - String(url).includes('landing-point') - ? { - type: 'FeatureCollection', - features: [ - { - type: 'Feature', - id: 'lisbon', - properties: { - id: 'lisbon', - name: 'Lisbon, Portugal', - coordinates: [-9.1, 38.7], - }, - geometry: { - type: 'LineString', - coordinates: [ - [-9.1, 38.7], - [-9.05, 38.72], - ], - }, - }, - ], - } - : { - type: 'FeatureCollection', - features: [ - { - type: 'Feature', - id: 'ac1', - properties: { id: 'ac1', name: 'Atlantic Crossing-1' }, - geometry: { - type: 'LineString', - coordinates: [ - [-40, 35], - [-30, 40], - ], - }, - }, - ], - }, + const camera = fakeCameraPort({ + pose: { + position: fromDegrees(-40, 35, 4_500_000), + fovy: Math.PI / 3, + aspectRatio: 1, + heading: 0.25, + }, }); - try { - layer.init(viewer); - layer.enable(viewer); - // enable() fires load() without awaiting it (legacy contract); poll the - // layer's own stats until the load settles. - const deadline = Date.now() + 2_000; - while (Date.now() < deadline) { - const stats = layer.getStats(); - if (stats.count > 0 || stats.error) break; - await new Promise((resolve) => setTimeout(resolve, 10)); - } - assert.equal(layer.getStats().error, null, 'harness load must succeed'); - } finally { - globalThis.fetch = originalFetch; - } - const raiseSweep = () => { - for (const fn of listeners.preRender) fn(); - }; - const advanceClock = (ms) => { - clockMs += ms; - }; + const flights = []; + camera.port.cancelFlight = () => flights.push('cancel'); + camera.port.flyTo = (destination, options) => + flights.push({ destination, options }); + const { draw } = bindFakeDraw(viewer, { camera: camera.port }); + layer.init(viewer); + /** The layer's live set named `name` (`lines`, `pins`, …). */ + const set = (name) => + [...draw.sets.values()].find( + (record) => !record.disposed && record.spec.id.endsWith(`:${name}`), + ); return { layer, viewer, + draw, + set, hostCalls, - dataSources, - raiseSweep, - listeners, - advanceClock, + flights, + setEye(lon, lat, height) { + camera.setPose({ position: fromDegrees(lon, lat, height) }); + }, + moveEnd: () => camera.emit('moveEnd'), + raiseSweep() { + for (const fn of preRender) fn(); + }, + advanceClock(ms) { + clockMs += ms; + }, + click(drawHit) { + clickHandler?.({ drawHit, pick: null }); + }, + async load() { + layer.enable(viewer); + source.releaseAll?.(); + const deadline = Date.now() + 2_000; + while (Date.now() < deadline) { + const stats = layer.getStats(); + if (stats.count > 0 || stats.error) break; + await new Promise((resolve) => setTimeout(resolve, 5)); + } + assert.equal(layer.getStats().error, null, 'harness load must succeed'); + }, }; } -test('a real enabled cable layer publishes host entries and has zero native labels', async () => { - const env = await createRealCableLayerHarness(); +/** A loaded harness over the fixtures (or `source`). */ +async function loadedHarness(options = {}) { + const deferred = deferredSource(); + const env = createCableHarness({ source: deferred.source, ...options }); + env.layer.enable(env.viewer); + deferred.releaseAll(); + await settle(); + assert.equal(env.layer.getStats().error, null, 'harness load must succeed'); + return env; +} + +test('a real enabled cable layer draws its sets, publishes host entries and has zero native labels', async () => { + const env = await loadedHarness(); env.raiseSweep(); const publishes = env.hostCalls.filter(([type]) => type === 'entries'); @@ -1445,28 +653,19 @@ test('a real enabled cable layer publishes host entries and has zero native labe collisionCapacity: CABLE_OVERLAY_COLLISION_CAPACITY, moving: false, }); + assert.equal(env.layer.getStats().referenceLabelCount, 2); - const referenceSource = env.dataSources.find((ds) => - /References/.test(ds.name || ''), + // Each set id is the layer's own, and nothing draws text. + const ids = [...env.draw.sets.keys()]; + assert.deepEqual( + ids.map((id) => id.replace(/^submarine-cables:\d+:/, '')), + ['lines', 'fills', 'pins', 'stems', 'references'], ); - assert.ok(referenceSource, 'reference data source must exist'); - const referenceEntities = referenceSource.entities.values; - assert.ok(referenceEntities.length > 0); - assert.ok( - referenceEntities.every((entity) => entity.label === undefined), - 'no reference entity may carry a native LabelGraphics', - ); - assert.ok( - referenceEntities.every( - (entity) => - entity.position?.isConstant === true && - entity.polyline?.positions?.isConstant === true, - ), - 'stem properties must be constants, never per-frame callbacks', - ); - - const stats = env.layer.getStats(); - assert.equal(stats.referenceLabelCount, 2); + assert.equal(env.set('lines').items.size, 1); + assert.equal(env.set('pins').items.size, 1); + assert.equal(env.set('stems').items.size, 2); + assert.equal(env.set('references').items.size, 2); + assert.ok(ids.every((id) => env.draw.set(id).show)); env.layer.disable(); assert.ok( @@ -1480,246 +679,253 @@ test('a real enabled cable layer publishes host entries and has zero native labe ['visible', CABLE_OVERLAY_SOURCE_ID, false], 'disable must hide the host source after clearing it', ); + assert.ok( + ids.every((id) => env.draw.set(id).items.size === 0), + 'hidden items are not free; disable must clear the sets', + ); - env.layer.destroy(env.viewer); - assert.equal( - env.dataSources.length, - 0, - 'destroy must remove every data source', + env.layer.destroy(); + assert.ok( + ids.every((id) => env.draw.sets.get(id).disposed), + 'destroy must dispose every set', ); }); -test('stems never rebuild mid-drag; exactly one rebuild lands on moveEnd', async () => { - const env = await createRealCableLayerHarness(); - env.raiseSweep(); // initial sizing at the parked camera +test('cables, landing pins and references draw as their entities did', async () => { + const env = await loadedHarness(); + assert.deepEqual(env.set('lines').spec.clampTo, 'both'); + assert.equal(env.set('pins').spec.blend, 'translucent'); + assert.equal(env.set('pins').spec.horizonCull, true); + assert.equal(env.set('references').spec.blend, 'translucent'); - const referenceSource = env.dataSources.find((ds) => - /References/.test(ds.name || ''), + const [line] = env.set('lines').items.values(); + assert.equal(line.mode, 'draped'); + assert.equal(line.widthPx, 2.5); + assert.deepEqual(line.style, { + kind: 'solid', + color: [0x39 / 255, 0xd5 / 255, 1, 0.92], + }); + assert.equal(line.clampTo, undefined, 'cable lines follow the stack'); + // Along the rhumb line, as GeoJSON lines were, in steps under 10 km. + const ends = [line.positions[0], line.positions.at(-1)].map(toLonLatH); + assert.ok( + Math.abs(ends[0].lon + 40) < 1e-9 && Math.abs(ends[0].lat - 35) < 1e-9, ); - const entity = referenceSource.entities.values[0]; - let stemRebuilds = 0; - const originalSet = entity.polyline.positions.setValue.bind( - entity.polyline.positions, + assert.ok( + Math.abs(ends[1].lon + 30) < 1e-9 && Math.abs(ends[1].lat - 40) < 1e-9, ); - entity.polyline.positions.setValue = (...args) => { - stemRebuilds++; - return originalSet(...args); + assert.ok(line.positions.length > 100); + const rhumb = new Cesium.EllipsoidRhumbLine( + Cesium.Cartographic.fromDegrees(-40, 35), + Cesium.Cartographic.fromDegrees(-30, 40), + ); + const middle = toLonLatH( + line.positions[Math.floor(line.positions.length / 2)], + ); + const along = rhumb.findIntersectionWithLongitude( + Cesium.Math.toRadians(middle.lon), + ); + assert.ok( + Math.abs(Cesium.Math.toDegrees(along.latitude) - middle.lat) < 1e-6, + ); + + const [pin] = env.set('pins').items.values(); + assert.deepEqual(pin.pos, { lon: -9.1, lat: 38.7, height: 0 }); + assert.equal(pin.height, 'clampGround'); + assert.deepEqual(pin.size, [6, 6]); + assert.equal(pin.anchor, 'bottom'); + assert.ok(pin.image.svg?.includes('fill="rgb(143,255,210)"')); + + const [cableStem, landingStem] = env.set('stems').items.values(); + assert.equal(cableStem.mode, '3d'); + assert.equal(cableStem.widthPx, 2); + assert.equal(landingStem.widthPx, 2.4); + assert.equal(cableStem.style.color[3], 0.58); + assert.equal(landingStem.style.color[3], 0.68); + const [cablePoint, landingPoint] = env.set('references').items.values(); + assert.equal(cablePoint.pixelSize, 7); + assert.equal(landingPoint.pixelSize, 8); + assert.equal(cablePoint.color[3], 0.84); + assert.equal(landingPoint.color[3], 0.94); + assert.deepEqual(cablePoint.outlineColor, [0, 0, 0, 0.65]); + assert.equal(cablePoint.outlineWidth, 1); + assert.equal(cablePoint.disableDepthTest, undefined, 'depth-tested'); + env.layer.destroy(); +}); + +test('a map-stack change re-drapes the cable lines once, and destroy detaches the listener', async () => { + const listeners = new Map(); + const eventTarget = { + addEventListener: (name, fn) => listeners.set(name, fn), + removeEventListener: (name, fn) => { + if (listeners.get(name) === fn) listeners.delete(name); + }, }; + const env = await loadedHarness({ mapStackEventTarget: eventTarget }); + // The harness scene has no globe → both at init (safe unknown fallback). + assert.equal(env.set('lines').spec.clampTo, 'both'); + const listener = listeners.get('gev:map-stack-changed'); + assert.equal(typeof listener, 'function', 'init must subscribe'); + + listener({ detail: { activeId: 'photoreal', status: 'ready' } }); + assert.equal(env.set('lines').spec.clampTo, 'tiles'); + listener({ detail: { activeId: 'osm', status: 'ready' } }); + assert.equal(env.set('lines').spec.clampTo, 'terrain'); + assert.equal(env.set('fills').spec.clampTo, 'both', 'fills never followed'); + + env.layer.destroy(); + assert.equal( + listeners.has('gev:map-stack-changed'), + false, + 'destroy must detach the stack listener', + ); +}); + +test('a click on a cable, pin, stem or reference flies to its reference; others do nothing', async () => { + const env = await loadedHarness(); + const [lineId] = env.set('lines').items.keys(); + const [pinId] = env.set('pins').items.keys(); + const [cableRef, landingRef] = env.set('references').items.keys(); + const flyTargets = () => + env.flights + .filter((flight) => flight !== 'cancel') + .map((flight) => flight.destination); + + env.click({ set: env.set('lines').spec.id, id: lineId }); + env.click({ set: env.set('pins').spec.id, id: pinId }); + env.click({ set: env.set('stems').spec.id, id: cableRef }); + env.click({ set: env.set('references').spec.id, id: landingRef }); + assert.deepEqual(flyTargets(), [ + { lon: -35, lat: 37.5, height: 6500 }, + { lon: -9.1, lat: 38.7, height: 6500 }, + { lon: -35, lat: 37.5, height: 6500 }, + { lon: -9.1, lat: 38.7, height: 6500 }, + ]); + const flight = env.flights.find((entry) => entry !== 'cancel'); + assert.deepEqual(flight.options, { + orientation: { heading: 0.25, pitch: (-52 * Math.PI) / 180, roll: 0 }, + durationS: 1.35, + easing: 'cubicInOut', + }); + assert.equal(env.flights[0], 'cancel', 'a running flight is cancelled'); + + env.flights.length = 0; + env.click({ set: 'other-layer:lines', id: lineId }); + env.click({ set: env.set('lines').spec.id, id: 'gone' }); + env.click(null); + env.layer.disable(); + env.click({ set: env.set('lines').spec.id, id: lineId }); + assert.deepEqual(env.flights, [], 'foreign, stale and disabled clicks'); + env.layer.destroy(); +}); + +test('stems never redraw mid-drag; exactly one redraw lands on moveEnd', async () => { + const env = await loadedHarness(); + env.raiseSweep(); // initial sizing at the parked camera + const stems = env.set('stems'); + const before = stems.writes; // Mid-drag: the camera moves every tick and frames keep rendering, but no - // moveEnd fires. However long this goes on, the stem constants must never - // be redefined — each redefinition rebuilt the whole batched stem - // primitive, and its unready replacement frames were the felt hitch. - const camera = env.viewer.camera.positionWC; + // moveEnd fires. However long this goes on, the stems must never be + // redrawn — each redraw rebuilt the stems, and its frames were the hitch. for (let tick = 0; tick < 30; tick++) { - env.viewer.camera.positionWC = Cesium.Cartesian3.add( - camera, - new Cesium.Cartesian3(0, 0, 100_000 * (tick + 1)), - new Cesium.Cartesian3(), - ); - env.raiseSweep(); // preRender fires every frame during a drag - await new Promise((resolve) => setTimeout(resolve, 25)); + env.setEye(-40, 35, 4_500_000 + 100_000 * (tick + 1)); + env.raiseSweep(); } assert.equal( - stemRebuilds, - 0, - 'render ticks without moveEnd must never redefine a stem', + stems.writes, + before, + 'render ticks without moveEnd never redraw', ); // The gesture ends close over the cable's reference point (inside the // 700 m..85 km stem clamp band, so the re-size is a real tip change): - // one moveEnd, one sweep, exactly one redefinition. - env.viewer.camera.positionWC = Cesium.Cartesian3.fromDegrees( - -35, - 37.5, - 400_000, - ); - for (const fn of env.listeners.moveEnd) fn(); + // one moveEnd, one sweep, exactly one redraw. + env.setEye(-35, 37.5, 400_000); + env.moveEnd(); env.raiseSweep(); - assert.equal(stemRebuilds, 1, 'moveEnd re-sizes the stem exactly once'); + assert.equal(stems.writes, before + 1, 'moveEnd re-sizes the stems once'); env.raiseSweep(); - assert.equal(stemRebuilds, 1, 'the next frame does not re-run the sweep'); - - env.layer.destroy(env.viewer); + assert.equal(stems.writes, before + 1, 'the next frame does not re-run'); + env.layer.destroy(); }); test('a tracked camera that never emits moveEnd is swept by the motion fallback', async () => { - const env = await createRealCableLayerHarness(); - // Tracking hands over a mid-altitude follow camera. 400 km keeps the stem - // inside the 700 m..85 km clamp band, so a sweep is observable as a real - // tip re-size (at the harness's 4,500 km parking altitude every stem sits - // pinned at the 85 km clamp and no sweep could be distinguished). - env.viewer.camera.positionWC = Cesium.Cartesian3.fromDegrees( - -35, - 37.5, - 400_000, - ); + const env = await loadedHarness(); + // 400 km keeps the stem inside the 700 m..85 km clamp band, so a sweep is + // observable as a real tip re-size. + env.setEye(-35, 37.5, 400_000); env.raiseSweep(); // initial sizing at the tracking handoff - - const referenceSource = env.dataSources.find((ds) => - /References/.test(ds.name || ''), - ); - const entity = referenceSource.entities.values[0]; - let stemRebuilds = 0; - const originalSet = entity.polyline.positions.setValue.bind( - entity.polyline.positions, - ); - entity.polyline.positions.setValue = (...args) => { - stemRebuilds++; - return originalSet(...args); - }; - - // Entity tracking / orbit: the follow camera advances every frame and - // moveEnd NEVER fires. Frames are simulated at 60 Hz on the harness clock. - const origin = env.viewer.camera.positionWC; + const stems = env.set('stems'); + const before = stems.writes; const frameMs = 1000 / 60; const trackFrames = (from, to) => { for (let frame = from; frame < to; frame++) { env.advanceClock(frameMs); - env.viewer.camera.positionWC = Cesium.Cartesian3.add( - origin, - new Cesium.Cartesian3(0, 0, 200 * (frame + 1)), - new Cesium.Cartesian3(), - ); + env.setEye(-35, 37.5, 400_000 + 200 * (frame + 1)); env.raiseSweep(); } }; - - // Inside the first probe window the sweep stays event-dirty-only, so the - // batched stem primitive is not rebuilt mid-motion (the shipped tradeoff). trackFrames(0, 60); assert.equal( - stemRebuilds, - 0, - 'inside the probe window a tracked camera still costs no rebuilds', + stems.writes, + before, + 'inside the probe window a tracked camera still costs no redraws', ); - - // Past the window the fallback fires — exactly once, not per frame. trackFrames(60, 130); assert.equal( - stemRebuilds, - 1, + stems.writes, + before + 1, 'the tracked camera earns exactly one fallback sweep per window', ); - - // Tracking stops but frames keep rendering. The motion accumulated since - // the last fallback sweep settles in exactly ONE further sweep... const parkFrames = (count) => { for (let frame = 0; frame < count; frame++) { env.advanceClock(frameMs); env.raiseSweep(); } }; - parkFrames(240); // 4 s parked: two full probe windows + parkFrames(240); assert.equal( - stemRebuilds, - 2, + stems.writes, + before + 2, 'a stopped camera settles its residual motion in one further sweep', ); - - // ...and the parked camera then costs zero sweeps for as long as it sits. - parkFrames(3600); // 60 s parked - assert.equal( - stemRebuilds, - 2, - 'a settled parked camera never spends another sweep', - ); - - env.layer.destroy(env.viewer); + parkFrames(3600); + assert.equal(stems.writes, before + 2, 'then a parked camera costs nothing'); + env.layer.destroy(); }); test('an unchanged cohort never republishes, so a parked camera stays governor-idle', async () => { - const env = await createRealCableLayerHarness(); + const env = await loadedHarness(); const publishCount = () => env.hostCalls.filter(([type]) => type === 'entries').length; env.raiseSweep(); assert.equal(publishCount(), 1, 'first sweep publishes the cohort'); - - // moveEnd with an unchanged camera re-arms the sweep; the identical winner - // set must NOT reach the host again (each publish costs a requested render). - for (const fn of env.listeners.moveEnd) fn(); + env.moveEnd(); env.raiseSweep(); - for (const fn of env.listeners.moveEnd) fn(); + env.moveEnd(); env.raiseSweep(); assert.equal(publishCount(), 1, 'identical cohorts are skipped'); - // A real camera move changes distances beyond the 50 km priority quantum, - // so the next sweep publishes again. - env.viewer.camera.positionWC = Cesium.Cartesian3.fromDegrees( - -40, - 35, - 6_500_000, - ); - for (const fn of env.listeners.moveEnd) fn(); + env.setEye(-40, 35, 6_500_000); + env.moveEnd(); env.raiseSweep(); assert.equal(publishCount(), 2, 'a changed cohort publishes'); - // disable → enable must force a republish even when the cohort is identical - // (the hide cleared the host source). env.layer.disable(); env.layer.enable(env.viewer); - await new Promise((resolve) => setTimeout(resolve, 10)); + await settle(); env.raiseSweep(); assert.equal( publishCount(), 3, 're-enable republishes after the hide cleared the source', ); - - env.layer.destroy(env.viewer); + env.layer.destroy(); }); -test('a toggle-off releases every data source and a toggle-on rebuilds them without refetching', async () => { - const env = await createRealCableLayerHarness(); - assert.equal( - env.dataSources.length, - 3, - 'cable + landing + reference sources while on', - ); - const before = env.layer.getStats().count; - assert.equal(before, 2); - - // Any fetch after this point is a bug: the rebuild must come from the cache. - const originalFetch = globalThis.fetch; - let fetches = 0; - globalThis.fetch = async () => { - fetches += 1; - throw new Error('unexpected refetch'); - }; - try { - env.layer.disable(); - assert.equal( - env.dataSources.length, - 0, - 'hidden entities are not free; disable must remove the sources', - ); - - env.layer.enable(env.viewer); - const deadline = Date.now() + 2_000; - while (Date.now() < deadline && env.dataSources.length < 3) { - await new Promise((resolve) => setTimeout(resolve, 10)); - } - assert.equal(fetches, 0, 'the rebuild must not touch the network'); - assert.equal(env.layer.getStats().error, null); - assert.equal(env.dataSources.length, 3, 're-enable rebuilds the trio'); - assert.equal(env.layer.getStats().count, before); - const referenceSource = env.dataSources.find((ds) => - /References/.test(ds.name || ''), - ); - assert.ok( - referenceSource?.entities.values.length > 0, - 'reference stems are rebuilt', - ); - - env.layer.destroy(env.viewer); - assert.equal(env.dataSources.length, 0); - } finally { - globalThis.fetch = originalFetch; - } -}); - -test('another GeoJSON source renders with its own label and rebuilds from accepted cache', async () => { +test('a toggle-off clears every set and a toggle-on redraws them without refetching', async () => { let reads = 0; const source = { label: 'Test cable directory', @@ -1729,24 +935,127 @@ test('another GeoJSON source renders with its own label and rebuilds from accept return { cables: CABLE_FIXTURE, landingPoints: LANDING_FIXTURE }; }, }; - const env = await createRealCableLayerHarness({ source }); + const env = createCableHarness({ source }); + await env.load(); + assert.equal(env.layer.source, source.label); + assert.equal(reads, 1); + const before = env.layer.getStats().count; + assert.equal(before, 2); + env.layer.disable(); + assert.equal(env.set('lines').items.size, 0); + env.layer.enable(env.viewer); + await settle(); + assert.equal(reads, 1, 'the redraw must not touch the network'); + assert.equal(env.layer.getStats().count, before); + assert.equal(env.set('lines').items.size, 1); + assert.equal(env.set('references').items.size, 2, 'references are redrawn'); + env.layer.destroy(); +}); + +test('an abort landing at the post-fetch boundary stops the stale load before it draws', async () => { + const deferred = deferredSource(); + const env = createCableHarness({ source: deferred.source }); try { - assert.equal(env.layer.source, source.label); - assert.equal(reads, 1); - assert.equal(env.dataSources.length, 3); - assert.ok( - env.dataSources.every((item) => item.name.startsWith(source.label)), - ); - env.layer.disable(); - assert.equal(env.dataSources.length, 0); env.layer.enable(env.viewer); - for (let i = 0; i < 8; i++) - await new Promise((resolve) => setTimeout(resolve, 0)); + // Release A's fetches and abort in the SAME frame: A's continuation runs + // with ownership already lost, and the post-fetch owns() check is the guard. + deferred.releaseAll(); + env.layer.disable(); + env.layer.enable(env.viewer); + const writes = env.set('lines').writes; + await settle(); + assert.equal(env.set('lines').writes, writes, 'stale load A must not draw'); + assert.equal(env.set('lines').items.size, 0); + deferred.releaseAll(); + await settle(); + assert.equal(env.set('lines').writes, writes + 1, 'load B alone draws'); + assert.equal(env.set('lines').items.size, 1); assert.equal(env.layer.getStats().count, 2); - assert.equal(env.dataSources.length, 3); - assert.equal(reads, 1); } finally { - env.layer.destroy(env.viewer); + env.layer.destroy(); + } +}); + +test('a direct destroy of a published layer clears and hides its host source', async () => { + const env = await loadedHarness(); + env.raiseSweep(); + assert.ok(env.hostCalls.some(([type]) => type === 'entries')); + env.hostCalls.length = 0; + // Destroy DIRECTLY — no disable() first. The publisher teardown must + // still clear the published source and hide it; skipping it would leave + // a visible overlay source with orphan labels. + env.layer.destroy(); + assert.ok( + env.hostCalls.some( + ([type, id]) => type === 'clear' && id === CABLE_OVERLAY_SOURCE_ID, + ), + 'direct destroy must clear the published host source', + ); + assert.deepEqual( + env.hostCalls.at(-1), + ['visible', CABLE_OVERLAY_SOURCE_ID, false], + 'direct destroy must hide the host source after clearing it', + ); +}); + +test("a stale aborted load never clobbers the next load's lifecycle (A/B/C toggle race)", async () => { + const deferred = deferredSource(); + const env = createCableHarness({ source: deferred.source }); + try { + env.layer.enable(env.viewer); + assert.equal(deferred.pending.length, 1, 'load A is in flight'); + // Abort A and immediately start B before A's rejection lands. + env.layer.disable(); + env.layer.enable(env.viewer); + const writes = env.set('lines').writes; + await settle(); // A's stale catch/finally runs here, after B began. + // C: the layer still reports a load in flight, so update() must not + // start a third load. + void env.layer.update(env.viewer); + await settle(); + assert.equal( + deferred.pending.filter((entry) => !entry.settled).length, + 1, + "only load B's fetch remains in flight — no duplicate load C", + ); + deferred.releaseAll(); + await settle(); + assert.equal(env.set('lines').writes, writes + 1, 'drawn exactly once'); + assert.equal(env.layer.getStats().error, null); + assert.equal(env.layer.getStats().count, 2); + } finally { + env.layer.destroy(); + } +}); + +test('destroy mid-load stays clean and a re-enabled layer reloads exactly once', async () => { + const deferred = deferredSource(); + const env = createCableHarness({ source: deferred.source }); + try { + env.layer.enable(env.viewer); + assert.equal(deferred.pending.length, 1); + const first = env.set('lines'); + env.layer.destroy(); + assert.equal(first.disposed, true); + const firstWrites = first.writes; + // Legacy contract: the layer supports re-init after destroy. Enable D + // before A's aborted rejection lands. + env.layer.enable(env.viewer); + await settle(); + void env.layer.update(env.viewer); + await settle(); + assert.equal( + deferred.pending.filter((entry) => !entry.settled).length, + 1, + "only load D's fetch remains in flight", + ); + deferred.releaseAll(); + await settle(); + assert.equal(first.writes, firstWrites, 'the destroyed load drew nothing'); + assert.equal(env.set('lines').writes, 1, 'the re-enable drew once'); + assert.equal(env.layer.getStats().count, 2); + } finally { + env.layer.destroy(); } }); @@ -1797,105 +1106,160 @@ function multipartCableFixture() { ]; } -function geometrySource(cables, landingPoints = []) { - return { - label: 'Multipart test source', - async fetch() { - return { - cables: { type: 'FeatureCollection', features: cables }, - landingPoints: { type: 'FeatureCollection', features: landingPoints }, - }; - }, - }; -} - -test('multipart association accepts frozen provider collections without modifying properties', async () => { - const payload = { - cables: { type: 'FeatureCollection', features: multipartCableFixture() }, - landingPoints: { - type: 'FeatureCollection', - features: multipartCableFixture(), - }, - }; - payload.cables.features[0].properties.__gevSourceFeatureIndex = - 'provider value'; - const before = structuredClone(payload); - const freeze = (value) => { - if (value && typeof value === 'object') { - for (const child of Object.values(value)) freeze(child); - Object.freeze(value); - } - return value; - }; - freeze(payload); - const env = await createRealCableLayerHarness({ - source: { label: 'Frozen multipart source', fetch: async () => payload }, +/** What a click on each item of a set names. */ +const picksOf = (env, name) => + [...env.set(name).items.keys()].map((id) => { + let info = null; + const before = env.flights.length; + env.click({ set: env.set(name).spec.id, id }); + if (env.flights.length > before) info = env.flights.at(-1).destination; + return info; }); - try { - for (const dataSource of env.dataSources.slice(0, 2)) { - assert.deepEqual( - dataSource.entities.values.map( - (entity) => cablePicks.read(entity)?.info.label, - ), - ['Alpha cable', 'Alpha cable', 'Alpha cable', 'Beta cable'], - ); - } - assert.equal(env.dataSources[2].entities.values.length, 4); - assert.deepEqual(payload, before); - const entity = env.dataSources[0].entities.values[0]; - assert.equal(entity.properties.__gevSourceFeatureIndex.getValue(), 0); - assert.match(entity.description.getValue(), /__gevSourceFeatureIndex/); - } finally { - env.layer.destroy(env.viewer); - } -}); -test('multipart cables retain their own styling, picking and culling on every segment', async () => { +test('multipart cables keep their own styling, picking and culling on every segment', async () => { const features = multipartCableFixture(); const before = JSON.stringify(features); - const env = await createRealCableLayerHarness({ - source: geometrySource(features), - }); - try { - const entities = env.dataSources[0].entities.values; - assert.equal(entities.length, 4); - for (const [index, entity] of entities.entries()) { - const feature = features[index < 3 ? 0 : 1]; - const info = cablePicks.read(entity)?.info; - assert.equal(info?.label, feature.properties.name, entity.id); - assert.deepEqual(info.reference, { - lon: feature.properties.coordinates[0], - lat: feature.properties.coordinates[1], - }); - assert.deepEqual( - entity.polyline.material.color.getValue(), - Cesium.Color.fromCssColorString(feature.properties.color).withAlpha( - 0.92, - ), - ); - assert.equal(entity.polyline.width.getValue(), 2.5); - } - env.raiseSweep(); - assert.deepEqual( - entities.map((entity) => entity.show), - [true, true, true, false], - ); - assert.equal( - env.dataSources[2].entities.values.length, - 2, - 'one reference per feature', - ); - assert.equal( - JSON.stringify(features), - before, - 'source features stay unchanged', - ); - } finally { - env.layer.destroy(env.viewer); + const env = createCableHarness({ source: geometrySource(features) }); + await env.load(); + const lines = [...env.set('lines').items.values()]; + assert.equal(lines.length, 4); + for (const [index, line] of lines.entries()) { + const feature = features[index < 3 ? 0 : 1]; + const hex = Number.parseInt(feature.properties.color.slice(1), 16); + assert.deepEqual(line.style.color, [ + ((hex >> 16) & 255) / 255, + ((hex >> 8) & 255) / 255, + (hex & 255) / 255, + 0.92, + ]); + assert.equal(line.widthPx, 2.5); } + assert.deepEqual(picksOf(env, 'lines'), [ + { lon: -40, lat: 35, height: 6500 }, + { lon: -40, lat: 35, height: 6500 }, + { lon: -40, lat: 35, height: 6500 }, + { lon: 140, lat: -35, height: 6500 }, + ]); + // Culled by the feature's reference: Beta is on the far side. + assert.deepEqual( + lines.map((line) => line.show), + [true, true, true, false], + ); + env.raiseSweep(); + assert.deepEqual( + [...env.set('lines').items.values()].map((line) => line.show), + [true, true, true, false], + ); + // Turning the globe brings Beta round and sends Alpha away: only the + // lines that changed are sent. + env.setEye(140, -35, 4_500_000); + env.moveEnd(); + const writes = env.set('lines').writes; + env.raiseSweep(); + assert.equal(env.set('lines').writes, writes + 1); + assert.deepEqual( + [...env.set('lines').items.values()].map((line) => line.show), + [false, false, false, true], + ); + assert.equal(env.set('references').items.size, 2, 'one per feature'); + assert.equal(JSON.stringify(features), before, 'features stay unchanged'); + env.layer.destroy(); }); -test('multipart association supports missing and repeated IDs without guessing Cesium suffixes', async () => { +test('landing geometry keeps every pick, its GeoJSON styling and one reference per feature', async () => { + const features = multipartCableFixture(); + features[1].properties.stroke = '#00ff00'; + features[1].properties['stroke-width'] = 4; + const env = createCableHarness({ source: geometrySource([], features) }); + await env.load(); + const lines = [...env.set('lines').items.values()]; + assert.equal(lines.length, 4); + assert.ok(lines.every((line) => line.clampTo === 'both')); + assert.deepEqual(lines[0].style.color, [0x8f / 255, 1, 0xd2 / 255, 0.9]); + assert.equal(lines[0].widthPx, 2); + assert.deepEqual(lines[3].style.color, [0, 1, 0, 1]); + assert.equal(lines[3].widthPx, 4); + assert.equal(env.set('references').items.size, 2); + assert.ok( + [...env.set('references').items.keys()].every((id) => + id.startsWith('landing-point-reference-'), + ), + ); + env.layer.destroy(); +}); + +test('polygons and reference-less features draw as the GeoJSON loader drew them', async () => { + const square = (lon, lat, height) => + [ + [lon, lat], + [lon + 1, lat], + [lon + 1, lat + 1], + [lon, lat + 1], + [lon, lat], + ].map((c) => (height === undefined ? c : [...c, height])); + const landings = [ + { + type: 'Feature', + properties: { id: 'plain', name: 'Plain' }, + geometry: { type: 'Polygon', coordinates: [square(-40, 35)] }, + }, + { + type: 'Feature', + properties: { id: 'red', name: 'Red', fill: '#ff0000' }, + geometry: { type: 'Polygon', coordinates: [square(-38, 35)] }, + }, + { + type: 'Feature', + properties: { id: 'solid', name: 'Solid', 'fill-opacity': 1 }, + geometry: { type: 'Polygon', coordinates: [square(-36, 35)] }, + }, + { + type: 'Feature', + properties: { id: 'raised', name: 'Raised', stroke: '#0000ff' }, + geometry: { type: 'Polygon', coordinates: [square(-34, 35, 500)] }, + }, + { + type: 'Feature', + properties: { name: 'Collection' }, + geometry: { + type: 'GeometryCollection', + geometries: [ + { + type: 'LineString', + coordinates: [ + [-30, 35], + [-29, 36], + ], + }, + ], + }, + }, + ]; + const env = createCableHarness({ source: geometrySource([], landings) }); + await env.load(); + const fills = [...env.set('fills').items.values()]; + assert.equal(fills.length, 4); + const landing = [0x8f / 255, 1, 0xd2 / 255]; + // The fill keeps the source's alpha; fill-opacity replaces it. + assert.deepEqual(fills[0].fill, [...landing, 0.35]); + assert.deepEqual(fills[1].fill, [1, 0, 0, 0.35]); + assert.deepEqual(fills[2].fill, [...landing, 1]); + assert.ok(fills.slice(0, 3).every((fill) => fill.height === 'clampGround')); + // Heights keep a polygon off the ground, outlined in its stroke. + assert.equal(fills[3].height, 'absolute'); + assert.equal(fills[3].geometry.perPositionHeight, true); + assert.deepEqual(fills[3].outline, [0, 0, 1, 1]); + assert.equal(fills[3].geometry.rings[0].length, 5); + // A feature with no reference still draws, unpicked and with no reference. + const lines = [...env.set('lines').items.values()]; + assert.equal(lines.length, 1); + assert.deepEqual(lines[0].style.color, [...landing, 0.9]); + assert.equal(env.set('references').items.size, 4); + assert.deepEqual(picksOf(env, 'lines'), [null]); + env.layer.destroy(); +}); + +test('reference ids follow the features, missing and repeated ids included', async () => { const features = multipartCableFixture(); features[1].id = 'alpha_2'; delete features[1].properties.id; @@ -1907,60 +1271,22 @@ test('multipart association supports missing and repeated IDs without guessing C repeated.properties.id = 'alpha'; repeated.properties.name = 'Repeated ID cable'; features.push(repeated); - const env = await createRealCableLayerHarness({ - source: geometrySource(features), - }); - try { - const entities = env.dataSources[0].entities.values; - assert.deepEqual( - entities.map((entity) => entity.id), - ['alpha', 'alpha_2', 'alpha_3', 'alpha_2_2', 'cable-2', 'alpha_4'], - ); - assert.deepEqual( - entities.map((entity) => cablePicks.read(entity)?.info.label), - [ - 'Alpha cable', - 'Alpha cable', - 'Alpha cable', - 'Beta cable', - 'Generated cable', - 'Repeated ID cable', - ], - ); - assert.deepEqual( - env.dataSources[2].entities.values.map( - (entity) => cablePicks.read(entity)?.info.featureId, - ), - ['alpha', 'alpha_2', 'cable-2', 'alpha'], - ); - } finally { - env.layer.destroy(env.viewer); - } + const env = createCableHarness({ source: geometrySource(features) }); + await env.load(); + assert.deepEqual( + [...env.set('references').items.keys()], + [ + 'cable-reference-0-alpha', + 'cable-reference-1-alpha_2', + 'cable-reference-2-cable-2', + 'cable-reference-3-alpha', + ], + ); + assert.equal(env.set('lines').items.size, 6); + env.layer.destroy(); }); -test('multipart landing geometry keeps every pick with one reference per feature', async () => { - const features = multipartCableFixture(); - const env = await createRealCableLayerHarness({ - source: geometrySource([], features), - }); - try { - const entities = env.dataSources[1].entities.values; - assert.deepEqual( - entities.map((entity) => cablePicks.read(entity)?.info.label), - ['Alpha cable', 'Alpha cable', 'Alpha cable', 'Beta cable'], - ); - assert.ok( - entities.every( - (entity) => cablePicks.read(entity)?.info.kind === 'landing-point', - ), - ); - assert.equal(env.dataSources[2].entities.values.length, 2); - } finally { - env.layer.destroy(env.viewer); - } -}); - -test('every bundled cable segment is associated with its source feature', async () => { +test('every bundled cable segment is drawn with its source feature', async () => { const { features } = JSON.parse( readFileSync( new URL( @@ -1970,31 +1296,22 @@ test('every bundled cable segment is associated with its source feature', async 'utf8', ), ); - // Some bundled features share a cable ID but have different references. const expandedFeatures = features.flatMap((feature) => feature.geometry.coordinates.map(() => feature), ); assert.ok(expandedFeatures.length > features.length); - const env = await createRealCableLayerHarness({ - source: geometrySource(features), - }); - try { - const entities = env.dataSources[0].entities.values; - assert.equal(entities.length, expandedFeatures.length); - for (const [index, entity] of entities.entries()) { - const feature = expandedFeatures[index]; - assert.equal( - cablePicks.read(entity)?.info.label, - feature.properties.name, - entity.id, - ); - assert.deepEqual(cablePicks.read(entity)?.info.reference, { - lon: feature.properties.coordinates[0], - lat: feature.properties.coordinates[1], - }); - } - assert.equal(env.dataSources[2].entities.values.length, features.length); - } finally { - env.layer.destroy(env.viewer); + const env = createCableHarness({ source: geometrySource(features) }); + await env.load(); + const lineSet = env.set('lines'); + assert.equal(lineSet.items.size, expandedFeatures.length); + const destinations = picksOf(env, 'lines'); + for (const [index, feature] of expandedFeatures.entries()) { + assert.deepEqual(destinations[index], { + lon: feature.properties.coordinates[0], + lat: feature.properties.coordinates[1], + height: 6500, + }); } + assert.equal(env.set('references').items.size, features.length); + env.layer.destroy(); }); diff --git a/src/geo/geodesic.js b/src/geo/geodesic.js new file mode 100644 index 000000000..d33c1ea8c --- /dev/null +++ b/src/geo/geodesic.js @@ -0,0 +1,150 @@ +/** + * @module geo/geodesic + * @description Surface distance along the WGS84 geodesic between two + * points, by the default renderer's own method (`EllipsoidGeodesic`, + * Vincenty's inverse formula): the same series in the same order, so the + * distance agrees with the renderer's to floating-point noise. Angles in + * radians, distances in metres. + */ +import { WGS84 } from './ellipsoid.js'; + +const MAJOR = WGS84.radii.x; +const MINOR = WGS84.radii.z; +const FLATTENING = (MAJOR - MINOR) / MAJOR; +const EPSILON12 = 1e-12; +/** + * Vincenty converges in a handful of steps except between nearly antipodal + * points, where it may not converge at all; stop there instead of hanging. + */ +const MAX_ITERATIONS = 200; + +/** Vincenty's longitude correction, shared with the direct series. */ +export function deltaLambda( + sineAlpha, + cosineSquaredAlpha, + sigma, + sineSigma, + cosineSigma, + cosineTwiceSigmaMidpoint, +) { + const f = FLATTENING; + const C = + (f * cosineSquaredAlpha * (4.0 + f * (4.0 - 3.0 * cosineSquaredAlpha))) / + 16.0; + return ( + (1.0 - C) * + f * + sineAlpha * + (sigma + + C * + sineSigma * + (cosineTwiceSigmaMidpoint + + C * + cosineSigma * + (2.0 * cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint - 1.0))) + ); +} + +/** + * Vincenty's inverse: the geodesic from (lon1, lat1) to (lon2, lat2), + * radians, as its length in metres, its start heading and its u². + */ +export function geodesicInverse(lon1, lat1, lon2, lat2) { + const l = lon2 - lon1; + const u1 = Math.atan((1 - FLATTENING) * Math.tan(lat1)); + const u2 = Math.atan((1 - FLATTENING) * Math.tan(lat2)); + const cosineU1 = Math.cos(u1); + const sineU1 = Math.sin(u1); + const cosineU2 = Math.cos(u2); + const sineU2 = Math.sin(u2); + const cc = cosineU1 * cosineU2; + const cs = cosineU1 * sineU2; + const ss = sineU1 * sineU2; + const sc = sineU1 * cosineU2; + + let lambda = l; + let lambdaDot; + let cosineLambda; + let sineLambda; + let sigma; + let cosineSigma; + let sineSigma; + let cosineSquaredAlpha; + let cosineTwiceSigmaMidpoint; + let iterations = 0; + do { + cosineLambda = Math.cos(lambda); + sineLambda = Math.sin(lambda); + const temp = cs - sc * cosineLambda; + sineSigma = Math.sqrt( + cosineU2 * cosineU2 * sineLambda * sineLambda + temp * temp, + ); + cosineSigma = ss + cc * cosineLambda; + sigma = Math.atan2(sineSigma, cosineSigma); + let sineAlpha; + if (sineSigma === 0.0) { + sineAlpha = 0.0; + cosineSquaredAlpha = 1.0; + } else { + sineAlpha = (cc * sineLambda) / sineSigma; + cosineSquaredAlpha = 1.0 - sineAlpha * sineAlpha; + } + lambdaDot = lambda; + cosineTwiceSigmaMidpoint = cosineSigma - (2.0 * ss) / cosineSquaredAlpha; + if (!isFinite(cosineTwiceSigmaMidpoint)) cosineTwiceSigmaMidpoint = 0.0; + lambda = + l + + deltaLambda( + sineAlpha, + cosineSquaredAlpha, + sigma, + sineSigma, + cosineSigma, + cosineTwiceSigmaMidpoint, + ); + } while ( + Math.abs(lambda - lambdaDot) > EPSILON12 && + ++iterations < MAX_ITERATIONS + ); + + const uSquared = + (cosineSquaredAlpha * (MAJOR * MAJOR - MINOR * MINOR)) / (MINOR * MINOR); + const A = + 1.0 + + (uSquared * + (4096.0 + uSquared * (uSquared * (320.0 - 175.0 * uSquared) - 768.0))) / + 16384.0; + const B = + (uSquared * + (256.0 + uSquared * (uSquared * (74.0 - 47.0 * uSquared) - 128.0))) / + 1024.0; + const cosineSquaredTwiceSigmaMidpoint = + cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint; + const deltaSigma = + B * + sineSigma * + (cosineTwiceSigmaMidpoint + + (B * + (cosineSigma * (2.0 * cosineSquaredTwiceSigmaMidpoint - 1.0) - + (B * + cosineTwiceSigmaMidpoint * + (4.0 * sineSigma * sineSigma - 3.0) * + (4.0 * cosineSquaredTwiceSigmaMidpoint - 3.0)) / + 6.0)) / + 4.0); + return { + distance: MINOR * A * (sigma - deltaSigma), + startHeading: Math.atan2(cosineU2 * sineLambda, cs - sc * cosineLambda), + uSquared, + }; +} + +/** + * Geodesic surface distance between two points; heights are ignored. + * @param {{lon: number, lat: number}} start Radians. + * @param {{lon: number, lat: number}} end Radians. + * @returns {number} Metres. + */ +export function surfaceDistance(start, end) { + return geodesicInverse(start.lon, start.lat, end.lon, end.lat).distance; +} diff --git a/src/geo/geodesic.test.mjs b/src/geo/geodesic.test.mjs new file mode 100644 index 000000000..9d9df6914 --- /dev/null +++ b/src/geo/geodesic.test.mjs @@ -0,0 +1,47 @@ +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import test from 'node:test'; +import { surfaceDistance } from './geodesic.js'; + +test('surface distance matches the default renderer’s geodesic', () => { + let seed = 11; + const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647; + const d = Math.PI / 180; + const geodesic = new Cesium.EllipsoidGeodesic(); + for (let i = 0; i < 400; i++) { + const start = { + lon: (random() * 360 - 180) * d, + lat: (random() * 170 - 85) * d, + }; + // Near pairs, as a nearby-sites query asks, and far ones short of antipodal. + const reach = i % 2 ? 2 : 120; + const end = { + lon: start.lon + (random() * 2 - 1) * reach * d, + lat: + Math.max( + -89, + Math.min(89, start.lat / d + (random() * 2 - 1) * reach), + ) * d, + }; + geodesic.setEndPoints( + new Cesium.Cartographic(start.lon, start.lat, 0), + new Cesium.Cartographic(end.lon, end.lat, 0), + ); + const expected = geodesic.surfaceDistance; + assert.ok( + Math.abs(surfaceDistance(start, end) - expected) <= + 1e-9 * Math.max(1, expected), + `${i}: ${surfaceDistance(start, end)} vs ${expected}`, + ); + } +}); + +test('the same point is no distance away, and nearly antipodal points still answer', () => { + const p = { lon: 0.3, lat: 0.7 }; + assert.equal(surfaceDistance(p, p), 0); + const far = surfaceDistance( + { lon: 0, lat: 0 }, + { lon: Math.PI - 1e-9, lat: 0 }, + ); + assert.ok(Number.isFinite(far) && far > 1.9e7); +}); diff --git a/src/geo/horizon.js b/src/geo/horizon.js new file mode 100644 index 000000000..f6c7cff57 --- /dev/null +++ b/src/geo/horizon.js @@ -0,0 +1,34 @@ +/** + * @module geo/horizon + * @description Whether a point is beyond the WGS84 ellipsoid's horizon from + * an eye, by the default renderer's own test (`EllipsoidalOccluder`), so + * code that culls by it agrees with what the renderer culls. + */ +import { WGS84 } from './ellipsoid.js'; + +/** + * A horizon test from `eye` (ECEF): `isPointVisible(p)` is false for a + * point the ellipsoid hides from it. + */ +export function horizonFrom(eye) { + const o = WGS84.oneOverRadii; + const cx = eye.x * o.x; + const cy = eye.y * o.y; + const cz = eye.z * o.z; + const limbSquared = cx * cx + cy * cy + cz * cz - 1; + return { + isPointVisible(p) { + const tx = p.x * o.x - cx; + const ty = p.y * o.y - cy; + const tz = p.z * o.z - cz; + const along = -(tx * cx + ty * cy + tz * cz); + // Inside the ellipsoid the plane through the eye culls instead. + const occluded = + limbSquared < 0 + ? along > 0 + : along > limbSquared && + (along * along) / (tx * tx + ty * ty + tz * tz) > limbSquared; + return !occluded; + }, + }; +} diff --git a/src/geo/horizon.test.mjs b/src/geo/horizon.test.mjs new file mode 100644 index 000000000..aa283a1a0 --- /dev/null +++ b/src/geo/horizon.test.mjs @@ -0,0 +1,33 @@ +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import test from 'node:test'; +import { fromDegrees } from './ellipsoid.js'; +import { horizonFrom } from './horizon.js'; + +test('the horizon hides what the default renderer’s occluder hides', () => { + let seed = 3; + const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647; + for (let i = 0; i < 30; i++) { + const eye = fromDegrees( + random() * 360 - 180, + random() * 170 - 85, + i === 0 ? -100 : random() * 2e7, + ); + const occluder = new Cesium.EllipsoidalOccluder( + Cesium.Ellipsoid.WGS84, + new Cesium.Cartesian3(eye.x, eye.y, eye.z), + ); + const horizon = horizonFrom(eye); + for (let k = 0; k < 50; k++) { + const p = fromDegrees( + random() * 360 - 180, + random() * 180 - 90, + random() * 1e5, + ); + assert.equal( + horizon.isPointVisible(p), + occluder.isPointVisible(new Cesium.Cartesian3(p.x, p.y, p.z)), + ); + } + } +}); diff --git a/src/geo/rhumb.js b/src/geo/rhumb.js new file mode 100644 index 000000000..8cd02a8be --- /dev/null +++ b/src/geo/rhumb.js @@ -0,0 +1,221 @@ +/** + * @module geo/rhumb + * @description Rhumb lines on the WGS84 ellipsoid, by the default + * renderer's own method (`EllipsoidRhumbLine`): the same series in the same + * order, so points along one land where the renderer put them. Angles in + * radians, distances in metres. + */ +import { WGS84 } from './ellipsoid.js'; +import { negativePiToPi } from './vector.js'; + +const MAJOR = WGS84.radii.x; +const MINOR = WGS84.radii.z; +const E2 = (MAJOR * MAJOR - MINOR * MINOR) / (MAJOR * MAJOR); +const E = Math.sqrt(E2); +const HALF_PI = Math.PI / 2; +const EPSILON8 = 1e-8; +const EPSILON10 = 1e-10; + +/** Meridian distance from the equator to `phi`. */ +function meridian(phi) { + const e2 = E2; + const e4 = e2 * e2; + const e6 = e4 * e2; + const e8 = e6 * e2; + const e10 = e8 * e2; + const e12 = e10 * e2; + return ( + MAJOR * + ((1 - + e2 / 4 - + (3 * e4) / 64 - + (5 * e6) / 256 - + (175 * e8) / 16384 - + (441 * e10) / 65536 - + (4851 * e12) / 1048576) * + phi - + ((3 * e2) / 8 + + (3 * e4) / 32 + + (45 * e6) / 1024 + + (105 * e8) / 4096 + + (2205 * e10) / 131072 + + (6237 * e12) / 524288) * + Math.sin(2 * phi) + + ((15 * e4) / 256 + + (45 * e6) / 1024 + + (525 * e8) / 16384 + + (1575 * e10) / 65536 + + (155925 * e12) / 8388608) * + Math.sin(4 * phi) - + ((35 * e6) / 3072 + + (175 * e8) / 12288 + + (3675 * e10) / 262144 + + (13475 * e12) / 1048576) * + Math.sin(6 * phi) + + ((315 * e8) / 131072 + (2205 * e10) / 524288 + (43659 * e12) / 8388608) * + Math.sin(8 * phi) - + ((693 * e10) / 1310720 + (6237 * e12) / 5242880) * Math.sin(10 * phi) + + ((1001 * e12) / 8388608) * Math.sin(12 * phi)) + ); +} + +/** The latitude a meridian distance `m` reaches. */ +function inverseMeridian(m) { + const d = m / MAJOR; + const d2 = d * d; + const d3 = d2 * d; + const d4 = d3 * d; + const e2 = E2; + const e4 = e2 * e2; + const e6 = e4 * e2; + const e8 = e6 * e2; + const e10 = e8 * e2; + const e12 = e10 * e2; + return ( + d + + (d * e2) / 4 + + (7 * d * e4) / 64 + + (15 * d * e6) / 256 + + (579 * d * e8) / 16384 + + (1515 * d * e10) / 65536 + + (16837 * d * e12) / 1048576 + + ((3 * d * e4) / 16 + + (45 * d * e6) / 256 - + (d * (32 * d2 - 561) * e8) / 4096 - + (d * (232 * d2 - 1677) * e10) / 16384 + + (d * (399985 - 90560 * d2 + 512 * d4) * e12) / 5242880) * + Math.cos(2 * d) + + ((21 * d * e6) / 256 + + (483 * d * e8) / 4096 - + (d * (224 * d2 - 1969) * e10) / 16384 - + (d * (33152 * d2 - 112599) * e12) / 1048576) * + Math.cos(4 * d) + + ((151 * d * e8) / 4096 + + (4681 * d * e10) / 65536 + + (1479 * d * e12) / 16384 - + (453 * d3 * e12) / 32768) * + Math.cos(6 * d) + + ((1097 * d * e10) / 65536 + (42783 * d * e12) / 1048576) * Math.cos(8 * d) + + ((8011 * d * e12) / 1048576) * Math.cos(10 * d) + + ((3 * e2) / 8 + + (3 * e4) / 16 + + (213 * e6) / 2048 - + (3 * d2 * e6) / 64 + + (255 * e8) / 4096 - + (33 * d2 * e8) / 512 + + (20861 * e10) / 524288 - + (33 * d2 * e10) / 512 + + (d4 * e10) / 1024 + + (28273 * e12) / 1048576 - + (471 * d2 * e12) / 8192 + + (9 * d4 * e12) / 4096) * + Math.sin(2 * d) + + ((21 * e4) / 256 + + (21 * e6) / 256 + + (533 * e8) / 8192 - + (21 * d2 * e8) / 512 + + (197 * e10) / 4096 - + (315 * d2 * e10) / 4096 + + (584039 * e12) / 16777216 - + (12517 * d2 * e12) / 131072 + + (7 * d4 * e12) / 2048) * + Math.sin(4 * d) + + ((151 * e6) / 6144 + + (151 * e8) / 4096 + + (5019 * e10) / 131072 - + (453 * d2 * e10) / 16384 + + (26965 * e12) / 786432 - + (8607 * d2 * e12) / 131072) * + Math.sin(6 * d) + + ((1097 * e8) / 131072 + + (1097 * e10) / 65536 + + (225797 * e12) / 10485760 - + (1097 * d2 * e12) / 65536) * + Math.sin(8 * d) + + ((8011 * e10) / 2621440 + (8011 * e12) / 1048576) * Math.sin(10 * d) + + ((293393 * e12) / 251658240) * Math.sin(12 * d) + ); +} + +/** Isometric latitude. */ +function sigma(latitude) { + const eSinL = E * Math.sin(latitude); + return ( + Math.log(Math.tan(0.5 * (HALF_PI + latitude))) - + (E / 2) * Math.log((1 + eSinL) / (1 - eSinL)) + ); +} + +/** Radius of the parallel at `latitude`. */ +function parallelRadius(latitude) { + const sinPhi = Math.sin(latitude); + return (MAJOR * Math.cos(latitude)) / Math.sqrt(1 - E2 * sinPhi * sinPhi); +} + +/** + * The rhumb line from `start` to `end` (`{lon, lat}` radians): its heading + * (radians from north), its length, and the point a distance along it. + */ +export function rhumbLine(start, end) { + const heading = Math.atan2( + negativePiToPi(end.lon - start.lon), + sigma(end.lat) - sigma(start.lat), + ); + // Near due east or west the series diverge: such a line follows its + // parallel. Its length and its points decide that as the renderer does. + const offEast = Math.abs(Math.abs(heading) - HALF_PI); + const measuredAlongParallel = + offEast <= Math.max(EPSILON8, EPSILON8 * HALF_PI); + const alongParallel = !(offEast > EPSILON8); + const distance = Math.abs( + measuredAlongParallel + ? parallelRadius(start.lat) * negativePiToPi(end.lon - start.lon) + : (meridian(end.lat) - meridian(start.lat)) / Math.cos(heading), + ); + return { + heading, + distance, + /** The point `metres` along the line from its start. */ + at(metres) { + if (metres === 0) return { lon: start.lon, lat: start.lat }; + if (alongParallel) { + const delta = metres / parallelRadius(start.lat); + return { + lon: negativePiToPi(start.lon + (heading > 0 ? delta : -delta)), + lat: start.lat, + }; + } + const lat = inverseMeridian( + meridian(start.lat) + metres * Math.cos(heading), + ); + const lon = + Math.abs(heading) < EPSILON10 + ? negativePiToPi(start.lon) + : negativePiToPi( + start.lon + Math.tan(heading) * (sigma(lat) - sigma(start.lat)), + ); + return { lon, lat }; + }, + }; +} + +/** + * The points along a path's rhumb lines no more than `granularity` metres + * apart, as a renderer drawing the path along rhumb lines places them: each + * leg of `distance` split into `ceil(distance / granularity)` equal parts. + * Takes and gives `{lon, lat}` in radians; the path's own points are kept. + */ +export function densifyRhumb(points, granularity = 9999) { + if (points.length < 2) return points.slice(); + const out = [points[0]]; + for (let i = 1; i < points.length; i++) { + const line = rhumbLine(points[i - 1], points[i]); + if (line.distance >= granularity) { + const parts = Math.ceil(line.distance / granularity); + const step = line.distance / parts; + for (let k = 1; k < parts; k++) out.push(line.at(step * k)); + } + out.push(points[i]); + } + return out; +} diff --git a/src/geo/rhumb.test.mjs b/src/geo/rhumb.test.mjs new file mode 100644 index 000000000..5112d4c4b --- /dev/null +++ b/src/geo/rhumb.test.mjs @@ -0,0 +1,79 @@ +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import test from 'node:test'; +import { densifyRhumb, rhumbLine } from './rhumb.js'; + +const d = Math.PI / 180; + +test('a rhumb line is the default renderer’s, length and points', () => { + let seed = 11; + const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647; + const cases = [ + [ + [-40, 35], + [-30, 40], + ], + [ + [170, -10], + [-170, 12], + ], + [ + [10, 20], + [60, 20], + ], + [ + [5, -60], + [5, 70], + ], + ]; + for (let i = 0; i < 40; i++) + cases.push([ + [random() * 360 - 180, random() * 160 - 80], + [random() * 360 - 180, random() * 160 - 80], + ]); + for (const [[lonA, latA], [lonB, latB]] of cases) { + const start = { lon: lonA * d, lat: latA * d }; + const end = { lon: lonB * d, lat: latB * d }; + let cesium; + try { + cesium = new Cesium.EllipsoidRhumbLine( + new Cesium.Cartographic(start.lon, start.lat), + new Cesium.Cartographic(end.lon, end.lat), + ); + } catch { + continue; // antipodal: the renderer refuses it too + } + const line = rhumbLine(start, end); + assert.ok( + Math.abs(line.distance - cesium.surfaceDistance) <= + 1e-9 * cesium.surfaceDistance + 1e-6, + `${lonA},${latA} → ${lonB},${latB}`, + ); + assert.ok(Math.abs(line.heading - cesium.heading) < 1e-12); + for (const f of [0.1, 0.5, 0.9]) { + const ours = line.at(line.distance * f); + const theirs = cesium.interpolateUsingSurfaceDistance( + cesium.surfaceDistance * f, + ); + assert.ok(Math.abs(ours.lon - theirs.longitude) < 1e-12); + assert.ok(Math.abs(ours.lat - theirs.latitude) < 1e-12); + } + } +}); + +test('a densified path keeps its points and spaces the rest under the granularity', () => { + const path = [ + { lon: -40 * d, lat: 35 * d }, + { lon: -39.95 * d, lat: 35 * d }, + { lon: -30 * d, lat: 40 * d }, + ]; + const dense = densifyRhumb(path, 9999); + assert.equal(dense[0], path[0]); + assert.equal(dense[1], path[1], 'a short leg adds nothing'); + assert.equal(dense.at(-1), path[2]); + const leg = rhumbLine(path[1], path[2]); + assert.equal(dense.length, 2 + Math.ceil(leg.distance / 9999)); + for (let i = 2; i < dense.length; i++) + assert.ok(rhumbLine(dense[i - 1], dense[i]).distance < 9999); + assert.deepEqual(densifyRhumb([path[0]]), [path[0]]); +}); diff --git a/src/layers/submarineCables/geometry.js b/src/layers/submarineCables/geometry.js index b4b434710..8c8c29deb 100644 --- a/src/layers/submarineCables/geometry.js +++ b/src/layers/submarineCables/geometry.js @@ -77,3 +77,43 @@ export function normalizeFeatures(json, kind) { }; }); } + +/** + * A GeoJSON geometry's drawable parts, as GeoJSON sources have always been + * drawn: each line string, point and polygon on its own (multi-geometries + * and collections split into their members). Coordinates stay + * `[lon, lat, height?]` degrees. + * @returns {{lines: number[][][], points: number[][], polygons: number[][][][]}} + */ +export function geometryParts( + geometry, + out = { lines: [], points: [], polygons: [] }, +) { + if (!geometry) return out; + const coords = geometry.coordinates; + switch (geometry.type) { + case 'Point': + out.points.push(coords); + break; + case 'MultiPoint': + for (const point of coords) out.points.push(point); + break; + case 'LineString': + out.lines.push(coords); + break; + case 'MultiLineString': + for (const line of coords) out.lines.push(line); + break; + case 'Polygon': + out.polygons.push(coords); + break; + case 'MultiPolygon': + for (const polygon of coords) out.polygons.push(polygon); + break; + case 'GeometryCollection': + for (const member of geometry.geometries ?? []) + geometryParts(member, out); + break; + } + return out; +} diff --git a/src/layers/submarineCables/index.js b/src/layers/submarineCables/index.js index c786e272c..e38e69bf3 100644 --- a/src/layers/submarineCables/index.js +++ b/src/layers/submarineCables/index.js @@ -41,7 +41,6 @@ export { export { cableClassificationTypeForStack, cableClassificationTypeForScene, - applyTranslucentMarkerBlend, } from './surface.js'; export { CABLE_REFERENCE_LABEL_WINNER_CAP, diff --git a/src/layers/submarineCables/ingestion.js b/src/layers/submarineCables/ingestion.js index 23bc4c735..9cc1a090f 100644 --- a/src/layers/submarineCables/ingestion.js +++ b/src/layers/submarineCables/ingestion.js @@ -1,25 +1,5 @@ import { msg, t } from '../../i18n/index.js'; -import { - featureLabel, - featureReference, - normalizeFeatures, -} from './geometry.js'; -import * as Cesium from 'cesium'; - -const SOURCE_FEATURE_INDEX = '__gevSourceFeatureIndex'; - -function indexedCollection(features) { - return { - type: 'FeatureCollection', - features: features.map((feature, index) => ({ - ...feature, - properties: { - ...feature.properties, - [SOURCE_FEATURE_INDEX]: index, - }, - })), - }; -} +import { normalizeFeatures } from './geometry.js'; export function createIngestion({ state, parts, source }) { async function load(viewer) { @@ -31,9 +11,9 @@ export function createIngestion({ state, parts, source }) { // Ownership token (the militaryAwareness activationId pattern): a // disable/abort followed by a fresh enable starts a NEWER load while this // one is still settling. The stale load must bail after every await and - // must never touch shared lifecycle state or the viewer it no longer + // must never touch shared lifecycle state or the sets it no longer // owns — clearing `_loading`/`_abort` for the successor is how duplicate - // or post-destroy data sources got added. + // loads got drawn. const generation = ++state._loadGeneration; const abort = new AbortController(); state._abort = abort; @@ -63,146 +43,10 @@ export function createIngestion({ state, parts, source }) { const cableFeatures = normalizeFeatures(cableJson, 'cable'); const landingFeatures = normalizeFeatures(landingJson, 'landing'); - const cableDataSource = await Cesium.GeoJsonDataSource.load( - indexedCollection(cableFeatures), - { - clampToGround: true, - stroke: state.cableColor.withAlpha(0.95), - fill: state.cableColor.withAlpha(0.18), - strokeWidth: 2, - markerColor: state.cableColor, - markerSize: 6, - }, - ); - if (!owns()) return; - const landingDataSource = await Cesium.GeoJsonDataSource.load( - indexedCollection(landingFeatures), - { - clampToGround: true, - stroke: state.landingColor.withAlpha(0.9), - fill: state.landingColor.withAlpha(0.35), - strokeWidth: 2, - markerColor: state.landingColor, - markerSize: 6, - }, - ); - if (!owns()) return; - - cableDataSource.name = `${source.label} Submarine Cables`; - landingDataSource.name = `${source.label} Landing Points`; - const referenceDataSource = new Cesium.CustomDataSource( - `${source.label} Cable References`, - ); - const addedSources = [ - cableDataSource, - landingDataSource, - referenceDataSource, - ]; - - // dataSources.add() is itself an await point: Cesium mutates the - // collection on a DEFERRED tick, so a disable/destroy racing this - // window finds nothing to remove and the adds still materialize - // afterwards. Await every add to settlement (allSettled so a partial - // failure cannot leave an unawaited add materializing later), then - // re-check ownership. Pinned teardown mechanism: disable/destroy never - // wait for in-flight adds — the stale generation's own post-await - // check here guarantees cleanup by removing exactly the sources THIS - // generation added. - const addResults = await Promise.allSettled([ - viewer.dataSources.add(cableDataSource), - viewer.dataSources.add(landingDataSource), - viewer.dataSources.add(referenceDataSource), - ]); - const rejectedAdd = addResults.find( - (result) => result.status === 'rejected', - ); - if (!owns() || rejectedAdd) { - // Compensate: every add has settled by now, so removal is effective - // (a remove inside the deferred window would have been a no-op). - // Remove EVERY generation-local source regardless of settle status: - // Cesium's add() pushes into the collection BEFORE raising - // dataSourceAdded, so a REJECTED add may still have landed its - // mutation. remove() of a never-added source is a harmless no-op. - for (const source of addedSources) { - try { - viewer.dataSources.remove(source, true); - } catch { - /* collection gone */ - } - } - if (owns() && rejectedAdd) throw rejectedAdd.reason; - return; - } - - // Await-free commit: the viewer accepted all three sources and this - // load still owns the lifecycle. - state._cableDataSource = cableDataSource; - state._landingDataSource = landingDataSource; - state._referenceDataSource = referenceDataSource; - - const cableEntities = state._cableDataSource.entities.values; - const landingEntities = state._landingDataSource.entities.values; - state._referenceRecords = []; - state._surfaceRecords = []; - - // Cesium expands multipart geometry into several entities and suffixes - // colliding IDs. Its copied properties retain this source index even - // when a provider has no ID, so every segment keeps the right owner. - const cableReferences = new Set(); - cableEntities.forEach((entity) => { - const index = entity.properties?.[SOURCE_FEATURE_INDEX]?.getValue(); - const feature = cableFeatures[index]; - const reference = featureReference(feature); - if (!reference) return; - - parts.rendering.styleCableEntity(entity, feature); - parts.interaction.registerPickEntity(entity, { - kind: 'cable', - reference, - label: featureLabel(feature), - }); - state._surfaceRecords.push({ - entity, - base: Cesium.Cartesian3.fromDegrees(reference.lon, reference.lat, 0), - }); - if (cableReferences.has(index)) return; - cableReferences.add(index); - parts.rendering.addReferenceStem({ - reference, - label: featureLabel(feature), - kind: 'cable', - color: state.cableColor, - feature, - }); - }); - - const landingReferences = new Set(); - landingEntities.forEach((entity) => { - const index = entity.properties?.[SOURCE_FEATURE_INDEX]?.getValue(); - const feature = landingFeatures[index]; - const reference = featureReference(feature); - if (!reference) return; - - parts.rendering.styleLandingEntity(entity, feature); - parts.interaction.registerPickEntity(entity, { - kind: 'landing-point', - reference, - label: featureLabel(feature), - }); - state._surfaceRecords.push({ - entity, - base: Cesium.Cartesian3.fromDegrees(reference.lon, reference.lat, 0), - }); - if (landingReferences.has(index)) return; - landingReferences.add(index); - parts.rendering.addReferenceStem({ - reference, - label: featureLabel(feature), - kind: 'landing-point', - color: state.landingColor, - feature, - }); - }); + // Await-free from here: this load still owns the lifecycle, and the + // items go into the layer's own sets in one pass. + parts.rendering.attach(viewer); + parts.rendering.drawFeatures(cableFeatures, landingFeatures); state._count = cableFeatures.length + landingFeatures.length; state._loaded = true; @@ -210,7 +54,7 @@ export function createIngestion({ state, parts, source }) { state._loadingLabel = ''; parts.rendering.updateVisibility(); state._referenceSweepGate.markDirty(); - viewer.scene.requestRender?.(); + viewer?.scene?.requestRender?.(); } catch (error) { // A stale or aborted load reports nothing: its failure belongs to a // lifecycle the user already left. diff --git a/src/layers/submarineCables/interaction.js b/src/layers/submarineCables/interaction.js index 3231aedd1..de7470da2 100644 --- a/src/layers/submarineCables/interaction.js +++ b/src/layers/submarineCables/interaction.js @@ -1,47 +1,24 @@ -import * as Cesium from 'cesium'; -import { cablePicks } from './pickState.js'; -import { cameraOf } from '../../render/cesium/camera.js'; - -export function createInteraction({ state, inputFor }) { - function registerPickEntity(entity, info) { - cablePicks.write(entity).info = info; - } +import { toRadians } from '../../geo/vector.js'; +import { cameraOf } from '../../render/rendererOf.js'; +export function createInteraction({ state, parts, inputFor }) { function beginInteraction(viewer) { if (state._clickSubscription) return; state._clickSubscription = inputFor(viewer).onClick((event) => { if (!state._enabled) return; - const record = resolvePickRecord(event.pick); + const record = resolvePickRecord(event.drawHit); if (!record?.reference) return; flyToReference(viewer, record.reference); }); } - function resolvePickRecord(picked) { - if (!picked) return null; - const primitive = picked.primitive; - if (primitive) { - const primitiveInfo = cablePicks.read(primitive)?.info; - if (primitiveInfo) return primitiveInfo; - if ( - primitive.id && - typeof primitive.id === 'object' && - primitive.id.reference - ) { - return primitive.id; - } - } - - const entity = picked.id; - if (entity) { - const entityInfo = cablePicks.read(entity)?.info; - if (entityInfo) return entityInfo; - if (entity.id && typeof entity.id === 'object' && entity.id.reference) { - return entity.id; - } - } - - return null; + /** + * What a click's draw hit names: a cable, landing point or reference of + * this layer's current items, as `{ label, kind, featureId, reference }`, + * or null. + */ + function resolvePickRecord(hit) { + return parts.rendering.pickInfo(hit); } function flyToReference(viewer, reference) { @@ -53,7 +30,7 @@ export function createInteraction({ state, inputFor }) { { orientation: { heading: camera.pose().heading || 0, - pitch: Cesium.Math.toRadians(-52), + pitch: toRadians(-52), roll: 0, }, durationS: 1.35, @@ -62,7 +39,6 @@ export function createInteraction({ state, inputFor }) { ); } return { - registerPickEntity, beginInteraction, resolvePickRecord, flyToReference, diff --git a/src/layers/submarineCables/lifecycle.js b/src/layers/submarineCables/lifecycle.js index 561d3f485..edbad8d81 100644 --- a/src/layers/submarineCables/lifecycle.js +++ b/src/layers/submarineCables/lifecycle.js @@ -1,3 +1,4 @@ +import { cameraOf } from '../../render/rendererOf.js'; import { cableClassificationTypeForScene, cableClassificationTypeForStack, @@ -14,9 +15,8 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) { init(viewer) { state._viewer = viewer; - state._classificationType = cableClassificationTypeForScene( - viewer?.scene, - ); + state._clampTo = cableClassificationTypeForScene(viewer?.scene); + parts.rendering.attach(viewer); if (!state._mapStackListener && mapStackEventTarget?.addEventListener) { state._mapStackListener = (event) => { parts.rendering.applyCableClassification( @@ -31,6 +31,12 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) { ); } parts.interaction.beginInteraction(viewer); + // The eye the sweep gate's motion probe reads, only when it probes. + const eye = { + get positionWC() { + return cameraOf(viewer).pose()?.position ?? null; + }, + }; if (!state._preRenderRemover) { state._preRenderRemover = viewer.scene.preRender.addEventListener( () => { @@ -41,7 +47,7 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) { if ( !state._enabled || !state._loaded || - !state._referenceSweepGate.shouldRun(viewer.camera) + !state._referenceSweepGate.shouldRun(eye) ) return; parts.rendering.updateReferenceVisibility(); @@ -49,7 +55,7 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) { ); } if (!state._moveEndRemover) { - state._moveEndRemover = viewer.camera.moveEnd.addEventListener(() => { + state._moveEndRemover = cameraOf(viewer).on('moveEnd', () => { if (!state._enabled) return; state._referenceSweepGate.markDirty(); viewer.scene.requestRender?.(); @@ -80,19 +86,21 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) { state._loading = false; state._loadingLabel = ''; } - // Free the entities rather than hide them; enable() rebuilds from the + // Free the items rather than hide them; enable() rebuilds from the // cached JSON. An in-flight load's own post-await ownership check - // removes whatever that stale generation adds later. - parts.rendering.releaseDataSources(state._viewer); + // keeps that stale generation from drawing anything later. + parts.rendering.releaseDrawing(); + parts.rendering.updateVisibility(); }, update(viewer) { return parts.ingestion.load(viewer || state._viewer); }, - destroy(viewer) { + destroy() { if (state._abort) state._abort.abort(); - parts.rendering.releaseDataSources(viewer || state._viewer); + parts.rendering.releaseDrawing({ clearSets: false }); + parts.rendering.detach(); state._cachedCableJson = null; state._cachedLandingJson = null; // hide() clears every published host entry and goes invisible while @@ -126,15 +134,10 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) { state._error = null; state._lastUpdate = null; state._loadingLabel = ''; - state._cableDataSource = null; - state._landingDataSource = null; - state._referenceDataSource = null; state._referenceRecords = []; - state._surfaceRecords = []; + state._surfaceItems = []; state._referenceLabelCount = 0; state._publishScratch.length = 0; - state._markerBlendDone = false; - state._markerBlendInvariantWarned = false; parts.rendering.resetPublishSignature(); state._referenceSweepGate.reset(); }, diff --git a/src/layers/submarineCables/overlay.js b/src/layers/submarineCables/overlay.js index a51d2769b..bb8ed6dac 100644 --- a/src/layers/submarineCables/overlay.js +++ b/src/layers/submarineCables/overlay.js @@ -1,4 +1,5 @@ -import * as Cesium from 'cesium'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { clone, distance } from '../../geo/vector.js'; import { CABLE_REFERENCE_LABEL_WINNER_CAP, CABLE_REFERENCE_LABEL_MAX_DISTANCE_M, @@ -41,7 +42,7 @@ export function selectCableReferenceLabelWinners( .sort( (a, b) => a.distanceM - b.distanceM || - String(a.entity?.id || '').localeCompare(String(b.entity?.id || '')), + String(a.id || '').localeCompare(String(b.id || '')), ) .slice(0, cap); } @@ -191,9 +192,9 @@ export function createCableReferenceSweepGate({ motionEpsilonM = CABLE_SWEEP_MOTION_EPSILON_M, } = {}) { const motionEpsilonSq = motionEpsilonM ** 2; - // Preallocated: the probe clones into it, so a moving camera allocates + // Preallocated: the probe copies into it, so a moving camera allocates // nothing per frame. - const lastSweptPosition = new Cesium.Cartesian3(); + const lastSweptPosition = { x: 0, y: 0, z: 0 }; let hasSweptPosition = false; let dirty = true; let lastProbeAt = -Infinity; @@ -203,7 +204,7 @@ export function createCableReferenceSweepGate({ lastProbeAt = time; const position = camera?.positionWC; hasSweptPosition = Boolean(position); - if (position) Cesium.Cartesian3.clone(position, lastSweptPosition); + if (position) copyInto(position, lastSweptPosition); return true; } @@ -212,7 +213,8 @@ export function createCableReferenceSweepGate({ dirty = true; }, /** - * @param {Cesium.Camera} [camera] Live camera; omit to disable the motion + * @param {{positionWC?: {x: number, y: number, z: number}}} [camera] + * Live camera (its ECEF eye as `positionWC`); omit to disable the motion * fallback entirely (pure dirty-only gate). * @returns {boolean} */ @@ -232,8 +234,7 @@ export function createCableReferenceSweepGate({ if (!position) return false; if ( hasSweptPosition && - Cesium.Cartesian3.distanceSquared(position, lastSweptPosition) <= - motionEpsilonSq + distanceSquared(position, lastSweptPosition) <= motionEpsilonSq ) { return false; } @@ -248,16 +249,17 @@ export function createCableReferenceSweepGate({ } /** - * Recompute one staticized stem on the sweep cadence. Replaces the former - * per-frame `CallbackProperty` pair: constant properties are redefined only - * when the camera-scaled tip moved beyond the settle epsilon, and the two - * preallocated position buffers alternate so each real change raises exactly - * one geometry notification (the localGeojson double-buffer pattern). - * @param {object} record Reference record with entity/base/tip/nextTip/buffers. - * @param {Cesium.Cartesian3} cameraPositionWC + * Recompute one stem on the sweep cadence: its tip rises with the camera's + * distance so the stem keeps about `STEM_TARGET_PX` on screen. The tip is + * moved in place (the overlay entry anchors to the same object) only when it + * moved beyond the settle epsilon, so the caller redraws only stems that + * really changed. + * @param {object} record Reference record with base/tip/reference. + * @param {{x: number, y: number, z: number}} cameraPositionWC ECEF eye. * @param {number} canvasHeight CSS-pixel canvas height. - * @param {number} fov Camera frustum field of view (radians). - * @returns {boolean} True when the stem geometry was redefined. + * @param {number} fov Camera field of view (radians): horizontal on a wide + * canvas, vertical on a tall one. + * @returns {boolean} True when the tip moved. */ export function updateCableReferenceStem( @@ -266,8 +268,8 @@ export function updateCableReferenceStem( canvasHeight, fov, ) { - const distance = Cesium.Cartesian3.distance(cameraPositionWC, record.base); - const effectiveDistance = Math.max(distance, 5000); + const range = distance(cameraPositionWC, record.base); + const effectiveDistance = Math.max(range, 5000); const height = canvasHeight || 1080; const fieldOfView = fov || Math.PI / 3; const metersPerPixelFactor = (2 * Math.tan(fieldOfView / 2)) / height; @@ -275,30 +277,21 @@ export function updateCableReferenceStem( 700, Math.min(85000, effectiveDistance * metersPerPixelFactor * STEM_TARGET_PX), ); - Cesium.Cartesian3.fromDegrees( + const nextTip = fromDegrees( record.reference.lon, record.reference.lat, tipHeight, - Cesium.Ellipsoid.WGS84, - record.nextTip, ); - if ( - Cesium.Cartesian3.distanceSquared(record.tip, record.nextTip) <= - CABLE_STEM_TIP_EPSILON_SQ - ) { + if (distanceSquared(record.tip, nextTip) <= CABLE_STEM_TIP_EPSILON_SQ) { return false; } - Cesium.Cartesian3.clone(record.nextTip, record.tip); - record.stemPositionBufferIndex = 1 - record.stemPositionBufferIndex; - const stemPositions = - record.stemPositionBuffers[record.stemPositionBufferIndex]; - stemPositions[0] = record.base; - stemPositions[1] = record.tip; - record.entity.position.setValue(record.tip); - record.entity.polyline.positions.setValue(stemPositions); + copyInto(nextTip, record.tip); return true; } +const distanceSquared = (a, b) => distance(a, b) ** 2; +const copyInto = (from, to) => Object.assign(to, clone(from)); + export function clampLabel(value, maxLength = 34) { const text = String(value || '') .replace(/\s+/g, ' ') diff --git a/src/layers/submarineCables/pickState.js b/src/layers/submarineCables/pickState.js deleted file mode 100644 index c84e592bb..000000000 --- a/src/layers/submarineCables/pickState.js +++ /dev/null @@ -1,7 +0,0 @@ -import { createEntityStore } from '../../data/entityRecords.js'; - -/** - * The reference a picked cable, landing point or reference marker flies to: - * `info` is `{ label, kind, featureId, reference: { lon, lat } }`. - */ -export const cablePicks = createEntityStore(); diff --git a/src/layers/submarineCables/pin.js b/src/layers/submarineCables/pin.js new file mode 100644 index 000000000..5e529e497 --- /dev/null +++ b/src/layers/submarineCables/pin.js @@ -0,0 +1,71 @@ +/** + * The map pin GeoJSON points have always been drawn with: a rounded box on + * a pointed stem, filled with the pin's colour and stroked a brighter + * shade, drawn the way the default renderer's pin builder draws it (its + * path, scaled from a 24-pixel design). + */ + +/** A colour byte as the default renderer writes it into CSS. */ +const byte = (value) => (value === 1 ? 255 : (value * 256) | 0); + +/** A renderer colour `[r, g, b, a]` as the default renderer writes it in CSS. */ +function css([r, g, b, a = 1]) { + return a === 1 + ? `rgb(${byte(r)},${byte(g)},${byte(b)})` + : `rgba(${byte(r)},${byte(g)},${byte(b)},${a})`; +} + +/** The colour brightened by `amount` (0..1) toward white, alpha kept. */ +function brighten([r, g, b, a = 1], amount) { + const keep = 1 - amount; + return [1 - (1 - r) * keep, 1 - (1 - g) * keep, 1 - (1 - b) * keep, a]; +} + +/** The default renderer's pin outline (`PinBuilder`), on a 24 px square. */ +const PIN_PATH = + 'M6.72 0.422L17.28 0.422C18.553 0.422 19.577 1.758 19.577 3.415' + + 'L19.577 10.973C19.577 12.63 18.553 13.966 17.282 13.966L14.386 14.008' + + 'L11.826 23.578L9.614 14.008L6.719 13.965' + + 'C5.446 13.983 4.422 12.629 4.422 10.972L4.422 3.416' + + 'C4.423 1.76 5.447 0.423 6.718 0.423Z'; + +const pins = new Map(); + +/** + * The pin image for a colour and size (pixels square), one per look: a + * canvas where there is a document, else the same pin as SVG. + * @param {[number, number, number, number]} color Renderer colour. + * @param {number} size + * @returns {import('../../render/contract/draw').ImageRef} + */ +export function cablePinImage(color, size) { + const fill = css(color); + const stroke = css(brighten(color, 0.6)); + const key = `cable-pin:${fill}:${stroke}:${size}`; + let image = pins.get(key); + if (image) return image; + if (typeof document !== 'undefined' && document.createElement) { + const canvas = document.createElement('canvas'); + canvas.width = size; + canvas.height = size; + const context = canvas.getContext('2d'); + context.save(); + context.scale(size / 24, size / 24); + context.fillStyle = fill; + context.strokeStyle = stroke; + context.lineWidth = 0.846; + const path = new Path2D(PIN_PATH); + context.fill(path); + context.stroke(path); + context.restore(); + image = { canvas, key }; + } else { + image = { + svg: + `` + + ``, + }; + } + pins.set(key, image); + return image; +} diff --git a/src/layers/submarineCables/policy.js b/src/layers/submarineCables/policy.js index 68009af2e..32083c99f 100644 --- a/src/layers/submarineCables/policy.js +++ b/src/layers/submarineCables/policy.js @@ -1,5 +1,3 @@ -import * as Cesium from 'cesium'; - export const BASE_CABLE_COLOR = '#39d5ff'; export const BASE_LANDING_COLOR = '#8fffd2'; @@ -54,7 +52,7 @@ export const CABLE_SWEEP_MOTION_EPSILON_M = 250; * trades away (photoreal tiles occluding label TEXT at low, city-level * cameras) matches the sibling dams/datacenters sources, which shipped * host-composited under the same ruling; the anchor points/stems remain - * Cesium-native and depth-tested. See + * drawn by the renderer and depth-tested. See * the world-overlay consolidation design notes ("Depth-testing * decision") for both dated decisions. */ @@ -81,18 +79,27 @@ export const CABLE_GLOBE_STACK_IDS = Object.freeze( new Set(['bing-aerial', 'bing-labels', 'esri-imagery', 'osm']), ); -/** EntityCluster's private marker collections and their required types. */ +/** Landing-point pins: CSS pixels square, anchored at the bottom tip. */ -export const MARKER_COLLECTION_EXPECTATIONS = Object.freeze([ - Object.freeze({ - key: '_billboardCollection', - type: Cesium.BillboardCollection, - }), - Object.freeze({ - key: '_pointCollection', - type: Cesium.PointPrimitiveCollection, - }), -]); +export const CABLE_PIN_SIZE_PX = 6; + +/** + * Pin sizes a GeoJSON feature may ask for (`marker-size`), the simplestyle + * names the map pins have always honoured. + */ + +export const CABLE_PIN_SIZES = Object.freeze({ + small: 24, + medium: 48, + large: 64, +}); + +/** + * Lines are placed along rhumb lines, as GeoJSON lines always were, at + * points no farther apart than this (metres); the renderer joins them. + */ + +export const CABLE_LINE_GRANULARITY_M = 9999; /** * Monotonic clock for the sweep gate's motion probe. A hoisted declaration: diff --git a/src/layers/submarineCables/rendering.js b/src/layers/submarineCables/rendering.js index 15f1fd263..95e14ee5a 100644 --- a/src/layers/submarineCables/rendering.js +++ b/src/layers/submarineCables/rendering.js @@ -1,8 +1,9 @@ -import * as Cesium from 'cesium'; -import { - probeTranslucentMarkerBlend, - commitTranslucentMarkerBlend, -} from './surface.js'; +import { fromDegrees, fromRadians } from '../../geo/ellipsoid.js'; +import { horizonFrom } from '../../geo/horizon.js'; +import { densifyRhumb } from '../../geo/rhumb.js'; +import { distance, toRadians } from '../../geo/vector.js'; +import { cssColor } from '../../render/color.js'; +import { cameraOf, drawOf } from '../../render/rendererOf.js'; import { clampLabel, createCableOverlayEntry, @@ -10,9 +11,149 @@ import { selectCableReferenceLabelWinners, cableReferencePriority, } from './overlay.js'; -import { cablePicks } from './pickState.js'; +import { featureLabel, featureReference, geometryParts } from './geometry.js'; +import { cablePinImage } from './pin.js'; +import { + CABLE_LINE_GRANULARITY_M, + CABLE_PIN_SIZE_PX, + CABLE_PIN_SIZES, +} from './policy.js'; + +/** + * The layer's draw sets start with this; each layer has its own + * (`submarine-cables:1:lines`, …), so several can share a renderer. Picks + * name them as `Hit.set`. + */ +export const CABLE_SET_PREFIX = 'submarine-cables'; +let layers = 0; + +const BLACK_OUTLINE = [0, 0, 0, 0.65]; + +/** A polygon's edges are placed along rhumb lines a degree apart at most. */ +const POLYGON_GRANULARITY_M = (6378137 * Math.PI) / 180; + +/** A renderer colour with its alpha replaced. */ +const withAlpha = (color, alpha) => [color[0], color[1], color[2], alpha]; + +/** A feature's CSS colour property, or null when absent or unreadable. */ +const propColor = (value) => + value === undefined || value === null ? null : cssColor(String(value)); + +/** Whether a GeoJSON property is set, as the GeoJSON loader asked. */ +const given = (value) => value !== undefined && value !== null; + +/** + * How a line draws. A cable with a reference takes the cable's own colour + * (or the base colour) and one width, whatever the feature asks; every other + * line keeps the GeoJSON styling it always had: the source's colour, + * overridable by the feature's simplestyle `stroke`, `stroke-opacity` and + * `stroke-width`, draped on every surface. + */ +function lineStyle(props, cable, styled, baseColor) { + if (cable && styled) { + const color = propColor(props.color) ?? baseColor; + return { + widthPx: 2.5, + style: { kind: 'solid', color: withAlpha(color, 0.92) }, + }; + } + return { + widthPx: props['stroke-width'] ?? 2, + clampTo: 'both', + style: { kind: 'solid', color: strokeColor(props, cable, baseColor) }, + }; +} + +/** A line's or raised polygon's simplestyle stroke colour. */ +function strokeColor(props, cable, baseColor) { + let color = given(props.stroke) ? propColor(props.stroke) : null; + const opacity = props['stroke-opacity']; + if (given(opacity) && opacity !== 1) + color = withAlpha( + color ?? withAlpha(baseColor, cable ? 0.95 : 0.9), + opacity, + ); + return color ?? withAlpha(baseColor, cable ? 0.95 : 0.9); +} + +/** + * A polygon's fill, as GeoJSON polygons were filled: simplestyle `fill` + * takes the source's fill alpha, and `fill-opacity` replaces it. + */ +function polygonFill(props, cable, baseColor) { + const alpha = cable ? 0.18 : 0.35; + let color = given(props.fill) ? propColor(props.fill) : null; + if (color) color = withAlpha(color, alpha); + const opacity = props['fill-opacity']; + if (given(opacity) && opacity !== alpha) + color = withAlpha(color ?? withAlpha(baseColor, alpha), opacity); + return color ?? withAlpha(baseColor, alpha); +} + +/** A finite `[lon, lat, height?]`, or null. */ +function lonLat(coordinate) { + if (!Array.isArray(coordinate) || coordinate.length < 2) return null; + const lon = Number(coordinate[0]); + const lat = Number(coordinate[1]); + if (!Number.isFinite(lon) || !Number.isFinite(lat)) return null; + return { lon: toRadians(lon), lat: toRadians(lat) }; +} + +/** A path's points along rhumb lines, as ECEF, the way GeoJSON drew them. */ +function rhumbPath(coordinates, granularity = CABLE_LINE_GRANULARITY_M) { + const points = []; + for (const coordinate of coordinates ?? []) { + const point = lonLat(coordinate); + if (point) points.push(point); + } + return densifyRhumb(points, granularity).map((p) => + fromRadians(p.lon, p.lat), + ); +} export function createRendering({ state }) { + /** Make the layer's draw sets on the viewer's renderer (once). */ + function attach(viewer) { + if (state._sets || !viewer) return; + const draw = drawOf(viewer); + const prefix = `${CABLE_SET_PREFIX}:${++layers}`; + const show = state._enabled; + state._sets = { + lines: draw.lines({ + id: `${prefix}:lines`, + clampTo: state._clampTo, + show, + }), + fills: draw.shapes({ id: `${prefix}:fills`, clampTo: 'both', show }), + // Pins cull past the horizon each frame, as the sweep culled them; + // the globe hides them there anyway. + pins: draw.icons({ + id: `${prefix}:pins`, + clampTo: 'both', + blend: 'translucent', + horizonCull: true, + show, + }), + stems: draw.lines({ id: `${prefix}:stems`, show }), + references: draw.points({ + id: `${prefix}:references`, + blend: 'translucent', + show, + }), + }; + state._setIds = new Set(Object.values(state._sets).map((set) => set.id)); + state._picks = new Map([...state._setIds].map((id) => [id, new Map()])); + } + + /** Dispose the draw sets (destroy); `attach` makes new ones. */ + function detach() { + if (!state._sets) return; + for (const set of Object.values(state._sets)) set.dispose(); + state._sets = null; + state._setIds = new Set(); + state._picks = new Map(); + } + function resetPublishSignature() { state._lastPublishedIds.length = 0; state._lastPublishedPriorities.length = 0; @@ -20,215 +161,309 @@ export function createRendering({ state }) { } /** - * Remove the three data sources from the viewer and forget the built - * entities. Hiding them (`show = false`) is NOT enough: Cesium's - * DataSourceDisplay still walks every visualizer of a hidden source on - * every frame, and the thousands of hidden polylines/billboards keep - * costing CPU and GC pressure long after the user toggled the layer off — - * that is the "everything gets sluggish after I turn layers off" report. - * The fetched JSON stays cached, so the next enable rebuilds without a - * network round trip or a re-parse. + * Clear the draw sets and forget the built items. Hiding them is NOT + * enough: thousands of hidden lines and markers keep costing memory long + * after the user toggled the layer off — that is the "everything gets + * sluggish after I turn layers off" report. The fetched JSON stays + * cached, so the next enable rebuilds without a network round trip or a + * re-parse. */ - function releaseDataSources(viewer) { - const sources = [ - state._cableDataSource, - state._landingDataSource, - state._referenceDataSource, - ]; - state._cableDataSource = null; - state._landingDataSource = null; - state._referenceDataSource = null; + /** + * Forget what was drawn; `clearSets: false` (destroy, where `detach` + * disposes the sets next) leaves the sets alone. + */ + function releaseDrawing({ clearSets = true } = {}) { state._referenceRecords = []; - state._surfaceRecords = []; + state._surfaceItems = []; state._referenceLabelCount = 0; state._publishScratch.length = 0; - // The blend pass targets the collections being dropped; the rebuilt - // sources need their own pass. - state._markerBlendDone = false; state._loaded = false; state._referenceSweepGate.reset(); - for (const source of sources) { - if (!source) continue; - try { - viewer?.dataSources?.remove(source, true); - } catch { - /* collection gone */ - } - } + if (!state._sets) return; + if (clearSets) for (const set of Object.values(state._sets)) set.clear(); + for (const picks of state._picks.values()) picks.clear(); } function updateVisibility() { - if (state._cableDataSource) state._cableDataSource.show = state._enabled; - if (state._landingDataSource) - state._landingDataSource.show = state._enabled; - if (state._referenceDataSource) - state._referenceDataSource.show = state._enabled; - } - - function styleCableEntity(entity, feature) { - if (!entity?.polyline) return; - const color = feature?.properties?.color - ? Cesium.Color.fromCssColorString(String(feature.properties.color)) - : state.cableColor; - entity.polyline.material = color.withAlpha(0.92); - entity.polyline.width = 2.5; - entity.polyline.clampToGround = true; - entity.polyline.classificationType = state._classificationType; - entity.show = true; + if (!state._sets) return; + for (const set of Object.values(state._sets)) set.show = state._enabled; } /** - * Apply the single translucent blend pass to the landing-billboard and - * reference-point collections. Landing entities carry only billboards and - * reference entities only points, so completion is one applied collection - * per source; a failed shape probe disables the optimization permanently - * for this session and says so loudly in dev builds. - * Both sources are probed BEFORE either is committed, so the helper's - * "defaults untouched on shape drift" fallback holds across the pair too — - * a reference-source failure can never leave the landing source already - * forced to TRANSLUCENT. - */ - - function applyMarkerBlendOnce() { - const landing = probeTranslucentMarkerBlend(state._landingDataSource); - const reference = probeTranslucentMarkerBlend(state._referenceDataSource); - if (landing.invariantFailed || reference.invariantFailed) { - state._markerBlendDone = true; - if (!state._markerBlendInvariantWarned && import.meta.env?.DEV === true) { - state._markerBlendInvariantWarned = true; - console.error( - '[Data:telegeography-submarine-cables] EntityCluster marker-collection ' + - 'shape changed — single-pass translucent blend skipped; markers fall ' + - "back to Cesium's default two-pass blend.", - ); - } - return; - } - const landingBlend = commitTranslucentMarkerBlend(landing); - const referenceBlend = commitTranslucentMarkerBlend(reference); - if (landingBlend.applied > 0 && referenceBlend.applied > 0) - state._markerBlendDone = true; - } - - /** - * Re-classify every cable ground line for the active surface. One batched - * ground-primitive rebuild per stack switch — never per frame. - * @param {Cesium.ClassificationType} next + * Re-drape every cable ground line for the active surface. One ground + * rebuild per stack switch — never per frame. + * @param {'tiles'|'terrain'|'both'} next */ function applyCableClassification(next) { - if (next === undefined || next === state._classificationType) return; - state._classificationType = next; - if (!state._cableDataSource) return; - const entities = state._cableDataSource.entities.values; - for (let i = 0; i < entities.length; i++) { - const polyline = entities[i].polyline; - if (polyline) polyline.classificationType = next; - } - state._viewer?.scene?.requestRender?.(); + if (next === undefined || next === state._clampTo) return; + state._clampTo = next; + state._sets?.lines.setOptions({ clampTo: next }); } - function styleLandingEntity(entity, feature) { - if (!entity?.point) return; - entity.point.color = state.landingColor.withAlpha(0.92); - entity.point.pixelSize = feature?.properties?.is_tbd ? 6 : 7; - entity.point.outlineColor = state.cableOutline; - entity.point.outlineWidth = 1; - entity.point.disableDepthTestDistance = 0; - entity.show = true; - } - - function addReferenceStem({ reference, label, kind, color, feature }) { - if (!state._referenceDataSource || !reference) return; - - const base = Cesium.Cartesian3.fromDegrees(reference.lon, reference.lat, 0); - const tip = Cesium.Cartesian3.fromDegrees( - reference.lon, - reference.lat, - 2500, - ); - const info = { - kind, - reference, - label, - featureId: feature?.id || feature?.properties?.id || null, - }; - const pointColor = color.withAlpha(kind === 'cable' ? 0.84 : 0.94); - const stemColor = color.withAlpha(kind === 'cable' ? 0.58 : 0.68); - // Constant properties on the sweep cadence, never per-frame callbacks: - // the sweep redefines them through the alternating buffers below. - const stemPositionBuffers = [ - [base, tip], - [base, tip], - ]; - - const entity = state._referenceDataSource.entities.add({ - id: `${kind}-reference-${state._referenceRecords.length}-${info.featureId || 'feature'}`, - position: tip, - polyline: { - positions: stemPositionBuffers[0], - width: kind === 'cable' ? 2 : 2.4, - material: new Cesium.ColorMaterialProperty(stemColor), - }, - point: { - pixelSize: kind === 'cable' ? 7 : 8, - color: pointColor, - outlineColor: Cesium.Color.BLACK.withAlpha(0.65), - outlineWidth: 1, - disableDepthTestDistance: 0, - }, + /** + * The items one source's features draw, by set: lines, fills and pins, + * each culled by its feature's reference, and a reference stem and point + * per feature. `kind` is `cable` or `landing-point`. + */ + function buildFeatures(features, kind, out) { + const cable = kind === 'cable'; + const baseColor = cssColor(cable ? state.cableColor : state.landingColor); + features.forEach((feature, index) => { + // A feature with no reference still draws, as the GeoJSON loader drew + // it: unstyled, not picked and never culled. + const reference = featureReference(feature); + const label = featureLabel(feature); + const info = reference && { + kind, + reference, + label, + featureId: feature?.id || feature?.properties?.id || null, + }; + const base = reference && fromDegrees(reference.lon, reference.lat, 0); + const keep = (set, item) => { + if (!reference) return; + out.picks[set].set(item.id, info); + if (set !== 'pins') out.surface.push({ set, item, base }); + }; + const props = feature?.properties || {}; + const parts = geometryParts(feature.geometry); + const key = `${kind}:${index}`; + parts.lines.forEach((coordinates, part) => { + const positions = rhumbPath(coordinates); + if (positions.length < 2) return; + const item = { + id: `${key}:line:${part}`, + positions, + mode: 'draped', + ...lineStyle(props, cable, Boolean(reference), baseColor), + show: true, + }; + out.lines.push(item); + keep('lines', item); + }); + parts.polygons.forEach((rings, part) => { + const fill = polygonFill(props, cable, baseColor); + // Polygons with heights stand at them, outlined, as the GeoJSON + // loader drew them; flat ones lie on the surface, edges along + // rhumb lines. + const raised = rings[0]?.[0]?.length > 2; + const drawn = rings + .map((ring) => + raised + ? ring + .filter((coordinate) => lonLat(coordinate)) + .map(([lon, lat, height]) => + fromDegrees(Number(lon), Number(lat), Number(height) || 0), + ) + : rhumbPath(ring, POLYGON_GRANULARITY_M).map((p) => ({ + x: p.x, + y: p.y, + z: p.z, + })), + ) + .filter((ring) => ring.length >= 3); + if (!drawn.length) return; + const item = { + id: `${key}:fill:${part}`, + geometry: raised + ? { kind: 'polygon', rings: drawn, perPositionHeight: true } + : { kind: 'polygon', rings: drawn }, + fill, + ...(raised + ? { + height: 'absolute', + // WebGL draws the loader's outline one pixel wide. + outline: strokeColor(props, cable, baseColor), + outlineWidth: 1, + } + : { height: 'clampGround' }), + show: true, + }; + out.fills.push(item); + keep('fills', item); + }); + parts.points.forEach((coordinate, part) => { + const point = lonLat(coordinate); + if (!point) return; + const color = + (given(props['marker-color']) && cssColor(props['marker-color'])) || + baseColor; + const size = CABLE_PIN_SIZES[props['marker-size']] ?? CABLE_PIN_SIZE_PX; + const raised = + coordinate.length > 2 && Number.isFinite(Number(coordinate[2])); + const item = { + id: `${key}:pin:${part}`, + pos: { + lon: Number(coordinate[0]), + lat: Number(coordinate[1]), + height: raised ? Number(coordinate[2]) : 0, + }, + height: raised ? 'absolute' : 'clampGround', + image: cablePinImage(color, size), + size: [size, size], + anchor: 'bottom', + }; + out.pins.push(item); + keep('pins', item); + }); + if (!reference) return; + addReference(out, { + reference, + label, + kind, + color: baseColor, + info, + base, + }); }); + } - cablePicks.write(entity).info = info; + function addReference(out, { reference, label, kind, color, info, base }) { + const cable = kind === 'cable'; + const tip = fromDegrees(reference.lon, reference.lat, 2500); + const id = `${kind}-reference-${out.references.length}-${info.featureId || 'feature'}`; const record = { - id: entity.id, - entity, + id, base, + // Moved in place: the overlay entry anchors to this object. tip, - nextTip: Cesium.Cartesian3.clone(tip), - stemPositionBuffers, - stemPositionBufferIndex: 0, reference, kind, label: clampLabel(label), - visible: false, + visible: true, distanceM: Infinity, entry: null, + stem: { + id, + positions: [base, { ...tip }], + widthPx: cable ? 2 : 2.4, + mode: '3d', + style: { + kind: 'solid', + color: withAlpha(color, cable ? 0.58 : 0.68), + }, + show: true, + }, + point: { + id, + pos: { ...tip }, + pixelSize: cable ? 7 : 8, + color: withAlpha(color, cable ? 0.84 : 0.94), + outlineColor: BLACK_OUTLINE, + outlineWidth: 1, + show: true, + }, }; record.entry = createCableOverlayEntry(record); - state._referenceRecords.push(record); + out.references.push(record); + out.picks.stems.set(id, info); + out.picks.references.set(id, info); + } + + /** + * Draw both sources' features, replacing what was drawn. Items start + * culled for the camera as it is, so the first sweep has nothing to redo. + */ + function drawFeatures(cableFeatures, landingFeatures) { + const out = { + lines: [], + fills: [], + pins: [], + references: [], + surface: [], + picks: { + lines: new Map(), + fills: new Map(), + pins: new Map(), + stems: new Map(), + references: new Map(), + }, + }; + buildFeatures(cableFeatures, 'cable', out); + buildFeatures(landingFeatures, 'landing-point', out); + state._referenceRecords = out.references; + state._surfaceItems = out.surface; + sweep({ draw: false }); + if (!state._sets) return; + const sets = state._sets; + for (const [name, picks] of Object.entries(out.picks)) { + const map = state._picks.get(sets[name].id); + map.clear(); + for (const [id, info] of picks) map.set(id, info); + } + sets.lines.set(out.lines); + sets.fills.set(out.fills); + sets.pins.set(out.pins); + sets.stems.set(out.references.map((record) => record.stem)); + sets.references.set(out.references.map((record) => record.point)); + } + + /** What a pick on one of the layer's sets names, or null. */ + function pickInfo(hit) { + if (!hit || !state._setIds.has(hit.set)) return null; + return state._picks.get(hit.set)?.get(hit.id) ?? null; + } + + /** + * One sweep: cull references and surface items by whether their + * reference is past the horizon, re-size visible stems, and redraw only + * what changed (`draw: false` changes the items without drawing them). + * Returns false when there is no camera to sweep from. + */ + function sweep({ draw = true } = {}) { + const viewer = state._viewer; + if (!viewer) return false; + const pose = cameraOf(viewer).pose(); + const cameraPos = pose?.position; + if (!cameraPos) return false; + const canvasHeight = viewer.scene?.canvas?.clientHeight || 1080; + // The field of view along the canvas's longer side. + const fov = + pose.aspectRatio > 1 + ? 2 * Math.atan(Math.tan(pose.fovy / 2) * pose.aspectRatio) + : pose.fovy; + const horizon = horizonFrom(cameraPos); + const stems = []; + const points = []; + for (const record of state._referenceRecords) { + const visible = horizon.isPointVisible(record.base); + const flipped = record.visible !== visible; + record.visible = visible; + record.distanceM = distance(cameraPos, record.base); + // Hidden stems keep their last geometry; this same sweep refreshes them + // in the pass where they turn visible again. + const moved = + visible && + updateCableReferenceStem(record, cameraPos, canvasHeight, fov); + if (!flipped && !moved) continue; + record.stem.positions = [record.base, { ...record.tip }]; + record.stem.show = visible; + record.point.pos = { ...record.tip }; + record.point.show = visible; + stems.push(record.stem); + points.push(record.point); + } + const surface = { lines: [], fills: [] }; + for (const entry of state._surfaceItems) { + const visible = horizon.isPointVisible(entry.base); + if (entry.item.show === visible) continue; + entry.item.show = visible; + surface[entry.set].push(entry.item); + } + if (draw && state._sets) { + if (stems.length) state._sets.stems.upsert(stems); + if (points.length) state._sets.references.upsert(points); + if (surface.lines.length) state._sets.lines.upsert(surface.lines); + if (surface.fills.length) state._sets.fills.upsert(surface.fills); + } + return true; } function updateReferenceVisibility() { - if (!state._enabled || !state._viewer?.camera) return; - const cameraPos = state._viewer.camera.positionWC; - if (!cameraPos) return; - - const canvasHeight = state._viewer.scene?.canvas?.clientHeight || 1080; - const fov = state._viewer.camera.frustum?.fov || Math.PI / 3; - const occluder = new Cesium.EllipsoidalOccluder( - Cesium.Ellipsoid.WGS84, - cameraPos, - ); - for (const record of state._referenceRecords) { - const visible = occluder.isPointVisible(record.base); - record.visible = visible; - record.distanceM = Cesium.Cartesian3.distance(cameraPos, record.base); - if (record.entity.show !== visible) { - record.entity.show = visible; - } - // Hidden stems keep their last geometry; this same sweep refreshes them - // in the pass where they turn visible again. - if (visible) - updateCableReferenceStem(record, cameraPos, canvasHeight, fov); - } - for (const record of state._surfaceRecords) { - const visible = occluder.isPointVisible(record.base); - if (record.entity.show !== visible) { - record.entity.show = visible; - } - } + if (!state._enabled || !state._viewer) return; + if (!sweep()) return; const winners = selectCableReferenceLabelWinners(state._referenceRecords); let changed = winners.length !== state._lastPublishedCount; for (let i = 0; i < winners.length; i++) { @@ -246,9 +481,6 @@ export function createRendering({ state }) { } state._publishScratch.length = winners.length; state._referenceLabelCount = winners.length; - // The marker collections are created lazily by the visualizers, so the - // single-pass blend is applied on the sweep cadence until both landed. - if (!state._markerBlendDone) applyMarkerBlendOnce(); if (!changed) return; state._overlayPublisher.publish(state._publishScratch); state._lastPublishedCount = winners.length; @@ -260,14 +492,14 @@ export function createRendering({ state }) { state._lastPublishedPriorities.length = winners.length; } return { + attach, + detach, resetPublishSignature, - releaseDataSources, + releaseDrawing, updateVisibility, - styleCableEntity, - applyMarkerBlendOnce, applyCableClassification, - styleLandingEntity, - addReferenceStem, + drawFeatures, + pickInfo, updateReferenceVisibility, }; } diff --git a/src/layers/submarineCables/state.js b/src/layers/submarineCables/state.js index 4bd67d12f..65bcac27d 100644 --- a/src/layers/submarineCables/state.js +++ b/src/layers/submarineCables/state.js @@ -1,4 +1,3 @@ -import * as Cesium from 'cesium'; import { createCableReferenceSweepGate, createCableOverlayPublisher, @@ -30,17 +29,30 @@ export function createState({ sweepClock, overlayHost }) { state._loadGeneration = 0; - state._cableDataSource = null; + /** + * The layer's draw sets, made at init: cable and landing lines (draped), + * pins (landing points), fills (polygons), stems and reference points. + */ - state._landingDataSource = null; + state._sets = null; - state._referenceDataSource = null; + /** Set ids this layer made, for matching picks. */ + + state._setIds = new Set(); + + /** What each drawn item is, by set id then item id (picks fly to it). */ + + state._picks = new Map(); + + /** Drawn surface items, culled by their feature's reference each sweep. */ + + state._surfaceItems = []; /** - * Fetched cable/landing JSON kept across disable/enable. A disable RELEASES - * the three data sources (see releaseDataSources) instead of hiding them, - * so a re-enable has to rebuild the entities; the network/parse half of - * that rebuild is the expensive part users would notice, so it is cached. + * Fetched cable/landing JSON kept across disable/enable. A disable CLEARS + * the draw sets (see releaseDrawing) instead of hiding them, so a + * re-enable has to rebuild the items; the network/parse half of that + * rebuild is the expensive part users would notice, so it is cached. */ state._cachedCableJson = null; @@ -49,8 +61,6 @@ export function createState({ sweepClock, overlayHost }) { state._referenceRecords = []; - state._surfaceRecords = []; - state._clickSubscription = null; state._preRenderRemover = null; @@ -59,15 +69,9 @@ export function createState({ sweepClock, overlayHost }) { state._mapStackListener = null; - /** Active ground-line classification; refined from live scene state at init. */ + /** What ground lines drape on; refined from live scene state at init. */ - state._classificationType = Cesium.ClassificationType.BOTH; - - /** True once both marker collections blend translucent (or the shape probe failed). */ - - state._markerBlendDone = false; - - state._markerBlendInvariantWarned = false; + state._clampTo = 'both'; state._referenceLabelCount = 0; @@ -96,10 +100,8 @@ export function createState({ sweepClock, overlayHost }) { state._lastPublishedCount = -1; - state.cableColor = Cesium.Color.fromCssColorString(BASE_CABLE_COLOR); + state.cableColor = BASE_CABLE_COLOR; - state.cableOutline = Cesium.Color.BLACK.withAlpha(0.45); - - state.landingColor = Cesium.Color.fromCssColorString(BASE_LANDING_COLOR); + state.landingColor = BASE_LANDING_COLOR; return state; } diff --git a/src/layers/submarineCables/surface.js b/src/layers/submarineCables/surface.js index 36556bbb3..3ef7e57c5 100644 --- a/src/layers/submarineCables/surface.js +++ b/src/layers/submarineCables/surface.js @@ -1,126 +1,34 @@ -import * as Cesium from 'cesium'; -import { - CABLE_GLOBE_STACK_IDS, - MARKER_COLLECTION_EXPECTATIONS, -} from './policy.js'; +import { CABLE_GLOBE_STACK_IDS } from './policy.js'; /** - * Ground-line classification for one map stack. The photoreal stack renders - * Google 3D tiles with the Cesium globe HIDDEN, so cable ground lines only - * need the 3D-tile classification pass there; every other known stack (the - * bing stacks and osm) renders imagery on the shown globe, so only the - * terrain pass applies. - * Classifying against just the active surface halves the batched - * GroundPolylinePrimitive's emitted command sets. BOTH is the safe fallback - * for an unknown stack — it renders on every surface, exactly the shipped - * pre-optimization behavior. + * What cable ground lines drape on for one map stack. The photoreal stack + * renders Google 3D tiles with the globe HIDDEN, so cable ground lines only + * need to drape on the tiles there; every other known stack (the bing + * stacks and osm) renders imagery on the shown globe, so only the terrain + * applies. + * Draping on just the active surface halves the ground lines' draw + * commands. `both` is the safe fallback for an unknown stack — it renders + * on every surface, exactly the shipped pre-optimization behavior. * @param {string|null|undefined} activeId MapStackController stack id. - * @returns {Cesium.ClassificationType} + * @returns {'tiles'|'terrain'|'both'} The draw sets' `clampTo`. */ export function cableClassificationTypeForStack(activeId) { - if (activeId === 'photoreal') return Cesium.ClassificationType.CESIUM_3D_TILE; - if (CABLE_GLOBE_STACK_IDS.has(activeId)) - return Cesium.ClassificationType.TERRAIN; - return Cesium.ClassificationType.BOTH; + if (activeId === 'photoreal') return 'tiles'; + if (CABLE_GLOBE_STACK_IDS.has(activeId)) return 'terrain'; + return 'both'; } /** * Derive the active surface from live scene state. The boot-time * `setStack(..., { silent: true })` fires no 'gev:map-stack-changed' event, - * so the initial classification reads the scene the way the height-datum - * listeners do: the photoreal regime is exactly "globe hidden". - * @param {Cesium.Scene|null|undefined} scene - * @returns {Cesium.ClassificationType} + * so the initial surface is read the way the height-datum listeners do: the + * photoreal regime is exactly "globe hidden". + * @param {{globe?: {show?: boolean}}|null|undefined} scene + * @returns {'tiles'|'terrain'|'both'} */ export function cableClassificationTypeForScene(scene) { - if (!scene?.globe) return Cesium.ClassificationType.BOTH; - return scene.globe.show === false - ? Cesium.ClassificationType.CESIUM_3D_TILE - : Cesium.ClassificationType.TERRAIN; -} - -/** - * Validate one data source's marker collections WITHOUT mutating anything. - * Splitting validation from mutation is what makes the fallback honest: a - * shape failure on the SECOND collection (or the second data source) must - * not leave the first one already forced to TRANSLUCENT. - * @param {Cesium.DataSource|null|undefined} dataSource - * @returns {{ready:object[],pending:number,invariantFailed:boolean}} - */ - -export function probeTranslucentMarkerBlend(dataSource) { - const cluster = dataSource?.clustering; - if (!cluster) return { ready: [], pending: 0, invariantFailed: true }; - const ready = []; - let pending = 0; - let invariantFailed = false; - for (const { key, type } of MARKER_COLLECTION_EXPECTATIONS) { - if (!(key in cluster)) { - invariantFailed = true; - continue; - } - const collection = cluster[key]; - if (collection === undefined || collection === null) { - pending++; - continue; - } - if (!(collection instanceof type) || !('blendOption' in collection)) { - invariantFailed = true; - continue; - } - ready.push(collection); - } - // Any failure discards every collected target: nothing is mutated at all. - if (invariantFailed) return { ready: [], pending: 0, invariantFailed: true }; - return { ready, pending, invariantFailed: false }; -} - -/** - * Commit a clean probe. Only ever called once every probe in the batch has - * passed, so this cannot land a partial application. - * @param {{ready:object[],pending:number}} probe - * @returns {{applied:number,pending:number,invariantFailed:boolean}} - */ - -export function commitTranslucentMarkerBlend(probe) { - for (const collection of probe.ready) { - if (collection.blendOption !== Cesium.BlendOption.TRANSLUCENT) { - collection.blendOption = Cesium.BlendOption.TRANSLUCENT; - } - } - return { - applied: probe.ready.length, - pending: probe.pending, - invariantFailed: false, - }; -} - -/** - * Force one translucent draw pass for a data source's marker collections. - * The default `OPAQUE_AND_TRANSLUCENT` blend emits two draw commands per - * collection, and every cable marker is translucent (alpha < 1), so the - * opaque pass is pure overhead across 1,917 landing billboards + 2,629 - * reference points. Cesium has no public accessor for the entity-backed - * collections, so this reaches through EntityCluster's private fields under - * a SHAPE INVARIANT the caller must honor loudly: the constructor - * pre-assigns `_billboardCollection`/`_pointCollection` (= undefined until a - * visualizer lazily creates them), so a missing PROPERTY means Cesium's - * shape changed — report `invariantFailed` and never touch anything — - * while a present-but-undefined value only means "not created yet" - * (`pending`). Wrong instance types also fail the invariant. The cables - * sources never enable clustering, so created collections persist. - * VALIDATE-ALL-THEN-MUTATE-ALL: every field/type check runs before the first - * assignment, so a failure anywhere leaves BOTH collections on Cesium's - * default blend — the fallback this helper promises. - * @param {Cesium.DataSource|null|undefined} dataSource - * @returns {{applied:number,pending:number,invariantFailed:boolean}} - */ - -export function applyTranslucentMarkerBlend(dataSource) { - const probe = probeTranslucentMarkerBlend(dataSource); - if (probe.invariantFailed) - return { applied: 0, pending: 0, invariantFailed: true }; - return commitTranslucentMarkerBlend(probe); + if (!scene?.globe) return 'both'; + return scene.globe.show === false ? 'tiles' : 'terrain'; } diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index de84b57ec..d9e8f505c 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -148,6 +148,7 @@ export function createCesiumDraw({ scene, report }) { record.pickIds = []; record.placed = []; record.patchable = null; + record.lineParts = null; build(record); setsVersion += 1; }; @@ -162,7 +163,7 @@ export function createCesiumDraw({ scene, report }) { }, upsert(list) { // Items that only change how they look are changed where they are. - if (patchPoints(record, list)) { + if (patchPoints(record, list) || patchLines(record, list)) { for (const item of list) items.set(item.id, item); setsVersion += 1; requestRender(); @@ -190,12 +191,12 @@ export function createCesiumDraw({ scene, report }) { Object.assign(spec, options); // What clamped items clamp to, how points blend, and whether ground // primitives pick, are built into them. Models clamp nothing, only - // points build in the blend, and only shapes and lines have ground + // points and icons build in the blend, and only shapes and lines have ground // primitives: other kinds are not rebuilt for those (models would // load again). if ( (kind !== 'models' && spec.clampTo !== clampTo) || - (kind === 'points' && spec.blend !== blend) || + ((kind === 'points' || kind === 'icons') && spec.blend !== blend) || ((kind === 'shapes' || kind === 'lines') && (spec.pickable !== false) !== pickable) ) @@ -322,6 +323,7 @@ export function createCesiumDraw({ scene, report }) { for (const record of sets.values()) { const ground = record.pending; if (!ground || ground.some((p) => !p.isDestroyed() && !p.ready)) continue; + showPending(record); for (const primitive of ground) primitive.show = true; record.pending = null; retire(record); @@ -381,7 +383,10 @@ export function createCesiumDraw({ scene, report }) { } function buildIcons(record) { - const host = new Cesium.BillboardCollection({ scene }); + const host = new Cesium.BillboardCollection({ + scene, + blendOption: pointBlendOf(record.spec.blend), + }); record.atlases = new Set(); for (const item of record.items.values()) { const image = iconImage(record, item.image); @@ -629,12 +634,23 @@ export function createCesiumDraw({ scene, report }) { function buildLines(record) { const host = new Cesium.PolylineCollection(); const draped = new Map(); + // Each line as drawn, for upserts that change it in place. + const parts = new Map(); + record.lineParts = parts; for (const item of record.items.values()) { if (item.mode === 'draped') { if (item.style.kind !== 'solid') throw new Error('the Cesium renderer drapes solid lines only'); const clampTo = item.clampTo ?? record.spec.clampTo ?? 'both'; if (!draped.has(clampTo)) draped.set(clampTo, []); + const id = pickId(record, item); + parts.set(item.id, { + look: lineLook(item), + positions: flatPositions(item.positions), + clampTo, + id, + ground: null, + }); draped.get(clampTo).push( new Cesium.GeometryInstance({ geometry: new Cesium.GroundPolylineGeometry({ @@ -650,33 +666,124 @@ export function createCesiumDraw({ scene, report }) { item.show !== false, ), }, - id: pickId(record, item), + id, }), ); continue; } - host.add({ + const polyline = host.add({ positions: linePositions(item), width: item.widthPx, material: lineMaterial(item.style), show: item.show !== false, id: pickId(record, item), }); + parts.set(item.id, { look: lineLook(item), polyline }); } if (!draped.size) return replaceHost(record, host); // Draped lines drape as the entities' clamped polylines do. - const ground = [...draped].map( - ([clampTo, geometryInstances]) => - new Cesium.GroundPolylinePrimitive({ - geometryInstances, - appearance: new Cesium.PolylineColorAppearance(), - classificationType: classificationOf(clampTo), - allowPicking: record.spec.pickable !== false, - }), - ); + const byClamp = new Map(); + const ground = [...draped].map(([clampTo, geometryInstances]) => { + const primitive = new Cesium.GroundPolylinePrimitive({ + geometryInstances, + appearance: new Cesium.PolylineColorAppearance(), + classificationType: classificationOf(clampTo), + allowPicking: record.spec.pickable !== false, + }); + byClamp.set(clampTo, primitive); + return primitive; + }); + for (const part of parts.values()) + if (part.clampTo) part.ground = byClamp.get(part.clampTo); replaceHost(record, collect(host, ground), ground, host); } + /** + * How a line draws, but for where it runs and whether it shows: lines + * that keep it can be changed in place. + */ + const lineLook = (item) => + JSON.stringify([ + item.mode, + item.widthPx, + item.clampTo, + item.style, + item.depthFailColor, + item.segmentColors, + item.segmentShow, + item.revealFraction, + item.frame, + ]); + + /** A line's positions as one flat array of numbers, to compare. */ + function flatPositions(positions) { + if (positions instanceof Float64Array) return Array.from(positions); + const flat = []; + for (const p of positions) + if ('x' in p) flat.push(p.x, p.y, p.z); + else flat.push(p.lon, p.lat, p.height ?? 0, NaN); + return flat; + } + + const samePositions = (a, b) => + a.length === b.length && a.every((value, i) => Object.is(value, b[i])); + + /** + * Upsert lines in place, without a rebuild, when every item is drawn now + * and looks the same: then only whether it shows, its `meta`, and where + * a line not draped runs change. A draped line keeps its positions, and + * its ground primitive must be ready. False, changing nothing, otherwise. + */ + function patchLines(record, list) { + const parts = record.lineParts; + if (record.kind !== 'lines' || !parts) return false; + for (const item of list) { + const was = parts.get(item.id); + if (!was || was.look !== lineLook(item)) return false; + if ( + was.ground && + (was.ground.isDestroyed() || + (!was.ground.ready && !record.pending?.includes(was.ground)) || + !samePositions(flatPositions(item.positions), was.positions)) + ) + return false; + } + for (const item of list) { + const was = parts.get(item.id); + const show = item.show !== false; + if (was.polyline) { + was.polyline.positions = linePositions(item); + was.polyline.show = show; + was.polyline.id.meta = item.meta; + continue; + } + was.id.meta = item.meta; + // A ground primitive still building takes its show once it is ready + // (`swapReady`), so a show change never restarts the build. + if (was.ground.ready) showPart(was, show); + else was.pendingShow = show; + } + return true; + } + + /** A draped line part's show, on its ready ground primitive. */ + function showPart(part, show) { + const attributes = part.ground.getGeometryInstanceAttributes(part.id); + attributes.show = Cesium.ShowGeometryInstanceAttribute.toValue( + show, + attributes.show, + ); + } + + /** The shows patched in while a set's ground primitives were building. */ + function showPending(record) { + for (const part of record.lineParts?.values() ?? []) + if (part.pendingShow !== undefined && !part.ground.isDestroyed()) { + showPart(part, part.pendingShow); + part.pendingShow = undefined; + } + } + /** One host for a set's own collection and its ground primitives. */ function collect(own, ground) { const host = new Cesium.PrimitiveCollection(); diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 313477b77..7c4aa4385 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -1097,3 +1097,133 @@ test('the context layer draws its rim as an outlined ellipse on a viewer of its rendering.disposeVisual(); assert.equal(other.added.length, 0); }); + +/** Run `fn` with the image classes Cesium's materials test uniforms against. */ +function withImageClasses(fn) { + const names = [ + 'HTMLCanvasElement', + 'HTMLImageElement', + 'ImageBitmap', + 'OffscreenCanvas', + ]; + const real = names.map((name) => globalThis[name]); + for (const name of names) globalThis[name] ??= class {}; + try { + return fn(); + } finally { + names.forEach((name, i) => (globalThis[name] = real[i])); + } +} + +test('lines that change only whether they show, or where an undraped one runs, change in place', () => + withImageClasses(() => { + const { scene, draw, frame } = drawOver(); + const set = draw.lines({ id: 'patched' }); + const draped = (id, show = true, meta) => ({ + id, + positions: [ + { lon: 0, lat: 0 }, + { lon: 1, lat: 1 }, + ], + widthPx: 2.5, + mode: 'draped', + style: { kind: 'solid', color: '#7fe6ed' }, + show, + meta, + }); + const stem = (id, height, show = true) => ({ + id, + positions: [ + Cesium.Cartesian3.fromDegrees(0, 0, 0), + Cesium.Cartesian3.fromDegrees(0, 0, height), + ], + widthPx: 2, + mode: '3d', + style: { kind: 'solid', color: [1, 1, 1, 0.5] }, + show, + meta: height, + }); + const attributes = new Map(); + const fakeAttributes = (ground) => { + ground.getGeometryInstanceAttributes = (id) => { + if (!attributes.has(id.id)) + attributes.set(id.id, { show: new Uint8Array([1]) }); + return attributes.get(id.id); + }; + }; + set.set([draped('a'), draped('b'), stem('s', 100)]); + const host = scene.added[0]; + const ground = host.get(1); + fakeAttributes(ground); + // Still building: the show waits for the ground, and the build goes on. + set.upsert([draped('a', false)]); + assert.equal(scene.added[0], host, 'not rebuilt while its ground builds'); + assert.equal(attributes.size, 0); + Object.defineProperty(ground, 'ready', { value: true }); + frame(); + assert.deepEqual([...attributes.get('a').show], [0], 'shown once ready'); + set.upsert([draped('b', false)]); + assert.equal(scene.added[0], host, 'changed in place once ready'); + assert.deepEqual([...attributes.get('b').show], [0]); + set.upsert([draped('b', true, 'new')]); + assert.deepEqual([...attributes.get('b').show], [1]); + const [, idB] = ground.geometryInstances.map((instance) => instance.id); + assert.equal(idB.meta, 'new', 'picks read the new meta'); + // An undraped line moves and hides in place, and keeps its new meta. + const line = host.get(0).get(0); + set.upsert([stem('s', 2500, false)]); + assert.equal(scene.added[0], host); + assert.equal(host.get(0).get(0), line); + assert.equal(line.show, false); + assert.equal(line.id.meta, 2500); + assert.ok( + Cesium.Cartesian3.equalsEpsilon( + line.positions[1], + Cesium.Cartesian3.fromDegrees(0, 0, 2500), + 1e-6, + ), + ); + // One item that cannot change in place rebuilds them all, and patches + // none of the others first. + set.upsert([ + draped('a'), + { + ...draped('b'), + positions: [ + { lon: 0, lat: 0 }, + { lon: 2, lat: 2 }, + ], + }, + ]); + assert.deepEqual([...attributes.get('a').show], [0], 'not patched'); + assert.notEqual(scene.added.at(-1), host, 'a draped line that moves'); + const moved = scene.added.at(-1); + set.upsert([{ ...stem('s', 2500), widthPx: 3 }]); + assert.notEqual(scene.added.at(-1), moved, 'a line that looks different'); + // A ground primitive gone from under the set rebuilds too. + const third = scene.added.at(-1); + third.get(1).destroy(); + set.upsert([draped('a', false)]); + assert.notEqual(scene.added.at(-1), third, 'its ground destroyed'); + set.dispose(); + })); + +test('icons blend as their set says', () => { + const { scene, draw } = drawOver(); + const set = draw.icons({ id: 'pins', blend: 'translucent' }); + set.set([ + { + id: 'a', + pos: { lon: 0, lat: 0 }, + image: 'pin.png', + size: [6, 6], + }, + ]); + assert.equal(scene.added[0].blendOption, Cesium.BlendOption.TRANSLUCENT); + set.setOptions({ blend: undefined }); + assert.equal( + scene.added[0].blendOption, + Cesium.BlendOption.OPAQUE_AND_TRANSLUCENT, + ); + set.dispose(); +}); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 4e0957343..d0070e82b 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -126,13 +126,6 @@ "src/layers/streetLevel/selection.js", "src/layers/streetLevel/sequenceCones.js", "src/layers/streetLevel/view.js", - "src/layers/submarineCables/ingestion.js", - "src/layers/submarineCables/interaction.js", - "src/layers/submarineCables/overlay.js", - "src/layers/submarineCables/policy.js", - "src/layers/submarineCables/rendering.js", - "src/layers/submarineCables/state.js", - "src/layers/submarineCables/surface.js", "src/layers/traffic/animation.js", "src/layers/traffic/flow.js", "src/layers/traffic/footprint.js", diff --git a/src/render/color.js b/src/render/color.js index 986567399..529dfe5b5 100644 --- a/src/render/color.js +++ b/src/render/color.js @@ -13,3 +13,74 @@ export function hexColor(hex, alpha = 1) { alpha, ]; } + +// The default renderer's own patterns, so a colour reads as it read there. +const SHORT_HEX = /^#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?$/i; +const LONG_HEX = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i; +const RGB = + /^rgba?\s*\(\s*([0-9.]+%?)\s*[,\s]+\s*([0-9.]+%?)\s*[,\s]+\s*([0-9.]+%?)(?:\s*[,\s/]+\s*([0-9.]+))?\s*\)$/i; +const HSL = + /^hsla?\s*\(\s*([0-9.]+)\s*[,\s]+\s*([0-9.]+%)\s*[,\s]+\s*([0-9.]+%)(?:\s*[,\s/]+\s*([0-9.]+))?\s*\)$/i; + +function hueToRgb(m1, m2, h) { + if (h < 0) h += 1; + if (h > 1) h -= 1; + if (h * 6 < 1) return m1 + (m2 - m1) * 6 * h; + if (h * 2 < 1) return m2; + if (h * 3 < 2) return m1 + (m2 - m1) * (2 / 3 - h) * 6; + return m1; +} + +const rgbChannel = (text) => + Number.parseFloat(text) / (text.endsWith('%') ? 100 : 255); + +/** + * A CSS colour (`#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()`, `rgba()`, + * `hsl()`, `hsla()`) as a renderer colour, read as the default renderer + * reads it; null for anything else (named colours included). + */ +export function cssColor(text) { + const css = String(text ?? '').trim(); + let m = SHORT_HEX.exec(css); + if (m) + return [ + Number.parseInt(m[1], 16) / 15, + Number.parseInt(m[2], 16) / 15, + Number.parseInt(m[3], 16) / 15, + Number.parseInt(m[4] ?? 'f', 16) / 15, + ]; + m = LONG_HEX.exec(css); + if (m) + return [ + Number.parseInt(m[1], 16) / 255, + Number.parseInt(m[2], 16) / 255, + Number.parseInt(m[3], 16) / 255, + Number.parseInt(m[4] ?? 'ff', 16) / 255, + ]; + m = RGB.exec(css); + if (m) + return [ + rgbChannel(m[1]), + rgbChannel(m[2]), + rgbChannel(m[3]), + Number.parseFloat(m[4] ?? '1.0'), + ]; + m = HSL.exec(css); + if (!m) return null; + const hue = (Number.parseFloat(m[1]) / 360) % 1; + const saturation = Number.parseFloat(m[2]) / 100; + const lightness = Number.parseFloat(m[3]) / 100; + const alpha = Number.parseFloat(m[4] ?? '1.0'); + if (saturation === 0) return [lightness, lightness, lightness, alpha]; + const m2 = + lightness < 0.5 + ? lightness * (1 + saturation) + : lightness + saturation - lightness * saturation; + const m1 = 2 * lightness - m2; + return [ + hueToRgb(m1, m2, hue + 1 / 3), + hueToRgb(m1, m2, hue), + hueToRgb(m1, m2, hue - 1 / 3), + alpha, + ]; +} diff --git a/src/render/color.test.mjs b/src/render/color.test.mjs index 3d93690d1..dd5ba4ef2 100644 --- a/src/render/color.test.mjs +++ b/src/render/color.test.mjs @@ -6,3 +6,26 @@ test('hex colours become renderer colours at the given alpha', () => { assert.deepEqual(hexColor('#ff8000'), [1, 128 / 255, 0, 1]); assert.deepEqual(hexColor('#000000', 0.25), [0, 0, 0, 0.25]); }); + +test('CSS colours read as the default renderer reads them', async () => { + const Cesium = await import('cesium'); + const { cssColor } = await import('./color.js'); + for (const css of [ + '#39d5ff', + ' #8fffd2 ', + '#abc', + '#abcd', + '#11223344', + 'rgb(10, 20, 30)', + 'rgba(10,20,30,0.5)', + 'rgb(10% 20% 30% / 0.25)', + 'hsl(120, 50%, 25%)', + 'hsla(300, 100%, 75%, 0.4)', + 'hsl(30, 0%, 40%)', + ]) { + const c = Cesium.Color.fromCssColorString(css); + assert.deepEqual(cssColor(css), [c.red, c.green, c.blue, c.alpha], css); + } + assert.equal(cssColor('not a colour'), null); + assert.equal(cssColor(undefined), null); +}); diff --git a/src/render/stub/geodesic.js b/src/render/stub/geodesic.js index 12fac64d3..bb37b4e02 100644 --- a/src/render/stub/geodesic.js +++ b/src/render/stub/geodesic.js @@ -1,95 +1,17 @@ /** * @module render/stub/geodesic * @description The point a fraction of the way along the WGS84 geodesic - * between two places: Vincenty's inverse formula, then the series the - * default renderer interpolates with, term for term, so a rectangle's - * centre matches its to floating-point noise. + * between two places: Vincenty's inverse formula (`geo/geodesic`), then + * the series the default renderer interpolates with, term for term, so a + * rectangle's centre matches its to floating-point noise. */ -import { TWO_PI, WGS84 } from './math.js'; +import { deltaLambda, geodesicInverse as inverse } from '../../geo/geodesic.js'; +import { WGS84 } from './math.js'; -const EPSILON12 = 1e-12; const A = WGS84.radii.x; const B = WGS84.radii.z; const F = (A - B) / A; -function deltaLambda(sineAlpha, cos2Alpha, sigma, sinSigma, cosSigma, cos2Sm) { - const C = (F * cos2Alpha * (4 + F * (4 - 3 * cos2Alpha))) / 16; - return ( - (1 - C) * - F * - sineAlpha * - (sigma + C * sinSigma * (cos2Sm + C * cosSigma * (2 * cos2Sm * cos2Sm - 1))) - ); -} - -/** Distance, start heading and u² of the geodesic from (lon1, lat1) to (lon2, lat2), radians. */ -function inverse(lon1, lat1, lon2, lat2) { - const l = lon2 - lon1; - const u1 = Math.atan((1 - F) * Math.tan(lat1)); - const u2 = Math.atan((1 - F) * Math.tan(lat2)); - const cosU1 = Math.cos(u1); - const sinU1 = Math.sin(u1); - const cosU2 = Math.cos(u2); - const sinU2 = Math.sin(u2); - const cc = cosU1 * cosU2; - const cs = cosU1 * sinU2; - const ss = sinU1 * sinU2; - const sc = sinU1 * cosU2; - let lambda = l; - let lambdaDot = TWO_PI; - let cosLambda; - let sinLambda; - let sigma; - let cosSigma; - let sinSigma; - let cos2Alpha; - let cos2Sm; - do { - cosLambda = Math.cos(lambda); - sinLambda = Math.sin(lambda); - const temp = cs - sc * cosLambda; - sinSigma = Math.sqrt(cosU2 * cosU2 * sinLambda * sinLambda + temp * temp); - cosSigma = ss + cc * cosLambda; - sigma = Math.atan2(sinSigma, cosSigma); - let sineAlpha; - if (sinSigma === 0) { - sineAlpha = 0; - cos2Alpha = 1; - } else { - sineAlpha = (cc * sinLambda) / sinSigma; - cos2Alpha = 1 - sineAlpha * sineAlpha; - } - lambdaDot = lambda; - cos2Sm = cosSigma - (2 * ss) / cos2Alpha; - if (!isFinite(cos2Sm)) cos2Sm = 0; - lambda = - l + deltaLambda(sineAlpha, cos2Alpha, sigma, sinSigma, cosSigma, cos2Sm); - } while (Math.abs(lambda - lambdaDot) > EPSILON12); - const uSquared = (cos2Alpha * (A * A - B * B)) / (B * B); - const bigA = - 1 + - (uSquared * (4096 + uSquared * (uSquared * (320 - 175 * uSquared) - 768))) / - 16384; - const bigB = - (uSquared * (256 + uSquared * (uSquared * (74 - 47 * uSquared) - 128))) / - 1024; - const cos2Sm2 = cos2Sm * cos2Sm; - const deltaSigma = - bigB * - sinSigma * - (cos2Sm + - (bigB * - (cosSigma * (2 * cos2Sm2 - 1) - - (bigB * cos2Sm * (4 * sinSigma * sinSigma - 3) * (4 * cos2Sm2 - 3)) / - 6)) / - 4); - return { - distance: B * bigA * (sigma - deltaSigma), - startHeading: Math.atan2(cosU2 * sinLambda, cs - sc * cosLambda), - uSquared, - }; -} - /** * The longitude and latitude (radians) `fraction` of the way along the * geodesic from (lon1, lat1) to (lon2, lat2). diff --git a/src/render/stub/index.js b/src/render/stub/index.js index 82f8ee84d..95feb9a9a 100644 --- a/src/render/stub/index.js +++ b/src/render/stub/index.js @@ -9,6 +9,7 @@ * Nothing runs on its own: `testing.tick()` and `testing.advance()` drive the * loop on a virtual clock, one frame at a time, in the contract's order. */ +import { horizonFrom } from '../../geo/horizon.js'; import { createInputRouter } from '../input/router.js'; import { CAPABILITIES, CONTRACT_VERSION } from '../contract/index.js'; import { createStubCamera } from './camera.js'; @@ -27,7 +28,6 @@ import { toDegrees, toEcef, vec, - WGS84, } from './math.js'; const FRAME_MS = 1000 / 60; @@ -504,15 +504,7 @@ export function createStubRenderer(options = {}) { } function isOccluded(position) { - const e = eye(); - const r = WGS84.oneOverRadii; - const cv = vec(e.position.x * r.x, e.position.y * r.y, e.position.z * r.z); - const vh = dot(cv, cv) - 1; - const t = vec(position.x * r.x, position.y * r.y, position.z * r.z); - const vt = sub(t, cv); - const vtDotVc = -dot(vt, cv); - if (vh < 0) return vtDotVc > 0; - return vtDotVc > vh && (vtDotVc * vtDotVc) / dot(vt, vt) > vh; + return !horizonFrom(eye().position).isPointVisible(position); } let scriptedPicks = null; diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index 974a48b02..7c70d5f07 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -70,6 +70,7 @@ const DRAW_FROM_CALLER = new Set([ './layers/gnss', './layers/perimeters', './layers/awareness', + './layers/submarine-cables', ]); const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));