From f6422d2247c4d0fd34c7c945f3d3d16dfe14fddd Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sat, 7 Nov 2026 00:37:51 -0800 Subject: [PATCH] Draw the vessels layer's ships through the renderer's ports The ships are one icon set from the draw port, held on course with hold motion segments and drawn over depth as before; the layer keeps what it last drew in an icon book and reads focus and pick ownership back from there, matching clicks on the draw hit's set and id. Its frame hook, camera pose, horizon test and screen projection come from the frame, camera and query ports, with the horizon lift in geo/horizon judging the same point the GPU cull does. The icons' draw set is disposed when the layer is destroyed. rendering.js no longer imports Cesium or touches the scene's primitives, picks, render events or camera, and leaves the Cesium allow-list. It still reads the canvas size for the label budget. Callers of the vessels entry load the Cesium adapter's unbound fallbacks. --- docs/CURRENT-STATE.md | 4 + scripts/package-boundaries.json | 3 + src/data/aisLiveVessels.test.mjs | 67 +++-- src/data/focusResumeGate.test.mjs | 7 +- src/layers/vessels/evidence.js | 8 +- src/layers/vessels/iconBook.js | 53 ++++ src/layers/vessels/lifecycle.js | 9 +- src/layers/vessels/ownership.test.mjs | 32 ++- src/layers/vessels/renderGovernor.test.mjs | 5 +- src/layers/vessels/rendering.js | 276 +++++++++++---------- src/layers/vessels/selection.js | 14 +- src/layers/vessels/state.js | 3 +- src/layers/vessels/testing.js | 7 +- src/render/cesium/draw.test.mjs | 94 +++++++ src/render/cesiumAllowList.json | 1 - src/render/unboundCamera.test.mjs | 1 + 16 files changed, 394 insertions(+), 190 deletions(-) create mode 100644 src/layers/vessels/iconBook.js diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index d4ded2b2a..d36bbe144 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1109,6 +1109,10 @@ destroying the layer cancels pending work and ignores late results. `./layers/vessels` package entry. The factory owns feed lifecycle, keyed records, rendering, selection, trails and cards in separate components. The standalone entry supplies its AISStream source, scene services and existing row limits. +Its ship icons are one renderer icon draw set (held motion, course rotation, +focus emphasis, horizon cull) and the entry no longer reaches Cesium, so a +caller handing it a Cesium viewer, with no renderer bound, +loads the `./render/cesium/unbound` export once first. Incomplete observations retain missing keyed vessels for at most five minutes since their last accepted receipt, within the renderer's row budget (plus the diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index b3e885a2d..c95b42f39 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1687,6 +1687,7 @@ "src/layers/vessels/queries.js", "src/geo/vector.js", "src/layers/vessels/rendering.js", + "src/layers/vessels/iconBook.js", "src/data/entityRecords.js", "src/data/iconSetPrimitive.js", "src/data/iconSet.js", @@ -3450,6 +3451,7 @@ "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", "src/layers/vessels/rendering.js", + "src/layers/vessels/iconBook.js", "src/layers/vessels/selection.js", "src/layers/vessels/state.js", "src/layers/vessels/testing.js", @@ -4395,6 +4397,7 @@ "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", "src/layers/vessels/rendering.js", + "src/layers/vessels/iconBook.js", "src/layers/vessels/selection.js", "src/layers/vessels/state.js", "src/layers/vessels/testing.js", diff --git a/src/data/aisLiveVessels.test.mjs b/src/data/aisLiveVessels.test.mjs index f9a514a5b..26c0a175a 100644 --- a/src/data/aisLiveVessels.test.mjs +++ b/src/data/aisLiveVessels.test.mjs @@ -40,7 +40,8 @@ import { presentSelectedVessel, subscribeSelectedVessel, } from '../hudReadouts.js'; -import { createIconSet } from './iconSet.js'; +import { createVesselIconBook } from '../layers/vessels/iconBook.js'; +import { bindRenderer } from '../render/rendererOf.js'; test('open feed with vessels is healthy (null)', () => { assert.equal( @@ -769,12 +770,12 @@ test('disable and destroy make abort-ignoring AIS responses inert', async () => /** One vessel row in a fresh set, as the layer adds it, plus its record. */ function focusFixture() { - const icons = createIconSet(); - const row = icons.add('353136000', { - layer: 'ais-live-vessels', + const icons = createVesselIconBook(); + icons.put({ id: '353136000', + size: [32, 32], + meta: { layer: 'ais-live-vessels', id: '353136000' }, }); - icons.setSize(row, 32, 32); const record = { iconId: '353136000', position: { x: 1, y: 2, z: 3 }, @@ -784,7 +785,7 @@ function focusFixture() { icons, records: [record], record, - focus: () => icons.focus(icons.row('353136000')), + focus: () => icons.focus('353136000'), }; } @@ -1192,9 +1193,18 @@ test('vessel interaction wire: CCTV-owned pick preserves vessel selection', () = }); test('vessel interaction wire: own-layer unkeyed record pick does not deselect', () => { - const icons = createIconSet(); - icons.add('ais-unkeyed:1', { id: 'ais-unkeyed:1' }); - const harness = installWireHarness({ id: 'ais-unkeyed:1' }, { icons }); + // The layer's icon set, drawing the unkeyed row. + const icons = createVesselIconBook({ + id: 'ais-vessels:test', + upsert() {}, + remove() {}, + dispose() {}, + }); + icons.put({ id: 'ais-unkeyed:1', size: [32, 32], meta: {} }); + const harness = installWireHarness( + { id: { set: 'ais-vessels:test', id: 'ais-unkeyed:1' } }, + { icons }, + ); try { harness.handler.click({ position: { x: 10, y: 20 } }); assert.equal( @@ -1564,19 +1574,36 @@ test('buildSelectedVesselCard: full detail card with MMSI + position time', () = test('vessel host publication preserves the shipped grid winner and separation selector', () => { const publications = []; - const originalProjection = Cesium.SceneTransforms.worldToWindowCoordinates; - const makeCandidate = (mmsi, name, x, y, speed = 1) => - makeRecord({ + // Where the query port projects each candidate, by its position's x. + const screens = new Map(); + const makeCandidate = (mmsi, name, x, y, speed = 1) => { + const key = screens.size + 1; + screens.set(key, { x, y }); + return makeRecord({ mmsi, name, speed, - position: { x: 1, y: 2, z: 3, screen: { x, y } }, + position: { x: key, y: 2, z: 3 }, }); + }; const low = makeCandidate('100', 'VESSEL', 20, 20, 1); const winner = makeCandidate('200', 'NAMED WINNER', 40, 30, 16); const separated = makeCandidate('300', 'SEPARATED', 400, 300, 3); - Cesium.SceneTransforms.worldToWindowCoordinates = (_scene, position) => - position.screen; + const viewer = { + scene: { canvas: { clientWidth: 1600, clientHeight: 900 } }, + }; + const unbind = bindRenderer(viewer, { + query: { + project: (p) => screens.get(p.x) ?? null, + projectMany(source, out) { + for (let i = 0; i * 3 < source.length; i++) { + const screen = screens.get(source[i * 3]); + out[i * 2] = screen ? screen.x : NaN; + out[i * 2 + 1] = screen ? screen.y : NaN; + } + }, + }, + }); _setVesselOverlayHostForTest({ setEntries(sourceId, entries, options) { publications.push({ sourceId, entries, options }); @@ -1585,7 +1612,7 @@ test('vessel host publication preserves the shipped grid winner and separation s clearSource() {}, }); _setVesselStateForTest({ - viewer: { scene: { canvas: { clientWidth: 1600, clientHeight: 900 } } }, + viewer, records: [low, winner, separated], }); try { @@ -1599,7 +1626,7 @@ test('vessel host publication preserves the shipped grid winner and separation s assert.equal(publications[0].options.cohortLimit, 112); assert.equal(publications[0].options.collisionCapacity, 112); } finally { - Cesium.SceneTransforms.worldToWindowCoordinates = originalProjection; + unbind(); _setVesselStateForTest({ enabled: false }); _setVesselOverlayHostForTest(); } @@ -2009,13 +2036,13 @@ test('vessel selection passes the opaque source reference to optional history', }); test('vessel focus wire skips hidden sprites at rest while a target is tracked', () => { - const icons = createIconSet(); + const icons = createVesselIconBook(); const records = Array.from({ length: 51 }, (_, i) => { const iconId = String(i); - icons.setSize(icons.add(iconId, { id: iconId }), 32, 32); + icons.put({ id: iconId, size: [32, 32], meta: { id: iconId } }); return { iconId, position: { x: 1, y: 2, z: 3 }, visible: i === 0 }; }); - const focus = (record) => icons.focus(icons.row(record.iconId)); + const focus = (record) => icons.focus(record.iconId); const target = { screenRect: { left: 40, top: 40, right: 60, bottom: 60 }, paddingPx: 0, diff --git a/src/data/focusResumeGate.test.mjs b/src/data/focusResumeGate.test.mjs index 5e70f1ab1..eba05fffc 100644 --- a/src/data/focusResumeGate.test.mjs +++ b/src/data/focusResumeGate.test.mjs @@ -5,6 +5,7 @@ import { applyCctvFocusDeemphasis } from './cctv.js'; import { applySatellitePointFocusDeemphasis } from './satellites.js'; import { DEFAULT_FOCUS_DEEMPHASIS_PARAMS } from './focusDeemphasis.js'; import { createIconSet } from './iconSet.js'; +import { createVesselIconBook } from '../layers/vessels/iconBook.js'; const params = { ...DEFAULT_FOCUS_DEEMPHASIS_PARAMS, paddingPx: 0 }; const target = { @@ -63,8 +64,8 @@ function assertResumeGate(name, makePass) { } assertResumeGate('vessel', () => { - const icons = createIconSet(); - icons.setSize(icons.add('353136000', { id: '353136000' }), 32, 32); + const icons = createVesselIconBook(); + icons.put({ id: '353136000', size: [32, 32], meta: { id: '353136000' } }); const record = { iconId: '353136000', position: { x: 1, y: 2, z: 3 }, @@ -82,7 +83,7 @@ assertResumeGate('vessel', () => { cameraDistanceFor: () => 1200, params, }), - readAlpha: () => icons.focus(icons.row('353136000')), + readAlpha: () => icons.focus('353136000'), }; }); diff --git a/src/layers/vessels/evidence.js b/src/layers/vessels/evidence.js index 91503410c..3c84924b8 100644 --- a/src/layers/vessels/evidence.js +++ b/src/layers/vessels/evidence.js @@ -41,13 +41,13 @@ export function createEvidence({ const query = findQuery(state.viewer); return state.records.all.map((record) => { const visual = components.rendering.getVisual(record); - const row = state.icons?.row(visual.iconId) ?? -1; - const position = row >= 0 ? visual.position : null; + const drawn = state.icons?.has(visual.iconId) === true; + const position = drawn ? visual.position : null; const screen = position ? query?.project(position) : null; return { id: record.mmsi, - show: row >= 0 && visual.visible === true, - alpha: row >= 0 ? state.icons.focus(row) : null, + show: drawn && visual.visible === true, + alpha: drawn ? state.icons.focus(visual.iconId) : null, x: screen?.x ?? null, y: screen?.y ?? null, }; diff --git a/src/layers/vessels/iconBook.js b/src/layers/vessels/iconBook.js new file mode 100644 index 000000000..16e089308 --- /dev/null +++ b/src/layers/vessels/iconBook.js @@ -0,0 +1,53 @@ +/** + * The vessel icons the layer draws, as it last drew them: each icon item by + * its row id, and the renderer draw set they go to. The layer reads its own + * icons back from here (focus emphasis, ownership of a pick), never from the + * renderer. + */ + +/** + * @param {import('../../render/contract/draw').DrawSet|null} [drawSet] + * Where the icons are drawn; none keeps them only here (tests). + */ +export function createVesselIconBook(drawSet = null) { + const items = new Map(); + const book = { + /** The draw set's id, or null. */ + setId: drawSet?.id ?? null, + get show() { + return drawSet ? drawSet.show : true; + }, + set show(value) { + if (drawSet) drawSet.show = value; + }, + /** How many icons are drawn. */ + get size() { + return items.size; + }, + /** The drawn row ids, in the order first drawn. */ + ids: () => [...items.keys()], + /** Whether a row id is drawn. */ + has: (id) => items.has(id), + /** The item drawn under a row id, or undefined. */ + item: (id) => items.get(id), + /** Draw an item (anew, or as it now is). */ + put(item) { + items.set(item.id, item); + drawSet?.upsert([item]); + }, + remove(id) { + if (items.delete(id)) drawSet?.remove([id]); + }, + /** A row's focus emphasis, 1 when not de-emphasised. */ + focus: (id) => items.get(id)?.focus ?? 1, + setFocus(id, factor) { + const item = items.get(id); + if (item) book.put({ ...item, focus: factor }); + }, + dispose() { + items.clear(); + drawSet?.dispose(); + }, + }; + return book; +} diff --git a/src/layers/vessels/lifecycle.js b/src/layers/vessels/lifecycle.js index 4fb628a97..4aa76817c 100644 --- a/src/layers/vessels/lifecycle.js +++ b/src/layers/vessels/lifecycle.js @@ -115,7 +115,6 @@ export function createLifecycle({ state.feed.firstConnectTimer = null; state.feed.abort = null; state.icons = null; - state.iconPrimitive = null; state.records.all = []; state.records.byMmsi = new Map(); state.records.unkeyed = []; @@ -232,13 +231,7 @@ export function createLifecycle({ unregisterPickOwner('ais-live-vessels'); components.selection.clearVesselInspection(); components.tracking.destroySelectedVesselTrail(); - if (state.iconPrimitive && activeViewer?.scene?.primitives) { - activeViewer.scene.primitives.remove(state.iconPrimitive); - } - // Not in a scene (or no viewer to remove it from): still stop its atlas - // listener and free its GPU resources. - if (state.iconPrimitive && !state.iconPrimitive.isDestroyed()) - state.iconPrimitive.destroy(); + components.rendering.disposeCollections(); vesselState._vesselOverlayHost.clearSource(VESSEL_OVERLAY_SOURCE_ID); vesselState._vesselOverlayHost.setVisible( VESSEL_OVERLAY_SOURCE_ID, diff --git a/src/layers/vessels/ownership.test.mjs b/src/layers/vessels/ownership.test.mjs index 955d012d4..bc70af17f 100644 --- a/src/layers/vessels/ownership.test.mjs +++ b/src/layers/vessels/ownership.test.mjs @@ -3,7 +3,16 @@ import assert from 'node:assert/strict'; import { createVesselLayer } from './index.js'; import { createVesselState } from './state.js'; import * as Cesium from 'cesium'; -import { createIconSet } from '../../data/iconSet.js'; +import { createVesselIconBook } from './iconBook.js'; +import { liftedForHorizon } from '../../geo/horizon.js'; +import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs'; +import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs'; + +/** A query port with nothing on screen: the viewer doubles have no scene. */ +const offscreen = { + project: () => null, + projectMany: (source, out) => out.fill(NaN), +}; const noop = () => {}; function services() { @@ -40,7 +49,9 @@ function services() { } function setup(source, options = {}, viewer = {}) { const layer = createVesselLayer({ source, services: services(), options }); - const icons = createIconSet(); + const icons = createVesselIconBook(); + if (viewer.camera) + bindFakeCesiumCamera(viewer, { query: offscreen, draw: fakeDrawPort() }); layer.testing._setVesselStateForTest({ viewer, icons }); let now = 1000; layer.testing._setAisRuntimeForTest({ @@ -279,19 +290,17 @@ test('refresh keeps the icon row and its pick identity, and eviction releases th let current = snapshot([observation('111')]); const { layer, icons } = setup({ getSnapshot: async () => current }); await layer.update(); - assert.equal(icons.count, 1); - assert.equal(icons.idAt(0), '111'); - const meta = icons.metaAt(0); - const drawn = () => - icons.position(icons.row('111'), 0, new Cesium.Cartesian3()); + assert.deepEqual(icons.ids(), ['111']); + const meta = icons.item('111').meta; + const drawn = () => icons.item('111').pos; const near = (a, b) => Cesium.Cartesian3.distance(a, b) < 0.01; assert.ok(near(layer.findByQuery('111').position, drawn())); const oldPosition = drawn(); current = snapshot([{ ...observation('111'), longitude: 4.06 }]); await layer.update(); - assert.equal(icons.count, 1); + assert.equal(icons.size, 1); assert.equal( - icons.metaAt(icons.row('111')), + icons.item('111').meta, meta, 'focus identity survives a refresh', ); @@ -431,12 +440,9 @@ test('cards and detection judge the horizon where the icon shader culls the row' viewer, ); await layer.update(); - const row = icons.row('111'); occluder.cameraPosition = positionWC; assert.equal( - occluder.isPointVisible( - icons.cullPoint(row, icons.position(row, 0, new Cesium.Cartesian3())), - ), + occluder.isPointVisible(liftedForHorizon(icons.item('111').pos)), true, ); assert.deepEqual( diff --git a/src/layers/vessels/renderGovernor.test.mjs b/src/layers/vessels/renderGovernor.test.mjs index 2fec27871..bc38b95bb 100644 --- a/src/layers/vessels/renderGovernor.test.mjs +++ b/src/layers/vessels/renderGovernor.test.mjs @@ -2,6 +2,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { createVesselLayer } from './index.js'; import { VISIBILITY_UPDATE_MS } from './policy.js'; +import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs'; // Vessels move only when a poll lands, so the layer must let the scene idle: // it asks for frames for forced passes and one trailing frame after the camera @@ -54,7 +55,9 @@ function setup() { pitch: -1.2, roll: 0, }; - layer.testing._setVesselStateForTest({ viewer: { camera, scene: {} } }); + const viewer = { camera, scene: {} }; + bindFakeCesiumScene(viewer); + layer.testing._setVesselStateForTest({ viewer }); layer.testing._setAisRuntimeForTest({ now: () => clock, setTimeout(fn, ms) { diff --git a/src/layers/vessels/rendering.js b/src/layers/vessels/rendering.js index 8e5e4b276..0b915e60a 100644 --- a/src/layers/vessels/rendering.js +++ b/src/layers/vessels/rendering.js @@ -1,8 +1,3 @@ -import * as Cesium from 'cesium'; -// The Cesium camera factory, which loads the query factory: given a viewer -// of a caller's own, with no renderer bound, the view area and evidence -// reads still find a camera and a query port. -import '../../render/cesium/camera.js'; import { t } from '../../i18n/index.js'; import { vesselTypeCss, @@ -11,15 +6,16 @@ import { applyVesselOverlayPolicy, VESSEL_CARD_FADE_DISTANCE_M, } from '../../data/vesselLabels.js'; -import { cameraPoseSignature } from '../../data/iconOrientation.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { horizonFrom, liftedForHorizon } from '../../geo/horizon.js'; +import { distance } from '../../geo/vector.js'; import { - createIconSet, - ICON_CULL_LIFT, - ICON_ROTATES, -} from '../../data/iconSet.js'; -import { writeHoldSegment } from '../../data/iconSegment.js'; -import { IconSetPrimitive } from '../../data/iconSetPrimitive.js'; -import { iconAtlas } from '../../data/iconAtlas.js'; + drawOf, + findCamera, + findFrame, + findQuery, +} from '../../render/rendererOf.js'; +import { createVesselIconBook } from './iconBook.js'; import { VESSEL_LIFT_M, DEFAULT_RENDER_ROWS, @@ -33,6 +29,20 @@ import { /** The ship artwork's own raster size (px). */ const SHIP_ICON_PX = 32; +let instances = 0; + +/** + * The camera pose a pass evaluated, to the precision that moves what it + * draws: the eye to 10 m and its angles to a milliradian. + */ +function poseSignature(pose) { + const p = pose.position; + return ( + `${Math.round(p.x / 10)}:${Math.round(p.y / 10)}:${Math.round(p.z / 10)}:` + + `${pose.heading.toFixed(3)}:${pose.pitch.toFixed(3)}:${pose.roll.toFixed(3)}` + ); +} + export function createRendering({ vesselState, services, @@ -73,22 +83,26 @@ export function createRendering({ * Where a record's icon is anchored: VESSEL_LIFT_M above the sea surface * (the geoid, once its grid has loaded). * @param {Object} record - Vessel record with a finite lat/lon. - * @returns {Cesium.Cartesian3} A Cesium position: icon rows, focus and the - * layer's queries take it as it is. + * @returns {{x: number, y: number, z: number}} ECEF metres: icon items, + * focus and the layer's queries take it as it is. */ function anchorPosition(record) { const heightM = components.queries.vesselDatumHeightM( components.tracking.currentGeoidN(record.lat, record.lon), VESSEL_LIFT_M, ); - return Cesium.Cartesian3.fromDegrees(record.lon, record.lat, heightM); + return fromDegrees(record.lon, record.lat, heightM); } + // Reused projection buffers for the card pass, grown to the candidates. + let worldXyz = new Float64Array(0); + let screenXy = new Float32Array(0); + function resetRecordVisuals() { visualRecords = new WeakMap(); } - const { registerSpriteCollection } = services.sprites; + const { registerSpriteSet } = services.sprites; const { forgetSpriteFocus, focusNowMs, @@ -121,25 +135,51 @@ export function createRendering({ } /** - * The layer's icon set and its primitive. Vessels hold still between polls, - * so each row is a hold segment and the primitive's clock only keeps segment - * times small. The set draws depth-test-free on the near plane and culls the - * far side on the GPU (locked height-datum principle #2: contacts are ALWAYS - * visible; the tile sea mesh ≠ the geoid, so a depth-tested chevron at the - * geoid would clip behind local tide/mesh noise). + * The layer's icon draw set. Vessels hold still between polls, so each + * item's motion is a hold at its anchor, turned along its course on screen. + * The set draws over depth and culls the far side of the horizon, judged a + * little above sea level (locked height-datum principle #2: contacts are + * ALWAYS visible; the tile sea mesh ≠ the geoid, so a depth-tested chevron + * at the geoid would clip behind local tide/mesh noise). */ function ensureCollections(viewer) { if (!viewer || state.icons) return; - const epoch = Cesium.JulianDate.now(); - state.icons = createIconSet({ epoch }); - state.icons.show = state.feed.enabled; - state.iconPrimitive = new IconSetPrimitive({ - set: state.icons, - renderTime: () => epoch, - requestRender: () => governorRequestRender('ais-vessels-icons'), + const set = drawOf(viewer).icons({ + id: `ais-vessels:${++instances}`, + horizonCull: true, }); - viewer.scene.primitives.add(state.iconPrimitive); - registerSpriteCollection('ais', state.iconPrimitive); + // Columns of no rows put the set's host in the scene now, where the + // sprite order finds it, rather than with its first vessel. + set.setColumns?.({ ids: [] }); + state.icons = createVesselIconBook(set); + state.icons.show = state.feed.enabled; + registerSpriteSet?.('ais', set.id); + } + + /** Let the icon draw set go (the layer is destroyed). */ + function disposeCollections() { + state.icons?.dispose(); + state.icons = null; + } + + /** The icon item a record draws, as it now is. */ + function iconItem(record, visual) { + const selected = record === state.selectedRecord; + const courseDeg = vesselCourseDeg(record); + return { + id: visual.iconId, + pos: visual.position, + image: shipIcon(record, selected), + size: [SHIP_ICON_PX, SHIP_ICON_PX], + scale: shipScale(record) * (selected ? 1.2 : 1), + rotationMode: 'course', + // Held on course; `course` for renderers without motion segments. + course: courseDeg, + motion: { kind: 'hold', courseDeg }, + focus: state.icons?.focus(visual.iconId) ?? 1, + disableDepthTest: Infinity, + meta: visual.meta, + }; } /** @@ -147,53 +187,32 @@ export function createRendering({ * (vesselLabels.js) rebuilt by the declutter pass — no per-record label * primitive exists anymore. * @param {Object} record - Normalized vessel record. - * @param {Cesium.EllipsoidalOccluder|null} occluder - Horizon occluder for initial visibility. + * @param {{isPointVisible: Function}|null} occluder - Horizon test for initial visibility. */ function addRecordPrimitives(record, occluder) { const visual = getVisual(record); - const set = state.icons; - const row = set.add(visual.iconId, { - layer: 'ais-live-vessels', - id: visual.iconId, - }); - set.setSize(row, SHIP_ICON_PX, SHIP_ICON_PX); - set.setFlag(row, ICON_ROTATES, true); - // Sea level sits at geoid N, below the ellipsoid across much of the ocean. - set.setFlag(row, ICON_CULL_LIFT, true); - set.setShown(row, true); - syncRecordIcon(record); + // The pick meta, and the key of the vessel's focus emphasis. + visual.meta = { layer: 'ais-live-vessels', id: visual.iconId }; + state.icons.put({ ...iconItem(record, visual), focus: 1 }); + if (visual.position) + visual.cullPosition = liftedForHorizon(visual.position); visual.visible = isVisible(visual.cullPosition, occluder); } /** - * Write a record's row from its visual position, course, tint and selection, - * and keep the point the shader judges the horizon at (`cullPosition`) so - * the CPU card/focus pass draws the same boundary. + * Draw a record's icon from its visual position, course, tint and + * selection, and keep the point the renderer judges the horizon at + * (`cullPosition`: lifted to a little above sea level, as a horizon-culled + * GPU icon is) so the CPU card/focus pass draws the same boundary. * @param {Object} record - Vessel record with a prepared visual. */ function syncRecordIcon(record) { const visual = getVisual(record); - const set = state.icons; - const row = set?.row(visual.iconId) ?? -1; - if (row < 0 || !visual.position) return; - const selected = record === state.selectedRecord; - const slot = iconAtlas.slot(shipIcon(record, selected), SHIP_ICON_PX); - set.setImage(row, slot, slot); - set.setScale(row, shipScale(record) * (selected ? 1.2 : 1)); - writeHoldSegment( - set.segments, - row, - visual.position, - vesselCourseDeg(record), - ); - set.segmentWritten(row); - visual.cullPosition = set.cullPoint( - row, - visual.position, - visual.cullPosition, - ); + if (!state.icons?.has(visual.iconId) || !visual.position) return; + state.icons.put(iconItem(record, visual)); + visual.cullPosition = liftedForHorizon(visual.position); } /** @@ -203,12 +222,11 @@ export function createRendering({ function removeRecordPrimitives(record) { if (!record) return; - const set = state.icons; + const icons = state.icons; const visual = getVisual(record); - const row = set?.row(visual.iconId) ?? -1; - if (row < 0) return; - forgetSpriteFocus(set.metaAt(row)); - set.remove(visual.iconId); + if (!icons?.has(visual.iconId)) return; + forgetSpriteFocus(icons.item(visual.iconId).meta); + icons.remove(visual.iconId); } function shipScale(record) { @@ -221,7 +239,7 @@ export function createRendering({ /** * Best available real-world direction of travel for a vessel, degrees * clockwise from north (true heading preferred, course-over-ground fallback). - * The icon set turns this into its screen rotation on the GPU each frame. + * The renderer turns this into its screen rotation each frame. * @param {Object} record - Vessel record. * @returns {number} Course in degrees (0 when unknown). */ @@ -268,9 +286,8 @@ export function createRendering({ // own label publication requests a frame, and scheduling on that would loop. function installRuntime(viewer) { if (state.preRenderRemover || !viewer) return; - state.preRenderRemover = viewer.scene.preRender.addEventListener(() => - updateVisibility(), - ); + state.preRenderRemover = + findFrame(viewer)?.on('preRender', () => updateVisibility()) ?? null; } function scheduleTrailingVisibilityPass(now) { @@ -296,6 +313,7 @@ export function createRendering({ if (force) governorRequestRender('ais-vessels-update'); const now = focusNowMs(performance.now()); const focusTarget = getFocusTarget(); + const pose = state.viewer ? findCamera(state.viewer)?.pose() : null; const regularPass = force || now - state.lastVisibilityUpdate >= VISIBILITY_UPDATE_MS; const focusPass = @@ -303,8 +321,8 @@ export function createRendering({ (force || now - state.lastFocusUpdate >= FOCUS_UPDATE_MS); if ( !regularPass && - state.viewer?.camera && - cameraPoseSignature(state.viewer.camera) !== vesselState._lastCamPoseSig + pose && + poseSignature(pose) !== vesselState._lastCamPoseSig ) scheduleTrailingVisibilityPass(now); if (!regularPass && !focusPass) return; @@ -315,10 +333,7 @@ export function createRendering({ // Still record the pose this pass evaluated, or every later frame that // falls inside the cadence would schedule another trailing frame. if (regularPass) { - if (state.viewer?.camera) - vesselState._lastCamPoseSig = cameraPoseSignature( - state.viewer.camera, - ); + if (pose) vesselState._lastCamPoseSig = poseSignature(pose); updateClusteredLabels([]); } if (focusPass) { @@ -328,15 +343,14 @@ export function createRendering({ return; } - const scene = state.viewer?.scene; - const camera = state.viewer?.camera; + const query = state.viewer ? findQuery(state.viewer) : null; if (regularPass) { // Candidate construction stays on the original 800 ms selector cadence. // The 80 ms focus-only pass below never allocates label candidates. // Icons cull and rotate on the GPU; this pass only picks the cards and // remembers which vessels the horizon leaves in view for focus. - if (camera) vesselState._lastCamPoseSig = cameraPoseSignature(camera); - const occluder = makeOccluder(); + if (pose) vesselState._lastCamPoseSig = poseSignature(pose); + const occluder = makeOccluder(pose); const labelCandidates = []; for (const record of state.records.all) { const visual = getVisual(record); @@ -345,20 +359,14 @@ export function createRendering({ } updateClusteredLabels(labelCandidates); } - if (focusPass && scene && camera) { + if (focusPass && query && pose) { const result = applyVesselFocusDeemphasis({ records: state.records.all, target: focusTarget, previousActiveCount: state.activeFocusCount, nowMs: now, - screenPositionFor: (position) => - Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - position, - vesselState._scratchFocusScreen, - ), - cameraDistanceFor: (position) => - Cesium.Cartesian3.distance(camera.positionWC, position), + screenPositionFor: (position) => query.project(position), + cameraDistanceFor: (position) => distance(pose.position, position), }); state.activeFocusCount = result.activeCount; if (result.activeCount > 0 || result.transitioning) @@ -368,13 +376,13 @@ export function createRendering({ } /** - * Apply focus emphasis to vessel icons through the set's focus column + * Apply focus emphasis to vessel icons through their items' `focus` * (narrow always-visible amendment: the ship chevron remains present at the * non-zero floor while it competes with the tracked target). Kept as a * production wire seam so the animation/deadband contract can be tested - * without constructing WebGL. + * without a renderer. * @param {object} input - * @param {object} [input.icons] The icon set (defaults to the layer's). + * @param {object} [input.icons] The icon book (defaults to the layer's). * @returns {{writes:number,transitioning:boolean,activeCount:number,ran:boolean}} */ @@ -396,10 +404,11 @@ export function createRendering({ let activeCount = 0; for (const record of records || []) { const visual = getVisual(record); - const row = icons?.row(visual?.iconId) ?? -1; + const id = visual?.iconId; + const item = icons?.item(id); const position = visual?.position; - if (row < 0 || !position) continue; - const sprite = icons.metaAt(row); + if (!item || !position) continue; + const sprite = item.meta; // Most of a worldwide feed sits behind the horizon. A hidden icon with // no pending focus state at full emphasis would advance to exactly what // it already is, so skip it instead of paying its distance and state @@ -407,7 +416,7 @@ export function createRendering({ if ( !visual.visible && spriteFocusAtRest(sprite) && - !focusAlphaNeedsWrite(icons.focus(row), 1, params) + !focusAlphaNeedsWrite(icons.focus(id), 1, params) ) continue; const focus = advanceSpriteFocus(sprite, { @@ -420,26 +429,24 @@ export function createRendering({ params, // Vessel artwork is 32 px before scale. Including the ambient // chevron's own rendered extent prevents edge-overlap misses. - spriteHalfWidthPx: icons.width(row) * icons.scale(row) * 0.5, - spriteHalfHeightPx: icons.height(row) * icons.scale(row) * 0.5, + spriteHalfWidthPx: item.size[0] * (item.scale ?? 1) * 0.5, + spriteHalfHeightPx: item.size[1] * (item.scale ?? 1) * 0.5, }); transitioning ||= focus.transitioning; if (focus.active) activeCount += 1; - if (focusAlphaNeedsWrite(icons.focus(row), focus.factor, params)) { - icons.setFocus(row, focus.factor); + if (focusAlphaNeedsWrite(icons.focus(id), focus.factor, params)) { + icons.setFocus(id, focus.factor); writes += 1; } } return { writes, transitioning, activeCount, ran: true }; } - function makeOccluder() { - const cameraPosition = state.viewer?.camera?.positionWC; - if (!cameraPosition) return null; - return new Cesium.EllipsoidalOccluder( - Cesium.Ellipsoid.WGS84, - cameraPosition, - ); + /** The ellipsoid's horizon from the eye, or null with no camera. */ + function makeOccluder( + pose = state.viewer ? findCamera(state.viewer)?.pose() : null, + ) { + return pose?.position ? horizonFrom(pose.position) : null; } function isVisible(cullPosition, occluder) { @@ -460,34 +467,47 @@ export function createRendering({ function updateClusteredLabels(records) { const viewer = state.viewer; - const scene = viewer?.scene; + const query = viewer ? findQuery(viewer) : null; const selected = state.selectedRecord; const entries = selected ? [components.cards.buildSelectedVesselCard(selected)] : []; const maxLabels = labelRowLimit(); - if (!scene || !records.length || maxLabels <= 0) { + if (!query || !records.length || maxLabels <= 0) { state.activeLabelCount = entries.length; publishVesselOverlayEntries(entries); return; } + // Every candidate projected in one call: NaN behind the eye. + const ambient = records.filter((record) => record !== selected); + if (worldXyz.length < ambient.length * 3) { + worldXyz = new Float64Array(ambient.length * 3); + screenXy = new Float32Array(ambient.length * 2); + } + ambient.forEach((record, i) => { + const p = getVisual(record).position; + worldXyz[i * 3] = p.x; + worldXyz[i * 3 + 1] = p.y; + worldXyz[i * 3 + 2] = p.z; + }); + query.projectMany( + worldXyz.subarray(0, ambient.length * 3), + screenXy.subarray(0, ambient.length * 2), + ); const cells = new Map(); - for (const record of records) { - const visual = getVisual(record); - if (record === selected) continue; - const screen = Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - visual.position, - ); - if (!screen) continue; - const key = `${Math.floor(screen.x / LABEL_GRID_PX)}:${Math.floor(screen.y / LABEL_GRID_PX)}`; + for (let i = 0; i < ambient.length; i++) { + const record = ambient[i]; + const x = screenXy[i * 2]; + const y = screenXy[i * 2 + 1]; + if (Number.isNaN(x) || Number.isNaN(y)) continue; + const key = `${Math.floor(x / LABEL_GRID_PX)}:${Math.floor(y / LABEL_GRID_PX)}`; const candidate = { record, score: labelPriority(record, selected), - x: screen.x, - y: screen.y, + x, + y, }; const existing = cells.get(key); if (!existing || candidate.score > existing.score) { @@ -499,10 +519,7 @@ export function createRendering({ // selected card's anchor seeds the accepted set so ambient cards keep clear. const accepted = []; if (selected) { - const screen = Cesium.SceneTransforms.worldToWindowCoordinates( - scene, - iconPosition(selected), - ); + const screen = query.project(iconPosition(selected)); if (screen) accepted.push({ x: screen.x, y: screen.y }); } const ranked = [...cells.values()].sort((a, b) => b.score - a.score); @@ -606,6 +623,7 @@ export function createRendering({ renderRowLimit, labelRowLimit, ensureCollections, + disposeCollections, addRecordPrimitives, syncRecordIcon, removeRecordPrimitives, diff --git a/src/layers/vessels/selection.js b/src/layers/vessels/selection.js index c7357b928..4dde9fa68 100644 --- a/src/layers/vessels/selection.js +++ b/src/layers/vessels/selection.js @@ -27,15 +27,17 @@ export function createSelection({ function bindVesselInteraction(viewer, keyTarget) { state.clickSubscription = inputFor(viewer).onClick((event) => { if (!state.feed.enabled) return; - const picked = event.hit; const pickedId = event.id; let record = pickedId ? state.records.byMmsi.get(pickedId) : null; - // A vessel icon's pick id is its row id: the MMSI, or an unkeyed row's. - // Removing a row destroys its pick id, so an evicted vessel cannot be - // picked at all; a live row whose record is gone stays a no-op below. - const rawId = picked?.id; + // A vessel icon's pick is an item of the layer's icon set, whose id is + // its row id: the MMSI, or an unkeyed row's. Removing a row removes its + // item, so an evicted vessel cannot be picked at all; a live row whose + // record is gone stays a no-op below. + const hit = event.drawHit; const ownRecordPick = - typeof rawId === 'string' && state.icons?.has(rawId) === true; + Boolean(hit) && + hit.set === state.icons?.setId && + state.icons.has(hit.id) === true; // An own-layer row without a live map key is a strict no-op (FB-1 // residual). Trails carry no layer identity and hug their contacts, so any diff --git a/src/layers/vessels/state.js b/src/layers/vessels/state.js index 4d3965126..368764102 100644 --- a/src/layers/vessels/state.js +++ b/src/layers/vessels/state.js @@ -55,9 +55,8 @@ export function createVesselState({ source, services }) { records: new VesselRecords({ now: () => vesselState._aisRuntime.now() }), viewer: null, - /** The vessels' icon set and the primitive that draws it. */ + /** The vessels' icons as drawn (`iconBook.js`), and their draw set. */ icons: null, - iconPrimitive: null, /** The click subscription's unsubscribe. */ clickSubscription: null, /** Exact EventTarget currently holding the Escape listener. */ diff --git a/src/layers/vessels/testing.js b/src/layers/vessels/testing.js index 789e80cad..9471fa0c4 100644 --- a/src/layers/vessels/testing.js +++ b/src/layers/vessels/testing.js @@ -1,5 +1,5 @@ import { DEFAULT_AIS_RUNTIME } from './policy.js'; -import { createIconSet } from '../../data/iconSet.js'; +import { createVesselIconBook } from './iconBook.js'; export function createTesting({ vesselState, @@ -49,8 +49,9 @@ export function createTesting({ .map((record) => [record.mmsi, record]), ); state.selectedRecord = options.selectedRecord || null; - state.icons = options.icons || createIconSet(); - state.iconPrimitive = null; + // `icons: null` leaves the layer to make its own draw set. + state.icons = + options.icons === null ? null : options.icons || createVesselIconBook(); state.trail = options.trail || null; state.trailMmsi = options.trailMmsi || null; state.trailPositions = Array.isArray(options.trailPositions) diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 0e592d6f9..4b2173e00 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -3,6 +3,7 @@ import * as Cesium from 'cesium'; import test from 'node:test'; import { bindRenderer, drawOf, findDraw } from '../rendererOf.js'; import { createCesiumDraw } from './draw.js'; +import { drawHitOf } from './drawHit.js'; // Node has no WebGL context to report line-width limits. Cesium.ContextLimits._minimumAliasedLineWidth = 1; @@ -1630,3 +1631,96 @@ test('icons scale, fade and show by eye distance, and drop the curves in place', assert.equal(a.show, false, 'an empty range shows it nowhere'); set.dispose(); }); + +test('the vessels layer draws its ships as one GPU icon set that holds them on course', async () => { + const { createVesselLayer } = await import('../../layers/vessels/index.js'); + const { IconSetPrimitive } = await import('../../data/iconSetPrimitive.js'); + const { ICON_CULL_LIFT, ICON_ROTATES } = + await import('../../data/iconSet.js'); + const scene = fakeScene(); + const part = createCesiumDraw({ + scene, + report: (error) => assert.fail(error), + }); + const viewer = { scene }; + const noop = () => {}; + const unbind = bindRenderer(viewer, { + draw: part.port, + query: { project: () => null, projectMany: (s, out) => out.fill(NaN) }, + }); + const layer = createVesselLayer({ + source: { getSnapshot: async () => ({ records: [] }) }, + services: { + context: { + clearSelectedEntityContextForLayer: noop, + registerEntityContext: () => null, + }, + trails: { + createTrail: () => ({ setPositions: noop, clear: noop, destroy: noop }), + }, + labels: { formatKnots: (knots) => `${knots} kt` }, + picking: { unregisterPickOwner: noop }, + overlay: { + setOverlayEntries: noop, + setOverlaySourceVisible: noop, + clearOverlaySource: noop, + }, + geoid: {}, + sprites: {}, + focus: { + focusNowMs: (now) => now, + getFocusTarget: () => null, + focusPassIsNeeded: () => false, + forgetSpriteFocus: noop, + }, + worldFocus: {}, + render: { + holdContinuousRender: noop, + releaseContinuousRender: noop, + governorRequestRender: noop, + }, + }, + }); + layer.testing._setVesselStateForTest({ viewer, icons: null }); + layer.testing._reconcileVesselsForTest(viewer, [ + { mmsi: '244000001', lat: 51.95, lon: 4.1, heading: 90, speed: 12 }, + { mmsi: '244000002', lat: 51.96, lon: 4.2, course: 200, speed: 2 }, + ]); + const [host] = scene.added; + assert.ok(host instanceof IconSetPrimitive, 'one GPU icon set'); + assert.match(host.drawSetId, /^ais-vessels:\d+$/); + const record = part.sets.get(host.drawSetId); + const set = record.gpu.set; + assert.equal(set.count, 2); + const row = set.row('244000001'); + const tau = set.seconds(Cesium.JulianDate.now()); + assert.equal(set.course(row, tau), 90, 'held on its heading'); + assert.equal(set.course(set.row('244000002'), tau), 200, 'or its course'); + assert.equal(set.width(row), 32); + assert.ok(Math.abs(set.scale(row) - 0.68) < 1e-6, 'scaled by speed'); + assert.equal(set.flags(row) & ICON_ROTATES, ICON_ROTATES); + assert.equal(set.flags(row) & ICON_CULL_LIFT, ICON_CULL_LIFT); + assert.ok(set.depthTestDistance(row) >= 1e30, 'over depth everywhere'); + const at = Cesium.Cartographic.fromCartesian(set.position(row, tau)); + assert.ok(Math.abs(Cesium.Math.toDegrees(at.longitude) - 4.1) < 1e-6); + assert.ok(Math.abs(Cesium.Math.toDegrees(at.latitude) - 51.95) < 1e-6); + const facade = { show: true }; + assert.deepEqual(drawHitOf(host._pickObject('244000001', null, facade)), { + set: host.drawSetId, + id: '244000001', + meta: { layer: 'ais-live-vessels', id: '244000001' }, + surface: false, + }); + + // A poll that moves one and drops the other writes rows, not a new host. + layer.testing._reconcileVesselsForTest(viewer, [ + { mmsi: '244000001', lat: 51.95, lon: 4.12, heading: 95, speed: 12 }, + ]); + assert.equal(scene.added[0], host); + assert.equal(set.count, 1); + assert.equal(set.course(set.row('244000001'), tau), 95); + + layer.destroy(viewer); + assert.equal(scene.added.length, 0, 'destroyed: the set goes'); + unbind(); +}); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 5735e0943..bdd24bf38 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -103,7 +103,6 @@ "src/layers/transit/lifecycle.js", "src/layers/transit/rendering.js", "src/layers/transit/testing.js", - "src/layers/vessels/rendering.js", "src/layers/weather/index.js", "src/layers/weather/shellRendering.js", "src/layers/wind/gpuRendering.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index d046bed70..5d2d2bd47 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -78,6 +78,7 @@ const DRAW_FROM_CALLER = new Set([ './layers/awareness', './layers/submarine-cables', './layers/alpr', + './layers/vessels', ]); const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));