Merge main (d49d3d10) into the renderer branch

This commit is contained in:
Sameh Khamis committed 2026-11-14 17:21:53 -08:00
commit 489c316556
134 files changed
+4980 -229

No files matched your search

+55 -20
View File
@@ -1,8 +1,10 @@
import {
AID_TO_NAVIGATION_STYLE,
accentForVesselType,
displayVesselType,
normalizeVesselType,
} from '../../data/vesselLabels.js';
import { isAidToNavigation } from '../../data/vesselTypes.js';
import { formatNumber, t } from '../../i18n/index.js';
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
@@ -16,14 +18,21 @@ export function createCards({
function updateSelectedVesselHud(record) {
// Pinned vessels missing from recent refreshes get a stale marker
const stale = (record.missedRefreshes || 0) > 0;
// An aid to navigation is a fixed mark: it has no speed or heading to show.
const aid = isAidToNavigation(record);
services.readouts?.presentSelectedVessel({
text: [
t('AIS: {name}', { name: trimHudValue(record.name, 32) }),
t('{type} SPD: {speed} HDG: {heading}', {
type: trimHudValue(record.type || t('VESSEL'), 24),
speed: formatSpeed(record.speed),
heading: formatHeading(record.heading ?? record.course),
}),
aid
? aidKind(
trimHudValue(record.type || t('AID TO NAVIGATION'), 24),
record,
)
: t('{type} SPD: {speed} HDG: {heading}', {
type: trimHudValue(record.type || t('VESSEL'), 24),
speed: formatSpeed(record.speed),
heading: formatHeading(record.heading ?? record.course),
}),
`MMSI: ${record.mmsi || '--'} ${formatPositionTime(record)}${stale ? ` · ${t('STALE')}` : ''}`,
].join('\n'),
});
@@ -43,27 +52,29 @@ export function createCards({
/**
* Card model for an ambient (decluttered-in) vessel — name title plus one
* compact type/speed/heading detail line, anchored at the record's current
* rendered position (height-datum caveat: no datum work here). Pure —
* exported for unit tests.
* rendered position (height-datum caveat: no datum work here). An aid to
* navigation's line is its kind alone. Pure — exported for unit tests.
* @param {Object} record - Vessel record.
* @returns {Object} vesselLabels entry.
*/
function buildVesselCard(record) {
const parts = [];
const aid = isAidToNavigation(record);
const type = vesselTypeShort(record);
if (type) parts.push(type);
if (record.speed !== null && record.speed !== undefined)
if (record.virtual === true) parts.push(t('VIRTUAL'));
if (!aid && record.speed !== null && record.speed !== undefined)
parts.push(formatSpeed(record.speed));
const direction = record.heading ?? record.course;
if (Number.isFinite(direction))
if (!aid && Number.isFinite(direction))
parts.push(`${roundHeadingDegrees(direction)}°`);
return {
id: vesselOverlayEntryId(record),
actionable: Boolean(record?.id),
position: components.rendering.iconPosition(record),
gapPx: 10,
accent: accentForVesselType(record.type),
accent: vesselAccent(record, aid),
title: trimHudValue(displayVesselName(record), 26),
details: parts.length ? [parts.join(' · ')] : [],
selected: false,
@@ -74,22 +85,26 @@ export function createCards({
/**
* Card model for the click-selected vessel — the full-detail card, drawn last
* (on top) and never distance-faded by the overlay. Pinned-but-vanished
* vessels carry a STALE marker (mirrors the HUD readout). Pure — exported
* for unit tests.
* vessels carry a STALE marker (mirrors the HUD readout). An aid to
* navigation shows its kind with no speed or heading. Pure — exported for
* unit tests.
* @param {Object} record - Selected vessel record.
* @returns {Object} vesselLabels entry.
*/
function buildSelectedVesselCard(record) {
const aid = isAidToNavigation(record);
const direction = record.heading ?? record.course;
const details = [
[
vesselTypeShort(record) || t('VESSEL'),
formatSpeed(record.speed),
Number.isFinite(direction)
? `${roundHeadingDegrees(direction)}°`
: '--°',
].join(' · '),
aid
? aidKind(vesselTypeShort(record) || t('AID TO NAVIGATION'), record)
: [
vesselTypeShort(record) || t('VESSEL'),
formatSpeed(record.speed),
Number.isFinite(direction)
? `${roundHeadingDegrees(direction)}°`
: '--°',
].join(' · '),
];
const destination = String(record.destination || '').trim();
if (destination) details.push(`→ ${trimHudValue(destination, 24)}`);
@@ -102,7 +117,7 @@ export function createCards({
actionable: Boolean(record?.id),
position: components.rendering.iconPosition(record),
gapPx: 12,
accent: accentForVesselType(record.type),
accent: vesselAccent(record, aid),
title: trimHudValue(displayVesselName(record), 32),
details,
selected: true,
@@ -110,6 +125,20 @@ export function createCards({
};
}
/** An aid's kind, marked virtual when nothing physical stands there. */
function aidKind(kind, record) {
return record.virtual === true ? `${kind} · ${t('VIRTUAL')}` : kind;
}
/** A card's accent: an aid's disc colour, else its ship type's. */
function vesselAccent(record, aid) {
return aid
? AID_TO_NAVIGATION_STYLE.accent
: accentForVesselType(record.type);
}
/** Stable overlay identity for keyed and source-retained unkeyed rows. */
function vesselOverlayEntryId(record) {
@@ -125,9 +154,15 @@ export function createCards({
* Uppercased AIS type for the card (empty string when unknown). Free feed
* text is bounded to the card width; a translated type token is a short
* catalog word and shows whole, never cut mid-word ("AUXILIAR DE PUERTO").
* An aid's kind is the whole line, so it keeps the room speed and heading
* would take ("CARDINAL MARK N", not "CARDINAL MARK ").
*/
function vesselTypeShort(record) {
if (isAidToNavigation(record)) {
const kind = String(record.type || '').trim();
return kind ? trimHudValue(kind.toUpperCase(), 26) : '';
}
const feedType = normalizeVesselType(record.type);
const shown = displayVesselType(record.type);
return shown === feedType
+1
View File
@@ -31,6 +31,7 @@ export function createVesselLayer({ source, services, options = {} } = {}) {
parts.queries = createQueries(context);
parts.snapshots = createVesselSnapshotRenderer({
state: vesselState.state,
placement: services?.placement ?? null,
records: vesselState.state.records,
rendering: parts.rendering,
tracking: parts.tracking,
+1
View File
@@ -218,6 +218,7 @@ export function createIngestion({
speed: record.speedMps == null ? null : record.speedMps / 0.514444,
course: record.courseDeg,
heading: record.headingDeg,
virtual: record.virtual === true,
last_position_epoch:
record.observedAtMs == null ? null : record.observedAtMs / 1000,
last_position_UTC:
+4
View File
@@ -115,6 +115,8 @@ export function createLifecycle({
state.feed.firstConnectTimer = null;
state.feed.abort = null;
state.icons = null;
if (services.placement)
for (const id of state.records.byId.keys()) services.placement.forget(id);
state.records.all = [];
state.records.byId = new Map();
state.records.unkeyed = [];
@@ -207,6 +209,7 @@ export function createLifecycle({
invalidateAisSession();
releaseContinuousRender('ais-vessels');
components.rendering.cancelTrailingVisibilityPass();
components.rendering.cancelPlacementFrame();
unregisterPickOwner('ais-live-vessels');
components.rendering.setVisible(false);
vesselState._vesselOverlayHost.clearSource(VESSEL_OVERLAY_SOURCE_ID);
@@ -228,6 +231,7 @@ export function createLifecycle({
invalidateAisSession();
releaseContinuousRender('ais-vessels'); // direct-destroy path (perf wave 2 fix)
components.rendering.cancelTrailingVisibilityPass();
components.rendering.cancelPlacementFrame();
if (state.feed.abort) state.feed.abort.abort();
unregisterPickOwner('ais-live-vessels');
components.selection.clearVesselInspection();
+45
View File
@@ -556,3 +556,48 @@ test('AIS feed rows stay keyed by their MMSI', async () => {
['235000001', '235000001'],
);
});
test('an aid to navigation is drawn as a disc, a vessel as its chevron', async () => {
const aid = {
...observation('993672001'),
mmsi: '993672001',
type: 'Port Hand Mark',
speedMps: 0,
};
const ship = { ...observation('366999002'), type: 'Cargo' };
const { layer, icons } = setup({
async getSnapshot() {
return snapshot([aid, ship]);
},
});
await layer.update();
const svgOf = (id) => {
assert.ok(icons.has(id), id);
return atob(icons.item(id).image.split(',')[1]);
};
assert.match(svgOf('993672001'), /<circle/);
// The source's virtual flag reaches the layer's record.
const recordOf = (id) => layer.testing._vesselRecordForTest(id);
assert.equal(recordOf('993672001').virtual, false);
assert.equal(recordOf('366999002').virtual, false);
assert.doesNotMatch(svgOf('993672001'), /<path/);
assert.match(svgOf('366999002'), /<path/);
});
test('a virtual aid to navigation keeps its disc and its virtual flag', async () => {
const aid = {
...observation('993672009'),
mmsi: '993672009',
type: 'Isolated danger',
virtual: true,
};
const { layer, icons } = setup({
async getSnapshot() {
return snapshot([aid]);
},
});
await layer.update();
assert.ok(icons.has('993672009'));
assert.equal(layer.testing._vesselRecordForTest('993672009').virtual, true);
assert.match(atob(icons.item('993672009').image.split(',')[1]), /<circle/);
});
+107
View File
@@ -0,0 +1,107 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { VesselRecords } from './records.js';
import { createVesselSnapshotRenderer } from './snapshotRenderer.js';
import { layerPlacement } from '../../data/placementProvider.js';
const row = (id, fields = {}) => ({
id,
mmsi: id,
lat: 51.93,
lon: 4.05,
speed: 10,
course: 90,
heading: 92,
last_position_epoch: 1_000,
...fields,
});
function harness({ placement = null, following = false } = {}) {
const visuals = [];
const state = { selectedRecord: null, trailId: null };
const records = new VesselRecords({ now: () => 5_000_000 });
const rendering = {
ensureCollections() {},
makeOccluder: () => null,
renderRowLimit: () => Infinity,
prepareRecordVisual(record) {
visuals.push(record.id);
return { billboard: null };
},
addRecordPrimitives() {},
removeRecordPrimitives() {},
shipIcon: () => 'icon',
shipScale: () => 1,
syncRecordIcon() {},
updateVisibility() {},
};
const renderer = createVesselSnapshotRenderer({
state,
placement,
records,
rendering,
tracking: {},
selection: {},
cards: {},
followsClock: () => following,
});
return {
visuals,
reconcile: (rows, options) => renderer.reconcileVessels({}, rows, options),
};
}
function recording() {
const told = [];
const forgotten = [];
const placement = layerPlacement(
{
layer: () => ({
observe: (id, fix) => told.push([id, fix]),
place: () => null,
forget: (id) => forgotten.push(id),
}),
},
'vessels',
);
return { told, forgotten, placement };
}
test('vessels reconcile as before with no placement', () => {
const own = harness();
own.reconcile([row('a'), row('b')]);
own.reconcile([row('a', { lat: 52, last_position_epoch: 1_060 })]);
const { placement } = recording();
const placed = harness({ placement });
placed.reconcile([row('a'), row('b')]);
placed.reconcile([row('a', { lat: 52, last_position_epoch: 1_060 })]);
assert.deepEqual(placed.visuals, own.visuals);
});
test('each live vessel fix is told to the placement, in m/s, and a vessel that leaves is forgotten', () => {
const { told, forgotten, placement } = recording();
const probe = harness({ placement });
probe.reconcile([row('a'), row('b', { speed: null, course: null })]);
probe.reconcile([row('a', { lat: 52, last_position_epoch: 1_060 })]);
assert.deepEqual(
told.map(([id, fix]) => [id, fix.timeMs, fix.lat]),
[
['a', 1_000_000, 51.93],
['b', 1_000_000, 51.93],
['a', 1_060_000, 52],
],
);
assert.ok(Math.abs(told[0][1].speedMps - 10 * (1852 / 3600)) < 1e-12);
assert.equal(told[0][1].courseDeg, 90);
assert.equal(told[0][1].headingDeg, 92);
assert.ok(Number.isNaN(told[1][1].speedMps));
assert.ok(Number.isNaN(told[1][1].courseDeg));
assert.deepEqual(forgotten, ['b']);
});
test('following the world clock, or rows at another time, tell the placement nothing', () => {
const { told, placement } = recording();
harness({ placement, following: true }).reconcile([row('a')]);
harness({ placement }).reconcile([row('a')], { replace: true });
assert.deepEqual(told, []);
});
+3
View File
@@ -31,6 +31,8 @@ export function normalizeVessel(row) {
speed: finiteNumber(row.speed),
course: finiteNumber(row.course),
heading: finiteNumber(row.heading),
// A virtual aid to navigation: a mark with nothing physical there.
virtual: row.virtual === true,
lastPositionUtc: String(row.last_position_UTC || ''),
lastPositionEpoch: finiteNumber(row.last_position_epoch),
missedRefreshes: 0,
@@ -159,6 +161,7 @@ export class VesselRecords {
record.speed = next.speed;
record.course = next.course;
record.heading = next.heading;
record.virtual = next.virtual;
record.lastPositionUtc = next.lastPositionUtc;
record.lastPositionEpoch = next.lastPositionEpoch;
record.missedRefreshes = 0;
+56 -1
View File
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import { createVesselLayer } from './index.js';
import { VISIBILITY_UPDATE_MS } from './policy.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { layerPlacement } from '../../data/placementProvider.js';
// 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
@@ -10,7 +11,7 @@ import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
const noop = () => {};
function setup({ focusPassIsNeeded = () => false } = {}) {
function setup({ focusPassIsNeeded = () => false, placement = null } = {}) {
let clock = 10_000;
const requests = [];
const holds = new Set();
@@ -47,6 +48,7 @@ function setup({ focusPassIsNeeded = () => false } = {}) {
releaseContinuousRender: (id) => holds.delete(id),
governorRequestRender: (reason) => requests.push(reason),
},
...(placement ? { placement: layerPlacement(placement, 'vessels') } : {}),
},
});
const camera = {
@@ -184,3 +186,56 @@ test('a focus pass reads the camera pose even with a trailing frame waiting', ()
frame();
assert.ok(reads > 0, 'the focus pass needs the eye');
});
test('a placement that places nothing asks for no frames; one that places a drawn vessel moves it in place', (t) => {
let mono = 0;
t.mock.method(performance, 'now', () => mono);
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
});
let spot = null;
const { layer, camera, requests, timers, advance } = setup({
placement: { layer: () => ({ place: () => spot }) },
});
const record = { mmsi: '111', lat: 51.93, lon: 4.05 };
const viewer = { camera, scene: {} };
bindFakeCesiumScene(viewer);
layer.testing._setVesselStateForTest({ viewer, records: [record] });
const visual = layer.testing._prepareVesselVisualForTest(record);
// Drawn: on the camera's side of the horizon.
visual.visible = true;
const position = visual.position;
const before = { ...position };
// Nothing placed: no frame is asked for, and the vessel stays put.
for (let i = 0; i < 8; i += 1) {
mono += 250;
layer.testing._runPlacementPassForTest();
advance(250);
}
assert.equal(timers.size, 0);
assert.deepEqual(requests, []);
assert.deepEqual({ ...visual.position }, before);
// Placed: moved in place, no new positions, and a frame asked for.
spot = { lat: 51.94, lon: 4.05 };
mono += 250;
layer.testing._runPlacementPassForTest();
assert.equal(visual.position, position, 'written in place');
assert.notDeepEqual({ ...visual.position }, before);
assert.equal(timers.size, 1);
advance(1_000);
assert.deepEqual(requests, ['ais-vessels-placement']);
// Turning the layer off drops the pending frame.
mono += 250;
layer.testing._runPlacementPassForTest();
assert.equal(timers.size, 1);
layer.destroy();
assert.equal(timers.size, 0);
advance(1_000);
assert.deepEqual(requests, ['ais-vessels-placement']);
});
+140 -20
View File
@@ -1,12 +1,13 @@
import { t } from '../../i18n/index.js';
import {
AID_TO_NAVIGATION_STYLE,
vesselTypeCss,
vesselOverlayCohortLimit,
VESSEL_OVERLAY_SOURCE_ID,
applyVesselOverlayPolicy,
VESSEL_CARD_FADE_DISTANCE_M,
} from '../../data/vesselLabels.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { fromDegrees, fromDegreesInto } from '../../geo/ellipsoid.js';
import { horizonFrom, liftedForHorizon } from '../../geo/horizon.js';
import { distance, distanceSquared } from '../../geo/vector.js';
import {
@@ -35,9 +36,12 @@ import {
vesselModelSpec,
} from '../../data/fleetModels.js';
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
import { isAidToNavigation } from '../../data/vesselTypes.js';
/** How often vessels move on as the world clock plays (wall ms). */
const FOLLOW_POSITION_MS = 250;
/** A frame is asked for this often while a placement moves live vessels. */
const PLACEMENT_FRAME_MS = 1000;
/** The ship artwork's own raster size (px). */
const SHIP_ICON_PX = 32;
@@ -79,26 +83,43 @@ export function createRendering({
};
visualRecords.set(record, visual);
}
visual.position = anchorPosition(record);
const { lat, lon } = drawnAt(record);
visual.position = anchorAt(lat, lon);
// A ship model's origin is its waterline: the sea surface, unlifted.
visual.waterline = anchorPosition(record, 0);
visual.waterline = anchorAt(lat, lon, 0);
if (services.placement) {
visual.drawnLat = lat;
visual.drawnLon = lon;
}
return visual;
}
/**
* Where a record's icon is anchored: VESSEL_LIFT_M above the sea surface
* (the geoid, once its grid has loaded). Following the world clock, a
* vessel is drawn where it was at the time.
* Where a record is drawn now: following the world clock, where it was at
* the time; live, where a host-supplied placement draws it, if one does.
* @param {Object} record - Vessel record with a finite lat/lon.
* @returns {{lat: number, lon: number}} A fresh pair (the placement's
* answer is reused by its next call).
*/
function drawnAt(record) {
const { lat, lon } = followsClock(vesselState)
? vesselPositionAt(record, vesselState.worldNow())
: (services.placement?.place(record.id, vesselState._aisRuntime.now()) ??
record);
return { lat, lon };
}
/**
* Where an icon at `lat`/`lon` is anchored: VESSEL_LIFT_M above the sea
* surface (the geoid, once its grid has loaded).
* @param {number} lat
* @param {number} lon
* @param {number} [liftM] Height above the sea surface (the icon's lift by
* default; 0 for a ship model's waterline).
* @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, liftM = VESSEL_LIFT_M) {
const { lat, lon } = followsClock(vesselState)
? vesselPositionAt(record, vesselState.worldNow())
: record;
function anchorAt(lat, lon, liftM = VESSEL_LIFT_M) {
const heightM = components.queries.vesselDatumHeightM(
components.tracking.currentGeoidN(lat, lon),
liftM,
@@ -106,6 +127,35 @@ export function createRendering({
return fromDegrees(lon, lat, heightM);
}
/**
* Where a record's icon is anchored (see drawnAt and anchorAt).
* @param {Object} record - Vessel record with a finite lat/lon.
* @param {number} [liftM] Height above the sea surface.
* @returns {{x: number, y: number, z: number}} ECEF metres.
*/
function anchorPosition(record, liftM = VESSEL_LIFT_M) {
const { lat, lon } = drawnAt(record);
return anchorAt(lat, lon, liftM);
}
/**
* Move a prepared vessel visual to `lat`/`lon` (a host-supplied placement
* moved it), writing into its own positions rather than allocating new
* ones: the placement pass runs for every drawn vessel several times a
* second. Its icon is drawn there again.
*/
function moveRecordVisual(record, visual, lat, lon) {
const heightM = components.queries.vesselDatumHeightM(
components.tracking.currentGeoidN(lat, lon),
VESSEL_LIFT_M,
);
fromDegreesInto(lon, lat, heightM, visual.position);
fromDegreesInto(lon, lat, heightM - VESSEL_LIFT_M, visual.waterline);
visual.drawnLat = lat;
visual.drawnLon = lon;
syncRecordIcon(record);
}
// Reused projection buffers for the card pass, grown to the candidates.
let worldXyz = new Float64Array(0);
let screenXy = new Float32Array(0);
@@ -281,12 +331,14 @@ 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 renderer turns this into its screen rotation each frame.
* The renderer turns this into its screen rotation each frame. An aid to
* navigation is fixed, so it has none.
* @param {Object} record - Vessel record.
* @returns {number} Course in degrees (0 when unknown).
*/
function vesselCourseDeg(record) {
if (isAidToNavigation(record)) return 0;
const direction = record.heading ?? record.course;
return Number.isFinite(direction) ? direction : 0;
}
@@ -294,6 +346,7 @@ export function createRendering({
/**
* Build (and cache) a chevron/delta-wing SVG data URL tinted for the vessel.
* The shape points north (up) so the row's course maps directly to heading.
* An aid to navigation, which has no heading, is a ringed disc instead.
* One icon is generated per color+variant and shares one atlas slot.
* @param {Object} record - Vessel record (drives per-type tint).
* @param {boolean} selected - True for the white/brighter selected variant.
@@ -301,16 +354,25 @@ export function createRendering({
*/
function shipIcon(record, selected) {
const cssColor = selected ? '#ffffff' : vesselTypeCss(record.type);
const key = `${cssColor}:${selected ? 'selected' : 'normal'}`;
const aid = isAidToNavigation(record);
const cssColor = selected
? '#ffffff'
: aid
? AID_TO_NAVIGATION_STYLE.css
: vesselTypeCss(record.type);
const key = `${cssColor}:${selected ? 'selected' : 'normal'}:${aid ? 'aid' : 'ship'}`;
if (vesselState.shipIconCache.has(key))
return vesselState.shipIconCache.get(key);
const stroke = selected ? 'rgba(6,26,32,0.95)' : 'rgba(4,18,24,0.9)';
const strokeWidth = selected ? 1.1 : 0.7;
const shape = aid
? `<circle r="8" fill="${cssColor}" stroke="${stroke}" stroke-width="${strokeWidth * 2}"/>
<circle r="3" fill="${stroke}"/>`
: `<path d="M0,-14 L11,10 L4,7 L0,14 L-4,7 L-11,10 Z" fill="${cssColor}" stroke="${stroke}" stroke-width="${strokeWidth}" stroke-linejoin="round"/>`;
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
<g transform="translate(16,16)">
<path d="M0,-14 L11,10 L4,7 L0,14 L-4,7 L-11,10 Z" fill="${cssColor}" stroke="${stroke}" stroke-width="${strokeWidth}" stroke-linejoin="round"/>
${shape}
</g>
</svg>`;
const icon = 'data:image/svg+xml;base64,' + btoa(svg);
@@ -344,8 +406,13 @@ export function createRendering({
});
}
/** The model item for `record`, its spec rebuilt only when its type or size changes. */
/**
* The model item for `record`, its spec rebuilt only when its type or size
* changes; null for a virtual aid to navigation, which keeps its disc: no
* buoy stands there (vesselModelSpec).
*/
function modelItem(record, set) {
if (record.virtual === true) return null;
let item = modelItems.get(record.id);
if (!item || item.record !== record)
item = {
@@ -354,13 +421,14 @@ export function createRendering({
tint: null,
modelOwnsVisual: false,
};
const specKey = `${record.type}|${record.length}|${record.beam}|${record.name}`;
const specKey = `${record.type}|${record.mmsi}|${record.length}|${record.beam}|${record.name}`;
if (item.specKey !== specKey) {
item.specKey = specKey;
item.spec = vesselModelSpec(set, record);
}
item.position = getVisual(record).waterline;
item.headingDeg = vesselCourseDeg(record);
// An aid to navigation is a fixed mark: it does not turn to a heading.
item.headingDeg = item.spec?.fixed ? 0 : vesselCourseDeg(record);
item.show = record.id !== state.cockpitSubjectId;
return item;
}
@@ -381,7 +449,8 @@ export function createRendering({
const waterline = getVisual(record).waterline;
if (!waterline) continue;
if (distanceSquared(eye, waterline) > limitSq) continue;
into.set(record.id, modelItem(record, set));
const item = modelItem(record, set);
if (item) into.set(record.id, item);
}
}
@@ -412,8 +481,10 @@ export function createRendering({
gatherModelItems(set, next);
} else {
for (const [id, item] of modelItems)
if (state.records.byId.get(id) === item.record)
next.set(id, modelItem(item.record, set));
if (state.records.byId.get(id) === item.record) {
const kept = modelItem(item.record, set);
if (kept) next.set(id, kept);
}
}
for (const [id, item] of modelItems)
if (next.get(id) !== item) handBackVisual(item.record);
@@ -453,6 +524,7 @@ export function createRendering({
state.preRenderRemover =
findFrame(viewer)?.on('preRender', () => {
if (followsClock(vesselState)) followClockPositions();
else if (services.placement && state.feed.enabled) followPlacements();
updateVisibility();
if (state.feed.enabled) updateModels();
}) ?? null;
@@ -475,6 +547,52 @@ export function createRendering({
}
}
// Live with a host-supplied placement, vessels move on between refreshes:
// drawn where it places them at most every FOLLOW_POSITION_MS, with a frame
// asked for every PLACEMENT_FRAME_MS while it places any drawn vessel, so
// they move while the scene idles.
let placedAtWallMs = -Infinity;
let placing = false;
let placementFrameTimer = null;
function followPlacements() {
const wallMs = performance.now();
if (wallMs - placedAtWallMs >= FOLLOW_POSITION_MS) {
placedAtWallMs = wallMs;
placing = false;
const nowMs = vesselState._aisRuntime.now();
// Drawn vessels only, as a sprite or a model: a hidden one is placed
// again when it is drawn.
for (const record of state.records.all) {
const visual = visualRecords.get(record);
if (!visual?.position) continue;
const drawn =
(visual.visible && !isCockpitSubject(record)) ||
visual.modelOwnsVisual;
if (!drawn) continue;
const placed = services.placement.place(record.id, nowMs);
if (placed) placing = true;
const { lat, lon } = placed ?? record;
if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
moveRecordVisual(record, visual, lat, lon);
}
}
if (placing && placementFrameTimer === null)
placementFrameTimer = vesselState._aisRuntime.setTimeout(() => {
placementFrameTimer = null;
if (state.feed.enabled && !followsClock(vesselState))
governorRequestRender('ais-vessels-placement');
}, PLACEMENT_FRAME_MS);
}
/** Stop asking for placement frames (the layer turned off or went away). */
function cancelPlacementFrame() {
placedAtWallMs = -Infinity;
placing = false;
if (placementFrameTimer === null) return;
vesselState._aisRuntime.clearTimeout(placementFrameTimer);
placementFrameTimer = null;
}
function scheduleTrailingVisibilityPass(now) {
if (state.trailingVisibilityTimer) return;
const waitMs = Math.max(
@@ -837,6 +955,8 @@ export function createRendering({
installRuntime,
updateVisibility,
cancelTrailingVisibilityPass,
cancelPlacementFrame,
followPlacements,
applyVesselFocusDeemphasis,
makeOccluder,
isVisible,
+36 -1
View File
@@ -1,7 +1,32 @@
/** Connect portable vessel reconciliation to scene and selection operations. */
const KNOT_MPS = 1852 / 3600;
const finiteOrNaN = (value) =>
typeof value === 'number' && Number.isFinite(value) ? value : NaN;
/**
* A vessel record's fix as a host-supplied placement takes it: its own time
* (when it was received, if the row gives none), position, speed in m/s
* (rows give knots), course and heading.
*/
function placementFix(record) {
const epoch = record.lastPositionEpoch;
return {
timeMs: Number.isFinite(epoch) ? epoch * 1000 : record.receivedAtMs,
lat: record.lat,
lon: record.lon,
altitudeM: NaN,
speedMps: Number.isFinite(record.speed) ? record.speed * KNOT_MPS : NaN,
courseDeg: finiteOrNaN(record.course),
headingDeg: finiteOrNaN(record.heading),
};
}
/**
* Connect portable vessel reconciliation to scene and selection operations.
* `placement`, a host-supplied placement, is told each live fix.
*/
export function createVesselSnapshotRenderer({
state,
placement = null,
records,
rendering,
tracking,
@@ -18,6 +43,13 @@ export function createVesselSnapshotRenderer({
rendering.ensureCollections(viewer);
const occluder = rendering.makeOccluder();
const follow = followsClock();
// Live fixes only: following the clock, the layer places every vessel.
const observe =
placement && !follow && !replace
? (record) => {
if (record.id) placement.observe(record.id, placementFix(record));
}
: () => {};
records.reconcile(
rows,
{
@@ -29,10 +61,12 @@ export function createVesselSnapshotRenderer({
},
{
add(record) {
observe(record);
rendering.prepareRecordVisual(record);
rendering.addRecordPrimitives(record, occluder);
},
updated(record) {
observe(record);
const selected = record === state.selectedRecord;
rendering.prepareRecordVisual(record);
rendering.syncRecordIcon(record);
@@ -48,6 +82,7 @@ export function createVesselSnapshotRenderer({
rendering.removeRecordPrimitives(record);
},
removed(id) {
placement?.forget(id);
if (state.trailId === id) tracking.clearSelectedVesselTrail();
},
staleSelected(record) {
+21
View File
@@ -164,6 +164,18 @@ export function createTesting({
components.rendering.updateVisibility(force);
}
/** Draw a record's visual where it stands now. Test-only seam. */
function _prepareVesselVisualForTest(record) {
return components.rendering.prepareRecordVisual(record);
}
/** Run one live placement pass (a host-supplied placement). Test-only seam. */
function _runPlacementPassForTest() {
components.rendering.followPlacements();
}
/** True while a trailing visibility frame is scheduled. Test-only seam. */
function _hasTrailingVisibilityPassForTest() {
@@ -183,6 +195,12 @@ export function createTesting({
vesselCount: state.records.byId.size,
};
}
/** The layer's record for a vessel id, or null. Test-only seam. */
function _vesselRecordForTest(id) {
return state.records.byId.get(id) ?? null;
}
return {
_bindVesselInteractionForTest,
_setVesselStateForTest,
@@ -195,7 +213,10 @@ export function createTesting({
_setAisRuntimeForTest,
_getVesselFeedStateForTest,
_getVesselStateForTest,
_vesselRecordForTest,
_runVisibilityPassForTest,
_prepareVesselVisualForTest,
_runPlacementPassForTest,
_hasTrailingVisibilityPassForTest,
};
}
+5
View File
@@ -66,6 +66,11 @@ export function createTracking({
continue;
visual.position = components.rendering.anchorPosition(record);
components.rendering.syncRecordIcon(record);
// A placed vessel is drawn again at its placement on the next pass.
if (services.placement) {
visual.drawnLat = NaN;
visual.drawnLon = NaN;
}
}
// The rows moved with no poll behind them: draw the frame that shows it.
governorRequestRender('ais-vessels-refloor');