Files
gods-eye-view/src/layers/vessels/selection.js
T
German Khokhlov 1fe8267550 refactor(vessels): Cesium rendering behind a renderer interface
src/layers/vessels/render/cesium.js holds the Cesium objects the layer
built itself, one for one: the translucent BillboardCollection of
chevrons (centred, screen-aligned, never depth-tested), the horizon
occluder, window projection, canvas size, viewer.trackedEntityChanged,
and the trail (data/trailRenderer's entity polyline, kept on Cesium: the
engine.lines Primitive path did not draw below the photoreal mesh in
round 6 — the plan's T13/T15 blocker; flights does the same).
The logic imports no Cesium: geo math, Rgba WHITE, the chevron artwork in
icons.js, clicks through the engine's selection dispatcher (own-rule
owner, same rule). Registered as CESIUM_LAYER_RENDERERS['ais-live-vessels'];
src/layers/vessels joins the boundary rule.

W1 replay vs 7c7422e2: vessels/flights/military/localAdsb counts, known
objects, screen points, requests and shot sha256 identical.
qa-vessel-cards --data synthetic 2/2 and qa-vessel-datum (?qaFeed=
vessels:fixture) 4/4, the same as 6eec8f6c.

Tests moved with the code (same meaning): cameraHandoff (the click body
is handleClick), inputOwnership (the guard precedes the click rule's
read of the pick), renderers.test (vessels in the extracted list),
importDirections (an unmoved example layer is satellites), the
ownership services fixture (renderer service).
2026-10-17 12:47:14 +04:00

310 lines
11 KiB
JavaScript

