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.
This commit is contained in:
Sameh Khamis committed 2026-11-07 00:38:20 -08:00
1 parent bb85e0fa74
commit f6422d2247
16 files changed
+394 -190

No files matched your search

+4 -4
View File
@@ -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,
};
+53
View File
@@ -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<object>|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;
}
+1 -8
View File
@@ -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,
+19 -13
View File
@@ -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(
+4 -1
View File
@@ -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) {
+147 -129
View File
@@ -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,
+8 -6
View File
@@ -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
+1 -2
View File
@@ -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. */
+4 -3
View File
@@ -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)