import { isPointerFree } from '../../data/inputOwnership.js';
import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js';
export function createSelection({
vesselState,
services,
parts: components,
layer,
options,
}) {
const { state } = vesselState;
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
const { requestWorldFocus } = services.worldFocus;
const {
selectEntityContext,
registerEntityContext,
clearSelectedEntityContextForLayer,
} = services.context;
const aisLiveVesselsLayer = layer;
/**
* Join the engine's selection dispatcher with this layer's own click rule
* (`onClick`: every click with its top pick, no gesture rule, as its old
* LEFT_CLICK handler), plus Escape and the "another layer took the camera"
* signal. The test seam (interactionHandlerFactory) gives a handler-like
* click source over a fake viewer's scene.pick instead.
* @param {object|null} scene The viewer, or the renderer's view.
*/
function installInteraction(scene) {
if (state.clickHandler || state.selectionRemove || !scene) return;
const keyTarget = state.interactionKeyTarget || document;
if (state.interactionHandlerFactory) {
bindVesselInteraction(
scene,
state.interactionHandlerFactory(scene),
keyTarget,
);
return;
}
const renderer = state.renderer;
const dispatcher = services.selection?.selectionDispatcherFor?.(
renderer?.engine,
);
if (!dispatcher) return;
state.selectionRemove = dispatcher.register('ais-live-vessels', {
// Owned while enabled (the lifecycle registers the same predicate on
// enable and drops it on disable).
owns: (id) => state.feed.enabled && state.records.byMmsi.has(id),
onClick: (ctx) => handleClick(ctx),
});
bindKeysAndFollow(renderer, keyTarget);
}
/** Test seam: a handler-like click source over `viewer.scene.pick`. */
function bindVesselInteraction(viewer, handler, keyTarget) {
state.clickHandler = handler;
handler.setInputAction((click) =>
handleClick({
position: click.position,
picked: viewer.scene.pick(click.position),
}),
);
// The follow signal of the Cesium renderer over that viewer.
bindKeysAndFollow(
services.renderer?.create({ viewer, engine: null }),
keyTarget,
);
}
function bindKeysAndFollow(renderer, keyTarget) {
state.keyTarget = keyTarget;
state.keydownHandler = onVesselKeyDown;
keyTarget.addEventListener('keydown', state.keydownHandler);
// Vessels never follow, so any new follow belongs to another layer and
// takes interaction ownership of the scene.
const follow = renderer?.follow;
state.trackedEntityRemover =
follow?.onChanged(() => {
if (follow.active() && state.selectedRecord) clearVesselInspection();
}) ?? null;
}
/** The vessel click rule (the old LEFT_CLICK handler's, as is). */
function handleClick(click) {
// A tool owns the pointer (src/data/inputOwnership.js): yield the click.
if (!isPointerFree()) return;
if (!state.feed.enabled) return;
const picked = click.picked;
const pickedId = resolvePickId(picked);
let record = pickedId ? state.records.byMmsi.get(pickedId) : null;
const ownRecordPick = Boolean(pickedRecordOf(picked));
// An own-layer record without a live map key is a strict no-op (FB-1
// residual). Trails carry no layer identity and hug their contacts, so any
// `gev-trail:*` pick is also a no-op. Every other non-vessel pick — sibling
// unowned scene picks dismiss the current vessel inspection.
if (ownRecordPick && (!pickedId || !record)) return;
if (pickedId && !record && String(pickedId).startsWith('gev-trail:'))
return;
// A sibling layer already owns this click. Preserve the current vessel
// selection and do not compete with its camera command.
const siblingOwned =
pickedId && isOwnedByOtherLayer('ais-live-vessels', pickedId);
// Cyclone geometry is ambient context behind painted cards. Its handler
// yields to the same foreground AIS hit. Keep moving-contact precedence
// unchanged: those handlers may issue their own camera command.
const cycloneBackground =
siblingOwned && !isOwnedByOtherLayer('weather-cyclones', pickedId);
if (siblingOwned && !cycloneBackground) return;
// Cards are painted on a pointer-events:none canvas, so the scene pick is
// usually terrain behind the card. Resolve against the host's current
// actionable hit rectangles before treating the click as empty space.
const cardHit = !record
? vesselState._vesselOverlayHost.hitTest?.(
click.position?.x,
click.position?.y,
{
...(cycloneBackground
? {}
: { sourceId: VESSEL_OVERLAY_SOURCE_ID }),
},
)
: null;
if (cycloneBackground && cardHit?.sourceId !== VESSEL_OVERLAY_SOURCE_ID)
return;
if (!record && cardHit) {
const mmsi = String(cardHit.entryId || '').startsWith('vessel:')
? cardHit.entryId.slice('vessel:'.length)
: null;
record = mmsi ? state.records.byMmsi.get(mmsi) || null : null;
// A stale card id is not empty terrain and must not clear a newer
// selection. The next paint will evict its hit rectangle.
if (!record) return;
}
if (record) {
// A valid sprite or card click always transfers the camera exactly once,
// including a second click on the already-selected vessel.
selectAndFocusVessel(record);
} else {
const transition = components.queries.reduceVesselSelection({
selectedMmsi: state.selectedRecord?.mmsi,
pickedMmsi: null,
gesture: 'click',
});
if (transition.action === 'deselect') clearVesselInspection();
}
}
/** The vessel record a pick is of (keyed or not), through the renderer. */
function pickedRecordOf(picked) {
return state.renderer?.pickedRecord(picked) ?? null;
}
/** Select one live vessel and request one UI-owned camera transfer. */
function selectAndFocusVessel(record) {
if (!record?.mmsi) return false;
const transition = components.queries.reduceVesselSelection({
selectedMmsi: state.selectedRecord?.mmsi,
pickedMmsi: record.mmsi,
gesture: 'click',
});
if (transition.action === 'select') selectVessel(record);
requestWorldFocus({
kind: 'vessel',
id: record.mmsi,
label: record.name || record.mmsi,
position:
components.rendering.getVisual(record).billboard?.position ||
components.rendering.getVisual(record).position,
});
return true;
}
function removeVesselInteraction() {
if (state.clickHandler) {
state.clickHandler.destroy();
state.clickHandler = null;
}
state.selectionRemove?.();
state.selectionRemove = null;
if (state.keyTarget && state.keydownHandler) {
state.keyTarget.removeEventListener('keydown', state.keydownHandler);
}
state.keyTarget = null;
state.keydownHandler = null;
if (state.trackedEntityRemover) {
state.trackedEntityRemover();
state.trackedEntityRemover = null;
}
}
function onVesselKeyDown(event) {
if (!state.feed.enabled || event.key !== 'Escape') return;
const transition = components.queries.reduceVesselSelection({
selectedMmsi: state.selectedRecord?.mmsi,
gesture: 'escape',
});
if (transition.action === 'deselect') {
clearVesselInspection();
}
}
function selectVessel(record) {
if (!record?.mmsi) return;
const reuseTrail = state.trailMmsi === record.mmsi;
clearSelection({ preserveTrail: reuseTrail });
state.selectedRecord = record;
record.missedRefreshes = 0;
if (components.rendering.getVisual(record).billboard) {
components.rendering.getVisual(record).billboard.image =
components.rendering.shipIcon(record, true);
components.rendering.getVisual(record).billboard.scale =
components.rendering.shipScale(record) * 1.2;
}
// Rebuild the card set immediately so the full-detail card appears on the
// click, not up to VISIBILITY_UPDATE_MS later.
components.rendering.updateVisibility(true);
components.cards.updateSelectedVesselHud(record);
if (registerSelectedContext(record)) {
selectEntityContext(record);
}
// Track-history trail (PRD F3/F4): seed with the current position + async
// backfill from the server-side per-MMSI ring buffer.
if (reuseTrail) {
components.tracking.appendSelectedVesselTrailFix(record);
} else {
components.tracking.startSelectedVesselTrail(record);
}
}
/**
* Register (or refresh) the selected vessel in the shared context store so
* the realtime/voice layer can describe what the user has selected.
* @param {Object} record - Selected vessel record.
* @returns {Object|null} The context record, or null if registration failed.
*/
function registerSelectedContext(record) {
if (!record?.mmsi) return null;
try {
return registerEntityContext(record, {
id: `ais-${record.mmsi}`,
layerId: 'ais-live-vessels',
layerName: 'Live AIS Vessels',
source: aisLiveVesselsLayer.source,
label: components.cards.displayVesselName(record),
latitude: record.lat,
longitude: record.lon,
properties: {
mmsi: record.mmsi,
type: record.type,
speedKt: record.speed,
course: record.course,
destination: record.destination,
},
});
} catch (error) {
console.warn('[Data:ais-live-vessels] context register failed', error);
return null;
}
}
function clearSelection({ preserveTrail = false, evicted = false } = {}) {
const record = state.selectedRecord;
if (components.rendering.getVisual(record)?.billboard) {
components.rendering.getVisual(record).billboard.image =
components.rendering.shipIcon(record, false);
components.rendering.getVisual(record).billboard.scale =
components.rendering.shipScale(record);
}
state.selectedRecord = null;
// Drop the full-detail card right away (no-op when the layer is disabled —
// disable() clears the entry set itself).
if (record && state.feed.enabled)
components.rendering.updateVisibility(true);
if (!preserveTrail) components.tracking.clearSelectedVesselTrail();
try {
clearSelectedEntityContextForLayer('ais-live-vessels', { evicted });
} catch (error) {
console.warn('[Data:ais-live-vessels] context clear failed', error);
}
}
/**
* @param {object} [options] Clear origin.
* @param {boolean} [options.evicted=false] The vessel aged out of the feed
* rather than being deselected.
*/
function clearVesselInspection({ evicted = false } = {}) {
clearSelection({ evicted });
components.cards.resetSelectedVesselHud();
}
return {
installInteraction,
bindVesselInteraction,
selectAndFocusVessel,
removeVesselInteraction,
onVesselKeyDown,
selectVessel,
registerSelectedContext,
clearSelection,
clearVesselInspection,
};
}